[Flang] remove whole-archive option for AIX linker (#76039)
[llvm-project.git] / clang / lib / Sema / SemaInit.cpp
blob0fbd87ce34db9065ecd37ca605ecb1ad850c329e
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.
11 //===----------------------------------------------------------------------===//
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/DeclObjC.h"
15 #include "clang/AST/ExprCXX.h"
16 #include "clang/AST/ExprObjC.h"
17 #include "clang/AST/ExprOpenMP.h"
18 #include "clang/AST/IgnoreExpr.h"
19 #include "clang/AST/TypeLoc.h"
20 #include "clang/Basic/CharInfo.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "clang/Basic/Specifiers.h"
23 #include "clang/Basic/TargetInfo.h"
24 #include "clang/Sema/Designator.h"
25 #include "clang/Sema/EnterExpressionEvaluationContext.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/SemaInternal.h"
29 #include "llvm/ADT/APInt.h"
30 #include "llvm/ADT/FoldingSet.h"
31 #include "llvm/ADT/PointerIntPair.h"
32 #include "llvm/ADT/SmallString.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/StringExtras.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
38 using namespace clang;
40 //===----------------------------------------------------------------------===//
41 // Sema Initialization Checking
42 //===----------------------------------------------------------------------===//
44 /// Check whether T is compatible with a wide character type (wchar_t,
45 /// char16_t or char32_t).
46 static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
47 if (Context.typesAreCompatible(Context.getWideCharType(), T))
48 return true;
49 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
50 return Context.typesAreCompatible(Context.Char16Ty, T) ||
51 Context.typesAreCompatible(Context.Char32Ty, T);
53 return false;
56 enum StringInitFailureKind {
57 SIF_None,
58 SIF_NarrowStringIntoWideChar,
59 SIF_WideStringIntoChar,
60 SIF_IncompatWideStringIntoWideChar,
61 SIF_UTF8StringIntoPlainChar,
62 SIF_PlainStringIntoUTF8Char,
63 SIF_Other
66 /// Check whether the array of type AT can be initialized by the Init
67 /// expression by means of string initialization. Returns SIF_None if so,
68 /// otherwise returns a StringInitFailureKind that describes why the
69 /// initialization would not work.
70 static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
71 ASTContext &Context) {
72 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
73 return SIF_Other;
75 // See if this is a string literal or @encode.
76 Init = Init->IgnoreParens();
78 // Handle @encode, which is a narrow string.
79 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
80 return SIF_None;
82 // Otherwise we can only handle string literals.
83 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
84 if (!SL)
85 return SIF_Other;
87 const QualType ElemTy =
88 Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
90 auto IsCharOrUnsignedChar = [](const QualType &T) {
91 const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr());
92 return BT && BT->isCharType() && BT->getKind() != BuiltinType::SChar;
95 switch (SL->getKind()) {
96 case StringLiteralKind::UTF8:
97 // char8_t array can be initialized with a UTF-8 string.
98 // - C++20 [dcl.init.string] (DR)
99 // Additionally, an array of char or unsigned char may be initialized
100 // by a UTF-8 string literal.
101 if (ElemTy->isChar8Type() ||
102 (Context.getLangOpts().Char8 &&
103 IsCharOrUnsignedChar(ElemTy.getCanonicalType())))
104 return SIF_None;
105 [[fallthrough]];
106 case StringLiteralKind::Ordinary:
107 // char array can be initialized with a narrow string.
108 // Only allow char x[] = "foo"; not char x[] = L"foo";
109 if (ElemTy->isCharType())
110 return (SL->getKind() == StringLiteralKind::UTF8 &&
111 Context.getLangOpts().Char8)
112 ? SIF_UTF8StringIntoPlainChar
113 : SIF_None;
114 if (ElemTy->isChar8Type())
115 return SIF_PlainStringIntoUTF8Char;
116 if (IsWideCharCompatible(ElemTy, Context))
117 return SIF_NarrowStringIntoWideChar;
118 return SIF_Other;
119 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
120 // "An array with element type compatible with a qualified or unqualified
121 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
122 // string literal with the corresponding encoding prefix (L, u, or U,
123 // respectively), optionally enclosed in braces.
124 case StringLiteralKind::UTF16:
125 if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
126 return SIF_None;
127 if (ElemTy->isCharType() || ElemTy->isChar8Type())
128 return SIF_WideStringIntoChar;
129 if (IsWideCharCompatible(ElemTy, Context))
130 return SIF_IncompatWideStringIntoWideChar;
131 return SIF_Other;
132 case StringLiteralKind::UTF32:
133 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
134 return SIF_None;
135 if (ElemTy->isCharType() || ElemTy->isChar8Type())
136 return SIF_WideStringIntoChar;
137 if (IsWideCharCompatible(ElemTy, Context))
138 return SIF_IncompatWideStringIntoWideChar;
139 return SIF_Other;
140 case StringLiteralKind::Wide:
141 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
142 return SIF_None;
143 if (ElemTy->isCharType() || ElemTy->isChar8Type())
144 return SIF_WideStringIntoChar;
145 if (IsWideCharCompatible(ElemTy, Context))
146 return SIF_IncompatWideStringIntoWideChar;
147 return SIF_Other;
148 case StringLiteralKind::Unevaluated:
149 assert(false && "Unevaluated string literal in initialization");
150 break;
153 llvm_unreachable("missed a StringLiteral kind?");
156 static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
157 ASTContext &Context) {
158 const ArrayType *arrayType = Context.getAsArrayType(declType);
159 if (!arrayType)
160 return SIF_Other;
161 return IsStringInit(init, arrayType, Context);
164 bool Sema::IsStringInit(Expr *Init, const ArrayType *AT) {
165 return ::IsStringInit(Init, AT, Context) == SIF_None;
168 /// Update the type of a string literal, including any surrounding parentheses,
169 /// to match the type of the object which it is initializing.
170 static void updateStringLiteralType(Expr *E, QualType Ty) {
171 while (true) {
172 E->setType(Ty);
173 E->setValueKind(VK_PRValue);
174 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
175 break;
176 E = IgnoreParensSingleStep(E);
180 /// Fix a compound literal initializing an array so it's correctly marked
181 /// as an rvalue.
182 static void updateGNUCompoundLiteralRValue(Expr *E) {
183 while (true) {
184 E->setValueKind(VK_PRValue);
185 if (isa<CompoundLiteralExpr>(E))
186 break;
187 E = IgnoreParensSingleStep(E);
191 static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
192 Sema &S) {
193 // Get the length of the string as parsed.
194 auto *ConstantArrayTy =
195 cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
196 uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
198 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
199 // C99 6.7.8p14. We have an array of character type with unknown size
200 // being initialized to a string literal.
201 llvm::APInt ConstVal(32, StrLength);
202 // Return a new array type (C99 6.7.8p22).
203 DeclT = S.Context.getConstantArrayType(
204 IAT->getElementType(), ConstVal, nullptr, ArraySizeModifier::Normal, 0);
205 updateStringLiteralType(Str, DeclT);
206 return;
209 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
211 // We have an array of character type with known size. However,
212 // the size may be smaller or larger than the string we are initializing.
213 // FIXME: Avoid truncation for 64-bit length strings.
214 if (S.getLangOpts().CPlusPlus) {
215 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
216 // For Pascal strings it's OK to strip off the terminating null character,
217 // so the example below is valid:
219 // unsigned char a[2] = "\pa";
220 if (SL->isPascal())
221 StrLength--;
224 // [dcl.init.string]p2
225 if (StrLength > CAT->getSize().getZExtValue())
226 S.Diag(Str->getBeginLoc(),
227 diag::err_initializer_string_for_char_array_too_long)
228 << CAT->getSize().getZExtValue() << StrLength
229 << Str->getSourceRange();
230 } else {
231 // C99 6.7.8p14.
232 if (StrLength-1 > CAT->getSize().getZExtValue())
233 S.Diag(Str->getBeginLoc(),
234 diag::ext_initializer_string_for_char_array_too_long)
235 << Str->getSourceRange();
238 // Set the type to the actual size that we are initializing. If we have
239 // something like:
240 // char x[1] = "foo";
241 // then this will set the string literal's type to char[1].
242 updateStringLiteralType(Str, DeclT);
245 //===----------------------------------------------------------------------===//
246 // Semantic checking for initializer lists.
247 //===----------------------------------------------------------------------===//
249 namespace {
251 /// Semantic checking for initializer lists.
253 /// The InitListChecker class contains a set of routines that each
254 /// handle the initialization of a certain kind of entity, e.g.,
255 /// arrays, vectors, struct/union types, scalars, etc. The
256 /// InitListChecker itself performs a recursive walk of the subobject
257 /// structure of the type to be initialized, while stepping through
258 /// the initializer list one element at a time. The IList and Index
259 /// parameters to each of the Check* routines contain the active
260 /// (syntactic) initializer list and the index into that initializer
261 /// list that represents the current initializer. Each routine is
262 /// responsible for moving that Index forward as it consumes elements.
264 /// Each Check* routine also has a StructuredList/StructuredIndex
265 /// arguments, which contains the current "structured" (semantic)
266 /// initializer list and the index into that initializer list where we
267 /// are copying initializers as we map them over to the semantic
268 /// list. Once we have completed our recursive walk of the subobject
269 /// structure, we will have constructed a full semantic initializer
270 /// list.
272 /// C99 designators cause changes in the initializer list traversal,
273 /// because they make the initialization "jump" into a specific
274 /// subobject and then continue the initialization from that
275 /// point. CheckDesignatedInitializer() recursively steps into the
276 /// designated subobject and manages backing out the recursion to
277 /// initialize the subobjects after the one designated.
279 /// If an initializer list contains any designators, we build a placeholder
280 /// structured list even in 'verify only' mode, so that we can track which
281 /// elements need 'empty' initializtion.
282 class InitListChecker {
283 Sema &SemaRef;
284 bool hadError = false;
285 bool VerifyOnly; // No diagnostics.
286 bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
287 bool InOverloadResolution;
288 InitListExpr *FullyStructuredList = nullptr;
289 NoInitExpr *DummyExpr = nullptr;
290 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr;
292 NoInitExpr *getDummyInit() {
293 if (!DummyExpr)
294 DummyExpr = new (SemaRef.Context) NoInitExpr(SemaRef.Context.VoidTy);
295 return DummyExpr;
298 void CheckImplicitInitList(const InitializedEntity &Entity,
299 InitListExpr *ParentIList, QualType T,
300 unsigned &Index, InitListExpr *StructuredList,
301 unsigned &StructuredIndex);
302 void CheckExplicitInitList(const InitializedEntity &Entity,
303 InitListExpr *IList, QualType &T,
304 InitListExpr *StructuredList,
305 bool TopLevelObject = false);
306 void CheckListElementTypes(const InitializedEntity &Entity,
307 InitListExpr *IList, QualType &DeclType,
308 bool SubobjectIsDesignatorContext,
309 unsigned &Index,
310 InitListExpr *StructuredList,
311 unsigned &StructuredIndex,
312 bool TopLevelObject = false);
313 void CheckSubElementType(const InitializedEntity &Entity,
314 InitListExpr *IList, QualType ElemType,
315 unsigned &Index,
316 InitListExpr *StructuredList,
317 unsigned &StructuredIndex,
318 bool DirectlyDesignated = false);
319 void CheckComplexType(const InitializedEntity &Entity,
320 InitListExpr *IList, QualType DeclType,
321 unsigned &Index,
322 InitListExpr *StructuredList,
323 unsigned &StructuredIndex);
324 void CheckScalarType(const InitializedEntity &Entity,
325 InitListExpr *IList, QualType DeclType,
326 unsigned &Index,
327 InitListExpr *StructuredList,
328 unsigned &StructuredIndex);
329 void CheckReferenceType(const InitializedEntity &Entity,
330 InitListExpr *IList, QualType DeclType,
331 unsigned &Index,
332 InitListExpr *StructuredList,
333 unsigned &StructuredIndex);
334 void CheckVectorType(const InitializedEntity &Entity,
335 InitListExpr *IList, QualType DeclType, unsigned &Index,
336 InitListExpr *StructuredList,
337 unsigned &StructuredIndex);
338 void CheckStructUnionTypes(const InitializedEntity &Entity,
339 InitListExpr *IList, QualType DeclType,
340 CXXRecordDecl::base_class_const_range Bases,
341 RecordDecl::field_iterator Field,
342 bool SubobjectIsDesignatorContext, unsigned &Index,
343 InitListExpr *StructuredList,
344 unsigned &StructuredIndex,
345 bool TopLevelObject = false);
346 void CheckArrayType(const InitializedEntity &Entity,
347 InitListExpr *IList, QualType &DeclType,
348 llvm::APSInt elementIndex,
349 bool SubobjectIsDesignatorContext, unsigned &Index,
350 InitListExpr *StructuredList,
351 unsigned &StructuredIndex);
352 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
353 InitListExpr *IList, DesignatedInitExpr *DIE,
354 unsigned DesigIdx,
355 QualType &CurrentObjectType,
356 RecordDecl::field_iterator *NextField,
357 llvm::APSInt *NextElementIndex,
358 unsigned &Index,
359 InitListExpr *StructuredList,
360 unsigned &StructuredIndex,
361 bool FinishSubobjectInit,
362 bool TopLevelObject);
363 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
364 QualType CurrentObjectType,
365 InitListExpr *StructuredList,
366 unsigned StructuredIndex,
367 SourceRange InitRange,
368 bool IsFullyOverwritten = false);
369 void UpdateStructuredListElement(InitListExpr *StructuredList,
370 unsigned &StructuredIndex,
371 Expr *expr);
372 InitListExpr *createInitListExpr(QualType CurrentObjectType,
373 SourceRange InitRange,
374 unsigned ExpectedNumInits);
375 int numArrayElements(QualType DeclType);
376 int numStructUnionElements(QualType DeclType);
377 static RecordDecl *getRecordDecl(QualType DeclType);
379 ExprResult PerformEmptyInit(SourceLocation Loc,
380 const InitializedEntity &Entity);
382 /// Diagnose that OldInit (or part thereof) has been overridden by NewInit.
383 void diagnoseInitOverride(Expr *OldInit, SourceRange NewInitRange,
384 bool UnionOverride = false,
385 bool FullyOverwritten = true) {
386 // Overriding an initializer via a designator is valid with C99 designated
387 // initializers, but ill-formed with C++20 designated initializers.
388 unsigned DiagID =
389 SemaRef.getLangOpts().CPlusPlus
390 ? (UnionOverride ? diag::ext_initializer_union_overrides
391 : diag::ext_initializer_overrides)
392 : diag::warn_initializer_overrides;
394 if (InOverloadResolution && SemaRef.getLangOpts().CPlusPlus) {
395 // In overload resolution, we have to strictly enforce the rules, and so
396 // don't allow any overriding of prior initializers. This matters for a
397 // case such as:
399 // union U { int a, b; };
400 // struct S { int a, b; };
401 // void f(U), f(S);
403 // Here, f({.a = 1, .b = 2}) is required to call the struct overload. For
404 // consistency, we disallow all overriding of prior initializers in
405 // overload resolution, not only overriding of union members.
406 hadError = true;
407 } else if (OldInit->getType().isDestructedType() && !FullyOverwritten) {
408 // If we'll be keeping around the old initializer but overwriting part of
409 // the object it initialized, and that object is not trivially
410 // destructible, this can leak. Don't allow that, not even as an
411 // extension.
413 // FIXME: It might be reasonable to allow this in cases where the part of
414 // the initializer that we're overriding has trivial destruction.
415 DiagID = diag::err_initializer_overrides_destructed;
416 } else if (!OldInit->getSourceRange().isValid()) {
417 // We need to check on source range validity because the previous
418 // initializer does not have to be an explicit initializer. e.g.,
420 // struct P { int a, b; };
421 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
423 // There is an overwrite taking place because the first braced initializer
424 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
426 // Such overwrites are harmless, so we don't diagnose them. (Note that in
427 // C++, this cannot be reached unless we've already seen and diagnosed a
428 // different conformance issue, such as a mixture of designated and
429 // non-designated initializers or a multi-level designator.)
430 return;
433 if (!VerifyOnly) {
434 SemaRef.Diag(NewInitRange.getBegin(), DiagID)
435 << NewInitRange << FullyOverwritten << OldInit->getType();
436 SemaRef.Diag(OldInit->getBeginLoc(), diag::note_previous_initializer)
437 << (OldInit->HasSideEffects(SemaRef.Context) && FullyOverwritten)
438 << OldInit->getSourceRange();
442 // Explanation on the "FillWithNoInit" mode:
444 // Assume we have the following definitions (Case#1):
445 // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
446 // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
448 // l.lp.x[1][0..1] should not be filled with implicit initializers because the
449 // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
451 // But if we have (Case#2):
452 // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
454 // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
455 // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
457 // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
458 // in the InitListExpr, the "holes" in Case#1 are filled not with empty
459 // initializers but with special "NoInitExpr" place holders, which tells the
460 // CodeGen not to generate any initializers for these parts.
461 void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
462 const InitializedEntity &ParentEntity,
463 InitListExpr *ILE, bool &RequiresSecondPass,
464 bool FillWithNoInit);
465 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
466 const InitializedEntity &ParentEntity,
467 InitListExpr *ILE, bool &RequiresSecondPass,
468 bool FillWithNoInit = false);
469 void FillInEmptyInitializations(const InitializedEntity &Entity,
470 InitListExpr *ILE, bool &RequiresSecondPass,
471 InitListExpr *OuterILE, unsigned OuterIndex,
472 bool FillWithNoInit = false);
473 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
474 Expr *InitExpr, FieldDecl *Field,
475 bool TopLevelObject);
476 void CheckEmptyInitializable(const InitializedEntity &Entity,
477 SourceLocation Loc);
479 public:
480 InitListChecker(
481 Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T,
482 bool VerifyOnly, bool TreatUnavailableAsInvalid,
483 bool InOverloadResolution = false,
484 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr);
485 InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL,
486 QualType &T,
487 SmallVectorImpl<QualType> &AggrDeductionCandidateParamTypes)
488 : InitListChecker(S, Entity, IL, T, /*VerifyOnly=*/true,
489 /*TreatUnavailableAsInvalid=*/false,
490 /*InOverloadResolution=*/false,
491 &AggrDeductionCandidateParamTypes){};
493 bool HadError() { return hadError; }
495 // Retrieves the fully-structured initializer list used for
496 // semantic analysis and code generation.
497 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
500 } // end anonymous namespace
502 ExprResult InitListChecker::PerformEmptyInit(SourceLocation Loc,
503 const InitializedEntity &Entity) {
504 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
505 true);
506 MultiExprArg SubInit;
507 Expr *InitExpr;
508 InitListExpr DummyInitList(SemaRef.Context, Loc, std::nullopt, Loc);
510 // C++ [dcl.init.aggr]p7:
511 // If there are fewer initializer-clauses in the list than there are
512 // members in the aggregate, then each member not explicitly initialized
513 // ...
514 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
515 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
516 if (EmptyInitList) {
517 // C++1y / DR1070:
518 // shall be initialized [...] from an empty initializer list.
520 // We apply the resolution of this DR to C++11 but not C++98, since C++98
521 // does not have useful semantics for initialization from an init list.
522 // We treat this as copy-initialization, because aggregate initialization
523 // always performs copy-initialization on its elements.
525 // Only do this if we're initializing a class type, to avoid filling in
526 // the initializer list where possible.
527 InitExpr = VerifyOnly
528 ? &DummyInitList
529 : new (SemaRef.Context)
530 InitListExpr(SemaRef.Context, Loc, std::nullopt, Loc);
531 InitExpr->setType(SemaRef.Context.VoidTy);
532 SubInit = InitExpr;
533 Kind = InitializationKind::CreateCopy(Loc, Loc);
534 } else {
535 // C++03:
536 // shall be value-initialized.
539 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
540 // libstdc++4.6 marks the vector default constructor as explicit in
541 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
542 // stlport does so too. Look for std::__debug for libstdc++, and for
543 // std:: for stlport. This is effectively a compiler-side implementation of
544 // LWG2193.
545 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
546 InitializationSequence::FK_ExplicitConstructor) {
547 OverloadCandidateSet::iterator Best;
548 OverloadingResult O =
549 InitSeq.getFailedCandidateSet()
550 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
551 (void)O;
552 assert(O == OR_Success && "Inconsistent overload resolution");
553 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
554 CXXRecordDecl *R = CtorDecl->getParent();
556 if (CtorDecl->getMinRequiredArguments() == 0 &&
557 CtorDecl->isExplicit() && R->getDeclName() &&
558 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
559 bool IsInStd = false;
560 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
561 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
562 if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
563 IsInStd = true;
566 if (IsInStd && llvm::StringSwitch<bool>(R->getName())
567 .Cases("basic_string", "deque", "forward_list", true)
568 .Cases("list", "map", "multimap", "multiset", true)
569 .Cases("priority_queue", "queue", "set", "stack", true)
570 .Cases("unordered_map", "unordered_set", "vector", true)
571 .Default(false)) {
572 InitSeq.InitializeFrom(
573 SemaRef, Entity,
574 InitializationKind::CreateValue(Loc, Loc, Loc, true),
575 MultiExprArg(), /*TopLevelOfInitList=*/false,
576 TreatUnavailableAsInvalid);
577 // Emit a warning for this. System header warnings aren't shown
578 // by default, but people working on system headers should see it.
579 if (!VerifyOnly) {
580 SemaRef.Diag(CtorDecl->getLocation(),
581 diag::warn_invalid_initializer_from_system_header);
582 if (Entity.getKind() == InitializedEntity::EK_Member)
583 SemaRef.Diag(Entity.getDecl()->getLocation(),
584 diag::note_used_in_initialization_here);
585 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
586 SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
591 if (!InitSeq) {
592 if (!VerifyOnly) {
593 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
594 if (Entity.getKind() == InitializedEntity::EK_Member)
595 SemaRef.Diag(Entity.getDecl()->getLocation(),
596 diag::note_in_omitted_aggregate_initializer)
597 << /*field*/1 << Entity.getDecl();
598 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
599 bool IsTrailingArrayNewMember =
600 Entity.getParent() &&
601 Entity.getParent()->isVariableLengthArrayNew();
602 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
603 << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
604 << Entity.getElementIndex();
607 hadError = true;
608 return ExprError();
611 return VerifyOnly ? ExprResult()
612 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
615 void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
616 SourceLocation Loc) {
617 // If we're building a fully-structured list, we'll check this at the end
618 // once we know which elements are actually initialized. Otherwise, we know
619 // that there are no designators so we can just check now.
620 if (FullyStructuredList)
621 return;
622 PerformEmptyInit(Loc, Entity);
625 void InitListChecker::FillInEmptyInitForBase(
626 unsigned Init, const CXXBaseSpecifier &Base,
627 const InitializedEntity &ParentEntity, InitListExpr *ILE,
628 bool &RequiresSecondPass, bool FillWithNoInit) {
629 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
630 SemaRef.Context, &Base, false, &ParentEntity);
632 if (Init >= ILE->getNumInits() || !ILE->getInit(Init)) {
633 ExprResult BaseInit = FillWithNoInit
634 ? new (SemaRef.Context) NoInitExpr(Base.getType())
635 : PerformEmptyInit(ILE->getEndLoc(), BaseEntity);
636 if (BaseInit.isInvalid()) {
637 hadError = true;
638 return;
641 if (!VerifyOnly) {
642 assert(Init < ILE->getNumInits() && "should have been expanded");
643 ILE->setInit(Init, BaseInit.getAs<Expr>());
645 } else if (InitListExpr *InnerILE =
646 dyn_cast<InitListExpr>(ILE->getInit(Init))) {
647 FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,
648 ILE, Init, FillWithNoInit);
649 } else if (DesignatedInitUpdateExpr *InnerDIUE =
650 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
651 FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
652 RequiresSecondPass, ILE, Init,
653 /*FillWithNoInit =*/true);
657 void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
658 const InitializedEntity &ParentEntity,
659 InitListExpr *ILE,
660 bool &RequiresSecondPass,
661 bool FillWithNoInit) {
662 SourceLocation Loc = ILE->getEndLoc();
663 unsigned NumInits = ILE->getNumInits();
664 InitializedEntity MemberEntity
665 = InitializedEntity::InitializeMember(Field, &ParentEntity);
667 if (Init >= NumInits || !ILE->getInit(Init)) {
668 if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
669 if (!RType->getDecl()->isUnion())
670 assert((Init < NumInits || VerifyOnly) &&
671 "This ILE should have been expanded");
673 if (FillWithNoInit) {
674 assert(!VerifyOnly && "should not fill with no-init in verify-only mode");
675 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
676 if (Init < NumInits)
677 ILE->setInit(Init, Filler);
678 else
679 ILE->updateInit(SemaRef.Context, Init, Filler);
680 return;
682 // C++1y [dcl.init.aggr]p7:
683 // If there are fewer initializer-clauses in the list than there are
684 // members in the aggregate, then each member not explicitly initialized
685 // shall be initialized from its brace-or-equal-initializer [...]
686 if (Field->hasInClassInitializer()) {
687 if (VerifyOnly)
688 return;
690 ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
691 if (DIE.isInvalid()) {
692 hadError = true;
693 return;
695 SemaRef.checkInitializerLifetime(MemberEntity, DIE.get());
696 if (Init < NumInits)
697 ILE->setInit(Init, DIE.get());
698 else {
699 ILE->updateInit(SemaRef.Context, Init, DIE.get());
700 RequiresSecondPass = true;
702 return;
705 if (Field->getType()->isReferenceType()) {
706 if (!VerifyOnly) {
707 // C++ [dcl.init.aggr]p9:
708 // If an incomplete or empty initializer-list leaves a
709 // member of reference type uninitialized, the program is
710 // ill-formed.
711 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
712 << Field->getType()
713 << (ILE->isSyntacticForm() ? ILE : ILE->getSyntacticForm())
714 ->getSourceRange();
715 SemaRef.Diag(Field->getLocation(), diag::note_uninit_reference_member);
717 hadError = true;
718 return;
721 ExprResult MemberInit = PerformEmptyInit(Loc, MemberEntity);
722 if (MemberInit.isInvalid()) {
723 hadError = true;
724 return;
727 if (hadError || VerifyOnly) {
728 // Do nothing
729 } else if (Init < NumInits) {
730 ILE->setInit(Init, MemberInit.getAs<Expr>());
731 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
732 // Empty initialization requires a constructor call, so
733 // extend the initializer list to include the constructor
734 // call and make a note that we'll need to take another pass
735 // through the initializer list.
736 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
737 RequiresSecondPass = true;
739 } else if (InitListExpr *InnerILE
740 = dyn_cast<InitListExpr>(ILE->getInit(Init))) {
741 FillInEmptyInitializations(MemberEntity, InnerILE,
742 RequiresSecondPass, ILE, Init, FillWithNoInit);
743 } else if (DesignatedInitUpdateExpr *InnerDIUE =
744 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
745 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
746 RequiresSecondPass, ILE, Init,
747 /*FillWithNoInit =*/true);
751 /// Recursively replaces NULL values within the given initializer list
752 /// with expressions that perform value-initialization of the
753 /// appropriate type, and finish off the InitListExpr formation.
754 void
755 InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
756 InitListExpr *ILE,
757 bool &RequiresSecondPass,
758 InitListExpr *OuterILE,
759 unsigned OuterIndex,
760 bool FillWithNoInit) {
761 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
762 "Should not have void type");
764 // We don't need to do any checks when just filling NoInitExprs; that can't
765 // fail.
766 if (FillWithNoInit && VerifyOnly)
767 return;
769 // If this is a nested initializer list, we might have changed its contents
770 // (and therefore some of its properties, such as instantiation-dependence)
771 // while filling it in. Inform the outer initializer list so that its state
772 // can be updated to match.
773 // FIXME: We should fully build the inner initializers before constructing
774 // the outer InitListExpr instead of mutating AST nodes after they have
775 // been used as subexpressions of other nodes.
776 struct UpdateOuterILEWithUpdatedInit {
777 InitListExpr *Outer;
778 unsigned OuterIndex;
779 ~UpdateOuterILEWithUpdatedInit() {
780 if (Outer)
781 Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
783 } UpdateOuterRAII = {OuterILE, OuterIndex};
785 // A transparent ILE is not performing aggregate initialization and should
786 // not be filled in.
787 if (ILE->isTransparent())
788 return;
790 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
791 const RecordDecl *RDecl = RType->getDecl();
792 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
793 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
794 Entity, ILE, RequiresSecondPass, FillWithNoInit);
795 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
796 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
797 for (auto *Field : RDecl->fields()) {
798 if (Field->hasInClassInitializer()) {
799 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
800 FillWithNoInit);
801 break;
804 } else {
805 // The fields beyond ILE->getNumInits() are default initialized, so in
806 // order to leave them uninitialized, the ILE is expanded and the extra
807 // fields are then filled with NoInitExpr.
808 unsigned NumElems = numStructUnionElements(ILE->getType());
809 if (!RDecl->isUnion() && RDecl->hasFlexibleArrayMember())
810 ++NumElems;
811 if (!VerifyOnly && ILE->getNumInits() < NumElems)
812 ILE->resizeInits(SemaRef.Context, NumElems);
814 unsigned Init = 0;
816 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
817 for (auto &Base : CXXRD->bases()) {
818 if (hadError)
819 return;
821 FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
822 FillWithNoInit);
823 ++Init;
827 for (auto *Field : RDecl->fields()) {
828 if (Field->isUnnamedBitfield())
829 continue;
831 if (hadError)
832 return;
834 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
835 FillWithNoInit);
836 if (hadError)
837 return;
839 ++Init;
841 // Only look at the first initialization of a union.
842 if (RDecl->isUnion())
843 break;
847 return;
850 QualType ElementType;
852 InitializedEntity ElementEntity = Entity;
853 unsigned NumInits = ILE->getNumInits();
854 unsigned NumElements = NumInits;
855 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
856 ElementType = AType->getElementType();
857 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
858 NumElements = CAType->getSize().getZExtValue();
859 // For an array new with an unknown bound, ask for one additional element
860 // in order to populate the array filler.
861 if (Entity.isVariableLengthArrayNew())
862 ++NumElements;
863 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
864 0, Entity);
865 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
866 ElementType = VType->getElementType();
867 NumElements = VType->getNumElements();
868 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
869 0, Entity);
870 } else
871 ElementType = ILE->getType();
873 bool SkipEmptyInitChecks = false;
874 for (unsigned Init = 0; Init != NumElements; ++Init) {
875 if (hadError)
876 return;
878 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
879 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
880 ElementEntity.setElementIndex(Init);
882 if (Init >= NumInits && (ILE->hasArrayFiller() || SkipEmptyInitChecks))
883 return;
885 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
886 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
887 ILE->setInit(Init, ILE->getArrayFiller());
888 else if (!InitExpr && !ILE->hasArrayFiller()) {
889 // In VerifyOnly mode, there's no point performing empty initialization
890 // more than once.
891 if (SkipEmptyInitChecks)
892 continue;
894 Expr *Filler = nullptr;
896 if (FillWithNoInit)
897 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
898 else {
899 ExprResult ElementInit =
900 PerformEmptyInit(ILE->getEndLoc(), ElementEntity);
901 if (ElementInit.isInvalid()) {
902 hadError = true;
903 return;
906 Filler = ElementInit.getAs<Expr>();
909 if (hadError) {
910 // Do nothing
911 } else if (VerifyOnly) {
912 SkipEmptyInitChecks = true;
913 } else if (Init < NumInits) {
914 // For arrays, just set the expression used for value-initialization
915 // of the "holes" in the array.
916 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
917 ILE->setArrayFiller(Filler);
918 else
919 ILE->setInit(Init, Filler);
920 } else {
921 // For arrays, just set the expression used for value-initialization
922 // of the rest of elements and exit.
923 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
924 ILE->setArrayFiller(Filler);
925 return;
928 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
929 // Empty initialization requires a constructor call, so
930 // extend the initializer list to include the constructor
931 // call and make a note that we'll need to take another pass
932 // through the initializer list.
933 ILE->updateInit(SemaRef.Context, Init, Filler);
934 RequiresSecondPass = true;
937 } else if (InitListExpr *InnerILE
938 = dyn_cast_or_null<InitListExpr>(InitExpr)) {
939 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
940 ILE, Init, FillWithNoInit);
941 } else if (DesignatedInitUpdateExpr *InnerDIUE =
942 dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr)) {
943 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
944 RequiresSecondPass, ILE, Init,
945 /*FillWithNoInit =*/true);
950 static bool hasAnyDesignatedInits(const InitListExpr *IL) {
951 for (const Stmt *Init : *IL)
952 if (isa_and_nonnull<DesignatedInitExpr>(Init))
953 return true;
954 return false;
957 InitListChecker::InitListChecker(
958 Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T,
959 bool VerifyOnly, bool TreatUnavailableAsInvalid, bool InOverloadResolution,
960 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes)
961 : SemaRef(S), VerifyOnly(VerifyOnly),
962 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid),
963 InOverloadResolution(InOverloadResolution),
964 AggrDeductionCandidateParamTypes(AggrDeductionCandidateParamTypes) {
965 if (!VerifyOnly || hasAnyDesignatedInits(IL)) {
966 FullyStructuredList =
967 createInitListExpr(T, IL->getSourceRange(), IL->getNumInits());
969 // FIXME: Check that IL isn't already the semantic form of some other
970 // InitListExpr. If it is, we'd create a broken AST.
971 if (!VerifyOnly)
972 FullyStructuredList->setSyntacticForm(IL);
975 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
976 /*TopLevelObject=*/true);
978 if (!hadError && !AggrDeductionCandidateParamTypes && FullyStructuredList) {
979 bool RequiresSecondPass = false;
980 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
981 /*OuterILE=*/nullptr, /*OuterIndex=*/0);
982 if (RequiresSecondPass && !hadError)
983 FillInEmptyInitializations(Entity, FullyStructuredList,
984 RequiresSecondPass, nullptr, 0);
986 if (hadError && FullyStructuredList)
987 FullyStructuredList->markError();
990 int InitListChecker::numArrayElements(QualType DeclType) {
991 // FIXME: use a proper constant
992 int maxElements = 0x7FFFFFFF;
993 if (const ConstantArrayType *CAT =
994 SemaRef.Context.getAsConstantArrayType(DeclType)) {
995 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
997 return maxElements;
1000 int InitListChecker::numStructUnionElements(QualType DeclType) {
1001 RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl();
1002 int InitializableMembers = 0;
1003 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
1004 InitializableMembers += CXXRD->getNumBases();
1005 for (const auto *Field : structDecl->fields())
1006 if (!Field->isUnnamedBitfield())
1007 ++InitializableMembers;
1009 if (structDecl->isUnion())
1010 return std::min(InitializableMembers, 1);
1011 return InitializableMembers - structDecl->hasFlexibleArrayMember();
1014 RecordDecl *InitListChecker::getRecordDecl(QualType DeclType) {
1015 if (const auto *RT = DeclType->getAs<RecordType>())
1016 return RT->getDecl();
1017 if (const auto *Inject = DeclType->getAs<InjectedClassNameType>())
1018 return Inject->getDecl();
1019 return nullptr;
1022 /// Determine whether Entity is an entity for which it is idiomatic to elide
1023 /// the braces in aggregate initialization.
1024 static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) {
1025 // Recursive initialization of the one and only field within an aggregate
1026 // class is considered idiomatic. This case arises in particular for
1027 // initialization of std::array, where the C++ standard suggests the idiom of
1029 // std::array<T, N> arr = {1, 2, 3};
1031 // (where std::array is an aggregate struct containing a single array field.
1033 if (!Entity.getParent())
1034 return false;
1036 // Allows elide brace initialization for aggregates with empty base.
1037 if (Entity.getKind() == InitializedEntity::EK_Base) {
1038 auto *ParentRD =
1039 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1040 CXXRecordDecl *CXXRD = cast<CXXRecordDecl>(ParentRD);
1041 return CXXRD->getNumBases() == 1 && CXXRD->field_empty();
1044 // Allow brace elision if the only subobject is a field.
1045 if (Entity.getKind() == InitializedEntity::EK_Member) {
1046 auto *ParentRD =
1047 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1048 if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD)) {
1049 if (CXXRD->getNumBases()) {
1050 return false;
1053 auto FieldIt = ParentRD->field_begin();
1054 assert(FieldIt != ParentRD->field_end() &&
1055 "no fields but have initializer for member?");
1056 return ++FieldIt == ParentRD->field_end();
1059 return false;
1062 /// Check whether the range of the initializer \p ParentIList from element
1063 /// \p Index onwards can be used to initialize an object of type \p T. Update
1064 /// \p Index to indicate how many elements of the list were consumed.
1066 /// This also fills in \p StructuredList, from element \p StructuredIndex
1067 /// onwards, with the fully-braced, desugared form of the initialization.
1068 void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
1069 InitListExpr *ParentIList,
1070 QualType T, unsigned &Index,
1071 InitListExpr *StructuredList,
1072 unsigned &StructuredIndex) {
1073 int maxElements = 0;
1075 if (T->isArrayType())
1076 maxElements = numArrayElements(T);
1077 else if (T->isRecordType())
1078 maxElements = numStructUnionElements(T);
1079 else if (T->isVectorType())
1080 maxElements = T->castAs<VectorType>()->getNumElements();
1081 else
1082 llvm_unreachable("CheckImplicitInitList(): Illegal type");
1084 if (maxElements == 0) {
1085 if (!VerifyOnly)
1086 SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(),
1087 diag::err_implicit_empty_initializer);
1088 ++Index;
1089 hadError = true;
1090 return;
1093 // Build a structured initializer list corresponding to this subobject.
1094 InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(
1095 ParentIList, Index, T, StructuredList, StructuredIndex,
1096 SourceRange(ParentIList->getInit(Index)->getBeginLoc(),
1097 ParentIList->getSourceRange().getEnd()));
1098 unsigned StructuredSubobjectInitIndex = 0;
1100 // Check the element types and build the structural subobject.
1101 unsigned StartIndex = Index;
1102 CheckListElementTypes(Entity, ParentIList, T,
1103 /*SubobjectIsDesignatorContext=*/false, Index,
1104 StructuredSubobjectInitList,
1105 StructuredSubobjectInitIndex);
1107 if (StructuredSubobjectInitList) {
1108 StructuredSubobjectInitList->setType(T);
1110 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
1111 // Update the structured sub-object initializer so that it's ending
1112 // range corresponds with the end of the last initializer it used.
1113 if (EndIndex < ParentIList->getNumInits() &&
1114 ParentIList->getInit(EndIndex)) {
1115 SourceLocation EndLoc
1116 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
1117 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
1120 // Complain about missing braces.
1121 if (!VerifyOnly && (T->isArrayType() || T->isRecordType()) &&
1122 !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
1123 !isIdiomaticBraceElisionEntity(Entity)) {
1124 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1125 diag::warn_missing_braces)
1126 << StructuredSubobjectInitList->getSourceRange()
1127 << FixItHint::CreateInsertion(
1128 StructuredSubobjectInitList->getBeginLoc(), "{")
1129 << FixItHint::CreateInsertion(
1130 SemaRef.getLocForEndOfToken(
1131 StructuredSubobjectInitList->getEndLoc()),
1132 "}");
1135 // Warn if this type won't be an aggregate in future versions of C++.
1136 auto *CXXRD = T->getAsCXXRecordDecl();
1137 if (!VerifyOnly && CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1138 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1139 diag::warn_cxx20_compat_aggregate_init_with_ctors)
1140 << StructuredSubobjectInitList->getSourceRange() << T;
1145 /// Warn that \p Entity was of scalar type and was initialized by a
1146 /// single-element braced initializer list.
1147 static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
1148 SourceRange Braces) {
1149 // Don't warn during template instantiation. If the initialization was
1150 // non-dependent, we warned during the initial parse; otherwise, the
1151 // type might not be scalar in some uses of the template.
1152 if (S.inTemplateInstantiation())
1153 return;
1155 unsigned DiagID = 0;
1157 switch (Entity.getKind()) {
1158 case InitializedEntity::EK_VectorElement:
1159 case InitializedEntity::EK_ComplexElement:
1160 case InitializedEntity::EK_ArrayElement:
1161 case InitializedEntity::EK_Parameter:
1162 case InitializedEntity::EK_Parameter_CF_Audited:
1163 case InitializedEntity::EK_TemplateParameter:
1164 case InitializedEntity::EK_Result:
1165 case InitializedEntity::EK_ParenAggInitMember:
1166 // Extra braces here are suspicious.
1167 DiagID = diag::warn_braces_around_init;
1168 break;
1170 case InitializedEntity::EK_Member:
1171 // Warn on aggregate initialization but not on ctor init list or
1172 // default member initializer.
1173 if (Entity.getParent())
1174 DiagID = diag::warn_braces_around_init;
1175 break;
1177 case InitializedEntity::EK_Variable:
1178 case InitializedEntity::EK_LambdaCapture:
1179 // No warning, might be direct-list-initialization.
1180 // FIXME: Should we warn for copy-list-initialization in these cases?
1181 break;
1183 case InitializedEntity::EK_New:
1184 case InitializedEntity::EK_Temporary:
1185 case InitializedEntity::EK_CompoundLiteralInit:
1186 // No warning, braces are part of the syntax of the underlying construct.
1187 break;
1189 case InitializedEntity::EK_RelatedResult:
1190 // No warning, we already warned when initializing the result.
1191 break;
1193 case InitializedEntity::EK_Exception:
1194 case InitializedEntity::EK_Base:
1195 case InitializedEntity::EK_Delegating:
1196 case InitializedEntity::EK_BlockElement:
1197 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
1198 case InitializedEntity::EK_Binding:
1199 case InitializedEntity::EK_StmtExprResult:
1200 llvm_unreachable("unexpected braced scalar init");
1203 if (DiagID) {
1204 S.Diag(Braces.getBegin(), DiagID)
1205 << Entity.getType()->isSizelessBuiltinType() << Braces
1206 << FixItHint::CreateRemoval(Braces.getBegin())
1207 << FixItHint::CreateRemoval(Braces.getEnd());
1211 /// Check whether the initializer \p IList (that was written with explicit
1212 /// braces) can be used to initialize an object of type \p T.
1214 /// This also fills in \p StructuredList with the fully-braced, desugared
1215 /// form of the initialization.
1216 void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
1217 InitListExpr *IList, QualType &T,
1218 InitListExpr *StructuredList,
1219 bool TopLevelObject) {
1220 unsigned Index = 0, StructuredIndex = 0;
1221 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
1222 Index, StructuredList, StructuredIndex, TopLevelObject);
1223 if (StructuredList) {
1224 QualType ExprTy = T;
1225 if (!ExprTy->isArrayType())
1226 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
1227 if (!VerifyOnly)
1228 IList->setType(ExprTy);
1229 StructuredList->setType(ExprTy);
1231 if (hadError)
1232 return;
1234 // Don't complain for incomplete types, since we'll get an error elsewhere.
1235 if (Index < IList->getNumInits() && !T->isIncompleteType()) {
1236 // We have leftover initializers
1237 bool ExtraInitsIsError = SemaRef.getLangOpts().CPlusPlus ||
1238 (SemaRef.getLangOpts().OpenCL && T->isVectorType());
1239 hadError = ExtraInitsIsError;
1240 if (VerifyOnly) {
1241 return;
1242 } else if (StructuredIndex == 1 &&
1243 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1244 SIF_None) {
1245 unsigned DK =
1246 ExtraInitsIsError
1247 ? diag::err_excess_initializers_in_char_array_initializer
1248 : diag::ext_excess_initializers_in_char_array_initializer;
1249 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1250 << IList->getInit(Index)->getSourceRange();
1251 } else if (T->isSizelessBuiltinType()) {
1252 unsigned DK = ExtraInitsIsError
1253 ? diag::err_excess_initializers_for_sizeless_type
1254 : diag::ext_excess_initializers_for_sizeless_type;
1255 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1256 << T << IList->getInit(Index)->getSourceRange();
1257 } else {
1258 int initKind = T->isArrayType() ? 0 :
1259 T->isVectorType() ? 1 :
1260 T->isScalarType() ? 2 :
1261 T->isUnionType() ? 3 :
1264 unsigned DK = ExtraInitsIsError ? diag::err_excess_initializers
1265 : diag::ext_excess_initializers;
1266 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1267 << initKind << IList->getInit(Index)->getSourceRange();
1271 if (!VerifyOnly) {
1272 if (T->isScalarType() && IList->getNumInits() == 1 &&
1273 !isa<InitListExpr>(IList->getInit(0)))
1274 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
1276 // Warn if this is a class type that won't be an aggregate in future
1277 // versions of C++.
1278 auto *CXXRD = T->getAsCXXRecordDecl();
1279 if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1280 // Don't warn if there's an equivalent default constructor that would be
1281 // used instead.
1282 bool HasEquivCtor = false;
1283 if (IList->getNumInits() == 0) {
1284 auto *CD = SemaRef.LookupDefaultConstructor(CXXRD);
1285 HasEquivCtor = CD && !CD->isDeleted();
1288 if (!HasEquivCtor) {
1289 SemaRef.Diag(IList->getBeginLoc(),
1290 diag::warn_cxx20_compat_aggregate_init_with_ctors)
1291 << IList->getSourceRange() << T;
1297 void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
1298 InitListExpr *IList,
1299 QualType &DeclType,
1300 bool SubobjectIsDesignatorContext,
1301 unsigned &Index,
1302 InitListExpr *StructuredList,
1303 unsigned &StructuredIndex,
1304 bool TopLevelObject) {
1305 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1306 // Explicitly braced initializer for complex type can be real+imaginary
1307 // parts.
1308 CheckComplexType(Entity, IList, DeclType, Index,
1309 StructuredList, StructuredIndex);
1310 } else if (DeclType->isScalarType()) {
1311 CheckScalarType(Entity, IList, DeclType, Index,
1312 StructuredList, StructuredIndex);
1313 } else if (DeclType->isVectorType()) {
1314 CheckVectorType(Entity, IList, DeclType, Index,
1315 StructuredList, StructuredIndex);
1316 } else if (const RecordDecl *RD = getRecordDecl(DeclType)) {
1317 auto Bases =
1318 CXXRecordDecl::base_class_const_range(CXXRecordDecl::base_class_const_iterator(),
1319 CXXRecordDecl::base_class_const_iterator());
1320 if (DeclType->isRecordType()) {
1321 assert(DeclType->isAggregateType() &&
1322 "non-aggregate records should be handed in CheckSubElementType");
1323 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1324 Bases = CXXRD->bases();
1325 } else {
1326 Bases = cast<CXXRecordDecl>(RD)->bases();
1328 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1329 SubobjectIsDesignatorContext, Index, StructuredList,
1330 StructuredIndex, TopLevelObject);
1331 } else if (DeclType->isArrayType()) {
1332 llvm::APSInt Zero(
1333 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1334 false);
1335 CheckArrayType(Entity, IList, DeclType, Zero,
1336 SubobjectIsDesignatorContext, Index,
1337 StructuredList, StructuredIndex);
1338 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1339 // This type is invalid, issue a diagnostic.
1340 ++Index;
1341 if (!VerifyOnly)
1342 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1343 << DeclType;
1344 hadError = true;
1345 } else if (DeclType->isReferenceType()) {
1346 CheckReferenceType(Entity, IList, DeclType, Index,
1347 StructuredList, StructuredIndex);
1348 } else if (DeclType->isObjCObjectType()) {
1349 if (!VerifyOnly)
1350 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType;
1351 hadError = true;
1352 } else if (DeclType->isOCLIntelSubgroupAVCType() ||
1353 DeclType->isSizelessBuiltinType()) {
1354 // Checks for scalar type are sufficient for these types too.
1355 CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1356 StructuredIndex);
1357 } else if (DeclType->isDependentType()) {
1358 // C++ [over.match.class.deduct]p1.5:
1359 // brace elision is not considered for any aggregate element that has a
1360 // dependent non-array type or an array type with a value-dependent bound
1361 ++Index;
1362 assert(AggrDeductionCandidateParamTypes);
1363 AggrDeductionCandidateParamTypes->push_back(DeclType);
1364 } else {
1365 if (!VerifyOnly)
1366 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1367 << DeclType;
1368 hadError = true;
1372 void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
1373 InitListExpr *IList,
1374 QualType ElemType,
1375 unsigned &Index,
1376 InitListExpr *StructuredList,
1377 unsigned &StructuredIndex,
1378 bool DirectlyDesignated) {
1379 Expr *expr = IList->getInit(Index);
1381 if (ElemType->isReferenceType())
1382 return CheckReferenceType(Entity, IList, ElemType, Index,
1383 StructuredList, StructuredIndex);
1385 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
1386 if (SubInitList->getNumInits() == 1 &&
1387 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1388 SIF_None) {
1389 // FIXME: It would be more faithful and no less correct to include an
1390 // InitListExpr in the semantic form of the initializer list in this case.
1391 expr = SubInitList->getInit(0);
1393 // Nested aggregate initialization and C++ initialization are handled later.
1394 } else if (isa<ImplicitValueInitExpr>(expr)) {
1395 // This happens during template instantiation when we see an InitListExpr
1396 // that we've already checked once.
1397 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
1398 "found implicit initialization for the wrong type");
1399 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1400 ++Index;
1401 return;
1404 if (SemaRef.getLangOpts().CPlusPlus || isa<InitListExpr>(expr)) {
1405 // C++ [dcl.init.aggr]p2:
1406 // Each member is copy-initialized from the corresponding
1407 // initializer-clause.
1409 // FIXME: Better EqualLoc?
1410 InitializationKind Kind =
1411 InitializationKind::CreateCopy(expr->getBeginLoc(), SourceLocation());
1413 // Vector elements can be initialized from other vectors in which case
1414 // we need initialization entity with a type of a vector (and not a vector
1415 // element!) initializing multiple vector elements.
1416 auto TmpEntity =
1417 (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType())
1418 ? InitializedEntity::InitializeTemporary(ElemType)
1419 : Entity;
1421 if (TmpEntity.getType()->isDependentType()) {
1422 // C++ [over.match.class.deduct]p1.5:
1423 // brace elision is not considered for any aggregate element that has a
1424 // dependent non-array type or an array type with a value-dependent
1425 // bound
1426 assert(AggrDeductionCandidateParamTypes);
1427 if (!isa_and_nonnull<ConstantArrayType>(
1428 SemaRef.Context.getAsArrayType(ElemType))) {
1429 ++Index;
1430 AggrDeductionCandidateParamTypes->push_back(ElemType);
1431 return;
1433 } else {
1434 InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr,
1435 /*TopLevelOfInitList*/ true);
1436 // C++14 [dcl.init.aggr]p13:
1437 // If the assignment-expression can initialize a member, the member is
1438 // initialized. Otherwise [...] brace elision is assumed
1440 // Brace elision is never performed if the element is not an
1441 // assignment-expression.
1442 if (Seq || isa<InitListExpr>(expr)) {
1443 if (!VerifyOnly) {
1444 ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr);
1445 if (Result.isInvalid())
1446 hadError = true;
1448 UpdateStructuredListElement(StructuredList, StructuredIndex,
1449 Result.getAs<Expr>());
1450 } else if (!Seq) {
1451 hadError = true;
1452 } else if (StructuredList) {
1453 UpdateStructuredListElement(StructuredList, StructuredIndex,
1454 getDummyInit());
1456 ++Index;
1457 if (AggrDeductionCandidateParamTypes)
1458 AggrDeductionCandidateParamTypes->push_back(ElemType);
1459 return;
1463 // Fall through for subaggregate initialization
1464 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1465 // FIXME: Need to handle atomic aggregate types with implicit init lists.
1466 return CheckScalarType(Entity, IList, ElemType, Index,
1467 StructuredList, StructuredIndex);
1468 } else if (const ArrayType *arrayType =
1469 SemaRef.Context.getAsArrayType(ElemType)) {
1470 // arrayType can be incomplete if we're initializing a flexible
1471 // array member. There's nothing we can do with the completed
1472 // type here, though.
1474 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
1475 // FIXME: Should we do this checking in verify-only mode?
1476 if (!VerifyOnly)
1477 CheckStringInit(expr, ElemType, arrayType, SemaRef);
1478 if (StructuredList)
1479 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1480 ++Index;
1481 return;
1484 // Fall through for subaggregate initialization.
1486 } else {
1487 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
1488 ElemType->isOpenCLSpecificType()) && "Unexpected type");
1490 // C99 6.7.8p13:
1492 // The initializer for a structure or union object that has
1493 // automatic storage duration shall be either an initializer
1494 // list as described below, or a single expression that has
1495 // compatible structure or union type. In the latter case, the
1496 // initial value of the object, including unnamed members, is
1497 // that of the expression.
1498 ExprResult ExprRes = expr;
1499 if (SemaRef.CheckSingleAssignmentConstraints(
1500 ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
1501 if (ExprRes.isInvalid())
1502 hadError = true;
1503 else {
1504 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
1505 if (ExprRes.isInvalid())
1506 hadError = true;
1508 UpdateStructuredListElement(StructuredList, StructuredIndex,
1509 ExprRes.getAs<Expr>());
1510 ++Index;
1511 return;
1513 ExprRes.get();
1514 // Fall through for subaggregate initialization
1517 // C++ [dcl.init.aggr]p12:
1519 // [...] Otherwise, if the member is itself a non-empty
1520 // subaggregate, brace elision is assumed and the initializer is
1521 // considered for the initialization of the first member of
1522 // the subaggregate.
1523 // OpenCL vector initializer is handled elsewhere.
1524 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1525 ElemType->isAggregateType()) {
1526 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1527 StructuredIndex);
1528 ++StructuredIndex;
1530 // In C++20, brace elision is not permitted for a designated initializer.
1531 if (DirectlyDesignated && SemaRef.getLangOpts().CPlusPlus && !hadError) {
1532 if (InOverloadResolution)
1533 hadError = true;
1534 if (!VerifyOnly) {
1535 SemaRef.Diag(expr->getBeginLoc(),
1536 diag::ext_designated_init_brace_elision)
1537 << expr->getSourceRange()
1538 << FixItHint::CreateInsertion(expr->getBeginLoc(), "{")
1539 << FixItHint::CreateInsertion(
1540 SemaRef.getLocForEndOfToken(expr->getEndLoc()), "}");
1543 } else {
1544 if (!VerifyOnly) {
1545 // We cannot initialize this element, so let PerformCopyInitialization
1546 // produce the appropriate diagnostic. We already checked that this
1547 // initialization will fail.
1548 ExprResult Copy =
1549 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
1550 /*TopLevelOfInitList=*/true);
1551 (void)Copy;
1552 assert(Copy.isInvalid() &&
1553 "expected non-aggregate initialization to fail");
1555 hadError = true;
1556 ++Index;
1557 ++StructuredIndex;
1561 void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1562 InitListExpr *IList, QualType DeclType,
1563 unsigned &Index,
1564 InitListExpr *StructuredList,
1565 unsigned &StructuredIndex) {
1566 assert(Index == 0 && "Index in explicit init list must be zero");
1568 // As an extension, clang supports complex initializers, which initialize
1569 // a complex number component-wise. When an explicit initializer list for
1570 // a complex number contains two initializers, this extension kicks in:
1571 // it expects the initializer list to contain two elements convertible to
1572 // the element type of the complex type. The first element initializes
1573 // the real part, and the second element intitializes the imaginary part.
1575 if (IList->getNumInits() < 2)
1576 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1577 StructuredIndex);
1579 // This is an extension in C. (The builtin _Complex type does not exist
1580 // in the C++ standard.)
1581 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
1582 SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init)
1583 << IList->getSourceRange();
1585 // Initialize the complex number.
1586 QualType elementType = DeclType->castAs<ComplexType>()->getElementType();
1587 InitializedEntity ElementEntity =
1588 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1590 for (unsigned i = 0; i < 2; ++i) {
1591 ElementEntity.setElementIndex(Index);
1592 CheckSubElementType(ElementEntity, IList, elementType, Index,
1593 StructuredList, StructuredIndex);
1597 void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
1598 InitListExpr *IList, QualType DeclType,
1599 unsigned &Index,
1600 InitListExpr *StructuredList,
1601 unsigned &StructuredIndex) {
1602 if (Index >= IList->getNumInits()) {
1603 if (!VerifyOnly) {
1604 if (SemaRef.getLangOpts().CPlusPlus) {
1605 if (DeclType->isSizelessBuiltinType())
1606 SemaRef.Diag(IList->getBeginLoc(),
1607 SemaRef.getLangOpts().CPlusPlus11
1608 ? diag::warn_cxx98_compat_empty_sizeless_initializer
1609 : diag::err_empty_sizeless_initializer)
1610 << DeclType << IList->getSourceRange();
1611 else
1612 SemaRef.Diag(IList->getBeginLoc(),
1613 SemaRef.getLangOpts().CPlusPlus11
1614 ? diag::warn_cxx98_compat_empty_scalar_initializer
1615 : diag::err_empty_scalar_initializer)
1616 << IList->getSourceRange();
1619 hadError =
1620 SemaRef.getLangOpts().CPlusPlus && !SemaRef.getLangOpts().CPlusPlus11;
1621 ++Index;
1622 ++StructuredIndex;
1623 return;
1626 Expr *expr = IList->getInit(Index);
1627 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
1628 // FIXME: This is invalid, and accepting it causes overload resolution
1629 // to pick the wrong overload in some corner cases.
1630 if (!VerifyOnly)
1631 SemaRef.Diag(SubIList->getBeginLoc(), diag::ext_many_braces_around_init)
1632 << DeclType->isSizelessBuiltinType() << SubIList->getSourceRange();
1634 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1635 StructuredIndex);
1636 return;
1637 } else if (isa<DesignatedInitExpr>(expr)) {
1638 if (!VerifyOnly)
1639 SemaRef.Diag(expr->getBeginLoc(),
1640 diag::err_designator_for_scalar_or_sizeless_init)
1641 << DeclType->isSizelessBuiltinType() << DeclType
1642 << expr->getSourceRange();
1643 hadError = true;
1644 ++Index;
1645 ++StructuredIndex;
1646 return;
1649 ExprResult Result;
1650 if (VerifyOnly) {
1651 if (SemaRef.CanPerformCopyInitialization(Entity, expr))
1652 Result = getDummyInit();
1653 else
1654 Result = ExprError();
1655 } else {
1656 Result =
1657 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1658 /*TopLevelOfInitList=*/true);
1661 Expr *ResultExpr = nullptr;
1663 if (Result.isInvalid())
1664 hadError = true; // types weren't compatible.
1665 else {
1666 ResultExpr = Result.getAs<Expr>();
1668 if (ResultExpr != expr && !VerifyOnly) {
1669 // The type was promoted, update initializer list.
1670 // FIXME: Why are we updating the syntactic init list?
1671 IList->setInit(Index, ResultExpr);
1674 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1675 ++Index;
1676 if (AggrDeductionCandidateParamTypes)
1677 AggrDeductionCandidateParamTypes->push_back(DeclType);
1680 void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1681 InitListExpr *IList, QualType DeclType,
1682 unsigned &Index,
1683 InitListExpr *StructuredList,
1684 unsigned &StructuredIndex) {
1685 if (Index >= IList->getNumInits()) {
1686 // FIXME: It would be wonderful if we could point at the actual member. In
1687 // general, it would be useful to pass location information down the stack,
1688 // so that we know the location (or decl) of the "current object" being
1689 // initialized.
1690 if (!VerifyOnly)
1691 SemaRef.Diag(IList->getBeginLoc(),
1692 diag::err_init_reference_member_uninitialized)
1693 << DeclType << IList->getSourceRange();
1694 hadError = true;
1695 ++Index;
1696 ++StructuredIndex;
1697 return;
1700 Expr *expr = IList->getInit(Index);
1701 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1702 if (!VerifyOnly)
1703 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list)
1704 << DeclType << IList->getSourceRange();
1705 hadError = true;
1706 ++Index;
1707 ++StructuredIndex;
1708 return;
1711 ExprResult Result;
1712 if (VerifyOnly) {
1713 if (SemaRef.CanPerformCopyInitialization(Entity,expr))
1714 Result = getDummyInit();
1715 else
1716 Result = ExprError();
1717 } else {
1718 Result =
1719 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1720 /*TopLevelOfInitList=*/true);
1723 if (Result.isInvalid())
1724 hadError = true;
1726 expr = Result.getAs<Expr>();
1727 // FIXME: Why are we updating the syntactic init list?
1728 if (!VerifyOnly && expr)
1729 IList->setInit(Index, expr);
1731 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1732 ++Index;
1733 if (AggrDeductionCandidateParamTypes)
1734 AggrDeductionCandidateParamTypes->push_back(DeclType);
1737 void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1738 InitListExpr *IList, QualType DeclType,
1739 unsigned &Index,
1740 InitListExpr *StructuredList,
1741 unsigned &StructuredIndex) {
1742 const VectorType *VT = DeclType->castAs<VectorType>();
1743 unsigned maxElements = VT->getNumElements();
1744 unsigned numEltsInit = 0;
1745 QualType elementType = VT->getElementType();
1747 if (Index >= IList->getNumInits()) {
1748 // Make sure the element type can be value-initialized.
1749 CheckEmptyInitializable(
1750 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1751 IList->getEndLoc());
1752 return;
1755 if (!SemaRef.getLangOpts().OpenCL && !SemaRef.getLangOpts().HLSL ) {
1756 // If the initializing element is a vector, try to copy-initialize
1757 // instead of breaking it apart (which is doomed to failure anyway).
1758 Expr *Init = IList->getInit(Index);
1759 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1760 ExprResult Result;
1761 if (VerifyOnly) {
1762 if (SemaRef.CanPerformCopyInitialization(Entity, Init))
1763 Result = getDummyInit();
1764 else
1765 Result = ExprError();
1766 } else {
1767 Result =
1768 SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init,
1769 /*TopLevelOfInitList=*/true);
1772 Expr *ResultExpr = nullptr;
1773 if (Result.isInvalid())
1774 hadError = true; // types weren't compatible.
1775 else {
1776 ResultExpr = Result.getAs<Expr>();
1778 if (ResultExpr != Init && !VerifyOnly) {
1779 // The type was promoted, update initializer list.
1780 // FIXME: Why are we updating the syntactic init list?
1781 IList->setInit(Index, ResultExpr);
1784 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1785 ++Index;
1786 if (AggrDeductionCandidateParamTypes)
1787 AggrDeductionCandidateParamTypes->push_back(elementType);
1788 return;
1791 InitializedEntity ElementEntity =
1792 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1794 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1795 // Don't attempt to go past the end of the init list
1796 if (Index >= IList->getNumInits()) {
1797 CheckEmptyInitializable(ElementEntity, IList->getEndLoc());
1798 break;
1801 ElementEntity.setElementIndex(Index);
1802 CheckSubElementType(ElementEntity, IList, elementType, Index,
1803 StructuredList, StructuredIndex);
1806 if (VerifyOnly)
1807 return;
1809 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1810 const VectorType *T = Entity.getType()->castAs<VectorType>();
1811 if (isBigEndian && (T->getVectorKind() == VectorKind::Neon ||
1812 T->getVectorKind() == VectorKind::NeonPoly)) {
1813 // The ability to use vector initializer lists is a GNU vector extension
1814 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1815 // endian machines it works fine, however on big endian machines it
1816 // exhibits surprising behaviour:
1818 // uint32x2_t x = {42, 64};
1819 // return vget_lane_u32(x, 0); // Will return 64.
1821 // Because of this, explicitly call out that it is non-portable.
1823 SemaRef.Diag(IList->getBeginLoc(),
1824 diag::warn_neon_vector_initializer_non_portable);
1826 const char *typeCode;
1827 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1829 if (elementType->isFloatingType())
1830 typeCode = "f";
1831 else if (elementType->isSignedIntegerType())
1832 typeCode = "s";
1833 else if (elementType->isUnsignedIntegerType())
1834 typeCode = "u";
1835 else
1836 llvm_unreachable("Invalid element type!");
1838 SemaRef.Diag(IList->getBeginLoc(),
1839 SemaRef.Context.getTypeSize(VT) > 64
1840 ? diag::note_neon_vector_initializer_non_portable_q
1841 : diag::note_neon_vector_initializer_non_portable)
1842 << typeCode << typeSize;
1845 return;
1848 InitializedEntity ElementEntity =
1849 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1851 // OpenCL and HLSL initializers allow vectors to be constructed from vectors.
1852 for (unsigned i = 0; i < maxElements; ++i) {
1853 // Don't attempt to go past the end of the init list
1854 if (Index >= IList->getNumInits())
1855 break;
1857 ElementEntity.setElementIndex(Index);
1859 QualType IType = IList->getInit(Index)->getType();
1860 if (!IType->isVectorType()) {
1861 CheckSubElementType(ElementEntity, IList, elementType, Index,
1862 StructuredList, StructuredIndex);
1863 ++numEltsInit;
1864 } else {
1865 QualType VecType;
1866 const VectorType *IVT = IType->castAs<VectorType>();
1867 unsigned numIElts = IVT->getNumElements();
1869 if (IType->isExtVectorType())
1870 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1871 else
1872 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
1873 IVT->getVectorKind());
1874 CheckSubElementType(ElementEntity, IList, VecType, Index,
1875 StructuredList, StructuredIndex);
1876 numEltsInit += numIElts;
1880 // OpenCL and HLSL require all elements to be initialized.
1881 if (numEltsInit != maxElements) {
1882 if (!VerifyOnly)
1883 SemaRef.Diag(IList->getBeginLoc(),
1884 diag::err_vector_incorrect_num_initializers)
1885 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1886 hadError = true;
1890 /// Check if the type of a class element has an accessible destructor, and marks
1891 /// it referenced. Returns true if we shouldn't form a reference to the
1892 /// destructor.
1894 /// Aggregate initialization requires a class element's destructor be
1895 /// accessible per 11.6.1 [dcl.init.aggr]:
1897 /// The destructor for each element of class type is potentially invoked
1898 /// (15.4 [class.dtor]) from the context where the aggregate initialization
1899 /// occurs.
1900 static bool checkDestructorReference(QualType ElementType, SourceLocation Loc,
1901 Sema &SemaRef) {
1902 auto *CXXRD = ElementType->getAsCXXRecordDecl();
1903 if (!CXXRD)
1904 return false;
1906 CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(CXXRD);
1907 SemaRef.CheckDestructorAccess(Loc, Destructor,
1908 SemaRef.PDiag(diag::err_access_dtor_temp)
1909 << ElementType);
1910 SemaRef.MarkFunctionReferenced(Loc, Destructor);
1911 return SemaRef.DiagnoseUseOfDecl(Destructor, Loc);
1914 void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
1915 InitListExpr *IList, QualType &DeclType,
1916 llvm::APSInt elementIndex,
1917 bool SubobjectIsDesignatorContext,
1918 unsigned &Index,
1919 InitListExpr *StructuredList,
1920 unsigned &StructuredIndex) {
1921 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1923 if (!VerifyOnly) {
1924 if (checkDestructorReference(arrayType->getElementType(),
1925 IList->getEndLoc(), SemaRef)) {
1926 hadError = true;
1927 return;
1931 // Check for the special-case of initializing an array with a string.
1932 if (Index < IList->getNumInits()) {
1933 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1934 SIF_None) {
1935 // We place the string literal directly into the resulting
1936 // initializer list. This is the only place where the structure
1937 // of the structured initializer list doesn't match exactly,
1938 // because doing so would involve allocating one character
1939 // constant for each string.
1940 // FIXME: Should we do these checks in verify-only mode too?
1941 if (!VerifyOnly)
1942 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1943 if (StructuredList) {
1944 UpdateStructuredListElement(StructuredList, StructuredIndex,
1945 IList->getInit(Index));
1946 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1948 ++Index;
1949 if (AggrDeductionCandidateParamTypes)
1950 AggrDeductionCandidateParamTypes->push_back(DeclType);
1951 return;
1954 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
1955 // Check for VLAs; in standard C it would be possible to check this
1956 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1957 // them in all sorts of strange places).
1958 bool HasErr = IList->getNumInits() != 0 || SemaRef.getLangOpts().CPlusPlus;
1959 if (!VerifyOnly) {
1960 // C23 6.7.10p4: An entity of variable length array type shall not be
1961 // initialized except by an empty initializer.
1963 // The C extension warnings are issued from ParseBraceInitializer() and
1964 // do not need to be issued here. However, we continue to issue an error
1965 // in the case there are initializers or we are compiling C++. We allow
1966 // use of VLAs in C++, but it's not clear we want to allow {} to zero
1967 // init a VLA in C++ in all cases (such as with non-trivial constructors).
1968 // FIXME: should we allow this construct in C++ when it makes sense to do
1969 // so?
1970 if (HasErr)
1971 SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),
1972 diag::err_variable_object_no_init)
1973 << VAT->getSizeExpr()->getSourceRange();
1975 hadError = HasErr;
1976 ++Index;
1977 ++StructuredIndex;
1978 return;
1981 // We might know the maximum number of elements in advance.
1982 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1983 elementIndex.isUnsigned());
1984 bool maxElementsKnown = false;
1985 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
1986 maxElements = CAT->getSize();
1987 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
1988 elementIndex.setIsUnsigned(maxElements.isUnsigned());
1989 maxElementsKnown = true;
1992 QualType elementType = arrayType->getElementType();
1993 while (Index < IList->getNumInits()) {
1994 Expr *Init = IList->getInit(Index);
1995 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1996 // If we're not the subobject that matches up with the '{' for
1997 // the designator, we shouldn't be handling the
1998 // designator. Return immediately.
1999 if (!SubobjectIsDesignatorContext)
2000 return;
2002 // Handle this designated initializer. elementIndex will be
2003 // updated to be the next array element we'll initialize.
2004 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
2005 DeclType, nullptr, &elementIndex, Index,
2006 StructuredList, StructuredIndex, true,
2007 false)) {
2008 hadError = true;
2009 continue;
2012 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
2013 maxElements = maxElements.extend(elementIndex.getBitWidth());
2014 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
2015 elementIndex = elementIndex.extend(maxElements.getBitWidth());
2016 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2018 // If the array is of incomplete type, keep track of the number of
2019 // elements in the initializer.
2020 if (!maxElementsKnown && elementIndex > maxElements)
2021 maxElements = elementIndex;
2023 continue;
2026 // If we know the maximum number of elements, and we've already
2027 // hit it, stop consuming elements in the initializer list.
2028 if (maxElementsKnown && elementIndex == maxElements)
2029 break;
2031 InitializedEntity ElementEntity =
2032 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
2033 Entity);
2034 // Check this element.
2035 CheckSubElementType(ElementEntity, IList, elementType, Index,
2036 StructuredList, StructuredIndex);
2037 ++elementIndex;
2039 // If the array is of incomplete type, keep track of the number of
2040 // elements in the initializer.
2041 if (!maxElementsKnown && elementIndex > maxElements)
2042 maxElements = elementIndex;
2044 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
2045 // If this is an incomplete array type, the actual type needs to
2046 // be calculated here.
2047 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
2048 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
2049 // Sizing an array implicitly to zero is not allowed by ISO C,
2050 // but is supported by GNU.
2051 SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
2054 DeclType = SemaRef.Context.getConstantArrayType(
2055 elementType, maxElements, nullptr, ArraySizeModifier::Normal, 0);
2057 if (!hadError) {
2058 // If there are any members of the array that get value-initialized, check
2059 // that is possible. That happens if we know the bound and don't have
2060 // enough elements, or if we're performing an array new with an unknown
2061 // bound.
2062 if ((maxElementsKnown && elementIndex < maxElements) ||
2063 Entity.isVariableLengthArrayNew())
2064 CheckEmptyInitializable(
2065 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
2066 IList->getEndLoc());
2070 bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
2071 Expr *InitExpr,
2072 FieldDecl *Field,
2073 bool TopLevelObject) {
2074 // Handle GNU flexible array initializers.
2075 unsigned FlexArrayDiag;
2076 if (isa<InitListExpr>(InitExpr) &&
2077 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
2078 // Empty flexible array init always allowed as an extension
2079 FlexArrayDiag = diag::ext_flexible_array_init;
2080 } else if (!TopLevelObject) {
2081 // Disallow flexible array init on non-top-level object
2082 FlexArrayDiag = diag::err_flexible_array_init;
2083 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
2084 // Disallow flexible array init on anything which is not a variable.
2085 FlexArrayDiag = diag::err_flexible_array_init;
2086 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
2087 // Disallow flexible array init on local variables.
2088 FlexArrayDiag = diag::err_flexible_array_init;
2089 } else {
2090 // Allow other cases.
2091 FlexArrayDiag = diag::ext_flexible_array_init;
2094 if (!VerifyOnly) {
2095 SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
2096 << InitExpr->getBeginLoc();
2097 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2098 << Field;
2101 return FlexArrayDiag != diag::ext_flexible_array_init;
2104 void InitListChecker::CheckStructUnionTypes(
2105 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
2106 CXXRecordDecl::base_class_const_range Bases, RecordDecl::field_iterator Field,
2107 bool SubobjectIsDesignatorContext, unsigned &Index,
2108 InitListExpr *StructuredList, unsigned &StructuredIndex,
2109 bool TopLevelObject) {
2110 const RecordDecl *RD = getRecordDecl(DeclType);
2112 // If the record is invalid, some of it's members are invalid. To avoid
2113 // confusion, we forgo checking the initializer for the entire record.
2114 if (RD->isInvalidDecl()) {
2115 // Assume it was supposed to consume a single initializer.
2116 ++Index;
2117 hadError = true;
2118 return;
2121 if (RD->isUnion() && IList->getNumInits() == 0) {
2122 if (!VerifyOnly)
2123 for (FieldDecl *FD : RD->fields()) {
2124 QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
2125 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2126 hadError = true;
2127 return;
2131 // If there's a default initializer, use it.
2132 if (isa<CXXRecordDecl>(RD) &&
2133 cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
2134 if (!StructuredList)
2135 return;
2136 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2137 Field != FieldEnd; ++Field) {
2138 if (Field->hasInClassInitializer()) {
2139 StructuredList->setInitializedFieldInUnion(*Field);
2140 // FIXME: Actually build a CXXDefaultInitExpr?
2141 return;
2146 // Value-initialize the first member of the union that isn't an unnamed
2147 // bitfield.
2148 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2149 Field != FieldEnd; ++Field) {
2150 if (!Field->isUnnamedBitfield()) {
2151 CheckEmptyInitializable(
2152 InitializedEntity::InitializeMember(*Field, &Entity),
2153 IList->getEndLoc());
2154 if (StructuredList)
2155 StructuredList->setInitializedFieldInUnion(*Field);
2156 break;
2159 return;
2162 bool InitializedSomething = false;
2164 // If we have any base classes, they are initialized prior to the fields.
2165 for (auto I = Bases.begin(), E = Bases.end(); I != E; ++I) {
2166 auto &Base = *I;
2167 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
2169 // Designated inits always initialize fields, so if we see one, all
2170 // remaining base classes have no explicit initializer.
2171 if (Init && isa<DesignatedInitExpr>(Init))
2172 Init = nullptr;
2174 // C++ [over.match.class.deduct]p1.6:
2175 // each non-trailing aggregate element that is a pack expansion is assumed
2176 // to correspond to no elements of the initializer list, and (1.7) a
2177 // trailing aggregate element that is a pack expansion is assumed to
2178 // correspond to all remaining elements of the initializer list (if any).
2180 // C++ [over.match.class.deduct]p1.9:
2181 // ... except that additional parameter packs of the form P_j... are
2182 // inserted into the parameter list in their original aggregate element
2183 // position corresponding to each non-trailing aggregate element of
2184 // type P_j that was skipped because it was a parameter pack, and the
2185 // trailing sequence of parameters corresponding to a trailing
2186 // aggregate element that is a pack expansion (if any) is replaced
2187 // by a single parameter of the form T_n....
2188 if (AggrDeductionCandidateParamTypes && Base.isPackExpansion()) {
2189 AggrDeductionCandidateParamTypes->push_back(
2190 SemaRef.Context.getPackExpansionType(Base.getType(), std::nullopt));
2192 // Trailing pack expansion
2193 if (I + 1 == E && RD->field_empty()) {
2194 if (Index < IList->getNumInits())
2195 Index = IList->getNumInits();
2196 return;
2199 continue;
2202 SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
2203 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
2204 SemaRef.Context, &Base, false, &Entity);
2205 if (Init) {
2206 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
2207 StructuredList, StructuredIndex);
2208 InitializedSomething = true;
2209 } else {
2210 CheckEmptyInitializable(BaseEntity, InitLoc);
2213 if (!VerifyOnly)
2214 if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) {
2215 hadError = true;
2216 return;
2220 // If structDecl is a forward declaration, this loop won't do
2221 // anything except look at designated initializers; That's okay,
2222 // because an error should get printed out elsewhere. It might be
2223 // worthwhile to skip over the rest of the initializer, though.
2224 RecordDecl::field_iterator FieldEnd = RD->field_end();
2225 size_t NumRecordDecls = llvm::count_if(RD->decls(), [&](const Decl *D) {
2226 return isa<FieldDecl>(D) || isa<RecordDecl>(D);
2228 bool CheckForMissingFields =
2229 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
2230 bool HasDesignatedInit = false;
2232 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
2234 while (Index < IList->getNumInits()) {
2235 Expr *Init = IList->getInit(Index);
2236 SourceLocation InitLoc = Init->getBeginLoc();
2238 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2239 // If we're not the subobject that matches up with the '{' for
2240 // the designator, we shouldn't be handling the
2241 // designator. Return immediately.
2242 if (!SubobjectIsDesignatorContext)
2243 return;
2245 HasDesignatedInit = true;
2247 // Handle this designated initializer. Field will be updated to
2248 // the next field that we'll be initializing.
2249 bool DesignatedInitFailed = CheckDesignatedInitializer(
2250 Entity, IList, DIE, 0, DeclType, &Field, nullptr, Index,
2251 StructuredList, StructuredIndex, true, TopLevelObject);
2252 if (DesignatedInitFailed)
2253 hadError = true;
2255 // Find the field named by the designated initializer.
2256 DesignatedInitExpr::Designator *D = DIE->getDesignator(0);
2257 if (!VerifyOnly && D->isFieldDesignator()) {
2258 FieldDecl *F = D->getFieldDecl();
2259 InitializedFields.insert(F);
2260 if (!DesignatedInitFailed) {
2261 QualType ET = SemaRef.Context.getBaseElementType(F->getType());
2262 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2263 hadError = true;
2264 return;
2269 InitializedSomething = true;
2271 // Disable check for missing fields when designators are used.
2272 // This matches gcc behaviour.
2273 if (!SemaRef.getLangOpts().CPlusPlus)
2274 CheckForMissingFields = false;
2275 continue;
2278 // Check if this is an initializer of forms:
2280 // struct foo f = {};
2281 // struct foo g = {0};
2283 // These are okay for randomized structures. [C99 6.7.8p19]
2285 // Also, if there is only one element in the structure, we allow something
2286 // like this, because it's really not randomized in the tranditional sense.
2288 // struct foo h = {bar};
2289 auto IsZeroInitializer = [&](const Expr *I) {
2290 if (IList->getNumInits() == 1) {
2291 if (NumRecordDecls == 1)
2292 return true;
2293 if (const auto *IL = dyn_cast<IntegerLiteral>(I))
2294 return IL->getValue().isZero();
2296 return false;
2299 // Don't allow non-designated initializers on randomized structures.
2300 if (RD->isRandomized() && !IsZeroInitializer(Init)) {
2301 if (!VerifyOnly)
2302 SemaRef.Diag(InitLoc, diag::err_non_designated_init_used);
2303 hadError = true;
2304 break;
2307 if (Field == FieldEnd) {
2308 // We've run out of fields. We're done.
2309 break;
2312 // We've already initialized a member of a union. We're done.
2313 if (InitializedSomething && RD->isUnion())
2314 break;
2316 // If we've hit the flexible array member at the end, we're done.
2317 if (Field->getType()->isIncompleteArrayType())
2318 break;
2320 if (Field->isUnnamedBitfield()) {
2321 // Don't initialize unnamed bitfields, e.g. "int : 20;"
2322 ++Field;
2323 continue;
2326 // Make sure we can use this declaration.
2327 bool InvalidUse;
2328 if (VerifyOnly)
2329 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2330 else
2331 InvalidUse = SemaRef.DiagnoseUseOfDecl(
2332 *Field, IList->getInit(Index)->getBeginLoc());
2333 if (InvalidUse) {
2334 ++Index;
2335 ++Field;
2336 hadError = true;
2337 continue;
2340 if (!VerifyOnly) {
2341 QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
2342 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2343 hadError = true;
2344 return;
2348 InitializedEntity MemberEntity =
2349 InitializedEntity::InitializeMember(*Field, &Entity);
2350 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2351 StructuredList, StructuredIndex);
2352 InitializedSomething = true;
2353 InitializedFields.insert(*Field);
2355 if (RD->isUnion() && StructuredList) {
2356 // Initialize the first field within the union.
2357 StructuredList->setInitializedFieldInUnion(*Field);
2360 ++Field;
2363 // Emit warnings for missing struct field initializers.
2364 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
2365 !RD->isUnion()) {
2366 // It is possible we have one or more unnamed bitfields remaining.
2367 // Find first (if any) named field and emit warning.
2368 for (RecordDecl::field_iterator it = HasDesignatedInit ? RD->field_begin()
2369 : Field,
2370 end = RD->field_end();
2371 it != end; ++it) {
2372 if (HasDesignatedInit && InitializedFields.count(*it))
2373 continue;
2375 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer() &&
2376 !it->getType()->isIncompleteArrayType()) {
2377 SemaRef.Diag(IList->getSourceRange().getEnd(),
2378 diag::warn_missing_field_initializers)
2379 << *it;
2380 break;
2385 // Check that any remaining fields can be value-initialized if we're not
2386 // building a structured list. (If we are, we'll check this later.)
2387 if (!StructuredList && Field != FieldEnd && !RD->isUnion() &&
2388 !Field->getType()->isIncompleteArrayType()) {
2389 for (; Field != FieldEnd && !hadError; ++Field) {
2390 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
2391 CheckEmptyInitializable(
2392 InitializedEntity::InitializeMember(*Field, &Entity),
2393 IList->getEndLoc());
2397 // Check that the types of the remaining fields have accessible destructors.
2398 if (!VerifyOnly) {
2399 // If the initializer expression has a designated initializer, check the
2400 // elements for which a designated initializer is not provided too.
2401 RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
2402 : Field;
2403 for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
2404 QualType ET = SemaRef.Context.getBaseElementType(I->getType());
2405 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2406 hadError = true;
2407 return;
2412 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
2413 Index >= IList->getNumInits())
2414 return;
2416 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
2417 TopLevelObject)) {
2418 hadError = true;
2419 ++Index;
2420 return;
2423 InitializedEntity MemberEntity =
2424 InitializedEntity::InitializeMember(*Field, &Entity);
2426 if (isa<InitListExpr>(IList->getInit(Index)) ||
2427 AggrDeductionCandidateParamTypes)
2428 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2429 StructuredList, StructuredIndex);
2430 else
2431 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
2432 StructuredList, StructuredIndex);
2435 /// Expand a field designator that refers to a member of an
2436 /// anonymous struct or union into a series of field designators that
2437 /// refers to the field within the appropriate subobject.
2439 static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
2440 DesignatedInitExpr *DIE,
2441 unsigned DesigIdx,
2442 IndirectFieldDecl *IndirectField) {
2443 typedef DesignatedInitExpr::Designator Designator;
2445 // Build the replacement designators.
2446 SmallVector<Designator, 4> Replacements;
2447 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2448 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2449 if (PI + 1 == PE)
2450 Replacements.push_back(Designator::CreateFieldDesignator(
2451 (IdentifierInfo *)nullptr, DIE->getDesignator(DesigIdx)->getDotLoc(),
2452 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2453 else
2454 Replacements.push_back(Designator::CreateFieldDesignator(
2455 (IdentifierInfo *)nullptr, SourceLocation(), SourceLocation()));
2456 assert(isa<FieldDecl>(*PI));
2457 Replacements.back().setFieldDecl(cast<FieldDecl>(*PI));
2460 // Expand the current designator into the set of replacement
2461 // designators, so we have a full subobject path down to where the
2462 // member of the anonymous struct/union is actually stored.
2463 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
2464 &Replacements[0] + Replacements.size());
2467 static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
2468 DesignatedInitExpr *DIE) {
2469 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2470 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2471 for (unsigned I = 0; I < NumIndexExprs; ++I)
2472 IndexExprs[I] = DIE->getSubExpr(I + 1);
2473 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2474 IndexExprs,
2475 DIE->getEqualOrColonLoc(),
2476 DIE->usesGNUSyntax(), DIE->getInit());
2479 namespace {
2481 // Callback to only accept typo corrections that are for field members of
2482 // the given struct or union.
2483 class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {
2484 public:
2485 explicit FieldInitializerValidatorCCC(const RecordDecl *RD)
2486 : Record(RD) {}
2488 bool ValidateCandidate(const TypoCorrection &candidate) override {
2489 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2490 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2493 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2494 return std::make_unique<FieldInitializerValidatorCCC>(*this);
2497 private:
2498 const RecordDecl *Record;
2501 } // end anonymous namespace
2503 /// Check the well-formedness of a C99 designated initializer.
2505 /// Determines whether the designated initializer @p DIE, which
2506 /// resides at the given @p Index within the initializer list @p
2507 /// IList, is well-formed for a current object of type @p DeclType
2508 /// (C99 6.7.8). The actual subobject that this designator refers to
2509 /// within the current subobject is returned in either
2510 /// @p NextField or @p NextElementIndex (whichever is appropriate).
2512 /// @param IList The initializer list in which this designated
2513 /// initializer occurs.
2515 /// @param DIE The designated initializer expression.
2517 /// @param DesigIdx The index of the current designator.
2519 /// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2520 /// into which the designation in @p DIE should refer.
2522 /// @param NextField If non-NULL and the first designator in @p DIE is
2523 /// a field, this will be set to the field declaration corresponding
2524 /// to the field named by the designator. On input, this is expected to be
2525 /// the next field that would be initialized in the absence of designation,
2526 /// if the complete object being initialized is a struct.
2528 /// @param NextElementIndex If non-NULL and the first designator in @p
2529 /// DIE is an array designator or GNU array-range designator, this
2530 /// will be set to the last index initialized by this designator.
2532 /// @param Index Index into @p IList where the designated initializer
2533 /// @p DIE occurs.
2535 /// @param StructuredList The initializer list expression that
2536 /// describes all of the subobject initializers in the order they'll
2537 /// actually be initialized.
2539 /// @returns true if there was an error, false otherwise.
2540 bool
2541 InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2542 InitListExpr *IList,
2543 DesignatedInitExpr *DIE,
2544 unsigned DesigIdx,
2545 QualType &CurrentObjectType,
2546 RecordDecl::field_iterator *NextField,
2547 llvm::APSInt *NextElementIndex,
2548 unsigned &Index,
2549 InitListExpr *StructuredList,
2550 unsigned &StructuredIndex,
2551 bool FinishSubobjectInit,
2552 bool TopLevelObject) {
2553 if (DesigIdx == DIE->size()) {
2554 // C++20 designated initialization can result in direct-list-initialization
2555 // of the designated subobject. This is the only way that we can end up
2556 // performing direct initialization as part of aggregate initialization, so
2557 // it needs special handling.
2558 if (DIE->isDirectInit()) {
2559 Expr *Init = DIE->getInit();
2560 assert(isa<InitListExpr>(Init) &&
2561 "designator result in direct non-list initialization?");
2562 InitializationKind Kind = InitializationKind::CreateDirectList(
2563 DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc());
2564 InitializationSequence Seq(SemaRef, Entity, Kind, Init,
2565 /*TopLevelOfInitList*/ true);
2566 if (StructuredList) {
2567 ExprResult Result = VerifyOnly
2568 ? getDummyInit()
2569 : Seq.Perform(SemaRef, Entity, Kind, Init);
2570 UpdateStructuredListElement(StructuredList, StructuredIndex,
2571 Result.get());
2573 ++Index;
2574 if (AggrDeductionCandidateParamTypes)
2575 AggrDeductionCandidateParamTypes->push_back(CurrentObjectType);
2576 return !Seq;
2579 // Check the actual initialization for the designated object type.
2580 bool prevHadError = hadError;
2582 // Temporarily remove the designator expression from the
2583 // initializer list that the child calls see, so that we don't try
2584 // to re-process the designator.
2585 unsigned OldIndex = Index;
2586 IList->setInit(OldIndex, DIE->getInit());
2588 CheckSubElementType(Entity, IList, CurrentObjectType, Index, StructuredList,
2589 StructuredIndex, /*DirectlyDesignated=*/true);
2591 // Restore the designated initializer expression in the syntactic
2592 // form of the initializer list.
2593 if (IList->getInit(OldIndex) != DIE->getInit())
2594 DIE->setInit(IList->getInit(OldIndex));
2595 IList->setInit(OldIndex, DIE);
2597 return hadError && !prevHadError;
2600 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
2601 bool IsFirstDesignator = (DesigIdx == 0);
2602 if (IsFirstDesignator ? FullyStructuredList : StructuredList) {
2603 // Determine the structural initializer list that corresponds to the
2604 // current subobject.
2605 if (IsFirstDesignator)
2606 StructuredList = FullyStructuredList;
2607 else {
2608 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2609 StructuredList->getInit(StructuredIndex) : nullptr;
2610 if (!ExistingInit && StructuredList->hasArrayFiller())
2611 ExistingInit = StructuredList->getArrayFiller();
2613 if (!ExistingInit)
2614 StructuredList = getStructuredSubobjectInit(
2615 IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
2616 SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
2617 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2618 StructuredList = Result;
2619 else {
2620 // We are creating an initializer list that initializes the
2621 // subobjects of the current object, but there was already an
2622 // initialization that completely initialized the current
2623 // subobject, e.g., by a compound literal:
2625 // struct X { int a, b; };
2626 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2628 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
2629 // designated initializer re-initializes only its current object
2630 // subobject [0].b.
2631 diagnoseInitOverride(ExistingInit,
2632 SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2633 /*UnionOverride=*/false,
2634 /*FullyOverwritten=*/false);
2636 if (!VerifyOnly) {
2637 if (DesignatedInitUpdateExpr *E =
2638 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2639 StructuredList = E->getUpdater();
2640 else {
2641 DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
2642 DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(),
2643 ExistingInit, DIE->getEndLoc());
2644 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2645 StructuredList = DIUE->getUpdater();
2647 } else {
2648 // We don't need to track the structured representation of a
2649 // designated init update of an already-fully-initialized object in
2650 // verify-only mode. The only reason we would need the structure is
2651 // to determine where the uninitialized "holes" are, and in this
2652 // case, we know there aren't any and we can't introduce any.
2653 StructuredList = nullptr;
2659 if (D->isFieldDesignator()) {
2660 // C99 6.7.8p7:
2662 // If a designator has the form
2664 // . identifier
2666 // then the current object (defined below) shall have
2667 // structure or union type and the identifier shall be the
2668 // name of a member of that type.
2669 RecordDecl *RD = getRecordDecl(CurrentObjectType);
2670 if (!RD) {
2671 SourceLocation Loc = D->getDotLoc();
2672 if (Loc.isInvalid())
2673 Loc = D->getFieldLoc();
2674 if (!VerifyOnly)
2675 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
2676 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2677 ++Index;
2678 return true;
2681 FieldDecl *KnownField = D->getFieldDecl();
2682 if (!KnownField) {
2683 const IdentifierInfo *FieldName = D->getFieldName();
2684 ValueDecl *VD = SemaRef.tryLookupUnambiguousFieldDecl(RD, FieldName);
2685 if (auto *FD = dyn_cast_if_present<FieldDecl>(VD)) {
2686 KnownField = FD;
2687 } else if (auto *IFD = dyn_cast_if_present<IndirectFieldDecl>(VD)) {
2688 // In verify mode, don't modify the original.
2689 if (VerifyOnly)
2690 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2691 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
2692 D = DIE->getDesignator(DesigIdx);
2693 KnownField = cast<FieldDecl>(*IFD->chain_begin());
2695 if (!KnownField) {
2696 if (VerifyOnly) {
2697 ++Index;
2698 return true; // No typo correction when just trying this out.
2701 // We found a placeholder variable
2702 if (SemaRef.DiagRedefinedPlaceholderFieldDecl(DIE->getBeginLoc(), RD,
2703 FieldName)) {
2704 ++Index;
2705 return true;
2707 // Name lookup found something, but it wasn't a field.
2708 if (DeclContextLookupResult Lookup = RD->lookup(FieldName);
2709 !Lookup.empty()) {
2710 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2711 << FieldName;
2712 SemaRef.Diag(Lookup.front()->getLocation(),
2713 diag::note_field_designator_found);
2714 ++Index;
2715 return true;
2718 // Name lookup didn't find anything.
2719 // Determine whether this was a typo for another field name.
2720 FieldInitializerValidatorCCC CCC(RD);
2721 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2722 DeclarationNameInfo(FieldName, D->getFieldLoc()),
2723 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC,
2724 Sema::CTK_ErrorRecovery, RD)) {
2725 SemaRef.diagnoseTypo(
2726 Corrected,
2727 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
2728 << FieldName << CurrentObjectType);
2729 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
2730 hadError = true;
2731 } else {
2732 // Typo correction didn't find anything.
2733 SourceLocation Loc = D->getFieldLoc();
2735 // The loc can be invalid with a "null" designator (i.e. an anonymous
2736 // union/struct). Do our best to approximate the location.
2737 if (Loc.isInvalid())
2738 Loc = IList->getBeginLoc();
2740 SemaRef.Diag(Loc, diag::err_field_designator_unknown)
2741 << FieldName << CurrentObjectType << DIE->getSourceRange();
2742 ++Index;
2743 return true;
2748 unsigned NumBases = 0;
2749 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
2750 NumBases = CXXRD->getNumBases();
2752 unsigned FieldIndex = NumBases;
2754 for (auto *FI : RD->fields()) {
2755 if (FI->isUnnamedBitfield())
2756 continue;
2757 if (declaresSameEntity(KnownField, FI)) {
2758 KnownField = FI;
2759 break;
2761 ++FieldIndex;
2764 RecordDecl::field_iterator Field =
2765 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
2767 // All of the fields of a union are located at the same place in
2768 // the initializer list.
2769 if (RD->isUnion()) {
2770 FieldIndex = 0;
2771 if (StructuredList) {
2772 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
2773 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
2774 assert(StructuredList->getNumInits() == 1
2775 && "A union should never have more than one initializer!");
2777 Expr *ExistingInit = StructuredList->getInit(0);
2778 if (ExistingInit) {
2779 // We're about to throw away an initializer, emit warning.
2780 diagnoseInitOverride(
2781 ExistingInit, SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2782 /*UnionOverride=*/true,
2783 /*FullyOverwritten=*/SemaRef.getLangOpts().CPlusPlus ? false
2784 : true);
2787 // remove existing initializer
2788 StructuredList->resizeInits(SemaRef.Context, 0);
2789 StructuredList->setInitializedFieldInUnion(nullptr);
2792 StructuredList->setInitializedFieldInUnion(*Field);
2796 // Make sure we can use this declaration.
2797 bool InvalidUse;
2798 if (VerifyOnly)
2799 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2800 else
2801 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
2802 if (InvalidUse) {
2803 ++Index;
2804 return true;
2807 // C++20 [dcl.init.list]p3:
2808 // The ordered identifiers in the designators of the designated-
2809 // initializer-list shall form a subsequence of the ordered identifiers
2810 // in the direct non-static data members of T.
2812 // Note that this is not a condition on forming the aggregate
2813 // initialization, only on actually performing initialization,
2814 // so it is not checked in VerifyOnly mode.
2816 // FIXME: This is the only reordering diagnostic we produce, and it only
2817 // catches cases where we have a top-level field designator that jumps
2818 // backwards. This is the only such case that is reachable in an
2819 // otherwise-valid C++20 program, so is the only case that's required for
2820 // conformance, but for consistency, we should diagnose all the other
2821 // cases where a designator takes us backwards too.
2822 if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus &&
2823 NextField &&
2824 (*NextField == RD->field_end() ||
2825 (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) {
2826 // Find the field that we just initialized.
2827 FieldDecl *PrevField = nullptr;
2828 for (auto FI = RD->field_begin(); FI != RD->field_end(); ++FI) {
2829 if (FI->isUnnamedBitfield())
2830 continue;
2831 if (*NextField != RD->field_end() &&
2832 declaresSameEntity(*FI, **NextField))
2833 break;
2834 PrevField = *FI;
2837 if (PrevField &&
2838 PrevField->getFieldIndex() > KnownField->getFieldIndex()) {
2839 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
2840 diag::ext_designated_init_reordered)
2841 << KnownField << PrevField << DIE->getSourceRange();
2843 unsigned OldIndex = StructuredIndex - 1;
2844 if (StructuredList && OldIndex <= StructuredList->getNumInits()) {
2845 if (Expr *PrevInit = StructuredList->getInit(OldIndex)) {
2846 SemaRef.Diag(PrevInit->getBeginLoc(),
2847 diag::note_previous_field_init)
2848 << PrevField << PrevInit->getSourceRange();
2855 // Update the designator with the field declaration.
2856 if (!VerifyOnly)
2857 D->setFieldDecl(*Field);
2859 // Make sure that our non-designated initializer list has space
2860 // for a subobject corresponding to this field.
2861 if (StructuredList && FieldIndex >= StructuredList->getNumInits())
2862 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2864 // This designator names a flexible array member.
2865 if (Field->getType()->isIncompleteArrayType()) {
2866 bool Invalid = false;
2867 if ((DesigIdx + 1) != DIE->size()) {
2868 // We can't designate an object within the flexible array
2869 // member (because GCC doesn't allow it).
2870 if (!VerifyOnly) {
2871 DesignatedInitExpr::Designator *NextD
2872 = DIE->getDesignator(DesigIdx + 1);
2873 SemaRef.Diag(NextD->getBeginLoc(),
2874 diag::err_designator_into_flexible_array_member)
2875 << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
2876 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2877 << *Field;
2879 Invalid = true;
2882 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2883 !isa<StringLiteral>(DIE->getInit())) {
2884 // The initializer is not an initializer list.
2885 if (!VerifyOnly) {
2886 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
2887 diag::err_flexible_array_init_needs_braces)
2888 << DIE->getInit()->getSourceRange();
2889 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2890 << *Field;
2892 Invalid = true;
2895 // Check GNU flexible array initializer.
2896 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
2897 TopLevelObject))
2898 Invalid = true;
2900 if (Invalid) {
2901 ++Index;
2902 return true;
2905 // Initialize the array.
2906 bool prevHadError = hadError;
2907 unsigned newStructuredIndex = FieldIndex;
2908 unsigned OldIndex = Index;
2909 IList->setInit(Index, DIE->getInit());
2911 InitializedEntity MemberEntity =
2912 InitializedEntity::InitializeMember(*Field, &Entity);
2913 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2914 StructuredList, newStructuredIndex);
2916 IList->setInit(OldIndex, DIE);
2917 if (hadError && !prevHadError) {
2918 ++Field;
2919 ++FieldIndex;
2920 if (NextField)
2921 *NextField = Field;
2922 StructuredIndex = FieldIndex;
2923 return true;
2925 } else {
2926 // Recurse to check later designated subobjects.
2927 QualType FieldType = Field->getType();
2928 unsigned newStructuredIndex = FieldIndex;
2930 InitializedEntity MemberEntity =
2931 InitializedEntity::InitializeMember(*Field, &Entity);
2932 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
2933 FieldType, nullptr, nullptr, Index,
2934 StructuredList, newStructuredIndex,
2935 FinishSubobjectInit, false))
2936 return true;
2939 // Find the position of the next field to be initialized in this
2940 // subobject.
2941 ++Field;
2942 ++FieldIndex;
2944 // If this the first designator, our caller will continue checking
2945 // the rest of this struct/class/union subobject.
2946 if (IsFirstDesignator) {
2947 if (Field != RD->field_end() && Field->isUnnamedBitfield())
2948 ++Field;
2950 if (NextField)
2951 *NextField = Field;
2953 StructuredIndex = FieldIndex;
2954 return false;
2957 if (!FinishSubobjectInit)
2958 return false;
2960 // We've already initialized something in the union; we're done.
2961 if (RD->isUnion())
2962 return hadError;
2964 // Check the remaining fields within this class/struct/union subobject.
2965 bool prevHadError = hadError;
2967 auto NoBases =
2968 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
2969 CXXRecordDecl::base_class_iterator());
2970 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
2971 false, Index, StructuredList, FieldIndex);
2972 return hadError && !prevHadError;
2975 // C99 6.7.8p6:
2977 // If a designator has the form
2979 // [ constant-expression ]
2981 // then the current object (defined below) shall have array
2982 // type and the expression shall be an integer constant
2983 // expression. If the array is of unknown size, any
2984 // nonnegative value is valid.
2986 // Additionally, cope with the GNU extension that permits
2987 // designators of the form
2989 // [ constant-expression ... constant-expression ]
2990 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
2991 if (!AT) {
2992 if (!VerifyOnly)
2993 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2994 << CurrentObjectType;
2995 ++Index;
2996 return true;
2999 Expr *IndexExpr = nullptr;
3000 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
3001 if (D->isArrayDesignator()) {
3002 IndexExpr = DIE->getArrayIndex(*D);
3003 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
3004 DesignatedEndIndex = DesignatedStartIndex;
3005 } else {
3006 assert(D->isArrayRangeDesignator() && "Need array-range designator");
3008 DesignatedStartIndex =
3009 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
3010 DesignatedEndIndex =
3011 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
3012 IndexExpr = DIE->getArrayRangeEnd(*D);
3014 // Codegen can't handle evaluating array range designators that have side
3015 // effects, because we replicate the AST value for each initialized element.
3016 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
3017 // elements with something that has a side effect, so codegen can emit an
3018 // "error unsupported" error instead of miscompiling the app.
3019 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
3020 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
3021 FullyStructuredList->sawArrayRangeDesignator();
3024 if (isa<ConstantArrayType>(AT)) {
3025 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
3026 DesignatedStartIndex
3027 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
3028 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
3029 DesignatedEndIndex
3030 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
3031 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
3032 if (DesignatedEndIndex >= MaxElements) {
3033 if (!VerifyOnly)
3034 SemaRef.Diag(IndexExpr->getBeginLoc(),
3035 diag::err_array_designator_too_large)
3036 << toString(DesignatedEndIndex, 10) << toString(MaxElements, 10)
3037 << IndexExpr->getSourceRange();
3038 ++Index;
3039 return true;
3041 } else {
3042 unsigned DesignatedIndexBitWidth =
3043 ConstantArrayType::getMaxSizeBits(SemaRef.Context);
3044 DesignatedStartIndex =
3045 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
3046 DesignatedEndIndex =
3047 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
3048 DesignatedStartIndex.setIsUnsigned(true);
3049 DesignatedEndIndex.setIsUnsigned(true);
3052 bool IsStringLiteralInitUpdate =
3053 StructuredList && StructuredList->isStringLiteralInit();
3054 if (IsStringLiteralInitUpdate && VerifyOnly) {
3055 // We're just verifying an update to a string literal init. We don't need
3056 // to split the string up into individual characters to do that.
3057 StructuredList = nullptr;
3058 } else if (IsStringLiteralInitUpdate) {
3059 // We're modifying a string literal init; we have to decompose the string
3060 // so we can modify the individual characters.
3061 ASTContext &Context = SemaRef.Context;
3062 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParenImpCasts();
3064 // Compute the character type
3065 QualType CharTy = AT->getElementType();
3067 // Compute the type of the integer literals.
3068 QualType PromotedCharTy = CharTy;
3069 if (Context.isPromotableIntegerType(CharTy))
3070 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
3071 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
3073 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
3074 // Get the length of the string.
3075 uint64_t StrLen = SL->getLength();
3076 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
3077 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
3078 StructuredList->resizeInits(Context, StrLen);
3080 // Build a literal for each character in the string, and put them into
3081 // the init list.
3082 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3083 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
3084 Expr *Init = new (Context) IntegerLiteral(
3085 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3086 if (CharTy != PromotedCharTy)
3087 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3088 Init, nullptr, VK_PRValue,
3089 FPOptionsOverride());
3090 StructuredList->updateInit(Context, i, Init);
3092 } else {
3093 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
3094 std::string Str;
3095 Context.getObjCEncodingForType(E->getEncodedType(), Str);
3097 // Get the length of the string.
3098 uint64_t StrLen = Str.size();
3099 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
3100 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
3101 StructuredList->resizeInits(Context, StrLen);
3103 // Build a literal for each character in the string, and put them into
3104 // the init list.
3105 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3106 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
3107 Expr *Init = new (Context) IntegerLiteral(
3108 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3109 if (CharTy != PromotedCharTy)
3110 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3111 Init, nullptr, VK_PRValue,
3112 FPOptionsOverride());
3113 StructuredList->updateInit(Context, i, Init);
3118 // Make sure that our non-designated initializer list has space
3119 // for a subobject corresponding to this array element.
3120 if (StructuredList &&
3121 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
3122 StructuredList->resizeInits(SemaRef.Context,
3123 DesignatedEndIndex.getZExtValue() + 1);
3125 // Repeatedly perform subobject initializations in the range
3126 // [DesignatedStartIndex, DesignatedEndIndex].
3128 // Move to the next designator
3129 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
3130 unsigned OldIndex = Index;
3132 InitializedEntity ElementEntity =
3133 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
3135 while (DesignatedStartIndex <= DesignatedEndIndex) {
3136 // Recurse to check later designated subobjects.
3137 QualType ElementType = AT->getElementType();
3138 Index = OldIndex;
3140 ElementEntity.setElementIndex(ElementIndex);
3141 if (CheckDesignatedInitializer(
3142 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
3143 nullptr, Index, StructuredList, ElementIndex,
3144 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
3145 false))
3146 return true;
3148 // Move to the next index in the array that we'll be initializing.
3149 ++DesignatedStartIndex;
3150 ElementIndex = DesignatedStartIndex.getZExtValue();
3153 // If this the first designator, our caller will continue checking
3154 // the rest of this array subobject.
3155 if (IsFirstDesignator) {
3156 if (NextElementIndex)
3157 *NextElementIndex = DesignatedStartIndex;
3158 StructuredIndex = ElementIndex;
3159 return false;
3162 if (!FinishSubobjectInit)
3163 return false;
3165 // Check the remaining elements within this array subobject.
3166 bool prevHadError = hadError;
3167 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
3168 /*SubobjectIsDesignatorContext=*/false, Index,
3169 StructuredList, ElementIndex);
3170 return hadError && !prevHadError;
3173 // Get the structured initializer list for a subobject of type
3174 // @p CurrentObjectType.
3175 InitListExpr *
3176 InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
3177 QualType CurrentObjectType,
3178 InitListExpr *StructuredList,
3179 unsigned StructuredIndex,
3180 SourceRange InitRange,
3181 bool IsFullyOverwritten) {
3182 if (!StructuredList)
3183 return nullptr;
3185 Expr *ExistingInit = nullptr;
3186 if (StructuredIndex < StructuredList->getNumInits())
3187 ExistingInit = StructuredList->getInit(StructuredIndex);
3189 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
3190 // There might have already been initializers for subobjects of the current
3191 // object, but a subsequent initializer list will overwrite the entirety
3192 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
3194 // struct P { char x[6]; };
3195 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
3197 // The first designated initializer is ignored, and l.x is just "f".
3198 if (!IsFullyOverwritten)
3199 return Result;
3201 if (ExistingInit) {
3202 // We are creating an initializer list that initializes the
3203 // subobjects of the current object, but there was already an
3204 // initialization that completely initialized the current
3205 // subobject:
3207 // struct X { int a, b; };
3208 // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 };
3210 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
3211 // designated initializer overwrites the [0].b initializer
3212 // from the prior initialization.
3214 // When the existing initializer is an expression rather than an
3215 // initializer list, we cannot decompose and update it in this way.
3216 // For example:
3218 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
3220 // This case is handled by CheckDesignatedInitializer.
3221 diagnoseInitOverride(ExistingInit, InitRange);
3224 unsigned ExpectedNumInits = 0;
3225 if (Index < IList->getNumInits()) {
3226 if (auto *Init = dyn_cast_or_null<InitListExpr>(IList->getInit(Index)))
3227 ExpectedNumInits = Init->getNumInits();
3228 else
3229 ExpectedNumInits = IList->getNumInits() - Index;
3232 InitListExpr *Result =
3233 createInitListExpr(CurrentObjectType, InitRange, ExpectedNumInits);
3235 // Link this new initializer list into the structured initializer
3236 // lists.
3237 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
3238 return Result;
3241 InitListExpr *
3242 InitListChecker::createInitListExpr(QualType CurrentObjectType,
3243 SourceRange InitRange,
3244 unsigned ExpectedNumInits) {
3245 InitListExpr *Result = new (SemaRef.Context) InitListExpr(
3246 SemaRef.Context, InitRange.getBegin(), std::nullopt, InitRange.getEnd());
3248 QualType ResultType = CurrentObjectType;
3249 if (!ResultType->isArrayType())
3250 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
3251 Result->setType(ResultType);
3253 // Pre-allocate storage for the structured initializer list.
3254 unsigned NumElements = 0;
3256 if (const ArrayType *AType
3257 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
3258 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
3259 NumElements = CAType->getSize().getZExtValue();
3260 // Simple heuristic so that we don't allocate a very large
3261 // initializer with many empty entries at the end.
3262 if (NumElements > ExpectedNumInits)
3263 NumElements = 0;
3265 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) {
3266 NumElements = VType->getNumElements();
3267 } else if (CurrentObjectType->isRecordType()) {
3268 NumElements = numStructUnionElements(CurrentObjectType);
3269 } else if (CurrentObjectType->isDependentType()) {
3270 NumElements = 1;
3273 Result->reserveInits(SemaRef.Context, NumElements);
3275 return Result;
3278 /// Update the initializer at index @p StructuredIndex within the
3279 /// structured initializer list to the value @p expr.
3280 void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
3281 unsigned &StructuredIndex,
3282 Expr *expr) {
3283 // No structured initializer list to update
3284 if (!StructuredList)
3285 return;
3287 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
3288 StructuredIndex, expr)) {
3289 // This initializer overwrites a previous initializer.
3290 // No need to diagnose when `expr` is nullptr because a more relevant
3291 // diagnostic has already been issued and this diagnostic is potentially
3292 // noise.
3293 if (expr)
3294 diagnoseInitOverride(PrevInit, expr->getSourceRange());
3297 ++StructuredIndex;
3300 /// Determine whether we can perform aggregate initialization for the purposes
3301 /// of overload resolution.
3302 bool Sema::CanPerformAggregateInitializationForOverloadResolution(
3303 const InitializedEntity &Entity, InitListExpr *From) {
3304 QualType Type = Entity.getType();
3305 InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true,
3306 /*TreatUnavailableAsInvalid=*/false,
3307 /*InOverloadResolution=*/true);
3308 return !Check.HadError();
3311 /// Check that the given Index expression is a valid array designator
3312 /// value. This is essentially just a wrapper around
3313 /// VerifyIntegerConstantExpression that also checks for negative values
3314 /// and produces a reasonable diagnostic if there is a
3315 /// failure. Returns the index expression, possibly with an implicit cast
3316 /// added, on success. If everything went okay, Value will receive the
3317 /// value of the constant expression.
3318 static ExprResult
3319 CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
3320 SourceLocation Loc = Index->getBeginLoc();
3322 // Make sure this is an integer constant expression.
3323 ExprResult Result =
3324 S.VerifyIntegerConstantExpression(Index, &Value, Sema::AllowFold);
3325 if (Result.isInvalid())
3326 return Result;
3328 if (Value.isSigned() && Value.isNegative())
3329 return S.Diag(Loc, diag::err_array_designator_negative)
3330 << toString(Value, 10) << Index->getSourceRange();
3332 Value.setIsUnsigned(true);
3333 return Result;
3336 ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
3337 SourceLocation EqualOrColonLoc,
3338 bool GNUSyntax,
3339 ExprResult Init) {
3340 typedef DesignatedInitExpr::Designator ASTDesignator;
3342 bool Invalid = false;
3343 SmallVector<ASTDesignator, 32> Designators;
3344 SmallVector<Expr *, 32> InitExpressions;
3346 // Build designators and check array designator expressions.
3347 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
3348 const Designator &D = Desig.getDesignator(Idx);
3350 if (D.isFieldDesignator()) {
3351 Designators.push_back(ASTDesignator::CreateFieldDesignator(
3352 D.getFieldDecl(), D.getDotLoc(), D.getFieldLoc()));
3353 } else if (D.isArrayDesignator()) {
3354 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
3355 llvm::APSInt IndexValue;
3356 if (!Index->isTypeDependent() && !Index->isValueDependent())
3357 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
3358 if (!Index)
3359 Invalid = true;
3360 else {
3361 Designators.push_back(ASTDesignator::CreateArrayDesignator(
3362 InitExpressions.size(), D.getLBracketLoc(), D.getRBracketLoc()));
3363 InitExpressions.push_back(Index);
3365 } else if (D.isArrayRangeDesignator()) {
3366 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
3367 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
3368 llvm::APSInt StartValue;
3369 llvm::APSInt EndValue;
3370 bool StartDependent = StartIndex->isTypeDependent() ||
3371 StartIndex->isValueDependent();
3372 bool EndDependent = EndIndex->isTypeDependent() ||
3373 EndIndex->isValueDependent();
3374 if (!StartDependent)
3375 StartIndex =
3376 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
3377 if (!EndDependent)
3378 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
3380 if (!StartIndex || !EndIndex)
3381 Invalid = true;
3382 else {
3383 // Make sure we're comparing values with the same bit width.
3384 if (StartDependent || EndDependent) {
3385 // Nothing to compute.
3386 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
3387 EndValue = EndValue.extend(StartValue.getBitWidth());
3388 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
3389 StartValue = StartValue.extend(EndValue.getBitWidth());
3391 if (!StartDependent && !EndDependent && EndValue < StartValue) {
3392 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
3393 << toString(StartValue, 10) << toString(EndValue, 10)
3394 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
3395 Invalid = true;
3396 } else {
3397 Designators.push_back(ASTDesignator::CreateArrayRangeDesignator(
3398 InitExpressions.size(), D.getLBracketLoc(), D.getEllipsisLoc(),
3399 D.getRBracketLoc()));
3400 InitExpressions.push_back(StartIndex);
3401 InitExpressions.push_back(EndIndex);
3407 if (Invalid || Init.isInvalid())
3408 return ExprError();
3410 return DesignatedInitExpr::Create(Context, Designators, InitExpressions,
3411 EqualOrColonLoc, GNUSyntax,
3412 Init.getAs<Expr>());
3415 //===----------------------------------------------------------------------===//
3416 // Initialization entity
3417 //===----------------------------------------------------------------------===//
3419 InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
3420 const InitializedEntity &Parent)
3421 : Parent(&Parent), Index(Index)
3423 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
3424 Kind = EK_ArrayElement;
3425 Type = AT->getElementType();
3426 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
3427 Kind = EK_VectorElement;
3428 Type = VT->getElementType();
3429 } else {
3430 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
3431 assert(CT && "Unexpected type");
3432 Kind = EK_ComplexElement;
3433 Type = CT->getElementType();
3437 InitializedEntity
3438 InitializedEntity::InitializeBase(ASTContext &Context,
3439 const CXXBaseSpecifier *Base,
3440 bool IsInheritedVirtualBase,
3441 const InitializedEntity *Parent) {
3442 InitializedEntity Result;
3443 Result.Kind = EK_Base;
3444 Result.Parent = Parent;
3445 Result.Base = {Base, IsInheritedVirtualBase};
3446 Result.Type = Base->getType();
3447 return Result;
3450 DeclarationName InitializedEntity::getName() const {
3451 switch (getKind()) {
3452 case EK_Parameter:
3453 case EK_Parameter_CF_Audited: {
3454 ParmVarDecl *D = Parameter.getPointer();
3455 return (D ? D->getDeclName() : DeclarationName());
3458 case EK_Variable:
3459 case EK_Member:
3460 case EK_ParenAggInitMember:
3461 case EK_Binding:
3462 case EK_TemplateParameter:
3463 return Variable.VariableOrMember->getDeclName();
3465 case EK_LambdaCapture:
3466 return DeclarationName(Capture.VarID);
3468 case EK_Result:
3469 case EK_StmtExprResult:
3470 case EK_Exception:
3471 case EK_New:
3472 case EK_Temporary:
3473 case EK_Base:
3474 case EK_Delegating:
3475 case EK_ArrayElement:
3476 case EK_VectorElement:
3477 case EK_ComplexElement:
3478 case EK_BlockElement:
3479 case EK_LambdaToBlockConversionBlockElement:
3480 case EK_CompoundLiteralInit:
3481 case EK_RelatedResult:
3482 return DeclarationName();
3485 llvm_unreachable("Invalid EntityKind!");
3488 ValueDecl *InitializedEntity::getDecl() const {
3489 switch (getKind()) {
3490 case EK_Variable:
3491 case EK_Member:
3492 case EK_ParenAggInitMember:
3493 case EK_Binding:
3494 case EK_TemplateParameter:
3495 return Variable.VariableOrMember;
3497 case EK_Parameter:
3498 case EK_Parameter_CF_Audited:
3499 return Parameter.getPointer();
3501 case EK_Result:
3502 case EK_StmtExprResult:
3503 case EK_Exception:
3504 case EK_New:
3505 case EK_Temporary:
3506 case EK_Base:
3507 case EK_Delegating:
3508 case EK_ArrayElement:
3509 case EK_VectorElement:
3510 case EK_ComplexElement:
3511 case EK_BlockElement:
3512 case EK_LambdaToBlockConversionBlockElement:
3513 case EK_LambdaCapture:
3514 case EK_CompoundLiteralInit:
3515 case EK_RelatedResult:
3516 return nullptr;
3519 llvm_unreachable("Invalid EntityKind!");
3522 bool InitializedEntity::allowsNRVO() const {
3523 switch (getKind()) {
3524 case EK_Result:
3525 case EK_Exception:
3526 return LocAndNRVO.NRVO;
3528 case EK_StmtExprResult:
3529 case EK_Variable:
3530 case EK_Parameter:
3531 case EK_Parameter_CF_Audited:
3532 case EK_TemplateParameter:
3533 case EK_Member:
3534 case EK_ParenAggInitMember:
3535 case EK_Binding:
3536 case EK_New:
3537 case EK_Temporary:
3538 case EK_CompoundLiteralInit:
3539 case EK_Base:
3540 case EK_Delegating:
3541 case EK_ArrayElement:
3542 case EK_VectorElement:
3543 case EK_ComplexElement:
3544 case EK_BlockElement:
3545 case EK_LambdaToBlockConversionBlockElement:
3546 case EK_LambdaCapture:
3547 case EK_RelatedResult:
3548 break;
3551 return false;
3554 unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
3555 assert(getParent() != this);
3556 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3557 for (unsigned I = 0; I != Depth; ++I)
3558 OS << "`-";
3560 switch (getKind()) {
3561 case EK_Variable: OS << "Variable"; break;
3562 case EK_Parameter: OS << "Parameter"; break;
3563 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3564 break;
3565 case EK_TemplateParameter: OS << "TemplateParameter"; break;
3566 case EK_Result: OS << "Result"; break;
3567 case EK_StmtExprResult: OS << "StmtExprResult"; break;
3568 case EK_Exception: OS << "Exception"; break;
3569 case EK_Member:
3570 case EK_ParenAggInitMember:
3571 OS << "Member";
3572 break;
3573 case EK_Binding: OS << "Binding"; break;
3574 case EK_New: OS << "New"; break;
3575 case EK_Temporary: OS << "Temporary"; break;
3576 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
3577 case EK_RelatedResult: OS << "RelatedResult"; break;
3578 case EK_Base: OS << "Base"; break;
3579 case EK_Delegating: OS << "Delegating"; break;
3580 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3581 case EK_VectorElement: OS << "VectorElement " << Index; break;
3582 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3583 case EK_BlockElement: OS << "Block"; break;
3584 case EK_LambdaToBlockConversionBlockElement:
3585 OS << "Block (lambda)";
3586 break;
3587 case EK_LambdaCapture:
3588 OS << "LambdaCapture ";
3589 OS << DeclarationName(Capture.VarID);
3590 break;
3593 if (auto *D = getDecl()) {
3594 OS << " ";
3595 D->printQualifiedName(OS);
3598 OS << " '" << getType() << "'\n";
3600 return Depth + 1;
3603 LLVM_DUMP_METHOD void InitializedEntity::dump() const {
3604 dumpImpl(llvm::errs());
3607 //===----------------------------------------------------------------------===//
3608 // Initialization sequence
3609 //===----------------------------------------------------------------------===//
3611 void InitializationSequence::Step::Destroy() {
3612 switch (Kind) {
3613 case SK_ResolveAddressOfOverloadedFunction:
3614 case SK_CastDerivedToBasePRValue:
3615 case SK_CastDerivedToBaseXValue:
3616 case SK_CastDerivedToBaseLValue:
3617 case SK_BindReference:
3618 case SK_BindReferenceToTemporary:
3619 case SK_FinalCopy:
3620 case SK_ExtraneousCopyToTemporary:
3621 case SK_UserConversion:
3622 case SK_QualificationConversionPRValue:
3623 case SK_QualificationConversionXValue:
3624 case SK_QualificationConversionLValue:
3625 case SK_FunctionReferenceConversion:
3626 case SK_AtomicConversion:
3627 case SK_ListInitialization:
3628 case SK_UnwrapInitList:
3629 case SK_RewrapInitList:
3630 case SK_ConstructorInitialization:
3631 case SK_ConstructorInitializationFromList:
3632 case SK_ZeroInitialization:
3633 case SK_CAssignment:
3634 case SK_StringInit:
3635 case SK_ObjCObjectConversion:
3636 case SK_ArrayLoopIndex:
3637 case SK_ArrayLoopInit:
3638 case SK_ArrayInit:
3639 case SK_GNUArrayInit:
3640 case SK_ParenthesizedArrayInit:
3641 case SK_PassByIndirectCopyRestore:
3642 case SK_PassByIndirectRestore:
3643 case SK_ProduceObjCObject:
3644 case SK_StdInitializerList:
3645 case SK_StdInitializerListConstructorCall:
3646 case SK_OCLSamplerInit:
3647 case SK_OCLZeroOpaqueType:
3648 case SK_ParenthesizedListInit:
3649 break;
3651 case SK_ConversionSequence:
3652 case SK_ConversionSequenceNoNarrowing:
3653 delete ICS;
3657 bool InitializationSequence::isDirectReferenceBinding() const {
3658 // There can be some lvalue adjustments after the SK_BindReference step.
3659 for (const Step &S : llvm::reverse(Steps)) {
3660 if (S.Kind == SK_BindReference)
3661 return true;
3662 if (S.Kind == SK_BindReferenceToTemporary)
3663 return false;
3665 return false;
3668 bool InitializationSequence::isAmbiguous() const {
3669 if (!Failed())
3670 return false;
3672 switch (getFailureKind()) {
3673 case FK_TooManyInitsForReference:
3674 case FK_ParenthesizedListInitForReference:
3675 case FK_ArrayNeedsInitList:
3676 case FK_ArrayNeedsInitListOrStringLiteral:
3677 case FK_ArrayNeedsInitListOrWideStringLiteral:
3678 case FK_NarrowStringIntoWideCharArray:
3679 case FK_WideStringIntoCharArray:
3680 case FK_IncompatWideStringIntoWideChar:
3681 case FK_PlainStringIntoUTF8Char:
3682 case FK_UTF8StringIntoPlainChar:
3683 case FK_AddressOfOverloadFailed: // FIXME: Could do better
3684 case FK_NonConstLValueReferenceBindingToTemporary:
3685 case FK_NonConstLValueReferenceBindingToBitfield:
3686 case FK_NonConstLValueReferenceBindingToVectorElement:
3687 case FK_NonConstLValueReferenceBindingToMatrixElement:
3688 case FK_NonConstLValueReferenceBindingToUnrelated:
3689 case FK_RValueReferenceBindingToLValue:
3690 case FK_ReferenceAddrspaceMismatchTemporary:
3691 case FK_ReferenceInitDropsQualifiers:
3692 case FK_ReferenceInitFailed:
3693 case FK_ConversionFailed:
3694 case FK_ConversionFromPropertyFailed:
3695 case FK_TooManyInitsForScalar:
3696 case FK_ParenthesizedListInitForScalar:
3697 case FK_ReferenceBindingToInitList:
3698 case FK_InitListBadDestinationType:
3699 case FK_DefaultInitOfConst:
3700 case FK_Incomplete:
3701 case FK_ArrayTypeMismatch:
3702 case FK_NonConstantArrayInit:
3703 case FK_ListInitializationFailed:
3704 case FK_VariableLengthArrayHasInitializer:
3705 case FK_PlaceholderType:
3706 case FK_ExplicitConstructor:
3707 case FK_AddressOfUnaddressableFunction:
3708 case FK_ParenthesizedListInitFailed:
3709 case FK_DesignatedInitForNonAggregate:
3710 return false;
3712 case FK_ReferenceInitOverloadFailed:
3713 case FK_UserConversionOverloadFailed:
3714 case FK_ConstructorOverloadFailed:
3715 case FK_ListConstructorOverloadFailed:
3716 return FailedOverloadResult == OR_Ambiguous;
3719 llvm_unreachable("Invalid EntityKind!");
3722 bool InitializationSequence::isConstructorInitialization() const {
3723 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3726 void
3727 InitializationSequence
3728 ::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3729 DeclAccessPair Found,
3730 bool HadMultipleCandidates) {
3731 Step S;
3732 S.Kind = SK_ResolveAddressOfOverloadedFunction;
3733 S.Type = Function->getType();
3734 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3735 S.Function.Function = Function;
3736 S.Function.FoundDecl = Found;
3737 Steps.push_back(S);
3740 void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
3741 ExprValueKind VK) {
3742 Step S;
3743 switch (VK) {
3744 case VK_PRValue:
3745 S.Kind = SK_CastDerivedToBasePRValue;
3746 break;
3747 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3748 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
3750 S.Type = BaseType;
3751 Steps.push_back(S);
3754 void InitializationSequence::AddReferenceBindingStep(QualType T,
3755 bool BindingTemporary) {
3756 Step S;
3757 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3758 S.Type = T;
3759 Steps.push_back(S);
3762 void InitializationSequence::AddFinalCopy(QualType T) {
3763 Step S;
3764 S.Kind = SK_FinalCopy;
3765 S.Type = T;
3766 Steps.push_back(S);
3769 void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
3770 Step S;
3771 S.Kind = SK_ExtraneousCopyToTemporary;
3772 S.Type = T;
3773 Steps.push_back(S);
3776 void
3777 InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
3778 DeclAccessPair FoundDecl,
3779 QualType T,
3780 bool HadMultipleCandidates) {
3781 Step S;
3782 S.Kind = SK_UserConversion;
3783 S.Type = T;
3784 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3785 S.Function.Function = Function;
3786 S.Function.FoundDecl = FoundDecl;
3787 Steps.push_back(S);
3790 void InitializationSequence::AddQualificationConversionStep(QualType Ty,
3791 ExprValueKind VK) {
3792 Step S;
3793 S.Kind = SK_QualificationConversionPRValue; // work around a gcc warning
3794 switch (VK) {
3795 case VK_PRValue:
3796 S.Kind = SK_QualificationConversionPRValue;
3797 break;
3798 case VK_XValue:
3799 S.Kind = SK_QualificationConversionXValue;
3800 break;
3801 case VK_LValue:
3802 S.Kind = SK_QualificationConversionLValue;
3803 break;
3805 S.Type = Ty;
3806 Steps.push_back(S);
3809 void InitializationSequence::AddFunctionReferenceConversionStep(QualType Ty) {
3810 Step S;
3811 S.Kind = SK_FunctionReferenceConversion;
3812 S.Type = Ty;
3813 Steps.push_back(S);
3816 void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
3817 Step S;
3818 S.Kind = SK_AtomicConversion;
3819 S.Type = Ty;
3820 Steps.push_back(S);
3823 void InitializationSequence::AddConversionSequenceStep(
3824 const ImplicitConversionSequence &ICS, QualType T,
3825 bool TopLevelOfInitList) {
3826 Step S;
3827 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3828 : SK_ConversionSequence;
3829 S.Type = T;
3830 S.ICS = new ImplicitConversionSequence(ICS);
3831 Steps.push_back(S);
3834 void InitializationSequence::AddListInitializationStep(QualType T) {
3835 Step S;
3836 S.Kind = SK_ListInitialization;
3837 S.Type = T;
3838 Steps.push_back(S);
3841 void InitializationSequence::AddConstructorInitializationStep(
3842 DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3843 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
3844 Step S;
3845 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
3846 : SK_ConstructorInitializationFromList
3847 : SK_ConstructorInitialization;
3848 S.Type = T;
3849 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3850 S.Function.Function = Constructor;
3851 S.Function.FoundDecl = FoundDecl;
3852 Steps.push_back(S);
3855 void InitializationSequence::AddZeroInitializationStep(QualType T) {
3856 Step S;
3857 S.Kind = SK_ZeroInitialization;
3858 S.Type = T;
3859 Steps.push_back(S);
3862 void InitializationSequence::AddCAssignmentStep(QualType T) {
3863 Step S;
3864 S.Kind = SK_CAssignment;
3865 S.Type = T;
3866 Steps.push_back(S);
3869 void InitializationSequence::AddStringInitStep(QualType T) {
3870 Step S;
3871 S.Kind = SK_StringInit;
3872 S.Type = T;
3873 Steps.push_back(S);
3876 void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
3877 Step S;
3878 S.Kind = SK_ObjCObjectConversion;
3879 S.Type = T;
3880 Steps.push_back(S);
3883 void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) {
3884 Step S;
3885 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
3886 S.Type = T;
3887 Steps.push_back(S);
3890 void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) {
3891 Step S;
3892 S.Kind = SK_ArrayLoopIndex;
3893 S.Type = EltT;
3894 Steps.insert(Steps.begin(), S);
3896 S.Kind = SK_ArrayLoopInit;
3897 S.Type = T;
3898 Steps.push_back(S);
3901 void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
3902 Step S;
3903 S.Kind = SK_ParenthesizedArrayInit;
3904 S.Type = T;
3905 Steps.push_back(S);
3908 void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
3909 bool shouldCopy) {
3910 Step s;
3911 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3912 : SK_PassByIndirectRestore);
3913 s.Type = type;
3914 Steps.push_back(s);
3917 void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3918 Step S;
3919 S.Kind = SK_ProduceObjCObject;
3920 S.Type = T;
3921 Steps.push_back(S);
3924 void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3925 Step S;
3926 S.Kind = SK_StdInitializerList;
3927 S.Type = T;
3928 Steps.push_back(S);
3931 void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3932 Step S;
3933 S.Kind = SK_OCLSamplerInit;
3934 S.Type = T;
3935 Steps.push_back(S);
3938 void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T) {
3939 Step S;
3940 S.Kind = SK_OCLZeroOpaqueType;
3941 S.Type = T;
3942 Steps.push_back(S);
3945 void InitializationSequence::AddParenthesizedListInitStep(QualType T) {
3946 Step S;
3947 S.Kind = SK_ParenthesizedListInit;
3948 S.Type = T;
3949 Steps.push_back(S);
3952 void InitializationSequence::RewrapReferenceInitList(QualType T,
3953 InitListExpr *Syntactic) {
3954 assert(Syntactic->getNumInits() == 1 &&
3955 "Can only rewrap trivial init lists.");
3956 Step S;
3957 S.Kind = SK_UnwrapInitList;
3958 S.Type = Syntactic->getInit(0)->getType();
3959 Steps.insert(Steps.begin(), S);
3961 S.Kind = SK_RewrapInitList;
3962 S.Type = T;
3963 S.WrappingSyntacticList = Syntactic;
3964 Steps.push_back(S);
3967 void InitializationSequence::SetOverloadFailure(FailureKind Failure,
3968 OverloadingResult Result) {
3969 setSequenceKind(FailedSequence);
3970 this->Failure = Failure;
3971 this->FailedOverloadResult = Result;
3974 //===----------------------------------------------------------------------===//
3975 // Attempt initialization
3976 //===----------------------------------------------------------------------===//
3978 /// Tries to add a zero initializer. Returns true if that worked.
3979 static bool
3980 maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
3981 const InitializedEntity &Entity) {
3982 if (Entity.getKind() != InitializedEntity::EK_Variable)
3983 return false;
3985 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
3986 if (VD->getInit() || VD->getEndLoc().isMacroID())
3987 return false;
3989 QualType VariableTy = VD->getType().getCanonicalType();
3990 SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc());
3991 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
3992 if (!Init.empty()) {
3993 Sequence.AddZeroInitializationStep(Entity.getType());
3994 Sequence.SetZeroInitializationFixit(Init, Loc);
3995 return true;
3997 return false;
4000 static void MaybeProduceObjCObject(Sema &S,
4001 InitializationSequence &Sequence,
4002 const InitializedEntity &Entity) {
4003 if (!S.getLangOpts().ObjCAutoRefCount) return;
4005 /// When initializing a parameter, produce the value if it's marked
4006 /// __attribute__((ns_consumed)).
4007 if (Entity.isParameterKind()) {
4008 if (!Entity.isParameterConsumed())
4009 return;
4011 assert(Entity.getType()->isObjCRetainableType() &&
4012 "consuming an object of unretainable type?");
4013 Sequence.AddProduceObjCObjectStep(Entity.getType());
4015 /// When initializing a return value, if the return type is a
4016 /// retainable type, then returns need to immediately retain the
4017 /// object. If an autorelease is required, it will be done at the
4018 /// last instant.
4019 } else if (Entity.getKind() == InitializedEntity::EK_Result ||
4020 Entity.getKind() == InitializedEntity::EK_StmtExprResult) {
4021 if (!Entity.getType()->isObjCRetainableType())
4022 return;
4024 Sequence.AddProduceObjCObjectStep(Entity.getType());
4028 static void TryListInitialization(Sema &S,
4029 const InitializedEntity &Entity,
4030 const InitializationKind &Kind,
4031 InitListExpr *InitList,
4032 InitializationSequence &Sequence,
4033 bool TreatUnavailableAsInvalid);
4035 /// When initializing from init list via constructor, handle
4036 /// initialization of an object of type std::initializer_list<T>.
4038 /// \return true if we have handled initialization of an object of type
4039 /// std::initializer_list<T>, false otherwise.
4040 static bool TryInitializerListConstruction(Sema &S,
4041 InitListExpr *List,
4042 QualType DestType,
4043 InitializationSequence &Sequence,
4044 bool TreatUnavailableAsInvalid) {
4045 QualType E;
4046 if (!S.isStdInitializerList(DestType, &E))
4047 return false;
4049 if (!S.isCompleteType(List->getExprLoc(), E)) {
4050 Sequence.setIncompleteTypeFailure(E);
4051 return true;
4054 // Try initializing a temporary array from the init list.
4055 QualType ArrayType = S.Context.getConstantArrayType(
4056 E.withConst(),
4057 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
4058 List->getNumInits()),
4059 nullptr, clang::ArraySizeModifier::Normal, 0);
4060 InitializedEntity HiddenArray =
4061 InitializedEntity::InitializeTemporary(ArrayType);
4062 InitializationKind Kind = InitializationKind::CreateDirectList(
4063 List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
4064 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
4065 TreatUnavailableAsInvalid);
4066 if (Sequence)
4067 Sequence.AddStdInitializerListConstructionStep(DestType);
4068 return true;
4071 /// Determine if the constructor has the signature of a copy or move
4072 /// constructor for the type T of the class in which it was found. That is,
4073 /// determine if its first parameter is of type T or reference to (possibly
4074 /// cv-qualified) T.
4075 static bool hasCopyOrMoveCtorParam(ASTContext &Ctx,
4076 const ConstructorInfo &Info) {
4077 if (Info.Constructor->getNumParams() == 0)
4078 return false;
4080 QualType ParmT =
4081 Info.Constructor->getParamDecl(0)->getType().getNonReferenceType();
4082 QualType ClassT =
4083 Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
4085 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
4088 static OverloadingResult ResolveConstructorOverload(
4089 Sema &S, SourceLocation DeclLoc, MultiExprArg Args,
4090 OverloadCandidateSet &CandidateSet, QualType DestType,
4091 DeclContext::lookup_result Ctors, OverloadCandidateSet::iterator &Best,
4092 bool CopyInitializing, bool AllowExplicit, bool OnlyListConstructors,
4093 bool IsListInit, bool RequireActualConstructor,
4094 bool SecondStepOfCopyInit = false) {
4095 CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor);
4096 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
4098 for (NamedDecl *D : Ctors) {
4099 auto Info = getConstructorInfo(D);
4100 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
4101 continue;
4103 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
4104 continue;
4106 // C++11 [over.best.ics]p4:
4107 // ... and the constructor or user-defined conversion function is a
4108 // candidate by
4109 // - 13.3.1.3, when the argument is the temporary in the second step
4110 // of a class copy-initialization, or
4111 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
4112 // - the second phase of 13.3.1.7 when the initializer list has exactly
4113 // one element that is itself an initializer list, and the target is
4114 // the first parameter of a constructor of class X, and the conversion
4115 // is to X or reference to (possibly cv-qualified X),
4116 // user-defined conversion sequences are not considered.
4117 bool SuppressUserConversions =
4118 SecondStepOfCopyInit ||
4119 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
4120 hasCopyOrMoveCtorParam(S.Context, Info));
4122 if (Info.ConstructorTmpl)
4123 S.AddTemplateOverloadCandidate(
4124 Info.ConstructorTmpl, Info.FoundDecl,
4125 /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions,
4126 /*PartialOverloading=*/false, AllowExplicit);
4127 else {
4128 // C++ [over.match.copy]p1:
4129 // - When initializing a temporary to be bound to the first parameter
4130 // of a constructor [for type T] that takes a reference to possibly
4131 // cv-qualified T as its first argument, called with a single
4132 // argument in the context of direct-initialization, explicit
4133 // conversion functions are also considered.
4134 // FIXME: What if a constructor template instantiates to such a signature?
4135 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
4136 Args.size() == 1 &&
4137 hasCopyOrMoveCtorParam(S.Context, Info);
4138 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
4139 CandidateSet, SuppressUserConversions,
4140 /*PartialOverloading=*/false, AllowExplicit,
4141 AllowExplicitConv);
4145 // FIXME: Work around a bug in C++17 guaranteed copy elision.
4147 // When initializing an object of class type T by constructor
4148 // ([over.match.ctor]) or by list-initialization ([over.match.list])
4149 // from a single expression of class type U, conversion functions of
4150 // U that convert to the non-reference type cv T are candidates.
4151 // Explicit conversion functions are only candidates during
4152 // direct-initialization.
4154 // Note: SecondStepOfCopyInit is only ever true in this case when
4155 // evaluating whether to produce a C++98 compatibility warning.
4156 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
4157 !RequireActualConstructor && !SecondStepOfCopyInit) {
4158 Expr *Initializer = Args[0];
4159 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
4160 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
4161 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
4162 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4163 NamedDecl *D = *I;
4164 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4165 D = D->getUnderlyingDecl();
4167 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4168 CXXConversionDecl *Conv;
4169 if (ConvTemplate)
4170 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4171 else
4172 Conv = cast<CXXConversionDecl>(D);
4174 if (ConvTemplate)
4175 S.AddTemplateConversionCandidate(
4176 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4177 CandidateSet, AllowExplicit, AllowExplicit,
4178 /*AllowResultConversion*/ false);
4179 else
4180 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
4181 DestType, CandidateSet, AllowExplicit,
4182 AllowExplicit,
4183 /*AllowResultConversion*/ false);
4188 // Perform overload resolution and return the result.
4189 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
4192 /// Attempt initialization by constructor (C++ [dcl.init]), which
4193 /// enumerates the constructors of the initialized entity and performs overload
4194 /// resolution to select the best.
4195 /// \param DestType The destination class type.
4196 /// \param DestArrayType The destination type, which is either DestType or
4197 /// a (possibly multidimensional) array of DestType.
4198 /// \param IsListInit Is this list-initialization?
4199 /// \param IsInitListCopy Is this non-list-initialization resulting from a
4200 /// list-initialization from {x} where x is the same
4201 /// type as the entity?
4202 static void TryConstructorInitialization(Sema &S,
4203 const InitializedEntity &Entity,
4204 const InitializationKind &Kind,
4205 MultiExprArg Args, QualType DestType,
4206 QualType DestArrayType,
4207 InitializationSequence &Sequence,
4208 bool IsListInit = false,
4209 bool IsInitListCopy = false) {
4210 assert(((!IsListInit && !IsInitListCopy) ||
4211 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
4212 "IsListInit/IsInitListCopy must come with a single initializer list "
4213 "argument.");
4214 InitListExpr *ILE =
4215 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
4216 MultiExprArg UnwrappedArgs =
4217 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
4219 // The type we're constructing needs to be complete.
4220 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
4221 Sequence.setIncompleteTypeFailure(DestType);
4222 return;
4225 bool RequireActualConstructor =
4226 !(Entity.getKind() != InitializedEntity::EK_Base &&
4227 Entity.getKind() != InitializedEntity::EK_Delegating &&
4228 Entity.getKind() !=
4229 InitializedEntity::EK_LambdaToBlockConversionBlockElement);
4231 // C++17 [dcl.init]p17:
4232 // - If the initializer expression is a prvalue and the cv-unqualified
4233 // version of the source type is the same class as the class of the
4234 // destination, the initializer expression is used to initialize the
4235 // destination object.
4236 // Per DR (no number yet), this does not apply when initializing a base
4237 // class or delegating to another constructor from a mem-initializer.
4238 // ObjC++: Lambda captured by the block in the lambda to block conversion
4239 // should avoid copy elision.
4240 if (S.getLangOpts().CPlusPlus17 && !RequireActualConstructor &&
4241 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() &&
4242 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
4243 // Convert qualifications if necessary.
4244 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4245 if (ILE)
4246 Sequence.RewrapReferenceInitList(DestType, ILE);
4247 return;
4250 const RecordType *DestRecordType = DestType->getAs<RecordType>();
4251 assert(DestRecordType && "Constructor initialization requires record type");
4252 CXXRecordDecl *DestRecordDecl
4253 = cast<CXXRecordDecl>(DestRecordType->getDecl());
4255 // Build the candidate set directly in the initialization sequence
4256 // structure, so that it will persist if we fail.
4257 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4259 // Determine whether we are allowed to call explicit constructors or
4260 // explicit conversion operators.
4261 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
4262 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
4264 // - Otherwise, if T is a class type, constructors are considered. The
4265 // applicable constructors are enumerated, and the best one is chosen
4266 // through overload resolution.
4267 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
4269 OverloadingResult Result = OR_No_Viable_Function;
4270 OverloadCandidateSet::iterator Best;
4271 bool AsInitializerList = false;
4273 // C++11 [over.match.list]p1, per DR1467:
4274 // When objects of non-aggregate type T are list-initialized, such that
4275 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
4276 // according to the rules in this section, overload resolution selects
4277 // the constructor in two phases:
4279 // - Initially, the candidate functions are the initializer-list
4280 // constructors of the class T and the argument list consists of the
4281 // initializer list as a single argument.
4282 if (IsListInit) {
4283 AsInitializerList = true;
4285 // If the initializer list has no elements and T has a default constructor,
4286 // the first phase is omitted.
4287 if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(DestRecordDecl)))
4288 Result = ResolveConstructorOverload(
4289 S, Kind.getLocation(), Args, CandidateSet, DestType, Ctors, Best,
4290 CopyInitialization, AllowExplicit,
4291 /*OnlyListConstructors=*/true, IsListInit, RequireActualConstructor);
4294 // C++11 [over.match.list]p1:
4295 // - If no viable initializer-list constructor is found, overload resolution
4296 // is performed again, where the candidate functions are all the
4297 // constructors of the class T and the argument list consists of the
4298 // elements of the initializer list.
4299 if (Result == OR_No_Viable_Function) {
4300 AsInitializerList = false;
4301 Result = ResolveConstructorOverload(
4302 S, Kind.getLocation(), UnwrappedArgs, CandidateSet, DestType, Ctors,
4303 Best, CopyInitialization, AllowExplicit,
4304 /*OnlyListConstructors=*/false, IsListInit, RequireActualConstructor);
4306 if (Result) {
4307 Sequence.SetOverloadFailure(
4308 IsListInit ? InitializationSequence::FK_ListConstructorOverloadFailed
4309 : InitializationSequence::FK_ConstructorOverloadFailed,
4310 Result);
4312 if (Result != OR_Deleted)
4313 return;
4316 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4318 // In C++17, ResolveConstructorOverload can select a conversion function
4319 // instead of a constructor.
4320 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
4321 // Add the user-defined conversion step that calls the conversion function.
4322 QualType ConvType = CD->getConversionType();
4323 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
4324 "should not have selected this conversion function");
4325 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
4326 HadMultipleCandidates);
4327 if (!S.Context.hasSameType(ConvType, DestType))
4328 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4329 if (IsListInit)
4330 Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
4331 return;
4334 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
4335 if (Result != OR_Deleted) {
4336 // C++11 [dcl.init]p6:
4337 // If a program calls for the default initialization of an object
4338 // of a const-qualified type T, T shall be a class type with a
4339 // user-provided default constructor.
4340 // C++ core issue 253 proposal:
4341 // If the implicit default constructor initializes all subobjects, no
4342 // initializer should be required.
4343 // The 253 proposal is for example needed to process libstdc++ headers
4344 // in 5.x.
4345 if (Kind.getKind() == InitializationKind::IK_Default &&
4346 Entity.getType().isConstQualified()) {
4347 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
4348 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4349 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
4350 return;
4354 // C++11 [over.match.list]p1:
4355 // In copy-list-initialization, if an explicit constructor is chosen, the
4356 // initializer is ill-formed.
4357 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
4358 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
4359 return;
4363 // [class.copy.elision]p3:
4364 // In some copy-initialization contexts, a two-stage overload resolution
4365 // is performed.
4366 // If the first overload resolution selects a deleted function, we also
4367 // need the initialization sequence to decide whether to perform the second
4368 // overload resolution.
4369 // For deleted functions in other contexts, there is no need to get the
4370 // initialization sequence.
4371 if (Result == OR_Deleted && Kind.getKind() != InitializationKind::IK_Copy)
4372 return;
4374 // Add the constructor initialization step. Any cv-qualification conversion is
4375 // subsumed by the initialization.
4376 Sequence.AddConstructorInitializationStep(
4377 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
4378 IsListInit | IsInitListCopy, AsInitializerList);
4381 static bool
4382 ResolveOverloadedFunctionForReferenceBinding(Sema &S,
4383 Expr *Initializer,
4384 QualType &SourceType,
4385 QualType &UnqualifiedSourceType,
4386 QualType UnqualifiedTargetType,
4387 InitializationSequence &Sequence) {
4388 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
4389 S.Context.OverloadTy) {
4390 DeclAccessPair Found;
4391 bool HadMultipleCandidates = false;
4392 if (FunctionDecl *Fn
4393 = S.ResolveAddressOfOverloadedFunction(Initializer,
4394 UnqualifiedTargetType,
4395 false, Found,
4396 &HadMultipleCandidates)) {
4397 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
4398 HadMultipleCandidates);
4399 SourceType = Fn->getType();
4400 UnqualifiedSourceType = SourceType.getUnqualifiedType();
4401 } else if (!UnqualifiedTargetType->isRecordType()) {
4402 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4403 return true;
4406 return false;
4409 static void TryReferenceInitializationCore(Sema &S,
4410 const InitializedEntity &Entity,
4411 const InitializationKind &Kind,
4412 Expr *Initializer,
4413 QualType cv1T1, QualType T1,
4414 Qualifiers T1Quals,
4415 QualType cv2T2, QualType T2,
4416 Qualifiers T2Quals,
4417 InitializationSequence &Sequence,
4418 bool TopLevelOfInitList);
4420 static void TryValueInitialization(Sema &S,
4421 const InitializedEntity &Entity,
4422 const InitializationKind &Kind,
4423 InitializationSequence &Sequence,
4424 InitListExpr *InitList = nullptr);
4426 /// Attempt list initialization of a reference.
4427 static void TryReferenceListInitialization(Sema &S,
4428 const InitializedEntity &Entity,
4429 const InitializationKind &Kind,
4430 InitListExpr *InitList,
4431 InitializationSequence &Sequence,
4432 bool TreatUnavailableAsInvalid) {
4433 // First, catch C++03 where this isn't possible.
4434 if (!S.getLangOpts().CPlusPlus11) {
4435 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4436 return;
4438 // Can't reference initialize a compound literal.
4439 if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
4440 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4441 return;
4444 QualType DestType = Entity.getType();
4445 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4446 Qualifiers T1Quals;
4447 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4449 // Reference initialization via an initializer list works thus:
4450 // If the initializer list consists of a single element that is
4451 // reference-related to the referenced type, bind directly to that element
4452 // (possibly creating temporaries).
4453 // Otherwise, initialize a temporary with the initializer list and
4454 // bind to that.
4455 if (InitList->getNumInits() == 1) {
4456 Expr *Initializer = InitList->getInit(0);
4457 QualType cv2T2 = S.getCompletedType(Initializer);
4458 Qualifiers T2Quals;
4459 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4461 // If this fails, creating a temporary wouldn't work either.
4462 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4463 T1, Sequence))
4464 return;
4466 SourceLocation DeclLoc = Initializer->getBeginLoc();
4467 Sema::ReferenceCompareResult RefRelationship
4468 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2);
4469 if (RefRelationship >= Sema::Ref_Related) {
4470 // Try to bind the reference here.
4471 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4472 T1Quals, cv2T2, T2, T2Quals, Sequence,
4473 /*TopLevelOfInitList=*/true);
4474 if (Sequence)
4475 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4476 return;
4479 // Update the initializer if we've resolved an overloaded function.
4480 if (Sequence.step_begin() != Sequence.step_end())
4481 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4483 // Perform address space compatibility check.
4484 QualType cv1T1IgnoreAS = cv1T1;
4485 if (T1Quals.hasAddressSpace()) {
4486 Qualifiers T2Quals;
4487 (void)S.Context.getUnqualifiedArrayType(InitList->getType(), T2Quals);
4488 if (!T1Quals.isAddressSpaceSupersetOf(T2Quals)) {
4489 Sequence.SetFailed(
4490 InitializationSequence::FK_ReferenceInitDropsQualifiers);
4491 return;
4493 // Ignore address space of reference type at this point and perform address
4494 // space conversion after the reference binding step.
4495 cv1T1IgnoreAS =
4496 S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace());
4498 // Not reference-related. Create a temporary and bind to that.
4499 InitializedEntity TempEntity =
4500 InitializedEntity::InitializeTemporary(cv1T1IgnoreAS);
4502 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
4503 TreatUnavailableAsInvalid);
4504 if (Sequence) {
4505 if (DestType->isRValueReferenceType() ||
4506 (T1Quals.hasConst() && !T1Quals.hasVolatile())) {
4507 if (S.getLangOpts().CPlusPlus20 &&
4508 isa<IncompleteArrayType>(T1->getUnqualifiedDesugaredType()) &&
4509 DestType->isRValueReferenceType()) {
4510 // C++20 [dcl.init.list]p3.10:
4511 // List-initialization of an object or reference of type T is defined as
4512 // follows:
4513 // ..., unless T is “reference to array of unknown bound of U”, in which
4514 // case the type of the prvalue is the type of x in the declaration U
4515 // x[] H, where H is the initializer list.
4516 Sequence.AddQualificationConversionStep(cv1T1, clang::VK_PRValue);
4518 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS,
4519 /*BindingTemporary=*/true);
4520 if (T1Quals.hasAddressSpace())
4521 Sequence.AddQualificationConversionStep(
4522 cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue);
4523 } else
4524 Sequence.SetFailed(
4525 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
4529 /// Attempt list initialization (C++0x [dcl.init.list])
4530 static void TryListInitialization(Sema &S,
4531 const InitializedEntity &Entity,
4532 const InitializationKind &Kind,
4533 InitListExpr *InitList,
4534 InitializationSequence &Sequence,
4535 bool TreatUnavailableAsInvalid) {
4536 QualType DestType = Entity.getType();
4538 // C++ doesn't allow scalar initialization with more than one argument.
4539 // But C99 complex numbers are scalars and it makes sense there.
4540 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
4541 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
4542 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
4543 return;
4545 if (DestType->isReferenceType()) {
4546 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
4547 TreatUnavailableAsInvalid);
4548 return;
4551 if (DestType->isRecordType() &&
4552 !S.isCompleteType(InitList->getBeginLoc(), DestType)) {
4553 Sequence.setIncompleteTypeFailure(DestType);
4554 return;
4557 // C++20 [dcl.init.list]p3:
4558 // - If the braced-init-list contains a designated-initializer-list, T shall
4559 // be an aggregate class. [...] Aggregate initialization is performed.
4561 // We allow arrays here too in order to support array designators.
4563 // FIXME: This check should precede the handling of reference initialization.
4564 // We follow other compilers in allowing things like 'Aggr &&a = {.x = 1};'
4565 // as a tentative DR resolution.
4566 bool IsDesignatedInit = InitList->hasDesignatedInit();
4567 if (!DestType->isAggregateType() && IsDesignatedInit) {
4568 Sequence.SetFailed(
4569 InitializationSequence::FK_DesignatedInitForNonAggregate);
4570 return;
4573 // C++11 [dcl.init.list]p3, per DR1467:
4574 // - If T is a class type and the initializer list has a single element of
4575 // type cv U, where U is T or a class derived from T, the object is
4576 // initialized from that element (by copy-initialization for
4577 // copy-list-initialization, or by direct-initialization for
4578 // direct-list-initialization).
4579 // - Otherwise, if T is a character array and the initializer list has a
4580 // single element that is an appropriately-typed string literal
4581 // (8.5.2 [dcl.init.string]), initialization is performed as described
4582 // in that section.
4583 // - Otherwise, if T is an aggregate, [...] (continue below).
4584 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1 &&
4585 !IsDesignatedInit) {
4586 if (DestType->isRecordType()) {
4587 QualType InitType = InitList->getInit(0)->getType();
4588 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
4589 S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {
4590 Expr *InitListAsExpr = InitList;
4591 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4592 DestType, Sequence,
4593 /*InitListSyntax*/false,
4594 /*IsInitListCopy*/true);
4595 return;
4598 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
4599 Expr *SubInit[1] = {InitList->getInit(0)};
4600 if (!isa<VariableArrayType>(DestAT) &&
4601 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
4602 InitializationKind SubKind =
4603 Kind.getKind() == InitializationKind::IK_DirectList
4604 ? InitializationKind::CreateDirect(Kind.getLocation(),
4605 InitList->getLBraceLoc(),
4606 InitList->getRBraceLoc())
4607 : Kind;
4608 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4609 /*TopLevelOfInitList*/ true,
4610 TreatUnavailableAsInvalid);
4612 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4613 // the element is not an appropriately-typed string literal, in which
4614 // case we should proceed as in C++11 (below).
4615 if (Sequence) {
4616 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4617 return;
4623 // C++11 [dcl.init.list]p3:
4624 // - If T is an aggregate, aggregate initialization is performed.
4625 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
4626 (S.getLangOpts().CPlusPlus11 &&
4627 S.isStdInitializerList(DestType, nullptr) && !IsDesignatedInit)) {
4628 if (S.getLangOpts().CPlusPlus11) {
4629 // - Otherwise, if the initializer list has no elements and T is a
4630 // class type with a default constructor, the object is
4631 // value-initialized.
4632 if (InitList->getNumInits() == 0) {
4633 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4634 if (S.LookupDefaultConstructor(RD)) {
4635 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
4636 return;
4640 // - Otherwise, if T is a specialization of std::initializer_list<E>,
4641 // an initializer_list object constructed [...]
4642 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
4643 TreatUnavailableAsInvalid))
4644 return;
4646 // - Otherwise, if T is a class type, constructors are considered.
4647 Expr *InitListAsExpr = InitList;
4648 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4649 DestType, Sequence, /*InitListSyntax*/true);
4650 } else
4651 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
4652 return;
4655 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
4656 InitList->getNumInits() == 1) {
4657 Expr *E = InitList->getInit(0);
4659 // - Otherwise, if T is an enumeration with a fixed underlying type,
4660 // the initializer-list has a single element v, and the initialization
4661 // is direct-list-initialization, the object is initialized with the
4662 // value T(v); if a narrowing conversion is required to convert v to
4663 // the underlying type of T, the program is ill-formed.
4664 auto *ET = DestType->getAs<EnumType>();
4665 if (S.getLangOpts().CPlusPlus17 &&
4666 Kind.getKind() == InitializationKind::IK_DirectList &&
4667 ET && ET->getDecl()->isFixed() &&
4668 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
4669 (E->getType()->isIntegralOrUnscopedEnumerationType() ||
4670 E->getType()->isFloatingType())) {
4671 // There are two ways that T(v) can work when T is an enumeration type.
4672 // If there is either an implicit conversion sequence from v to T or
4673 // a conversion function that can convert from v to T, then we use that.
4674 // Otherwise, if v is of integral, unscoped enumeration, or floating-point
4675 // type, it is converted to the enumeration type via its underlying type.
4676 // There is no overlap possible between these two cases (except when the
4677 // source value is already of the destination type), and the first
4678 // case is handled by the general case for single-element lists below.
4679 ImplicitConversionSequence ICS;
4680 ICS.setStandard();
4681 ICS.Standard.setAsIdentityConversion();
4682 if (!E->isPRValue())
4683 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4684 // If E is of a floating-point type, then the conversion is ill-formed
4685 // due to narrowing, but go through the motions in order to produce the
4686 // right diagnostic.
4687 ICS.Standard.Second = E->getType()->isFloatingType()
4688 ? ICK_Floating_Integral
4689 : ICK_Integral_Conversion;
4690 ICS.Standard.setFromType(E->getType());
4691 ICS.Standard.setToType(0, E->getType());
4692 ICS.Standard.setToType(1, DestType);
4693 ICS.Standard.setToType(2, DestType);
4694 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
4695 /*TopLevelOfInitList*/true);
4696 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4697 return;
4700 // - Otherwise, if the initializer list has a single element of type E
4701 // [...references are handled above...], the object or reference is
4702 // initialized from that element (by copy-initialization for
4703 // copy-list-initialization, or by direct-initialization for
4704 // direct-list-initialization); if a narrowing conversion is required
4705 // to convert the element to T, the program is ill-formed.
4707 // Per core-24034, this is direct-initialization if we were performing
4708 // direct-list-initialization and copy-initialization otherwise.
4709 // We can't use InitListChecker for this, because it always performs
4710 // copy-initialization. This only matters if we might use an 'explicit'
4711 // conversion operator, or for the special case conversion of nullptr_t to
4712 // bool, so we only need to handle those cases.
4714 // FIXME: Why not do this in all cases?
4715 Expr *Init = InitList->getInit(0);
4716 if (Init->getType()->isRecordType() ||
4717 (Init->getType()->isNullPtrType() && DestType->isBooleanType())) {
4718 InitializationKind SubKind =
4719 Kind.getKind() == InitializationKind::IK_DirectList
4720 ? InitializationKind::CreateDirect(Kind.getLocation(),
4721 InitList->getLBraceLoc(),
4722 InitList->getRBraceLoc())
4723 : Kind;
4724 Expr *SubInit[1] = { Init };
4725 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4726 /*TopLevelOfInitList*/true,
4727 TreatUnavailableAsInvalid);
4728 if (Sequence)
4729 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4730 return;
4734 InitListChecker CheckInitList(S, Entity, InitList,
4735 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
4736 if (CheckInitList.HadError()) {
4737 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
4738 return;
4741 // Add the list initialization step with the built init list.
4742 Sequence.AddListInitializationStep(DestType);
4745 /// Try a reference initialization that involves calling a conversion
4746 /// function.
4747 static OverloadingResult TryRefInitWithConversionFunction(
4748 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4749 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
4750 InitializationSequence &Sequence) {
4751 QualType DestType = Entity.getType();
4752 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4753 QualType T1 = cv1T1.getUnqualifiedType();
4754 QualType cv2T2 = Initializer->getType();
4755 QualType T2 = cv2T2.getUnqualifiedType();
4757 assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) &&
4758 "Must have incompatible references when binding via conversion");
4760 // Build the candidate set directly in the initialization sequence
4761 // structure, so that it will persist if we fail.
4762 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4763 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4765 // Determine whether we are allowed to call explicit conversion operators.
4766 // Note that none of [over.match.copy], [over.match.conv], nor
4767 // [over.match.ref] permit an explicit constructor to be chosen when
4768 // initializing a reference, not even for direct-initialization.
4769 bool AllowExplicitCtors = false;
4770 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
4772 const RecordType *T1RecordType = nullptr;
4773 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
4774 S.isCompleteType(Kind.getLocation(), T1)) {
4775 // The type we're converting to is a class type. Enumerate its constructors
4776 // to see if there is a suitable conversion.
4777 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
4779 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
4780 auto Info = getConstructorInfo(D);
4781 if (!Info.Constructor)
4782 continue;
4784 if (!Info.Constructor->isInvalidDecl() &&
4785 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
4786 if (Info.ConstructorTmpl)
4787 S.AddTemplateOverloadCandidate(
4788 Info.ConstructorTmpl, Info.FoundDecl,
4789 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
4790 /*SuppressUserConversions=*/true,
4791 /*PartialOverloading*/ false, AllowExplicitCtors);
4792 else
4793 S.AddOverloadCandidate(
4794 Info.Constructor, Info.FoundDecl, Initializer, CandidateSet,
4795 /*SuppressUserConversions=*/true,
4796 /*PartialOverloading*/ false, AllowExplicitCtors);
4800 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
4801 return OR_No_Viable_Function;
4803 const RecordType *T2RecordType = nullptr;
4804 if ((T2RecordType = T2->getAs<RecordType>()) &&
4805 S.isCompleteType(Kind.getLocation(), T2)) {
4806 // The type we're converting from is a class type, enumerate its conversion
4807 // functions.
4808 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4810 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4811 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4812 NamedDecl *D = *I;
4813 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4814 if (isa<UsingShadowDecl>(D))
4815 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4817 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4818 CXXConversionDecl *Conv;
4819 if (ConvTemplate)
4820 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4821 else
4822 Conv = cast<CXXConversionDecl>(D);
4824 // If the conversion function doesn't return a reference type,
4825 // it can't be considered for this conversion unless we're allowed to
4826 // consider rvalues.
4827 // FIXME: Do we need to make sure that we only consider conversion
4828 // candidates with reference-compatible results? That might be needed to
4829 // break recursion.
4830 if ((AllowRValues ||
4831 Conv->getConversionType()->isLValueReferenceType())) {
4832 if (ConvTemplate)
4833 S.AddTemplateConversionCandidate(
4834 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4835 CandidateSet,
4836 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
4837 else
4838 S.AddConversionCandidate(
4839 Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet,
4840 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
4844 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4845 return OR_No_Viable_Function;
4847 SourceLocation DeclLoc = Initializer->getBeginLoc();
4849 // Perform overload resolution. If it fails, return the failed result.
4850 OverloadCandidateSet::iterator Best;
4851 if (OverloadingResult Result
4852 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
4853 return Result;
4855 FunctionDecl *Function = Best->Function;
4856 // This is the overload that will be used for this initialization step if we
4857 // use this initialization. Mark it as referenced.
4858 Function->setReferenced();
4860 // Compute the returned type and value kind of the conversion.
4861 QualType cv3T3;
4862 if (isa<CXXConversionDecl>(Function))
4863 cv3T3 = Function->getReturnType();
4864 else
4865 cv3T3 = T1;
4867 ExprValueKind VK = VK_PRValue;
4868 if (cv3T3->isLValueReferenceType())
4869 VK = VK_LValue;
4870 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
4871 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
4872 cv3T3 = cv3T3.getNonLValueExprType(S.Context);
4874 // Add the user-defined conversion step.
4875 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4876 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
4877 HadMultipleCandidates);
4879 // Determine whether we'll need to perform derived-to-base adjustments or
4880 // other conversions.
4881 Sema::ReferenceConversions RefConv;
4882 Sema::ReferenceCompareResult NewRefRelationship =
4883 S.CompareReferenceRelationship(DeclLoc, T1, cv3T3, &RefConv);
4885 // Add the final conversion sequence, if necessary.
4886 if (NewRefRelationship == Sema::Ref_Incompatible) {
4887 assert(!isa<CXXConstructorDecl>(Function) &&
4888 "should not have conversion after constructor");
4890 ImplicitConversionSequence ICS;
4891 ICS.setStandard();
4892 ICS.Standard = Best->FinalConversion;
4893 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
4895 // Every implicit conversion results in a prvalue, except for a glvalue
4896 // derived-to-base conversion, which we handle below.
4897 cv3T3 = ICS.Standard.getToType(2);
4898 VK = VK_PRValue;
4901 // If the converted initializer is a prvalue, its type T4 is adjusted to
4902 // type "cv1 T4" and the temporary materialization conversion is applied.
4904 // We adjust the cv-qualifications to match the reference regardless of
4905 // whether we have a prvalue so that the AST records the change. In this
4906 // case, T4 is "cv3 T3".
4907 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
4908 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
4909 Sequence.AddQualificationConversionStep(cv1T4, VK);
4910 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_PRValue);
4911 VK = IsLValueRef ? VK_LValue : VK_XValue;
4913 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
4914 Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
4915 else if (RefConv & Sema::ReferenceConversions::ObjC)
4916 Sequence.AddObjCObjectConversionStep(cv1T1);
4917 else if (RefConv & Sema::ReferenceConversions::Function)
4918 Sequence.AddFunctionReferenceConversionStep(cv1T1);
4919 else if (RefConv & Sema::ReferenceConversions::Qualification) {
4920 if (!S.Context.hasSameType(cv1T4, cv1T1))
4921 Sequence.AddQualificationConversionStep(cv1T1, VK);
4924 return OR_Success;
4927 static void CheckCXX98CompatAccessibleCopy(Sema &S,
4928 const InitializedEntity &Entity,
4929 Expr *CurInitExpr);
4931 /// Attempt reference initialization (C++0x [dcl.init.ref])
4932 static void TryReferenceInitialization(Sema &S, const InitializedEntity &Entity,
4933 const InitializationKind &Kind,
4934 Expr *Initializer,
4935 InitializationSequence &Sequence,
4936 bool TopLevelOfInitList) {
4937 QualType DestType = Entity.getType();
4938 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4939 Qualifiers T1Quals;
4940 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4941 QualType cv2T2 = S.getCompletedType(Initializer);
4942 Qualifiers T2Quals;
4943 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4945 // If the initializer is the address of an overloaded function, try
4946 // to resolve the overloaded function. If all goes well, T2 is the
4947 // type of the resulting function.
4948 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4949 T1, Sequence))
4950 return;
4952 // Delegate everything else to a subfunction.
4953 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4954 T1Quals, cv2T2, T2, T2Quals, Sequence,
4955 TopLevelOfInitList);
4958 /// Determine whether an expression is a non-referenceable glvalue (one to
4959 /// which a reference can never bind). Attempting to bind a reference to
4960 /// such a glvalue will always create a temporary.
4961 static bool isNonReferenceableGLValue(Expr *E) {
4962 return E->refersToBitField() || E->refersToVectorElement() ||
4963 E->refersToMatrixElement();
4966 /// Reference initialization without resolving overloaded functions.
4968 /// We also can get here in C if we call a builtin which is declared as
4969 /// a function with a parameter of reference type (such as __builtin_va_end()).
4970 static void TryReferenceInitializationCore(Sema &S,
4971 const InitializedEntity &Entity,
4972 const InitializationKind &Kind,
4973 Expr *Initializer,
4974 QualType cv1T1, QualType T1,
4975 Qualifiers T1Quals,
4976 QualType cv2T2, QualType T2,
4977 Qualifiers T2Quals,
4978 InitializationSequence &Sequence,
4979 bool TopLevelOfInitList) {
4980 QualType DestType = Entity.getType();
4981 SourceLocation DeclLoc = Initializer->getBeginLoc();
4983 // Compute some basic properties of the types and the initializer.
4984 bool isLValueRef = DestType->isLValueReferenceType();
4985 bool isRValueRef = !isLValueRef;
4986 Expr::Classification InitCategory = Initializer->Classify(S.Context);
4988 Sema::ReferenceConversions RefConv;
4989 Sema::ReferenceCompareResult RefRelationship =
4990 S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, &RefConv);
4992 // C++0x [dcl.init.ref]p5:
4993 // A reference to type "cv1 T1" is initialized by an expression of type
4994 // "cv2 T2" as follows:
4996 // - If the reference is an lvalue reference and the initializer
4997 // expression
4998 // Note the analogous bullet points for rvalue refs to functions. Because
4999 // there are no function rvalues in C++, rvalue refs to functions are treated
5000 // like lvalue refs.
5001 OverloadingResult ConvOvlResult = OR_Success;
5002 bool T1Function = T1->isFunctionType();
5003 if (isLValueRef || T1Function) {
5004 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
5005 (RefRelationship == Sema::Ref_Compatible ||
5006 (Kind.isCStyleOrFunctionalCast() &&
5007 RefRelationship == Sema::Ref_Related))) {
5008 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
5009 // reference-compatible with "cv2 T2," or
5010 if (RefConv & (Sema::ReferenceConversions::DerivedToBase |
5011 Sema::ReferenceConversions::ObjC)) {
5012 // If we're converting the pointee, add any qualifiers first;
5013 // these qualifiers must all be top-level, so just convert to "cv1 T2".
5014 if (RefConv & (Sema::ReferenceConversions::Qualification))
5015 Sequence.AddQualificationConversionStep(
5016 S.Context.getQualifiedType(T2, T1Quals),
5017 Initializer->getValueKind());
5018 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5019 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
5020 else
5021 Sequence.AddObjCObjectConversionStep(cv1T1);
5022 } else if (RefConv & Sema::ReferenceConversions::Qualification) {
5023 // Perform a (possibly multi-level) qualification conversion.
5024 Sequence.AddQualificationConversionStep(cv1T1,
5025 Initializer->getValueKind());
5026 } else if (RefConv & Sema::ReferenceConversions::Function) {
5027 Sequence.AddFunctionReferenceConversionStep(cv1T1);
5030 // We only create a temporary here when binding a reference to a
5031 // bit-field or vector element. Those cases are't supposed to be
5032 // handled by this bullet, but the outcome is the same either way.
5033 Sequence.AddReferenceBindingStep(cv1T1, false);
5034 return;
5037 // - has a class type (i.e., T2 is a class type), where T1 is not
5038 // reference-related to T2, and can be implicitly converted to an
5039 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
5040 // with "cv3 T3" (this conversion is selected by enumerating the
5041 // applicable conversion functions (13.3.1.6) and choosing the best
5042 // one through overload resolution (13.3)),
5043 // If we have an rvalue ref to function type here, the rhs must be
5044 // an rvalue. DR1287 removed the "implicitly" here.
5045 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
5046 (isLValueRef || InitCategory.isRValue())) {
5047 if (S.getLangOpts().CPlusPlus) {
5048 // Try conversion functions only for C++.
5049 ConvOvlResult = TryRefInitWithConversionFunction(
5050 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
5051 /*IsLValueRef*/ isLValueRef, Sequence);
5052 if (ConvOvlResult == OR_Success)
5053 return;
5054 if (ConvOvlResult != OR_No_Viable_Function)
5055 Sequence.SetOverloadFailure(
5056 InitializationSequence::FK_ReferenceInitOverloadFailed,
5057 ConvOvlResult);
5058 } else {
5059 ConvOvlResult = OR_No_Viable_Function;
5064 // - Otherwise, the reference shall be an lvalue reference to a
5065 // non-volatile const type (i.e., cv1 shall be const), or the reference
5066 // shall be an rvalue reference.
5067 // For address spaces, we interpret this to mean that an addr space
5068 // of a reference "cv1 T1" is a superset of addr space of "cv2 T2".
5069 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile() &&
5070 T1Quals.isAddressSpaceSupersetOf(T2Quals))) {
5071 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
5072 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
5073 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5074 Sequence.SetOverloadFailure(
5075 InitializationSequence::FK_ReferenceInitOverloadFailed,
5076 ConvOvlResult);
5077 else if (!InitCategory.isLValue())
5078 Sequence.SetFailed(
5079 T1Quals.isAddressSpaceSupersetOf(T2Quals)
5080 ? InitializationSequence::
5081 FK_NonConstLValueReferenceBindingToTemporary
5082 : InitializationSequence::FK_ReferenceInitDropsQualifiers);
5083 else {
5084 InitializationSequence::FailureKind FK;
5085 switch (RefRelationship) {
5086 case Sema::Ref_Compatible:
5087 if (Initializer->refersToBitField())
5088 FK = InitializationSequence::
5089 FK_NonConstLValueReferenceBindingToBitfield;
5090 else if (Initializer->refersToVectorElement())
5091 FK = InitializationSequence::
5092 FK_NonConstLValueReferenceBindingToVectorElement;
5093 else if (Initializer->refersToMatrixElement())
5094 FK = InitializationSequence::
5095 FK_NonConstLValueReferenceBindingToMatrixElement;
5096 else
5097 llvm_unreachable("unexpected kind of compatible initializer");
5098 break;
5099 case Sema::Ref_Related:
5100 FK = InitializationSequence::FK_ReferenceInitDropsQualifiers;
5101 break;
5102 case Sema::Ref_Incompatible:
5103 FK = InitializationSequence::
5104 FK_NonConstLValueReferenceBindingToUnrelated;
5105 break;
5107 Sequence.SetFailed(FK);
5109 return;
5112 // - If the initializer expression
5113 // - is an
5114 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
5115 // [1z] rvalue (but not a bit-field) or
5116 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
5118 // Note: functions are handled above and below rather than here...
5119 if (!T1Function &&
5120 (RefRelationship == Sema::Ref_Compatible ||
5121 (Kind.isCStyleOrFunctionalCast() &&
5122 RefRelationship == Sema::Ref_Related)) &&
5123 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
5124 (InitCategory.isPRValue() &&
5125 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
5126 T2->isArrayType())))) {
5127 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_PRValue;
5128 if (InitCategory.isPRValue() && T2->isRecordType()) {
5129 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
5130 // compiler the freedom to perform a copy here or bind to the
5131 // object, while C++0x requires that we bind directly to the
5132 // object. Hence, we always bind to the object without making an
5133 // extra copy. However, in C++03 requires that we check for the
5134 // presence of a suitable copy constructor:
5136 // The constructor that would be used to make the copy shall
5137 // be callable whether or not the copy is actually done.
5138 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
5139 Sequence.AddExtraneousCopyToTemporary(cv2T2);
5140 else if (S.getLangOpts().CPlusPlus11)
5141 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
5144 // C++1z [dcl.init.ref]/5.2.1.2:
5145 // If the converted initializer is a prvalue, its type T4 is adjusted
5146 // to type "cv1 T4" and the temporary materialization conversion is
5147 // applied.
5148 // Postpone address space conversions to after the temporary materialization
5149 // conversion to allow creating temporaries in the alloca address space.
5150 auto T1QualsIgnoreAS = T1Quals;
5151 auto T2QualsIgnoreAS = T2Quals;
5152 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5153 T1QualsIgnoreAS.removeAddressSpace();
5154 T2QualsIgnoreAS.removeAddressSpace();
5156 QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1QualsIgnoreAS);
5157 if (T1QualsIgnoreAS != T2QualsIgnoreAS)
5158 Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
5159 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_PRValue);
5160 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
5161 // Add addr space conversion if required.
5162 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5163 auto T4Quals = cv1T4.getQualifiers();
5164 T4Quals.addAddressSpace(T1Quals.getAddressSpace());
5165 QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals);
5166 Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind);
5167 cv1T4 = cv1T4WithAS;
5170 // In any case, the reference is bound to the resulting glvalue (or to
5171 // an appropriate base class subobject).
5172 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5173 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
5174 else if (RefConv & Sema::ReferenceConversions::ObjC)
5175 Sequence.AddObjCObjectConversionStep(cv1T1);
5176 else if (RefConv & Sema::ReferenceConversions::Qualification) {
5177 if (!S.Context.hasSameType(cv1T4, cv1T1))
5178 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
5180 return;
5183 // - has a class type (i.e., T2 is a class type), where T1 is not
5184 // reference-related to T2, and can be implicitly converted to an
5185 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
5186 // where "cv1 T1" is reference-compatible with "cv3 T3",
5188 // DR1287 removes the "implicitly" here.
5189 if (T2->isRecordType()) {
5190 if (RefRelationship == Sema::Ref_Incompatible) {
5191 ConvOvlResult = TryRefInitWithConversionFunction(
5192 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
5193 /*IsLValueRef*/ isLValueRef, Sequence);
5194 if (ConvOvlResult)
5195 Sequence.SetOverloadFailure(
5196 InitializationSequence::FK_ReferenceInitOverloadFailed,
5197 ConvOvlResult);
5199 return;
5202 if (RefRelationship == Sema::Ref_Compatible &&
5203 isRValueRef && InitCategory.isLValue()) {
5204 Sequence.SetFailed(
5205 InitializationSequence::FK_RValueReferenceBindingToLValue);
5206 return;
5209 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
5210 return;
5213 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
5214 // from the initializer expression using the rules for a non-reference
5215 // copy-initialization (8.5). The reference is then bound to the
5216 // temporary. [...]
5218 // Ignore address space of reference type at this point and perform address
5219 // space conversion after the reference binding step.
5220 QualType cv1T1IgnoreAS =
5221 T1Quals.hasAddressSpace()
5222 ? S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace())
5223 : cv1T1;
5225 InitializedEntity TempEntity =
5226 InitializedEntity::InitializeTemporary(cv1T1IgnoreAS);
5228 // FIXME: Why do we use an implicit conversion here rather than trying
5229 // copy-initialization?
5230 ImplicitConversionSequence ICS
5231 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
5232 /*SuppressUserConversions=*/false,
5233 Sema::AllowedExplicit::None,
5234 /*FIXME:InOverloadResolution=*/false,
5235 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5236 /*AllowObjCWritebackConversion=*/false);
5238 if (ICS.isBad()) {
5239 // FIXME: Use the conversion function set stored in ICS to turn
5240 // this into an overloading ambiguity diagnostic. However, we need
5241 // to keep that set as an OverloadCandidateSet rather than as some
5242 // other kind of set.
5243 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5244 Sequence.SetOverloadFailure(
5245 InitializationSequence::FK_ReferenceInitOverloadFailed,
5246 ConvOvlResult);
5247 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
5248 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
5249 else
5250 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
5251 return;
5252 } else {
5253 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType(),
5254 TopLevelOfInitList);
5257 // [...] If T1 is reference-related to T2, cv1 must be the
5258 // same cv-qualification as, or greater cv-qualification
5259 // than, cv2; otherwise, the program is ill-formed.
5260 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
5261 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
5262 if (RefRelationship == Sema::Ref_Related &&
5263 ((T1CVRQuals | T2CVRQuals) != T1CVRQuals ||
5264 !T1Quals.isAddressSpaceSupersetOf(T2Quals))) {
5265 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
5266 return;
5269 // [...] If T1 is reference-related to T2 and the reference is an rvalue
5270 // reference, the initializer expression shall not be an lvalue.
5271 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
5272 InitCategory.isLValue()) {
5273 Sequence.SetFailed(
5274 InitializationSequence::FK_RValueReferenceBindingToLValue);
5275 return;
5278 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true);
5280 if (T1Quals.hasAddressSpace()) {
5281 if (!Qualifiers::isAddressSpaceSupersetOf(T1Quals.getAddressSpace(),
5282 LangAS::Default)) {
5283 Sequence.SetFailed(
5284 InitializationSequence::FK_ReferenceAddrspaceMismatchTemporary);
5285 return;
5287 Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue
5288 : VK_XValue);
5292 /// Attempt character array initialization from a string literal
5293 /// (C++ [dcl.init.string], C99 6.7.8).
5294 static void TryStringLiteralInitialization(Sema &S,
5295 const InitializedEntity &Entity,
5296 const InitializationKind &Kind,
5297 Expr *Initializer,
5298 InitializationSequence &Sequence) {
5299 Sequence.AddStringInitStep(Entity.getType());
5302 /// Attempt value initialization (C++ [dcl.init]p7).
5303 static void TryValueInitialization(Sema &S,
5304 const InitializedEntity &Entity,
5305 const InitializationKind &Kind,
5306 InitializationSequence &Sequence,
5307 InitListExpr *InitList) {
5308 assert((!InitList || InitList->getNumInits() == 0) &&
5309 "Shouldn't use value-init for non-empty init lists");
5311 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
5313 // To value-initialize an object of type T means:
5314 QualType T = Entity.getType();
5316 // -- if T is an array type, then each element is value-initialized;
5317 T = S.Context.getBaseElementType(T);
5319 if (const RecordType *RT = T->getAs<RecordType>()) {
5320 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
5321 bool NeedZeroInitialization = true;
5322 // C++98:
5323 // -- if T is a class type (clause 9) with a user-declared constructor
5324 // (12.1), then the default constructor for T is called (and the
5325 // initialization is ill-formed if T has no accessible default
5326 // constructor);
5327 // C++11:
5328 // -- if T is a class type (clause 9) with either no default constructor
5329 // (12.1 [class.ctor]) or a default constructor that is user-provided
5330 // or deleted, then the object is default-initialized;
5332 // Note that the C++11 rule is the same as the C++98 rule if there are no
5333 // defaulted or deleted constructors, so we just use it unconditionally.
5334 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
5335 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
5336 NeedZeroInitialization = false;
5338 // -- if T is a (possibly cv-qualified) non-union class type without a
5339 // user-provided or deleted default constructor, then the object is
5340 // zero-initialized and, if T has a non-trivial default constructor,
5341 // default-initialized;
5342 // The 'non-union' here was removed by DR1502. The 'non-trivial default
5343 // constructor' part was removed by DR1507.
5344 if (NeedZeroInitialization)
5345 Sequence.AddZeroInitializationStep(Entity.getType());
5347 // C++03:
5348 // -- if T is a non-union class type without a user-declared constructor,
5349 // then every non-static data member and base class component of T is
5350 // value-initialized;
5351 // [...] A program that calls for [...] value-initialization of an
5352 // entity of reference type is ill-formed.
5354 // C++11 doesn't need this handling, because value-initialization does not
5355 // occur recursively there, and the implicit default constructor is
5356 // defined as deleted in the problematic cases.
5357 if (!S.getLangOpts().CPlusPlus11 &&
5358 ClassDecl->hasUninitializedReferenceMember()) {
5359 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
5360 return;
5363 // If this is list-value-initialization, pass the empty init list on when
5364 // building the constructor call. This affects the semantics of a few
5365 // things (such as whether an explicit default constructor can be called).
5366 Expr *InitListAsExpr = InitList;
5367 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
5368 bool InitListSyntax = InitList;
5370 // FIXME: Instead of creating a CXXConstructExpr of array type here,
5371 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
5372 return TryConstructorInitialization(
5373 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
5377 Sequence.AddZeroInitializationStep(Entity.getType());
5380 /// Attempt default initialization (C++ [dcl.init]p6).
5381 static void TryDefaultInitialization(Sema &S,
5382 const InitializedEntity &Entity,
5383 const InitializationKind &Kind,
5384 InitializationSequence &Sequence) {
5385 assert(Kind.getKind() == InitializationKind::IK_Default);
5387 // C++ [dcl.init]p6:
5388 // To default-initialize an object of type T means:
5389 // - if T is an array type, each element is default-initialized;
5390 QualType DestType = S.Context.getBaseElementType(Entity.getType());
5392 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
5393 // constructor for T is called (and the initialization is ill-formed if
5394 // T has no accessible default constructor);
5395 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
5396 TryConstructorInitialization(S, Entity, Kind, std::nullopt, DestType,
5397 Entity.getType(), Sequence);
5398 return;
5401 // - otherwise, no initialization is performed.
5403 // If a program calls for the default initialization of an object of
5404 // a const-qualified type T, T shall be a class type with a user-provided
5405 // default constructor.
5406 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
5407 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
5408 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
5409 return;
5412 // If the destination type has a lifetime property, zero-initialize it.
5413 if (DestType.getQualifiers().hasObjCLifetime()) {
5414 Sequence.AddZeroInitializationStep(Entity.getType());
5415 return;
5419 static void TryOrBuildParenListInitialization(
5420 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
5421 ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly,
5422 ExprResult *Result = nullptr) {
5423 unsigned EntityIndexToProcess = 0;
5424 SmallVector<Expr *, 4> InitExprs;
5425 QualType ResultType;
5426 Expr *ArrayFiller = nullptr;
5427 FieldDecl *InitializedFieldInUnion = nullptr;
5429 auto HandleInitializedEntity = [&](const InitializedEntity &SubEntity,
5430 const InitializationKind &SubKind,
5431 Expr *Arg, Expr **InitExpr = nullptr) {
5432 InitializationSequence IS = [&]() {
5433 if (Arg)
5434 return InitializationSequence(S, SubEntity, SubKind, Arg);
5435 return InitializationSequence(S, SubEntity, SubKind, std::nullopt);
5436 }();
5438 if (IS.Failed()) {
5439 if (!VerifyOnly) {
5440 if (Arg)
5441 IS.Diagnose(S, SubEntity, SubKind, Arg);
5442 else
5443 IS.Diagnose(S, SubEntity, SubKind, std::nullopt);
5444 } else {
5445 Sequence.SetFailed(
5446 InitializationSequence::FK_ParenthesizedListInitFailed);
5449 return false;
5451 if (!VerifyOnly) {
5452 ExprResult ER;
5453 if (Arg)
5454 ER = IS.Perform(S, SubEntity, SubKind, Arg);
5455 else
5456 ER = IS.Perform(S, SubEntity, SubKind, std::nullopt);
5457 if (InitExpr)
5458 *InitExpr = ER.get();
5459 else
5460 InitExprs.push_back(ER.get());
5462 return true;
5465 if (const ArrayType *AT =
5466 S.getASTContext().getAsArrayType(Entity.getType())) {
5467 SmallVector<InitializedEntity, 4> ElementEntities;
5468 uint64_t ArrayLength;
5469 // C++ [dcl.init]p16.5
5470 // if the destination type is an array, the object is initialized as
5471 // follows. Let x1, . . . , xk be the elements of the expression-list. If
5472 // the destination type is an array of unknown bound, it is defined as
5473 // having k elements.
5474 if (const ConstantArrayType *CAT =
5475 S.getASTContext().getAsConstantArrayType(Entity.getType())) {
5476 ArrayLength = CAT->getSize().getZExtValue();
5477 ResultType = Entity.getType();
5478 } else if (const VariableArrayType *VAT =
5479 S.getASTContext().getAsVariableArrayType(Entity.getType())) {
5480 // Braced-initialization of variable array types is not allowed, even if
5481 // the size is greater than or equal to the number of args, so we don't
5482 // allow them to be initialized via parenthesized aggregate initialization
5483 // either.
5484 const Expr *SE = VAT->getSizeExpr();
5485 S.Diag(SE->getBeginLoc(), diag::err_variable_object_no_init)
5486 << SE->getSourceRange();
5487 return;
5488 } else {
5489 assert(isa<IncompleteArrayType>(Entity.getType()));
5490 ArrayLength = Args.size();
5492 EntityIndexToProcess = ArrayLength;
5494 // ...the ith array element is copy-initialized with xi for each
5495 // 1 <= i <= k
5496 for (Expr *E : Args) {
5497 InitializedEntity SubEntity = InitializedEntity::InitializeElement(
5498 S.getASTContext(), EntityIndexToProcess, Entity);
5499 InitializationKind SubKind = InitializationKind::CreateForInit(
5500 E->getExprLoc(), /*isDirectInit=*/false, E);
5501 if (!HandleInitializedEntity(SubEntity, SubKind, E))
5502 return;
5504 // ...and value-initialized for each k < i <= n;
5505 if (ArrayLength > Args.size()) {
5506 InitializedEntity SubEntity = InitializedEntity::InitializeElement(
5507 S.getASTContext(), Args.size(), Entity);
5508 InitializationKind SubKind = InitializationKind::CreateValue(
5509 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
5510 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr, &ArrayFiller))
5511 return;
5514 if (ResultType.isNull()) {
5515 ResultType = S.Context.getConstantArrayType(
5516 AT->getElementType(), llvm::APInt(/*numBits=*/32, ArrayLength),
5517 /*SizeExpr=*/nullptr, ArraySizeModifier::Normal, 0);
5519 } else if (auto *RT = Entity.getType()->getAs<RecordType>()) {
5520 bool IsUnion = RT->isUnionType();
5521 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
5523 if (!IsUnion) {
5524 for (const CXXBaseSpecifier &Base : RD->bases()) {
5525 InitializedEntity SubEntity = InitializedEntity::InitializeBase(
5526 S.getASTContext(), &Base, false, &Entity);
5527 if (EntityIndexToProcess < Args.size()) {
5528 // C++ [dcl.init]p16.6.2.2.
5529 // ...the object is initialized is follows. Let e1, ..., en be the
5530 // elements of the aggregate([dcl.init.aggr]). Let x1, ..., xk be
5531 // the elements of the expression-list...The element ei is
5532 // copy-initialized with xi for 1 <= i <= k.
5533 Expr *E = Args[EntityIndexToProcess];
5534 InitializationKind SubKind = InitializationKind::CreateForInit(
5535 E->getExprLoc(), /*isDirectInit=*/false, E);
5536 if (!HandleInitializedEntity(SubEntity, SubKind, E))
5537 return;
5538 } else {
5539 // We've processed all of the args, but there are still base classes
5540 // that have to be initialized.
5541 // C++ [dcl.init]p17.6.2.2
5542 // The remaining elements...otherwise are value initialzed
5543 InitializationKind SubKind = InitializationKind::CreateValue(
5544 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(),
5545 /*IsImplicit=*/true);
5546 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
5547 return;
5549 EntityIndexToProcess++;
5553 for (FieldDecl *FD : RD->fields()) {
5554 // Unnamed bitfields should not be initialized at all, either with an arg
5555 // or by default.
5556 if (FD->isUnnamedBitfield())
5557 continue;
5559 InitializedEntity SubEntity =
5560 InitializedEntity::InitializeMemberFromParenAggInit(FD);
5562 if (EntityIndexToProcess < Args.size()) {
5563 // ...The element ei is copy-initialized with xi for 1 <= i <= k.
5564 Expr *E = Args[EntityIndexToProcess];
5566 // Incomplete array types indicate flexible array members. Do not allow
5567 // paren list initializations of structs with these members, as GCC
5568 // doesn't either.
5569 if (FD->getType()->isIncompleteArrayType()) {
5570 if (!VerifyOnly) {
5571 S.Diag(E->getBeginLoc(), diag::err_flexible_array_init)
5572 << SourceRange(E->getBeginLoc(), E->getEndLoc());
5573 S.Diag(FD->getLocation(), diag::note_flexible_array_member) << FD;
5575 Sequence.SetFailed(
5576 InitializationSequence::FK_ParenthesizedListInitFailed);
5577 return;
5580 InitializationKind SubKind = InitializationKind::CreateForInit(
5581 E->getExprLoc(), /*isDirectInit=*/false, E);
5582 if (!HandleInitializedEntity(SubEntity, SubKind, E))
5583 return;
5585 // Unions should have only one initializer expression, so we bail out
5586 // after processing the first field. If there are more initializers then
5587 // it will be caught when we later check whether EntityIndexToProcess is
5588 // less than Args.size();
5589 if (IsUnion) {
5590 InitializedFieldInUnion = FD;
5591 EntityIndexToProcess = 1;
5592 break;
5594 } else {
5595 // We've processed all of the args, but there are still members that
5596 // have to be initialized.
5597 if (FD->hasInClassInitializer()) {
5598 if (!VerifyOnly) {
5599 // C++ [dcl.init]p16.6.2.2
5600 // The remaining elements are initialized with their default
5601 // member initializers, if any
5602 ExprResult DIE = S.BuildCXXDefaultInitExpr(
5603 Kind.getParenOrBraceRange().getEnd(), FD);
5604 if (DIE.isInvalid())
5605 return;
5606 S.checkInitializerLifetime(SubEntity, DIE.get());
5607 InitExprs.push_back(DIE.get());
5609 } else {
5610 // C++ [dcl.init]p17.6.2.2
5611 // The remaining elements...otherwise are value initialzed
5612 if (FD->getType()->isReferenceType()) {
5613 Sequence.SetFailed(
5614 InitializationSequence::FK_ParenthesizedListInitFailed);
5615 if (!VerifyOnly) {
5616 SourceRange SR = Kind.getParenOrBraceRange();
5617 S.Diag(SR.getEnd(), diag::err_init_reference_member_uninitialized)
5618 << FD->getType() << SR;
5619 S.Diag(FD->getLocation(), diag::note_uninit_reference_member);
5621 return;
5623 InitializationKind SubKind = InitializationKind::CreateValue(
5624 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
5625 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
5626 return;
5629 EntityIndexToProcess++;
5631 ResultType = Entity.getType();
5634 // Not all of the args have been processed, so there must've been more args
5635 // than were required to initialize the element.
5636 if (EntityIndexToProcess < Args.size()) {
5637 Sequence.SetFailed(InitializationSequence::FK_ParenthesizedListInitFailed);
5638 if (!VerifyOnly) {
5639 QualType T = Entity.getType();
5640 int InitKind = T->isArrayType() ? 0 : T->isUnionType() ? 3 : 4;
5641 SourceRange ExcessInitSR(Args[EntityIndexToProcess]->getBeginLoc(),
5642 Args.back()->getEndLoc());
5643 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5644 << InitKind << ExcessInitSR;
5646 return;
5649 if (VerifyOnly) {
5650 Sequence.setSequenceKind(InitializationSequence::NormalSequence);
5651 Sequence.AddParenthesizedListInitStep(Entity.getType());
5652 } else if (Result) {
5653 SourceRange SR = Kind.getParenOrBraceRange();
5654 auto *CPLIE = CXXParenListInitExpr::Create(
5655 S.getASTContext(), InitExprs, ResultType, Args.size(),
5656 Kind.getLocation(), SR.getBegin(), SR.getEnd());
5657 if (ArrayFiller)
5658 CPLIE->setArrayFiller(ArrayFiller);
5659 if (InitializedFieldInUnion)
5660 CPLIE->setInitializedFieldInUnion(InitializedFieldInUnion);
5661 *Result = CPLIE;
5662 S.Diag(Kind.getLocation(),
5663 diag::warn_cxx17_compat_aggregate_init_paren_list)
5664 << Kind.getLocation() << SR << ResultType;
5668 /// Attempt a user-defined conversion between two types (C++ [dcl.init]),
5669 /// which enumerates all conversion functions and performs overload resolution
5670 /// to select the best.
5671 static void TryUserDefinedConversion(Sema &S,
5672 QualType DestType,
5673 const InitializationKind &Kind,
5674 Expr *Initializer,
5675 InitializationSequence &Sequence,
5676 bool TopLevelOfInitList) {
5677 assert(!DestType->isReferenceType() && "References are handled elsewhere");
5678 QualType SourceType = Initializer->getType();
5679 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
5680 "Must have a class type to perform a user-defined conversion");
5682 // Build the candidate set directly in the initialization sequence
5683 // structure, so that it will persist if we fail.
5684 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
5685 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
5686 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
5688 // Determine whether we are allowed to call explicit constructors or
5689 // explicit conversion operators.
5690 bool AllowExplicit = Kind.AllowExplicit();
5692 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
5693 // The type we're converting to is a class type. Enumerate its constructors
5694 // to see if there is a suitable conversion.
5695 CXXRecordDecl *DestRecordDecl
5696 = cast<CXXRecordDecl>(DestRecordType->getDecl());
5698 // Try to complete the type we're converting to.
5699 if (S.isCompleteType(Kind.getLocation(), DestType)) {
5700 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
5701 auto Info = getConstructorInfo(D);
5702 if (!Info.Constructor)
5703 continue;
5705 if (!Info.Constructor->isInvalidDecl() &&
5706 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
5707 if (Info.ConstructorTmpl)
5708 S.AddTemplateOverloadCandidate(
5709 Info.ConstructorTmpl, Info.FoundDecl,
5710 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
5711 /*SuppressUserConversions=*/true,
5712 /*PartialOverloading*/ false, AllowExplicit);
5713 else
5714 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
5715 Initializer, CandidateSet,
5716 /*SuppressUserConversions=*/true,
5717 /*PartialOverloading*/ false, AllowExplicit);
5723 SourceLocation DeclLoc = Initializer->getBeginLoc();
5725 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
5726 // The type we're converting from is a class type, enumerate its conversion
5727 // functions.
5729 // We can only enumerate the conversion functions for a complete type; if
5730 // the type isn't complete, simply skip this step.
5731 if (S.isCompleteType(DeclLoc, SourceType)) {
5732 CXXRecordDecl *SourceRecordDecl
5733 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
5735 const auto &Conversions =
5736 SourceRecordDecl->getVisibleConversionFunctions();
5737 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5738 NamedDecl *D = *I;
5739 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
5740 if (isa<UsingShadowDecl>(D))
5741 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5743 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5744 CXXConversionDecl *Conv;
5745 if (ConvTemplate)
5746 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5747 else
5748 Conv = cast<CXXConversionDecl>(D);
5750 if (ConvTemplate)
5751 S.AddTemplateConversionCandidate(
5752 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
5753 CandidateSet, AllowExplicit, AllowExplicit);
5754 else
5755 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
5756 DestType, CandidateSet, AllowExplicit,
5757 AllowExplicit);
5762 // Perform overload resolution. If it fails, return the failed result.
5763 OverloadCandidateSet::iterator Best;
5764 if (OverloadingResult Result
5765 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5766 Sequence.SetOverloadFailure(
5767 InitializationSequence::FK_UserConversionOverloadFailed, Result);
5769 // [class.copy.elision]p3:
5770 // In some copy-initialization contexts, a two-stage overload resolution
5771 // is performed.
5772 // If the first overload resolution selects a deleted function, we also
5773 // need the initialization sequence to decide whether to perform the second
5774 // overload resolution.
5775 if (!(Result == OR_Deleted &&
5776 Kind.getKind() == InitializationKind::IK_Copy))
5777 return;
5780 FunctionDecl *Function = Best->Function;
5781 Function->setReferenced();
5782 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5784 if (isa<CXXConstructorDecl>(Function)) {
5785 // Add the user-defined conversion step. Any cv-qualification conversion is
5786 // subsumed by the initialization. Per DR5, the created temporary is of the
5787 // cv-unqualified type of the destination.
5788 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
5789 DestType.getUnqualifiedType(),
5790 HadMultipleCandidates);
5792 // C++14 and before:
5793 // - if the function is a constructor, the call initializes a temporary
5794 // of the cv-unqualified version of the destination type. The [...]
5795 // temporary [...] is then used to direct-initialize, according to the
5796 // rules above, the object that is the destination of the
5797 // copy-initialization.
5798 // Note that this just performs a simple object copy from the temporary.
5800 // C++17:
5801 // - if the function is a constructor, the call is a prvalue of the
5802 // cv-unqualified version of the destination type whose return object
5803 // is initialized by the constructor. The call is used to
5804 // direct-initialize, according to the rules above, the object that
5805 // is the destination of the copy-initialization.
5806 // Therefore we need to do nothing further.
5808 // FIXME: Mark this copy as extraneous.
5809 if (!S.getLangOpts().CPlusPlus17)
5810 Sequence.AddFinalCopy(DestType);
5811 else if (DestType.hasQualifiers())
5812 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
5813 return;
5816 // Add the user-defined conversion step that calls the conversion function.
5817 QualType ConvType = Function->getCallResultType();
5818 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
5819 HadMultipleCandidates);
5821 if (ConvType->getAs<RecordType>()) {
5822 // The call is used to direct-initialize [...] the object that is the
5823 // destination of the copy-initialization.
5825 // In C++17, this does not call a constructor if we enter /17.6.1:
5826 // - If the initializer expression is a prvalue and the cv-unqualified
5827 // version of the source type is the same as the class of the
5828 // destination [... do not make an extra copy]
5830 // FIXME: Mark this copy as extraneous.
5831 if (!S.getLangOpts().CPlusPlus17 ||
5832 Function->getReturnType()->isReferenceType() ||
5833 !S.Context.hasSameUnqualifiedType(ConvType, DestType))
5834 Sequence.AddFinalCopy(DestType);
5835 else if (!S.Context.hasSameType(ConvType, DestType))
5836 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
5837 return;
5840 // If the conversion following the call to the conversion function
5841 // is interesting, add it as a separate step.
5842 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
5843 Best->FinalConversion.Third) {
5844 ImplicitConversionSequence ICS;
5845 ICS.setStandard();
5846 ICS.Standard = Best->FinalConversion;
5847 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
5851 /// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
5852 /// a function with a pointer return type contains a 'return false;' statement.
5853 /// In C++11, 'false' is not a null pointer, so this breaks the build of any
5854 /// code using that header.
5856 /// Work around this by treating 'return false;' as zero-initializing the result
5857 /// if it's used in a pointer-returning function in a system header.
5858 static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
5859 const InitializedEntity &Entity,
5860 const Expr *Init) {
5861 return S.getLangOpts().CPlusPlus11 &&
5862 Entity.getKind() == InitializedEntity::EK_Result &&
5863 Entity.getType()->isPointerType() &&
5864 isa<CXXBoolLiteralExpr>(Init) &&
5865 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
5866 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
5869 /// The non-zero enum values here are indexes into diagnostic alternatives.
5870 enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
5872 /// Determines whether this expression is an acceptable ICR source.
5873 static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
5874 bool isAddressOf, bool &isWeakAccess) {
5875 // Skip parens.
5876 e = e->IgnoreParens();
5878 // Skip address-of nodes.
5879 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
5880 if (op->getOpcode() == UO_AddrOf)
5881 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
5882 isWeakAccess);
5884 // Skip certain casts.
5885 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
5886 switch (ce->getCastKind()) {
5887 case CK_Dependent:
5888 case CK_BitCast:
5889 case CK_LValueBitCast:
5890 case CK_NoOp:
5891 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
5893 case CK_ArrayToPointerDecay:
5894 return IIK_nonscalar;
5896 case CK_NullToPointer:
5897 return IIK_okay;
5899 default:
5900 break;
5903 // If we have a declaration reference, it had better be a local variable.
5904 } else if (isa<DeclRefExpr>(e)) {
5905 // set isWeakAccess to true, to mean that there will be an implicit
5906 // load which requires a cleanup.
5907 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
5908 isWeakAccess = true;
5910 if (!isAddressOf) return IIK_nonlocal;
5912 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
5913 if (!var) return IIK_nonlocal;
5915 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
5917 // If we have a conditional operator, check both sides.
5918 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
5919 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
5920 isWeakAccess))
5921 return iik;
5923 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
5925 // These are never scalar.
5926 } else if (isa<ArraySubscriptExpr>(e)) {
5927 return IIK_nonscalar;
5929 // Otherwise, it needs to be a null pointer constant.
5930 } else {
5931 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
5932 ? IIK_okay : IIK_nonlocal);
5935 return IIK_nonlocal;
5938 /// Check whether the given expression is a valid operand for an
5939 /// indirect copy/restore.
5940 static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
5941 assert(src->isPRValue());
5942 bool isWeakAccess = false;
5943 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
5944 // If isWeakAccess to true, there will be an implicit
5945 // load which requires a cleanup.
5946 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
5947 S.Cleanup.setExprNeedsCleanups(true);
5949 if (iik == IIK_okay) return;
5951 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
5952 << ((unsigned) iik - 1) // shift index into diagnostic explanations
5953 << src->getSourceRange();
5956 /// Determine whether we have compatible array types for the
5957 /// purposes of GNU by-copy array initialization.
5958 static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
5959 const ArrayType *Source) {
5960 // If the source and destination array types are equivalent, we're
5961 // done.
5962 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
5963 return true;
5965 // Make sure that the element types are the same.
5966 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
5967 return false;
5969 // The only mismatch we allow is when the destination is an
5970 // incomplete array type and the source is a constant array type.
5971 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
5974 static bool tryObjCWritebackConversion(Sema &S,
5975 InitializationSequence &Sequence,
5976 const InitializedEntity &Entity,
5977 Expr *Initializer) {
5978 bool ArrayDecay = false;
5979 QualType ArgType = Initializer->getType();
5980 QualType ArgPointee;
5981 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
5982 ArrayDecay = true;
5983 ArgPointee = ArgArrayType->getElementType();
5984 ArgType = S.Context.getPointerType(ArgPointee);
5987 // Handle write-back conversion.
5988 QualType ConvertedArgType;
5989 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
5990 ConvertedArgType))
5991 return false;
5993 // We should copy unless we're passing to an argument explicitly
5994 // marked 'out'.
5995 bool ShouldCopy = true;
5996 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5997 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5999 // Do we need an lvalue conversion?
6000 if (ArrayDecay || Initializer->isGLValue()) {
6001 ImplicitConversionSequence ICS;
6002 ICS.setStandard();
6003 ICS.Standard.setAsIdentityConversion();
6005 QualType ResultType;
6006 if (ArrayDecay) {
6007 ICS.Standard.First = ICK_Array_To_Pointer;
6008 ResultType = S.Context.getPointerType(ArgPointee);
6009 } else {
6010 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
6011 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
6014 Sequence.AddConversionSequenceStep(ICS, ResultType);
6017 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
6018 return true;
6021 static bool TryOCLSamplerInitialization(Sema &S,
6022 InitializationSequence &Sequence,
6023 QualType DestType,
6024 Expr *Initializer) {
6025 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
6026 (!Initializer->isIntegerConstantExpr(S.Context) &&
6027 !Initializer->getType()->isSamplerT()))
6028 return false;
6030 Sequence.AddOCLSamplerInitStep(DestType);
6031 return true;
6034 static bool IsZeroInitializer(Expr *Initializer, Sema &S) {
6035 return Initializer->isIntegerConstantExpr(S.getASTContext()) &&
6036 (Initializer->EvaluateKnownConstInt(S.getASTContext()) == 0);
6039 static bool TryOCLZeroOpaqueTypeInitialization(Sema &S,
6040 InitializationSequence &Sequence,
6041 QualType DestType,
6042 Expr *Initializer) {
6043 if (!S.getLangOpts().OpenCL)
6044 return false;
6047 // OpenCL 1.2 spec, s6.12.10
6049 // The event argument can also be used to associate the
6050 // async_work_group_copy with a previous async copy allowing
6051 // an event to be shared by multiple async copies; otherwise
6052 // event should be zero.
6054 if (DestType->isEventT() || DestType->isQueueT()) {
6055 if (!IsZeroInitializer(Initializer, S))
6056 return false;
6058 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
6059 return true;
6062 // We should allow zero initialization for all types defined in the
6063 // cl_intel_device_side_avc_motion_estimation extension, except
6064 // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t.
6065 if (S.getOpenCLOptions().isAvailableOption(
6066 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()) &&
6067 DestType->isOCLIntelSubgroupAVCType()) {
6068 if (DestType->isOCLIntelSubgroupAVCMcePayloadType() ||
6069 DestType->isOCLIntelSubgroupAVCMceResultType())
6070 return false;
6071 if (!IsZeroInitializer(Initializer, S))
6072 return false;
6074 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
6075 return true;
6078 return false;
6081 InitializationSequence::InitializationSequence(
6082 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
6083 MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid)
6084 : FailedOverloadResult(OR_Success),
6085 FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
6086 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
6087 TreatUnavailableAsInvalid);
6090 /// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
6091 /// address of that function, this returns true. Otherwise, it returns false.
6092 static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
6093 auto *DRE = dyn_cast<DeclRefExpr>(E);
6094 if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
6095 return false;
6097 return !S.checkAddressOfFunctionIsAvailable(
6098 cast<FunctionDecl>(DRE->getDecl()));
6101 /// Determine whether we can perform an elementwise array copy for this kind
6102 /// of entity.
6103 static bool canPerformArrayCopy(const InitializedEntity &Entity) {
6104 switch (Entity.getKind()) {
6105 case InitializedEntity::EK_LambdaCapture:
6106 // C++ [expr.prim.lambda]p24:
6107 // For array members, the array elements are direct-initialized in
6108 // increasing subscript order.
6109 return true;
6111 case InitializedEntity::EK_Variable:
6112 // C++ [dcl.decomp]p1:
6113 // [...] each element is copy-initialized or direct-initialized from the
6114 // corresponding element of the assignment-expression [...]
6115 return isa<DecompositionDecl>(Entity.getDecl());
6117 case InitializedEntity::EK_Member:
6118 // C++ [class.copy.ctor]p14:
6119 // - if the member is an array, each element is direct-initialized with
6120 // the corresponding subobject of x
6121 return Entity.isImplicitMemberInitializer();
6123 case InitializedEntity::EK_ArrayElement:
6124 // All the above cases are intended to apply recursively, even though none
6125 // of them actually say that.
6126 if (auto *E = Entity.getParent())
6127 return canPerformArrayCopy(*E);
6128 break;
6130 default:
6131 break;
6134 return false;
6137 void InitializationSequence::InitializeFrom(Sema &S,
6138 const InitializedEntity &Entity,
6139 const InitializationKind &Kind,
6140 MultiExprArg Args,
6141 bool TopLevelOfInitList,
6142 bool TreatUnavailableAsInvalid) {
6143 ASTContext &Context = S.Context;
6145 // Eliminate non-overload placeholder types in the arguments. We
6146 // need to do this before checking whether types are dependent
6147 // because lowering a pseudo-object expression might well give us
6148 // something of dependent type.
6149 for (unsigned I = 0, E = Args.size(); I != E; ++I)
6150 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
6151 // FIXME: should we be doing this here?
6152 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
6153 if (result.isInvalid()) {
6154 SetFailed(FK_PlaceholderType);
6155 return;
6157 Args[I] = result.get();
6160 // C++0x [dcl.init]p16:
6161 // The semantics of initializers are as follows. The destination type is
6162 // the type of the object or reference being initialized and the source
6163 // type is the type of the initializer expression. The source type is not
6164 // defined when the initializer is a braced-init-list or when it is a
6165 // parenthesized list of expressions.
6166 QualType DestType = Entity.getType();
6168 if (DestType->isDependentType() ||
6169 Expr::hasAnyTypeDependentArguments(Args)) {
6170 SequenceKind = DependentSequence;
6171 return;
6174 // Almost everything is a normal sequence.
6175 setSequenceKind(NormalSequence);
6177 QualType SourceType;
6178 Expr *Initializer = nullptr;
6179 if (Args.size() == 1) {
6180 Initializer = Args[0];
6181 if (S.getLangOpts().ObjC) {
6182 if (S.CheckObjCBridgeRelatedConversions(Initializer->getBeginLoc(),
6183 DestType, Initializer->getType(),
6184 Initializer) ||
6185 S.CheckConversionToObjCLiteral(DestType, Initializer))
6186 Args[0] = Initializer;
6188 if (!isa<InitListExpr>(Initializer))
6189 SourceType = Initializer->getType();
6192 // - If the initializer is a (non-parenthesized) braced-init-list, the
6193 // object is list-initialized (8.5.4).
6194 if (Kind.getKind() != InitializationKind::IK_Direct) {
6195 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
6196 TryListInitialization(S, Entity, Kind, InitList, *this,
6197 TreatUnavailableAsInvalid);
6198 return;
6202 // - If the destination type is a reference type, see 8.5.3.
6203 if (DestType->isReferenceType()) {
6204 // C++0x [dcl.init.ref]p1:
6205 // A variable declared to be a T& or T&&, that is, "reference to type T"
6206 // (8.3.2), shall be initialized by an object, or function, of type T or
6207 // by an object that can be converted into a T.
6208 // (Therefore, multiple arguments are not permitted.)
6209 if (Args.size() != 1)
6210 SetFailed(FK_TooManyInitsForReference);
6211 // C++17 [dcl.init.ref]p5:
6212 // A reference [...] is initialized by an expression [...] as follows:
6213 // If the initializer is not an expression, presumably we should reject,
6214 // but the standard fails to actually say so.
6215 else if (isa<InitListExpr>(Args[0]))
6216 SetFailed(FK_ParenthesizedListInitForReference);
6217 else
6218 TryReferenceInitialization(S, Entity, Kind, Args[0], *this,
6219 TopLevelOfInitList);
6220 return;
6223 // - If the initializer is (), the object is value-initialized.
6224 if (Kind.getKind() == InitializationKind::IK_Value ||
6225 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
6226 TryValueInitialization(S, Entity, Kind, *this);
6227 return;
6230 // Handle default initialization.
6231 if (Kind.getKind() == InitializationKind::IK_Default) {
6232 TryDefaultInitialization(S, Entity, Kind, *this);
6233 return;
6236 // - If the destination type is an array of characters, an array of
6237 // char16_t, an array of char32_t, or an array of wchar_t, and the
6238 // initializer is a string literal, see 8.5.2.
6239 // - Otherwise, if the destination type is an array, the program is
6240 // ill-formed.
6241 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
6242 if (Initializer && isa<VariableArrayType>(DestAT)) {
6243 SetFailed(FK_VariableLengthArrayHasInitializer);
6244 return;
6247 if (Initializer) {
6248 switch (IsStringInit(Initializer, DestAT, Context)) {
6249 case SIF_None:
6250 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
6251 return;
6252 case SIF_NarrowStringIntoWideChar:
6253 SetFailed(FK_NarrowStringIntoWideCharArray);
6254 return;
6255 case SIF_WideStringIntoChar:
6256 SetFailed(FK_WideStringIntoCharArray);
6257 return;
6258 case SIF_IncompatWideStringIntoWideChar:
6259 SetFailed(FK_IncompatWideStringIntoWideChar);
6260 return;
6261 case SIF_PlainStringIntoUTF8Char:
6262 SetFailed(FK_PlainStringIntoUTF8Char);
6263 return;
6264 case SIF_UTF8StringIntoPlainChar:
6265 SetFailed(FK_UTF8StringIntoPlainChar);
6266 return;
6267 case SIF_Other:
6268 break;
6272 // Some kinds of initialization permit an array to be initialized from
6273 // another array of the same type, and perform elementwise initialization.
6274 if (Initializer && isa<ConstantArrayType>(DestAT) &&
6275 S.Context.hasSameUnqualifiedType(Initializer->getType(),
6276 Entity.getType()) &&
6277 canPerformArrayCopy(Entity)) {
6278 // If source is a prvalue, use it directly.
6279 if (Initializer->isPRValue()) {
6280 AddArrayInitStep(DestType, /*IsGNUExtension*/false);
6281 return;
6284 // Emit element-at-a-time copy loop.
6285 InitializedEntity Element =
6286 InitializedEntity::InitializeElement(S.Context, 0, Entity);
6287 QualType InitEltT =
6288 Context.getAsArrayType(Initializer->getType())->getElementType();
6289 OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
6290 Initializer->getValueKind(),
6291 Initializer->getObjectKind());
6292 Expr *OVEAsExpr = &OVE;
6293 InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList,
6294 TreatUnavailableAsInvalid);
6295 if (!Failed())
6296 AddArrayInitLoopStep(Entity.getType(), InitEltT);
6297 return;
6300 // Note: as an GNU C extension, we allow initialization of an
6301 // array from a compound literal that creates an array of the same
6302 // type, so long as the initializer has no side effects.
6303 if (!S.getLangOpts().CPlusPlus && Initializer &&
6304 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
6305 Initializer->getType()->isArrayType()) {
6306 const ArrayType *SourceAT
6307 = Context.getAsArrayType(Initializer->getType());
6308 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
6309 SetFailed(FK_ArrayTypeMismatch);
6310 else if (Initializer->HasSideEffects(S.Context))
6311 SetFailed(FK_NonConstantArrayInit);
6312 else {
6313 AddArrayInitStep(DestType, /*IsGNUExtension*/true);
6316 // Note: as a GNU C++ extension, we allow list-initialization of a
6317 // class member of array type from a parenthesized initializer list.
6318 else if (S.getLangOpts().CPlusPlus &&
6319 Entity.getKind() == InitializedEntity::EK_Member &&
6320 Initializer && isa<InitListExpr>(Initializer)) {
6321 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
6322 *this, TreatUnavailableAsInvalid);
6323 AddParenthesizedArrayInitStep(DestType);
6324 } else if (S.getLangOpts().CPlusPlus20 && !TopLevelOfInitList &&
6325 Kind.getKind() == InitializationKind::IK_Direct)
6326 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
6327 /*VerifyOnly=*/true);
6328 else if (DestAT->getElementType()->isCharType())
6329 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
6330 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
6331 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
6332 else
6333 SetFailed(FK_ArrayNeedsInitList);
6335 return;
6338 // Determine whether we should consider writeback conversions for
6339 // Objective-C ARC.
6340 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
6341 Entity.isParameterKind();
6343 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
6344 return;
6346 // We're at the end of the line for C: it's either a write-back conversion
6347 // or it's a C assignment. There's no need to check anything else.
6348 if (!S.getLangOpts().CPlusPlus) {
6349 assert(Initializer && "Initializer must be non-null");
6350 // If allowed, check whether this is an Objective-C writeback conversion.
6351 if (allowObjCWritebackConversion &&
6352 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
6353 return;
6356 if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer))
6357 return;
6359 // Handle initialization in C
6360 AddCAssignmentStep(DestType);
6361 MaybeProduceObjCObject(S, *this, Entity);
6362 return;
6365 assert(S.getLangOpts().CPlusPlus);
6367 // - If the destination type is a (possibly cv-qualified) class type:
6368 if (DestType->isRecordType()) {
6369 // - If the initialization is direct-initialization, or if it is
6370 // copy-initialization where the cv-unqualified version of the
6371 // source type is the same class as, or a derived class of, the
6372 // class of the destination, constructors are considered. [...]
6373 if (Kind.getKind() == InitializationKind::IK_Direct ||
6374 (Kind.getKind() == InitializationKind::IK_Copy &&
6375 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
6376 (Initializer && S.IsDerivedFrom(Initializer->getBeginLoc(),
6377 SourceType, DestType))))) {
6378 TryConstructorInitialization(S, Entity, Kind, Args, DestType, DestType,
6379 *this);
6381 // We fall back to the "no matching constructor" path if the
6382 // failed candidate set has functions other than the three default
6383 // constructors. For example, conversion function.
6384 if (const auto *RD =
6385 dyn_cast<CXXRecordDecl>(DestType->getAs<RecordType>()->getDecl());
6386 // In general, we should call isCompleteType for RD to check its
6387 // completeness, we don't call it here as it was already called in the
6388 // above TryConstructorInitialization.
6389 S.getLangOpts().CPlusPlus20 && RD && RD->hasDefinition() &&
6390 RD->isAggregate() && Failed() &&
6391 getFailureKind() == FK_ConstructorOverloadFailed) {
6392 // Do not attempt paren list initialization if overload resolution
6393 // resolves to a deleted function .
6395 // We may reach this condition if we have a union wrapping a class with
6396 // a non-trivial copy or move constructor and we call one of those two
6397 // constructors. The union is an aggregate, but the matched constructor
6398 // is implicitly deleted, so we need to prevent aggregate initialization
6399 // (otherwise, it'll attempt aggregate initialization by initializing
6400 // the first element with a reference to the union).
6401 OverloadCandidateSet::iterator Best;
6402 OverloadingResult OR = getFailedCandidateSet().BestViableFunction(
6403 S, Kind.getLocation(), Best);
6404 if (OR != OverloadingResult::OR_Deleted) {
6405 // C++20 [dcl.init] 17.6.2.2:
6406 // - Otherwise, if no constructor is viable, the destination type is
6407 // an
6408 // aggregate class, and the initializer is a parenthesized
6409 // expression-list.
6410 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
6411 /*VerifyOnly=*/true);
6414 } else {
6415 // - Otherwise (i.e., for the remaining copy-initialization cases),
6416 // user-defined conversion sequences that can convert from the
6417 // source type to the destination type or (when a conversion
6418 // function is used) to a derived class thereof are enumerated as
6419 // described in 13.3.1.4, and the best one is chosen through
6420 // overload resolution (13.3).
6421 assert(Initializer && "Initializer must be non-null");
6422 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
6423 TopLevelOfInitList);
6425 return;
6428 assert(Args.size() >= 1 && "Zero-argument case handled above");
6430 // For HLSL ext vector types we allow list initialization behavior for C++
6431 // constructor syntax. This is accomplished by converting initialization
6432 // arguments an InitListExpr late.
6433 if (S.getLangOpts().HLSL && DestType->isExtVectorType() &&
6434 (SourceType.isNull() ||
6435 !Context.hasSameUnqualifiedType(SourceType, DestType))) {
6437 llvm::SmallVector<Expr *> InitArgs;
6438 for (auto *Arg : Args) {
6439 if (Arg->getType()->isExtVectorType()) {
6440 const auto *VTy = Arg->getType()->castAs<ExtVectorType>();
6441 unsigned Elm = VTy->getNumElements();
6442 for (unsigned Idx = 0; Idx < Elm; ++Idx) {
6443 InitArgs.emplace_back(new (Context) ArraySubscriptExpr(
6444 Arg,
6445 IntegerLiteral::Create(
6446 Context, llvm::APInt(Context.getIntWidth(Context.IntTy), Idx),
6447 Context.IntTy, SourceLocation()),
6448 VTy->getElementType(), Arg->getValueKind(), Arg->getObjectKind(),
6449 SourceLocation()));
6451 } else
6452 InitArgs.emplace_back(Arg);
6454 InitListExpr *ILE = new (Context) InitListExpr(
6455 S.getASTContext(), SourceLocation(), InitArgs, SourceLocation());
6456 Args[0] = ILE;
6457 AddListInitializationStep(DestType);
6458 return;
6461 // The remaining cases all need a source type.
6462 if (Args.size() > 1) {
6463 SetFailed(FK_TooManyInitsForScalar);
6464 return;
6465 } else if (isa<InitListExpr>(Args[0])) {
6466 SetFailed(FK_ParenthesizedListInitForScalar);
6467 return;
6470 // - Otherwise, if the source type is a (possibly cv-qualified) class
6471 // type, conversion functions are considered.
6472 if (!SourceType.isNull() && SourceType->isRecordType()) {
6473 assert(Initializer && "Initializer must be non-null");
6474 // For a conversion to _Atomic(T) from either T or a class type derived
6475 // from T, initialize the T object then convert to _Atomic type.
6476 bool NeedAtomicConversion = false;
6477 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
6478 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
6479 S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType,
6480 Atomic->getValueType())) {
6481 DestType = Atomic->getValueType();
6482 NeedAtomicConversion = true;
6486 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
6487 TopLevelOfInitList);
6488 MaybeProduceObjCObject(S, *this, Entity);
6489 if (!Failed() && NeedAtomicConversion)
6490 AddAtomicConversionStep(Entity.getType());
6491 return;
6494 // - Otherwise, if the initialization is direct-initialization, the source
6495 // type is std::nullptr_t, and the destination type is bool, the initial
6496 // value of the object being initialized is false.
6497 if (!SourceType.isNull() && SourceType->isNullPtrType() &&
6498 DestType->isBooleanType() &&
6499 Kind.getKind() == InitializationKind::IK_Direct) {
6500 AddConversionSequenceStep(
6501 ImplicitConversionSequence::getNullptrToBool(SourceType, DestType,
6502 Initializer->isGLValue()),
6503 DestType);
6504 return;
6507 // - Otherwise, the initial value of the object being initialized is the
6508 // (possibly converted) value of the initializer expression. Standard
6509 // conversions (Clause 4) will be used, if necessary, to convert the
6510 // initializer expression to the cv-unqualified version of the
6511 // destination type; no user-defined conversions are considered.
6513 ImplicitConversionSequence ICS
6514 = S.TryImplicitConversion(Initializer, DestType,
6515 /*SuppressUserConversions*/true,
6516 Sema::AllowedExplicit::None,
6517 /*InOverloadResolution*/ false,
6518 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
6519 allowObjCWritebackConversion);
6521 if (ICS.isStandard() &&
6522 ICS.Standard.Second == ICK_Writeback_Conversion) {
6523 // Objective-C ARC writeback conversion.
6525 // We should copy unless we're passing to an argument explicitly
6526 // marked 'out'.
6527 bool ShouldCopy = true;
6528 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
6529 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
6531 // If there was an lvalue adjustment, add it as a separate conversion.
6532 if (ICS.Standard.First == ICK_Array_To_Pointer ||
6533 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6534 ImplicitConversionSequence LvalueICS;
6535 LvalueICS.setStandard();
6536 LvalueICS.Standard.setAsIdentityConversion();
6537 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
6538 LvalueICS.Standard.First = ICS.Standard.First;
6539 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
6542 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
6543 } else if (ICS.isBad()) {
6544 DeclAccessPair dap;
6545 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
6546 AddZeroInitializationStep(Entity.getType());
6547 } else if (Initializer->getType() == Context.OverloadTy &&
6548 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
6549 false, dap))
6550 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
6551 else if (Initializer->getType()->isFunctionType() &&
6552 isExprAnUnaddressableFunction(S, Initializer))
6553 SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction);
6554 else
6555 SetFailed(InitializationSequence::FK_ConversionFailed);
6556 } else {
6557 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
6559 MaybeProduceObjCObject(S, *this, Entity);
6563 InitializationSequence::~InitializationSequence() {
6564 for (auto &S : Steps)
6565 S.Destroy();
6568 //===----------------------------------------------------------------------===//
6569 // Perform initialization
6570 //===----------------------------------------------------------------------===//
6571 static Sema::AssignmentAction
6572 getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
6573 switch(Entity.getKind()) {
6574 case InitializedEntity::EK_Variable:
6575 case InitializedEntity::EK_New:
6576 case InitializedEntity::EK_Exception:
6577 case InitializedEntity::EK_Base:
6578 case InitializedEntity::EK_Delegating:
6579 return Sema::AA_Initializing;
6581 case InitializedEntity::EK_Parameter:
6582 if (Entity.getDecl() &&
6583 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
6584 return Sema::AA_Sending;
6586 return Sema::AA_Passing;
6588 case InitializedEntity::EK_Parameter_CF_Audited:
6589 if (Entity.getDecl() &&
6590 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
6591 return Sema::AA_Sending;
6593 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
6595 case InitializedEntity::EK_Result:
6596 case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right.
6597 return Sema::AA_Returning;
6599 case InitializedEntity::EK_Temporary:
6600 case InitializedEntity::EK_RelatedResult:
6601 // FIXME: Can we tell apart casting vs. converting?
6602 return Sema::AA_Casting;
6604 case InitializedEntity::EK_TemplateParameter:
6605 // This is really initialization, but refer to it as conversion for
6606 // consistency with CheckConvertedConstantExpression.
6607 return Sema::AA_Converting;
6609 case InitializedEntity::EK_Member:
6610 case InitializedEntity::EK_ParenAggInitMember:
6611 case InitializedEntity::EK_Binding:
6612 case InitializedEntity::EK_ArrayElement:
6613 case InitializedEntity::EK_VectorElement:
6614 case InitializedEntity::EK_ComplexElement:
6615 case InitializedEntity::EK_BlockElement:
6616 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
6617 case InitializedEntity::EK_LambdaCapture:
6618 case InitializedEntity::EK_CompoundLiteralInit:
6619 return Sema::AA_Initializing;
6622 llvm_unreachable("Invalid EntityKind!");
6625 /// Whether we should bind a created object as a temporary when
6626 /// initializing the given entity.
6627 static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
6628 switch (Entity.getKind()) {
6629 case InitializedEntity::EK_ArrayElement:
6630 case InitializedEntity::EK_Member:
6631 case InitializedEntity::EK_ParenAggInitMember:
6632 case InitializedEntity::EK_Result:
6633 case InitializedEntity::EK_StmtExprResult:
6634 case InitializedEntity::EK_New:
6635 case InitializedEntity::EK_Variable:
6636 case InitializedEntity::EK_Base:
6637 case InitializedEntity::EK_Delegating:
6638 case InitializedEntity::EK_VectorElement:
6639 case InitializedEntity::EK_ComplexElement:
6640 case InitializedEntity::EK_Exception:
6641 case InitializedEntity::EK_BlockElement:
6642 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
6643 case InitializedEntity::EK_LambdaCapture:
6644 case InitializedEntity::EK_CompoundLiteralInit:
6645 case InitializedEntity::EK_TemplateParameter:
6646 return false;
6648 case InitializedEntity::EK_Parameter:
6649 case InitializedEntity::EK_Parameter_CF_Audited:
6650 case InitializedEntity::EK_Temporary:
6651 case InitializedEntity::EK_RelatedResult:
6652 case InitializedEntity::EK_Binding:
6653 return true;
6656 llvm_unreachable("missed an InitializedEntity kind?");
6659 /// Whether the given entity, when initialized with an object
6660 /// created for that initialization, requires destruction.
6661 static bool shouldDestroyEntity(const InitializedEntity &Entity) {
6662 switch (Entity.getKind()) {
6663 case InitializedEntity::EK_Result:
6664 case InitializedEntity::EK_StmtExprResult:
6665 case InitializedEntity::EK_New:
6666 case InitializedEntity::EK_Base:
6667 case InitializedEntity::EK_Delegating:
6668 case InitializedEntity::EK_VectorElement:
6669 case InitializedEntity::EK_ComplexElement:
6670 case InitializedEntity::EK_BlockElement:
6671 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
6672 case InitializedEntity::EK_LambdaCapture:
6673 return false;
6675 case InitializedEntity::EK_Member:
6676 case InitializedEntity::EK_ParenAggInitMember:
6677 case InitializedEntity::EK_Binding:
6678 case InitializedEntity::EK_Variable:
6679 case InitializedEntity::EK_Parameter:
6680 case InitializedEntity::EK_Parameter_CF_Audited:
6681 case InitializedEntity::EK_TemplateParameter:
6682 case InitializedEntity::EK_Temporary:
6683 case InitializedEntity::EK_ArrayElement:
6684 case InitializedEntity::EK_Exception:
6685 case InitializedEntity::EK_CompoundLiteralInit:
6686 case InitializedEntity::EK_RelatedResult:
6687 return true;
6690 llvm_unreachable("missed an InitializedEntity kind?");
6693 /// Get the location at which initialization diagnostics should appear.
6694 static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
6695 Expr *Initializer) {
6696 switch (Entity.getKind()) {
6697 case InitializedEntity::EK_Result:
6698 case InitializedEntity::EK_StmtExprResult:
6699 return Entity.getReturnLoc();
6701 case InitializedEntity::EK_Exception:
6702 return Entity.getThrowLoc();
6704 case InitializedEntity::EK_Variable:
6705 case InitializedEntity::EK_Binding:
6706 return Entity.getDecl()->getLocation();
6708 case InitializedEntity::EK_LambdaCapture:
6709 return Entity.getCaptureLoc();
6711 case InitializedEntity::EK_ArrayElement:
6712 case InitializedEntity::EK_Member:
6713 case InitializedEntity::EK_ParenAggInitMember:
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_New:
6719 case InitializedEntity::EK_Base:
6720 case InitializedEntity::EK_Delegating:
6721 case InitializedEntity::EK_VectorElement:
6722 case InitializedEntity::EK_ComplexElement:
6723 case InitializedEntity::EK_BlockElement:
6724 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
6725 case InitializedEntity::EK_CompoundLiteralInit:
6726 case InitializedEntity::EK_RelatedResult:
6727 return Initializer->getBeginLoc();
6729 llvm_unreachable("missed an InitializedEntity kind?");
6732 /// Make a (potentially elidable) temporary copy of the object
6733 /// provided by the given initializer by calling the appropriate copy
6734 /// constructor.
6736 /// \param S The Sema object used for type-checking.
6738 /// \param T The type of the temporary object, which must either be
6739 /// the type of the initializer expression or a superclass thereof.
6741 /// \param Entity The entity being initialized.
6743 /// \param CurInit The initializer expression.
6745 /// \param IsExtraneousCopy Whether this is an "extraneous" copy that
6746 /// is permitted in C++03 (but not C++0x) when binding a reference to
6747 /// an rvalue.
6749 /// \returns An expression that copies the initializer expression into
6750 /// a temporary object, or an error expression if a copy could not be
6751 /// created.
6752 static ExprResult CopyObject(Sema &S,
6753 QualType T,
6754 const InitializedEntity &Entity,
6755 ExprResult CurInit,
6756 bool IsExtraneousCopy) {
6757 if (CurInit.isInvalid())
6758 return CurInit;
6759 // Determine which class type we're copying to.
6760 Expr *CurInitExpr = (Expr *)CurInit.get();
6761 CXXRecordDecl *Class = nullptr;
6762 if (const RecordType *Record = T->getAs<RecordType>())
6763 Class = cast<CXXRecordDecl>(Record->getDecl());
6764 if (!Class)
6765 return CurInit;
6767 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
6769 // Make sure that the type we are copying is complete.
6770 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
6771 return CurInit;
6773 // Perform overload resolution using the class's constructors. Per
6774 // C++11 [dcl.init]p16, second bullet for class types, this initialization
6775 // is direct-initialization.
6776 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6777 DeclContext::lookup_result Ctors = S.LookupConstructors(Class);
6779 OverloadCandidateSet::iterator Best;
6780 switch (ResolveConstructorOverload(
6781 S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
6782 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
6783 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
6784 /*RequireActualConstructor=*/false,
6785 /*SecondStepOfCopyInit=*/true)) {
6786 case OR_Success:
6787 break;
6789 case OR_No_Viable_Function:
6790 CandidateSet.NoteCandidates(
6791 PartialDiagnosticAt(
6792 Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext()
6793 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
6794 : diag::err_temp_copy_no_viable)
6795 << (int)Entity.getKind() << CurInitExpr->getType()
6796 << CurInitExpr->getSourceRange()),
6797 S, OCD_AllCandidates, CurInitExpr);
6798 if (!IsExtraneousCopy || S.isSFINAEContext())
6799 return ExprError();
6800 return CurInit;
6802 case OR_Ambiguous:
6803 CandidateSet.NoteCandidates(
6804 PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous)
6805 << (int)Entity.getKind()
6806 << CurInitExpr->getType()
6807 << CurInitExpr->getSourceRange()),
6808 S, OCD_AmbiguousCandidates, CurInitExpr);
6809 return ExprError();
6811 case OR_Deleted:
6812 S.Diag(Loc, diag::err_temp_copy_deleted)
6813 << (int)Entity.getKind() << CurInitExpr->getType()
6814 << CurInitExpr->getSourceRange();
6815 S.NoteDeletedFunction(Best->Function);
6816 return ExprError();
6819 bool HadMultipleCandidates = CandidateSet.size() > 1;
6821 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
6822 SmallVector<Expr*, 8> ConstructorArgs;
6823 CurInit.get(); // Ownership transferred into MultiExprArg, below.
6825 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
6826 IsExtraneousCopy);
6828 if (IsExtraneousCopy) {
6829 // If this is a totally extraneous copy for C++03 reference
6830 // binding purposes, just return the original initialization
6831 // expression. We don't generate an (elided) copy operation here
6832 // because doing so would require us to pass down a flag to avoid
6833 // infinite recursion, where each step adds another extraneous,
6834 // elidable copy.
6836 // Instantiate the default arguments of any extra parameters in
6837 // the selected copy constructor, as if we were going to create a
6838 // proper call to the copy constructor.
6839 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
6840 ParmVarDecl *Parm = Constructor->getParamDecl(I);
6841 if (S.RequireCompleteType(Loc, Parm->getType(),
6842 diag::err_call_incomplete_argument))
6843 break;
6845 // Build the default argument expression; we don't actually care
6846 // if this succeeds or not, because this routine will complain
6847 // if there was a problem.
6848 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
6851 return CurInitExpr;
6854 // Determine the arguments required to actually perform the
6855 // constructor call (we might have derived-to-base conversions, or
6856 // the copy constructor may have default arguments).
6857 if (S.CompleteConstructorCall(Constructor, T, CurInitExpr, Loc,
6858 ConstructorArgs))
6859 return ExprError();
6861 // C++0x [class.copy]p32:
6862 // When certain criteria are met, an implementation is allowed to
6863 // omit the copy/move construction of a class object, even if the
6864 // copy/move constructor and/or destructor for the object have
6865 // side effects. [...]
6866 // - when a temporary class object that has not been bound to a
6867 // reference (12.2) would be copied/moved to a class object
6868 // with the same cv-unqualified type, the copy/move operation
6869 // can be omitted by constructing the temporary object
6870 // directly into the target of the omitted copy/move
6872 // Note that the other three bullets are handled elsewhere. Copy
6873 // elision for return statements and throw expressions are handled as part
6874 // of constructor initialization, while copy elision for exception handlers
6875 // is handled by the run-time.
6877 // FIXME: If the function parameter is not the same type as the temporary, we
6878 // should still be able to elide the copy, but we don't have a way to
6879 // represent in the AST how much should be elided in this case.
6880 bool Elidable =
6881 CurInitExpr->isTemporaryObject(S.Context, Class) &&
6882 S.Context.hasSameUnqualifiedType(
6883 Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
6884 CurInitExpr->getType());
6886 // Actually perform the constructor call.
6887 CurInit = S.BuildCXXConstructExpr(
6888 Loc, T, Best->FoundDecl, Constructor, Elidable, ConstructorArgs,
6889 HadMultipleCandidates,
6890 /*ListInit*/ false,
6891 /*StdInitListInit*/ false,
6892 /*ZeroInit*/ false, CXXConstructionKind::Complete, SourceRange());
6894 // If we're supposed to bind temporaries, do so.
6895 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
6896 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
6897 return CurInit;
6900 /// Check whether elidable copy construction for binding a reference to
6901 /// a temporary would have succeeded if we were building in C++98 mode, for
6902 /// -Wc++98-compat.
6903 static void CheckCXX98CompatAccessibleCopy(Sema &S,
6904 const InitializedEntity &Entity,
6905 Expr *CurInitExpr) {
6906 assert(S.getLangOpts().CPlusPlus11);
6908 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
6909 if (!Record)
6910 return;
6912 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
6913 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
6914 return;
6916 // Find constructors which would have been considered.
6917 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6918 DeclContext::lookup_result Ctors =
6919 S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl()));
6921 // Perform overload resolution.
6922 OverloadCandidateSet::iterator Best;
6923 OverloadingResult OR = ResolveConstructorOverload(
6924 S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
6925 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
6926 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
6927 /*RequireActualConstructor=*/false,
6928 /*SecondStepOfCopyInit=*/true);
6930 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
6931 << OR << (int)Entity.getKind() << CurInitExpr->getType()
6932 << CurInitExpr->getSourceRange();
6934 switch (OR) {
6935 case OR_Success:
6936 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
6937 Best->FoundDecl, Entity, Diag);
6938 // FIXME: Check default arguments as far as that's possible.
6939 break;
6941 case OR_No_Viable_Function:
6942 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
6943 OCD_AllCandidates, CurInitExpr);
6944 break;
6946 case OR_Ambiguous:
6947 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
6948 OCD_AmbiguousCandidates, CurInitExpr);
6949 break;
6951 case OR_Deleted:
6952 S.Diag(Loc, Diag);
6953 S.NoteDeletedFunction(Best->Function);
6954 break;
6958 void InitializationSequence::PrintInitLocationNote(Sema &S,
6959 const InitializedEntity &Entity) {
6960 if (Entity.isParamOrTemplateParamKind() && Entity.getDecl()) {
6961 if (Entity.getDecl()->getLocation().isInvalid())
6962 return;
6964 if (Entity.getDecl()->getDeclName())
6965 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
6966 << Entity.getDecl()->getDeclName();
6967 else
6968 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
6970 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
6971 Entity.getMethodDecl())
6972 S.Diag(Entity.getMethodDecl()->getLocation(),
6973 diag::note_method_return_type_change)
6974 << Entity.getMethodDecl()->getDeclName();
6977 /// Returns true if the parameters describe a constructor initialization of
6978 /// an explicit temporary object, e.g. "Point(x, y)".
6979 static bool isExplicitTemporary(const InitializedEntity &Entity,
6980 const InitializationKind &Kind,
6981 unsigned NumArgs) {
6982 switch (Entity.getKind()) {
6983 case InitializedEntity::EK_Temporary:
6984 case InitializedEntity::EK_CompoundLiteralInit:
6985 case InitializedEntity::EK_RelatedResult:
6986 break;
6987 default:
6988 return false;
6991 switch (Kind.getKind()) {
6992 case InitializationKind::IK_DirectList:
6993 return true;
6994 // FIXME: Hack to work around cast weirdness.
6995 case InitializationKind::IK_Direct:
6996 case InitializationKind::IK_Value:
6997 return NumArgs != 1;
6998 default:
6999 return false;
7003 static ExprResult
7004 PerformConstructorInitialization(Sema &S,
7005 const InitializedEntity &Entity,
7006 const InitializationKind &Kind,
7007 MultiExprArg Args,
7008 const InitializationSequence::Step& Step,
7009 bool &ConstructorInitRequiresZeroInit,
7010 bool IsListInitialization,
7011 bool IsStdInitListInitialization,
7012 SourceLocation LBraceLoc,
7013 SourceLocation RBraceLoc) {
7014 unsigned NumArgs = Args.size();
7015 CXXConstructorDecl *Constructor
7016 = cast<CXXConstructorDecl>(Step.Function.Function);
7017 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
7019 // Build a call to the selected constructor.
7020 SmallVector<Expr*, 8> ConstructorArgs;
7021 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
7022 ? Kind.getEqualLoc()
7023 : Kind.getLocation();
7025 if (Kind.getKind() == InitializationKind::IK_Default) {
7026 // Force even a trivial, implicit default constructor to be
7027 // semantically checked. We do this explicitly because we don't build
7028 // the definition for completely trivial constructors.
7029 assert(Constructor->getParent() && "No parent class for constructor.");
7030 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
7031 Constructor->isTrivial() && !Constructor->isUsed(false)) {
7032 S.runWithSufficientStackSpace(Loc, [&] {
7033 S.DefineImplicitDefaultConstructor(Loc, Constructor);
7038 ExprResult CurInit((Expr *)nullptr);
7040 // C++ [over.match.copy]p1:
7041 // - When initializing a temporary to be bound to the first parameter
7042 // of a constructor that takes a reference to possibly cv-qualified
7043 // T as its first argument, called with a single argument in the
7044 // context of direct-initialization, explicit conversion functions
7045 // are also considered.
7046 bool AllowExplicitConv =
7047 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
7048 hasCopyOrMoveCtorParam(S.Context,
7049 getConstructorInfo(Step.Function.FoundDecl));
7051 // Determine the arguments required to actually perform the constructor
7052 // call.
7053 if (S.CompleteConstructorCall(Constructor, Step.Type, Args, Loc,
7054 ConstructorArgs, AllowExplicitConv,
7055 IsListInitialization))
7056 return ExprError();
7058 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
7059 // An explicitly-constructed temporary, e.g., X(1, 2).
7060 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
7061 return ExprError();
7063 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
7064 if (!TSInfo)
7065 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
7066 SourceRange ParenOrBraceRange =
7067 (Kind.getKind() == InitializationKind::IK_DirectList)
7068 ? SourceRange(LBraceLoc, RBraceLoc)
7069 : Kind.getParenOrBraceRange();
7071 CXXConstructorDecl *CalleeDecl = Constructor;
7072 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
7073 Step.Function.FoundDecl.getDecl())) {
7074 CalleeDecl = S.findInheritingConstructor(Loc, Constructor, Shadow);
7076 S.MarkFunctionReferenced(Loc, CalleeDecl);
7078 CurInit = S.CheckForImmediateInvocation(
7079 CXXTemporaryObjectExpr::Create(
7080 S.Context, CalleeDecl,
7081 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
7082 ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
7083 IsListInitialization, IsStdInitListInitialization,
7084 ConstructorInitRequiresZeroInit),
7085 CalleeDecl);
7086 } else {
7087 CXXConstructionKind ConstructKind = CXXConstructionKind::Complete;
7089 if (Entity.getKind() == InitializedEntity::EK_Base) {
7090 ConstructKind = Entity.getBaseSpecifier()->isVirtual()
7091 ? CXXConstructionKind::VirtualBase
7092 : CXXConstructionKind::NonVirtualBase;
7093 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
7094 ConstructKind = CXXConstructionKind::Delegating;
7097 // Only get the parenthesis or brace range if it is a list initialization or
7098 // direct construction.
7099 SourceRange ParenOrBraceRange;
7100 if (IsListInitialization)
7101 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
7102 else if (Kind.getKind() == InitializationKind::IK_Direct)
7103 ParenOrBraceRange = Kind.getParenOrBraceRange();
7105 // If the entity allows NRVO, mark the construction as elidable
7106 // unconditionally.
7107 if (Entity.allowsNRVO())
7108 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
7109 Step.Function.FoundDecl,
7110 Constructor, /*Elidable=*/true,
7111 ConstructorArgs,
7112 HadMultipleCandidates,
7113 IsListInitialization,
7114 IsStdInitListInitialization,
7115 ConstructorInitRequiresZeroInit,
7116 ConstructKind,
7117 ParenOrBraceRange);
7118 else
7119 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
7120 Step.Function.FoundDecl,
7121 Constructor,
7122 ConstructorArgs,
7123 HadMultipleCandidates,
7124 IsListInitialization,
7125 IsStdInitListInitialization,
7126 ConstructorInitRequiresZeroInit,
7127 ConstructKind,
7128 ParenOrBraceRange);
7130 if (CurInit.isInvalid())
7131 return ExprError();
7133 // Only check access if all of that succeeded.
7134 S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity);
7135 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
7136 return ExprError();
7138 if (const ArrayType *AT = S.Context.getAsArrayType(Entity.getType()))
7139 if (checkDestructorReference(S.Context.getBaseElementType(AT), Loc, S))
7140 return ExprError();
7142 if (shouldBindAsTemporary(Entity))
7143 CurInit = S.MaybeBindToTemporary(CurInit.get());
7145 return CurInit;
7148 namespace {
7149 enum LifetimeKind {
7150 /// The lifetime of a temporary bound to this entity ends at the end of the
7151 /// full-expression, and that's (probably) fine.
7152 LK_FullExpression,
7154 /// The lifetime of a temporary bound to this entity is extended to the
7155 /// lifeitme of the entity itself.
7156 LK_Extended,
7158 /// The lifetime of a temporary bound to this entity probably ends too soon,
7159 /// because the entity is allocated in a new-expression.
7160 LK_New,
7162 /// The lifetime of a temporary bound to this entity ends too soon, because
7163 /// the entity is a return object.
7164 LK_Return,
7166 /// The lifetime of a temporary bound to this entity ends too soon, because
7167 /// the entity is the result of a statement expression.
7168 LK_StmtExprResult,
7170 /// This is a mem-initializer: if it would extend a temporary (other than via
7171 /// a default member initializer), the program is ill-formed.
7172 LK_MemInitializer,
7174 using LifetimeResult =
7175 llvm::PointerIntPair<const InitializedEntity *, 3, LifetimeKind>;
7178 /// Determine the declaration which an initialized entity ultimately refers to,
7179 /// for the purpose of lifetime-extending a temporary bound to a reference in
7180 /// the initialization of \p Entity.
7181 static LifetimeResult getEntityLifetime(
7182 const InitializedEntity *Entity,
7183 const InitializedEntity *InitField = nullptr) {
7184 // C++11 [class.temporary]p5:
7185 switch (Entity->getKind()) {
7186 case InitializedEntity::EK_Variable:
7187 // The temporary [...] persists for the lifetime of the reference
7188 return {Entity, LK_Extended};
7190 case InitializedEntity::EK_Member:
7191 // For subobjects, we look at the complete object.
7192 if (Entity->getParent())
7193 return getEntityLifetime(Entity->getParent(), Entity);
7195 // except:
7196 // C++17 [class.base.init]p8:
7197 // A temporary expression bound to a reference member in a
7198 // mem-initializer is ill-formed.
7199 // C++17 [class.base.init]p11:
7200 // A temporary expression bound to a reference member from a
7201 // default member initializer is ill-formed.
7203 // The context of p11 and its example suggest that it's only the use of a
7204 // default member initializer from a constructor that makes the program
7205 // ill-formed, not its mere existence, and that it can even be used by
7206 // aggregate initialization.
7207 return {Entity, Entity->isDefaultMemberInitializer() ? LK_Extended
7208 : LK_MemInitializer};
7210 case InitializedEntity::EK_Binding:
7211 // Per [dcl.decomp]p3, the binding is treated as a variable of reference
7212 // type.
7213 return {Entity, LK_Extended};
7215 case InitializedEntity::EK_Parameter:
7216 case InitializedEntity::EK_Parameter_CF_Audited:
7217 // -- A temporary bound to a reference parameter in a function call
7218 // persists until the completion of the full-expression containing
7219 // the call.
7220 return {nullptr, LK_FullExpression};
7222 case InitializedEntity::EK_TemplateParameter:
7223 // FIXME: This will always be ill-formed; should we eagerly diagnose it here?
7224 return {nullptr, LK_FullExpression};
7226 case InitializedEntity::EK_Result:
7227 // -- The lifetime of a temporary bound to the returned value in a
7228 // function return statement is not extended; the temporary is
7229 // destroyed at the end of the full-expression in the return statement.
7230 return {nullptr, LK_Return};
7232 case InitializedEntity::EK_StmtExprResult:
7233 // FIXME: Should we lifetime-extend through the result of a statement
7234 // expression?
7235 return {nullptr, LK_StmtExprResult};
7237 case InitializedEntity::EK_New:
7238 // -- A temporary bound to a reference in a new-initializer persists
7239 // until the completion of the full-expression containing the
7240 // new-initializer.
7241 return {nullptr, LK_New};
7243 case InitializedEntity::EK_Temporary:
7244 case InitializedEntity::EK_CompoundLiteralInit:
7245 case InitializedEntity::EK_RelatedResult:
7246 // We don't yet know the storage duration of the surrounding temporary.
7247 // Assume it's got full-expression duration for now, it will patch up our
7248 // storage duration if that's not correct.
7249 return {nullptr, LK_FullExpression};
7251 case InitializedEntity::EK_ArrayElement:
7252 // For subobjects, we look at the complete object.
7253 return getEntityLifetime(Entity->getParent(), InitField);
7255 case InitializedEntity::EK_Base:
7256 // For subobjects, we look at the complete object.
7257 if (Entity->getParent())
7258 return getEntityLifetime(Entity->getParent(), InitField);
7259 return {InitField, LK_MemInitializer};
7261 case InitializedEntity::EK_Delegating:
7262 // We can reach this case for aggregate initialization in a constructor:
7263 // struct A { int &&r; };
7264 // struct B : A { B() : A{0} {} };
7265 // In this case, use the outermost field decl as the context.
7266 return {InitField, LK_MemInitializer};
7268 case InitializedEntity::EK_BlockElement:
7269 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
7270 case InitializedEntity::EK_LambdaCapture:
7271 case InitializedEntity::EK_VectorElement:
7272 case InitializedEntity::EK_ComplexElement:
7273 return {nullptr, LK_FullExpression};
7275 case InitializedEntity::EK_Exception:
7276 // FIXME: Can we diagnose lifetime problems with exceptions?
7277 return {nullptr, LK_FullExpression};
7279 case InitializedEntity::EK_ParenAggInitMember:
7280 // -- A temporary object bound to a reference element of an aggregate of
7281 // class type initialized from a parenthesized expression-list
7282 // [dcl.init, 9.3] persists until the completion of the full-expression
7283 // containing the expression-list.
7284 return {nullptr, LK_FullExpression};
7287 llvm_unreachable("unknown entity kind");
7290 namespace {
7291 enum ReferenceKind {
7292 /// Lifetime would be extended by a reference binding to a temporary.
7293 RK_ReferenceBinding,
7294 /// Lifetime would be extended by a std::initializer_list object binding to
7295 /// its backing array.
7296 RK_StdInitializerList,
7299 /// A temporary or local variable. This will be one of:
7300 /// * A MaterializeTemporaryExpr.
7301 /// * A DeclRefExpr whose declaration is a local.
7302 /// * An AddrLabelExpr.
7303 /// * A BlockExpr for a block with captures.
7304 using Local = Expr*;
7306 /// Expressions we stepped over when looking for the local state. Any steps
7307 /// that would inhibit lifetime extension or take us out of subexpressions of
7308 /// the initializer are included.
7309 struct IndirectLocalPathEntry {
7310 enum EntryKind {
7311 DefaultInit,
7312 AddressOf,
7313 VarInit,
7314 LValToRVal,
7315 LifetimeBoundCall,
7316 TemporaryCopy,
7317 LambdaCaptureInit,
7318 GslReferenceInit,
7319 GslPointerInit
7320 } Kind;
7321 Expr *E;
7322 union {
7323 const Decl *D = nullptr;
7324 const LambdaCapture *Capture;
7326 IndirectLocalPathEntry() {}
7327 IndirectLocalPathEntry(EntryKind K, Expr *E) : Kind(K), E(E) {}
7328 IndirectLocalPathEntry(EntryKind K, Expr *E, const Decl *D)
7329 : Kind(K), E(E), D(D) {}
7330 IndirectLocalPathEntry(EntryKind K, Expr *E, const LambdaCapture *Capture)
7331 : Kind(K), E(E), Capture(Capture) {}
7334 using IndirectLocalPath = llvm::SmallVectorImpl<IndirectLocalPathEntry>;
7336 struct RevertToOldSizeRAII {
7337 IndirectLocalPath &Path;
7338 unsigned OldSize = Path.size();
7339 RevertToOldSizeRAII(IndirectLocalPath &Path) : Path(Path) {}
7340 ~RevertToOldSizeRAII() { Path.resize(OldSize); }
7343 using LocalVisitor = llvm::function_ref<bool(IndirectLocalPath &Path, Local L,
7344 ReferenceKind RK)>;
7347 static bool isVarOnPath(IndirectLocalPath &Path, VarDecl *VD) {
7348 for (auto E : Path)
7349 if (E.Kind == IndirectLocalPathEntry::VarInit && E.D == VD)
7350 return true;
7351 return false;
7354 static bool pathContainsInit(IndirectLocalPath &Path) {
7355 return llvm::any_of(Path, [=](IndirectLocalPathEntry E) {
7356 return E.Kind == IndirectLocalPathEntry::DefaultInit ||
7357 E.Kind == IndirectLocalPathEntry::VarInit;
7361 static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
7362 Expr *Init, LocalVisitor Visit,
7363 bool RevisitSubinits,
7364 bool EnableLifetimeWarnings);
7366 static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
7367 Expr *Init, ReferenceKind RK,
7368 LocalVisitor Visit,
7369 bool EnableLifetimeWarnings);
7371 template <typename T> static bool isRecordWithAttr(QualType Type) {
7372 if (auto *RD = Type->getAsCXXRecordDecl())
7373 return RD->hasAttr<T>();
7374 return false;
7377 // Decl::isInStdNamespace will return false for iterators in some STL
7378 // implementations due to them being defined in a namespace outside of the std
7379 // namespace.
7380 static bool isInStlNamespace(const Decl *D) {
7381 const DeclContext *DC = D->getDeclContext();
7382 if (!DC)
7383 return false;
7384 if (const auto *ND = dyn_cast<NamespaceDecl>(DC))
7385 if (const IdentifierInfo *II = ND->getIdentifier()) {
7386 StringRef Name = II->getName();
7387 if (Name.size() >= 2 && Name.front() == '_' &&
7388 (Name[1] == '_' || isUppercase(Name[1])))
7389 return true;
7392 return DC->isStdNamespace();
7395 static bool shouldTrackImplicitObjectArg(const CXXMethodDecl *Callee) {
7396 if (auto *Conv = dyn_cast_or_null<CXXConversionDecl>(Callee))
7397 if (isRecordWithAttr<PointerAttr>(Conv->getConversionType()))
7398 return true;
7399 if (!isInStlNamespace(Callee->getParent()))
7400 return false;
7401 if (!isRecordWithAttr<PointerAttr>(
7402 Callee->getFunctionObjectParameterType()) &&
7403 !isRecordWithAttr<OwnerAttr>(Callee->getFunctionObjectParameterType()))
7404 return false;
7405 if (Callee->getReturnType()->isPointerType() ||
7406 isRecordWithAttr<PointerAttr>(Callee->getReturnType())) {
7407 if (!Callee->getIdentifier())
7408 return false;
7409 return llvm::StringSwitch<bool>(Callee->getName())
7410 .Cases("begin", "rbegin", "cbegin", "crbegin", true)
7411 .Cases("end", "rend", "cend", "crend", true)
7412 .Cases("c_str", "data", "get", true)
7413 // Map and set types.
7414 .Cases("find", "equal_range", "lower_bound", "upper_bound", true)
7415 .Default(false);
7416 } else if (Callee->getReturnType()->isReferenceType()) {
7417 if (!Callee->getIdentifier()) {
7418 auto OO = Callee->getOverloadedOperator();
7419 return OO == OverloadedOperatorKind::OO_Subscript ||
7420 OO == OverloadedOperatorKind::OO_Star;
7422 return llvm::StringSwitch<bool>(Callee->getName())
7423 .Cases("front", "back", "at", "top", "value", true)
7424 .Default(false);
7426 return false;
7429 static bool shouldTrackFirstArgument(const FunctionDecl *FD) {
7430 if (!FD->getIdentifier() || FD->getNumParams() != 1)
7431 return false;
7432 const auto *RD = FD->getParamDecl(0)->getType()->getPointeeCXXRecordDecl();
7433 if (!FD->isInStdNamespace() || !RD || !RD->isInStdNamespace())
7434 return false;
7435 if (!isRecordWithAttr<PointerAttr>(QualType(RD->getTypeForDecl(), 0)) &&
7436 !isRecordWithAttr<OwnerAttr>(QualType(RD->getTypeForDecl(), 0)))
7437 return false;
7438 if (FD->getReturnType()->isPointerType() ||
7439 isRecordWithAttr<PointerAttr>(FD->getReturnType())) {
7440 return llvm::StringSwitch<bool>(FD->getName())
7441 .Cases("begin", "rbegin", "cbegin", "crbegin", true)
7442 .Cases("end", "rend", "cend", "crend", true)
7443 .Case("data", true)
7444 .Default(false);
7445 } else if (FD->getReturnType()->isReferenceType()) {
7446 return llvm::StringSwitch<bool>(FD->getName())
7447 .Cases("get", "any_cast", true)
7448 .Default(false);
7450 return false;
7453 static void handleGslAnnotatedTypes(IndirectLocalPath &Path, Expr *Call,
7454 LocalVisitor Visit) {
7455 auto VisitPointerArg = [&](const Decl *D, Expr *Arg, bool Value) {
7456 // We are not interested in the temporary base objects of gsl Pointers:
7457 // Temp().ptr; // Here ptr might not dangle.
7458 if (isa<MemberExpr>(Arg->IgnoreImpCasts()))
7459 return;
7460 // Once we initialized a value with a reference, it can no longer dangle.
7461 if (!Value) {
7462 for (const IndirectLocalPathEntry &PE : llvm::reverse(Path)) {
7463 if (PE.Kind == IndirectLocalPathEntry::GslReferenceInit)
7464 continue;
7465 if (PE.Kind == IndirectLocalPathEntry::GslPointerInit)
7466 return;
7467 break;
7470 Path.push_back({Value ? IndirectLocalPathEntry::GslPointerInit
7471 : IndirectLocalPathEntry::GslReferenceInit,
7472 Arg, D});
7473 if (Arg->isGLValue())
7474 visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
7475 Visit,
7476 /*EnableLifetimeWarnings=*/true);
7477 else
7478 visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
7479 /*EnableLifetimeWarnings=*/true);
7480 Path.pop_back();
7483 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) {
7484 const auto *MD = cast_or_null<CXXMethodDecl>(MCE->getDirectCallee());
7485 if (MD && shouldTrackImplicitObjectArg(MD))
7486 VisitPointerArg(MD, MCE->getImplicitObjectArgument(),
7487 !MD->getReturnType()->isReferenceType());
7488 return;
7489 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(Call)) {
7490 FunctionDecl *Callee = OCE->getDirectCallee();
7491 if (Callee && Callee->isCXXInstanceMember() &&
7492 shouldTrackImplicitObjectArg(cast<CXXMethodDecl>(Callee)))
7493 VisitPointerArg(Callee, OCE->getArg(0),
7494 !Callee->getReturnType()->isReferenceType());
7495 return;
7496 } else if (auto *CE = dyn_cast<CallExpr>(Call)) {
7497 FunctionDecl *Callee = CE->getDirectCallee();
7498 if (Callee && shouldTrackFirstArgument(Callee))
7499 VisitPointerArg(Callee, CE->getArg(0),
7500 !Callee->getReturnType()->isReferenceType());
7501 return;
7504 if (auto *CCE = dyn_cast<CXXConstructExpr>(Call)) {
7505 const auto *Ctor = CCE->getConstructor();
7506 const CXXRecordDecl *RD = Ctor->getParent();
7507 if (CCE->getNumArgs() > 0 && RD->hasAttr<PointerAttr>())
7508 VisitPointerArg(Ctor->getParamDecl(0), CCE->getArgs()[0], true);
7512 static bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD) {
7513 const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7514 if (!TSI)
7515 return false;
7516 // Don't declare this variable in the second operand of the for-statement;
7517 // GCC miscompiles that by ending its lifetime before evaluating the
7518 // third operand. See gcc.gnu.org/PR86769.
7519 AttributedTypeLoc ATL;
7520 for (TypeLoc TL = TSI->getTypeLoc();
7521 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7522 TL = ATL.getModifiedLoc()) {
7523 if (ATL.getAttrAs<LifetimeBoundAttr>())
7524 return true;
7527 // Assume that all assignment operators with a "normal" return type return
7528 // *this, that is, an lvalue reference that is the same type as the implicit
7529 // object parameter (or the LHS for a non-member operator$=).
7530 OverloadedOperatorKind OO = FD->getDeclName().getCXXOverloadedOperator();
7531 if (OO == OO_Equal || isCompoundAssignmentOperator(OO)) {
7532 QualType RetT = FD->getReturnType();
7533 if (RetT->isLValueReferenceType()) {
7534 ASTContext &Ctx = FD->getASTContext();
7535 QualType LHST;
7536 auto *MD = dyn_cast<CXXMethodDecl>(FD);
7537 if (MD && MD->isCXXInstanceMember())
7538 LHST = Ctx.getLValueReferenceType(MD->getFunctionObjectParameterType());
7539 else
7540 LHST = MD->getParamDecl(0)->getType();
7541 if (Ctx.hasSameType(RetT, LHST))
7542 return true;
7546 return false;
7549 static void visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call,
7550 LocalVisitor Visit) {
7551 const FunctionDecl *Callee;
7552 ArrayRef<Expr*> Args;
7554 if (auto *CE = dyn_cast<CallExpr>(Call)) {
7555 Callee = CE->getDirectCallee();
7556 Args = llvm::ArrayRef(CE->getArgs(), CE->getNumArgs());
7557 } else {
7558 auto *CCE = cast<CXXConstructExpr>(Call);
7559 Callee = CCE->getConstructor();
7560 Args = llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs());
7562 if (!Callee)
7563 return;
7565 Expr *ObjectArg = nullptr;
7566 if (isa<CXXOperatorCallExpr>(Call) && Callee->isCXXInstanceMember()) {
7567 ObjectArg = Args[0];
7568 Args = Args.slice(1);
7569 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) {
7570 ObjectArg = MCE->getImplicitObjectArgument();
7573 auto VisitLifetimeBoundArg = [&](const Decl *D, Expr *Arg) {
7574 Path.push_back({IndirectLocalPathEntry::LifetimeBoundCall, Arg, D});
7575 if (Arg->isGLValue())
7576 visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
7577 Visit,
7578 /*EnableLifetimeWarnings=*/false);
7579 else
7580 visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
7581 /*EnableLifetimeWarnings=*/false);
7582 Path.pop_back();
7585 if (ObjectArg && implicitObjectParamIsLifetimeBound(Callee))
7586 VisitLifetimeBoundArg(Callee, ObjectArg);
7588 bool CheckCoroCall = false;
7589 if (const auto *RD = Callee->getReturnType()->getAsRecordDecl()) {
7590 CheckCoroCall = RD->hasAttr<CoroLifetimeBoundAttr>() &&
7591 RD->hasAttr<CoroReturnTypeAttr>();
7593 for (unsigned I = 0,
7594 N = std::min<unsigned>(Callee->getNumParams(), Args.size());
7595 I != N; ++I) {
7596 if (CheckCoroCall || Callee->getParamDecl(I)->hasAttr<LifetimeBoundAttr>())
7597 VisitLifetimeBoundArg(Callee->getParamDecl(I), Args[I]);
7601 /// Visit the locals that would be reachable through a reference bound to the
7602 /// glvalue expression \c Init.
7603 static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
7604 Expr *Init, ReferenceKind RK,
7605 LocalVisitor Visit,
7606 bool EnableLifetimeWarnings) {
7607 RevertToOldSizeRAII RAII(Path);
7609 // Walk past any constructs which we can lifetime-extend across.
7610 Expr *Old;
7611 do {
7612 Old = Init;
7614 if (auto *FE = dyn_cast<FullExpr>(Init))
7615 Init = FE->getSubExpr();
7617 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
7618 // If this is just redundant braces around an initializer, step over it.
7619 if (ILE->isTransparent())
7620 Init = ILE->getInit(0);
7623 // Step over any subobject adjustments; we may have a materialized
7624 // temporary inside them.
7625 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
7627 // Per current approach for DR1376, look through casts to reference type
7628 // when performing lifetime extension.
7629 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
7630 if (CE->getSubExpr()->isGLValue())
7631 Init = CE->getSubExpr();
7633 // Per the current approach for DR1299, look through array element access
7634 // on array glvalues when performing lifetime extension.
7635 if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init)) {
7636 Init = ASE->getBase();
7637 auto *ICE = dyn_cast<ImplicitCastExpr>(Init);
7638 if (ICE && ICE->getCastKind() == CK_ArrayToPointerDecay)
7639 Init = ICE->getSubExpr();
7640 else
7641 // We can't lifetime extend through this but we might still find some
7642 // retained temporaries.
7643 return visitLocalsRetainedByInitializer(Path, Init, Visit, true,
7644 EnableLifetimeWarnings);
7647 // Step into CXXDefaultInitExprs so we can diagnose cases where a
7648 // constructor inherits one as an implicit mem-initializer.
7649 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
7650 Path.push_back(
7651 {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
7652 Init = DIE->getExpr();
7654 } while (Init != Old);
7656 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) {
7657 if (Visit(Path, Local(MTE), RK))
7658 visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit, true,
7659 EnableLifetimeWarnings);
7662 if (isa<CallExpr>(Init)) {
7663 if (EnableLifetimeWarnings)
7664 handleGslAnnotatedTypes(Path, Init, Visit);
7665 return visitLifetimeBoundArguments(Path, Init, Visit);
7668 switch (Init->getStmtClass()) {
7669 case Stmt::DeclRefExprClass: {
7670 // If we find the name of a local non-reference parameter, we could have a
7671 // lifetime problem.
7672 auto *DRE = cast<DeclRefExpr>(Init);
7673 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
7674 if (VD && VD->hasLocalStorage() &&
7675 !DRE->refersToEnclosingVariableOrCapture()) {
7676 if (!VD->getType()->isReferenceType()) {
7677 Visit(Path, Local(DRE), RK);
7678 } else if (isa<ParmVarDecl>(DRE->getDecl())) {
7679 // The lifetime of a reference parameter is unknown; assume it's OK
7680 // for now.
7681 break;
7682 } else if (VD->getInit() && !isVarOnPath(Path, VD)) {
7683 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
7684 visitLocalsRetainedByReferenceBinding(Path, VD->getInit(),
7685 RK_ReferenceBinding, Visit,
7686 EnableLifetimeWarnings);
7689 break;
7692 case Stmt::UnaryOperatorClass: {
7693 // The only unary operator that make sense to handle here
7694 // is Deref. All others don't resolve to a "name." This includes
7695 // handling all sorts of rvalues passed to a unary operator.
7696 const UnaryOperator *U = cast<UnaryOperator>(Init);
7697 if (U->getOpcode() == UO_Deref)
7698 visitLocalsRetainedByInitializer(Path, U->getSubExpr(), Visit, true,
7699 EnableLifetimeWarnings);
7700 break;
7703 case Stmt::OMPArraySectionExprClass: {
7704 visitLocalsRetainedByInitializer(Path,
7705 cast<OMPArraySectionExpr>(Init)->getBase(),
7706 Visit, true, EnableLifetimeWarnings);
7707 break;
7710 case Stmt::ConditionalOperatorClass:
7711 case Stmt::BinaryConditionalOperatorClass: {
7712 auto *C = cast<AbstractConditionalOperator>(Init);
7713 if (!C->getTrueExpr()->getType()->isVoidType())
7714 visitLocalsRetainedByReferenceBinding(Path, C->getTrueExpr(), RK, Visit,
7715 EnableLifetimeWarnings);
7716 if (!C->getFalseExpr()->getType()->isVoidType())
7717 visitLocalsRetainedByReferenceBinding(Path, C->getFalseExpr(), RK, Visit,
7718 EnableLifetimeWarnings);
7719 break;
7722 // FIXME: Visit the left-hand side of an -> or ->*.
7724 default:
7725 break;
7729 /// Visit the locals that would be reachable through an object initialized by
7730 /// the prvalue expression \c Init.
7731 static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
7732 Expr *Init, LocalVisitor Visit,
7733 bool RevisitSubinits,
7734 bool EnableLifetimeWarnings) {
7735 RevertToOldSizeRAII RAII(Path);
7737 Expr *Old;
7738 do {
7739 Old = Init;
7741 // Step into CXXDefaultInitExprs so we can diagnose cases where a
7742 // constructor inherits one as an implicit mem-initializer.
7743 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
7744 Path.push_back({IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
7745 Init = DIE->getExpr();
7748 if (auto *FE = dyn_cast<FullExpr>(Init))
7749 Init = FE->getSubExpr();
7751 // Dig out the expression which constructs the extended temporary.
7752 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
7754 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
7755 Init = BTE->getSubExpr();
7757 Init = Init->IgnoreParens();
7759 // Step over value-preserving rvalue casts.
7760 if (auto *CE = dyn_cast<CastExpr>(Init)) {
7761 switch (CE->getCastKind()) {
7762 case CK_LValueToRValue:
7763 // If we can match the lvalue to a const object, we can look at its
7764 // initializer.
7765 Path.push_back({IndirectLocalPathEntry::LValToRVal, CE});
7766 return visitLocalsRetainedByReferenceBinding(
7767 Path, Init, RK_ReferenceBinding,
7768 [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool {
7769 if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
7770 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
7771 if (VD && VD->getType().isConstQualified() && VD->getInit() &&
7772 !isVarOnPath(Path, VD)) {
7773 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
7774 visitLocalsRetainedByInitializer(Path, VD->getInit(), Visit, true,
7775 EnableLifetimeWarnings);
7777 } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L)) {
7778 if (MTE->getType().isConstQualified())
7779 visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit,
7780 true, EnableLifetimeWarnings);
7782 return false;
7783 }, EnableLifetimeWarnings);
7785 // We assume that objects can be retained by pointers cast to integers,
7786 // but not if the integer is cast to floating-point type or to _Complex.
7787 // We assume that casts to 'bool' do not preserve enough information to
7788 // retain a local object.
7789 case CK_NoOp:
7790 case CK_BitCast:
7791 case CK_BaseToDerived:
7792 case CK_DerivedToBase:
7793 case CK_UncheckedDerivedToBase:
7794 case CK_Dynamic:
7795 case CK_ToUnion:
7796 case CK_UserDefinedConversion:
7797 case CK_ConstructorConversion:
7798 case CK_IntegralToPointer:
7799 case CK_PointerToIntegral:
7800 case CK_VectorSplat:
7801 case CK_IntegralCast:
7802 case CK_CPointerToObjCPointerCast:
7803 case CK_BlockPointerToObjCPointerCast:
7804 case CK_AnyPointerToBlockPointerCast:
7805 case CK_AddressSpaceConversion:
7806 break;
7808 case CK_ArrayToPointerDecay:
7809 // Model array-to-pointer decay as taking the address of the array
7810 // lvalue.
7811 Path.push_back({IndirectLocalPathEntry::AddressOf, CE});
7812 return visitLocalsRetainedByReferenceBinding(Path, CE->getSubExpr(),
7813 RK_ReferenceBinding, Visit,
7814 EnableLifetimeWarnings);
7816 default:
7817 return;
7820 Init = CE->getSubExpr();
7822 } while (Old != Init);
7824 // C++17 [dcl.init.list]p6:
7825 // initializing an initializer_list object from the array extends the
7826 // lifetime of the array exactly like binding a reference to a temporary.
7827 if (auto *ILE = dyn_cast<CXXStdInitializerListExpr>(Init))
7828 return visitLocalsRetainedByReferenceBinding(Path, ILE->getSubExpr(),
7829 RK_StdInitializerList, Visit,
7830 EnableLifetimeWarnings);
7832 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
7833 // We already visited the elements of this initializer list while
7834 // performing the initialization. Don't visit them again unless we've
7835 // changed the lifetime of the initialized entity.
7836 if (!RevisitSubinits)
7837 return;
7839 if (ILE->isTransparent())
7840 return visitLocalsRetainedByInitializer(Path, ILE->getInit(0), Visit,
7841 RevisitSubinits,
7842 EnableLifetimeWarnings);
7844 if (ILE->getType()->isArrayType()) {
7845 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
7846 visitLocalsRetainedByInitializer(Path, ILE->getInit(I), Visit,
7847 RevisitSubinits,
7848 EnableLifetimeWarnings);
7849 return;
7852 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
7853 assert(RD->isAggregate() && "aggregate init on non-aggregate");
7855 // If we lifetime-extend a braced initializer which is initializing an
7856 // aggregate, and that aggregate contains reference members which are
7857 // bound to temporaries, those temporaries are also lifetime-extended.
7858 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
7859 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
7860 visitLocalsRetainedByReferenceBinding(Path, ILE->getInit(0),
7861 RK_ReferenceBinding, Visit,
7862 EnableLifetimeWarnings);
7863 else {
7864 unsigned Index = 0;
7865 for (; Index < RD->getNumBases() && Index < ILE->getNumInits(); ++Index)
7866 visitLocalsRetainedByInitializer(Path, ILE->getInit(Index), Visit,
7867 RevisitSubinits,
7868 EnableLifetimeWarnings);
7869 for (const auto *I : RD->fields()) {
7870 if (Index >= ILE->getNumInits())
7871 break;
7872 if (I->isUnnamedBitfield())
7873 continue;
7874 Expr *SubInit = ILE->getInit(Index);
7875 if (I->getType()->isReferenceType())
7876 visitLocalsRetainedByReferenceBinding(Path, SubInit,
7877 RK_ReferenceBinding, Visit,
7878 EnableLifetimeWarnings);
7879 else
7880 // This might be either aggregate-initialization of a member or
7881 // initialization of a std::initializer_list object. Regardless,
7882 // we should recursively lifetime-extend that initializer.
7883 visitLocalsRetainedByInitializer(Path, SubInit, Visit,
7884 RevisitSubinits,
7885 EnableLifetimeWarnings);
7886 ++Index;
7890 return;
7893 // The lifetime of an init-capture is that of the closure object constructed
7894 // by a lambda-expression.
7895 if (auto *LE = dyn_cast<LambdaExpr>(Init)) {
7896 LambdaExpr::capture_iterator CapI = LE->capture_begin();
7897 for (Expr *E : LE->capture_inits()) {
7898 assert(CapI != LE->capture_end());
7899 const LambdaCapture &Cap = *CapI++;
7900 if (!E)
7901 continue;
7902 if (Cap.capturesVariable())
7903 Path.push_back({IndirectLocalPathEntry::LambdaCaptureInit, E, &Cap});
7904 if (E->isGLValue())
7905 visitLocalsRetainedByReferenceBinding(Path, E, RK_ReferenceBinding,
7906 Visit, EnableLifetimeWarnings);
7907 else
7908 visitLocalsRetainedByInitializer(Path, E, Visit, true,
7909 EnableLifetimeWarnings);
7910 if (Cap.capturesVariable())
7911 Path.pop_back();
7915 // Assume that a copy or move from a temporary references the same objects
7916 // that the temporary does.
7917 if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
7918 if (CCE->getConstructor()->isCopyOrMoveConstructor()) {
7919 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(CCE->getArg(0))) {
7920 Expr *Arg = MTE->getSubExpr();
7921 Path.push_back({IndirectLocalPathEntry::TemporaryCopy, Arg,
7922 CCE->getConstructor()});
7923 visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
7924 /*EnableLifetimeWarnings*/false);
7925 Path.pop_back();
7930 if (isa<CallExpr>(Init) || isa<CXXConstructExpr>(Init)) {
7931 if (EnableLifetimeWarnings)
7932 handleGslAnnotatedTypes(Path, Init, Visit);
7933 return visitLifetimeBoundArguments(Path, Init, Visit);
7936 switch (Init->getStmtClass()) {
7937 case Stmt::UnaryOperatorClass: {
7938 auto *UO = cast<UnaryOperator>(Init);
7939 // If the initializer is the address of a local, we could have a lifetime
7940 // problem.
7941 if (UO->getOpcode() == UO_AddrOf) {
7942 // If this is &rvalue, then it's ill-formed and we have already diagnosed
7943 // it. Don't produce a redundant warning about the lifetime of the
7944 // temporary.
7945 if (isa<MaterializeTemporaryExpr>(UO->getSubExpr()))
7946 return;
7948 Path.push_back({IndirectLocalPathEntry::AddressOf, UO});
7949 visitLocalsRetainedByReferenceBinding(Path, UO->getSubExpr(),
7950 RK_ReferenceBinding, Visit,
7951 EnableLifetimeWarnings);
7953 break;
7956 case Stmt::BinaryOperatorClass: {
7957 // Handle pointer arithmetic.
7958 auto *BO = cast<BinaryOperator>(Init);
7959 BinaryOperatorKind BOK = BO->getOpcode();
7960 if (!BO->getType()->isPointerType() || (BOK != BO_Add && BOK != BO_Sub))
7961 break;
7963 if (BO->getLHS()->getType()->isPointerType())
7964 visitLocalsRetainedByInitializer(Path, BO->getLHS(), Visit, true,
7965 EnableLifetimeWarnings);
7966 else if (BO->getRHS()->getType()->isPointerType())
7967 visitLocalsRetainedByInitializer(Path, BO->getRHS(), Visit, true,
7968 EnableLifetimeWarnings);
7969 break;
7972 case Stmt::ConditionalOperatorClass:
7973 case Stmt::BinaryConditionalOperatorClass: {
7974 auto *C = cast<AbstractConditionalOperator>(Init);
7975 // In C++, we can have a throw-expression operand, which has 'void' type
7976 // and isn't interesting from a lifetime perspective.
7977 if (!C->getTrueExpr()->getType()->isVoidType())
7978 visitLocalsRetainedByInitializer(Path, C->getTrueExpr(), Visit, true,
7979 EnableLifetimeWarnings);
7980 if (!C->getFalseExpr()->getType()->isVoidType())
7981 visitLocalsRetainedByInitializer(Path, C->getFalseExpr(), Visit, true,
7982 EnableLifetimeWarnings);
7983 break;
7986 case Stmt::BlockExprClass:
7987 if (cast<BlockExpr>(Init)->getBlockDecl()->hasCaptures()) {
7988 // This is a local block, whose lifetime is that of the function.
7989 Visit(Path, Local(cast<BlockExpr>(Init)), RK_ReferenceBinding);
7991 break;
7993 case Stmt::AddrLabelExprClass:
7994 // We want to warn if the address of a label would escape the function.
7995 Visit(Path, Local(cast<AddrLabelExpr>(Init)), RK_ReferenceBinding);
7996 break;
7998 default:
7999 break;
8003 /// Whether a path to an object supports lifetime extension.
8004 enum PathLifetimeKind {
8005 /// Lifetime-extend along this path.
8006 Extend,
8007 /// We should lifetime-extend, but we don't because (due to technical
8008 /// limitations) we can't. This happens for default member initializers,
8009 /// which we don't clone for every use, so we don't have a unique
8010 /// MaterializeTemporaryExpr to update.
8011 ShouldExtend,
8012 /// Do not lifetime extend along this path.
8013 NoExtend
8016 /// Determine whether this is an indirect path to a temporary that we are
8017 /// supposed to lifetime-extend along.
8018 static PathLifetimeKind
8019 shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path) {
8020 PathLifetimeKind Kind = PathLifetimeKind::Extend;
8021 for (auto Elem : Path) {
8022 if (Elem.Kind == IndirectLocalPathEntry::DefaultInit)
8023 Kind = PathLifetimeKind::ShouldExtend;
8024 else if (Elem.Kind != IndirectLocalPathEntry::LambdaCaptureInit)
8025 return PathLifetimeKind::NoExtend;
8027 return Kind;
8030 /// Find the range for the first interesting entry in the path at or after I.
8031 static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I,
8032 Expr *E) {
8033 for (unsigned N = Path.size(); I != N; ++I) {
8034 switch (Path[I].Kind) {
8035 case IndirectLocalPathEntry::AddressOf:
8036 case IndirectLocalPathEntry::LValToRVal:
8037 case IndirectLocalPathEntry::LifetimeBoundCall:
8038 case IndirectLocalPathEntry::TemporaryCopy:
8039 case IndirectLocalPathEntry::GslReferenceInit:
8040 case IndirectLocalPathEntry::GslPointerInit:
8041 // These exist primarily to mark the path as not permitting or
8042 // supporting lifetime extension.
8043 break;
8045 case IndirectLocalPathEntry::VarInit:
8046 if (cast<VarDecl>(Path[I].D)->isImplicit())
8047 return SourceRange();
8048 [[fallthrough]];
8049 case IndirectLocalPathEntry::DefaultInit:
8050 return Path[I].E->getSourceRange();
8052 case IndirectLocalPathEntry::LambdaCaptureInit:
8053 if (!Path[I].Capture->capturesVariable())
8054 continue;
8055 return Path[I].E->getSourceRange();
8058 return E->getSourceRange();
8061 static bool pathOnlyInitializesGslPointer(IndirectLocalPath &Path) {
8062 for (const auto &It : llvm::reverse(Path)) {
8063 if (It.Kind == IndirectLocalPathEntry::VarInit)
8064 continue;
8065 if (It.Kind == IndirectLocalPathEntry::AddressOf)
8066 continue;
8067 if (It.Kind == IndirectLocalPathEntry::LifetimeBoundCall)
8068 continue;
8069 return It.Kind == IndirectLocalPathEntry::GslPointerInit ||
8070 It.Kind == IndirectLocalPathEntry::GslReferenceInit;
8072 return false;
8075 void Sema::checkInitializerLifetime(const InitializedEntity &Entity,
8076 Expr *Init) {
8077 LifetimeResult LR = getEntityLifetime(&Entity);
8078 LifetimeKind LK = LR.getInt();
8079 const InitializedEntity *ExtendingEntity = LR.getPointer();
8081 // If this entity doesn't have an interesting lifetime, don't bother looking
8082 // for temporaries within its initializer.
8083 if (LK == LK_FullExpression)
8084 return;
8086 auto TemporaryVisitor = [&](IndirectLocalPath &Path, Local L,
8087 ReferenceKind RK) -> bool {
8088 SourceRange DiagRange = nextPathEntryRange(Path, 0, L);
8089 SourceLocation DiagLoc = DiagRange.getBegin();
8091 auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L);
8093 bool IsGslPtrInitWithGslTempOwner = false;
8094 bool IsLocalGslOwner = false;
8095 if (pathOnlyInitializesGslPointer(Path)) {
8096 if (isa<DeclRefExpr>(L)) {
8097 // We do not want to follow the references when returning a pointer originating
8098 // from a local owner to avoid the following false positive:
8099 // int &p = *localUniquePtr;
8100 // someContainer.add(std::move(localUniquePtr));
8101 // return p;
8102 IsLocalGslOwner = isRecordWithAttr<OwnerAttr>(L->getType());
8103 if (pathContainsInit(Path) || !IsLocalGslOwner)
8104 return false;
8105 } else {
8106 IsGslPtrInitWithGslTempOwner = MTE && !MTE->getExtendingDecl() &&
8107 isRecordWithAttr<OwnerAttr>(MTE->getType());
8108 // Skipping a chain of initializing gsl::Pointer annotated objects.
8109 // We are looking only for the final source to find out if it was
8110 // a local or temporary owner or the address of a local variable/param.
8111 if (!IsGslPtrInitWithGslTempOwner)
8112 return true;
8116 switch (LK) {
8117 case LK_FullExpression:
8118 llvm_unreachable("already handled this");
8120 case LK_Extended: {
8121 if (!MTE) {
8122 // The initialized entity has lifetime beyond the full-expression,
8123 // and the local entity does too, so don't warn.
8125 // FIXME: We should consider warning if a static / thread storage
8126 // duration variable retains an automatic storage duration local.
8127 return false;
8130 if (IsGslPtrInitWithGslTempOwner && DiagLoc.isValid()) {
8131 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange;
8132 return false;
8135 switch (shouldLifetimeExtendThroughPath(Path)) {
8136 case PathLifetimeKind::Extend:
8137 // Update the storage duration of the materialized temporary.
8138 // FIXME: Rebuild the expression instead of mutating it.
8139 MTE->setExtendingDecl(ExtendingEntity->getDecl(),
8140 ExtendingEntity->allocateManglingNumber());
8141 // Also visit the temporaries lifetime-extended by this initializer.
8142 return true;
8144 case PathLifetimeKind::ShouldExtend:
8145 // We're supposed to lifetime-extend the temporary along this path (per
8146 // the resolution of DR1815), but we don't support that yet.
8148 // FIXME: Properly handle this situation. Perhaps the easiest approach
8149 // would be to clone the initializer expression on each use that would
8150 // lifetime extend its temporaries.
8151 Diag(DiagLoc, diag::warn_unsupported_lifetime_extension)
8152 << RK << DiagRange;
8153 break;
8155 case PathLifetimeKind::NoExtend:
8156 // If the path goes through the initialization of a variable or field,
8157 // it can't possibly reach a temporary created in this full-expression.
8158 // We will have already diagnosed any problems with the initializer.
8159 if (pathContainsInit(Path))
8160 return false;
8162 Diag(DiagLoc, diag::warn_dangling_variable)
8163 << RK << !Entity.getParent()
8164 << ExtendingEntity->getDecl()->isImplicit()
8165 << ExtendingEntity->getDecl() << Init->isGLValue() << DiagRange;
8166 break;
8168 break;
8171 case LK_MemInitializer: {
8172 if (isa<MaterializeTemporaryExpr>(L)) {
8173 // Under C++ DR1696, if a mem-initializer (or a default member
8174 // initializer used by the absence of one) would lifetime-extend a
8175 // temporary, the program is ill-formed.
8176 if (auto *ExtendingDecl =
8177 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
8178 if (IsGslPtrInitWithGslTempOwner) {
8179 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer_member)
8180 << ExtendingDecl << DiagRange;
8181 Diag(ExtendingDecl->getLocation(),
8182 diag::note_ref_or_ptr_member_declared_here)
8183 << true;
8184 return false;
8186 bool IsSubobjectMember = ExtendingEntity != &Entity;
8187 Diag(DiagLoc, shouldLifetimeExtendThroughPath(Path) !=
8188 PathLifetimeKind::NoExtend
8189 ? diag::err_dangling_member
8190 : diag::warn_dangling_member)
8191 << ExtendingDecl << IsSubobjectMember << RK << DiagRange;
8192 // Don't bother adding a note pointing to the field if we're inside
8193 // its default member initializer; our primary diagnostic points to
8194 // the same place in that case.
8195 if (Path.empty() ||
8196 Path.back().Kind != IndirectLocalPathEntry::DefaultInit) {
8197 Diag(ExtendingDecl->getLocation(),
8198 diag::note_lifetime_extending_member_declared_here)
8199 << RK << IsSubobjectMember;
8201 } else {
8202 // We have a mem-initializer but no particular field within it; this
8203 // is either a base class or a delegating initializer directly
8204 // initializing the base-class from something that doesn't live long
8205 // enough.
8207 // FIXME: Warn on this.
8208 return false;
8210 } else {
8211 // Paths via a default initializer can only occur during error recovery
8212 // (there's no other way that a default initializer can refer to a
8213 // local). Don't produce a bogus warning on those cases.
8214 if (pathContainsInit(Path))
8215 return false;
8217 // Suppress false positives for code like the one below:
8218 // Ctor(unique_ptr<T> up) : member(*up), member2(move(up)) {}
8219 if (IsLocalGslOwner && pathOnlyInitializesGslPointer(Path))
8220 return false;
8222 auto *DRE = dyn_cast<DeclRefExpr>(L);
8223 auto *VD = DRE ? dyn_cast<VarDecl>(DRE->getDecl()) : nullptr;
8224 if (!VD) {
8225 // A member was initialized to a local block.
8226 // FIXME: Warn on this.
8227 return false;
8230 if (auto *Member =
8231 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
8232 bool IsPointer = !Member->getType()->isReferenceType();
8233 Diag(DiagLoc, IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
8234 : diag::warn_bind_ref_member_to_parameter)
8235 << Member << VD << isa<ParmVarDecl>(VD) << DiagRange;
8236 Diag(Member->getLocation(),
8237 diag::note_ref_or_ptr_member_declared_here)
8238 << (unsigned)IsPointer;
8241 break;
8244 case LK_New:
8245 if (isa<MaterializeTemporaryExpr>(L)) {
8246 if (IsGslPtrInitWithGslTempOwner)
8247 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange;
8248 else
8249 Diag(DiagLoc, RK == RK_ReferenceBinding
8250 ? diag::warn_new_dangling_reference
8251 : diag::warn_new_dangling_initializer_list)
8252 << !Entity.getParent() << DiagRange;
8253 } else {
8254 // We can't determine if the allocation outlives the local declaration.
8255 return false;
8257 break;
8259 case LK_Return:
8260 case LK_StmtExprResult:
8261 if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
8262 // We can't determine if the local variable outlives the statement
8263 // expression.
8264 if (LK == LK_StmtExprResult)
8265 return false;
8266 Diag(DiagLoc, diag::warn_ret_stack_addr_ref)
8267 << Entity.getType()->isReferenceType() << DRE->getDecl()
8268 << isa<ParmVarDecl>(DRE->getDecl()) << DiagRange;
8269 } else if (isa<BlockExpr>(L)) {
8270 Diag(DiagLoc, diag::err_ret_local_block) << DiagRange;
8271 } else if (isa<AddrLabelExpr>(L)) {
8272 // Don't warn when returning a label from a statement expression.
8273 // Leaving the scope doesn't end its lifetime.
8274 if (LK == LK_StmtExprResult)
8275 return false;
8276 Diag(DiagLoc, diag::warn_ret_addr_label) << DiagRange;
8277 } else {
8278 Diag(DiagLoc, diag::warn_ret_local_temp_addr_ref)
8279 << Entity.getType()->isReferenceType() << DiagRange;
8281 break;
8284 for (unsigned I = 0; I != Path.size(); ++I) {
8285 auto Elem = Path[I];
8287 switch (Elem.Kind) {
8288 case IndirectLocalPathEntry::AddressOf:
8289 case IndirectLocalPathEntry::LValToRVal:
8290 // These exist primarily to mark the path as not permitting or
8291 // supporting lifetime extension.
8292 break;
8294 case IndirectLocalPathEntry::LifetimeBoundCall:
8295 case IndirectLocalPathEntry::TemporaryCopy:
8296 case IndirectLocalPathEntry::GslPointerInit:
8297 case IndirectLocalPathEntry::GslReferenceInit:
8298 // FIXME: Consider adding a note for these.
8299 break;
8301 case IndirectLocalPathEntry::DefaultInit: {
8302 auto *FD = cast<FieldDecl>(Elem.D);
8303 Diag(FD->getLocation(), diag::note_init_with_default_member_initializer)
8304 << FD << nextPathEntryRange(Path, I + 1, L);
8305 break;
8308 case IndirectLocalPathEntry::VarInit: {
8309 const VarDecl *VD = cast<VarDecl>(Elem.D);
8310 Diag(VD->getLocation(), diag::note_local_var_initializer)
8311 << VD->getType()->isReferenceType()
8312 << VD->isImplicit() << VD->getDeclName()
8313 << nextPathEntryRange(Path, I + 1, L);
8314 break;
8317 case IndirectLocalPathEntry::LambdaCaptureInit:
8318 if (!Elem.Capture->capturesVariable())
8319 break;
8320 // FIXME: We can't easily tell apart an init-capture from a nested
8321 // capture of an init-capture.
8322 const ValueDecl *VD = Elem.Capture->getCapturedVar();
8323 Diag(Elem.Capture->getLocation(), diag::note_lambda_capture_initializer)
8324 << VD << VD->isInitCapture() << Elem.Capture->isExplicit()
8325 << (Elem.Capture->getCaptureKind() == LCK_ByRef) << VD
8326 << nextPathEntryRange(Path, I + 1, L);
8327 break;
8331 // We didn't lifetime-extend, so don't go any further; we don't need more
8332 // warnings or errors on inner temporaries within this one's initializer.
8333 return false;
8336 bool EnableLifetimeWarnings = !getDiagnostics().isIgnored(
8337 diag::warn_dangling_lifetime_pointer, SourceLocation());
8338 llvm::SmallVector<IndirectLocalPathEntry, 8> Path;
8339 if (Init->isGLValue())
8340 visitLocalsRetainedByReferenceBinding(Path, Init, RK_ReferenceBinding,
8341 TemporaryVisitor,
8342 EnableLifetimeWarnings);
8343 else
8344 visitLocalsRetainedByInitializer(Path, Init, TemporaryVisitor, false,
8345 EnableLifetimeWarnings);
8348 static void DiagnoseNarrowingInInitList(Sema &S,
8349 const ImplicitConversionSequence &ICS,
8350 QualType PreNarrowingType,
8351 QualType EntityType,
8352 const Expr *PostInit);
8354 /// Provide warnings when std::move is used on construction.
8355 static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
8356 bool IsReturnStmt) {
8357 if (!InitExpr)
8358 return;
8360 if (S.inTemplateInstantiation())
8361 return;
8363 QualType DestType = InitExpr->getType();
8364 if (!DestType->isRecordType())
8365 return;
8367 unsigned DiagID = 0;
8368 if (IsReturnStmt) {
8369 const CXXConstructExpr *CCE =
8370 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
8371 if (!CCE || CCE->getNumArgs() != 1)
8372 return;
8374 if (!CCE->getConstructor()->isCopyOrMoveConstructor())
8375 return;
8377 InitExpr = CCE->getArg(0)->IgnoreImpCasts();
8380 // Find the std::move call and get the argument.
8381 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
8382 if (!CE || !CE->isCallToStdMove())
8383 return;
8385 const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
8387 if (IsReturnStmt) {
8388 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
8389 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
8390 return;
8392 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
8393 if (!VD || !VD->hasLocalStorage())
8394 return;
8396 // __block variables are not moved implicitly.
8397 if (VD->hasAttr<BlocksAttr>())
8398 return;
8400 QualType SourceType = VD->getType();
8401 if (!SourceType->isRecordType())
8402 return;
8404 if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
8405 return;
8408 // If we're returning a function parameter, copy elision
8409 // is not possible.
8410 if (isa<ParmVarDecl>(VD))
8411 DiagID = diag::warn_redundant_move_on_return;
8412 else
8413 DiagID = diag::warn_pessimizing_move_on_return;
8414 } else {
8415 DiagID = diag::warn_pessimizing_move_on_initialization;
8416 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
8417 if (!ArgStripped->isPRValue() || !ArgStripped->getType()->isRecordType())
8418 return;
8421 S.Diag(CE->getBeginLoc(), DiagID);
8423 // Get all the locations for a fix-it. Don't emit the fix-it if any location
8424 // is within a macro.
8425 SourceLocation CallBegin = CE->getCallee()->getBeginLoc();
8426 if (CallBegin.isMacroID())
8427 return;
8428 SourceLocation RParen = CE->getRParenLoc();
8429 if (RParen.isMacroID())
8430 return;
8431 SourceLocation LParen;
8432 SourceLocation ArgLoc = Arg->getBeginLoc();
8434 // Special testing for the argument location. Since the fix-it needs the
8435 // location right before the argument, the argument location can be in a
8436 // macro only if it is at the beginning of the macro.
8437 while (ArgLoc.isMacroID() &&
8438 S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) {
8439 ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).getBegin();
8442 if (LParen.isMacroID())
8443 return;
8445 LParen = ArgLoc.getLocWithOffset(-1);
8447 S.Diag(CE->getBeginLoc(), diag::note_remove_move)
8448 << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
8449 << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
8452 static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
8453 // Check to see if we are dereferencing a null pointer. If so, this is
8454 // undefined behavior, so warn about it. This only handles the pattern
8455 // "*null", which is a very syntactic check.
8456 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
8457 if (UO->getOpcode() == UO_Deref &&
8458 UO->getSubExpr()->IgnoreParenCasts()->
8459 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
8460 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
8461 S.PDiag(diag::warn_binding_null_to_reference)
8462 << UO->getSubExpr()->getSourceRange());
8466 MaterializeTemporaryExpr *
8467 Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
8468 bool BoundToLvalueReference) {
8469 auto MTE = new (Context)
8470 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
8472 // Order an ExprWithCleanups for lifetime marks.
8474 // TODO: It'll be good to have a single place to check the access of the
8475 // destructor and generate ExprWithCleanups for various uses. Currently these
8476 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
8477 // but there may be a chance to merge them.
8478 Cleanup.setExprNeedsCleanups(false);
8479 return MTE;
8482 ExprResult Sema::TemporaryMaterializationConversion(Expr *E) {
8483 // In C++98, we don't want to implicitly create an xvalue.
8484 // FIXME: This means that AST consumers need to deal with "prvalues" that
8485 // denote materialized temporaries. Maybe we should add another ValueKind
8486 // for "xvalue pretending to be a prvalue" for C++98 support.
8487 if (!E->isPRValue() || !getLangOpts().CPlusPlus11)
8488 return E;
8490 // C++1z [conv.rval]/1: T shall be a complete type.
8491 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
8492 // If so, we should check for a non-abstract class type here too.
8493 QualType T = E->getType();
8494 if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
8495 return ExprError();
8497 return CreateMaterializeTemporaryExpr(E->getType(), E, false);
8500 ExprResult Sema::PerformQualificationConversion(Expr *E, QualType Ty,
8501 ExprValueKind VK,
8502 CheckedConversionKind CCK) {
8504 CastKind CK = CK_NoOp;
8506 if (VK == VK_PRValue) {
8507 auto PointeeTy = Ty->getPointeeType();
8508 auto ExprPointeeTy = E->getType()->getPointeeType();
8509 if (!PointeeTy.isNull() &&
8510 PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace())
8511 CK = CK_AddressSpaceConversion;
8512 } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) {
8513 CK = CK_AddressSpaceConversion;
8516 return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK);
8519 ExprResult InitializationSequence::Perform(Sema &S,
8520 const InitializedEntity &Entity,
8521 const InitializationKind &Kind,
8522 MultiExprArg Args,
8523 QualType *ResultType) {
8524 if (Failed()) {
8525 Diagnose(S, Entity, Kind, Args);
8526 return ExprError();
8528 if (!ZeroInitializationFixit.empty()) {
8529 const Decl *D = Entity.getDecl();
8530 const auto *VD = dyn_cast_or_null<VarDecl>(D);
8531 QualType DestType = Entity.getType();
8533 // The initialization would have succeeded with this fixit. Since the fixit
8534 // is on the error, we need to build a valid AST in this case, so this isn't
8535 // handled in the Failed() branch above.
8536 if (!DestType->isRecordType() && VD && VD->isConstexpr()) {
8537 // Use a more useful diagnostic for constexpr variables.
8538 S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
8539 << VD
8540 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
8541 ZeroInitializationFixit);
8542 } else {
8543 unsigned DiagID = diag::err_default_init_const;
8544 if (S.getLangOpts().MSVCCompat && D && D->hasAttr<SelectAnyAttr>())
8545 DiagID = diag::ext_default_init_const;
8547 S.Diag(Kind.getLocation(), DiagID)
8548 << DestType << (bool)DestType->getAs<RecordType>()
8549 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
8550 ZeroInitializationFixit);
8554 if (getKind() == DependentSequence) {
8555 // If the declaration is a non-dependent, incomplete array type
8556 // that has an initializer, then its type will be completed once
8557 // the initializer is instantiated.
8558 if (ResultType && !Entity.getType()->isDependentType() &&
8559 Args.size() == 1) {
8560 QualType DeclType = Entity.getType();
8561 if (const IncompleteArrayType *ArrayT
8562 = S.Context.getAsIncompleteArrayType(DeclType)) {
8563 // FIXME: We don't currently have the ability to accurately
8564 // compute the length of an initializer list without
8565 // performing full type-checking of the initializer list
8566 // (since we have to determine where braces are implicitly
8567 // introduced and such). So, we fall back to making the array
8568 // type a dependently-sized array type with no specified
8569 // bound.
8570 if (isa<InitListExpr>((Expr *)Args[0])) {
8571 SourceRange Brackets;
8573 // Scavange the location of the brackets from the entity, if we can.
8574 if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) {
8575 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
8576 TypeLoc TL = TInfo->getTypeLoc();
8577 if (IncompleteArrayTypeLoc ArrayLoc =
8578 TL.getAs<IncompleteArrayTypeLoc>())
8579 Brackets = ArrayLoc.getBracketsRange();
8583 *ResultType
8584 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
8585 /*NumElts=*/nullptr,
8586 ArrayT->getSizeModifier(),
8587 ArrayT->getIndexTypeCVRQualifiers(),
8588 Brackets);
8593 if (Kind.getKind() == InitializationKind::IK_Direct &&
8594 !Kind.isExplicitCast()) {
8595 // Rebuild the ParenListExpr.
8596 SourceRange ParenRange = Kind.getParenOrBraceRange();
8597 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
8598 Args);
8600 assert(Kind.getKind() == InitializationKind::IK_Copy ||
8601 Kind.isExplicitCast() ||
8602 Kind.getKind() == InitializationKind::IK_DirectList);
8603 return ExprResult(Args[0]);
8606 // No steps means no initialization.
8607 if (Steps.empty())
8608 return ExprResult((Expr *)nullptr);
8610 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
8611 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
8612 !Entity.isParamOrTemplateParamKind()) {
8613 // Produce a C++98 compatibility warning if we are initializing a reference
8614 // from an initializer list. For parameters, we produce a better warning
8615 // elsewhere.
8616 Expr *Init = Args[0];
8617 S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init)
8618 << Init->getSourceRange();
8621 if (S.getLangOpts().MicrosoftExt && Args.size() == 1 &&
8622 isa<PredefinedExpr>(Args[0]) && Entity.getType()->isArrayType()) {
8623 // Produce a Microsoft compatibility warning when initializing from a
8624 // predefined expression since MSVC treats predefined expressions as string
8625 // literals.
8626 Expr *Init = Args[0];
8627 S.Diag(Init->getBeginLoc(), diag::ext_init_from_predefined) << Init;
8630 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
8631 QualType ETy = Entity.getType();
8632 bool HasGlobalAS = ETy.hasAddressSpace() &&
8633 ETy.getAddressSpace() == LangAS::opencl_global;
8635 if (S.getLangOpts().OpenCLVersion >= 200 &&
8636 ETy->isAtomicType() && !HasGlobalAS &&
8637 Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
8638 S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init)
8639 << 1
8640 << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc());
8641 return ExprError();
8644 QualType DestType = Entity.getType().getNonReferenceType();
8645 // FIXME: Ugly hack around the fact that Entity.getType() is not
8646 // the same as Entity.getDecl()->getType() in cases involving type merging,
8647 // and we want latter when it makes sense.
8648 if (ResultType)
8649 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
8650 Entity.getType();
8652 ExprResult CurInit((Expr *)nullptr);
8653 SmallVector<Expr*, 4> ArrayLoopCommonExprs;
8655 // HLSL allows vector initialization to function like list initialization, but
8656 // use the syntax of a C++-like constructor.
8657 bool IsHLSLVectorInit = S.getLangOpts().HLSL && DestType->isExtVectorType() &&
8658 isa<InitListExpr>(Args[0]);
8659 (void)IsHLSLVectorInit;
8661 // For initialization steps that start with a single initializer,
8662 // grab the only argument out the Args and place it into the "current"
8663 // initializer.
8664 switch (Steps.front().Kind) {
8665 case SK_ResolveAddressOfOverloadedFunction:
8666 case SK_CastDerivedToBasePRValue:
8667 case SK_CastDerivedToBaseXValue:
8668 case SK_CastDerivedToBaseLValue:
8669 case SK_BindReference:
8670 case SK_BindReferenceToTemporary:
8671 case SK_FinalCopy:
8672 case SK_ExtraneousCopyToTemporary:
8673 case SK_UserConversion:
8674 case SK_QualificationConversionLValue:
8675 case SK_QualificationConversionXValue:
8676 case SK_QualificationConversionPRValue:
8677 case SK_FunctionReferenceConversion:
8678 case SK_AtomicConversion:
8679 case SK_ConversionSequence:
8680 case SK_ConversionSequenceNoNarrowing:
8681 case SK_ListInitialization:
8682 case SK_UnwrapInitList:
8683 case SK_RewrapInitList:
8684 case SK_CAssignment:
8685 case SK_StringInit:
8686 case SK_ObjCObjectConversion:
8687 case SK_ArrayLoopIndex:
8688 case SK_ArrayLoopInit:
8689 case SK_ArrayInit:
8690 case SK_GNUArrayInit:
8691 case SK_ParenthesizedArrayInit:
8692 case SK_PassByIndirectCopyRestore:
8693 case SK_PassByIndirectRestore:
8694 case SK_ProduceObjCObject:
8695 case SK_StdInitializerList:
8696 case SK_OCLSamplerInit:
8697 case SK_OCLZeroOpaqueType: {
8698 assert(Args.size() == 1 || IsHLSLVectorInit);
8699 CurInit = Args[0];
8700 if (!CurInit.get()) return ExprError();
8701 break;
8704 case SK_ConstructorInitialization:
8705 case SK_ConstructorInitializationFromList:
8706 case SK_StdInitializerListConstructorCall:
8707 case SK_ZeroInitialization:
8708 case SK_ParenthesizedListInit:
8709 break;
8712 // Promote from an unevaluated context to an unevaluated list context in
8713 // C++11 list-initialization; we need to instantiate entities usable in
8714 // constant expressions here in order to perform narrowing checks =(
8715 EnterExpressionEvaluationContext Evaluated(
8716 S, EnterExpressionEvaluationContext::InitList,
8717 CurInit.get() && isa<InitListExpr>(CurInit.get()));
8719 // C++ [class.abstract]p2:
8720 // no objects of an abstract class can be created except as subobjects
8721 // of a class derived from it
8722 auto checkAbstractType = [&](QualType T) -> bool {
8723 if (Entity.getKind() == InitializedEntity::EK_Base ||
8724 Entity.getKind() == InitializedEntity::EK_Delegating)
8725 return false;
8726 return S.RequireNonAbstractType(Kind.getLocation(), T,
8727 diag::err_allocation_of_abstract_type);
8730 // Walk through the computed steps for the initialization sequence,
8731 // performing the specified conversions along the way.
8732 bool ConstructorInitRequiresZeroInit = false;
8733 for (step_iterator Step = step_begin(), StepEnd = step_end();
8734 Step != StepEnd; ++Step) {
8735 if (CurInit.isInvalid())
8736 return ExprError();
8738 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
8740 switch (Step->Kind) {
8741 case SK_ResolveAddressOfOverloadedFunction:
8742 // Overload resolution determined which function invoke; update the
8743 // initializer to reflect that choice.
8744 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
8745 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
8746 return ExprError();
8747 CurInit = S.FixOverloadedFunctionReference(CurInit,
8748 Step->Function.FoundDecl,
8749 Step->Function.Function);
8750 // We might get back another placeholder expression if we resolved to a
8751 // builtin.
8752 if (!CurInit.isInvalid())
8753 CurInit = S.CheckPlaceholderExpr(CurInit.get());
8754 break;
8756 case SK_CastDerivedToBasePRValue:
8757 case SK_CastDerivedToBaseXValue:
8758 case SK_CastDerivedToBaseLValue: {
8759 // We have a derived-to-base cast that produces either an rvalue or an
8760 // lvalue. Perform that cast.
8762 CXXCastPath BasePath;
8764 // Casts to inaccessible base classes are allowed with C-style casts.
8765 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
8766 if (S.CheckDerivedToBaseConversion(
8767 SourceType, Step->Type, CurInit.get()->getBeginLoc(),
8768 CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess))
8769 return ExprError();
8771 ExprValueKind VK =
8772 Step->Kind == SK_CastDerivedToBaseLValue
8773 ? VK_LValue
8774 : (Step->Kind == SK_CastDerivedToBaseXValue ? VK_XValue
8775 : VK_PRValue);
8776 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
8777 CK_DerivedToBase, CurInit.get(),
8778 &BasePath, VK, FPOptionsOverride());
8779 break;
8782 case SK_BindReference:
8783 // Reference binding does not have any corresponding ASTs.
8785 // Check exception specifications
8786 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
8787 return ExprError();
8789 // We don't check for e.g. function pointers here, since address
8790 // availability checks should only occur when the function first decays
8791 // into a pointer or reference.
8792 if (CurInit.get()->getType()->isFunctionProtoType()) {
8793 if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
8794 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
8795 if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
8796 DRE->getBeginLoc()))
8797 return ExprError();
8802 CheckForNullPointerDereference(S, CurInit.get());
8803 break;
8805 case SK_BindReferenceToTemporary: {
8806 // Make sure the "temporary" is actually an rvalue.
8807 assert(CurInit.get()->isPRValue() && "not a temporary");
8809 // Check exception specifications
8810 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
8811 return ExprError();
8813 QualType MTETy = Step->Type;
8815 // When this is an incomplete array type (such as when this is
8816 // initializing an array of unknown bounds from an init list), use THAT
8817 // type instead so that we propagate the array bounds.
8818 if (MTETy->isIncompleteArrayType() &&
8819 !CurInit.get()->getType()->isIncompleteArrayType() &&
8820 S.Context.hasSameType(
8821 MTETy->getPointeeOrArrayElementType(),
8822 CurInit.get()->getType()->getPointeeOrArrayElementType()))
8823 MTETy = CurInit.get()->getType();
8825 // Materialize the temporary into memory.
8826 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
8827 MTETy, CurInit.get(), Entity.getType()->isLValueReferenceType());
8828 CurInit = MTE;
8830 // If we're extending this temporary to automatic storage duration -- we
8831 // need to register its cleanup during the full-expression's cleanups.
8832 if (MTE->getStorageDuration() == SD_Automatic &&
8833 MTE->getType().isDestructedType())
8834 S.Cleanup.setExprNeedsCleanups(true);
8835 break;
8838 case SK_FinalCopy:
8839 if (checkAbstractType(Step->Type))
8840 return ExprError();
8842 // If the overall initialization is initializing a temporary, we already
8843 // bound our argument if it was necessary to do so. If not (if we're
8844 // ultimately initializing a non-temporary), our argument needs to be
8845 // bound since it's initializing a function parameter.
8846 // FIXME: This is a mess. Rationalize temporary destruction.
8847 if (!shouldBindAsTemporary(Entity))
8848 CurInit = S.MaybeBindToTemporary(CurInit.get());
8849 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8850 /*IsExtraneousCopy=*/false);
8851 break;
8853 case SK_ExtraneousCopyToTemporary:
8854 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8855 /*IsExtraneousCopy=*/true);
8856 break;
8858 case SK_UserConversion: {
8859 // We have a user-defined conversion that invokes either a constructor
8860 // or a conversion function.
8861 CastKind CastKind;
8862 FunctionDecl *Fn = Step->Function.Function;
8863 DeclAccessPair FoundFn = Step->Function.FoundDecl;
8864 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
8865 bool CreatedObject = false;
8866 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
8867 // Build a call to the selected constructor.
8868 SmallVector<Expr*, 8> ConstructorArgs;
8869 SourceLocation Loc = CurInit.get()->getBeginLoc();
8871 // Determine the arguments required to actually perform the constructor
8872 // call.
8873 Expr *Arg = CurInit.get();
8874 if (S.CompleteConstructorCall(Constructor, Step->Type,
8875 MultiExprArg(&Arg, 1), Loc,
8876 ConstructorArgs))
8877 return ExprError();
8879 // Build an expression that constructs a temporary.
8880 CurInit = S.BuildCXXConstructExpr(
8881 Loc, Step->Type, FoundFn, Constructor, ConstructorArgs,
8882 HadMultipleCandidates,
8883 /*ListInit*/ false,
8884 /*StdInitListInit*/ false,
8885 /*ZeroInit*/ false, CXXConstructionKind::Complete, SourceRange());
8886 if (CurInit.isInvalid())
8887 return ExprError();
8889 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
8890 Entity);
8891 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
8892 return ExprError();
8894 CastKind = CK_ConstructorConversion;
8895 CreatedObject = true;
8896 } else {
8897 // Build a call to the conversion function.
8898 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
8899 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
8900 FoundFn);
8901 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
8902 return ExprError();
8904 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
8905 HadMultipleCandidates);
8906 if (CurInit.isInvalid())
8907 return ExprError();
8909 CastKind = CK_UserDefinedConversion;
8910 CreatedObject = Conversion->getReturnType()->isRecordType();
8913 if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
8914 return ExprError();
8916 CurInit = ImplicitCastExpr::Create(
8917 S.Context, CurInit.get()->getType(), CastKind, CurInit.get(), nullptr,
8918 CurInit.get()->getValueKind(), S.CurFPFeatureOverrides());
8920 if (shouldBindAsTemporary(Entity))
8921 // The overall entity is temporary, so this expression should be
8922 // destroyed at the end of its full-expression.
8923 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
8924 else if (CreatedObject && shouldDestroyEntity(Entity)) {
8925 // The object outlasts the full-expression, but we need to prepare for
8926 // a destructor being run on it.
8927 // FIXME: It makes no sense to do this here. This should happen
8928 // regardless of how we initialized the entity.
8929 QualType T = CurInit.get()->getType();
8930 if (const RecordType *Record = T->getAs<RecordType>()) {
8931 CXXDestructorDecl *Destructor
8932 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
8933 S.CheckDestructorAccess(CurInit.get()->getBeginLoc(), Destructor,
8934 S.PDiag(diag::err_access_dtor_temp) << T);
8935 S.MarkFunctionReferenced(CurInit.get()->getBeginLoc(), Destructor);
8936 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc()))
8937 return ExprError();
8940 break;
8943 case SK_QualificationConversionLValue:
8944 case SK_QualificationConversionXValue:
8945 case SK_QualificationConversionPRValue: {
8946 // Perform a qualification conversion; these can never go wrong.
8947 ExprValueKind VK =
8948 Step->Kind == SK_QualificationConversionLValue
8949 ? VK_LValue
8950 : (Step->Kind == SK_QualificationConversionXValue ? VK_XValue
8951 : VK_PRValue);
8952 CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK);
8953 break;
8956 case SK_FunctionReferenceConversion:
8957 assert(CurInit.get()->isLValue() &&
8958 "function reference should be lvalue");
8959 CurInit =
8960 S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK_LValue);
8961 break;
8963 case SK_AtomicConversion: {
8964 assert(CurInit.get()->isPRValue() && "cannot convert glvalue to atomic");
8965 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8966 CK_NonAtomicToAtomic, VK_PRValue);
8967 break;
8970 case SK_ConversionSequence:
8971 case SK_ConversionSequenceNoNarrowing: {
8972 if (const auto *FromPtrType =
8973 CurInit.get()->getType()->getAs<PointerType>()) {
8974 if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) {
8975 if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8976 !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8977 // Do not check static casts here because they are checked earlier
8978 // in Sema::ActOnCXXNamedCast()
8979 if (!Kind.isStaticCast()) {
8980 S.Diag(CurInit.get()->getExprLoc(),
8981 diag::warn_noderef_to_dereferenceable_pointer)
8982 << CurInit.get()->getSourceRange();
8988 Sema::CheckedConversionKind CCK
8989 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
8990 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
8991 : Kind.isExplicitCast()? Sema::CCK_OtherCast
8992 : Sema::CCK_ImplicitConversion;
8993 ExprResult CurInitExprRes =
8994 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
8995 getAssignmentAction(Entity), CCK);
8996 if (CurInitExprRes.isInvalid())
8997 return ExprError();
8999 S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), CurInit.get());
9001 CurInit = CurInitExprRes;
9003 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
9004 S.getLangOpts().CPlusPlus)
9005 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
9006 CurInit.get());
9008 break;
9011 case SK_ListInitialization: {
9012 if (checkAbstractType(Step->Type))
9013 return ExprError();
9015 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
9016 // If we're not initializing the top-level entity, we need to create an
9017 // InitializeTemporary entity for our target type.
9018 QualType Ty = Step->Type;
9019 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
9020 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
9021 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
9022 InitListChecker PerformInitList(S, InitEntity,
9023 InitList, Ty, /*VerifyOnly=*/false,
9024 /*TreatUnavailableAsInvalid=*/false);
9025 if (PerformInitList.HadError())
9026 return ExprError();
9028 // Hack: We must update *ResultType if available in order to set the
9029 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
9030 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
9031 if (ResultType &&
9032 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
9033 if ((*ResultType)->isRValueReferenceType())
9034 Ty = S.Context.getRValueReferenceType(Ty);
9035 else if ((*ResultType)->isLValueReferenceType())
9036 Ty = S.Context.getLValueReferenceType(Ty,
9037 (*ResultType)->castAs<LValueReferenceType>()->isSpelledAsLValue());
9038 *ResultType = Ty;
9041 InitListExpr *StructuredInitList =
9042 PerformInitList.getFullyStructuredList();
9043 CurInit.get();
9044 CurInit = shouldBindAsTemporary(InitEntity)
9045 ? S.MaybeBindToTemporary(StructuredInitList)
9046 : StructuredInitList;
9047 break;
9050 case SK_ConstructorInitializationFromList: {
9051 if (checkAbstractType(Step->Type))
9052 return ExprError();
9054 // When an initializer list is passed for a parameter of type "reference
9055 // to object", we don't get an EK_Temporary entity, but instead an
9056 // EK_Parameter entity with reference type.
9057 // FIXME: This is a hack. What we really should do is create a user
9058 // conversion step for this case, but this makes it considerably more
9059 // complicated. For now, this will do.
9060 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
9061 Entity.getType().getNonReferenceType());
9062 bool UseTemporary = Entity.getType()->isReferenceType();
9063 assert(Args.size() == 1 && "expected a single argument for list init");
9064 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9065 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
9066 << InitList->getSourceRange();
9067 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
9068 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
9069 Entity,
9070 Kind, Arg, *Step,
9071 ConstructorInitRequiresZeroInit,
9072 /*IsListInitialization*/true,
9073 /*IsStdInitListInit*/false,
9074 InitList->getLBraceLoc(),
9075 InitList->getRBraceLoc());
9076 break;
9079 case SK_UnwrapInitList:
9080 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
9081 break;
9083 case SK_RewrapInitList: {
9084 Expr *E = CurInit.get();
9085 InitListExpr *Syntactic = Step->WrappingSyntacticList;
9086 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
9087 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
9088 ILE->setSyntacticForm(Syntactic);
9089 ILE->setType(E->getType());
9090 ILE->setValueKind(E->getValueKind());
9091 CurInit = ILE;
9092 break;
9095 case SK_ConstructorInitialization:
9096 case SK_StdInitializerListConstructorCall: {
9097 if (checkAbstractType(Step->Type))
9098 return ExprError();
9100 // When an initializer list is passed for a parameter of type "reference
9101 // to object", we don't get an EK_Temporary entity, but instead an
9102 // EK_Parameter entity with reference type.
9103 // FIXME: This is a hack. What we really should do is create a user
9104 // conversion step for this case, but this makes it considerably more
9105 // complicated. For now, this will do.
9106 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
9107 Entity.getType().getNonReferenceType());
9108 bool UseTemporary = Entity.getType()->isReferenceType();
9109 bool IsStdInitListInit =
9110 Step->Kind == SK_StdInitializerListConstructorCall;
9111 Expr *Source = CurInit.get();
9112 SourceRange Range = Kind.hasParenOrBraceRange()
9113 ? Kind.getParenOrBraceRange()
9114 : SourceRange();
9115 CurInit = PerformConstructorInitialization(
9116 S, UseTemporary ? TempEntity : Entity, Kind,
9117 Source ? MultiExprArg(Source) : Args, *Step,
9118 ConstructorInitRequiresZeroInit,
9119 /*IsListInitialization*/ IsStdInitListInit,
9120 /*IsStdInitListInitialization*/ IsStdInitListInit,
9121 /*LBraceLoc*/ Range.getBegin(),
9122 /*RBraceLoc*/ Range.getEnd());
9123 break;
9126 case SK_ZeroInitialization: {
9127 step_iterator NextStep = Step;
9128 ++NextStep;
9129 if (NextStep != StepEnd &&
9130 (NextStep->Kind == SK_ConstructorInitialization ||
9131 NextStep->Kind == SK_ConstructorInitializationFromList)) {
9132 // The need for zero-initialization is recorded directly into
9133 // the call to the object's constructor within the next step.
9134 ConstructorInitRequiresZeroInit = true;
9135 } else if (Kind.getKind() == InitializationKind::IK_Value &&
9136 S.getLangOpts().CPlusPlus &&
9137 !Kind.isImplicitValueInit()) {
9138 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
9139 if (!TSInfo)
9140 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
9141 Kind.getRange().getBegin());
9143 CurInit = new (S.Context) CXXScalarValueInitExpr(
9144 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
9145 Kind.getRange().getEnd());
9146 } else {
9147 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
9149 break;
9152 case SK_CAssignment: {
9153 QualType SourceType = CurInit.get()->getType();
9155 // Save off the initial CurInit in case we need to emit a diagnostic
9156 ExprResult InitialCurInit = CurInit;
9157 ExprResult Result = CurInit;
9158 Sema::AssignConvertType ConvTy =
9159 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
9160 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
9161 if (Result.isInvalid())
9162 return ExprError();
9163 CurInit = Result;
9165 // If this is a call, allow conversion to a transparent union.
9166 ExprResult CurInitExprRes = CurInit;
9167 if (ConvTy != Sema::Compatible &&
9168 Entity.isParameterKind() &&
9169 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
9170 == Sema::Compatible)
9171 ConvTy = Sema::Compatible;
9172 if (CurInitExprRes.isInvalid())
9173 return ExprError();
9174 CurInit = CurInitExprRes;
9176 bool Complained;
9177 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
9178 Step->Type, SourceType,
9179 InitialCurInit.get(),
9180 getAssignmentAction(Entity, true),
9181 &Complained)) {
9182 PrintInitLocationNote(S, Entity);
9183 return ExprError();
9184 } else if (Complained)
9185 PrintInitLocationNote(S, Entity);
9186 break;
9189 case SK_StringInit: {
9190 QualType Ty = Step->Type;
9191 bool UpdateType = ResultType && Entity.getType()->isIncompleteArrayType();
9192 CheckStringInit(CurInit.get(), UpdateType ? *ResultType : Ty,
9193 S.Context.getAsArrayType(Ty), S);
9194 break;
9197 case SK_ObjCObjectConversion:
9198 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
9199 CK_ObjCObjectLValueCast,
9200 CurInit.get()->getValueKind());
9201 break;
9203 case SK_ArrayLoopIndex: {
9204 Expr *Cur = CurInit.get();
9205 Expr *BaseExpr = new (S.Context)
9206 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
9207 Cur->getValueKind(), Cur->getObjectKind(), Cur);
9208 Expr *IndexExpr =
9209 new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType());
9210 CurInit = S.CreateBuiltinArraySubscriptExpr(
9211 BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
9212 ArrayLoopCommonExprs.push_back(BaseExpr);
9213 break;
9216 case SK_ArrayLoopInit: {
9217 assert(!ArrayLoopCommonExprs.empty() &&
9218 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
9219 Expr *Common = ArrayLoopCommonExprs.pop_back_val();
9220 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
9221 CurInit.get());
9222 break;
9225 case SK_GNUArrayInit:
9226 // Okay: we checked everything before creating this step. Note that
9227 // this is a GNU extension.
9228 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
9229 << Step->Type << CurInit.get()->getType()
9230 << CurInit.get()->getSourceRange();
9231 updateGNUCompoundLiteralRValue(CurInit.get());
9232 [[fallthrough]];
9233 case SK_ArrayInit:
9234 // If the destination type is an incomplete array type, update the
9235 // type accordingly.
9236 if (ResultType) {
9237 if (const IncompleteArrayType *IncompleteDest
9238 = S.Context.getAsIncompleteArrayType(Step->Type)) {
9239 if (const ConstantArrayType *ConstantSource
9240 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
9241 *ResultType = S.Context.getConstantArrayType(
9242 IncompleteDest->getElementType(), ConstantSource->getSize(),
9243 ConstantSource->getSizeExpr(), ArraySizeModifier::Normal, 0);
9247 break;
9249 case SK_ParenthesizedArrayInit:
9250 // Okay: we checked everything before creating this step. Note that
9251 // this is a GNU extension.
9252 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
9253 << CurInit.get()->getSourceRange();
9254 break;
9256 case SK_PassByIndirectCopyRestore:
9257 case SK_PassByIndirectRestore:
9258 checkIndirectCopyRestoreSource(S, CurInit.get());
9259 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
9260 CurInit.get(), Step->Type,
9261 Step->Kind == SK_PassByIndirectCopyRestore);
9262 break;
9264 case SK_ProduceObjCObject:
9265 CurInit = ImplicitCastExpr::Create(
9266 S.Context, Step->Type, CK_ARCProduceObject, CurInit.get(), nullptr,
9267 VK_PRValue, FPOptionsOverride());
9268 break;
9270 case SK_StdInitializerList: {
9271 S.Diag(CurInit.get()->getExprLoc(),
9272 diag::warn_cxx98_compat_initializer_list_init)
9273 << CurInit.get()->getSourceRange();
9275 // Materialize the temporary into memory.
9276 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
9277 CurInit.get()->getType(), CurInit.get(),
9278 /*BoundToLvalueReference=*/false);
9280 // Wrap it in a construction of a std::initializer_list<T>.
9281 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
9283 // Bind the result, in case the library has given initializer_list a
9284 // non-trivial destructor.
9285 if (shouldBindAsTemporary(Entity))
9286 CurInit = S.MaybeBindToTemporary(CurInit.get());
9287 break;
9290 case SK_OCLSamplerInit: {
9291 // Sampler initialization have 5 cases:
9292 // 1. function argument passing
9293 // 1a. argument is a file-scope variable
9294 // 1b. argument is a function-scope variable
9295 // 1c. argument is one of caller function's parameters
9296 // 2. variable initialization
9297 // 2a. initializing a file-scope variable
9298 // 2b. initializing a function-scope variable
9300 // For file-scope variables, since they cannot be initialized by function
9301 // call of __translate_sampler_initializer in LLVM IR, their references
9302 // need to be replaced by a cast from their literal initializers to
9303 // sampler type. Since sampler variables can only be used in function
9304 // calls as arguments, we only need to replace them when handling the
9305 // argument passing.
9306 assert(Step->Type->isSamplerT() &&
9307 "Sampler initialization on non-sampler type.");
9308 Expr *Init = CurInit.get()->IgnoreParens();
9309 QualType SourceType = Init->getType();
9310 // Case 1
9311 if (Entity.isParameterKind()) {
9312 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
9313 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
9314 << SourceType;
9315 break;
9316 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
9317 auto Var = cast<VarDecl>(DRE->getDecl());
9318 // Case 1b and 1c
9319 // No cast from integer to sampler is needed.
9320 if (!Var->hasGlobalStorage()) {
9321 CurInit = ImplicitCastExpr::Create(
9322 S.Context, Step->Type, CK_LValueToRValue, Init,
9323 /*BasePath=*/nullptr, VK_PRValue, FPOptionsOverride());
9324 break;
9326 // Case 1a
9327 // For function call with a file-scope sampler variable as argument,
9328 // get the integer literal.
9329 // Do not diagnose if the file-scope variable does not have initializer
9330 // since this has already been diagnosed when parsing the variable
9331 // declaration.
9332 if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
9333 break;
9334 Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
9335 Var->getInit()))->getSubExpr();
9336 SourceType = Init->getType();
9338 } else {
9339 // Case 2
9340 // Check initializer is 32 bit integer constant.
9341 // If the initializer is taken from global variable, do not diagnose since
9342 // this has already been done when parsing the variable declaration.
9343 if (!Init->isConstantInitializer(S.Context, false))
9344 break;
9346 if (!SourceType->isIntegerType() ||
9347 32 != S.Context.getIntWidth(SourceType)) {
9348 S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
9349 << SourceType;
9350 break;
9353 Expr::EvalResult EVResult;
9354 Init->EvaluateAsInt(EVResult, S.Context);
9355 llvm::APSInt Result = EVResult.Val.getInt();
9356 const uint64_t SamplerValue = Result.getLimitedValue();
9357 // 32-bit value of sampler's initializer is interpreted as
9358 // bit-field with the following structure:
9359 // |unspecified|Filter|Addressing Mode| Normalized Coords|
9360 // |31 6|5 4|3 1| 0|
9361 // This structure corresponds to enum values of sampler properties
9362 // defined in SPIR spec v1.2 and also opencl-c.h
9363 unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
9364 unsigned FilterMode = (0x30 & SamplerValue) >> 4;
9365 if (FilterMode != 1 && FilterMode != 2 &&
9366 !S.getOpenCLOptions().isAvailableOption(
9367 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()))
9368 S.Diag(Kind.getLocation(),
9369 diag::warn_sampler_initializer_invalid_bits)
9370 << "Filter Mode";
9371 if (AddressingMode > 4)
9372 S.Diag(Kind.getLocation(),
9373 diag::warn_sampler_initializer_invalid_bits)
9374 << "Addressing Mode";
9377 // Cases 1a, 2a and 2b
9378 // Insert cast from integer to sampler.
9379 CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy,
9380 CK_IntToOCLSampler);
9381 break;
9383 case SK_OCLZeroOpaqueType: {
9384 assert((Step->Type->isEventT() || Step->Type->isQueueT() ||
9385 Step->Type->isOCLIntelSubgroupAVCType()) &&
9386 "Wrong type for initialization of OpenCL opaque type.");
9388 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
9389 CK_ZeroToOCLOpaqueType,
9390 CurInit.get()->getValueKind());
9391 break;
9393 case SK_ParenthesizedListInit: {
9394 CurInit = nullptr;
9395 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
9396 /*VerifyOnly=*/false, &CurInit);
9397 if (CurInit.get() && ResultType)
9398 *ResultType = CurInit.get()->getType();
9399 if (shouldBindAsTemporary(Entity))
9400 CurInit = S.MaybeBindToTemporary(CurInit.get());
9401 break;
9406 Expr *Init = CurInit.get();
9407 if (!Init)
9408 return ExprError();
9410 // Check whether the initializer has a shorter lifetime than the initialized
9411 // entity, and if not, either lifetime-extend or warn as appropriate.
9412 S.checkInitializerLifetime(Entity, Init);
9414 // Diagnose non-fatal problems with the completed initialization.
9415 if (InitializedEntity::EntityKind EK = Entity.getKind();
9416 (EK == InitializedEntity::EK_Member ||
9417 EK == InitializedEntity::EK_ParenAggInitMember) &&
9418 cast<FieldDecl>(Entity.getDecl())->isBitField())
9419 S.CheckBitFieldInitialization(Kind.getLocation(),
9420 cast<FieldDecl>(Entity.getDecl()), Init);
9422 // Check for std::move on construction.
9423 CheckMoveOnConstruction(S, Init,
9424 Entity.getKind() == InitializedEntity::EK_Result);
9426 return Init;
9429 /// Somewhere within T there is an uninitialized reference subobject.
9430 /// Dig it out and diagnose it.
9431 static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
9432 QualType T) {
9433 if (T->isReferenceType()) {
9434 S.Diag(Loc, diag::err_reference_without_init)
9435 << T.getNonReferenceType();
9436 return true;
9439 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
9440 if (!RD || !RD->hasUninitializedReferenceMember())
9441 return false;
9443 for (const auto *FI : RD->fields()) {
9444 if (FI->isUnnamedBitfield())
9445 continue;
9447 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
9448 S.Diag(Loc, diag::note_value_initialization_here) << RD;
9449 return true;
9453 for (const auto &BI : RD->bases()) {
9454 if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) {
9455 S.Diag(Loc, diag::note_value_initialization_here) << RD;
9456 return true;
9460 return false;
9464 //===----------------------------------------------------------------------===//
9465 // Diagnose initialization failures
9466 //===----------------------------------------------------------------------===//
9468 /// Emit notes associated with an initialization that failed due to a
9469 /// "simple" conversion failure.
9470 static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
9471 Expr *op) {
9472 QualType destType = entity.getType();
9473 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
9474 op->getType()->isObjCObjectPointerType()) {
9476 // Emit a possible note about the conversion failing because the
9477 // operand is a message send with a related result type.
9478 S.EmitRelatedResultTypeNote(op);
9480 // Emit a possible note about a return failing because we're
9481 // expecting a related result type.
9482 if (entity.getKind() == InitializedEntity::EK_Result)
9483 S.EmitRelatedResultTypeNoteForReturn(destType);
9485 QualType fromType = op->getType();
9486 QualType fromPointeeType = fromType.getCanonicalType()->getPointeeType();
9487 QualType destPointeeType = destType.getCanonicalType()->getPointeeType();
9488 auto *fromDecl = fromType->getPointeeCXXRecordDecl();
9489 auto *destDecl = destType->getPointeeCXXRecordDecl();
9490 if (fromDecl && destDecl && fromDecl->getDeclKind() == Decl::CXXRecord &&
9491 destDecl->getDeclKind() == Decl::CXXRecord &&
9492 !fromDecl->isInvalidDecl() && !destDecl->isInvalidDecl() &&
9493 !fromDecl->hasDefinition() &&
9494 destPointeeType.getQualifiers().compatiblyIncludes(
9495 fromPointeeType.getQualifiers()))
9496 S.Diag(fromDecl->getLocation(), diag::note_forward_class_conversion)
9497 << S.getASTContext().getTagDeclType(fromDecl)
9498 << S.getASTContext().getTagDeclType(destDecl);
9501 static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
9502 InitListExpr *InitList) {
9503 QualType DestType = Entity.getType();
9505 QualType E;
9506 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
9507 QualType ArrayType = S.Context.getConstantArrayType(
9508 E.withConst(),
9509 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
9510 InitList->getNumInits()),
9511 nullptr, clang::ArraySizeModifier::Normal, 0);
9512 InitializedEntity HiddenArray =
9513 InitializedEntity::InitializeTemporary(ArrayType);
9514 return diagnoseListInit(S, HiddenArray, InitList);
9517 if (DestType->isReferenceType()) {
9518 // A list-initialization failure for a reference means that we tried to
9519 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
9520 // inner initialization failed.
9521 QualType T = DestType->castAs<ReferenceType>()->getPointeeType();
9522 diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
9523 SourceLocation Loc = InitList->getBeginLoc();
9524 if (auto *D = Entity.getDecl())
9525 Loc = D->getLocation();
9526 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
9527 return;
9530 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
9531 /*VerifyOnly=*/false,
9532 /*TreatUnavailableAsInvalid=*/false);
9533 assert(DiagnoseInitList.HadError() &&
9534 "Inconsistent init list check result.");
9537 bool InitializationSequence::Diagnose(Sema &S,
9538 const InitializedEntity &Entity,
9539 const InitializationKind &Kind,
9540 ArrayRef<Expr *> Args) {
9541 if (!Failed())
9542 return false;
9544 // When we want to diagnose only one element of a braced-init-list,
9545 // we need to factor it out.
9546 Expr *OnlyArg;
9547 if (Args.size() == 1) {
9548 auto *List = dyn_cast<InitListExpr>(Args[0]);
9549 if (List && List->getNumInits() == 1)
9550 OnlyArg = List->getInit(0);
9551 else
9552 OnlyArg = Args[0];
9554 else
9555 OnlyArg = nullptr;
9557 QualType DestType = Entity.getType();
9558 switch (Failure) {
9559 case FK_TooManyInitsForReference:
9560 // FIXME: Customize for the initialized entity?
9561 if (Args.empty()) {
9562 // Dig out the reference subobject which is uninitialized and diagnose it.
9563 // If this is value-initialization, this could be nested some way within
9564 // the target type.
9565 assert(Kind.getKind() == InitializationKind::IK_Value ||
9566 DestType->isReferenceType());
9567 bool Diagnosed =
9568 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
9569 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
9570 (void)Diagnosed;
9571 } else // FIXME: diagnostic below could be better!
9572 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
9573 << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9574 break;
9575 case FK_ParenthesizedListInitForReference:
9576 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
9577 << 1 << Entity.getType() << Args[0]->getSourceRange();
9578 break;
9580 case FK_ArrayNeedsInitList:
9581 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
9582 break;
9583 case FK_ArrayNeedsInitListOrStringLiteral:
9584 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
9585 break;
9586 case FK_ArrayNeedsInitListOrWideStringLiteral:
9587 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
9588 break;
9589 case FK_NarrowStringIntoWideCharArray:
9590 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
9591 break;
9592 case FK_WideStringIntoCharArray:
9593 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
9594 break;
9595 case FK_IncompatWideStringIntoWideChar:
9596 S.Diag(Kind.getLocation(),
9597 diag::err_array_init_incompat_wide_string_into_wchar);
9598 break;
9599 case FK_PlainStringIntoUTF8Char:
9600 S.Diag(Kind.getLocation(),
9601 diag::err_array_init_plain_string_into_char8_t);
9602 S.Diag(Args.front()->getBeginLoc(),
9603 diag::note_array_init_plain_string_into_char8_t)
9604 << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8");
9605 break;
9606 case FK_UTF8StringIntoPlainChar:
9607 S.Diag(Kind.getLocation(), diag::err_array_init_utf8_string_into_char)
9608 << DestType->isSignedIntegerType() << S.getLangOpts().CPlusPlus20;
9609 break;
9610 case FK_ArrayTypeMismatch:
9611 case FK_NonConstantArrayInit:
9612 S.Diag(Kind.getLocation(),
9613 (Failure == FK_ArrayTypeMismatch
9614 ? diag::err_array_init_different_type
9615 : diag::err_array_init_non_constant_array))
9616 << DestType.getNonReferenceType()
9617 << OnlyArg->getType()
9618 << Args[0]->getSourceRange();
9619 break;
9621 case FK_VariableLengthArrayHasInitializer:
9622 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
9623 << Args[0]->getSourceRange();
9624 break;
9626 case FK_AddressOfOverloadFailed: {
9627 DeclAccessPair Found;
9628 S.ResolveAddressOfOverloadedFunction(OnlyArg,
9629 DestType.getNonReferenceType(),
9630 true,
9631 Found);
9632 break;
9635 case FK_AddressOfUnaddressableFunction: {
9636 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl());
9637 S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
9638 OnlyArg->getBeginLoc());
9639 break;
9642 case FK_ReferenceInitOverloadFailed:
9643 case FK_UserConversionOverloadFailed:
9644 switch (FailedOverloadResult) {
9645 case OR_Ambiguous:
9647 FailedCandidateSet.NoteCandidates(
9648 PartialDiagnosticAt(
9649 Kind.getLocation(),
9650 Failure == FK_UserConversionOverloadFailed
9651 ? (S.PDiag(diag::err_typecheck_ambiguous_condition)
9652 << OnlyArg->getType() << DestType
9653 << Args[0]->getSourceRange())
9654 : (S.PDiag(diag::err_ref_init_ambiguous)
9655 << DestType << OnlyArg->getType()
9656 << Args[0]->getSourceRange())),
9657 S, OCD_AmbiguousCandidates, Args);
9658 break;
9660 case OR_No_Viable_Function: {
9661 auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args);
9662 if (!S.RequireCompleteType(Kind.getLocation(),
9663 DestType.getNonReferenceType(),
9664 diag::err_typecheck_nonviable_condition_incomplete,
9665 OnlyArg->getType(), Args[0]->getSourceRange()))
9666 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
9667 << (Entity.getKind() == InitializedEntity::EK_Result)
9668 << OnlyArg->getType() << Args[0]->getSourceRange()
9669 << DestType.getNonReferenceType();
9671 FailedCandidateSet.NoteCandidates(S, Args, Cands);
9672 break;
9674 case OR_Deleted: {
9675 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
9676 << OnlyArg->getType() << DestType.getNonReferenceType()
9677 << Args[0]->getSourceRange();
9678 OverloadCandidateSet::iterator Best;
9679 OverloadingResult Ovl
9680 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9681 if (Ovl == OR_Deleted) {
9682 S.NoteDeletedFunction(Best->Function);
9683 } else {
9684 llvm_unreachable("Inconsistent overload resolution?");
9686 break;
9689 case OR_Success:
9690 llvm_unreachable("Conversion did not fail!");
9692 break;
9694 case FK_NonConstLValueReferenceBindingToTemporary:
9695 if (isa<InitListExpr>(Args[0])) {
9696 S.Diag(Kind.getLocation(),
9697 diag::err_lvalue_reference_bind_to_initlist)
9698 << DestType.getNonReferenceType().isVolatileQualified()
9699 << DestType.getNonReferenceType()
9700 << Args[0]->getSourceRange();
9701 break;
9703 [[fallthrough]];
9705 case FK_NonConstLValueReferenceBindingToUnrelated:
9706 S.Diag(Kind.getLocation(),
9707 Failure == FK_NonConstLValueReferenceBindingToTemporary
9708 ? diag::err_lvalue_reference_bind_to_temporary
9709 : diag::err_lvalue_reference_bind_to_unrelated)
9710 << DestType.getNonReferenceType().isVolatileQualified()
9711 << DestType.getNonReferenceType()
9712 << OnlyArg->getType()
9713 << Args[0]->getSourceRange();
9714 break;
9716 case FK_NonConstLValueReferenceBindingToBitfield: {
9717 // We don't necessarily have an unambiguous source bit-field.
9718 FieldDecl *BitField = Args[0]->getSourceBitField();
9719 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
9720 << DestType.isVolatileQualified()
9721 << (BitField ? BitField->getDeclName() : DeclarationName())
9722 << (BitField != nullptr)
9723 << Args[0]->getSourceRange();
9724 if (BitField)
9725 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
9726 break;
9729 case FK_NonConstLValueReferenceBindingToVectorElement:
9730 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
9731 << DestType.isVolatileQualified()
9732 << Args[0]->getSourceRange();
9733 break;
9735 case FK_NonConstLValueReferenceBindingToMatrixElement:
9736 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_matrix_element)
9737 << DestType.isVolatileQualified() << Args[0]->getSourceRange();
9738 break;
9740 case FK_RValueReferenceBindingToLValue:
9741 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
9742 << DestType.getNonReferenceType() << OnlyArg->getType()
9743 << Args[0]->getSourceRange();
9744 break;
9746 case FK_ReferenceAddrspaceMismatchTemporary:
9747 S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace)
9748 << DestType << Args[0]->getSourceRange();
9749 break;
9751 case FK_ReferenceInitDropsQualifiers: {
9752 QualType SourceType = OnlyArg->getType();
9753 QualType NonRefType = DestType.getNonReferenceType();
9754 Qualifiers DroppedQualifiers =
9755 SourceType.getQualifiers() - NonRefType.getQualifiers();
9757 if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf(
9758 SourceType.getQualifiers()))
9759 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9760 << NonRefType << SourceType << 1 /*addr space*/
9761 << Args[0]->getSourceRange();
9762 else if (DroppedQualifiers.hasQualifiers())
9763 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9764 << NonRefType << SourceType << 0 /*cv quals*/
9765 << Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers())
9766 << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange();
9767 else
9768 // FIXME: Consider decomposing the type and explaining which qualifiers
9769 // were dropped where, or on which level a 'const' is missing, etc.
9770 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9771 << NonRefType << SourceType << 2 /*incompatible quals*/
9772 << Args[0]->getSourceRange();
9773 break;
9776 case FK_ReferenceInitFailed:
9777 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
9778 << DestType.getNonReferenceType()
9779 << DestType.getNonReferenceType()->isIncompleteType()
9780 << OnlyArg->isLValue()
9781 << OnlyArg->getType()
9782 << Args[0]->getSourceRange();
9783 emitBadConversionNotes(S, Entity, Args[0]);
9784 break;
9786 case FK_ConversionFailed: {
9787 QualType FromType = OnlyArg->getType();
9788 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
9789 << (int)Entity.getKind()
9790 << DestType
9791 << OnlyArg->isLValue()
9792 << FromType
9793 << Args[0]->getSourceRange();
9794 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
9795 S.Diag(Kind.getLocation(), PDiag);
9796 emitBadConversionNotes(S, Entity, Args[0]);
9797 break;
9800 case FK_ConversionFromPropertyFailed:
9801 // No-op. This error has already been reported.
9802 break;
9804 case FK_TooManyInitsForScalar: {
9805 SourceRange R;
9807 auto *InitList = dyn_cast<InitListExpr>(Args[0]);
9808 if (InitList && InitList->getNumInits() >= 1) {
9809 R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc());
9810 } else {
9811 assert(Args.size() > 1 && "Expected multiple initializers!");
9812 R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc());
9815 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
9816 if (Kind.isCStyleOrFunctionalCast())
9817 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
9818 << R;
9819 else
9820 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
9821 << /*scalar=*/2 << R;
9822 break;
9825 case FK_ParenthesizedListInitForScalar:
9826 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
9827 << 0 << Entity.getType() << Args[0]->getSourceRange();
9828 break;
9830 case FK_ReferenceBindingToInitList:
9831 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
9832 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
9833 break;
9835 case FK_InitListBadDestinationType:
9836 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
9837 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
9838 break;
9840 case FK_ListConstructorOverloadFailed:
9841 case FK_ConstructorOverloadFailed: {
9842 SourceRange ArgsRange;
9843 if (Args.size())
9844 ArgsRange =
9845 SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9847 if (Failure == FK_ListConstructorOverloadFailed) {
9848 assert(Args.size() == 1 &&
9849 "List construction from other than 1 argument.");
9850 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9851 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
9854 // FIXME: Using "DestType" for the entity we're printing is probably
9855 // bad.
9856 switch (FailedOverloadResult) {
9857 case OR_Ambiguous:
9858 FailedCandidateSet.NoteCandidates(
9859 PartialDiagnosticAt(Kind.getLocation(),
9860 S.PDiag(diag::err_ovl_ambiguous_init)
9861 << DestType << ArgsRange),
9862 S, OCD_AmbiguousCandidates, Args);
9863 break;
9865 case OR_No_Viable_Function:
9866 if (Kind.getKind() == InitializationKind::IK_Default &&
9867 (Entity.getKind() == InitializedEntity::EK_Base ||
9868 Entity.getKind() == InitializedEntity::EK_Member ||
9869 Entity.getKind() == InitializedEntity::EK_ParenAggInitMember) &&
9870 isa<CXXConstructorDecl>(S.CurContext)) {
9871 // This is implicit default initialization of a member or
9872 // base within a constructor. If no viable function was
9873 // found, notify the user that they need to explicitly
9874 // initialize this base/member.
9875 CXXConstructorDecl *Constructor
9876 = cast<CXXConstructorDecl>(S.CurContext);
9877 const CXXRecordDecl *InheritedFrom = nullptr;
9878 if (auto Inherited = Constructor->getInheritedConstructor())
9879 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
9880 if (Entity.getKind() == InitializedEntity::EK_Base) {
9881 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9882 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
9883 << S.Context.getTypeDeclType(Constructor->getParent())
9884 << /*base=*/0
9885 << Entity.getType()
9886 << InheritedFrom;
9888 RecordDecl *BaseDecl
9889 = Entity.getBaseSpecifier()->getType()->castAs<RecordType>()
9890 ->getDecl();
9891 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
9892 << S.Context.getTagDeclType(BaseDecl);
9893 } else {
9894 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9895 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
9896 << S.Context.getTypeDeclType(Constructor->getParent())
9897 << /*member=*/1
9898 << Entity.getName()
9899 << InheritedFrom;
9900 S.Diag(Entity.getDecl()->getLocation(),
9901 diag::note_member_declared_at);
9903 if (const RecordType *Record
9904 = Entity.getType()->getAs<RecordType>())
9905 S.Diag(Record->getDecl()->getLocation(),
9906 diag::note_previous_decl)
9907 << S.Context.getTagDeclType(Record->getDecl());
9909 break;
9912 FailedCandidateSet.NoteCandidates(
9913 PartialDiagnosticAt(
9914 Kind.getLocation(),
9915 S.PDiag(diag::err_ovl_no_viable_function_in_init)
9916 << DestType << ArgsRange),
9917 S, OCD_AllCandidates, Args);
9918 break;
9920 case OR_Deleted: {
9921 OverloadCandidateSet::iterator Best;
9922 OverloadingResult Ovl
9923 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9924 if (Ovl != OR_Deleted) {
9925 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
9926 << DestType << ArgsRange;
9927 llvm_unreachable("Inconsistent overload resolution?");
9928 break;
9931 // If this is a defaulted or implicitly-declared function, then
9932 // it was implicitly deleted. Make it clear that the deletion was
9933 // implicit.
9934 if (S.isImplicitlyDeleted(Best->Function))
9935 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
9936 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
9937 << DestType << ArgsRange;
9938 else
9939 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
9940 << DestType << ArgsRange;
9942 S.NoteDeletedFunction(Best->Function);
9943 break;
9946 case OR_Success:
9947 llvm_unreachable("Conversion did not fail!");
9950 break;
9952 case FK_DefaultInitOfConst:
9953 if (Entity.getKind() == InitializedEntity::EK_Member &&
9954 isa<CXXConstructorDecl>(S.CurContext)) {
9955 // This is implicit default-initialization of a const member in
9956 // a constructor. Complain that it needs to be explicitly
9957 // initialized.
9958 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
9959 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
9960 << (Constructor->getInheritedConstructor() ? 2 :
9961 Constructor->isImplicit() ? 1 : 0)
9962 << S.Context.getTypeDeclType(Constructor->getParent())
9963 << /*const=*/1
9964 << Entity.getName();
9965 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
9966 << Entity.getName();
9967 } else if (const auto *VD = dyn_cast_if_present<VarDecl>(Entity.getDecl());
9968 VD && VD->isConstexpr()) {
9969 S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
9970 << VD;
9971 } else {
9972 S.Diag(Kind.getLocation(), diag::err_default_init_const)
9973 << DestType << (bool)DestType->getAs<RecordType>();
9975 break;
9977 case FK_Incomplete:
9978 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
9979 diag::err_init_incomplete_type);
9980 break;
9982 case FK_ListInitializationFailed: {
9983 // Run the init list checker again to emit diagnostics.
9984 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9985 diagnoseListInit(S, Entity, InitList);
9986 break;
9989 case FK_PlaceholderType: {
9990 // FIXME: Already diagnosed!
9991 break;
9994 case FK_ExplicitConstructor: {
9995 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
9996 << Args[0]->getSourceRange();
9997 OverloadCandidateSet::iterator Best;
9998 OverloadingResult Ovl
9999 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
10000 (void)Ovl;
10001 assert(Ovl == OR_Success && "Inconsistent overload resolution");
10002 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
10003 S.Diag(CtorDecl->getLocation(),
10004 diag::note_explicit_ctor_deduction_guide_here) << false;
10005 break;
10008 case FK_ParenthesizedListInitFailed:
10009 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
10010 /*VerifyOnly=*/false);
10011 break;
10013 case FK_DesignatedInitForNonAggregate:
10014 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
10015 S.Diag(Kind.getLocation(), diag::err_designated_init_for_non_aggregate)
10016 << Entity.getType() << InitList->getSourceRange();
10017 break;
10020 PrintInitLocationNote(S, Entity);
10021 return true;
10024 void InitializationSequence::dump(raw_ostream &OS) const {
10025 switch (SequenceKind) {
10026 case FailedSequence: {
10027 OS << "Failed sequence: ";
10028 switch (Failure) {
10029 case FK_TooManyInitsForReference:
10030 OS << "too many initializers for reference";
10031 break;
10033 case FK_ParenthesizedListInitForReference:
10034 OS << "parenthesized list init for reference";
10035 break;
10037 case FK_ArrayNeedsInitList:
10038 OS << "array requires initializer list";
10039 break;
10041 case FK_AddressOfUnaddressableFunction:
10042 OS << "address of unaddressable function was taken";
10043 break;
10045 case FK_ArrayNeedsInitListOrStringLiteral:
10046 OS << "array requires initializer list or string literal";
10047 break;
10049 case FK_ArrayNeedsInitListOrWideStringLiteral:
10050 OS << "array requires initializer list or wide string literal";
10051 break;
10053 case FK_NarrowStringIntoWideCharArray:
10054 OS << "narrow string into wide char array";
10055 break;
10057 case FK_WideStringIntoCharArray:
10058 OS << "wide string into char array";
10059 break;
10061 case FK_IncompatWideStringIntoWideChar:
10062 OS << "incompatible wide string into wide char array";
10063 break;
10065 case FK_PlainStringIntoUTF8Char:
10066 OS << "plain string literal into char8_t array";
10067 break;
10069 case FK_UTF8StringIntoPlainChar:
10070 OS << "u8 string literal into char array";
10071 break;
10073 case FK_ArrayTypeMismatch:
10074 OS << "array type mismatch";
10075 break;
10077 case FK_NonConstantArrayInit:
10078 OS << "non-constant array initializer";
10079 break;
10081 case FK_AddressOfOverloadFailed:
10082 OS << "address of overloaded function failed";
10083 break;
10085 case FK_ReferenceInitOverloadFailed:
10086 OS << "overload resolution for reference initialization failed";
10087 break;
10089 case FK_NonConstLValueReferenceBindingToTemporary:
10090 OS << "non-const lvalue reference bound to temporary";
10091 break;
10093 case FK_NonConstLValueReferenceBindingToBitfield:
10094 OS << "non-const lvalue reference bound to bit-field";
10095 break;
10097 case FK_NonConstLValueReferenceBindingToVectorElement:
10098 OS << "non-const lvalue reference bound to vector element";
10099 break;
10101 case FK_NonConstLValueReferenceBindingToMatrixElement:
10102 OS << "non-const lvalue reference bound to matrix element";
10103 break;
10105 case FK_NonConstLValueReferenceBindingToUnrelated:
10106 OS << "non-const lvalue reference bound to unrelated type";
10107 break;
10109 case FK_RValueReferenceBindingToLValue:
10110 OS << "rvalue reference bound to an lvalue";
10111 break;
10113 case FK_ReferenceInitDropsQualifiers:
10114 OS << "reference initialization drops qualifiers";
10115 break;
10117 case FK_ReferenceAddrspaceMismatchTemporary:
10118 OS << "reference with mismatching address space bound to temporary";
10119 break;
10121 case FK_ReferenceInitFailed:
10122 OS << "reference initialization failed";
10123 break;
10125 case FK_ConversionFailed:
10126 OS << "conversion failed";
10127 break;
10129 case FK_ConversionFromPropertyFailed:
10130 OS << "conversion from property failed";
10131 break;
10133 case FK_TooManyInitsForScalar:
10134 OS << "too many initializers for scalar";
10135 break;
10137 case FK_ParenthesizedListInitForScalar:
10138 OS << "parenthesized list init for reference";
10139 break;
10141 case FK_ReferenceBindingToInitList:
10142 OS << "referencing binding to initializer list";
10143 break;
10145 case FK_InitListBadDestinationType:
10146 OS << "initializer list for non-aggregate, non-scalar type";
10147 break;
10149 case FK_UserConversionOverloadFailed:
10150 OS << "overloading failed for user-defined conversion";
10151 break;
10153 case FK_ConstructorOverloadFailed:
10154 OS << "constructor overloading failed";
10155 break;
10157 case FK_DefaultInitOfConst:
10158 OS << "default initialization of a const variable";
10159 break;
10161 case FK_Incomplete:
10162 OS << "initialization of incomplete type";
10163 break;
10165 case FK_ListInitializationFailed:
10166 OS << "list initialization checker failure";
10167 break;
10169 case FK_VariableLengthArrayHasInitializer:
10170 OS << "variable length array has an initializer";
10171 break;
10173 case FK_PlaceholderType:
10174 OS << "initializer expression isn't contextually valid";
10175 break;
10177 case FK_ListConstructorOverloadFailed:
10178 OS << "list constructor overloading failed";
10179 break;
10181 case FK_ExplicitConstructor:
10182 OS << "list copy initialization chose explicit constructor";
10183 break;
10185 case FK_ParenthesizedListInitFailed:
10186 OS << "parenthesized list initialization failed";
10187 break;
10189 case FK_DesignatedInitForNonAggregate:
10190 OS << "designated initializer for non-aggregate type";
10191 break;
10193 OS << '\n';
10194 return;
10197 case DependentSequence:
10198 OS << "Dependent sequence\n";
10199 return;
10201 case NormalSequence:
10202 OS << "Normal sequence: ";
10203 break;
10206 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
10207 if (S != step_begin()) {
10208 OS << " -> ";
10211 switch (S->Kind) {
10212 case SK_ResolveAddressOfOverloadedFunction:
10213 OS << "resolve address of overloaded function";
10214 break;
10216 case SK_CastDerivedToBasePRValue:
10217 OS << "derived-to-base (prvalue)";
10218 break;
10220 case SK_CastDerivedToBaseXValue:
10221 OS << "derived-to-base (xvalue)";
10222 break;
10224 case SK_CastDerivedToBaseLValue:
10225 OS << "derived-to-base (lvalue)";
10226 break;
10228 case SK_BindReference:
10229 OS << "bind reference to lvalue";
10230 break;
10232 case SK_BindReferenceToTemporary:
10233 OS << "bind reference to a temporary";
10234 break;
10236 case SK_FinalCopy:
10237 OS << "final copy in class direct-initialization";
10238 break;
10240 case SK_ExtraneousCopyToTemporary:
10241 OS << "extraneous C++03 copy to temporary";
10242 break;
10244 case SK_UserConversion:
10245 OS << "user-defined conversion via " << *S->Function.Function;
10246 break;
10248 case SK_QualificationConversionPRValue:
10249 OS << "qualification conversion (prvalue)";
10250 break;
10252 case SK_QualificationConversionXValue:
10253 OS << "qualification conversion (xvalue)";
10254 break;
10256 case SK_QualificationConversionLValue:
10257 OS << "qualification conversion (lvalue)";
10258 break;
10260 case SK_FunctionReferenceConversion:
10261 OS << "function reference conversion";
10262 break;
10264 case SK_AtomicConversion:
10265 OS << "non-atomic-to-atomic conversion";
10266 break;
10268 case SK_ConversionSequence:
10269 OS << "implicit conversion sequence (";
10270 S->ICS->dump(); // FIXME: use OS
10271 OS << ")";
10272 break;
10274 case SK_ConversionSequenceNoNarrowing:
10275 OS << "implicit conversion sequence with narrowing prohibited (";
10276 S->ICS->dump(); // FIXME: use OS
10277 OS << ")";
10278 break;
10280 case SK_ListInitialization:
10281 OS << "list aggregate initialization";
10282 break;
10284 case SK_UnwrapInitList:
10285 OS << "unwrap reference initializer list";
10286 break;
10288 case SK_RewrapInitList:
10289 OS << "rewrap reference initializer list";
10290 break;
10292 case SK_ConstructorInitialization:
10293 OS << "constructor initialization";
10294 break;
10296 case SK_ConstructorInitializationFromList:
10297 OS << "list initialization via constructor";
10298 break;
10300 case SK_ZeroInitialization:
10301 OS << "zero initialization";
10302 break;
10304 case SK_CAssignment:
10305 OS << "C assignment";
10306 break;
10308 case SK_StringInit:
10309 OS << "string initialization";
10310 break;
10312 case SK_ObjCObjectConversion:
10313 OS << "Objective-C object conversion";
10314 break;
10316 case SK_ArrayLoopIndex:
10317 OS << "indexing for array initialization loop";
10318 break;
10320 case SK_ArrayLoopInit:
10321 OS << "array initialization loop";
10322 break;
10324 case SK_ArrayInit:
10325 OS << "array initialization";
10326 break;
10328 case SK_GNUArrayInit:
10329 OS << "array initialization (GNU extension)";
10330 break;
10332 case SK_ParenthesizedArrayInit:
10333 OS << "parenthesized array initialization";
10334 break;
10336 case SK_PassByIndirectCopyRestore:
10337 OS << "pass by indirect copy and restore";
10338 break;
10340 case SK_PassByIndirectRestore:
10341 OS << "pass by indirect restore";
10342 break;
10344 case SK_ProduceObjCObject:
10345 OS << "Objective-C object retension";
10346 break;
10348 case SK_StdInitializerList:
10349 OS << "std::initializer_list from initializer list";
10350 break;
10352 case SK_StdInitializerListConstructorCall:
10353 OS << "list initialization from std::initializer_list";
10354 break;
10356 case SK_OCLSamplerInit:
10357 OS << "OpenCL sampler_t from integer constant";
10358 break;
10360 case SK_OCLZeroOpaqueType:
10361 OS << "OpenCL opaque type from zero";
10362 break;
10363 case SK_ParenthesizedListInit:
10364 OS << "initialization from a parenthesized list of values";
10365 break;
10368 OS << " [" << S->Type << ']';
10371 OS << '\n';
10374 void InitializationSequence::dump() const {
10375 dump(llvm::errs());
10378 static bool NarrowingErrs(const LangOptions &L) {
10379 return L.CPlusPlus11 &&
10380 (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015));
10383 static void DiagnoseNarrowingInInitList(Sema &S,
10384 const ImplicitConversionSequence &ICS,
10385 QualType PreNarrowingType,
10386 QualType EntityType,
10387 const Expr *PostInit) {
10388 const StandardConversionSequence *SCS = nullptr;
10389 switch (ICS.getKind()) {
10390 case ImplicitConversionSequence::StandardConversion:
10391 SCS = &ICS.Standard;
10392 break;
10393 case ImplicitConversionSequence::UserDefinedConversion:
10394 SCS = &ICS.UserDefined.After;
10395 break;
10396 case ImplicitConversionSequence::AmbiguousConversion:
10397 case ImplicitConversionSequence::StaticObjectArgumentConversion:
10398 case ImplicitConversionSequence::EllipsisConversion:
10399 case ImplicitConversionSequence::BadConversion:
10400 return;
10403 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
10404 APValue ConstantValue;
10405 QualType ConstantType;
10406 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
10407 ConstantType)) {
10408 case NK_Not_Narrowing:
10409 case NK_Dependent_Narrowing:
10410 // No narrowing occurred.
10411 return;
10413 case NK_Type_Narrowing:
10414 // This was a floating-to-integer conversion, which is always considered a
10415 // narrowing conversion even if the value is a constant and can be
10416 // represented exactly as an integer.
10417 S.Diag(PostInit->getBeginLoc(), NarrowingErrs(S.getLangOpts())
10418 ? diag::ext_init_list_type_narrowing
10419 : diag::warn_init_list_type_narrowing)
10420 << PostInit->getSourceRange()
10421 << PreNarrowingType.getLocalUnqualifiedType()
10422 << EntityType.getNonReferenceType().getLocalUnqualifiedType();
10423 break;
10425 case NK_Constant_Narrowing:
10426 // A constant value was narrowed.
10427 S.Diag(PostInit->getBeginLoc(),
10428 NarrowingErrs(S.getLangOpts())
10429 ? diag::ext_init_list_constant_narrowing
10430 : diag::warn_init_list_constant_narrowing)
10431 << PostInit->getSourceRange()
10432 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
10433 << EntityType.getNonReferenceType().getLocalUnqualifiedType();
10434 break;
10436 case NK_Variable_Narrowing:
10437 // A variable's value may have been narrowed.
10438 S.Diag(PostInit->getBeginLoc(),
10439 NarrowingErrs(S.getLangOpts())
10440 ? diag::ext_init_list_variable_narrowing
10441 : diag::warn_init_list_variable_narrowing)
10442 << PostInit->getSourceRange()
10443 << PreNarrowingType.getLocalUnqualifiedType()
10444 << EntityType.getNonReferenceType().getLocalUnqualifiedType();
10445 break;
10448 SmallString<128> StaticCast;
10449 llvm::raw_svector_ostream OS(StaticCast);
10450 OS << "static_cast<";
10451 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
10452 // It's important to use the typedef's name if there is one so that the
10453 // fixit doesn't break code using types like int64_t.
10455 // FIXME: This will break if the typedef requires qualification. But
10456 // getQualifiedNameAsString() includes non-machine-parsable components.
10457 OS << *TT->getDecl();
10458 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
10459 OS << BT->getName(S.getLangOpts());
10460 else {
10461 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
10462 // with a broken cast.
10463 return;
10465 OS << ">(";
10466 S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence)
10467 << PostInit->getSourceRange()
10468 << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str())
10469 << FixItHint::CreateInsertion(
10470 S.getLocForEndOfToken(PostInit->getEndLoc()), ")");
10473 //===----------------------------------------------------------------------===//
10474 // Initialization helper functions
10475 //===----------------------------------------------------------------------===//
10476 bool
10477 Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
10478 ExprResult Init) {
10479 if (Init.isInvalid())
10480 return false;
10482 Expr *InitE = Init.get();
10483 assert(InitE && "No initialization expression");
10485 InitializationKind Kind =
10486 InitializationKind::CreateCopy(InitE->getBeginLoc(), SourceLocation());
10487 InitializationSequence Seq(*this, Entity, Kind, InitE);
10488 return !Seq.Failed();
10491 ExprResult
10492 Sema::PerformCopyInitialization(const InitializedEntity &Entity,
10493 SourceLocation EqualLoc,
10494 ExprResult Init,
10495 bool TopLevelOfInitList,
10496 bool AllowExplicit) {
10497 if (Init.isInvalid())
10498 return ExprError();
10500 Expr *InitE = Init.get();
10501 assert(InitE && "No initialization expression?");
10503 if (EqualLoc.isInvalid())
10504 EqualLoc = InitE->getBeginLoc();
10506 InitializationKind Kind = InitializationKind::CreateCopy(
10507 InitE->getBeginLoc(), EqualLoc, AllowExplicit);
10508 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
10510 // Prevent infinite recursion when performing parameter copy-initialization.
10511 const bool ShouldTrackCopy =
10512 Entity.isParameterKind() && Seq.isConstructorInitialization();
10513 if (ShouldTrackCopy) {
10514 if (llvm::is_contained(CurrentParameterCopyTypes, Entity.getType())) {
10515 Seq.SetOverloadFailure(
10516 InitializationSequence::FK_ConstructorOverloadFailed,
10517 OR_No_Viable_Function);
10519 // Try to give a meaningful diagnostic note for the problematic
10520 // constructor.
10521 const auto LastStep = Seq.step_end() - 1;
10522 assert(LastStep->Kind ==
10523 InitializationSequence::SK_ConstructorInitialization);
10524 const FunctionDecl *Function = LastStep->Function.Function;
10525 auto Candidate =
10526 llvm::find_if(Seq.getFailedCandidateSet(),
10527 [Function](const OverloadCandidate &Candidate) -> bool {
10528 return Candidate.Viable &&
10529 Candidate.Function == Function &&
10530 Candidate.Conversions.size() > 0;
10532 if (Candidate != Seq.getFailedCandidateSet().end() &&
10533 Function->getNumParams() > 0) {
10534 Candidate->Viable = false;
10535 Candidate->FailureKind = ovl_fail_bad_conversion;
10536 Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion,
10537 InitE,
10538 Function->getParamDecl(0)->getType());
10541 CurrentParameterCopyTypes.push_back(Entity.getType());
10544 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
10546 if (ShouldTrackCopy)
10547 CurrentParameterCopyTypes.pop_back();
10549 return Result;
10552 /// Determine whether RD is, or is derived from, a specialization of CTD.
10553 static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD,
10554 ClassTemplateDecl *CTD) {
10555 auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
10556 auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
10557 return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
10559 return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
10562 QualType Sema::DeduceTemplateSpecializationFromInitializer(
10563 TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
10564 const InitializationKind &Kind, MultiExprArg Inits) {
10565 auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
10566 TSInfo->getType()->getContainedDeducedType());
10567 assert(DeducedTST && "not a deduced template specialization type");
10569 auto TemplateName = DeducedTST->getTemplateName();
10570 if (TemplateName.isDependent())
10571 return SubstAutoTypeDependent(TSInfo->getType());
10573 // We can only perform deduction for class templates.
10574 auto *Template =
10575 dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
10576 if (!Template) {
10577 Diag(Kind.getLocation(),
10578 diag::err_deduced_non_class_template_specialization_type)
10579 << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName;
10580 if (auto *TD = TemplateName.getAsTemplateDecl())
10581 NoteTemplateLocation(*TD);
10582 return QualType();
10585 // Can't deduce from dependent arguments.
10586 if (Expr::hasAnyTypeDependentArguments(Inits)) {
10587 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10588 diag::warn_cxx14_compat_class_template_argument_deduction)
10589 << TSInfo->getTypeLoc().getSourceRange() << 0;
10590 return SubstAutoTypeDependent(TSInfo->getType());
10593 // FIXME: Perform "exact type" matching first, per CWG discussion?
10594 // Or implement this via an implied 'T(T) -> T' deduction guide?
10596 // FIXME: Do we need/want a std::initializer_list<T> special case?
10598 // Look up deduction guides, including those synthesized from constructors.
10600 // C++1z [over.match.class.deduct]p1:
10601 // A set of functions and function templates is formed comprising:
10602 // - For each constructor of the class template designated by the
10603 // template-name, a function template [...]
10604 // - For each deduction-guide, a function or function template [...]
10605 DeclarationNameInfo NameInfo(
10606 Context.DeclarationNames.getCXXDeductionGuideName(Template),
10607 TSInfo->getTypeLoc().getEndLoc());
10608 LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
10609 LookupQualifiedName(Guides, Template->getDeclContext());
10611 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
10612 // clear on this, but they're not found by name so access does not apply.
10613 Guides.suppressDiagnostics();
10615 // Figure out if this is list-initialization.
10616 InitListExpr *ListInit =
10617 (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
10618 ? dyn_cast<InitListExpr>(Inits[0])
10619 : nullptr;
10621 // C++1z [over.match.class.deduct]p1:
10622 // Initialization and overload resolution are performed as described in
10623 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
10624 // (as appropriate for the type of initialization performed) for an object
10625 // of a hypothetical class type, where the selected functions and function
10626 // templates are considered to be the constructors of that class type
10628 // Since we know we're initializing a class type of a type unrelated to that
10629 // of the initializer, this reduces to something fairly reasonable.
10630 OverloadCandidateSet Candidates(Kind.getLocation(),
10631 OverloadCandidateSet::CSK_Normal);
10632 OverloadCandidateSet::iterator Best;
10634 bool AllowExplicit = !Kind.isCopyInit() || ListInit;
10636 // Return true if the candidate is added successfully, false otherwise.
10637 auto addDeductionCandidate = [&](FunctionTemplateDecl *TD,
10638 CXXDeductionGuideDecl *GD,
10639 DeclAccessPair FoundDecl,
10640 bool OnlyListConstructors,
10641 bool AllowAggregateDeductionCandidate) {
10642 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
10643 // For copy-initialization, the candidate functions are all the
10644 // converting constructors (12.3.1) of that class.
10645 // C++ [over.match.copy]p1: (non-list copy-initialization from class)
10646 // The converting constructors of T are candidate functions.
10647 if (!AllowExplicit) {
10648 // Overload resolution checks whether the deduction guide is declared
10649 // explicit for us.
10651 // When looking for a converting constructor, deduction guides that
10652 // could never be called with one argument are not interesting to
10653 // check or note.
10654 if (GD->getMinRequiredArguments() > 1 ||
10655 (GD->getNumParams() == 0 && !GD->isVariadic()))
10656 return;
10659 // C++ [over.match.list]p1.1: (first phase list initialization)
10660 // Initially, the candidate functions are the initializer-list
10661 // constructors of the class T
10662 if (OnlyListConstructors && !isInitListConstructor(GD))
10663 return;
10665 if (!AllowAggregateDeductionCandidate &&
10666 GD->getDeductionCandidateKind() == DeductionCandidate::Aggregate)
10667 return;
10669 // C++ [over.match.list]p1.2: (second phase list initialization)
10670 // the candidate functions are all the constructors of the class T
10671 // C++ [over.match.ctor]p1: (all other cases)
10672 // the candidate functions are all the constructors of the class of
10673 // the object being initialized
10675 // C++ [over.best.ics]p4:
10676 // When [...] the constructor [...] is a candidate by
10677 // - [over.match.copy] (in all cases)
10678 // FIXME: The "second phase of [over.match.list] case can also
10679 // theoretically happen here, but it's not clear whether we can
10680 // ever have a parameter of the right type.
10681 bool SuppressUserConversions = Kind.isCopyInit();
10683 if (TD) {
10684 SmallVector<Expr *, 8> TmpInits;
10685 for (Expr *E : Inits)
10686 if (auto *DI = dyn_cast<DesignatedInitExpr>(E))
10687 TmpInits.push_back(DI->getInit());
10688 else
10689 TmpInits.push_back(E);
10690 AddTemplateOverloadCandidate(
10691 TD, FoundDecl, /*ExplicitArgs=*/nullptr, TmpInits, Candidates,
10692 SuppressUserConversions,
10693 /*PartialOverloading=*/false, AllowExplicit, ADLCallKind::NotADL,
10694 /*PO=*/{}, AllowAggregateDeductionCandidate);
10695 } else {
10696 AddOverloadCandidate(GD, FoundDecl, Inits, Candidates,
10697 SuppressUserConversions,
10698 /*PartialOverloading=*/false, AllowExplicit);
10702 bool FoundDeductionGuide = false;
10704 auto TryToResolveOverload =
10705 [&](bool OnlyListConstructors) -> OverloadingResult {
10706 Candidates.clear(OverloadCandidateSet::CSK_Normal);
10707 bool HasAnyDeductionGuide = false;
10709 auto SynthesizeAggrGuide = [&](InitListExpr *ListInit) {
10710 auto *RD = cast<CXXRecordDecl>(Template->getTemplatedDecl());
10711 if (!(RD->getDefinition() && RD->isAggregate()))
10712 return;
10713 QualType Ty = Context.getRecordType(RD);
10714 SmallVector<QualType, 8> ElementTypes;
10716 InitListChecker CheckInitList(*this, Entity, ListInit, Ty, ElementTypes);
10717 if (!CheckInitList.HadError()) {
10718 // C++ [over.match.class.deduct]p1.8:
10719 // if e_i is of array type and x_i is a braced-init-list, T_i is an
10720 // rvalue reference to the declared type of e_i and
10721 // C++ [over.match.class.deduct]p1.9:
10722 // if e_i is of array type and x_i is a bstring-literal, T_i is an
10723 // lvalue reference to the const-qualified declared type of e_i and
10724 // C++ [over.match.class.deduct]p1.10:
10725 // otherwise, T_i is the declared type of e_i
10726 for (int I = 0, E = ListInit->getNumInits();
10727 I < E && !isa<PackExpansionType>(ElementTypes[I]); ++I)
10728 if (ElementTypes[I]->isArrayType()) {
10729 if (isa<InitListExpr>(ListInit->getInit(I)))
10730 ElementTypes[I] = Context.getRValueReferenceType(ElementTypes[I]);
10731 else if (isa<StringLiteral>(
10732 ListInit->getInit(I)->IgnoreParenImpCasts()))
10733 ElementTypes[I] =
10734 Context.getLValueReferenceType(ElementTypes[I].withConst());
10737 llvm::FoldingSetNodeID ID;
10738 ID.AddPointer(Template);
10739 for (auto &T : ElementTypes)
10740 T.getCanonicalType().Profile(ID);
10741 unsigned Hash = ID.ComputeHash();
10742 if (AggregateDeductionCandidates.count(Hash) == 0) {
10743 if (FunctionTemplateDecl *TD =
10744 DeclareImplicitDeductionGuideFromInitList(
10745 Template, ElementTypes,
10746 TSInfo->getTypeLoc().getEndLoc())) {
10747 auto *GD = cast<CXXDeductionGuideDecl>(TD->getTemplatedDecl());
10748 GD->setDeductionCandidateKind(DeductionCandidate::Aggregate);
10749 AggregateDeductionCandidates[Hash] = GD;
10750 addDeductionCandidate(TD, GD, DeclAccessPair::make(TD, AS_public),
10751 OnlyListConstructors,
10752 /*AllowAggregateDeductionCandidate=*/true);
10754 } else {
10755 CXXDeductionGuideDecl *GD = AggregateDeductionCandidates[Hash];
10756 FunctionTemplateDecl *TD = GD->getDescribedFunctionTemplate();
10757 assert(TD && "aggregate deduction candidate is function template");
10758 addDeductionCandidate(TD, GD, DeclAccessPair::make(TD, AS_public),
10759 OnlyListConstructors,
10760 /*AllowAggregateDeductionCandidate=*/true);
10762 HasAnyDeductionGuide = true;
10766 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
10767 NamedDecl *D = (*I)->getUnderlyingDecl();
10768 if (D->isInvalidDecl())
10769 continue;
10771 auto *TD = dyn_cast<FunctionTemplateDecl>(D);
10772 auto *GD = dyn_cast_if_present<CXXDeductionGuideDecl>(
10773 TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
10774 if (!GD)
10775 continue;
10777 if (!GD->isImplicit())
10778 HasAnyDeductionGuide = true;
10780 addDeductionCandidate(TD, GD, I.getPair(), OnlyListConstructors,
10781 /*AllowAggregateDeductionCandidate=*/false);
10784 // C++ [over.match.class.deduct]p1.4:
10785 // if C is defined and its definition satisfies the conditions for an
10786 // aggregate class ([dcl.init.aggr]) with the assumption that any
10787 // dependent base class has no virtual functions and no virtual base
10788 // classes, and the initializer is a non-empty braced-init-list or
10789 // parenthesized expression-list, and there are no deduction-guides for
10790 // C, the set contains an additional function template, called the
10791 // aggregate deduction candidate, defined as follows.
10792 if (getLangOpts().CPlusPlus20 && !HasAnyDeductionGuide) {
10793 if (ListInit && ListInit->getNumInits()) {
10794 SynthesizeAggrGuide(ListInit);
10795 } else if (Inits.size()) { // parenthesized expression-list
10796 // Inits are expressions inside the parentheses. We don't have
10797 // the parentheses source locations, use the begin/end of Inits as the
10798 // best heuristic.
10799 InitListExpr TempListInit(getASTContext(), Inits.front()->getBeginLoc(),
10800 Inits, Inits.back()->getEndLoc());
10801 SynthesizeAggrGuide(&TempListInit);
10805 FoundDeductionGuide = FoundDeductionGuide || HasAnyDeductionGuide;
10807 return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
10810 OverloadingResult Result = OR_No_Viable_Function;
10812 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
10813 // try initializer-list constructors.
10814 if (ListInit) {
10815 bool TryListConstructors = true;
10817 // Try list constructors unless the list is empty and the class has one or
10818 // more default constructors, in which case those constructors win.
10819 if (!ListInit->getNumInits()) {
10820 for (NamedDecl *D : Guides) {
10821 auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
10822 if (FD && FD->getMinRequiredArguments() == 0) {
10823 TryListConstructors = false;
10824 break;
10827 } else if (ListInit->getNumInits() == 1) {
10828 // C++ [over.match.class.deduct]:
10829 // As an exception, the first phase in [over.match.list] (considering
10830 // initializer-list constructors) is omitted if the initializer list
10831 // consists of a single expression of type cv U, where U is a
10832 // specialization of C or a class derived from a specialization of C.
10833 Expr *E = ListInit->getInit(0);
10834 auto *RD = E->getType()->getAsCXXRecordDecl();
10835 if (!isa<InitListExpr>(E) && RD &&
10836 isCompleteType(Kind.getLocation(), E->getType()) &&
10837 isOrIsDerivedFromSpecializationOf(RD, Template))
10838 TryListConstructors = false;
10841 if (TryListConstructors)
10842 Result = TryToResolveOverload(/*OnlyListConstructor*/true);
10843 // Then unwrap the initializer list and try again considering all
10844 // constructors.
10845 Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
10848 // If list-initialization fails, or if we're doing any other kind of
10849 // initialization, we (eventually) consider constructors.
10850 if (Result == OR_No_Viable_Function)
10851 Result = TryToResolveOverload(/*OnlyListConstructor*/false);
10853 switch (Result) {
10854 case OR_Ambiguous:
10855 // FIXME: For list-initialization candidates, it'd usually be better to
10856 // list why they were not viable when given the initializer list itself as
10857 // an argument.
10858 Candidates.NoteCandidates(
10859 PartialDiagnosticAt(
10860 Kind.getLocation(),
10861 PDiag(diag::err_deduced_class_template_ctor_ambiguous)
10862 << TemplateName),
10863 *this, OCD_AmbiguousCandidates, Inits);
10864 return QualType();
10866 case OR_No_Viable_Function: {
10867 CXXRecordDecl *Primary =
10868 cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
10869 bool Complete =
10870 isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary));
10871 Candidates.NoteCandidates(
10872 PartialDiagnosticAt(
10873 Kind.getLocation(),
10874 PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable
10875 : diag::err_deduced_class_template_incomplete)
10876 << TemplateName << !Guides.empty()),
10877 *this, OCD_AllCandidates, Inits);
10878 return QualType();
10881 case OR_Deleted: {
10882 Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
10883 << TemplateName;
10884 NoteDeletedFunction(Best->Function);
10885 return QualType();
10888 case OR_Success:
10889 // C++ [over.match.list]p1:
10890 // In copy-list-initialization, if an explicit constructor is chosen, the
10891 // initialization is ill-formed.
10892 if (Kind.isCopyInit() && ListInit &&
10893 cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
10894 bool IsDeductionGuide = !Best->Function->isImplicit();
10895 Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
10896 << TemplateName << IsDeductionGuide;
10897 Diag(Best->Function->getLocation(),
10898 diag::note_explicit_ctor_deduction_guide_here)
10899 << IsDeductionGuide;
10900 return QualType();
10903 // Make sure we didn't select an unusable deduction guide, and mark it
10904 // as referenced.
10905 DiagnoseUseOfDecl(Best->FoundDecl, Kind.getLocation());
10906 MarkFunctionReferenced(Kind.getLocation(), Best->Function);
10907 break;
10910 // C++ [dcl.type.class.deduct]p1:
10911 // The placeholder is replaced by the return type of the function selected
10912 // by overload resolution for class template deduction.
10913 QualType DeducedType =
10914 SubstAutoType(TSInfo->getType(), Best->Function->getReturnType());
10915 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10916 diag::warn_cxx14_compat_class_template_argument_deduction)
10917 << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType;
10919 // Warn if CTAD was used on a type that does not have any user-defined
10920 // deduction guides.
10921 if (!FoundDeductionGuide) {
10922 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10923 diag::warn_ctad_maybe_unsupported)
10924 << TemplateName;
10925 Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported);
10928 return DeducedType;