Path: blob/main/contrib/llvm-project/clang/lib/Sema/SemaInit.cpp
35234 views
//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements semantic analysis for initializers.9//10//===----------------------------------------------------------------------===//1112#include "CheckExprLifetime.h"13#include "clang/AST/ASTContext.h"14#include "clang/AST/DeclObjC.h"15#include "clang/AST/Expr.h"16#include "clang/AST/ExprCXX.h"17#include "clang/AST/ExprObjC.h"18#include "clang/AST/ExprOpenMP.h"19#include "clang/AST/IgnoreExpr.h"20#include "clang/AST/TypeLoc.h"21#include "clang/Basic/CharInfo.h"22#include "clang/Basic/SourceManager.h"23#include "clang/Basic/Specifiers.h"24#include "clang/Basic/TargetInfo.h"25#include "clang/Sema/Designator.h"26#include "clang/Sema/EnterExpressionEvaluationContext.h"27#include "clang/Sema/Initialization.h"28#include "clang/Sema/Lookup.h"29#include "clang/Sema/Ownership.h"30#include "clang/Sema/SemaInternal.h"31#include "clang/Sema/SemaObjC.h"32#include "llvm/ADT/APInt.h"33#include "llvm/ADT/FoldingSet.h"34#include "llvm/ADT/PointerIntPair.h"35#include "llvm/ADT/STLForwardCompat.h"36#include "llvm/ADT/SmallString.h"37#include "llvm/ADT/SmallVector.h"38#include "llvm/ADT/StringExtras.h"39#include "llvm/Support/ErrorHandling.h"40#include "llvm/Support/raw_ostream.h"4142using namespace clang;4344//===----------------------------------------------------------------------===//45// Sema Initialization Checking46//===----------------------------------------------------------------------===//4748/// Check whether T is compatible with a wide character type (wchar_t,49/// char16_t or char32_t).50static bool IsWideCharCompatible(QualType T, ASTContext &Context) {51if (Context.typesAreCompatible(Context.getWideCharType(), T))52return true;53if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {54return Context.typesAreCompatible(Context.Char16Ty, T) ||55Context.typesAreCompatible(Context.Char32Ty, T);56}57return false;58}5960enum StringInitFailureKind {61SIF_None,62SIF_NarrowStringIntoWideChar,63SIF_WideStringIntoChar,64SIF_IncompatWideStringIntoWideChar,65SIF_UTF8StringIntoPlainChar,66SIF_PlainStringIntoUTF8Char,67SIF_Other68};6970/// Check whether the array of type AT can be initialized by the Init71/// expression by means of string initialization. Returns SIF_None if so,72/// otherwise returns a StringInitFailureKind that describes why the73/// initialization would not work.74static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,75ASTContext &Context) {76if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))77return SIF_Other;7879// See if this is a string literal or @encode.80Init = Init->IgnoreParens();8182// Handle @encode, which is a narrow string.83if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())84return SIF_None;8586// Otherwise we can only handle string literals.87StringLiteral *SL = dyn_cast<StringLiteral>(Init);88if (!SL)89return SIF_Other;9091const QualType ElemTy =92Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();9394auto IsCharOrUnsignedChar = [](const QualType &T) {95const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr());96return BT && BT->isCharType() && BT->getKind() != BuiltinType::SChar;97};9899switch (SL->getKind()) {100case StringLiteralKind::UTF8:101// char8_t array can be initialized with a UTF-8 string.102// - C++20 [dcl.init.string] (DR)103// Additionally, an array of char or unsigned char may be initialized104// by a UTF-8 string literal.105if (ElemTy->isChar8Type() ||106(Context.getLangOpts().Char8 &&107IsCharOrUnsignedChar(ElemTy.getCanonicalType())))108return SIF_None;109[[fallthrough]];110case StringLiteralKind::Ordinary:111// char array can be initialized with a narrow string.112// Only allow char x[] = "foo"; not char x[] = L"foo";113if (ElemTy->isCharType())114return (SL->getKind() == StringLiteralKind::UTF8 &&115Context.getLangOpts().Char8)116? SIF_UTF8StringIntoPlainChar117: SIF_None;118if (ElemTy->isChar8Type())119return SIF_PlainStringIntoUTF8Char;120if (IsWideCharCompatible(ElemTy, Context))121return SIF_NarrowStringIntoWideChar;122return SIF_Other;123// C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:124// "An array with element type compatible with a qualified or unqualified125// version of wchar_t, char16_t, or char32_t may be initialized by a wide126// string literal with the corresponding encoding prefix (L, u, or U,127// respectively), optionally enclosed in braces.128case StringLiteralKind::UTF16:129if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))130return SIF_None;131if (ElemTy->isCharType() || ElemTy->isChar8Type())132return SIF_WideStringIntoChar;133if (IsWideCharCompatible(ElemTy, Context))134return SIF_IncompatWideStringIntoWideChar;135return SIF_Other;136case StringLiteralKind::UTF32:137if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))138return SIF_None;139if (ElemTy->isCharType() || ElemTy->isChar8Type())140return SIF_WideStringIntoChar;141if (IsWideCharCompatible(ElemTy, Context))142return SIF_IncompatWideStringIntoWideChar;143return SIF_Other;144case StringLiteralKind::Wide:145if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))146return SIF_None;147if (ElemTy->isCharType() || ElemTy->isChar8Type())148return SIF_WideStringIntoChar;149if (IsWideCharCompatible(ElemTy, Context))150return SIF_IncompatWideStringIntoWideChar;151return SIF_Other;152case StringLiteralKind::Unevaluated:153assert(false && "Unevaluated string literal in initialization");154break;155}156157llvm_unreachable("missed a StringLiteral kind?");158}159160static StringInitFailureKind IsStringInit(Expr *init, QualType declType,161ASTContext &Context) {162const ArrayType *arrayType = Context.getAsArrayType(declType);163if (!arrayType)164return SIF_Other;165return IsStringInit(init, arrayType, Context);166}167168bool Sema::IsStringInit(Expr *Init, const ArrayType *AT) {169return ::IsStringInit(Init, AT, Context) == SIF_None;170}171172/// Update the type of a string literal, including any surrounding parentheses,173/// to match the type of the object which it is initializing.174static void updateStringLiteralType(Expr *E, QualType Ty) {175while (true) {176E->setType(Ty);177E->setValueKind(VK_PRValue);178if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))179break;180E = IgnoreParensSingleStep(E);181}182}183184/// Fix a compound literal initializing an array so it's correctly marked185/// as an rvalue.186static void updateGNUCompoundLiteralRValue(Expr *E) {187while (true) {188E->setValueKind(VK_PRValue);189if (isa<CompoundLiteralExpr>(E))190break;191E = IgnoreParensSingleStep(E);192}193}194195static bool initializingConstexprVariable(const InitializedEntity &Entity) {196Decl *D = Entity.getDecl();197const InitializedEntity *Parent = &Entity;198199while (Parent) {200D = Parent->getDecl();201Parent = Parent->getParent();202}203204if (const auto *VD = dyn_cast_if_present<VarDecl>(D); VD && VD->isConstexpr())205return true;206207return false;208}209210static void CheckC23ConstexprInitStringLiteral(const StringLiteral *SE,211Sema &SemaRef, QualType &TT);212213static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,214Sema &S, bool CheckC23ConstexprInit = false) {215// Get the length of the string as parsed.216auto *ConstantArrayTy =217cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());218uint64_t StrLength = ConstantArrayTy->getZExtSize();219220if (CheckC23ConstexprInit)221if (const StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens()))222CheckC23ConstexprInitStringLiteral(SL, S, DeclT);223224if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {225// C99 6.7.8p14. We have an array of character type with unknown size226// being initialized to a string literal.227llvm::APInt ConstVal(32, StrLength);228// Return a new array type (C99 6.7.8p22).229DeclT = S.Context.getConstantArrayType(230IAT->getElementType(), ConstVal, nullptr, ArraySizeModifier::Normal, 0);231updateStringLiteralType(Str, DeclT);232return;233}234235const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);236237// We have an array of character type with known size. However,238// the size may be smaller or larger than the string we are initializing.239// FIXME: Avoid truncation for 64-bit length strings.240if (S.getLangOpts().CPlusPlus) {241if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {242// For Pascal strings it's OK to strip off the terminating null character,243// so the example below is valid:244//245// unsigned char a[2] = "\pa";246if (SL->isPascal())247StrLength--;248}249250// [dcl.init.string]p2251if (StrLength > CAT->getZExtSize())252S.Diag(Str->getBeginLoc(),253diag::err_initializer_string_for_char_array_too_long)254<< CAT->getZExtSize() << StrLength << Str->getSourceRange();255} else {256// C99 6.7.8p14.257if (StrLength - 1 > CAT->getZExtSize())258S.Diag(Str->getBeginLoc(),259diag::ext_initializer_string_for_char_array_too_long)260<< Str->getSourceRange();261}262263// Set the type to the actual size that we are initializing. If we have264// something like:265// char x[1] = "foo";266// then this will set the string literal's type to char[1].267updateStringLiteralType(Str, DeclT);268}269270//===----------------------------------------------------------------------===//271// Semantic checking for initializer lists.272//===----------------------------------------------------------------------===//273274namespace {275276/// Semantic checking for initializer lists.277///278/// The InitListChecker class contains a set of routines that each279/// handle the initialization of a certain kind of entity, e.g.,280/// arrays, vectors, struct/union types, scalars, etc. The281/// InitListChecker itself performs a recursive walk of the subobject282/// structure of the type to be initialized, while stepping through283/// the initializer list one element at a time. The IList and Index284/// parameters to each of the Check* routines contain the active285/// (syntactic) initializer list and the index into that initializer286/// list that represents the current initializer. Each routine is287/// responsible for moving that Index forward as it consumes elements.288///289/// Each Check* routine also has a StructuredList/StructuredIndex290/// arguments, which contains the current "structured" (semantic)291/// initializer list and the index into that initializer list where we292/// are copying initializers as we map them over to the semantic293/// list. Once we have completed our recursive walk of the subobject294/// structure, we will have constructed a full semantic initializer295/// list.296///297/// C99 designators cause changes in the initializer list traversal,298/// because they make the initialization "jump" into a specific299/// subobject and then continue the initialization from that300/// point. CheckDesignatedInitializer() recursively steps into the301/// designated subobject and manages backing out the recursion to302/// initialize the subobjects after the one designated.303///304/// If an initializer list contains any designators, we build a placeholder305/// structured list even in 'verify only' mode, so that we can track which306/// elements need 'empty' initializtion.307class InitListChecker {308Sema &SemaRef;309bool hadError = false;310bool VerifyOnly; // No diagnostics.311bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.312bool InOverloadResolution;313InitListExpr *FullyStructuredList = nullptr;314NoInitExpr *DummyExpr = nullptr;315SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr;316EmbedExpr *CurEmbed = nullptr; // Save current embed we're processing.317unsigned CurEmbedIndex = 0;318319NoInitExpr *getDummyInit() {320if (!DummyExpr)321DummyExpr = new (SemaRef.Context) NoInitExpr(SemaRef.Context.VoidTy);322return DummyExpr;323}324325void CheckImplicitInitList(const InitializedEntity &Entity,326InitListExpr *ParentIList, QualType T,327unsigned &Index, InitListExpr *StructuredList,328unsigned &StructuredIndex);329void CheckExplicitInitList(const InitializedEntity &Entity,330InitListExpr *IList, QualType &T,331InitListExpr *StructuredList,332bool TopLevelObject = false);333void CheckListElementTypes(const InitializedEntity &Entity,334InitListExpr *IList, QualType &DeclType,335bool SubobjectIsDesignatorContext,336unsigned &Index,337InitListExpr *StructuredList,338unsigned &StructuredIndex,339bool TopLevelObject = false);340void CheckSubElementType(const InitializedEntity &Entity,341InitListExpr *IList, QualType ElemType,342unsigned &Index,343InitListExpr *StructuredList,344unsigned &StructuredIndex,345bool DirectlyDesignated = false);346void CheckComplexType(const InitializedEntity &Entity,347InitListExpr *IList, QualType DeclType,348unsigned &Index,349InitListExpr *StructuredList,350unsigned &StructuredIndex);351void CheckScalarType(const InitializedEntity &Entity,352InitListExpr *IList, QualType DeclType,353unsigned &Index,354InitListExpr *StructuredList,355unsigned &StructuredIndex);356void CheckReferenceType(const InitializedEntity &Entity,357InitListExpr *IList, QualType DeclType,358unsigned &Index,359InitListExpr *StructuredList,360unsigned &StructuredIndex);361void CheckVectorType(const InitializedEntity &Entity,362InitListExpr *IList, QualType DeclType, unsigned &Index,363InitListExpr *StructuredList,364unsigned &StructuredIndex);365void CheckStructUnionTypes(const InitializedEntity &Entity,366InitListExpr *IList, QualType DeclType,367CXXRecordDecl::base_class_const_range Bases,368RecordDecl::field_iterator Field,369bool SubobjectIsDesignatorContext, unsigned &Index,370InitListExpr *StructuredList,371unsigned &StructuredIndex,372bool TopLevelObject = false);373void CheckArrayType(const InitializedEntity &Entity,374InitListExpr *IList, QualType &DeclType,375llvm::APSInt elementIndex,376bool SubobjectIsDesignatorContext, unsigned &Index,377InitListExpr *StructuredList,378unsigned &StructuredIndex);379bool CheckDesignatedInitializer(const InitializedEntity &Entity,380InitListExpr *IList, DesignatedInitExpr *DIE,381unsigned DesigIdx,382QualType &CurrentObjectType,383RecordDecl::field_iterator *NextField,384llvm::APSInt *NextElementIndex,385unsigned &Index,386InitListExpr *StructuredList,387unsigned &StructuredIndex,388bool FinishSubobjectInit,389bool TopLevelObject);390InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,391QualType CurrentObjectType,392InitListExpr *StructuredList,393unsigned StructuredIndex,394SourceRange InitRange,395bool IsFullyOverwritten = false);396void UpdateStructuredListElement(InitListExpr *StructuredList,397unsigned &StructuredIndex,398Expr *expr);399InitListExpr *createInitListExpr(QualType CurrentObjectType,400SourceRange InitRange,401unsigned ExpectedNumInits);402int numArrayElements(QualType DeclType);403int numStructUnionElements(QualType DeclType);404static RecordDecl *getRecordDecl(QualType DeclType);405406ExprResult PerformEmptyInit(SourceLocation Loc,407const InitializedEntity &Entity);408409/// Diagnose that OldInit (or part thereof) has been overridden by NewInit.410void diagnoseInitOverride(Expr *OldInit, SourceRange NewInitRange,411bool UnionOverride = false,412bool FullyOverwritten = true) {413// Overriding an initializer via a designator is valid with C99 designated414// initializers, but ill-formed with C++20 designated initializers.415unsigned DiagID =416SemaRef.getLangOpts().CPlusPlus417? (UnionOverride ? diag::ext_initializer_union_overrides418: diag::ext_initializer_overrides)419: diag::warn_initializer_overrides;420421if (InOverloadResolution && SemaRef.getLangOpts().CPlusPlus) {422// In overload resolution, we have to strictly enforce the rules, and so423// don't allow any overriding of prior initializers. This matters for a424// case such as:425//426// union U { int a, b; };427// struct S { int a, b; };428// void f(U), f(S);429//430// Here, f({.a = 1, .b = 2}) is required to call the struct overload. For431// consistency, we disallow all overriding of prior initializers in432// overload resolution, not only overriding of union members.433hadError = true;434} else if (OldInit->getType().isDestructedType() && !FullyOverwritten) {435// If we'll be keeping around the old initializer but overwriting part of436// the object it initialized, and that object is not trivially437// destructible, this can leak. Don't allow that, not even as an438// extension.439//440// FIXME: It might be reasonable to allow this in cases where the part of441// the initializer that we're overriding has trivial destruction.442DiagID = diag::err_initializer_overrides_destructed;443} else if (!OldInit->getSourceRange().isValid()) {444// We need to check on source range validity because the previous445// initializer does not have to be an explicit initializer. e.g.,446//447// struct P { int a, b; };448// struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };449//450// There is an overwrite taking place because the first braced initializer451// list "{ .a = 2 }" already provides value for .p.b (which is zero).452//453// Such overwrites are harmless, so we don't diagnose them. (Note that in454// C++, this cannot be reached unless we've already seen and diagnosed a455// different conformance issue, such as a mixture of designated and456// non-designated initializers or a multi-level designator.)457return;458}459460if (!VerifyOnly) {461SemaRef.Diag(NewInitRange.getBegin(), DiagID)462<< NewInitRange << FullyOverwritten << OldInit->getType();463SemaRef.Diag(OldInit->getBeginLoc(), diag::note_previous_initializer)464<< (OldInit->HasSideEffects(SemaRef.Context) && FullyOverwritten)465<< OldInit->getSourceRange();466}467}468469// Explanation on the "FillWithNoInit" mode:470//471// Assume we have the following definitions (Case#1):472// struct P { char x[6][6]; } xp = { .x[1] = "bar" };473// struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };474//475// l.lp.x[1][0..1] should not be filled with implicit initializers because the476// "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".477//478// But if we have (Case#2):479// struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };480//481// l.lp.x[1][0..1] are implicitly initialized and do not use values from the482// "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".483//484// To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"485// in the InitListExpr, the "holes" in Case#1 are filled not with empty486// initializers but with special "NoInitExpr" place holders, which tells the487// CodeGen not to generate any initializers for these parts.488void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,489const InitializedEntity &ParentEntity,490InitListExpr *ILE, bool &RequiresSecondPass,491bool FillWithNoInit);492void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,493const InitializedEntity &ParentEntity,494InitListExpr *ILE, bool &RequiresSecondPass,495bool FillWithNoInit = false);496void FillInEmptyInitializations(const InitializedEntity &Entity,497InitListExpr *ILE, bool &RequiresSecondPass,498InitListExpr *OuterILE, unsigned OuterIndex,499bool FillWithNoInit = false);500bool CheckFlexibleArrayInit(const InitializedEntity &Entity,501Expr *InitExpr, FieldDecl *Field,502bool TopLevelObject);503void CheckEmptyInitializable(const InitializedEntity &Entity,504SourceLocation Loc);505506Expr *HandleEmbed(EmbedExpr *Embed, const InitializedEntity &Entity) {507Expr *Result = nullptr;508// Undrestand which part of embed we'd like to reference.509if (!CurEmbed) {510CurEmbed = Embed;511CurEmbedIndex = 0;512}513// Reference just one if we're initializing a single scalar.514uint64_t ElsCount = 1;515// Otherwise try to fill whole array with embed data.516if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {517auto *AType =518SemaRef.Context.getAsArrayType(Entity.getParent()->getType());519assert(AType && "expected array type when initializing array");520ElsCount = Embed->getDataElementCount();521if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))522ElsCount = std::min(CAType->getSize().getZExtValue(),523ElsCount - CurEmbedIndex);524if (ElsCount == Embed->getDataElementCount()) {525CurEmbed = nullptr;526CurEmbedIndex = 0;527return Embed;528}529}530531Result = new (SemaRef.Context)532EmbedExpr(SemaRef.Context, Embed->getLocation(), Embed->getData(),533CurEmbedIndex, ElsCount);534CurEmbedIndex += ElsCount;535if (CurEmbedIndex >= Embed->getDataElementCount()) {536CurEmbed = nullptr;537CurEmbedIndex = 0;538}539return Result;540}541542public:543InitListChecker(544Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T,545bool VerifyOnly, bool TreatUnavailableAsInvalid,546bool InOverloadResolution = false,547SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr);548InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL,549QualType &T,550SmallVectorImpl<QualType> &AggrDeductionCandidateParamTypes)551: InitListChecker(S, Entity, IL, T, /*VerifyOnly=*/true,552/*TreatUnavailableAsInvalid=*/false,553/*InOverloadResolution=*/false,554&AggrDeductionCandidateParamTypes) {}555556bool HadError() { return hadError; }557558// Retrieves the fully-structured initializer list used for559// semantic analysis and code generation.560InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }561};562563} // end anonymous namespace564565ExprResult InitListChecker::PerformEmptyInit(SourceLocation Loc,566const InitializedEntity &Entity) {567InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,568true);569MultiExprArg SubInit;570Expr *InitExpr;571InitListExpr DummyInitList(SemaRef.Context, Loc, std::nullopt, Loc);572573// C++ [dcl.init.aggr]p7:574// If there are fewer initializer-clauses in the list than there are575// members in the aggregate, then each member not explicitly initialized576// ...577bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&578Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();579if (EmptyInitList) {580// C++1y / DR1070:581// shall be initialized [...] from an empty initializer list.582//583// We apply the resolution of this DR to C++11 but not C++98, since C++98584// does not have useful semantics for initialization from an init list.585// We treat this as copy-initialization, because aggregate initialization586// always performs copy-initialization on its elements.587//588// Only do this if we're initializing a class type, to avoid filling in589// the initializer list where possible.590InitExpr = VerifyOnly591? &DummyInitList592: new (SemaRef.Context)593InitListExpr(SemaRef.Context, Loc, std::nullopt, Loc);594InitExpr->setType(SemaRef.Context.VoidTy);595SubInit = InitExpr;596Kind = InitializationKind::CreateCopy(Loc, Loc);597} else {598// C++03:599// shall be value-initialized.600}601602InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);603// libstdc++4.6 marks the vector default constructor as explicit in604// _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.605// stlport does so too. Look for std::__debug for libstdc++, and for606// std:: for stlport. This is effectively a compiler-side implementation of607// LWG2193.608if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==609InitializationSequence::FK_ExplicitConstructor) {610OverloadCandidateSet::iterator Best;611OverloadingResult O =612InitSeq.getFailedCandidateSet()613.BestViableFunction(SemaRef, Kind.getLocation(), Best);614(void)O;615assert(O == OR_Success && "Inconsistent overload resolution");616CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);617CXXRecordDecl *R = CtorDecl->getParent();618619if (CtorDecl->getMinRequiredArguments() == 0 &&620CtorDecl->isExplicit() && R->getDeclName() &&621SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {622bool IsInStd = false;623for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());624ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {625if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))626IsInStd = true;627}628629if (IsInStd && llvm::StringSwitch<bool>(R->getName())630.Cases("basic_string", "deque", "forward_list", true)631.Cases("list", "map", "multimap", "multiset", true)632.Cases("priority_queue", "queue", "set", "stack", true)633.Cases("unordered_map", "unordered_set", "vector", true)634.Default(false)) {635InitSeq.InitializeFrom(636SemaRef, Entity,637InitializationKind::CreateValue(Loc, Loc, Loc, true),638MultiExprArg(), /*TopLevelOfInitList=*/false,639TreatUnavailableAsInvalid);640// Emit a warning for this. System header warnings aren't shown641// by default, but people working on system headers should see it.642if (!VerifyOnly) {643SemaRef.Diag(CtorDecl->getLocation(),644diag::warn_invalid_initializer_from_system_header);645if (Entity.getKind() == InitializedEntity::EK_Member)646SemaRef.Diag(Entity.getDecl()->getLocation(),647diag::note_used_in_initialization_here);648else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)649SemaRef.Diag(Loc, diag::note_used_in_initialization_here);650}651}652}653}654if (!InitSeq) {655if (!VerifyOnly) {656InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);657if (Entity.getKind() == InitializedEntity::EK_Member)658SemaRef.Diag(Entity.getDecl()->getLocation(),659diag::note_in_omitted_aggregate_initializer)660<< /*field*/1 << Entity.getDecl();661else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {662bool IsTrailingArrayNewMember =663Entity.getParent() &&664Entity.getParent()->isVariableLengthArrayNew();665SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)666<< (IsTrailingArrayNewMember ? 2 : /*array element*/0)667<< Entity.getElementIndex();668}669}670hadError = true;671return ExprError();672}673674return VerifyOnly ? ExprResult()675: InitSeq.Perform(SemaRef, Entity, Kind, SubInit);676}677678void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,679SourceLocation Loc) {680// If we're building a fully-structured list, we'll check this at the end681// once we know which elements are actually initialized. Otherwise, we know682// that there are no designators so we can just check now.683if (FullyStructuredList)684return;685PerformEmptyInit(Loc, Entity);686}687688void InitListChecker::FillInEmptyInitForBase(689unsigned Init, const CXXBaseSpecifier &Base,690const InitializedEntity &ParentEntity, InitListExpr *ILE,691bool &RequiresSecondPass, bool FillWithNoInit) {692InitializedEntity BaseEntity = InitializedEntity::InitializeBase(693SemaRef.Context, &Base, false, &ParentEntity);694695if (Init >= ILE->getNumInits() || !ILE->getInit(Init)) {696ExprResult BaseInit = FillWithNoInit697? new (SemaRef.Context) NoInitExpr(Base.getType())698: PerformEmptyInit(ILE->getEndLoc(), BaseEntity);699if (BaseInit.isInvalid()) {700hadError = true;701return;702}703704if (!VerifyOnly) {705assert(Init < ILE->getNumInits() && "should have been expanded");706ILE->setInit(Init, BaseInit.getAs<Expr>());707}708} else if (InitListExpr *InnerILE =709dyn_cast<InitListExpr>(ILE->getInit(Init))) {710FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,711ILE, Init, FillWithNoInit);712} else if (DesignatedInitUpdateExpr *InnerDIUE =713dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {714FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),715RequiresSecondPass, ILE, Init,716/*FillWithNoInit =*/true);717}718}719720void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,721const InitializedEntity &ParentEntity,722InitListExpr *ILE,723bool &RequiresSecondPass,724bool FillWithNoInit) {725SourceLocation Loc = ILE->getEndLoc();726unsigned NumInits = ILE->getNumInits();727InitializedEntity MemberEntity728= InitializedEntity::InitializeMember(Field, &ParentEntity);729730if (Init >= NumInits || !ILE->getInit(Init)) {731if (const RecordType *RType = ILE->getType()->getAs<RecordType>())732if (!RType->getDecl()->isUnion())733assert((Init < NumInits || VerifyOnly) &&734"This ILE should have been expanded");735736if (FillWithNoInit) {737assert(!VerifyOnly && "should not fill with no-init in verify-only mode");738Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());739if (Init < NumInits)740ILE->setInit(Init, Filler);741else742ILE->updateInit(SemaRef.Context, Init, Filler);743return;744}745// C++1y [dcl.init.aggr]p7:746// If there are fewer initializer-clauses in the list than there are747// members in the aggregate, then each member not explicitly initialized748// shall be initialized from its brace-or-equal-initializer [...]749if (Field->hasInClassInitializer()) {750if (VerifyOnly)751return;752753ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);754if (DIE.isInvalid()) {755hadError = true;756return;757}758SemaRef.checkInitializerLifetime(MemberEntity, DIE.get());759if (Init < NumInits)760ILE->setInit(Init, DIE.get());761else {762ILE->updateInit(SemaRef.Context, Init, DIE.get());763RequiresSecondPass = true;764}765return;766}767768if (Field->getType()->isReferenceType()) {769if (!VerifyOnly) {770// C++ [dcl.init.aggr]p9:771// If an incomplete or empty initializer-list leaves a772// member of reference type uninitialized, the program is773// ill-formed.774SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)775<< Field->getType()776<< (ILE->isSyntacticForm() ? ILE : ILE->getSyntacticForm())777->getSourceRange();778SemaRef.Diag(Field->getLocation(), diag::note_uninit_reference_member);779}780hadError = true;781return;782}783784ExprResult MemberInit = PerformEmptyInit(Loc, MemberEntity);785if (MemberInit.isInvalid()) {786hadError = true;787return;788}789790if (hadError || VerifyOnly) {791// Do nothing792} else if (Init < NumInits) {793ILE->setInit(Init, MemberInit.getAs<Expr>());794} else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {795// Empty initialization requires a constructor call, so796// extend the initializer list to include the constructor797// call and make a note that we'll need to take another pass798// through the initializer list.799ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());800RequiresSecondPass = true;801}802} else if (InitListExpr *InnerILE803= dyn_cast<InitListExpr>(ILE->getInit(Init))) {804FillInEmptyInitializations(MemberEntity, InnerILE,805RequiresSecondPass, ILE, Init, FillWithNoInit);806} else if (DesignatedInitUpdateExpr *InnerDIUE =807dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {808FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),809RequiresSecondPass, ILE, Init,810/*FillWithNoInit =*/true);811}812}813814/// Recursively replaces NULL values within the given initializer list815/// with expressions that perform value-initialization of the816/// appropriate type, and finish off the InitListExpr formation.817void818InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,819InitListExpr *ILE,820bool &RequiresSecondPass,821InitListExpr *OuterILE,822unsigned OuterIndex,823bool FillWithNoInit) {824assert((ILE->getType() != SemaRef.Context.VoidTy) &&825"Should not have void type");826827// We don't need to do any checks when just filling NoInitExprs; that can't828// fail.829if (FillWithNoInit && VerifyOnly)830return;831832// If this is a nested initializer list, we might have changed its contents833// (and therefore some of its properties, such as instantiation-dependence)834// while filling it in. Inform the outer initializer list so that its state835// can be updated to match.836// FIXME: We should fully build the inner initializers before constructing837// the outer InitListExpr instead of mutating AST nodes after they have838// been used as subexpressions of other nodes.839struct UpdateOuterILEWithUpdatedInit {840InitListExpr *Outer;841unsigned OuterIndex;842~UpdateOuterILEWithUpdatedInit() {843if (Outer)844Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));845}846} UpdateOuterRAII = {OuterILE, OuterIndex};847848// A transparent ILE is not performing aggregate initialization and should849// not be filled in.850if (ILE->isTransparent())851return;852853if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {854const RecordDecl *RDecl = RType->getDecl();855if (RDecl->isUnion() && ILE->getInitializedFieldInUnion()) {856FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(), Entity, ILE,857RequiresSecondPass, FillWithNoInit);858} else {859assert((!RDecl->isUnion() || !isa<CXXRecordDecl>(RDecl) ||860!cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) &&861"We should have computed initialized fields already");862// The fields beyond ILE->getNumInits() are default initialized, so in863// order to leave them uninitialized, the ILE is expanded and the extra864// fields are then filled with NoInitExpr.865unsigned NumElems = numStructUnionElements(ILE->getType());866if (!RDecl->isUnion() && RDecl->hasFlexibleArrayMember())867++NumElems;868if (!VerifyOnly && ILE->getNumInits() < NumElems)869ILE->resizeInits(SemaRef.Context, NumElems);870871unsigned Init = 0;872873if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {874for (auto &Base : CXXRD->bases()) {875if (hadError)876return;877878FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,879FillWithNoInit);880++Init;881}882}883884for (auto *Field : RDecl->fields()) {885if (Field->isUnnamedBitField())886continue;887888if (hadError)889return;890891FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,892FillWithNoInit);893if (hadError)894return;895896++Init;897898// Only look at the first initialization of a union.899if (RDecl->isUnion())900break;901}902}903904return;905}906907QualType ElementType;908909InitializedEntity ElementEntity = Entity;910unsigned NumInits = ILE->getNumInits();911uint64_t NumElements = NumInits;912if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {913ElementType = AType->getElementType();914if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))915NumElements = CAType->getZExtSize();916// For an array new with an unknown bound, ask for one additional element917// in order to populate the array filler.918if (Entity.isVariableLengthArrayNew())919++NumElements;920ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,9210, Entity);922} else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {923ElementType = VType->getElementType();924NumElements = VType->getNumElements();925ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,9260, Entity);927} else928ElementType = ILE->getType();929930bool SkipEmptyInitChecks = false;931for (uint64_t Init = 0; Init != NumElements; ++Init) {932if (hadError)933return;934935if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||936ElementEntity.getKind() == InitializedEntity::EK_VectorElement)937ElementEntity.setElementIndex(Init);938939if (Init >= NumInits && (ILE->hasArrayFiller() || SkipEmptyInitChecks))940return;941942Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);943if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())944ILE->setInit(Init, ILE->getArrayFiller());945else if (!InitExpr && !ILE->hasArrayFiller()) {946// In VerifyOnly mode, there's no point performing empty initialization947// more than once.948if (SkipEmptyInitChecks)949continue;950951Expr *Filler = nullptr;952953if (FillWithNoInit)954Filler = new (SemaRef.Context) NoInitExpr(ElementType);955else {956ExprResult ElementInit =957PerformEmptyInit(ILE->getEndLoc(), ElementEntity);958if (ElementInit.isInvalid()) {959hadError = true;960return;961}962963Filler = ElementInit.getAs<Expr>();964}965966if (hadError) {967// Do nothing968} else if (VerifyOnly) {969SkipEmptyInitChecks = true;970} else if (Init < NumInits) {971// For arrays, just set the expression used for value-initialization972// of the "holes" in the array.973if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)974ILE->setArrayFiller(Filler);975else976ILE->setInit(Init, Filler);977} else {978// For arrays, just set the expression used for value-initialization979// of the rest of elements and exit.980if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {981ILE->setArrayFiller(Filler);982return;983}984985if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {986// Empty initialization requires a constructor call, so987// extend the initializer list to include the constructor988// call and make a note that we'll need to take another pass989// through the initializer list.990ILE->updateInit(SemaRef.Context, Init, Filler);991RequiresSecondPass = true;992}993}994} else if (InitListExpr *InnerILE995= dyn_cast_or_null<InitListExpr>(InitExpr)) {996FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,997ILE, Init, FillWithNoInit);998} else if (DesignatedInitUpdateExpr *InnerDIUE =999dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr)) {1000FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),1001RequiresSecondPass, ILE, Init,1002/*FillWithNoInit =*/true);1003}1004}1005}10061007static bool hasAnyDesignatedInits(const InitListExpr *IL) {1008for (const Stmt *Init : *IL)1009if (isa_and_nonnull<DesignatedInitExpr>(Init))1010return true;1011return false;1012}10131014InitListChecker::InitListChecker(1015Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T,1016bool VerifyOnly, bool TreatUnavailableAsInvalid, bool InOverloadResolution,1017SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes)1018: SemaRef(S), VerifyOnly(VerifyOnly),1019TreatUnavailableAsInvalid(TreatUnavailableAsInvalid),1020InOverloadResolution(InOverloadResolution),1021AggrDeductionCandidateParamTypes(AggrDeductionCandidateParamTypes) {1022if (!VerifyOnly || hasAnyDesignatedInits(IL)) {1023FullyStructuredList =1024createInitListExpr(T, IL->getSourceRange(), IL->getNumInits());10251026// FIXME: Check that IL isn't already the semantic form of some other1027// InitListExpr. If it is, we'd create a broken AST.1028if (!VerifyOnly)1029FullyStructuredList->setSyntacticForm(IL);1030}10311032CheckExplicitInitList(Entity, IL, T, FullyStructuredList,1033/*TopLevelObject=*/true);10341035if (!hadError && !AggrDeductionCandidateParamTypes && FullyStructuredList) {1036bool RequiresSecondPass = false;1037FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,1038/*OuterILE=*/nullptr, /*OuterIndex=*/0);1039if (RequiresSecondPass && !hadError)1040FillInEmptyInitializations(Entity, FullyStructuredList,1041RequiresSecondPass, nullptr, 0);1042}1043if (hadError && FullyStructuredList)1044FullyStructuredList->markError();1045}10461047int InitListChecker::numArrayElements(QualType DeclType) {1048// FIXME: use a proper constant1049int maxElements = 0x7FFFFFFF;1050if (const ConstantArrayType *CAT =1051SemaRef.Context.getAsConstantArrayType(DeclType)) {1052maxElements = static_cast<int>(CAT->getZExtSize());1053}1054return maxElements;1055}10561057int InitListChecker::numStructUnionElements(QualType DeclType) {1058RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl();1059int InitializableMembers = 0;1060if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))1061InitializableMembers += CXXRD->getNumBases();1062for (const auto *Field : structDecl->fields())1063if (!Field->isUnnamedBitField())1064++InitializableMembers;10651066if (structDecl->isUnion())1067return std::min(InitializableMembers, 1);1068return InitializableMembers - structDecl->hasFlexibleArrayMember();1069}10701071RecordDecl *InitListChecker::getRecordDecl(QualType DeclType) {1072if (const auto *RT = DeclType->getAs<RecordType>())1073return RT->getDecl();1074if (const auto *Inject = DeclType->getAs<InjectedClassNameType>())1075return Inject->getDecl();1076return nullptr;1077}10781079/// Determine whether Entity is an entity for which it is idiomatic to elide1080/// the braces in aggregate initialization.1081static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) {1082// Recursive initialization of the one and only field within an aggregate1083// class is considered idiomatic. This case arises in particular for1084// initialization of std::array, where the C++ standard suggests the idiom of1085//1086// std::array<T, N> arr = {1, 2, 3};1087//1088// (where std::array is an aggregate struct containing a single array field.10891090if (!Entity.getParent())1091return false;10921093// Allows elide brace initialization for aggregates with empty base.1094if (Entity.getKind() == InitializedEntity::EK_Base) {1095auto *ParentRD =1096Entity.getParent()->getType()->castAs<RecordType>()->getDecl();1097CXXRecordDecl *CXXRD = cast<CXXRecordDecl>(ParentRD);1098return CXXRD->getNumBases() == 1 && CXXRD->field_empty();1099}11001101// Allow brace elision if the only subobject is a field.1102if (Entity.getKind() == InitializedEntity::EK_Member) {1103auto *ParentRD =1104Entity.getParent()->getType()->castAs<RecordType>()->getDecl();1105if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD)) {1106if (CXXRD->getNumBases()) {1107return false;1108}1109}1110auto FieldIt = ParentRD->field_begin();1111assert(FieldIt != ParentRD->field_end() &&1112"no fields but have initializer for member?");1113return ++FieldIt == ParentRD->field_end();1114}11151116return false;1117}11181119/// Check whether the range of the initializer \p ParentIList from element1120/// \p Index onwards can be used to initialize an object of type \p T. Update1121/// \p Index to indicate how many elements of the list were consumed.1122///1123/// This also fills in \p StructuredList, from element \p StructuredIndex1124/// onwards, with the fully-braced, desugared form of the initialization.1125void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,1126InitListExpr *ParentIList,1127QualType T, unsigned &Index,1128InitListExpr *StructuredList,1129unsigned &StructuredIndex) {1130int maxElements = 0;11311132if (T->isArrayType())1133maxElements = numArrayElements(T);1134else if (T->isRecordType())1135maxElements = numStructUnionElements(T);1136else if (T->isVectorType())1137maxElements = T->castAs<VectorType>()->getNumElements();1138else1139llvm_unreachable("CheckImplicitInitList(): Illegal type");11401141if (maxElements == 0) {1142if (!VerifyOnly)1143SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(),1144diag::err_implicit_empty_initializer);1145++Index;1146hadError = true;1147return;1148}11491150// Build a structured initializer list corresponding to this subobject.1151InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(1152ParentIList, Index, T, StructuredList, StructuredIndex,1153SourceRange(ParentIList->getInit(Index)->getBeginLoc(),1154ParentIList->getSourceRange().getEnd()));1155unsigned StructuredSubobjectInitIndex = 0;11561157// Check the element types and build the structural subobject.1158unsigned StartIndex = Index;1159CheckListElementTypes(Entity, ParentIList, T,1160/*SubobjectIsDesignatorContext=*/false, Index,1161StructuredSubobjectInitList,1162StructuredSubobjectInitIndex);11631164if (StructuredSubobjectInitList) {1165StructuredSubobjectInitList->setType(T);11661167unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);1168// Update the structured sub-object initializer so that it's ending1169// range corresponds with the end of the last initializer it used.1170if (EndIndex < ParentIList->getNumInits() &&1171ParentIList->getInit(EndIndex)) {1172SourceLocation EndLoc1173= ParentIList->getInit(EndIndex)->getSourceRange().getEnd();1174StructuredSubobjectInitList->setRBraceLoc(EndLoc);1175}11761177// Complain about missing braces.1178if (!VerifyOnly && (T->isArrayType() || T->isRecordType()) &&1179!ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&1180!isIdiomaticBraceElisionEntity(Entity)) {1181SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),1182diag::warn_missing_braces)1183<< StructuredSubobjectInitList->getSourceRange()1184<< FixItHint::CreateInsertion(1185StructuredSubobjectInitList->getBeginLoc(), "{")1186<< FixItHint::CreateInsertion(1187SemaRef.getLocForEndOfToken(1188StructuredSubobjectInitList->getEndLoc()),1189"}");1190}11911192// Warn if this type won't be an aggregate in future versions of C++.1193auto *CXXRD = T->getAsCXXRecordDecl();1194if (!VerifyOnly && CXXRD && CXXRD->hasUserDeclaredConstructor()) {1195SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),1196diag::warn_cxx20_compat_aggregate_init_with_ctors)1197<< StructuredSubobjectInitList->getSourceRange() << T;1198}1199}1200}12011202/// Warn that \p Entity was of scalar type and was initialized by a1203/// single-element braced initializer list.1204static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,1205SourceRange Braces) {1206// Don't warn during template instantiation. If the initialization was1207// non-dependent, we warned during the initial parse; otherwise, the1208// type might not be scalar in some uses of the template.1209if (S.inTemplateInstantiation())1210return;12111212unsigned DiagID = 0;12131214switch (Entity.getKind()) {1215case InitializedEntity::EK_VectorElement:1216case InitializedEntity::EK_ComplexElement:1217case InitializedEntity::EK_ArrayElement:1218case InitializedEntity::EK_Parameter:1219case InitializedEntity::EK_Parameter_CF_Audited:1220case InitializedEntity::EK_TemplateParameter:1221case InitializedEntity::EK_Result:1222case InitializedEntity::EK_ParenAggInitMember:1223// Extra braces here are suspicious.1224DiagID = diag::warn_braces_around_init;1225break;12261227case InitializedEntity::EK_Member:1228// Warn on aggregate initialization but not on ctor init list or1229// default member initializer.1230if (Entity.getParent())1231DiagID = diag::warn_braces_around_init;1232break;12331234case InitializedEntity::EK_Variable:1235case InitializedEntity::EK_LambdaCapture:1236// No warning, might be direct-list-initialization.1237// FIXME: Should we warn for copy-list-initialization in these cases?1238break;12391240case InitializedEntity::EK_New:1241case InitializedEntity::EK_Temporary:1242case InitializedEntity::EK_CompoundLiteralInit:1243// No warning, braces are part of the syntax of the underlying construct.1244break;12451246case InitializedEntity::EK_RelatedResult:1247// No warning, we already warned when initializing the result.1248break;12491250case InitializedEntity::EK_Exception:1251case InitializedEntity::EK_Base:1252case InitializedEntity::EK_Delegating:1253case InitializedEntity::EK_BlockElement:1254case InitializedEntity::EK_LambdaToBlockConversionBlockElement:1255case InitializedEntity::EK_Binding:1256case InitializedEntity::EK_StmtExprResult:1257llvm_unreachable("unexpected braced scalar init");1258}12591260if (DiagID) {1261S.Diag(Braces.getBegin(), DiagID)1262<< Entity.getType()->isSizelessBuiltinType() << Braces1263<< FixItHint::CreateRemoval(Braces.getBegin())1264<< FixItHint::CreateRemoval(Braces.getEnd());1265}1266}12671268/// Check whether the initializer \p IList (that was written with explicit1269/// braces) can be used to initialize an object of type \p T.1270///1271/// This also fills in \p StructuredList with the fully-braced, desugared1272/// form of the initialization.1273void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,1274InitListExpr *IList, QualType &T,1275InitListExpr *StructuredList,1276bool TopLevelObject) {1277unsigned Index = 0, StructuredIndex = 0;1278CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,1279Index, StructuredList, StructuredIndex, TopLevelObject);1280if (StructuredList) {1281QualType ExprTy = T;1282if (!ExprTy->isArrayType())1283ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);1284if (!VerifyOnly)1285IList->setType(ExprTy);1286StructuredList->setType(ExprTy);1287}1288if (hadError)1289return;12901291// Don't complain for incomplete types, since we'll get an error elsewhere.1292if (Index < IList->getNumInits() && !T->isIncompleteType()) {1293// We have leftover initializers1294bool ExtraInitsIsError = SemaRef.getLangOpts().CPlusPlus ||1295(SemaRef.getLangOpts().OpenCL && T->isVectorType());1296hadError = ExtraInitsIsError;1297if (VerifyOnly) {1298return;1299} else if (StructuredIndex == 1 &&1300IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==1301SIF_None) {1302unsigned DK =1303ExtraInitsIsError1304? diag::err_excess_initializers_in_char_array_initializer1305: diag::ext_excess_initializers_in_char_array_initializer;1306SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)1307<< IList->getInit(Index)->getSourceRange();1308} else if (T->isSizelessBuiltinType()) {1309unsigned DK = ExtraInitsIsError1310? diag::err_excess_initializers_for_sizeless_type1311: diag::ext_excess_initializers_for_sizeless_type;1312SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)1313<< T << IList->getInit(Index)->getSourceRange();1314} else {1315int initKind = T->isArrayType() ? 0 :1316T->isVectorType() ? 1 :1317T->isScalarType() ? 2 :1318T->isUnionType() ? 3 :13194;13201321unsigned DK = ExtraInitsIsError ? diag::err_excess_initializers1322: diag::ext_excess_initializers;1323SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)1324<< initKind << IList->getInit(Index)->getSourceRange();1325}1326}13271328if (!VerifyOnly) {1329if (T->isScalarType() && IList->getNumInits() == 1 &&1330!isa<InitListExpr>(IList->getInit(0)))1331warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());13321333// Warn if this is a class type that won't be an aggregate in future1334// versions of C++.1335auto *CXXRD = T->getAsCXXRecordDecl();1336if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {1337// Don't warn if there's an equivalent default constructor that would be1338// used instead.1339bool HasEquivCtor = false;1340if (IList->getNumInits() == 0) {1341auto *CD = SemaRef.LookupDefaultConstructor(CXXRD);1342HasEquivCtor = CD && !CD->isDeleted();1343}13441345if (!HasEquivCtor) {1346SemaRef.Diag(IList->getBeginLoc(),1347diag::warn_cxx20_compat_aggregate_init_with_ctors)1348<< IList->getSourceRange() << T;1349}1350}1351}1352}13531354void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,1355InitListExpr *IList,1356QualType &DeclType,1357bool SubobjectIsDesignatorContext,1358unsigned &Index,1359InitListExpr *StructuredList,1360unsigned &StructuredIndex,1361bool TopLevelObject) {1362if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {1363// Explicitly braced initializer for complex type can be real+imaginary1364// parts.1365CheckComplexType(Entity, IList, DeclType, Index,1366StructuredList, StructuredIndex);1367} else if (DeclType->isScalarType()) {1368CheckScalarType(Entity, IList, DeclType, Index,1369StructuredList, StructuredIndex);1370} else if (DeclType->isVectorType()) {1371CheckVectorType(Entity, IList, DeclType, Index,1372StructuredList, StructuredIndex);1373} else if (const RecordDecl *RD = getRecordDecl(DeclType)) {1374auto Bases =1375CXXRecordDecl::base_class_const_range(CXXRecordDecl::base_class_const_iterator(),1376CXXRecordDecl::base_class_const_iterator());1377if (DeclType->isRecordType()) {1378assert(DeclType->isAggregateType() &&1379"non-aggregate records should be handed in CheckSubElementType");1380if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))1381Bases = CXXRD->bases();1382} else {1383Bases = cast<CXXRecordDecl>(RD)->bases();1384}1385CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),1386SubobjectIsDesignatorContext, Index, StructuredList,1387StructuredIndex, TopLevelObject);1388} else if (DeclType->isArrayType()) {1389llvm::APSInt Zero(1390SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),1391false);1392CheckArrayType(Entity, IList, DeclType, Zero,1393SubobjectIsDesignatorContext, Index,1394StructuredList, StructuredIndex);1395} else if (DeclType->isVoidType() || DeclType->isFunctionType()) {1396// This type is invalid, issue a diagnostic.1397++Index;1398if (!VerifyOnly)1399SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)1400<< DeclType;1401hadError = true;1402} else if (DeclType->isReferenceType()) {1403CheckReferenceType(Entity, IList, DeclType, Index,1404StructuredList, StructuredIndex);1405} else if (DeclType->isObjCObjectType()) {1406if (!VerifyOnly)1407SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType;1408hadError = true;1409} else if (DeclType->isOCLIntelSubgroupAVCType() ||1410DeclType->isSizelessBuiltinType()) {1411// Checks for scalar type are sufficient for these types too.1412CheckScalarType(Entity, IList, DeclType, Index, StructuredList,1413StructuredIndex);1414} else if (DeclType->isDependentType()) {1415// C++ [over.match.class.deduct]p1.5:1416// brace elision is not considered for any aggregate element that has a1417// dependent non-array type or an array type with a value-dependent bound1418++Index;1419assert(AggrDeductionCandidateParamTypes);1420AggrDeductionCandidateParamTypes->push_back(DeclType);1421} else {1422if (!VerifyOnly)1423SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)1424<< DeclType;1425hadError = true;1426}1427}14281429void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,1430InitListExpr *IList,1431QualType ElemType,1432unsigned &Index,1433InitListExpr *StructuredList,1434unsigned &StructuredIndex,1435bool DirectlyDesignated) {1436Expr *expr = IList->getInit(Index);14371438if (ElemType->isReferenceType())1439return CheckReferenceType(Entity, IList, ElemType, Index,1440StructuredList, StructuredIndex);14411442if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {1443if (SubInitList->getNumInits() == 1 &&1444IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==1445SIF_None) {1446// FIXME: It would be more faithful and no less correct to include an1447// InitListExpr in the semantic form of the initializer list in this case.1448expr = SubInitList->getInit(0);1449}1450// Nested aggregate initialization and C++ initialization are handled later.1451} else if (isa<ImplicitValueInitExpr>(expr)) {1452// This happens during template instantiation when we see an InitListExpr1453// that we've already checked once.1454assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&1455"found implicit initialization for the wrong type");1456UpdateStructuredListElement(StructuredList, StructuredIndex, expr);1457++Index;1458return;1459}14601461if (SemaRef.getLangOpts().CPlusPlus || isa<InitListExpr>(expr)) {1462// C++ [dcl.init.aggr]p2:1463// Each member is copy-initialized from the corresponding1464// initializer-clause.14651466// FIXME: Better EqualLoc?1467InitializationKind Kind =1468InitializationKind::CreateCopy(expr->getBeginLoc(), SourceLocation());14691470// Vector elements can be initialized from other vectors in which case1471// we need initialization entity with a type of a vector (and not a vector1472// element!) initializing multiple vector elements.1473auto TmpEntity =1474(ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType())1475? InitializedEntity::InitializeTemporary(ElemType)1476: Entity;14771478if (TmpEntity.getType()->isDependentType()) {1479// C++ [over.match.class.deduct]p1.5:1480// brace elision is not considered for any aggregate element that has a1481// dependent non-array type or an array type with a value-dependent1482// bound1483assert(AggrDeductionCandidateParamTypes);14841485// In the presence of a braced-init-list within the initializer, we should1486// not perform brace-elision, even if brace elision would otherwise be1487// applicable. For example, given:1488//1489// template <class T> struct Foo {1490// T t[2];1491// };1492//1493// Foo t = {{1, 2}};1494//1495// we don't want the (T, T) but rather (T [2]) in terms of the initializer1496// {{1, 2}}.1497if (isa<InitListExpr, DesignatedInitExpr>(expr) ||1498!isa_and_present<ConstantArrayType>(1499SemaRef.Context.getAsArrayType(ElemType))) {1500++Index;1501AggrDeductionCandidateParamTypes->push_back(ElemType);1502return;1503}1504} else {1505InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr,1506/*TopLevelOfInitList*/ true);1507// C++14 [dcl.init.aggr]p13:1508// If the assignment-expression can initialize a member, the member is1509// initialized. Otherwise [...] brace elision is assumed1510//1511// Brace elision is never performed if the element is not an1512// assignment-expression.1513if (Seq || isa<InitListExpr>(expr)) {1514if (auto *Embed = dyn_cast<EmbedExpr>(expr)) {1515expr = HandleEmbed(Embed, Entity);1516}1517if (!VerifyOnly) {1518ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr);1519if (Result.isInvalid())1520hadError = true;15211522UpdateStructuredListElement(StructuredList, StructuredIndex,1523Result.getAs<Expr>());1524} else if (!Seq) {1525hadError = true;1526} else if (StructuredList) {1527UpdateStructuredListElement(StructuredList, StructuredIndex,1528getDummyInit());1529}1530if (!CurEmbed)1531++Index;1532if (AggrDeductionCandidateParamTypes)1533AggrDeductionCandidateParamTypes->push_back(ElemType);1534return;1535}1536}15371538// Fall through for subaggregate initialization1539} else if (ElemType->isScalarType() || ElemType->isAtomicType()) {1540// FIXME: Need to handle atomic aggregate types with implicit init lists.1541return CheckScalarType(Entity, IList, ElemType, Index,1542StructuredList, StructuredIndex);1543} else if (const ArrayType *arrayType =1544SemaRef.Context.getAsArrayType(ElemType)) {1545// arrayType can be incomplete if we're initializing a flexible1546// array member. There's nothing we can do with the completed1547// type here, though.15481549if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {1550// FIXME: Should we do this checking in verify-only mode?1551if (!VerifyOnly)1552CheckStringInit(expr, ElemType, arrayType, SemaRef,1553SemaRef.getLangOpts().C23 &&1554initializingConstexprVariable(Entity));1555if (StructuredList)1556UpdateStructuredListElement(StructuredList, StructuredIndex, expr);1557++Index;1558return;1559}15601561// Fall through for subaggregate initialization.15621563} else {1564assert((ElemType->isRecordType() || ElemType->isVectorType() ||1565ElemType->isOpenCLSpecificType()) && "Unexpected type");15661567// C99 6.7.8p13:1568//1569// The initializer for a structure or union object that has1570// automatic storage duration shall be either an initializer1571// list as described below, or a single expression that has1572// compatible structure or union type. In the latter case, the1573// initial value of the object, including unnamed members, is1574// that of the expression.1575ExprResult ExprRes = expr;1576if (SemaRef.CheckSingleAssignmentConstraints(1577ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {1578if (ExprRes.isInvalid())1579hadError = true;1580else {1581ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());1582if (ExprRes.isInvalid())1583hadError = true;1584}1585UpdateStructuredListElement(StructuredList, StructuredIndex,1586ExprRes.getAs<Expr>());1587++Index;1588return;1589}1590ExprRes.get();1591// Fall through for subaggregate initialization1592}15931594// C++ [dcl.init.aggr]p12:1595//1596// [...] Otherwise, if the member is itself a non-empty1597// subaggregate, brace elision is assumed and the initializer is1598// considered for the initialization of the first member of1599// the subaggregate.1600// OpenCL vector initializer is handled elsewhere.1601if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||1602ElemType->isAggregateType()) {1603CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,1604StructuredIndex);1605++StructuredIndex;16061607// In C++20, brace elision is not permitted for a designated initializer.1608if (DirectlyDesignated && SemaRef.getLangOpts().CPlusPlus && !hadError) {1609if (InOverloadResolution)1610hadError = true;1611if (!VerifyOnly) {1612SemaRef.Diag(expr->getBeginLoc(),1613diag::ext_designated_init_brace_elision)1614<< expr->getSourceRange()1615<< FixItHint::CreateInsertion(expr->getBeginLoc(), "{")1616<< FixItHint::CreateInsertion(1617SemaRef.getLocForEndOfToken(expr->getEndLoc()), "}");1618}1619}1620} else {1621if (!VerifyOnly) {1622// We cannot initialize this element, so let PerformCopyInitialization1623// produce the appropriate diagnostic. We already checked that this1624// initialization will fail.1625ExprResult Copy =1626SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,1627/*TopLevelOfInitList=*/true);1628(void)Copy;1629assert(Copy.isInvalid() &&1630"expected non-aggregate initialization to fail");1631}1632hadError = true;1633++Index;1634++StructuredIndex;1635}1636}16371638void InitListChecker::CheckComplexType(const InitializedEntity &Entity,1639InitListExpr *IList, QualType DeclType,1640unsigned &Index,1641InitListExpr *StructuredList,1642unsigned &StructuredIndex) {1643assert(Index == 0 && "Index in explicit init list must be zero");16441645// As an extension, clang supports complex initializers, which initialize1646// a complex number component-wise. When an explicit initializer list for1647// a complex number contains two initializers, this extension kicks in:1648// it expects the initializer list to contain two elements convertible to1649// the element type of the complex type. The first element initializes1650// the real part, and the second element intitializes the imaginary part.16511652if (IList->getNumInits() < 2)1653return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,1654StructuredIndex);16551656// This is an extension in C. (The builtin _Complex type does not exist1657// in the C++ standard.)1658if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)1659SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init)1660<< IList->getSourceRange();16611662// Initialize the complex number.1663QualType elementType = DeclType->castAs<ComplexType>()->getElementType();1664InitializedEntity ElementEntity =1665InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);16661667for (unsigned i = 0; i < 2; ++i) {1668ElementEntity.setElementIndex(Index);1669CheckSubElementType(ElementEntity, IList, elementType, Index,1670StructuredList, StructuredIndex);1671}1672}16731674void InitListChecker::CheckScalarType(const InitializedEntity &Entity,1675InitListExpr *IList, QualType DeclType,1676unsigned &Index,1677InitListExpr *StructuredList,1678unsigned &StructuredIndex) {1679if (Index >= IList->getNumInits()) {1680if (!VerifyOnly) {1681if (SemaRef.getLangOpts().CPlusPlus) {1682if (DeclType->isSizelessBuiltinType())1683SemaRef.Diag(IList->getBeginLoc(),1684SemaRef.getLangOpts().CPlusPlus111685? diag::warn_cxx98_compat_empty_sizeless_initializer1686: diag::err_empty_sizeless_initializer)1687<< DeclType << IList->getSourceRange();1688else1689SemaRef.Diag(IList->getBeginLoc(),1690SemaRef.getLangOpts().CPlusPlus111691? diag::warn_cxx98_compat_empty_scalar_initializer1692: diag::err_empty_scalar_initializer)1693<< IList->getSourceRange();1694}1695}1696hadError =1697SemaRef.getLangOpts().CPlusPlus && !SemaRef.getLangOpts().CPlusPlus11;1698++Index;1699++StructuredIndex;1700return;1701}17021703Expr *expr = IList->getInit(Index);1704if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {1705// FIXME: This is invalid, and accepting it causes overload resolution1706// to pick the wrong overload in some corner cases.1707if (!VerifyOnly)1708SemaRef.Diag(SubIList->getBeginLoc(), diag::ext_many_braces_around_init)1709<< DeclType->isSizelessBuiltinType() << SubIList->getSourceRange();17101711CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,1712StructuredIndex);1713return;1714} else if (isa<DesignatedInitExpr>(expr)) {1715if (!VerifyOnly)1716SemaRef.Diag(expr->getBeginLoc(),1717diag::err_designator_for_scalar_or_sizeless_init)1718<< DeclType->isSizelessBuiltinType() << DeclType1719<< expr->getSourceRange();1720hadError = true;1721++Index;1722++StructuredIndex;1723return;1724} else if (auto *Embed = dyn_cast<EmbedExpr>(expr)) {1725expr = HandleEmbed(Embed, Entity);1726}17271728ExprResult Result;1729if (VerifyOnly) {1730if (SemaRef.CanPerformCopyInitialization(Entity, expr))1731Result = getDummyInit();1732else1733Result = ExprError();1734} else {1735Result =1736SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,1737/*TopLevelOfInitList=*/true);1738}17391740Expr *ResultExpr = nullptr;17411742if (Result.isInvalid())1743hadError = true; // types weren't compatible.1744else {1745ResultExpr = Result.getAs<Expr>();17461747if (ResultExpr != expr && !VerifyOnly && !CurEmbed) {1748// The type was promoted, update initializer list.1749// FIXME: Why are we updating the syntactic init list?1750IList->setInit(Index, ResultExpr);1751}1752}17531754UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);1755if (!CurEmbed)1756++Index;1757if (AggrDeductionCandidateParamTypes)1758AggrDeductionCandidateParamTypes->push_back(DeclType);1759}17601761void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,1762InitListExpr *IList, QualType DeclType,1763unsigned &Index,1764InitListExpr *StructuredList,1765unsigned &StructuredIndex) {1766if (Index >= IList->getNumInits()) {1767// FIXME: It would be wonderful if we could point at the actual member. In1768// general, it would be useful to pass location information down the stack,1769// so that we know the location (or decl) of the "current object" being1770// initialized.1771if (!VerifyOnly)1772SemaRef.Diag(IList->getBeginLoc(),1773diag::err_init_reference_member_uninitialized)1774<< DeclType << IList->getSourceRange();1775hadError = true;1776++Index;1777++StructuredIndex;1778return;1779}17801781Expr *expr = IList->getInit(Index);1782if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {1783if (!VerifyOnly)1784SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list)1785<< DeclType << IList->getSourceRange();1786hadError = true;1787++Index;1788++StructuredIndex;1789return;1790}17911792ExprResult Result;1793if (VerifyOnly) {1794if (SemaRef.CanPerformCopyInitialization(Entity,expr))1795Result = getDummyInit();1796else1797Result = ExprError();1798} else {1799Result =1800SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,1801/*TopLevelOfInitList=*/true);1802}18031804if (Result.isInvalid())1805hadError = true;18061807expr = Result.getAs<Expr>();1808// FIXME: Why are we updating the syntactic init list?1809if (!VerifyOnly && expr)1810IList->setInit(Index, expr);18111812UpdateStructuredListElement(StructuredList, StructuredIndex, expr);1813++Index;1814if (AggrDeductionCandidateParamTypes)1815AggrDeductionCandidateParamTypes->push_back(DeclType);1816}18171818void InitListChecker::CheckVectorType(const InitializedEntity &Entity,1819InitListExpr *IList, QualType DeclType,1820unsigned &Index,1821InitListExpr *StructuredList,1822unsigned &StructuredIndex) {1823const VectorType *VT = DeclType->castAs<VectorType>();1824unsigned maxElements = VT->getNumElements();1825unsigned numEltsInit = 0;1826QualType elementType = VT->getElementType();18271828if (Index >= IList->getNumInits()) {1829// Make sure the element type can be value-initialized.1830CheckEmptyInitializable(1831InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),1832IList->getEndLoc());1833return;1834}18351836if (!SemaRef.getLangOpts().OpenCL && !SemaRef.getLangOpts().HLSL ) {1837// If the initializing element is a vector, try to copy-initialize1838// instead of breaking it apart (which is doomed to failure anyway).1839Expr *Init = IList->getInit(Index);1840if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {1841ExprResult Result;1842if (VerifyOnly) {1843if (SemaRef.CanPerformCopyInitialization(Entity, Init))1844Result = getDummyInit();1845else1846Result = ExprError();1847} else {1848Result =1849SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init,1850/*TopLevelOfInitList=*/true);1851}18521853Expr *ResultExpr = nullptr;1854if (Result.isInvalid())1855hadError = true; // types weren't compatible.1856else {1857ResultExpr = Result.getAs<Expr>();18581859if (ResultExpr != Init && !VerifyOnly) {1860// The type was promoted, update initializer list.1861// FIXME: Why are we updating the syntactic init list?1862IList->setInit(Index, ResultExpr);1863}1864}1865UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);1866++Index;1867if (AggrDeductionCandidateParamTypes)1868AggrDeductionCandidateParamTypes->push_back(elementType);1869return;1870}18711872InitializedEntity ElementEntity =1873InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);18741875for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {1876// Don't attempt to go past the end of the init list1877if (Index >= IList->getNumInits()) {1878CheckEmptyInitializable(ElementEntity, IList->getEndLoc());1879break;1880}18811882ElementEntity.setElementIndex(Index);1883CheckSubElementType(ElementEntity, IList, elementType, Index,1884StructuredList, StructuredIndex);1885}18861887if (VerifyOnly)1888return;18891890bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();1891const VectorType *T = Entity.getType()->castAs<VectorType>();1892if (isBigEndian && (T->getVectorKind() == VectorKind::Neon ||1893T->getVectorKind() == VectorKind::NeonPoly)) {1894// The ability to use vector initializer lists is a GNU vector extension1895// and is unrelated to the NEON intrinsics in arm_neon.h. On little1896// endian machines it works fine, however on big endian machines it1897// exhibits surprising behaviour:1898//1899// uint32x2_t x = {42, 64};1900// return vget_lane_u32(x, 0); // Will return 64.1901//1902// Because of this, explicitly call out that it is non-portable.1903//1904SemaRef.Diag(IList->getBeginLoc(),1905diag::warn_neon_vector_initializer_non_portable);19061907const char *typeCode;1908unsigned typeSize = SemaRef.Context.getTypeSize(elementType);19091910if (elementType->isFloatingType())1911typeCode = "f";1912else if (elementType->isSignedIntegerType())1913typeCode = "s";1914else if (elementType->isUnsignedIntegerType())1915typeCode = "u";1916else1917llvm_unreachable("Invalid element type!");19181919SemaRef.Diag(IList->getBeginLoc(),1920SemaRef.Context.getTypeSize(VT) > 641921? diag::note_neon_vector_initializer_non_portable_q1922: diag::note_neon_vector_initializer_non_portable)1923<< typeCode << typeSize;1924}19251926return;1927}19281929InitializedEntity ElementEntity =1930InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);19311932// OpenCL and HLSL initializers allow vectors to be constructed from vectors.1933for (unsigned i = 0; i < maxElements; ++i) {1934// Don't attempt to go past the end of the init list1935if (Index >= IList->getNumInits())1936break;19371938ElementEntity.setElementIndex(Index);19391940QualType IType = IList->getInit(Index)->getType();1941if (!IType->isVectorType()) {1942CheckSubElementType(ElementEntity, IList, elementType, Index,1943StructuredList, StructuredIndex);1944++numEltsInit;1945} else {1946QualType VecType;1947const VectorType *IVT = IType->castAs<VectorType>();1948unsigned numIElts = IVT->getNumElements();19491950if (IType->isExtVectorType())1951VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);1952else1953VecType = SemaRef.Context.getVectorType(elementType, numIElts,1954IVT->getVectorKind());1955CheckSubElementType(ElementEntity, IList, VecType, Index,1956StructuredList, StructuredIndex);1957numEltsInit += numIElts;1958}1959}19601961// OpenCL and HLSL require all elements to be initialized.1962if (numEltsInit != maxElements) {1963if (!VerifyOnly)1964SemaRef.Diag(IList->getBeginLoc(),1965diag::err_vector_incorrect_num_initializers)1966<< (numEltsInit < maxElements) << maxElements << numEltsInit;1967hadError = true;1968}1969}19701971/// Check if the type of a class element has an accessible destructor, and marks1972/// it referenced. Returns true if we shouldn't form a reference to the1973/// destructor.1974///1975/// Aggregate initialization requires a class element's destructor be1976/// accessible per 11.6.1 [dcl.init.aggr]:1977///1978/// The destructor for each element of class type is potentially invoked1979/// (15.4 [class.dtor]) from the context where the aggregate initialization1980/// occurs.1981static bool checkDestructorReference(QualType ElementType, SourceLocation Loc,1982Sema &SemaRef) {1983auto *CXXRD = ElementType->getAsCXXRecordDecl();1984if (!CXXRD)1985return false;19861987CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(CXXRD);1988SemaRef.CheckDestructorAccess(Loc, Destructor,1989SemaRef.PDiag(diag::err_access_dtor_temp)1990<< ElementType);1991SemaRef.MarkFunctionReferenced(Loc, Destructor);1992return SemaRef.DiagnoseUseOfDecl(Destructor, Loc);1993}19941995static bool1996canInitializeArrayWithEmbedDataString(ArrayRef<Expr *> ExprList,1997const InitializedEntity &Entity,1998ASTContext &Context) {1999QualType InitType = Entity.getType();2000const InitializedEntity *Parent = &Entity;20012002while (Parent) {2003InitType = Parent->getType();2004Parent = Parent->getParent();2005}20062007// Only one initializer, it's an embed and the types match;2008EmbedExpr *EE =2009ExprList.size() == 12010? dyn_cast_if_present<EmbedExpr>(ExprList[0]->IgnoreParens())2011: nullptr;2012if (!EE)2013return false;20142015if (InitType->isArrayType()) {2016const ArrayType *InitArrayType = InitType->getAsArrayTypeUnsafe();2017QualType InitElementTy = InitArrayType->getElementType();2018QualType EmbedExprElementTy = EE->getDataStringLiteral()->getType();2019const bool TypesMatch =2020Context.typesAreCompatible(InitElementTy, EmbedExprElementTy) ||2021(InitElementTy->isCharType() && EmbedExprElementTy->isCharType());2022if (TypesMatch)2023return true;2024}2025return false;2026}20272028void InitListChecker::CheckArrayType(const InitializedEntity &Entity,2029InitListExpr *IList, QualType &DeclType,2030llvm::APSInt elementIndex,2031bool SubobjectIsDesignatorContext,2032unsigned &Index,2033InitListExpr *StructuredList,2034unsigned &StructuredIndex) {2035const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);20362037if (!VerifyOnly) {2038if (checkDestructorReference(arrayType->getElementType(),2039IList->getEndLoc(), SemaRef)) {2040hadError = true;2041return;2042}2043}20442045if (canInitializeArrayWithEmbedDataString(IList->inits(), Entity,2046SemaRef.Context)) {2047EmbedExpr *Embed = cast<EmbedExpr>(IList->inits()[0]);2048IList->setInit(0, Embed->getDataStringLiteral());2049}20502051// Check for the special-case of initializing an array with a string.2052if (Index < IList->getNumInits()) {2053if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==2054SIF_None) {2055// We place the string literal directly into the resulting2056// initializer list. This is the only place where the structure2057// of the structured initializer list doesn't match exactly,2058// because doing so would involve allocating one character2059// constant for each string.2060// FIXME: Should we do these checks in verify-only mode too?2061if (!VerifyOnly)2062CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef,2063SemaRef.getLangOpts().C23 &&2064initializingConstexprVariable(Entity));2065if (StructuredList) {2066UpdateStructuredListElement(StructuredList, StructuredIndex,2067IList->getInit(Index));2068StructuredList->resizeInits(SemaRef.Context, StructuredIndex);2069}2070++Index;2071if (AggrDeductionCandidateParamTypes)2072AggrDeductionCandidateParamTypes->push_back(DeclType);2073return;2074}2075}2076if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {2077// Check for VLAs; in standard C it would be possible to check this2078// earlier, but I don't know where clang accepts VLAs (gcc accepts2079// them in all sorts of strange places).2080bool HasErr = IList->getNumInits() != 0 || SemaRef.getLangOpts().CPlusPlus;2081if (!VerifyOnly) {2082// C23 6.7.10p4: An entity of variable length array type shall not be2083// initialized except by an empty initializer.2084//2085// The C extension warnings are issued from ParseBraceInitializer() and2086// do not need to be issued here. However, we continue to issue an error2087// in the case there are initializers or we are compiling C++. We allow2088// use of VLAs in C++, but it's not clear we want to allow {} to zero2089// init a VLA in C++ in all cases (such as with non-trivial constructors).2090// FIXME: should we allow this construct in C++ when it makes sense to do2091// so?2092if (HasErr)2093SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),2094diag::err_variable_object_no_init)2095<< VAT->getSizeExpr()->getSourceRange();2096}2097hadError = HasErr;2098++Index;2099++StructuredIndex;2100return;2101}21022103// We might know the maximum number of elements in advance.2104llvm::APSInt maxElements(elementIndex.getBitWidth(),2105elementIndex.isUnsigned());2106bool maxElementsKnown = false;2107if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {2108maxElements = CAT->getSize();2109elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());2110elementIndex.setIsUnsigned(maxElements.isUnsigned());2111maxElementsKnown = true;2112}21132114QualType elementType = arrayType->getElementType();2115while (Index < IList->getNumInits()) {2116Expr *Init = IList->getInit(Index);2117if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {2118// If we're not the subobject that matches up with the '{' for2119// the designator, we shouldn't be handling the2120// designator. Return immediately.2121if (!SubobjectIsDesignatorContext)2122return;21232124// Handle this designated initializer. elementIndex will be2125// updated to be the next array element we'll initialize.2126if (CheckDesignatedInitializer(Entity, IList, DIE, 0,2127DeclType, nullptr, &elementIndex, Index,2128StructuredList, StructuredIndex, true,2129false)) {2130hadError = true;2131continue;2132}21332134if (elementIndex.getBitWidth() > maxElements.getBitWidth())2135maxElements = maxElements.extend(elementIndex.getBitWidth());2136else if (elementIndex.getBitWidth() < maxElements.getBitWidth())2137elementIndex = elementIndex.extend(maxElements.getBitWidth());2138elementIndex.setIsUnsigned(maxElements.isUnsigned());21392140// If the array is of incomplete type, keep track of the number of2141// elements in the initializer.2142if (!maxElementsKnown && elementIndex > maxElements)2143maxElements = elementIndex;21442145continue;2146}21472148// If we know the maximum number of elements, and we've already2149// hit it, stop consuming elements in the initializer list.2150if (maxElementsKnown && elementIndex == maxElements)2151break;21522153InitializedEntity ElementEntity = InitializedEntity::InitializeElement(2154SemaRef.Context, StructuredIndex, Entity);21552156unsigned EmbedElementIndexBeforeInit = CurEmbedIndex;2157// Check this element.2158CheckSubElementType(ElementEntity, IList, elementType, Index,2159StructuredList, StructuredIndex);2160++elementIndex;2161if ((CurEmbed || isa<EmbedExpr>(Init)) && elementType->isScalarType()) {2162if (CurEmbed) {2163elementIndex =2164elementIndex + CurEmbedIndex - EmbedElementIndexBeforeInit - 1;2165} else {2166auto Embed = cast<EmbedExpr>(Init);2167elementIndex = elementIndex + Embed->getDataElementCount() -2168EmbedElementIndexBeforeInit - 1;2169}2170}21712172// If the array is of incomplete type, keep track of the number of2173// elements in the initializer.2174if (!maxElementsKnown && elementIndex > maxElements)2175maxElements = elementIndex;2176}2177if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {2178// If this is an incomplete array type, the actual type needs to2179// be calculated here.2180llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());2181if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {2182// Sizing an array implicitly to zero is not allowed by ISO C,2183// but is supported by GNU.2184SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);2185}21862187DeclType = SemaRef.Context.getConstantArrayType(2188elementType, maxElements, nullptr, ArraySizeModifier::Normal, 0);2189}2190if (!hadError) {2191// If there are any members of the array that get value-initialized, check2192// that is possible. That happens if we know the bound and don't have2193// enough elements, or if we're performing an array new with an unknown2194// bound.2195if ((maxElementsKnown && elementIndex < maxElements) ||2196Entity.isVariableLengthArrayNew())2197CheckEmptyInitializable(2198InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),2199IList->getEndLoc());2200}2201}22022203bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,2204Expr *InitExpr,2205FieldDecl *Field,2206bool TopLevelObject) {2207// Handle GNU flexible array initializers.2208unsigned FlexArrayDiag;2209if (isa<InitListExpr>(InitExpr) &&2210cast<InitListExpr>(InitExpr)->getNumInits() == 0) {2211// Empty flexible array init always allowed as an extension2212FlexArrayDiag = diag::ext_flexible_array_init;2213} else if (!TopLevelObject) {2214// Disallow flexible array init on non-top-level object2215FlexArrayDiag = diag::err_flexible_array_init;2216} else if (Entity.getKind() != InitializedEntity::EK_Variable) {2217// Disallow flexible array init on anything which is not a variable.2218FlexArrayDiag = diag::err_flexible_array_init;2219} else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {2220// Disallow flexible array init on local variables.2221FlexArrayDiag = diag::err_flexible_array_init;2222} else {2223// Allow other cases.2224FlexArrayDiag = diag::ext_flexible_array_init;2225}22262227if (!VerifyOnly) {2228SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)2229<< InitExpr->getBeginLoc();2230SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)2231<< Field;2232}22332234return FlexArrayDiag != diag::ext_flexible_array_init;2235}22362237void InitListChecker::CheckStructUnionTypes(2238const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,2239CXXRecordDecl::base_class_const_range Bases, RecordDecl::field_iterator Field,2240bool SubobjectIsDesignatorContext, unsigned &Index,2241InitListExpr *StructuredList, unsigned &StructuredIndex,2242bool TopLevelObject) {2243const RecordDecl *RD = getRecordDecl(DeclType);22442245// If the record is invalid, some of it's members are invalid. To avoid2246// confusion, we forgo checking the initializer for the entire record.2247if (RD->isInvalidDecl()) {2248// Assume it was supposed to consume a single initializer.2249++Index;2250hadError = true;2251return;2252}22532254if (RD->isUnion() && IList->getNumInits() == 0) {2255if (!VerifyOnly)2256for (FieldDecl *FD : RD->fields()) {2257QualType ET = SemaRef.Context.getBaseElementType(FD->getType());2258if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {2259hadError = true;2260return;2261}2262}22632264// If there's a default initializer, use it.2265if (isa<CXXRecordDecl>(RD) &&2266cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {2267if (!StructuredList)2268return;2269for (RecordDecl::field_iterator FieldEnd = RD->field_end();2270Field != FieldEnd; ++Field) {2271if (Field->hasInClassInitializer() ||2272(Field->isAnonymousStructOrUnion() &&2273Field->getType()->getAsCXXRecordDecl()->hasInClassInitializer())) {2274StructuredList->setInitializedFieldInUnion(*Field);2275// FIXME: Actually build a CXXDefaultInitExpr?2276return;2277}2278}2279llvm_unreachable("Couldn't find in-class initializer");2280}22812282// Value-initialize the first member of the union that isn't an unnamed2283// bitfield.2284for (RecordDecl::field_iterator FieldEnd = RD->field_end();2285Field != FieldEnd; ++Field) {2286if (!Field->isUnnamedBitField()) {2287CheckEmptyInitializable(2288InitializedEntity::InitializeMember(*Field, &Entity),2289IList->getEndLoc());2290if (StructuredList)2291StructuredList->setInitializedFieldInUnion(*Field);2292break;2293}2294}2295return;2296}22972298bool InitializedSomething = false;22992300// If we have any base classes, they are initialized prior to the fields.2301for (auto I = Bases.begin(), E = Bases.end(); I != E; ++I) {2302auto &Base = *I;2303Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;23042305// Designated inits always initialize fields, so if we see one, all2306// remaining base classes have no explicit initializer.2307if (isa_and_nonnull<DesignatedInitExpr>(Init))2308Init = nullptr;23092310// C++ [over.match.class.deduct]p1.6:2311// each non-trailing aggregate element that is a pack expansion is assumed2312// to correspond to no elements of the initializer list, and (1.7) a2313// trailing aggregate element that is a pack expansion is assumed to2314// correspond to all remaining elements of the initializer list (if any).23152316// C++ [over.match.class.deduct]p1.9:2317// ... except that additional parameter packs of the form P_j... are2318// inserted into the parameter list in their original aggregate element2319// position corresponding to each non-trailing aggregate element of2320// type P_j that was skipped because it was a parameter pack, and the2321// trailing sequence of parameters corresponding to a trailing2322// aggregate element that is a pack expansion (if any) is replaced2323// by a single parameter of the form T_n....2324if (AggrDeductionCandidateParamTypes && Base.isPackExpansion()) {2325AggrDeductionCandidateParamTypes->push_back(2326SemaRef.Context.getPackExpansionType(Base.getType(), std::nullopt));23272328// Trailing pack expansion2329if (I + 1 == E && RD->field_empty()) {2330if (Index < IList->getNumInits())2331Index = IList->getNumInits();2332return;2333}23342335continue;2336}23372338SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();2339InitializedEntity BaseEntity = InitializedEntity::InitializeBase(2340SemaRef.Context, &Base, false, &Entity);2341if (Init) {2342CheckSubElementType(BaseEntity, IList, Base.getType(), Index,2343StructuredList, StructuredIndex);2344InitializedSomething = true;2345} else {2346CheckEmptyInitializable(BaseEntity, InitLoc);2347}23482349if (!VerifyOnly)2350if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) {2351hadError = true;2352return;2353}2354}23552356// If structDecl is a forward declaration, this loop won't do2357// anything except look at designated initializers; That's okay,2358// because an error should get printed out elsewhere. It might be2359// worthwhile to skip over the rest of the initializer, though.2360RecordDecl::field_iterator FieldEnd = RD->field_end();2361size_t NumRecordDecls = llvm::count_if(RD->decls(), [&](const Decl *D) {2362return isa<FieldDecl>(D) || isa<RecordDecl>(D);2363});2364bool HasDesignatedInit = false;23652366llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;23672368while (Index < IList->getNumInits()) {2369Expr *Init = IList->getInit(Index);2370SourceLocation InitLoc = Init->getBeginLoc();23712372if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {2373// If we're not the subobject that matches up with the '{' for2374// the designator, we shouldn't be handling the2375// designator. Return immediately.2376if (!SubobjectIsDesignatorContext)2377return;23782379HasDesignatedInit = true;23802381// Handle this designated initializer. Field will be updated to2382// the next field that we'll be initializing.2383bool DesignatedInitFailed = CheckDesignatedInitializer(2384Entity, IList, DIE, 0, DeclType, &Field, nullptr, Index,2385StructuredList, StructuredIndex, true, TopLevelObject);2386if (DesignatedInitFailed)2387hadError = true;23882389// Find the field named by the designated initializer.2390DesignatedInitExpr::Designator *D = DIE->getDesignator(0);2391if (!VerifyOnly && D->isFieldDesignator()) {2392FieldDecl *F = D->getFieldDecl();2393InitializedFields.insert(F);2394if (!DesignatedInitFailed) {2395QualType ET = SemaRef.Context.getBaseElementType(F->getType());2396if (checkDestructorReference(ET, InitLoc, SemaRef)) {2397hadError = true;2398return;2399}2400}2401}24022403InitializedSomething = true;2404continue;2405}24062407// Check if this is an initializer of forms:2408//2409// struct foo f = {};2410// struct foo g = {0};2411//2412// These are okay for randomized structures. [C99 6.7.8p19]2413//2414// Also, if there is only one element in the structure, we allow something2415// like this, because it's really not randomized in the traditional sense.2416//2417// struct foo h = {bar};2418auto IsZeroInitializer = [&](const Expr *I) {2419if (IList->getNumInits() == 1) {2420if (NumRecordDecls == 1)2421return true;2422if (const auto *IL = dyn_cast<IntegerLiteral>(I))2423return IL->getValue().isZero();2424}2425return false;2426};24272428// Don't allow non-designated initializers on randomized structures.2429if (RD->isRandomized() && !IsZeroInitializer(Init)) {2430if (!VerifyOnly)2431SemaRef.Diag(InitLoc, diag::err_non_designated_init_used);2432hadError = true;2433break;2434}24352436if (Field == FieldEnd) {2437// We've run out of fields. We're done.2438break;2439}24402441// We've already initialized a member of a union. We can stop entirely.2442if (InitializedSomething && RD->isUnion())2443return;24442445// Stop if we've hit a flexible array member.2446if (Field->getType()->isIncompleteArrayType())2447break;24482449if (Field->isUnnamedBitField()) {2450// Don't initialize unnamed bitfields, e.g. "int : 20;"2451++Field;2452continue;2453}24542455// Make sure we can use this declaration.2456bool InvalidUse;2457if (VerifyOnly)2458InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);2459else2460InvalidUse = SemaRef.DiagnoseUseOfDecl(2461*Field, IList->getInit(Index)->getBeginLoc());2462if (InvalidUse) {2463++Index;2464++Field;2465hadError = true;2466continue;2467}24682469if (!VerifyOnly) {2470QualType ET = SemaRef.Context.getBaseElementType(Field->getType());2471if (checkDestructorReference(ET, InitLoc, SemaRef)) {2472hadError = true;2473return;2474}2475}24762477InitializedEntity MemberEntity =2478InitializedEntity::InitializeMember(*Field, &Entity);2479CheckSubElementType(MemberEntity, IList, Field->getType(), Index,2480StructuredList, StructuredIndex);2481InitializedSomething = true;2482InitializedFields.insert(*Field);24832484if (RD->isUnion() && StructuredList) {2485// Initialize the first field within the union.2486StructuredList->setInitializedFieldInUnion(*Field);2487}24882489++Field;2490}24912492// Emit warnings for missing struct field initializers.2493// This check is disabled for designated initializers in C.2494// This matches gcc behaviour.2495bool IsCDesignatedInitializer =2496HasDesignatedInit && !SemaRef.getLangOpts().CPlusPlus;2497if (!VerifyOnly && InitializedSomething && !RD->isUnion() &&2498!IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&2499!IsCDesignatedInitializer) {2500// It is possible we have one or more unnamed bitfields remaining.2501// Find first (if any) named field and emit warning.2502for (RecordDecl::field_iterator it = HasDesignatedInit ? RD->field_begin()2503: Field,2504end = RD->field_end();2505it != end; ++it) {2506if (HasDesignatedInit && InitializedFields.count(*it))2507continue;25082509if (!it->isUnnamedBitField() && !it->hasInClassInitializer() &&2510!it->getType()->isIncompleteArrayType()) {2511auto Diag = HasDesignatedInit2512? diag::warn_missing_designated_field_initializers2513: diag::warn_missing_field_initializers;2514SemaRef.Diag(IList->getSourceRange().getEnd(), Diag) << *it;2515break;2516}2517}2518}25192520// Check that any remaining fields can be value-initialized if we're not2521// building a structured list. (If we are, we'll check this later.)2522if (!StructuredList && Field != FieldEnd && !RD->isUnion() &&2523!Field->getType()->isIncompleteArrayType()) {2524for (; Field != FieldEnd && !hadError; ++Field) {2525if (!Field->isUnnamedBitField() && !Field->hasInClassInitializer())2526CheckEmptyInitializable(2527InitializedEntity::InitializeMember(*Field, &Entity),2528IList->getEndLoc());2529}2530}25312532// Check that the types of the remaining fields have accessible destructors.2533if (!VerifyOnly) {2534// If the initializer expression has a designated initializer, check the2535// elements for which a designated initializer is not provided too.2536RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()2537: Field;2538for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {2539QualType ET = SemaRef.Context.getBaseElementType(I->getType());2540if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {2541hadError = true;2542return;2543}2544}2545}25462547if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||2548Index >= IList->getNumInits())2549return;25502551if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,2552TopLevelObject)) {2553hadError = true;2554++Index;2555return;2556}25572558InitializedEntity MemberEntity =2559InitializedEntity::InitializeMember(*Field, &Entity);25602561if (isa<InitListExpr>(IList->getInit(Index)) ||2562AggrDeductionCandidateParamTypes)2563CheckSubElementType(MemberEntity, IList, Field->getType(), Index,2564StructuredList, StructuredIndex);2565else2566CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,2567StructuredList, StructuredIndex);25682569if (RD->isUnion() && StructuredList) {2570// Initialize the first field within the union.2571StructuredList->setInitializedFieldInUnion(*Field);2572}2573}25742575/// Expand a field designator that refers to a member of an2576/// anonymous struct or union into a series of field designators that2577/// refers to the field within the appropriate subobject.2578///2579static void ExpandAnonymousFieldDesignator(Sema &SemaRef,2580DesignatedInitExpr *DIE,2581unsigned DesigIdx,2582IndirectFieldDecl *IndirectField) {2583typedef DesignatedInitExpr::Designator Designator;25842585// Build the replacement designators.2586SmallVector<Designator, 4> Replacements;2587for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),2588PE = IndirectField->chain_end(); PI != PE; ++PI) {2589if (PI + 1 == PE)2590Replacements.push_back(Designator::CreateFieldDesignator(2591(IdentifierInfo *)nullptr, DIE->getDesignator(DesigIdx)->getDotLoc(),2592DIE->getDesignator(DesigIdx)->getFieldLoc()));2593else2594Replacements.push_back(Designator::CreateFieldDesignator(2595(IdentifierInfo *)nullptr, SourceLocation(), SourceLocation()));2596assert(isa<FieldDecl>(*PI));2597Replacements.back().setFieldDecl(cast<FieldDecl>(*PI));2598}25992600// Expand the current designator into the set of replacement2601// designators, so we have a full subobject path down to where the2602// member of the anonymous struct/union is actually stored.2603DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],2604&Replacements[0] + Replacements.size());2605}26062607static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,2608DesignatedInitExpr *DIE) {2609unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;2610SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);2611for (unsigned I = 0; I < NumIndexExprs; ++I)2612IndexExprs[I] = DIE->getSubExpr(I + 1);2613return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),2614IndexExprs,2615DIE->getEqualOrColonLoc(),2616DIE->usesGNUSyntax(), DIE->getInit());2617}26182619namespace {26202621// Callback to only accept typo corrections that are for field members of2622// the given struct or union.2623class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {2624public:2625explicit FieldInitializerValidatorCCC(const RecordDecl *RD)2626: Record(RD) {}26272628bool ValidateCandidate(const TypoCorrection &candidate) override {2629FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();2630return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);2631}26322633std::unique_ptr<CorrectionCandidateCallback> clone() override {2634return std::make_unique<FieldInitializerValidatorCCC>(*this);2635}26362637private:2638const RecordDecl *Record;2639};26402641} // end anonymous namespace26422643/// Check the well-formedness of a C99 designated initializer.2644///2645/// Determines whether the designated initializer @p DIE, which2646/// resides at the given @p Index within the initializer list @p2647/// IList, is well-formed for a current object of type @p DeclType2648/// (C99 6.7.8). The actual subobject that this designator refers to2649/// within the current subobject is returned in either2650/// @p NextField or @p NextElementIndex (whichever is appropriate).2651///2652/// @param IList The initializer list in which this designated2653/// initializer occurs.2654///2655/// @param DIE The designated initializer expression.2656///2657/// @param DesigIdx The index of the current designator.2658///2659/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),2660/// into which the designation in @p DIE should refer.2661///2662/// @param NextField If non-NULL and the first designator in @p DIE is2663/// a field, this will be set to the field declaration corresponding2664/// to the field named by the designator. On input, this is expected to be2665/// the next field that would be initialized in the absence of designation,2666/// if the complete object being initialized is a struct.2667///2668/// @param NextElementIndex If non-NULL and the first designator in @p2669/// DIE is an array designator or GNU array-range designator, this2670/// will be set to the last index initialized by this designator.2671///2672/// @param Index Index into @p IList where the designated initializer2673/// @p DIE occurs.2674///2675/// @param StructuredList The initializer list expression that2676/// describes all of the subobject initializers in the order they'll2677/// actually be initialized.2678///2679/// @returns true if there was an error, false otherwise.2680bool2681InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,2682InitListExpr *IList,2683DesignatedInitExpr *DIE,2684unsigned DesigIdx,2685QualType &CurrentObjectType,2686RecordDecl::field_iterator *NextField,2687llvm::APSInt *NextElementIndex,2688unsigned &Index,2689InitListExpr *StructuredList,2690unsigned &StructuredIndex,2691bool FinishSubobjectInit,2692bool TopLevelObject) {2693if (DesigIdx == DIE->size()) {2694// C++20 designated initialization can result in direct-list-initialization2695// of the designated subobject. This is the only way that we can end up2696// performing direct initialization as part of aggregate initialization, so2697// it needs special handling.2698if (DIE->isDirectInit()) {2699Expr *Init = DIE->getInit();2700assert(isa<InitListExpr>(Init) &&2701"designator result in direct non-list initialization?");2702InitializationKind Kind = InitializationKind::CreateDirectList(2703DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc());2704InitializationSequence Seq(SemaRef, Entity, Kind, Init,2705/*TopLevelOfInitList*/ true);2706if (StructuredList) {2707ExprResult Result = VerifyOnly2708? getDummyInit()2709: Seq.Perform(SemaRef, Entity, Kind, Init);2710UpdateStructuredListElement(StructuredList, StructuredIndex,2711Result.get());2712}2713++Index;2714if (AggrDeductionCandidateParamTypes)2715AggrDeductionCandidateParamTypes->push_back(CurrentObjectType);2716return !Seq;2717}27182719// Check the actual initialization for the designated object type.2720bool prevHadError = hadError;27212722// Temporarily remove the designator expression from the2723// initializer list that the child calls see, so that we don't try2724// to re-process the designator.2725unsigned OldIndex = Index;2726IList->setInit(OldIndex, DIE->getInit());27272728CheckSubElementType(Entity, IList, CurrentObjectType, Index, StructuredList,2729StructuredIndex, /*DirectlyDesignated=*/true);27302731// Restore the designated initializer expression in the syntactic2732// form of the initializer list.2733if (IList->getInit(OldIndex) != DIE->getInit())2734DIE->setInit(IList->getInit(OldIndex));2735IList->setInit(OldIndex, DIE);27362737return hadError && !prevHadError;2738}27392740DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);2741bool IsFirstDesignator = (DesigIdx == 0);2742if (IsFirstDesignator ? FullyStructuredList : StructuredList) {2743// Determine the structural initializer list that corresponds to the2744// current subobject.2745if (IsFirstDesignator)2746StructuredList = FullyStructuredList;2747else {2748Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?2749StructuredList->getInit(StructuredIndex) : nullptr;2750if (!ExistingInit && StructuredList->hasArrayFiller())2751ExistingInit = StructuredList->getArrayFiller();27522753if (!ExistingInit)2754StructuredList = getStructuredSubobjectInit(2755IList, Index, CurrentObjectType, StructuredList, StructuredIndex,2756SourceRange(D->getBeginLoc(), DIE->getEndLoc()));2757else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))2758StructuredList = Result;2759else {2760// We are creating an initializer list that initializes the2761// subobjects of the current object, but there was already an2762// initialization that completely initialized the current2763// subobject, e.g., by a compound literal:2764//2765// struct X { int a, b; };2766// struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };2767//2768// Here, xs[0].a == 1 and xs[0].b == 3, since the second,2769// designated initializer re-initializes only its current object2770// subobject [0].b.2771diagnoseInitOverride(ExistingInit,2772SourceRange(D->getBeginLoc(), DIE->getEndLoc()),2773/*UnionOverride=*/false,2774/*FullyOverwritten=*/false);27752776if (!VerifyOnly) {2777if (DesignatedInitUpdateExpr *E =2778dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))2779StructuredList = E->getUpdater();2780else {2781DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)2782DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(),2783ExistingInit, DIE->getEndLoc());2784StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);2785StructuredList = DIUE->getUpdater();2786}2787} else {2788// We don't need to track the structured representation of a2789// designated init update of an already-fully-initialized object in2790// verify-only mode. The only reason we would need the structure is2791// to determine where the uninitialized "holes" are, and in this2792// case, we know there aren't any and we can't introduce any.2793StructuredList = nullptr;2794}2795}2796}2797}27982799if (D->isFieldDesignator()) {2800// C99 6.7.8p7:2801//2802// If a designator has the form2803//2804// . identifier2805//2806// then the current object (defined below) shall have2807// structure or union type and the identifier shall be the2808// name of a member of that type.2809RecordDecl *RD = getRecordDecl(CurrentObjectType);2810if (!RD) {2811SourceLocation Loc = D->getDotLoc();2812if (Loc.isInvalid())2813Loc = D->getFieldLoc();2814if (!VerifyOnly)2815SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)2816<< SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;2817++Index;2818return true;2819}28202821FieldDecl *KnownField = D->getFieldDecl();2822if (!KnownField) {2823const IdentifierInfo *FieldName = D->getFieldName();2824ValueDecl *VD = SemaRef.tryLookupUnambiguousFieldDecl(RD, FieldName);2825if (auto *FD = dyn_cast_if_present<FieldDecl>(VD)) {2826KnownField = FD;2827} else if (auto *IFD = dyn_cast_if_present<IndirectFieldDecl>(VD)) {2828// In verify mode, don't modify the original.2829if (VerifyOnly)2830DIE = CloneDesignatedInitExpr(SemaRef, DIE);2831ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);2832D = DIE->getDesignator(DesigIdx);2833KnownField = cast<FieldDecl>(*IFD->chain_begin());2834}2835if (!KnownField) {2836if (VerifyOnly) {2837++Index;2838return true; // No typo correction when just trying this out.2839}28402841// We found a placeholder variable2842if (SemaRef.DiagRedefinedPlaceholderFieldDecl(DIE->getBeginLoc(), RD,2843FieldName)) {2844++Index;2845return true;2846}2847// Name lookup found something, but it wasn't a field.2848if (DeclContextLookupResult Lookup = RD->lookup(FieldName);2849!Lookup.empty()) {2850SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)2851<< FieldName;2852SemaRef.Diag(Lookup.front()->getLocation(),2853diag::note_field_designator_found);2854++Index;2855return true;2856}28572858// Name lookup didn't find anything.2859// Determine whether this was a typo for another field name.2860FieldInitializerValidatorCCC CCC(RD);2861if (TypoCorrection Corrected = SemaRef.CorrectTypo(2862DeclarationNameInfo(FieldName, D->getFieldLoc()),2863Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC,2864Sema::CTK_ErrorRecovery, RD)) {2865SemaRef.diagnoseTypo(2866Corrected,2867SemaRef.PDiag(diag::err_field_designator_unknown_suggest)2868<< FieldName << CurrentObjectType);2869KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();2870hadError = true;2871} else {2872// Typo correction didn't find anything.2873SourceLocation Loc = D->getFieldLoc();28742875// The loc can be invalid with a "null" designator (i.e. an anonymous2876// union/struct). Do our best to approximate the location.2877if (Loc.isInvalid())2878Loc = IList->getBeginLoc();28792880SemaRef.Diag(Loc, diag::err_field_designator_unknown)2881<< FieldName << CurrentObjectType << DIE->getSourceRange();2882++Index;2883return true;2884}2885}2886}28872888unsigned NumBases = 0;2889if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))2890NumBases = CXXRD->getNumBases();28912892unsigned FieldIndex = NumBases;28932894for (auto *FI : RD->fields()) {2895if (FI->isUnnamedBitField())2896continue;2897if (declaresSameEntity(KnownField, FI)) {2898KnownField = FI;2899break;2900}2901++FieldIndex;2902}29032904RecordDecl::field_iterator Field =2905RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));29062907// All of the fields of a union are located at the same place in2908// the initializer list.2909if (RD->isUnion()) {2910FieldIndex = 0;2911if (StructuredList) {2912FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();2913if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {2914assert(StructuredList->getNumInits() == 12915&& "A union should never have more than one initializer!");29162917Expr *ExistingInit = StructuredList->getInit(0);2918if (ExistingInit) {2919// We're about to throw away an initializer, emit warning.2920diagnoseInitOverride(2921ExistingInit, SourceRange(D->getBeginLoc(), DIE->getEndLoc()),2922/*UnionOverride=*/true,2923/*FullyOverwritten=*/SemaRef.getLangOpts().CPlusPlus ? false2924: true);2925}29262927// remove existing initializer2928StructuredList->resizeInits(SemaRef.Context, 0);2929StructuredList->setInitializedFieldInUnion(nullptr);2930}29312932StructuredList->setInitializedFieldInUnion(*Field);2933}2934}29352936// Make sure we can use this declaration.2937bool InvalidUse;2938if (VerifyOnly)2939InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);2940else2941InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());2942if (InvalidUse) {2943++Index;2944return true;2945}29462947// C++20 [dcl.init.list]p3:2948// The ordered identifiers in the designators of the designated-2949// initializer-list shall form a subsequence of the ordered identifiers2950// in the direct non-static data members of T.2951//2952// Note that this is not a condition on forming the aggregate2953// initialization, only on actually performing initialization,2954// so it is not checked in VerifyOnly mode.2955//2956// FIXME: This is the only reordering diagnostic we produce, and it only2957// catches cases where we have a top-level field designator that jumps2958// backwards. This is the only such case that is reachable in an2959// otherwise-valid C++20 program, so is the only case that's required for2960// conformance, but for consistency, we should diagnose all the other2961// cases where a designator takes us backwards too.2962if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus &&2963NextField &&2964(*NextField == RD->field_end() ||2965(*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) {2966// Find the field that we just initialized.2967FieldDecl *PrevField = nullptr;2968for (auto FI = RD->field_begin(); FI != RD->field_end(); ++FI) {2969if (FI->isUnnamedBitField())2970continue;2971if (*NextField != RD->field_end() &&2972declaresSameEntity(*FI, **NextField))2973break;2974PrevField = *FI;2975}29762977if (PrevField &&2978PrevField->getFieldIndex() > KnownField->getFieldIndex()) {2979SemaRef.Diag(DIE->getInit()->getBeginLoc(),2980diag::ext_designated_init_reordered)2981<< KnownField << PrevField << DIE->getSourceRange();29822983unsigned OldIndex = StructuredIndex - 1;2984if (StructuredList && OldIndex <= StructuredList->getNumInits()) {2985if (Expr *PrevInit = StructuredList->getInit(OldIndex)) {2986SemaRef.Diag(PrevInit->getBeginLoc(),2987diag::note_previous_field_init)2988<< PrevField << PrevInit->getSourceRange();2989}2990}2991}2992}299329942995// Update the designator with the field declaration.2996if (!VerifyOnly)2997D->setFieldDecl(*Field);29982999// Make sure that our non-designated initializer list has space3000// for a subobject corresponding to this field.3001if (StructuredList && FieldIndex >= StructuredList->getNumInits())3002StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);30033004// This designator names a flexible array member.3005if (Field->getType()->isIncompleteArrayType()) {3006bool Invalid = false;3007if ((DesigIdx + 1) != DIE->size()) {3008// We can't designate an object within the flexible array3009// member (because GCC doesn't allow it).3010if (!VerifyOnly) {3011DesignatedInitExpr::Designator *NextD3012= DIE->getDesignator(DesigIdx + 1);3013SemaRef.Diag(NextD->getBeginLoc(),3014diag::err_designator_into_flexible_array_member)3015<< SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());3016SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)3017<< *Field;3018}3019Invalid = true;3020}30213022if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&3023!isa<StringLiteral>(DIE->getInit())) {3024// The initializer is not an initializer list.3025if (!VerifyOnly) {3026SemaRef.Diag(DIE->getInit()->getBeginLoc(),3027diag::err_flexible_array_init_needs_braces)3028<< DIE->getInit()->getSourceRange();3029SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)3030<< *Field;3031}3032Invalid = true;3033}30343035// Check GNU flexible array initializer.3036if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,3037TopLevelObject))3038Invalid = true;30393040if (Invalid) {3041++Index;3042return true;3043}30443045// Initialize the array.3046bool prevHadError = hadError;3047unsigned newStructuredIndex = FieldIndex;3048unsigned OldIndex = Index;3049IList->setInit(Index, DIE->getInit());30503051InitializedEntity MemberEntity =3052InitializedEntity::InitializeMember(*Field, &Entity);3053CheckSubElementType(MemberEntity, IList, Field->getType(), Index,3054StructuredList, newStructuredIndex);30553056IList->setInit(OldIndex, DIE);3057if (hadError && !prevHadError) {3058++Field;3059++FieldIndex;3060if (NextField)3061*NextField = Field;3062StructuredIndex = FieldIndex;3063return true;3064}3065} else {3066// Recurse to check later designated subobjects.3067QualType FieldType = Field->getType();3068unsigned newStructuredIndex = FieldIndex;30693070InitializedEntity MemberEntity =3071InitializedEntity::InitializeMember(*Field, &Entity);3072if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,3073FieldType, nullptr, nullptr, Index,3074StructuredList, newStructuredIndex,3075FinishSubobjectInit, false))3076return true;3077}30783079// Find the position of the next field to be initialized in this3080// subobject.3081++Field;3082++FieldIndex;30833084// If this the first designator, our caller will continue checking3085// the rest of this struct/class/union subobject.3086if (IsFirstDesignator) {3087if (Field != RD->field_end() && Field->isUnnamedBitField())3088++Field;30893090if (NextField)3091*NextField = Field;30923093StructuredIndex = FieldIndex;3094return false;3095}30963097if (!FinishSubobjectInit)3098return false;30993100// We've already initialized something in the union; we're done.3101if (RD->isUnion())3102return hadError;31033104// Check the remaining fields within this class/struct/union subobject.3105bool prevHadError = hadError;31063107auto NoBases =3108CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),3109CXXRecordDecl::base_class_iterator());3110CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,3111false, Index, StructuredList, FieldIndex);3112return hadError && !prevHadError;3113}31143115// C99 6.7.8p6:3116//3117// If a designator has the form3118//3119// [ constant-expression ]3120//3121// then the current object (defined below) shall have array3122// type and the expression shall be an integer constant3123// expression. If the array is of unknown size, any3124// nonnegative value is valid.3125//3126// Additionally, cope with the GNU extension that permits3127// designators of the form3128//3129// [ constant-expression ... constant-expression ]3130const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);3131if (!AT) {3132if (!VerifyOnly)3133SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)3134<< CurrentObjectType;3135++Index;3136return true;3137}31383139Expr *IndexExpr = nullptr;3140llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;3141if (D->isArrayDesignator()) {3142IndexExpr = DIE->getArrayIndex(*D);3143DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);3144DesignatedEndIndex = DesignatedStartIndex;3145} else {3146assert(D->isArrayRangeDesignator() && "Need array-range designator");31473148DesignatedStartIndex =3149DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);3150DesignatedEndIndex =3151DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);3152IndexExpr = DIE->getArrayRangeEnd(*D);31533154// Codegen can't handle evaluating array range designators that have side3155// effects, because we replicate the AST value for each initialized element.3156// As such, set the sawArrayRangeDesignator() bit if we initialize multiple3157// elements with something that has a side effect, so codegen can emit an3158// "error unsupported" error instead of miscompiling the app.3159if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&3160DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)3161FullyStructuredList->sawArrayRangeDesignator();3162}31633164if (isa<ConstantArrayType>(AT)) {3165llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);3166DesignatedStartIndex3167= DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());3168DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());3169DesignatedEndIndex3170= DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());3171DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());3172if (DesignatedEndIndex >= MaxElements) {3173if (!VerifyOnly)3174SemaRef.Diag(IndexExpr->getBeginLoc(),3175diag::err_array_designator_too_large)3176<< toString(DesignatedEndIndex, 10) << toString(MaxElements, 10)3177<< IndexExpr->getSourceRange();3178++Index;3179return true;3180}3181} else {3182unsigned DesignatedIndexBitWidth =3183ConstantArrayType::getMaxSizeBits(SemaRef.Context);3184DesignatedStartIndex =3185DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);3186DesignatedEndIndex =3187DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);3188DesignatedStartIndex.setIsUnsigned(true);3189DesignatedEndIndex.setIsUnsigned(true);3190}31913192bool IsStringLiteralInitUpdate =3193StructuredList && StructuredList->isStringLiteralInit();3194if (IsStringLiteralInitUpdate && VerifyOnly) {3195// We're just verifying an update to a string literal init. We don't need3196// to split the string up into individual characters to do that.3197StructuredList = nullptr;3198} else if (IsStringLiteralInitUpdate) {3199// We're modifying a string literal init; we have to decompose the string3200// so we can modify the individual characters.3201ASTContext &Context = SemaRef.Context;3202Expr *SubExpr = StructuredList->getInit(0)->IgnoreParenImpCasts();32033204// Compute the character type3205QualType CharTy = AT->getElementType();32063207// Compute the type of the integer literals.3208QualType PromotedCharTy = CharTy;3209if (Context.isPromotableIntegerType(CharTy))3210PromotedCharTy = Context.getPromotedIntegerType(CharTy);3211unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);32123213if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {3214// Get the length of the string.3215uint64_t StrLen = SL->getLength();3216if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))3217StrLen = cast<ConstantArrayType>(AT)->getZExtSize();3218StructuredList->resizeInits(Context, StrLen);32193220// Build a literal for each character in the string, and put them into3221// the init list.3222for (unsigned i = 0, e = StrLen; i != e; ++i) {3223llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));3224Expr *Init = new (Context) IntegerLiteral(3225Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());3226if (CharTy != PromotedCharTy)3227Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,3228Init, nullptr, VK_PRValue,3229FPOptionsOverride());3230StructuredList->updateInit(Context, i, Init);3231}3232} else {3233ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);3234std::string Str;3235Context.getObjCEncodingForType(E->getEncodedType(), Str);32363237// Get the length of the string.3238uint64_t StrLen = Str.size();3239if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))3240StrLen = cast<ConstantArrayType>(AT)->getZExtSize();3241StructuredList->resizeInits(Context, StrLen);32423243// Build a literal for each character in the string, and put them into3244// the init list.3245for (unsigned i = 0, e = StrLen; i != e; ++i) {3246llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);3247Expr *Init = new (Context) IntegerLiteral(3248Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());3249if (CharTy != PromotedCharTy)3250Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,3251Init, nullptr, VK_PRValue,3252FPOptionsOverride());3253StructuredList->updateInit(Context, i, Init);3254}3255}3256}32573258// Make sure that our non-designated initializer list has space3259// for a subobject corresponding to this array element.3260if (StructuredList &&3261DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())3262StructuredList->resizeInits(SemaRef.Context,3263DesignatedEndIndex.getZExtValue() + 1);32643265// Repeatedly perform subobject initializations in the range3266// [DesignatedStartIndex, DesignatedEndIndex].32673268// Move to the next designator3269unsigned ElementIndex = DesignatedStartIndex.getZExtValue();3270unsigned OldIndex = Index;32713272InitializedEntity ElementEntity =3273InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);32743275while (DesignatedStartIndex <= DesignatedEndIndex) {3276// Recurse to check later designated subobjects.3277QualType ElementType = AT->getElementType();3278Index = OldIndex;32793280ElementEntity.setElementIndex(ElementIndex);3281if (CheckDesignatedInitializer(3282ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,3283nullptr, Index, StructuredList, ElementIndex,3284FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),3285false))3286return true;32873288// Move to the next index in the array that we'll be initializing.3289++DesignatedStartIndex;3290ElementIndex = DesignatedStartIndex.getZExtValue();3291}32923293// If this the first designator, our caller will continue checking3294// the rest of this array subobject.3295if (IsFirstDesignator) {3296if (NextElementIndex)3297*NextElementIndex = DesignatedStartIndex;3298StructuredIndex = ElementIndex;3299return false;3300}33013302if (!FinishSubobjectInit)3303return false;33043305// Check the remaining elements within this array subobject.3306bool prevHadError = hadError;3307CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,3308/*SubobjectIsDesignatorContext=*/false, Index,3309StructuredList, ElementIndex);3310return hadError && !prevHadError;3311}33123313// Get the structured initializer list for a subobject of type3314// @p CurrentObjectType.3315InitListExpr *3316InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,3317QualType CurrentObjectType,3318InitListExpr *StructuredList,3319unsigned StructuredIndex,3320SourceRange InitRange,3321bool IsFullyOverwritten) {3322if (!StructuredList)3323return nullptr;33243325Expr *ExistingInit = nullptr;3326if (StructuredIndex < StructuredList->getNumInits())3327ExistingInit = StructuredList->getInit(StructuredIndex);33283329if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))3330// There might have already been initializers for subobjects of the current3331// object, but a subsequent initializer list will overwrite the entirety3332// of the current object. (See DR 253 and C99 6.7.8p21). e.g.,3333//3334// struct P { char x[6]; };3335// struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };3336//3337// The first designated initializer is ignored, and l.x is just "f".3338if (!IsFullyOverwritten)3339return Result;33403341if (ExistingInit) {3342// We are creating an initializer list that initializes the3343// subobjects of the current object, but there was already an3344// initialization that completely initialized the current3345// subobject:3346//3347// struct X { int a, b; };3348// struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 };3349//3350// Here, xs[0].a == 1 and xs[0].b == 3, since the second,3351// designated initializer overwrites the [0].b initializer3352// from the prior initialization.3353//3354// When the existing initializer is an expression rather than an3355// initializer list, we cannot decompose and update it in this way.3356// For example:3357//3358// struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };3359//3360// This case is handled by CheckDesignatedInitializer.3361diagnoseInitOverride(ExistingInit, InitRange);3362}33633364unsigned ExpectedNumInits = 0;3365if (Index < IList->getNumInits()) {3366if (auto *Init = dyn_cast_or_null<InitListExpr>(IList->getInit(Index)))3367ExpectedNumInits = Init->getNumInits();3368else3369ExpectedNumInits = IList->getNumInits() - Index;3370}33713372InitListExpr *Result =3373createInitListExpr(CurrentObjectType, InitRange, ExpectedNumInits);33743375// Link this new initializer list into the structured initializer3376// lists.3377StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);3378return Result;3379}33803381InitListExpr *3382InitListChecker::createInitListExpr(QualType CurrentObjectType,3383SourceRange InitRange,3384unsigned ExpectedNumInits) {3385InitListExpr *Result = new (SemaRef.Context) InitListExpr(3386SemaRef.Context, InitRange.getBegin(), std::nullopt, InitRange.getEnd());33873388QualType ResultType = CurrentObjectType;3389if (!ResultType->isArrayType())3390ResultType = ResultType.getNonLValueExprType(SemaRef.Context);3391Result->setType(ResultType);33923393// Pre-allocate storage for the structured initializer list.3394unsigned NumElements = 0;33953396if (const ArrayType *AType3397= SemaRef.Context.getAsArrayType(CurrentObjectType)) {3398if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {3399NumElements = CAType->getZExtSize();3400// Simple heuristic so that we don't allocate a very large3401// initializer with many empty entries at the end.3402if (NumElements > ExpectedNumInits)3403NumElements = 0;3404}3405} else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) {3406NumElements = VType->getNumElements();3407} else if (CurrentObjectType->isRecordType()) {3408NumElements = numStructUnionElements(CurrentObjectType);3409} else if (CurrentObjectType->isDependentType()) {3410NumElements = 1;3411}34123413Result->reserveInits(SemaRef.Context, NumElements);34143415return Result;3416}34173418/// Update the initializer at index @p StructuredIndex within the3419/// structured initializer list to the value @p expr.3420void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,3421unsigned &StructuredIndex,3422Expr *expr) {3423// No structured initializer list to update3424if (!StructuredList)3425return;34263427if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,3428StructuredIndex, expr)) {3429// This initializer overwrites a previous initializer.3430// No need to diagnose when `expr` is nullptr because a more relevant3431// diagnostic has already been issued and this diagnostic is potentially3432// noise.3433if (expr)3434diagnoseInitOverride(PrevInit, expr->getSourceRange());3435}34363437++StructuredIndex;3438}34393440bool Sema::CanPerformAggregateInitializationForOverloadResolution(3441const InitializedEntity &Entity, InitListExpr *From) {3442QualType Type = Entity.getType();3443InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true,3444/*TreatUnavailableAsInvalid=*/false,3445/*InOverloadResolution=*/true);3446return !Check.HadError();3447}34483449/// Check that the given Index expression is a valid array designator3450/// value. This is essentially just a wrapper around3451/// VerifyIntegerConstantExpression that also checks for negative values3452/// and produces a reasonable diagnostic if there is a3453/// failure. Returns the index expression, possibly with an implicit cast3454/// added, on success. If everything went okay, Value will receive the3455/// value of the constant expression.3456static ExprResult3457CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {3458SourceLocation Loc = Index->getBeginLoc();34593460// Make sure this is an integer constant expression.3461ExprResult Result =3462S.VerifyIntegerConstantExpression(Index, &Value, Sema::AllowFold);3463if (Result.isInvalid())3464return Result;34653466if (Value.isSigned() && Value.isNegative())3467return S.Diag(Loc, diag::err_array_designator_negative)3468<< toString(Value, 10) << Index->getSourceRange();34693470Value.setIsUnsigned(true);3471return Result;3472}34733474ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,3475SourceLocation EqualOrColonLoc,3476bool GNUSyntax,3477ExprResult Init) {3478typedef DesignatedInitExpr::Designator ASTDesignator;34793480bool Invalid = false;3481SmallVector<ASTDesignator, 32> Designators;3482SmallVector<Expr *, 32> InitExpressions;34833484// Build designators and check array designator expressions.3485for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {3486const Designator &D = Desig.getDesignator(Idx);34873488if (D.isFieldDesignator()) {3489Designators.push_back(ASTDesignator::CreateFieldDesignator(3490D.getFieldDecl(), D.getDotLoc(), D.getFieldLoc()));3491} else if (D.isArrayDesignator()) {3492Expr *Index = static_cast<Expr *>(D.getArrayIndex());3493llvm::APSInt IndexValue;3494if (!Index->isTypeDependent() && !Index->isValueDependent())3495Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();3496if (!Index)3497Invalid = true;3498else {3499Designators.push_back(ASTDesignator::CreateArrayDesignator(3500InitExpressions.size(), D.getLBracketLoc(), D.getRBracketLoc()));3501InitExpressions.push_back(Index);3502}3503} else if (D.isArrayRangeDesignator()) {3504Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());3505Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());3506llvm::APSInt StartValue;3507llvm::APSInt EndValue;3508bool StartDependent = StartIndex->isTypeDependent() ||3509StartIndex->isValueDependent();3510bool EndDependent = EndIndex->isTypeDependent() ||3511EndIndex->isValueDependent();3512if (!StartDependent)3513StartIndex =3514CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();3515if (!EndDependent)3516EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();35173518if (!StartIndex || !EndIndex)3519Invalid = true;3520else {3521// Make sure we're comparing values with the same bit width.3522if (StartDependent || EndDependent) {3523// Nothing to compute.3524} else if (StartValue.getBitWidth() > EndValue.getBitWidth())3525EndValue = EndValue.extend(StartValue.getBitWidth());3526else if (StartValue.getBitWidth() < EndValue.getBitWidth())3527StartValue = StartValue.extend(EndValue.getBitWidth());35283529if (!StartDependent && !EndDependent && EndValue < StartValue) {3530Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)3531<< toString(StartValue, 10) << toString(EndValue, 10)3532<< StartIndex->getSourceRange() << EndIndex->getSourceRange();3533Invalid = true;3534} else {3535Designators.push_back(ASTDesignator::CreateArrayRangeDesignator(3536InitExpressions.size(), D.getLBracketLoc(), D.getEllipsisLoc(),3537D.getRBracketLoc()));3538InitExpressions.push_back(StartIndex);3539InitExpressions.push_back(EndIndex);3540}3541}3542}3543}35443545if (Invalid || Init.isInvalid())3546return ExprError();35473548return DesignatedInitExpr::Create(Context, Designators, InitExpressions,3549EqualOrColonLoc, GNUSyntax,3550Init.getAs<Expr>());3551}35523553//===----------------------------------------------------------------------===//3554// Initialization entity3555//===----------------------------------------------------------------------===//35563557InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,3558const InitializedEntity &Parent)3559: Parent(&Parent), Index(Index)3560{3561if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {3562Kind = EK_ArrayElement;3563Type = AT->getElementType();3564} else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {3565Kind = EK_VectorElement;3566Type = VT->getElementType();3567} else {3568const ComplexType *CT = Parent.getType()->getAs<ComplexType>();3569assert(CT && "Unexpected type");3570Kind = EK_ComplexElement;3571Type = CT->getElementType();3572}3573}35743575InitializedEntity3576InitializedEntity::InitializeBase(ASTContext &Context,3577const CXXBaseSpecifier *Base,3578bool IsInheritedVirtualBase,3579const InitializedEntity *Parent) {3580InitializedEntity Result;3581Result.Kind = EK_Base;3582Result.Parent = Parent;3583Result.Base = {Base, IsInheritedVirtualBase};3584Result.Type = Base->getType();3585return Result;3586}35873588DeclarationName InitializedEntity::getName() const {3589switch (getKind()) {3590case EK_Parameter:3591case EK_Parameter_CF_Audited: {3592ParmVarDecl *D = Parameter.getPointer();3593return (D ? D->getDeclName() : DeclarationName());3594}35953596case EK_Variable:3597case EK_Member:3598case EK_ParenAggInitMember:3599case EK_Binding:3600case EK_TemplateParameter:3601return Variable.VariableOrMember->getDeclName();36023603case EK_LambdaCapture:3604return DeclarationName(Capture.VarID);36053606case EK_Result:3607case EK_StmtExprResult:3608case EK_Exception:3609case EK_New:3610case EK_Temporary:3611case EK_Base:3612case EK_Delegating:3613case EK_ArrayElement:3614case EK_VectorElement:3615case EK_ComplexElement:3616case EK_BlockElement:3617case EK_LambdaToBlockConversionBlockElement:3618case EK_CompoundLiteralInit:3619case EK_RelatedResult:3620return DeclarationName();3621}36223623llvm_unreachable("Invalid EntityKind!");3624}36253626ValueDecl *InitializedEntity::getDecl() const {3627switch (getKind()) {3628case EK_Variable:3629case EK_Member:3630case EK_ParenAggInitMember:3631case EK_Binding:3632case EK_TemplateParameter:3633return Variable.VariableOrMember;36343635case EK_Parameter:3636case EK_Parameter_CF_Audited:3637return Parameter.getPointer();36383639case EK_Result:3640case EK_StmtExprResult:3641case EK_Exception:3642case EK_New:3643case EK_Temporary:3644case EK_Base:3645case EK_Delegating:3646case EK_ArrayElement:3647case EK_VectorElement:3648case EK_ComplexElement:3649case EK_BlockElement:3650case EK_LambdaToBlockConversionBlockElement:3651case EK_LambdaCapture:3652case EK_CompoundLiteralInit:3653case EK_RelatedResult:3654return nullptr;3655}36563657llvm_unreachable("Invalid EntityKind!");3658}36593660bool InitializedEntity::allowsNRVO() const {3661switch (getKind()) {3662case EK_Result:3663case EK_Exception:3664return LocAndNRVO.NRVO;36653666case EK_StmtExprResult:3667case EK_Variable:3668case EK_Parameter:3669case EK_Parameter_CF_Audited:3670case EK_TemplateParameter:3671case EK_Member:3672case EK_ParenAggInitMember:3673case EK_Binding:3674case EK_New:3675case EK_Temporary:3676case EK_CompoundLiteralInit:3677case EK_Base:3678case EK_Delegating:3679case EK_ArrayElement:3680case EK_VectorElement:3681case EK_ComplexElement:3682case EK_BlockElement:3683case EK_LambdaToBlockConversionBlockElement:3684case EK_LambdaCapture:3685case EK_RelatedResult:3686break;3687}36883689return false;3690}36913692unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {3693assert(getParent() != this);3694unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;3695for (unsigned I = 0; I != Depth; ++I)3696OS << "`-";36973698switch (getKind()) {3699case EK_Variable: OS << "Variable"; break;3700case EK_Parameter: OS << "Parameter"; break;3701case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";3702break;3703case EK_TemplateParameter: OS << "TemplateParameter"; break;3704case EK_Result: OS << "Result"; break;3705case EK_StmtExprResult: OS << "StmtExprResult"; break;3706case EK_Exception: OS << "Exception"; break;3707case EK_Member:3708case EK_ParenAggInitMember:3709OS << "Member";3710break;3711case EK_Binding: OS << "Binding"; break;3712case EK_New: OS << "New"; break;3713case EK_Temporary: OS << "Temporary"; break;3714case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;3715case EK_RelatedResult: OS << "RelatedResult"; break;3716case EK_Base: OS << "Base"; break;3717case EK_Delegating: OS << "Delegating"; break;3718case EK_ArrayElement: OS << "ArrayElement " << Index; break;3719case EK_VectorElement: OS << "VectorElement " << Index; break;3720case EK_ComplexElement: OS << "ComplexElement " << Index; break;3721case EK_BlockElement: OS << "Block"; break;3722case EK_LambdaToBlockConversionBlockElement:3723OS << "Block (lambda)";3724break;3725case EK_LambdaCapture:3726OS << "LambdaCapture ";3727OS << DeclarationName(Capture.VarID);3728break;3729}37303731if (auto *D = getDecl()) {3732OS << " ";3733D->printQualifiedName(OS);3734}37353736OS << " '" << getType() << "'\n";37373738return Depth + 1;3739}37403741LLVM_DUMP_METHOD void InitializedEntity::dump() const {3742dumpImpl(llvm::errs());3743}37443745//===----------------------------------------------------------------------===//3746// Initialization sequence3747//===----------------------------------------------------------------------===//37483749void InitializationSequence::Step::Destroy() {3750switch (Kind) {3751case SK_ResolveAddressOfOverloadedFunction:3752case SK_CastDerivedToBasePRValue:3753case SK_CastDerivedToBaseXValue:3754case SK_CastDerivedToBaseLValue:3755case SK_BindReference:3756case SK_BindReferenceToTemporary:3757case SK_FinalCopy:3758case SK_ExtraneousCopyToTemporary:3759case SK_UserConversion:3760case SK_QualificationConversionPRValue:3761case SK_QualificationConversionXValue:3762case SK_QualificationConversionLValue:3763case SK_FunctionReferenceConversion:3764case SK_AtomicConversion:3765case SK_ListInitialization:3766case SK_UnwrapInitList:3767case SK_RewrapInitList:3768case SK_ConstructorInitialization:3769case SK_ConstructorInitializationFromList:3770case SK_ZeroInitialization:3771case SK_CAssignment:3772case SK_StringInit:3773case SK_ObjCObjectConversion:3774case SK_ArrayLoopIndex:3775case SK_ArrayLoopInit:3776case SK_ArrayInit:3777case SK_GNUArrayInit:3778case SK_ParenthesizedArrayInit:3779case SK_PassByIndirectCopyRestore:3780case SK_PassByIndirectRestore:3781case SK_ProduceObjCObject:3782case SK_StdInitializerList:3783case SK_StdInitializerListConstructorCall:3784case SK_OCLSamplerInit:3785case SK_OCLZeroOpaqueType:3786case SK_ParenthesizedListInit:3787break;37883789case SK_ConversionSequence:3790case SK_ConversionSequenceNoNarrowing:3791delete ICS;3792}3793}37943795bool InitializationSequence::isDirectReferenceBinding() const {3796// There can be some lvalue adjustments after the SK_BindReference step.3797for (const Step &S : llvm::reverse(Steps)) {3798if (S.Kind == SK_BindReference)3799return true;3800if (S.Kind == SK_BindReferenceToTemporary)3801return false;3802}3803return false;3804}38053806bool InitializationSequence::isAmbiguous() const {3807if (!Failed())3808return false;38093810switch (getFailureKind()) {3811case FK_TooManyInitsForReference:3812case FK_ParenthesizedListInitForReference:3813case FK_ArrayNeedsInitList:3814case FK_ArrayNeedsInitListOrStringLiteral:3815case FK_ArrayNeedsInitListOrWideStringLiteral:3816case FK_NarrowStringIntoWideCharArray:3817case FK_WideStringIntoCharArray:3818case FK_IncompatWideStringIntoWideChar:3819case FK_PlainStringIntoUTF8Char:3820case FK_UTF8StringIntoPlainChar:3821case FK_AddressOfOverloadFailed: // FIXME: Could do better3822case FK_NonConstLValueReferenceBindingToTemporary:3823case FK_NonConstLValueReferenceBindingToBitfield:3824case FK_NonConstLValueReferenceBindingToVectorElement:3825case FK_NonConstLValueReferenceBindingToMatrixElement:3826case FK_NonConstLValueReferenceBindingToUnrelated:3827case FK_RValueReferenceBindingToLValue:3828case FK_ReferenceAddrspaceMismatchTemporary:3829case FK_ReferenceInitDropsQualifiers:3830case FK_ReferenceInitFailed:3831case FK_ConversionFailed:3832case FK_ConversionFromPropertyFailed:3833case FK_TooManyInitsForScalar:3834case FK_ParenthesizedListInitForScalar:3835case FK_ReferenceBindingToInitList:3836case FK_InitListBadDestinationType:3837case FK_DefaultInitOfConst:3838case FK_Incomplete:3839case FK_ArrayTypeMismatch:3840case FK_NonConstantArrayInit:3841case FK_ListInitializationFailed:3842case FK_VariableLengthArrayHasInitializer:3843case FK_PlaceholderType:3844case FK_ExplicitConstructor:3845case FK_AddressOfUnaddressableFunction:3846case FK_ParenthesizedListInitFailed:3847case FK_DesignatedInitForNonAggregate:3848return false;38493850case FK_ReferenceInitOverloadFailed:3851case FK_UserConversionOverloadFailed:3852case FK_ConstructorOverloadFailed:3853case FK_ListConstructorOverloadFailed:3854return FailedOverloadResult == OR_Ambiguous;3855}38563857llvm_unreachable("Invalid EntityKind!");3858}38593860bool InitializationSequence::isConstructorInitialization() const {3861return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;3862}38633864void3865InitializationSequence3866::AddAddressOverloadResolutionStep(FunctionDecl *Function,3867DeclAccessPair Found,3868bool HadMultipleCandidates) {3869Step S;3870S.Kind = SK_ResolveAddressOfOverloadedFunction;3871S.Type = Function->getType();3872S.Function.HadMultipleCandidates = HadMultipleCandidates;3873S.Function.Function = Function;3874S.Function.FoundDecl = Found;3875Steps.push_back(S);3876}38773878void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,3879ExprValueKind VK) {3880Step S;3881switch (VK) {3882case VK_PRValue:3883S.Kind = SK_CastDerivedToBasePRValue;3884break;3885case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;3886case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;3887}3888S.Type = BaseType;3889Steps.push_back(S);3890}38913892void InitializationSequence::AddReferenceBindingStep(QualType T,3893bool BindingTemporary) {3894Step S;3895S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;3896S.Type = T;3897Steps.push_back(S);3898}38993900void InitializationSequence::AddFinalCopy(QualType T) {3901Step S;3902S.Kind = SK_FinalCopy;3903S.Type = T;3904Steps.push_back(S);3905}39063907void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {3908Step S;3909S.Kind = SK_ExtraneousCopyToTemporary;3910S.Type = T;3911Steps.push_back(S);3912}39133914void3915InitializationSequence::AddUserConversionStep(FunctionDecl *Function,3916DeclAccessPair FoundDecl,3917QualType T,3918bool HadMultipleCandidates) {3919Step S;3920S.Kind = SK_UserConversion;3921S.Type = T;3922S.Function.HadMultipleCandidates = HadMultipleCandidates;3923S.Function.Function = Function;3924S.Function.FoundDecl = FoundDecl;3925Steps.push_back(S);3926}39273928void InitializationSequence::AddQualificationConversionStep(QualType Ty,3929ExprValueKind VK) {3930Step S;3931S.Kind = SK_QualificationConversionPRValue; // work around a gcc warning3932switch (VK) {3933case VK_PRValue:3934S.Kind = SK_QualificationConversionPRValue;3935break;3936case VK_XValue:3937S.Kind = SK_QualificationConversionXValue;3938break;3939case VK_LValue:3940S.Kind = SK_QualificationConversionLValue;3941break;3942}3943S.Type = Ty;3944Steps.push_back(S);3945}39463947void InitializationSequence::AddFunctionReferenceConversionStep(QualType Ty) {3948Step S;3949S.Kind = SK_FunctionReferenceConversion;3950S.Type = Ty;3951Steps.push_back(S);3952}39533954void InitializationSequence::AddAtomicConversionStep(QualType Ty) {3955Step S;3956S.Kind = SK_AtomicConversion;3957S.Type = Ty;3958Steps.push_back(S);3959}39603961void InitializationSequence::AddConversionSequenceStep(3962const ImplicitConversionSequence &ICS, QualType T,3963bool TopLevelOfInitList) {3964Step S;3965S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing3966: SK_ConversionSequence;3967S.Type = T;3968S.ICS = new ImplicitConversionSequence(ICS);3969Steps.push_back(S);3970}39713972void InitializationSequence::AddListInitializationStep(QualType T) {3973Step S;3974S.Kind = SK_ListInitialization;3975S.Type = T;3976Steps.push_back(S);3977}39783979void InitializationSequence::AddConstructorInitializationStep(3980DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,3981bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {3982Step S;3983S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall3984: SK_ConstructorInitializationFromList3985: SK_ConstructorInitialization;3986S.Type = T;3987S.Function.HadMultipleCandidates = HadMultipleCandidates;3988S.Function.Function = Constructor;3989S.Function.FoundDecl = FoundDecl;3990Steps.push_back(S);3991}39923993void InitializationSequence::AddZeroInitializationStep(QualType T) {3994Step S;3995S.Kind = SK_ZeroInitialization;3996S.Type = T;3997Steps.push_back(S);3998}39994000void InitializationSequence::AddCAssignmentStep(QualType T) {4001Step S;4002S.Kind = SK_CAssignment;4003S.Type = T;4004Steps.push_back(S);4005}40064007void InitializationSequence::AddStringInitStep(QualType T) {4008Step S;4009S.Kind = SK_StringInit;4010S.Type = T;4011Steps.push_back(S);4012}40134014void InitializationSequence::AddObjCObjectConversionStep(QualType T) {4015Step S;4016S.Kind = SK_ObjCObjectConversion;4017S.Type = T;4018Steps.push_back(S);4019}40204021void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) {4022Step S;4023S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;4024S.Type = T;4025Steps.push_back(S);4026}40274028void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) {4029Step S;4030S.Kind = SK_ArrayLoopIndex;4031S.Type = EltT;4032Steps.insert(Steps.begin(), S);40334034S.Kind = SK_ArrayLoopInit;4035S.Type = T;4036Steps.push_back(S);4037}40384039void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {4040Step S;4041S.Kind = SK_ParenthesizedArrayInit;4042S.Type = T;4043Steps.push_back(S);4044}40454046void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,4047bool shouldCopy) {4048Step s;4049s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore4050: SK_PassByIndirectRestore);4051s.Type = type;4052Steps.push_back(s);4053}40544055void InitializationSequence::AddProduceObjCObjectStep(QualType T) {4056Step S;4057S.Kind = SK_ProduceObjCObject;4058S.Type = T;4059Steps.push_back(S);4060}40614062void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {4063Step S;4064S.Kind = SK_StdInitializerList;4065S.Type = T;4066Steps.push_back(S);4067}40684069void InitializationSequence::AddOCLSamplerInitStep(QualType T) {4070Step S;4071S.Kind = SK_OCLSamplerInit;4072S.Type = T;4073Steps.push_back(S);4074}40754076void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T) {4077Step S;4078S.Kind = SK_OCLZeroOpaqueType;4079S.Type = T;4080Steps.push_back(S);4081}40824083void InitializationSequence::AddParenthesizedListInitStep(QualType T) {4084Step S;4085S.Kind = SK_ParenthesizedListInit;4086S.Type = T;4087Steps.push_back(S);4088}40894090void InitializationSequence::RewrapReferenceInitList(QualType T,4091InitListExpr *Syntactic) {4092assert(Syntactic->getNumInits() == 1 &&4093"Can only rewrap trivial init lists.");4094Step S;4095S.Kind = SK_UnwrapInitList;4096S.Type = Syntactic->getInit(0)->getType();4097Steps.insert(Steps.begin(), S);40984099S.Kind = SK_RewrapInitList;4100S.Type = T;4101S.WrappingSyntacticList = Syntactic;4102Steps.push_back(S);4103}41044105void InitializationSequence::SetOverloadFailure(FailureKind Failure,4106OverloadingResult Result) {4107setSequenceKind(FailedSequence);4108this->Failure = Failure;4109this->FailedOverloadResult = Result;4110}41114112//===----------------------------------------------------------------------===//4113// Attempt initialization4114//===----------------------------------------------------------------------===//41154116/// Tries to add a zero initializer. Returns true if that worked.4117static bool4118maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,4119const InitializedEntity &Entity) {4120if (Entity.getKind() != InitializedEntity::EK_Variable)4121return false;41224123VarDecl *VD = cast<VarDecl>(Entity.getDecl());4124if (VD->getInit() || VD->getEndLoc().isMacroID())4125return false;41264127QualType VariableTy = VD->getType().getCanonicalType();4128SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc());4129std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);4130if (!Init.empty()) {4131Sequence.AddZeroInitializationStep(Entity.getType());4132Sequence.SetZeroInitializationFixit(Init, Loc);4133return true;4134}4135return false;4136}41374138static void MaybeProduceObjCObject(Sema &S,4139InitializationSequence &Sequence,4140const InitializedEntity &Entity) {4141if (!S.getLangOpts().ObjCAutoRefCount) return;41424143/// When initializing a parameter, produce the value if it's marked4144/// __attribute__((ns_consumed)).4145if (Entity.isParameterKind()) {4146if (!Entity.isParameterConsumed())4147return;41484149assert(Entity.getType()->isObjCRetainableType() &&4150"consuming an object of unretainable type?");4151Sequence.AddProduceObjCObjectStep(Entity.getType());41524153/// When initializing a return value, if the return type is a4154/// retainable type, then returns need to immediately retain the4155/// object. If an autorelease is required, it will be done at the4156/// last instant.4157} else if (Entity.getKind() == InitializedEntity::EK_Result ||4158Entity.getKind() == InitializedEntity::EK_StmtExprResult) {4159if (!Entity.getType()->isObjCRetainableType())4160return;41614162Sequence.AddProduceObjCObjectStep(Entity.getType());4163}4164}41654166static void TryListInitialization(Sema &S,4167const InitializedEntity &Entity,4168const InitializationKind &Kind,4169InitListExpr *InitList,4170InitializationSequence &Sequence,4171bool TreatUnavailableAsInvalid);41724173/// When initializing from init list via constructor, handle4174/// initialization of an object of type std::initializer_list<T>.4175///4176/// \return true if we have handled initialization of an object of type4177/// std::initializer_list<T>, false otherwise.4178static bool TryInitializerListConstruction(Sema &S,4179InitListExpr *List,4180QualType DestType,4181InitializationSequence &Sequence,4182bool TreatUnavailableAsInvalid) {4183QualType E;4184if (!S.isStdInitializerList(DestType, &E))4185return false;41864187if (!S.isCompleteType(List->getExprLoc(), E)) {4188Sequence.setIncompleteTypeFailure(E);4189return true;4190}41914192// Try initializing a temporary array from the init list.4193QualType ArrayType = S.Context.getConstantArrayType(4194E.withConst(),4195llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),4196List->getNumInits()),4197nullptr, clang::ArraySizeModifier::Normal, 0);4198InitializedEntity HiddenArray =4199InitializedEntity::InitializeTemporary(ArrayType);4200InitializationKind Kind = InitializationKind::CreateDirectList(4201List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());4202TryListInitialization(S, HiddenArray, Kind, List, Sequence,4203TreatUnavailableAsInvalid);4204if (Sequence)4205Sequence.AddStdInitializerListConstructionStep(DestType);4206return true;4207}42084209/// Determine if the constructor has the signature of a copy or move4210/// constructor for the type T of the class in which it was found. That is,4211/// determine if its first parameter is of type T or reference to (possibly4212/// cv-qualified) T.4213static bool hasCopyOrMoveCtorParam(ASTContext &Ctx,4214const ConstructorInfo &Info) {4215if (Info.Constructor->getNumParams() == 0)4216return false;42174218QualType ParmT =4219Info.Constructor->getParamDecl(0)->getType().getNonReferenceType();4220QualType ClassT =4221Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));42224223return Ctx.hasSameUnqualifiedType(ParmT, ClassT);4224}42254226static OverloadingResult ResolveConstructorOverload(4227Sema &S, SourceLocation DeclLoc, MultiExprArg Args,4228OverloadCandidateSet &CandidateSet, QualType DestType,4229DeclContext::lookup_result Ctors, OverloadCandidateSet::iterator &Best,4230bool CopyInitializing, bool AllowExplicit, bool OnlyListConstructors,4231bool IsListInit, bool RequireActualConstructor,4232bool SecondStepOfCopyInit = false) {4233CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor);4234CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());42354236for (NamedDecl *D : Ctors) {4237auto Info = getConstructorInfo(D);4238if (!Info.Constructor || Info.Constructor->isInvalidDecl())4239continue;42404241if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))4242continue;42434244// C++11 [over.best.ics]p4:4245// ... and the constructor or user-defined conversion function is a4246// candidate by4247// - 13.3.1.3, when the argument is the temporary in the second step4248// of a class copy-initialization, or4249// - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]4250// - the second phase of 13.3.1.7 when the initializer list has exactly4251// one element that is itself an initializer list, and the target is4252// the first parameter of a constructor of class X, and the conversion4253// is to X or reference to (possibly cv-qualified X),4254// user-defined conversion sequences are not considered.4255bool SuppressUserConversions =4256SecondStepOfCopyInit ||4257(IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&4258hasCopyOrMoveCtorParam(S.Context, Info));42594260if (Info.ConstructorTmpl)4261S.AddTemplateOverloadCandidate(4262Info.ConstructorTmpl, Info.FoundDecl,4263/*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions,4264/*PartialOverloading=*/false, AllowExplicit);4265else {4266// C++ [over.match.copy]p1:4267// - When initializing a temporary to be bound to the first parameter4268// of a constructor [for type T] that takes a reference to possibly4269// cv-qualified T as its first argument, called with a single4270// argument in the context of direct-initialization, explicit4271// conversion functions are also considered.4272// FIXME: What if a constructor template instantiates to such a signature?4273bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&4274Args.size() == 1 &&4275hasCopyOrMoveCtorParam(S.Context, Info);4276S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,4277CandidateSet, SuppressUserConversions,4278/*PartialOverloading=*/false, AllowExplicit,4279AllowExplicitConv);4280}4281}42824283// FIXME: Work around a bug in C++17 guaranteed copy elision.4284//4285// When initializing an object of class type T by constructor4286// ([over.match.ctor]) or by list-initialization ([over.match.list])4287// from a single expression of class type U, conversion functions of4288// U that convert to the non-reference type cv T are candidates.4289// Explicit conversion functions are only candidates during4290// direct-initialization.4291//4292// Note: SecondStepOfCopyInit is only ever true in this case when4293// evaluating whether to produce a C++98 compatibility warning.4294if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&4295!RequireActualConstructor && !SecondStepOfCopyInit) {4296Expr *Initializer = Args[0];4297auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();4298if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {4299const auto &Conversions = SourceRD->getVisibleConversionFunctions();4300for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {4301NamedDecl *D = *I;4302CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());4303D = D->getUnderlyingDecl();43044305FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);4306CXXConversionDecl *Conv;4307if (ConvTemplate)4308Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());4309else4310Conv = cast<CXXConversionDecl>(D);43114312if (ConvTemplate)4313S.AddTemplateConversionCandidate(4314ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,4315CandidateSet, AllowExplicit, AllowExplicit,4316/*AllowResultConversion*/ false);4317else4318S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,4319DestType, CandidateSet, AllowExplicit,4320AllowExplicit,4321/*AllowResultConversion*/ false);4322}4323}4324}43254326// Perform overload resolution and return the result.4327return CandidateSet.BestViableFunction(S, DeclLoc, Best);4328}43294330/// Attempt initialization by constructor (C++ [dcl.init]), which4331/// enumerates the constructors of the initialized entity and performs overload4332/// resolution to select the best.4333/// \param DestType The destination class type.4334/// \param DestArrayType The destination type, which is either DestType or4335/// a (possibly multidimensional) array of DestType.4336/// \param IsListInit Is this list-initialization?4337/// \param IsInitListCopy Is this non-list-initialization resulting from a4338/// list-initialization from {x} where x is the same4339/// type as the entity?4340static void TryConstructorInitialization(Sema &S,4341const InitializedEntity &Entity,4342const InitializationKind &Kind,4343MultiExprArg Args, QualType DestType,4344QualType DestArrayType,4345InitializationSequence &Sequence,4346bool IsListInit = false,4347bool IsInitListCopy = false) {4348assert(((!IsListInit && !IsInitListCopy) ||4349(Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&4350"IsListInit/IsInitListCopy must come with a single initializer list "4351"argument.");4352InitListExpr *ILE =4353(IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;4354MultiExprArg UnwrappedArgs =4355ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;43564357// The type we're constructing needs to be complete.4358if (!S.isCompleteType(Kind.getLocation(), DestType)) {4359Sequence.setIncompleteTypeFailure(DestType);4360return;4361}43624363bool RequireActualConstructor =4364!(Entity.getKind() != InitializedEntity::EK_Base &&4365Entity.getKind() != InitializedEntity::EK_Delegating &&4366Entity.getKind() !=4367InitializedEntity::EK_LambdaToBlockConversionBlockElement);43684369// C++17 [dcl.init]p17:4370// - If the initializer expression is a prvalue and the cv-unqualified4371// version of the source type is the same class as the class of the4372// destination, the initializer expression is used to initialize the4373// destination object.4374// Per DR (no number yet), this does not apply when initializing a base4375// class or delegating to another constructor from a mem-initializer.4376// ObjC++: Lambda captured by the block in the lambda to block conversion4377// should avoid copy elision.4378if (S.getLangOpts().CPlusPlus17 && !RequireActualConstructor &&4379UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() &&4380S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {4381// Convert qualifications if necessary.4382Sequence.AddQualificationConversionStep(DestType, VK_PRValue);4383if (ILE)4384Sequence.RewrapReferenceInitList(DestType, ILE);4385return;4386}43874388const RecordType *DestRecordType = DestType->getAs<RecordType>();4389assert(DestRecordType && "Constructor initialization requires record type");4390CXXRecordDecl *DestRecordDecl4391= cast<CXXRecordDecl>(DestRecordType->getDecl());43924393// Build the candidate set directly in the initialization sequence4394// structure, so that it will persist if we fail.4395OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();43964397// Determine whether we are allowed to call explicit constructors or4398// explicit conversion operators.4399bool AllowExplicit = Kind.AllowExplicit() || IsListInit;4400bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;44014402// - Otherwise, if T is a class type, constructors are considered. The4403// applicable constructors are enumerated, and the best one is chosen4404// through overload resolution.4405DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);44064407OverloadingResult Result = OR_No_Viable_Function;4408OverloadCandidateSet::iterator Best;4409bool AsInitializerList = false;44104411// C++11 [over.match.list]p1, per DR1467:4412// When objects of non-aggregate type T are list-initialized, such that4413// 8.5.4 [dcl.init.list] specifies that overload resolution is performed4414// according to the rules in this section, overload resolution selects4415// the constructor in two phases:4416//4417// - Initially, the candidate functions are the initializer-list4418// constructors of the class T and the argument list consists of the4419// initializer list as a single argument.4420if (IsListInit) {4421AsInitializerList = true;44224423// If the initializer list has no elements and T has a default constructor,4424// the first phase is omitted.4425if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(DestRecordDecl)))4426Result = ResolveConstructorOverload(4427S, Kind.getLocation(), Args, CandidateSet, DestType, Ctors, Best,4428CopyInitialization, AllowExplicit,4429/*OnlyListConstructors=*/true, IsListInit, RequireActualConstructor);4430}44314432// C++11 [over.match.list]p1:4433// - If no viable initializer-list constructor is found, overload resolution4434// is performed again, where the candidate functions are all the4435// constructors of the class T and the argument list consists of the4436// elements of the initializer list.4437if (Result == OR_No_Viable_Function) {4438AsInitializerList = false;4439Result = ResolveConstructorOverload(4440S, Kind.getLocation(), UnwrappedArgs, CandidateSet, DestType, Ctors,4441Best, CopyInitialization, AllowExplicit,4442/*OnlyListConstructors=*/false, IsListInit, RequireActualConstructor);4443}4444if (Result) {4445Sequence.SetOverloadFailure(4446IsListInit ? InitializationSequence::FK_ListConstructorOverloadFailed4447: InitializationSequence::FK_ConstructorOverloadFailed,4448Result);44494450if (Result != OR_Deleted)4451return;4452}44534454bool HadMultipleCandidates = (CandidateSet.size() > 1);44554456// In C++17, ResolveConstructorOverload can select a conversion function4457// instead of a constructor.4458if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {4459// Add the user-defined conversion step that calls the conversion function.4460QualType ConvType = CD->getConversionType();4461assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&4462"should not have selected this conversion function");4463Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,4464HadMultipleCandidates);4465if (!S.Context.hasSameType(ConvType, DestType))4466Sequence.AddQualificationConversionStep(DestType, VK_PRValue);4467if (IsListInit)4468Sequence.RewrapReferenceInitList(Entity.getType(), ILE);4469return;4470}44714472CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);4473if (Result != OR_Deleted) {4474// C++11 [dcl.init]p6:4475// If a program calls for the default initialization of an object4476// of a const-qualified type T, T shall be a class type with a4477// user-provided default constructor.4478// C++ core issue 253 proposal:4479// If the implicit default constructor initializes all subobjects, no4480// initializer should be required.4481// The 253 proposal is for example needed to process libstdc++ headers4482// in 5.x.4483if (Kind.getKind() == InitializationKind::IK_Default &&4484Entity.getType().isConstQualified()) {4485if (!CtorDecl->getParent()->allowConstDefaultInit()) {4486if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))4487Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);4488return;4489}4490}44914492// C++11 [over.match.list]p1:4493// In copy-list-initialization, if an explicit constructor is chosen, the4494// initializer is ill-formed.4495if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {4496Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);4497return;4498}4499}45004501// [class.copy.elision]p3:4502// In some copy-initialization contexts, a two-stage overload resolution4503// is performed.4504// If the first overload resolution selects a deleted function, we also4505// need the initialization sequence to decide whether to perform the second4506// overload resolution.4507// For deleted functions in other contexts, there is no need to get the4508// initialization sequence.4509if (Result == OR_Deleted && Kind.getKind() != InitializationKind::IK_Copy)4510return;45114512// Add the constructor initialization step. Any cv-qualification conversion is4513// subsumed by the initialization.4514Sequence.AddConstructorInitializationStep(4515Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,4516IsListInit | IsInitListCopy, AsInitializerList);4517}45184519static bool4520ResolveOverloadedFunctionForReferenceBinding(Sema &S,4521Expr *Initializer,4522QualType &SourceType,4523QualType &UnqualifiedSourceType,4524QualType UnqualifiedTargetType,4525InitializationSequence &Sequence) {4526if (S.Context.getCanonicalType(UnqualifiedSourceType) ==4527S.Context.OverloadTy) {4528DeclAccessPair Found;4529bool HadMultipleCandidates = false;4530if (FunctionDecl *Fn4531= S.ResolveAddressOfOverloadedFunction(Initializer,4532UnqualifiedTargetType,4533false, Found,4534&HadMultipleCandidates)) {4535Sequence.AddAddressOverloadResolutionStep(Fn, Found,4536HadMultipleCandidates);4537SourceType = Fn->getType();4538UnqualifiedSourceType = SourceType.getUnqualifiedType();4539} else if (!UnqualifiedTargetType->isRecordType()) {4540Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);4541return true;4542}4543}4544return false;4545}45464547static void TryReferenceInitializationCore(Sema &S,4548const InitializedEntity &Entity,4549const InitializationKind &Kind,4550Expr *Initializer,4551QualType cv1T1, QualType T1,4552Qualifiers T1Quals,4553QualType cv2T2, QualType T2,4554Qualifiers T2Quals,4555InitializationSequence &Sequence,4556bool TopLevelOfInitList);45574558static void TryValueInitialization(Sema &S,4559const InitializedEntity &Entity,4560const InitializationKind &Kind,4561InitializationSequence &Sequence,4562InitListExpr *InitList = nullptr);45634564/// Attempt list initialization of a reference.4565static void TryReferenceListInitialization(Sema &S,4566const InitializedEntity &Entity,4567const InitializationKind &Kind,4568InitListExpr *InitList,4569InitializationSequence &Sequence,4570bool TreatUnavailableAsInvalid) {4571// First, catch C++03 where this isn't possible.4572if (!S.getLangOpts().CPlusPlus11) {4573Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);4574return;4575}4576// Can't reference initialize a compound literal.4577if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {4578Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);4579return;4580}45814582QualType DestType = Entity.getType();4583QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();4584Qualifiers T1Quals;4585QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);45864587// Reference initialization via an initializer list works thus:4588// If the initializer list consists of a single element that is4589// reference-related to the referenced type, bind directly to that element4590// (possibly creating temporaries).4591// Otherwise, initialize a temporary with the initializer list and4592// bind to that.4593if (InitList->getNumInits() == 1) {4594Expr *Initializer = InitList->getInit(0);4595QualType cv2T2 = S.getCompletedType(Initializer);4596Qualifiers T2Quals;4597QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);45984599// If this fails, creating a temporary wouldn't work either.4600if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,4601T1, Sequence))4602return;46034604SourceLocation DeclLoc = Initializer->getBeginLoc();4605Sema::ReferenceCompareResult RefRelationship4606= S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2);4607if (RefRelationship >= Sema::Ref_Related) {4608// Try to bind the reference here.4609TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,4610T1Quals, cv2T2, T2, T2Quals, Sequence,4611/*TopLevelOfInitList=*/true);4612if (Sequence)4613Sequence.RewrapReferenceInitList(cv1T1, InitList);4614return;4615}46164617// Update the initializer if we've resolved an overloaded function.4618if (Sequence.step_begin() != Sequence.step_end())4619Sequence.RewrapReferenceInitList(cv1T1, InitList);4620}4621// Perform address space compatibility check.4622QualType cv1T1IgnoreAS = cv1T1;4623if (T1Quals.hasAddressSpace()) {4624Qualifiers T2Quals;4625(void)S.Context.getUnqualifiedArrayType(InitList->getType(), T2Quals);4626if (!T1Quals.isAddressSpaceSupersetOf(T2Quals)) {4627Sequence.SetFailed(4628InitializationSequence::FK_ReferenceInitDropsQualifiers);4629return;4630}4631// Ignore address space of reference type at this point and perform address4632// space conversion after the reference binding step.4633cv1T1IgnoreAS =4634S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace());4635}4636// Not reference-related. Create a temporary and bind to that.4637InitializedEntity TempEntity =4638InitializedEntity::InitializeTemporary(cv1T1IgnoreAS);46394640TryListInitialization(S, TempEntity, Kind, InitList, Sequence,4641TreatUnavailableAsInvalid);4642if (Sequence) {4643if (DestType->isRValueReferenceType() ||4644(T1Quals.hasConst() && !T1Quals.hasVolatile())) {4645if (S.getLangOpts().CPlusPlus20 &&4646isa<IncompleteArrayType>(T1->getUnqualifiedDesugaredType()) &&4647DestType->isRValueReferenceType()) {4648// C++20 [dcl.init.list]p3.10:4649// List-initialization of an object or reference of type T is defined as4650// follows:4651// ..., unless T is “reference to array of unknown bound of U”, in which4652// case the type of the prvalue is the type of x in the declaration U4653// x[] H, where H is the initializer list.4654Sequence.AddQualificationConversionStep(cv1T1, clang::VK_PRValue);4655}4656Sequence.AddReferenceBindingStep(cv1T1IgnoreAS,4657/*BindingTemporary=*/true);4658if (T1Quals.hasAddressSpace())4659Sequence.AddQualificationConversionStep(4660cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue);4661} else4662Sequence.SetFailed(4663InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);4664}4665}46664667/// Attempt list initialization (C++0x [dcl.init.list])4668static void TryListInitialization(Sema &S,4669const InitializedEntity &Entity,4670const InitializationKind &Kind,4671InitListExpr *InitList,4672InitializationSequence &Sequence,4673bool TreatUnavailableAsInvalid) {4674QualType DestType = Entity.getType();46754676// C++ doesn't allow scalar initialization with more than one argument.4677// But C99 complex numbers are scalars and it makes sense there.4678if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&4679!DestType->isAnyComplexType() && InitList->getNumInits() > 1) {4680Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);4681return;4682}4683if (DestType->isReferenceType()) {4684TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,4685TreatUnavailableAsInvalid);4686return;4687}46884689if (DestType->isRecordType() &&4690!S.isCompleteType(InitList->getBeginLoc(), DestType)) {4691Sequence.setIncompleteTypeFailure(DestType);4692return;4693}46944695// C++20 [dcl.init.list]p3:4696// - If the braced-init-list contains a designated-initializer-list, T shall4697// be an aggregate class. [...] Aggregate initialization is performed.4698//4699// We allow arrays here too in order to support array designators.4700//4701// FIXME: This check should precede the handling of reference initialization.4702// We follow other compilers in allowing things like 'Aggr &&a = {.x = 1};'4703// as a tentative DR resolution.4704bool IsDesignatedInit = InitList->hasDesignatedInit();4705if (!DestType->isAggregateType() && IsDesignatedInit) {4706Sequence.SetFailed(4707InitializationSequence::FK_DesignatedInitForNonAggregate);4708return;4709}47104711// C++11 [dcl.init.list]p3, per DR1467:4712// - If T is a class type and the initializer list has a single element of4713// type cv U, where U is T or a class derived from T, the object is4714// initialized from that element (by copy-initialization for4715// copy-list-initialization, or by direct-initialization for4716// direct-list-initialization).4717// - Otherwise, if T is a character array and the initializer list has a4718// single element that is an appropriately-typed string literal4719// (8.5.2 [dcl.init.string]), initialization is performed as described4720// in that section.4721// - Otherwise, if T is an aggregate, [...] (continue below).4722if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1 &&4723!IsDesignatedInit) {4724if (DestType->isRecordType()) {4725QualType InitType = InitList->getInit(0)->getType();4726if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||4727S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {4728Expr *InitListAsExpr = InitList;4729TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,4730DestType, Sequence,4731/*InitListSyntax*/false,4732/*IsInitListCopy*/true);4733return;4734}4735}4736if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {4737Expr *SubInit[1] = {InitList->getInit(0)};4738if (!isa<VariableArrayType>(DestAT) &&4739IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {4740InitializationKind SubKind =4741Kind.getKind() == InitializationKind::IK_DirectList4742? InitializationKind::CreateDirect(Kind.getLocation(),4743InitList->getLBraceLoc(),4744InitList->getRBraceLoc())4745: Kind;4746Sequence.InitializeFrom(S, Entity, SubKind, SubInit,4747/*TopLevelOfInitList*/ true,4748TreatUnavailableAsInvalid);47494750// TryStringLiteralInitialization() (in InitializeFrom()) will fail if4751// the element is not an appropriately-typed string literal, in which4752// case we should proceed as in C++11 (below).4753if (Sequence) {4754Sequence.RewrapReferenceInitList(Entity.getType(), InitList);4755return;4756}4757}4758}4759}47604761// C++11 [dcl.init.list]p3:4762// - If T is an aggregate, aggregate initialization is performed.4763if ((DestType->isRecordType() && !DestType->isAggregateType()) ||4764(S.getLangOpts().CPlusPlus11 &&4765S.isStdInitializerList(DestType, nullptr) && !IsDesignatedInit)) {4766if (S.getLangOpts().CPlusPlus11) {4767// - Otherwise, if the initializer list has no elements and T is a4768// class type with a default constructor, the object is4769// value-initialized.4770if (InitList->getNumInits() == 0) {4771CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();4772if (S.LookupDefaultConstructor(RD)) {4773TryValueInitialization(S, Entity, Kind, Sequence, InitList);4774return;4775}4776}47774778// - Otherwise, if T is a specialization of std::initializer_list<E>,4779// an initializer_list object constructed [...]4780if (TryInitializerListConstruction(S, InitList, DestType, Sequence,4781TreatUnavailableAsInvalid))4782return;47834784// - Otherwise, if T is a class type, constructors are considered.4785Expr *InitListAsExpr = InitList;4786TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,4787DestType, Sequence, /*InitListSyntax*/true);4788} else4789Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);4790return;4791}47924793if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&4794InitList->getNumInits() == 1) {4795Expr *E = InitList->getInit(0);47964797// - Otherwise, if T is an enumeration with a fixed underlying type,4798// the initializer-list has a single element v, and the initialization4799// is direct-list-initialization, the object is initialized with the4800// value T(v); if a narrowing conversion is required to convert v to4801// the underlying type of T, the program is ill-formed.4802auto *ET = DestType->getAs<EnumType>();4803if (S.getLangOpts().CPlusPlus17 &&4804Kind.getKind() == InitializationKind::IK_DirectList &&4805ET && ET->getDecl()->isFixed() &&4806!S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&4807(E->getType()->isIntegralOrUnscopedEnumerationType() ||4808E->getType()->isFloatingType())) {4809// There are two ways that T(v) can work when T is an enumeration type.4810// If there is either an implicit conversion sequence from v to T or4811// a conversion function that can convert from v to T, then we use that.4812// Otherwise, if v is of integral, unscoped enumeration, or floating-point4813// type, it is converted to the enumeration type via its underlying type.4814// There is no overlap possible between these two cases (except when the4815// source value is already of the destination type), and the first4816// case is handled by the general case for single-element lists below.4817ImplicitConversionSequence ICS;4818ICS.setStandard();4819ICS.Standard.setAsIdentityConversion();4820if (!E->isPRValue())4821ICS.Standard.First = ICK_Lvalue_To_Rvalue;4822// If E is of a floating-point type, then the conversion is ill-formed4823// due to narrowing, but go through the motions in order to produce the4824// right diagnostic.4825ICS.Standard.Second = E->getType()->isFloatingType()4826? ICK_Floating_Integral4827: ICK_Integral_Conversion;4828ICS.Standard.setFromType(E->getType());4829ICS.Standard.setToType(0, E->getType());4830ICS.Standard.setToType(1, DestType);4831ICS.Standard.setToType(2, DestType);4832Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),4833/*TopLevelOfInitList*/true);4834Sequence.RewrapReferenceInitList(Entity.getType(), InitList);4835return;4836}48374838// - Otherwise, if the initializer list has a single element of type E4839// [...references are handled above...], the object or reference is4840// initialized from that element (by copy-initialization for4841// copy-list-initialization, or by direct-initialization for4842// direct-list-initialization); if a narrowing conversion is required4843// to convert the element to T, the program is ill-formed.4844//4845// Per core-24034, this is direct-initialization if we were performing4846// direct-list-initialization and copy-initialization otherwise.4847// We can't use InitListChecker for this, because it always performs4848// copy-initialization. This only matters if we might use an 'explicit'4849// conversion operator, or for the special case conversion of nullptr_t to4850// bool, so we only need to handle those cases.4851//4852// FIXME: Why not do this in all cases?4853Expr *Init = InitList->getInit(0);4854if (Init->getType()->isRecordType() ||4855(Init->getType()->isNullPtrType() && DestType->isBooleanType())) {4856InitializationKind SubKind =4857Kind.getKind() == InitializationKind::IK_DirectList4858? InitializationKind::CreateDirect(Kind.getLocation(),4859InitList->getLBraceLoc(),4860InitList->getRBraceLoc())4861: Kind;4862Expr *SubInit[1] = { Init };4863Sequence.InitializeFrom(S, Entity, SubKind, SubInit,4864/*TopLevelOfInitList*/true,4865TreatUnavailableAsInvalid);4866if (Sequence)4867Sequence.RewrapReferenceInitList(Entity.getType(), InitList);4868return;4869}4870}48714872InitListChecker CheckInitList(S, Entity, InitList,4873DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);4874if (CheckInitList.HadError()) {4875Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);4876return;4877}48784879// Add the list initialization step with the built init list.4880Sequence.AddListInitializationStep(DestType);4881}48824883/// Try a reference initialization that involves calling a conversion4884/// function.4885static OverloadingResult TryRefInitWithConversionFunction(4886Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,4887Expr *Initializer, bool AllowRValues, bool IsLValueRef,4888InitializationSequence &Sequence) {4889QualType DestType = Entity.getType();4890QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();4891QualType T1 = cv1T1.getUnqualifiedType();4892QualType cv2T2 = Initializer->getType();4893QualType T2 = cv2T2.getUnqualifiedType();48944895assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) &&4896"Must have incompatible references when binding via conversion");48974898// Build the candidate set directly in the initialization sequence4899// structure, so that it will persist if we fail.4900OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();4901CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);49024903// Determine whether we are allowed to call explicit conversion operators.4904// Note that none of [over.match.copy], [over.match.conv], nor4905// [over.match.ref] permit an explicit constructor to be chosen when4906// initializing a reference, not even for direct-initialization.4907bool AllowExplicitCtors = false;4908bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();49094910const RecordType *T1RecordType = nullptr;4911if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&4912S.isCompleteType(Kind.getLocation(), T1)) {4913// The type we're converting to is a class type. Enumerate its constructors4914// to see if there is a suitable conversion.4915CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());49164917for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {4918auto Info = getConstructorInfo(D);4919if (!Info.Constructor)4920continue;49214922if (!Info.Constructor->isInvalidDecl() &&4923Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {4924if (Info.ConstructorTmpl)4925S.AddTemplateOverloadCandidate(4926Info.ConstructorTmpl, Info.FoundDecl,4927/*ExplicitArgs*/ nullptr, Initializer, CandidateSet,4928/*SuppressUserConversions=*/true,4929/*PartialOverloading*/ false, AllowExplicitCtors);4930else4931S.AddOverloadCandidate(4932Info.Constructor, Info.FoundDecl, Initializer, CandidateSet,4933/*SuppressUserConversions=*/true,4934/*PartialOverloading*/ false, AllowExplicitCtors);4935}4936}4937}4938if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())4939return OR_No_Viable_Function;49404941const RecordType *T2RecordType = nullptr;4942if ((T2RecordType = T2->getAs<RecordType>()) &&4943S.isCompleteType(Kind.getLocation(), T2)) {4944// The type we're converting from is a class type, enumerate its conversion4945// functions.4946CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());49474948const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();4949for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {4950NamedDecl *D = *I;4951CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());4952if (isa<UsingShadowDecl>(D))4953D = cast<UsingShadowDecl>(D)->getTargetDecl();49544955FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);4956CXXConversionDecl *Conv;4957if (ConvTemplate)4958Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());4959else4960Conv = cast<CXXConversionDecl>(D);49614962// If the conversion function doesn't return a reference type,4963// it can't be considered for this conversion unless we're allowed to4964// consider rvalues.4965// FIXME: Do we need to make sure that we only consider conversion4966// candidates with reference-compatible results? That might be needed to4967// break recursion.4968if ((AllowRValues ||4969Conv->getConversionType()->isLValueReferenceType())) {4970if (ConvTemplate)4971S.AddTemplateConversionCandidate(4972ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,4973CandidateSet,4974/*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);4975else4976S.AddConversionCandidate(4977Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet,4978/*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);4979}4980}4981}4982if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())4983return OR_No_Viable_Function;49844985SourceLocation DeclLoc = Initializer->getBeginLoc();49864987// Perform overload resolution. If it fails, return the failed result.4988OverloadCandidateSet::iterator Best;4989if (OverloadingResult Result4990= CandidateSet.BestViableFunction(S, DeclLoc, Best))4991return Result;49924993FunctionDecl *Function = Best->Function;4994// This is the overload that will be used for this initialization step if we4995// use this initialization. Mark it as referenced.4996Function->setReferenced();49974998// Compute the returned type and value kind of the conversion.4999QualType cv3T3;5000if (isa<CXXConversionDecl>(Function))5001cv3T3 = Function->getReturnType();5002else5003cv3T3 = T1;50045005ExprValueKind VK = VK_PRValue;5006if (cv3T3->isLValueReferenceType())5007VK = VK_LValue;5008else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())5009VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;5010cv3T3 = cv3T3.getNonLValueExprType(S.Context);50115012// Add the user-defined conversion step.5013bool HadMultipleCandidates = (CandidateSet.size() > 1);5014Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,5015HadMultipleCandidates);50165017// Determine whether we'll need to perform derived-to-base adjustments or5018// other conversions.5019Sema::ReferenceConversions RefConv;5020Sema::ReferenceCompareResult NewRefRelationship =5021S.CompareReferenceRelationship(DeclLoc, T1, cv3T3, &RefConv);50225023// Add the final conversion sequence, if necessary.5024if (NewRefRelationship == Sema::Ref_Incompatible) {5025assert(!isa<CXXConstructorDecl>(Function) &&5026"should not have conversion after constructor");50275028ImplicitConversionSequence ICS;5029ICS.setStandard();5030ICS.Standard = Best->FinalConversion;5031Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));50325033// Every implicit conversion results in a prvalue, except for a glvalue5034// derived-to-base conversion, which we handle below.5035cv3T3 = ICS.Standard.getToType(2);5036VK = VK_PRValue;5037}50385039// If the converted initializer is a prvalue, its type T4 is adjusted to5040// type "cv1 T4" and the temporary materialization conversion is applied.5041//5042// We adjust the cv-qualifications to match the reference regardless of5043// whether we have a prvalue so that the AST records the change. In this5044// case, T4 is "cv3 T3".5045QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());5046if (cv1T4.getQualifiers() != cv3T3.getQualifiers())5047Sequence.AddQualificationConversionStep(cv1T4, VK);5048Sequence.AddReferenceBindingStep(cv1T4, VK == VK_PRValue);5049VK = IsLValueRef ? VK_LValue : VK_XValue;50505051if (RefConv & Sema::ReferenceConversions::DerivedToBase)5052Sequence.AddDerivedToBaseCastStep(cv1T1, VK);5053else if (RefConv & Sema::ReferenceConversions::ObjC)5054Sequence.AddObjCObjectConversionStep(cv1T1);5055else if (RefConv & Sema::ReferenceConversions::Function)5056Sequence.AddFunctionReferenceConversionStep(cv1T1);5057else if (RefConv & Sema::ReferenceConversions::Qualification) {5058if (!S.Context.hasSameType(cv1T4, cv1T1))5059Sequence.AddQualificationConversionStep(cv1T1, VK);5060}50615062return OR_Success;5063}50645065static void CheckCXX98CompatAccessibleCopy(Sema &S,5066const InitializedEntity &Entity,5067Expr *CurInitExpr);50685069/// Attempt reference initialization (C++0x [dcl.init.ref])5070static void TryReferenceInitialization(Sema &S, const InitializedEntity &Entity,5071const InitializationKind &Kind,5072Expr *Initializer,5073InitializationSequence &Sequence,5074bool TopLevelOfInitList) {5075QualType DestType = Entity.getType();5076QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();5077Qualifiers T1Quals;5078QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);5079QualType cv2T2 = S.getCompletedType(Initializer);5080Qualifiers T2Quals;5081QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);50825083// If the initializer is the address of an overloaded function, try5084// to resolve the overloaded function. If all goes well, T2 is the5085// type of the resulting function.5086if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,5087T1, Sequence))5088return;50895090// Delegate everything else to a subfunction.5091TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,5092T1Quals, cv2T2, T2, T2Quals, Sequence,5093TopLevelOfInitList);5094}50955096/// Determine whether an expression is a non-referenceable glvalue (one to5097/// which a reference can never bind). Attempting to bind a reference to5098/// such a glvalue will always create a temporary.5099static bool isNonReferenceableGLValue(Expr *E) {5100return E->refersToBitField() || E->refersToVectorElement() ||5101E->refersToMatrixElement();5102}51035104/// Reference initialization without resolving overloaded functions.5105///5106/// We also can get here in C if we call a builtin which is declared as5107/// a function with a parameter of reference type (such as __builtin_va_end()).5108static void TryReferenceInitializationCore(Sema &S,5109const InitializedEntity &Entity,5110const InitializationKind &Kind,5111Expr *Initializer,5112QualType cv1T1, QualType T1,5113Qualifiers T1Quals,5114QualType cv2T2, QualType T2,5115Qualifiers T2Quals,5116InitializationSequence &Sequence,5117bool TopLevelOfInitList) {5118QualType DestType = Entity.getType();5119SourceLocation DeclLoc = Initializer->getBeginLoc();51205121// Compute some basic properties of the types and the initializer.5122bool isLValueRef = DestType->isLValueReferenceType();5123bool isRValueRef = !isLValueRef;5124Expr::Classification InitCategory = Initializer->Classify(S.Context);51255126Sema::ReferenceConversions RefConv;5127Sema::ReferenceCompareResult RefRelationship =5128S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, &RefConv);51295130// C++0x [dcl.init.ref]p5:5131// A reference to type "cv1 T1" is initialized by an expression of type5132// "cv2 T2" as follows:5133//5134// - If the reference is an lvalue reference and the initializer5135// expression5136// Note the analogous bullet points for rvalue refs to functions. Because5137// there are no function rvalues in C++, rvalue refs to functions are treated5138// like lvalue refs.5139OverloadingResult ConvOvlResult = OR_Success;5140bool T1Function = T1->isFunctionType();5141if (isLValueRef || T1Function) {5142if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&5143(RefRelationship == Sema::Ref_Compatible ||5144(Kind.isCStyleOrFunctionalCast() &&5145RefRelationship == Sema::Ref_Related))) {5146// - is an lvalue (but is not a bit-field), and "cv1 T1" is5147// reference-compatible with "cv2 T2," or5148if (RefConv & (Sema::ReferenceConversions::DerivedToBase |5149Sema::ReferenceConversions::ObjC)) {5150// If we're converting the pointee, add any qualifiers first;5151// these qualifiers must all be top-level, so just convert to "cv1 T2".5152if (RefConv & (Sema::ReferenceConversions::Qualification))5153Sequence.AddQualificationConversionStep(5154S.Context.getQualifiedType(T2, T1Quals),5155Initializer->getValueKind());5156if (RefConv & Sema::ReferenceConversions::DerivedToBase)5157Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);5158else5159Sequence.AddObjCObjectConversionStep(cv1T1);5160} else if (RefConv & Sema::ReferenceConversions::Qualification) {5161// Perform a (possibly multi-level) qualification conversion.5162Sequence.AddQualificationConversionStep(cv1T1,5163Initializer->getValueKind());5164} else if (RefConv & Sema::ReferenceConversions::Function) {5165Sequence.AddFunctionReferenceConversionStep(cv1T1);5166}51675168// We only create a temporary here when binding a reference to a5169// bit-field or vector element. Those cases are't supposed to be5170// handled by this bullet, but the outcome is the same either way.5171Sequence.AddReferenceBindingStep(cv1T1, false);5172return;5173}51745175// - has a class type (i.e., T2 is a class type), where T1 is not5176// reference-related to T2, and can be implicitly converted to an5177// lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible5178// with "cv3 T3" (this conversion is selected by enumerating the5179// applicable conversion functions (13.3.1.6) and choosing the best5180// one through overload resolution (13.3)),5181// If we have an rvalue ref to function type here, the rhs must be5182// an rvalue. DR1287 removed the "implicitly" here.5183if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&5184(isLValueRef || InitCategory.isRValue())) {5185if (S.getLangOpts().CPlusPlus) {5186// Try conversion functions only for C++.5187ConvOvlResult = TryRefInitWithConversionFunction(5188S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,5189/*IsLValueRef*/ isLValueRef, Sequence);5190if (ConvOvlResult == OR_Success)5191return;5192if (ConvOvlResult != OR_No_Viable_Function)5193Sequence.SetOverloadFailure(5194InitializationSequence::FK_ReferenceInitOverloadFailed,5195ConvOvlResult);5196} else {5197ConvOvlResult = OR_No_Viable_Function;5198}5199}5200}52015202// - Otherwise, the reference shall be an lvalue reference to a5203// non-volatile const type (i.e., cv1 shall be const), or the reference5204// shall be an rvalue reference.5205// For address spaces, we interpret this to mean that an addr space5206// of a reference "cv1 T1" is a superset of addr space of "cv2 T2".5207if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile() &&5208T1Quals.isAddressSpaceSupersetOf(T2Quals))) {5209if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)5210Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);5211else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())5212Sequence.SetOverloadFailure(5213InitializationSequence::FK_ReferenceInitOverloadFailed,5214ConvOvlResult);5215else if (!InitCategory.isLValue())5216Sequence.SetFailed(5217T1Quals.isAddressSpaceSupersetOf(T2Quals)5218? InitializationSequence::5219FK_NonConstLValueReferenceBindingToTemporary5220: InitializationSequence::FK_ReferenceInitDropsQualifiers);5221else {5222InitializationSequence::FailureKind FK;5223switch (RefRelationship) {5224case Sema::Ref_Compatible:5225if (Initializer->refersToBitField())5226FK = InitializationSequence::5227FK_NonConstLValueReferenceBindingToBitfield;5228else if (Initializer->refersToVectorElement())5229FK = InitializationSequence::5230FK_NonConstLValueReferenceBindingToVectorElement;5231else if (Initializer->refersToMatrixElement())5232FK = InitializationSequence::5233FK_NonConstLValueReferenceBindingToMatrixElement;5234else5235llvm_unreachable("unexpected kind of compatible initializer");5236break;5237case Sema::Ref_Related:5238FK = InitializationSequence::FK_ReferenceInitDropsQualifiers;5239break;5240case Sema::Ref_Incompatible:5241FK = InitializationSequence::5242FK_NonConstLValueReferenceBindingToUnrelated;5243break;5244}5245Sequence.SetFailed(FK);5246}5247return;5248}52495250// - If the initializer expression5251// - is an5252// [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or5253// [1z] rvalue (but not a bit-field) or5254// function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"5255//5256// Note: functions are handled above and below rather than here...5257if (!T1Function &&5258(RefRelationship == Sema::Ref_Compatible ||5259(Kind.isCStyleOrFunctionalCast() &&5260RefRelationship == Sema::Ref_Related)) &&5261((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||5262(InitCategory.isPRValue() &&5263(S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||5264T2->isArrayType())))) {5265ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_PRValue;5266if (InitCategory.isPRValue() && T2->isRecordType()) {5267// The corresponding bullet in C++03 [dcl.init.ref]p5 gives the5268// compiler the freedom to perform a copy here or bind to the5269// object, while C++0x requires that we bind directly to the5270// object. Hence, we always bind to the object without making an5271// extra copy. However, in C++03 requires that we check for the5272// presence of a suitable copy constructor:5273//5274// The constructor that would be used to make the copy shall5275// be callable whether or not the copy is actually done.5276if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)5277Sequence.AddExtraneousCopyToTemporary(cv2T2);5278else if (S.getLangOpts().CPlusPlus11)5279CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);5280}52815282// C++1z [dcl.init.ref]/5.2.1.2:5283// If the converted initializer is a prvalue, its type T4 is adjusted5284// to type "cv1 T4" and the temporary materialization conversion is5285// applied.5286// Postpone address space conversions to after the temporary materialization5287// conversion to allow creating temporaries in the alloca address space.5288auto T1QualsIgnoreAS = T1Quals;5289auto T2QualsIgnoreAS = T2Quals;5290if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {5291T1QualsIgnoreAS.removeAddressSpace();5292T2QualsIgnoreAS.removeAddressSpace();5293}5294QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1QualsIgnoreAS);5295if (T1QualsIgnoreAS != T2QualsIgnoreAS)5296Sequence.AddQualificationConversionStep(cv1T4, ValueKind);5297Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_PRValue);5298ValueKind = isLValueRef ? VK_LValue : VK_XValue;5299// Add addr space conversion if required.5300if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {5301auto T4Quals = cv1T4.getQualifiers();5302T4Quals.addAddressSpace(T1Quals.getAddressSpace());5303QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals);5304Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind);5305cv1T4 = cv1T4WithAS;5306}53075308// In any case, the reference is bound to the resulting glvalue (or to5309// an appropriate base class subobject).5310if (RefConv & Sema::ReferenceConversions::DerivedToBase)5311Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);5312else if (RefConv & Sema::ReferenceConversions::ObjC)5313Sequence.AddObjCObjectConversionStep(cv1T1);5314else if (RefConv & Sema::ReferenceConversions::Qualification) {5315if (!S.Context.hasSameType(cv1T4, cv1T1))5316Sequence.AddQualificationConversionStep(cv1T1, ValueKind);5317}5318return;5319}53205321// - has a class type (i.e., T2 is a class type), where T1 is not5322// reference-related to T2, and can be implicitly converted to an5323// xvalue, class prvalue, or function lvalue of type "cv3 T3",5324// where "cv1 T1" is reference-compatible with "cv3 T3",5325//5326// DR1287 removes the "implicitly" here.5327if (T2->isRecordType()) {5328if (RefRelationship == Sema::Ref_Incompatible) {5329ConvOvlResult = TryRefInitWithConversionFunction(5330S, Entity, Kind, Initializer, /*AllowRValues*/ true,5331/*IsLValueRef*/ isLValueRef, Sequence);5332if (ConvOvlResult)5333Sequence.SetOverloadFailure(5334InitializationSequence::FK_ReferenceInitOverloadFailed,5335ConvOvlResult);53365337return;5338}53395340if (RefRelationship == Sema::Ref_Compatible &&5341isRValueRef && InitCategory.isLValue()) {5342Sequence.SetFailed(5343InitializationSequence::FK_RValueReferenceBindingToLValue);5344return;5345}53465347Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);5348return;5349}53505351// - Otherwise, a temporary of type "cv1 T1" is created and initialized5352// from the initializer expression using the rules for a non-reference5353// copy-initialization (8.5). The reference is then bound to the5354// temporary. [...]53555356// Ignore address space of reference type at this point and perform address5357// space conversion after the reference binding step.5358QualType cv1T1IgnoreAS =5359T1Quals.hasAddressSpace()5360? S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace())5361: cv1T1;53625363InitializedEntity TempEntity =5364InitializedEntity::InitializeTemporary(cv1T1IgnoreAS);53655366// FIXME: Why do we use an implicit conversion here rather than trying5367// copy-initialization?5368ImplicitConversionSequence ICS5369= S.TryImplicitConversion(Initializer, TempEntity.getType(),5370/*SuppressUserConversions=*/false,5371Sema::AllowedExplicit::None,5372/*FIXME:InOverloadResolution=*/false,5373/*CStyle=*/Kind.isCStyleOrFunctionalCast(),5374/*AllowObjCWritebackConversion=*/false);53755376if (ICS.isBad()) {5377// FIXME: Use the conversion function set stored in ICS to turn5378// this into an overloading ambiguity diagnostic. However, we need5379// to keep that set as an OverloadCandidateSet rather than as some5380// other kind of set.5381if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())5382Sequence.SetOverloadFailure(5383InitializationSequence::FK_ReferenceInitOverloadFailed,5384ConvOvlResult);5385else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)5386Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);5387else5388Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);5389return;5390} else {5391Sequence.AddConversionSequenceStep(ICS, TempEntity.getType(),5392TopLevelOfInitList);5393}53945395// [...] If T1 is reference-related to T2, cv1 must be the5396// same cv-qualification as, or greater cv-qualification5397// than, cv2; otherwise, the program is ill-formed.5398unsigned T1CVRQuals = T1Quals.getCVRQualifiers();5399unsigned T2CVRQuals = T2Quals.getCVRQualifiers();5400if (RefRelationship == Sema::Ref_Related &&5401((T1CVRQuals | T2CVRQuals) != T1CVRQuals ||5402!T1Quals.isAddressSpaceSupersetOf(T2Quals))) {5403Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);5404return;5405}54065407// [...] If T1 is reference-related to T2 and the reference is an rvalue5408// reference, the initializer expression shall not be an lvalue.5409if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&5410InitCategory.isLValue()) {5411Sequence.SetFailed(5412InitializationSequence::FK_RValueReferenceBindingToLValue);5413return;5414}54155416Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true);54175418if (T1Quals.hasAddressSpace()) {5419if (!Qualifiers::isAddressSpaceSupersetOf(T1Quals.getAddressSpace(),5420LangAS::Default)) {5421Sequence.SetFailed(5422InitializationSequence::FK_ReferenceAddrspaceMismatchTemporary);5423return;5424}5425Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue5426: VK_XValue);5427}5428}54295430/// Attempt character array initialization from a string literal5431/// (C++ [dcl.init.string], C99 6.7.8).5432static void TryStringLiteralInitialization(Sema &S,5433const InitializedEntity &Entity,5434const InitializationKind &Kind,5435Expr *Initializer,5436InitializationSequence &Sequence) {5437Sequence.AddStringInitStep(Entity.getType());5438}54395440/// Attempt value initialization (C++ [dcl.init]p7).5441static void TryValueInitialization(Sema &S,5442const InitializedEntity &Entity,5443const InitializationKind &Kind,5444InitializationSequence &Sequence,5445InitListExpr *InitList) {5446assert((!InitList || InitList->getNumInits() == 0) &&5447"Shouldn't use value-init for non-empty init lists");54485449// C++98 [dcl.init]p5, C++11 [dcl.init]p7:5450//5451// To value-initialize an object of type T means:5452QualType T = Entity.getType();54535454// -- if T is an array type, then each element is value-initialized;5455T = S.Context.getBaseElementType(T);54565457if (const RecordType *RT = T->getAs<RecordType>()) {5458if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {5459bool NeedZeroInitialization = true;5460// C++98:5461// -- if T is a class type (clause 9) with a user-declared constructor5462// (12.1), then the default constructor for T is called (and the5463// initialization is ill-formed if T has no accessible default5464// constructor);5465// C++11:5466// -- if T is a class type (clause 9) with either no default constructor5467// (12.1 [class.ctor]) or a default constructor that is user-provided5468// or deleted, then the object is default-initialized;5469//5470// Note that the C++11 rule is the same as the C++98 rule if there are no5471// defaulted or deleted constructors, so we just use it unconditionally.5472CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);5473if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())5474NeedZeroInitialization = false;54755476// -- if T is a (possibly cv-qualified) non-union class type without a5477// user-provided or deleted default constructor, then the object is5478// zero-initialized and, if T has a non-trivial default constructor,5479// default-initialized;5480// The 'non-union' here was removed by DR1502. The 'non-trivial default5481// constructor' part was removed by DR1507.5482if (NeedZeroInitialization)5483Sequence.AddZeroInitializationStep(Entity.getType());54845485// C++03:5486// -- if T is a non-union class type without a user-declared constructor,5487// then every non-static data member and base class component of T is5488// value-initialized;5489// [...] A program that calls for [...] value-initialization of an5490// entity of reference type is ill-formed.5491//5492// C++11 doesn't need this handling, because value-initialization does not5493// occur recursively there, and the implicit default constructor is5494// defined as deleted in the problematic cases.5495if (!S.getLangOpts().CPlusPlus11 &&5496ClassDecl->hasUninitializedReferenceMember()) {5497Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);5498return;5499}55005501// If this is list-value-initialization, pass the empty init list on when5502// building the constructor call. This affects the semantics of a few5503// things (such as whether an explicit default constructor can be called).5504Expr *InitListAsExpr = InitList;5505MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);5506bool InitListSyntax = InitList;55075508// FIXME: Instead of creating a CXXConstructExpr of array type here,5509// wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.5510return TryConstructorInitialization(5511S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);5512}5513}55145515Sequence.AddZeroInitializationStep(Entity.getType());5516}55175518/// Attempt default initialization (C++ [dcl.init]p6).5519static void TryDefaultInitialization(Sema &S,5520const InitializedEntity &Entity,5521const InitializationKind &Kind,5522InitializationSequence &Sequence) {5523assert(Kind.getKind() == InitializationKind::IK_Default);55245525// C++ [dcl.init]p6:5526// To default-initialize an object of type T means:5527// - if T is an array type, each element is default-initialized;5528QualType DestType = S.Context.getBaseElementType(Entity.getType());55295530// - if T is a (possibly cv-qualified) class type (Clause 9), the default5531// constructor for T is called (and the initialization is ill-formed if5532// T has no accessible default constructor);5533if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {5534TryConstructorInitialization(S, Entity, Kind, std::nullopt, DestType,5535Entity.getType(), Sequence);5536return;5537}55385539// - otherwise, no initialization is performed.55405541// If a program calls for the default initialization of an object of5542// a const-qualified type T, T shall be a class type with a user-provided5543// default constructor.5544if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {5545if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))5546Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);5547return;5548}55495550// If the destination type has a lifetime property, zero-initialize it.5551if (DestType.getQualifiers().hasObjCLifetime()) {5552Sequence.AddZeroInitializationStep(Entity.getType());5553return;5554}5555}55565557static void TryOrBuildParenListInitialization(5558Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,5559ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly,5560ExprResult *Result = nullptr) {5561unsigned EntityIndexToProcess = 0;5562SmallVector<Expr *, 4> InitExprs;5563QualType ResultType;5564Expr *ArrayFiller = nullptr;5565FieldDecl *InitializedFieldInUnion = nullptr;55665567auto HandleInitializedEntity = [&](const InitializedEntity &SubEntity,5568const InitializationKind &SubKind,5569Expr *Arg, Expr **InitExpr = nullptr) {5570InitializationSequence IS = InitializationSequence(5571S, SubEntity, SubKind, Arg ? MultiExprArg(Arg) : std::nullopt);55725573if (IS.Failed()) {5574if (!VerifyOnly) {5575IS.Diagnose(S, SubEntity, SubKind, Arg ? ArrayRef(Arg) : std::nullopt);5576} else {5577Sequence.SetFailed(5578InitializationSequence::FK_ParenthesizedListInitFailed);5579}55805581return false;5582}5583if (!VerifyOnly) {5584ExprResult ER;5585ER = IS.Perform(S, SubEntity, SubKind,5586Arg ? MultiExprArg(Arg) : std::nullopt);55875588if (ER.isInvalid())5589return false;55905591if (InitExpr)5592*InitExpr = ER.get();5593else5594InitExprs.push_back(ER.get());5595}5596return true;5597};55985599if (const ArrayType *AT =5600S.getASTContext().getAsArrayType(Entity.getType())) {5601SmallVector<InitializedEntity, 4> ElementEntities;5602uint64_t ArrayLength;5603// C++ [dcl.init]p16.55604// if the destination type is an array, the object is initialized as5605// follows. Let x1, . . . , xk be the elements of the expression-list. If5606// the destination type is an array of unknown bound, it is defined as5607// having k elements.5608if (const ConstantArrayType *CAT =5609S.getASTContext().getAsConstantArrayType(Entity.getType())) {5610ArrayLength = CAT->getZExtSize();5611ResultType = Entity.getType();5612} else if (const VariableArrayType *VAT =5613S.getASTContext().getAsVariableArrayType(Entity.getType())) {5614// Braced-initialization of variable array types is not allowed, even if5615// the size is greater than or equal to the number of args, so we don't5616// allow them to be initialized via parenthesized aggregate initialization5617// either.5618const Expr *SE = VAT->getSizeExpr();5619S.Diag(SE->getBeginLoc(), diag::err_variable_object_no_init)5620<< SE->getSourceRange();5621return;5622} else {5623assert(Entity.getType()->isIncompleteArrayType());5624ArrayLength = Args.size();5625}5626EntityIndexToProcess = ArrayLength;56275628// ...the ith array element is copy-initialized with xi for each5629// 1 <= i <= k5630for (Expr *E : Args) {5631InitializedEntity SubEntity = InitializedEntity::InitializeElement(5632S.getASTContext(), EntityIndexToProcess, Entity);5633InitializationKind SubKind = InitializationKind::CreateForInit(5634E->getExprLoc(), /*isDirectInit=*/false, E);5635if (!HandleInitializedEntity(SubEntity, SubKind, E))5636return;5637}5638// ...and value-initialized for each k < i <= n;5639if (ArrayLength > Args.size() || Entity.isVariableLengthArrayNew()) {5640InitializedEntity SubEntity = InitializedEntity::InitializeElement(5641S.getASTContext(), Args.size(), Entity);5642InitializationKind SubKind = InitializationKind::CreateValue(5643Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);5644if (!HandleInitializedEntity(SubEntity, SubKind, nullptr, &ArrayFiller))5645return;5646}56475648if (ResultType.isNull()) {5649ResultType = S.Context.getConstantArrayType(5650AT->getElementType(), llvm::APInt(/*numBits=*/32, ArrayLength),5651/*SizeExpr=*/nullptr, ArraySizeModifier::Normal, 0);5652}5653} else if (auto *RT = Entity.getType()->getAs<RecordType>()) {5654bool IsUnion = RT->isUnionType();5655const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());5656if (RD->isInvalidDecl()) {5657// Exit early to avoid confusion when processing members.5658// We do the same for braced list initialization in5659// `CheckStructUnionTypes`.5660Sequence.SetFailed(5661clang::InitializationSequence::FK_ParenthesizedListInitFailed);5662return;5663}56645665if (!IsUnion) {5666for (const CXXBaseSpecifier &Base : RD->bases()) {5667InitializedEntity SubEntity = InitializedEntity::InitializeBase(5668S.getASTContext(), &Base, false, &Entity);5669if (EntityIndexToProcess < Args.size()) {5670// C++ [dcl.init]p16.6.2.2.5671// ...the object is initialized is follows. Let e1, ..., en be the5672// elements of the aggregate([dcl.init.aggr]). Let x1, ..., xk be5673// the elements of the expression-list...The element ei is5674// copy-initialized with xi for 1 <= i <= k.5675Expr *E = Args[EntityIndexToProcess];5676InitializationKind SubKind = InitializationKind::CreateForInit(5677E->getExprLoc(), /*isDirectInit=*/false, E);5678if (!HandleInitializedEntity(SubEntity, SubKind, E))5679return;5680} else {5681// We've processed all of the args, but there are still base classes5682// that have to be initialized.5683// C++ [dcl.init]p17.6.2.25684// The remaining elements...otherwise are value initialzed5685InitializationKind SubKind = InitializationKind::CreateValue(5686Kind.getLocation(), Kind.getLocation(), Kind.getLocation(),5687/*IsImplicit=*/true);5688if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))5689return;5690}5691EntityIndexToProcess++;5692}5693}56945695for (FieldDecl *FD : RD->fields()) {5696// Unnamed bitfields should not be initialized at all, either with an arg5697// or by default.5698if (FD->isUnnamedBitField())5699continue;57005701InitializedEntity SubEntity =5702InitializedEntity::InitializeMemberFromParenAggInit(FD);57035704if (EntityIndexToProcess < Args.size()) {5705// ...The element ei is copy-initialized with xi for 1 <= i <= k.5706Expr *E = Args[EntityIndexToProcess];57075708// Incomplete array types indicate flexible array members. Do not allow5709// paren list initializations of structs with these members, as GCC5710// doesn't either.5711if (FD->getType()->isIncompleteArrayType()) {5712if (!VerifyOnly) {5713S.Diag(E->getBeginLoc(), diag::err_flexible_array_init)5714<< SourceRange(E->getBeginLoc(), E->getEndLoc());5715S.Diag(FD->getLocation(), diag::note_flexible_array_member) << FD;5716}5717Sequence.SetFailed(5718InitializationSequence::FK_ParenthesizedListInitFailed);5719return;5720}57215722InitializationKind SubKind = InitializationKind::CreateForInit(5723E->getExprLoc(), /*isDirectInit=*/false, E);5724if (!HandleInitializedEntity(SubEntity, SubKind, E))5725return;57265727// Unions should have only one initializer expression, so we bail out5728// after processing the first field. If there are more initializers then5729// it will be caught when we later check whether EntityIndexToProcess is5730// less than Args.size();5731if (IsUnion) {5732InitializedFieldInUnion = FD;5733EntityIndexToProcess = 1;5734break;5735}5736} else {5737// We've processed all of the args, but there are still members that5738// have to be initialized.5739if (FD->hasInClassInitializer()) {5740if (!VerifyOnly) {5741// C++ [dcl.init]p16.6.2.25742// The remaining elements are initialized with their default5743// member initializers, if any5744ExprResult DIE = S.BuildCXXDefaultInitExpr(5745Kind.getParenOrBraceRange().getEnd(), FD);5746if (DIE.isInvalid())5747return;5748S.checkInitializerLifetime(SubEntity, DIE.get());5749InitExprs.push_back(DIE.get());5750}5751} else {5752// C++ [dcl.init]p17.6.2.25753// The remaining elements...otherwise are value initialzed5754if (FD->getType()->isReferenceType()) {5755Sequence.SetFailed(5756InitializationSequence::FK_ParenthesizedListInitFailed);5757if (!VerifyOnly) {5758SourceRange SR = Kind.getParenOrBraceRange();5759S.Diag(SR.getEnd(), diag::err_init_reference_member_uninitialized)5760<< FD->getType() << SR;5761S.Diag(FD->getLocation(), diag::note_uninit_reference_member);5762}5763return;5764}5765InitializationKind SubKind = InitializationKind::CreateValue(5766Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);5767if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))5768return;5769}5770}5771EntityIndexToProcess++;5772}5773ResultType = Entity.getType();5774}57755776// Not all of the args have been processed, so there must've been more args5777// than were required to initialize the element.5778if (EntityIndexToProcess < Args.size()) {5779Sequence.SetFailed(InitializationSequence::FK_ParenthesizedListInitFailed);5780if (!VerifyOnly) {5781QualType T = Entity.getType();5782int InitKind = T->isArrayType() ? 0 : T->isUnionType() ? 3 : 4;5783SourceRange ExcessInitSR(Args[EntityIndexToProcess]->getBeginLoc(),5784Args.back()->getEndLoc());5785S.Diag(Kind.getLocation(), diag::err_excess_initializers)5786<< InitKind << ExcessInitSR;5787}5788return;5789}57905791if (VerifyOnly) {5792Sequence.setSequenceKind(InitializationSequence::NormalSequence);5793Sequence.AddParenthesizedListInitStep(Entity.getType());5794} else if (Result) {5795SourceRange SR = Kind.getParenOrBraceRange();5796auto *CPLIE = CXXParenListInitExpr::Create(5797S.getASTContext(), InitExprs, ResultType, Args.size(),5798Kind.getLocation(), SR.getBegin(), SR.getEnd());5799if (ArrayFiller)5800CPLIE->setArrayFiller(ArrayFiller);5801if (InitializedFieldInUnion)5802CPLIE->setInitializedFieldInUnion(InitializedFieldInUnion);5803*Result = CPLIE;5804S.Diag(Kind.getLocation(),5805diag::warn_cxx17_compat_aggregate_init_paren_list)5806<< Kind.getLocation() << SR << ResultType;5807}5808}58095810/// Attempt a user-defined conversion between two types (C++ [dcl.init]),5811/// which enumerates all conversion functions and performs overload resolution5812/// to select the best.5813static void TryUserDefinedConversion(Sema &S,5814QualType DestType,5815const InitializationKind &Kind,5816Expr *Initializer,5817InitializationSequence &Sequence,5818bool TopLevelOfInitList) {5819assert(!DestType->isReferenceType() && "References are handled elsewhere");5820QualType SourceType = Initializer->getType();5821assert((DestType->isRecordType() || SourceType->isRecordType()) &&5822"Must have a class type to perform a user-defined conversion");58235824// Build the candidate set directly in the initialization sequence5825// structure, so that it will persist if we fail.5826OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();5827CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);5828CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());58295830// Determine whether we are allowed to call explicit constructors or5831// explicit conversion operators.5832bool AllowExplicit = Kind.AllowExplicit();58335834if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {5835// The type we're converting to is a class type. Enumerate its constructors5836// to see if there is a suitable conversion.5837CXXRecordDecl *DestRecordDecl5838= cast<CXXRecordDecl>(DestRecordType->getDecl());58395840// Try to complete the type we're converting to.5841if (S.isCompleteType(Kind.getLocation(), DestType)) {5842for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {5843auto Info = getConstructorInfo(D);5844if (!Info.Constructor)5845continue;58465847if (!Info.Constructor->isInvalidDecl() &&5848Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {5849if (Info.ConstructorTmpl)5850S.AddTemplateOverloadCandidate(5851Info.ConstructorTmpl, Info.FoundDecl,5852/*ExplicitArgs*/ nullptr, Initializer, CandidateSet,5853/*SuppressUserConversions=*/true,5854/*PartialOverloading*/ false, AllowExplicit);5855else5856S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,5857Initializer, CandidateSet,5858/*SuppressUserConversions=*/true,5859/*PartialOverloading*/ false, AllowExplicit);5860}5861}5862}5863}58645865SourceLocation DeclLoc = Initializer->getBeginLoc();58665867if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {5868// The type we're converting from is a class type, enumerate its conversion5869// functions.58705871// We can only enumerate the conversion functions for a complete type; if5872// the type isn't complete, simply skip this step.5873if (S.isCompleteType(DeclLoc, SourceType)) {5874CXXRecordDecl *SourceRecordDecl5875= cast<CXXRecordDecl>(SourceRecordType->getDecl());58765877const auto &Conversions =5878SourceRecordDecl->getVisibleConversionFunctions();5879for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {5880NamedDecl *D = *I;5881CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());5882if (isa<UsingShadowDecl>(D))5883D = cast<UsingShadowDecl>(D)->getTargetDecl();58845885FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);5886CXXConversionDecl *Conv;5887if (ConvTemplate)5888Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());5889else5890Conv = cast<CXXConversionDecl>(D);58915892if (ConvTemplate)5893S.AddTemplateConversionCandidate(5894ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,5895CandidateSet, AllowExplicit, AllowExplicit);5896else5897S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,5898DestType, CandidateSet, AllowExplicit,5899AllowExplicit);5900}5901}5902}59035904// Perform overload resolution. If it fails, return the failed result.5905OverloadCandidateSet::iterator Best;5906if (OverloadingResult Result5907= CandidateSet.BestViableFunction(S, DeclLoc, Best)) {5908Sequence.SetOverloadFailure(5909InitializationSequence::FK_UserConversionOverloadFailed, Result);59105911// [class.copy.elision]p3:5912// In some copy-initialization contexts, a two-stage overload resolution5913// is performed.5914// If the first overload resolution selects a deleted function, we also5915// need the initialization sequence to decide whether to perform the second5916// overload resolution.5917if (!(Result == OR_Deleted &&5918Kind.getKind() == InitializationKind::IK_Copy))5919return;5920}59215922FunctionDecl *Function = Best->Function;5923Function->setReferenced();5924bool HadMultipleCandidates = (CandidateSet.size() > 1);59255926if (isa<CXXConstructorDecl>(Function)) {5927// Add the user-defined conversion step. Any cv-qualification conversion is5928// subsumed by the initialization. Per DR5, the created temporary is of the5929// cv-unqualified type of the destination.5930Sequence.AddUserConversionStep(Function, Best->FoundDecl,5931DestType.getUnqualifiedType(),5932HadMultipleCandidates);59335934// C++14 and before:5935// - if the function is a constructor, the call initializes a temporary5936// of the cv-unqualified version of the destination type. The [...]5937// temporary [...] is then used to direct-initialize, according to the5938// rules above, the object that is the destination of the5939// copy-initialization.5940// Note that this just performs a simple object copy from the temporary.5941//5942// C++17:5943// - if the function is a constructor, the call is a prvalue of the5944// cv-unqualified version of the destination type whose return object5945// is initialized by the constructor. The call is used to5946// direct-initialize, according to the rules above, the object that5947// is the destination of the copy-initialization.5948// Therefore we need to do nothing further.5949//5950// FIXME: Mark this copy as extraneous.5951if (!S.getLangOpts().CPlusPlus17)5952Sequence.AddFinalCopy(DestType);5953else if (DestType.hasQualifiers())5954Sequence.AddQualificationConversionStep(DestType, VK_PRValue);5955return;5956}59575958// Add the user-defined conversion step that calls the conversion function.5959QualType ConvType = Function->getCallResultType();5960Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,5961HadMultipleCandidates);59625963if (ConvType->getAs<RecordType>()) {5964// The call is used to direct-initialize [...] the object that is the5965// destination of the copy-initialization.5966//5967// In C++17, this does not call a constructor if we enter /17.6.1:5968// - If the initializer expression is a prvalue and the cv-unqualified5969// version of the source type is the same as the class of the5970// destination [... do not make an extra copy]5971//5972// FIXME: Mark this copy as extraneous.5973if (!S.getLangOpts().CPlusPlus17 ||5974Function->getReturnType()->isReferenceType() ||5975!S.Context.hasSameUnqualifiedType(ConvType, DestType))5976Sequence.AddFinalCopy(DestType);5977else if (!S.Context.hasSameType(ConvType, DestType))5978Sequence.AddQualificationConversionStep(DestType, VK_PRValue);5979return;5980}59815982// If the conversion following the call to the conversion function5983// is interesting, add it as a separate step.5984if (Best->FinalConversion.First || Best->FinalConversion.Second ||5985Best->FinalConversion.Third) {5986ImplicitConversionSequence ICS;5987ICS.setStandard();5988ICS.Standard = Best->FinalConversion;5989Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);5990}5991}59925993/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,5994/// a function with a pointer return type contains a 'return false;' statement.5995/// In C++11, 'false' is not a null pointer, so this breaks the build of any5996/// code using that header.5997///5998/// Work around this by treating 'return false;' as zero-initializing the result5999/// if it's used in a pointer-returning function in a system header.6000static bool isLibstdcxxPointerReturnFalseHack(Sema &S,6001const InitializedEntity &Entity,6002const Expr *Init) {6003return S.getLangOpts().CPlusPlus11 &&6004Entity.getKind() == InitializedEntity::EK_Result &&6005Entity.getType()->isPointerType() &&6006isa<CXXBoolLiteralExpr>(Init) &&6007!cast<CXXBoolLiteralExpr>(Init)->getValue() &&6008S.getSourceManager().isInSystemHeader(Init->getExprLoc());6009}60106011/// The non-zero enum values here are indexes into diagnostic alternatives.6012enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };60136014/// Determines whether this expression is an acceptable ICR source.6015static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,6016bool isAddressOf, bool &isWeakAccess) {6017// Skip parens.6018e = e->IgnoreParens();60196020// Skip address-of nodes.6021if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {6022if (op->getOpcode() == UO_AddrOf)6023return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,6024isWeakAccess);60256026// Skip certain casts.6027} else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {6028switch (ce->getCastKind()) {6029case CK_Dependent:6030case CK_BitCast:6031case CK_LValueBitCast:6032case CK_NoOp:6033return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);60346035case CK_ArrayToPointerDecay:6036return IIK_nonscalar;60376038case CK_NullToPointer:6039return IIK_okay;60406041default:6042break;6043}60446045// If we have a declaration reference, it had better be a local variable.6046} else if (isa<DeclRefExpr>(e)) {6047// set isWeakAccess to true, to mean that there will be an implicit6048// load which requires a cleanup.6049if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)6050isWeakAccess = true;60516052if (!isAddressOf) return IIK_nonlocal;60536054VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());6055if (!var) return IIK_nonlocal;60566057return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);60586059// If we have a conditional operator, check both sides.6060} else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {6061if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,6062isWeakAccess))6063return iik;60646065return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);60666067// These are never scalar.6068} else if (isa<ArraySubscriptExpr>(e)) {6069return IIK_nonscalar;60706071// Otherwise, it needs to be a null pointer constant.6072} else {6073return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)6074? IIK_okay : IIK_nonlocal);6075}60766077return IIK_nonlocal;6078}60796080/// Check whether the given expression is a valid operand for an6081/// indirect copy/restore.6082static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {6083assert(src->isPRValue());6084bool isWeakAccess = false;6085InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);6086// If isWeakAccess to true, there will be an implicit6087// load which requires a cleanup.6088if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)6089S.Cleanup.setExprNeedsCleanups(true);60906091if (iik == IIK_okay) return;60926093S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)6094<< ((unsigned) iik - 1) // shift index into diagnostic explanations6095<< src->getSourceRange();6096}60976098/// Determine whether we have compatible array types for the6099/// purposes of GNU by-copy array initialization.6100static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,6101const ArrayType *Source) {6102// If the source and destination array types are equivalent, we're6103// done.6104if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))6105return true;61066107// Make sure that the element types are the same.6108if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))6109return false;61106111// The only mismatch we allow is when the destination is an6112// incomplete array type and the source is a constant array type.6113return Source->isConstantArrayType() && Dest->isIncompleteArrayType();6114}61156116static bool tryObjCWritebackConversion(Sema &S,6117InitializationSequence &Sequence,6118const InitializedEntity &Entity,6119Expr *Initializer) {6120bool ArrayDecay = false;6121QualType ArgType = Initializer->getType();6122QualType ArgPointee;6123if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {6124ArrayDecay = true;6125ArgPointee = ArgArrayType->getElementType();6126ArgType = S.Context.getPointerType(ArgPointee);6127}61286129// Handle write-back conversion.6130QualType ConvertedArgType;6131if (!S.ObjC().isObjCWritebackConversion(ArgType, Entity.getType(),6132ConvertedArgType))6133return false;61346135// We should copy unless we're passing to an argument explicitly6136// marked 'out'.6137bool ShouldCopy = true;6138if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))6139ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);61406141// Do we need an lvalue conversion?6142if (ArrayDecay || Initializer->isGLValue()) {6143ImplicitConversionSequence ICS;6144ICS.setStandard();6145ICS.Standard.setAsIdentityConversion();61466147QualType ResultType;6148if (ArrayDecay) {6149ICS.Standard.First = ICK_Array_To_Pointer;6150ResultType = S.Context.getPointerType(ArgPointee);6151} else {6152ICS.Standard.First = ICK_Lvalue_To_Rvalue;6153ResultType = Initializer->getType().getNonLValueExprType(S.Context);6154}61556156Sequence.AddConversionSequenceStep(ICS, ResultType);6157}61586159Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);6160return true;6161}61626163static bool TryOCLSamplerInitialization(Sema &S,6164InitializationSequence &Sequence,6165QualType DestType,6166Expr *Initializer) {6167if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||6168(!Initializer->isIntegerConstantExpr(S.Context) &&6169!Initializer->getType()->isSamplerT()))6170return false;61716172Sequence.AddOCLSamplerInitStep(DestType);6173return true;6174}61756176static bool IsZeroInitializer(Expr *Initializer, Sema &S) {6177return Initializer->isIntegerConstantExpr(S.getASTContext()) &&6178(Initializer->EvaluateKnownConstInt(S.getASTContext()) == 0);6179}61806181static bool TryOCLZeroOpaqueTypeInitialization(Sema &S,6182InitializationSequence &Sequence,6183QualType DestType,6184Expr *Initializer) {6185if (!S.getLangOpts().OpenCL)6186return false;61876188//6189// OpenCL 1.2 spec, s6.12.106190//6191// The event argument can also be used to associate the6192// async_work_group_copy with a previous async copy allowing6193// an event to be shared by multiple async copies; otherwise6194// event should be zero.6195//6196if (DestType->isEventT() || DestType->isQueueT()) {6197if (!IsZeroInitializer(Initializer, S))6198return false;61996200Sequence.AddOCLZeroOpaqueTypeStep(DestType);6201return true;6202}62036204// We should allow zero initialization for all types defined in the6205// cl_intel_device_side_avc_motion_estimation extension, except6206// intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t.6207if (S.getOpenCLOptions().isAvailableOption(6208"cl_intel_device_side_avc_motion_estimation", S.getLangOpts()) &&6209DestType->isOCLIntelSubgroupAVCType()) {6210if (DestType->isOCLIntelSubgroupAVCMcePayloadType() ||6211DestType->isOCLIntelSubgroupAVCMceResultType())6212return false;6213if (!IsZeroInitializer(Initializer, S))6214return false;62156216Sequence.AddOCLZeroOpaqueTypeStep(DestType);6217return true;6218}62196220return false;6221}62226223InitializationSequence::InitializationSequence(6224Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,6225MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid)6226: FailedOverloadResult(OR_Success),6227FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {6228InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,6229TreatUnavailableAsInvalid);6230}62316232/// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the6233/// address of that function, this returns true. Otherwise, it returns false.6234static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {6235auto *DRE = dyn_cast<DeclRefExpr>(E);6236if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))6237return false;62386239return !S.checkAddressOfFunctionIsAvailable(6240cast<FunctionDecl>(DRE->getDecl()));6241}62426243/// Determine whether we can perform an elementwise array copy for this kind6244/// of entity.6245static bool canPerformArrayCopy(const InitializedEntity &Entity) {6246switch (Entity.getKind()) {6247case InitializedEntity::EK_LambdaCapture:6248// C++ [expr.prim.lambda]p24:6249// For array members, the array elements are direct-initialized in6250// increasing subscript order.6251return true;62526253case InitializedEntity::EK_Variable:6254// C++ [dcl.decomp]p1:6255// [...] each element is copy-initialized or direct-initialized from the6256// corresponding element of the assignment-expression [...]6257return isa<DecompositionDecl>(Entity.getDecl());62586259case InitializedEntity::EK_Member:6260// C++ [class.copy.ctor]p14:6261// - if the member is an array, each element is direct-initialized with6262// the corresponding subobject of x6263return Entity.isImplicitMemberInitializer();62646265case InitializedEntity::EK_ArrayElement:6266// All the above cases are intended to apply recursively, even though none6267// of them actually say that.6268if (auto *E = Entity.getParent())6269return canPerformArrayCopy(*E);6270break;62716272default:6273break;6274}62756276return false;6277}62786279void InitializationSequence::InitializeFrom(Sema &S,6280const InitializedEntity &Entity,6281const InitializationKind &Kind,6282MultiExprArg Args,6283bool TopLevelOfInitList,6284bool TreatUnavailableAsInvalid) {6285ASTContext &Context = S.Context;62866287// Eliminate non-overload placeholder types in the arguments. We6288// need to do this before checking whether types are dependent6289// because lowering a pseudo-object expression might well give us6290// something of dependent type.6291for (unsigned I = 0, E = Args.size(); I != E; ++I)6292if (Args[I]->getType()->isNonOverloadPlaceholderType()) {6293// FIXME: should we be doing this here?6294ExprResult result = S.CheckPlaceholderExpr(Args[I]);6295if (result.isInvalid()) {6296SetFailed(FK_PlaceholderType);6297return;6298}6299Args[I] = result.get();6300}63016302// C++0x [dcl.init]p16:6303// The semantics of initializers are as follows. The destination type is6304// the type of the object or reference being initialized and the source6305// type is the type of the initializer expression. The source type is not6306// defined when the initializer is a braced-init-list or when it is a6307// parenthesized list of expressions.6308QualType DestType = Entity.getType();63096310if (DestType->isDependentType() ||6311Expr::hasAnyTypeDependentArguments(Args)) {6312SequenceKind = DependentSequence;6313return;6314}63156316// Almost everything is a normal sequence.6317setSequenceKind(NormalSequence);63186319QualType SourceType;6320Expr *Initializer = nullptr;6321if (Args.size() == 1) {6322Initializer = Args[0];6323if (S.getLangOpts().ObjC) {6324if (S.ObjC().CheckObjCBridgeRelatedConversions(6325Initializer->getBeginLoc(), DestType, Initializer->getType(),6326Initializer) ||6327S.ObjC().CheckConversionToObjCLiteral(DestType, Initializer))6328Args[0] = Initializer;6329}6330if (!isa<InitListExpr>(Initializer))6331SourceType = Initializer->getType();6332}63336334// - If the initializer is a (non-parenthesized) braced-init-list, the6335// object is list-initialized (8.5.4).6336if (Kind.getKind() != InitializationKind::IK_Direct) {6337if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {6338TryListInitialization(S, Entity, Kind, InitList, *this,6339TreatUnavailableAsInvalid);6340return;6341}6342}63436344// - If the destination type is a reference type, see 8.5.3.6345if (DestType->isReferenceType()) {6346// C++0x [dcl.init.ref]p1:6347// A variable declared to be a T& or T&&, that is, "reference to type T"6348// (8.3.2), shall be initialized by an object, or function, of type T or6349// by an object that can be converted into a T.6350// (Therefore, multiple arguments are not permitted.)6351if (Args.size() != 1)6352SetFailed(FK_TooManyInitsForReference);6353// C++17 [dcl.init.ref]p5:6354// A reference [...] is initialized by an expression [...] as follows:6355// If the initializer is not an expression, presumably we should reject,6356// but the standard fails to actually say so.6357else if (isa<InitListExpr>(Args[0]))6358SetFailed(FK_ParenthesizedListInitForReference);6359else6360TryReferenceInitialization(S, Entity, Kind, Args[0], *this,6361TopLevelOfInitList);6362return;6363}63646365// - If the initializer is (), the object is value-initialized.6366if (Kind.getKind() == InitializationKind::IK_Value ||6367(Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {6368TryValueInitialization(S, Entity, Kind, *this);6369return;6370}63716372// Handle default initialization.6373if (Kind.getKind() == InitializationKind::IK_Default) {6374TryDefaultInitialization(S, Entity, Kind, *this);6375return;6376}63776378// - If the destination type is an array of characters, an array of6379// char16_t, an array of char32_t, or an array of wchar_t, and the6380// initializer is a string literal, see 8.5.2.6381// - Otherwise, if the destination type is an array, the program is6382// ill-formed.6383// - Except in HLSL, where non-decaying array parameters behave like6384// non-array types for initialization.6385if (DestType->isArrayType() && !DestType->isArrayParameterType()) {6386const ArrayType *DestAT = Context.getAsArrayType(DestType);6387if (Initializer && isa<VariableArrayType>(DestAT)) {6388SetFailed(FK_VariableLengthArrayHasInitializer);6389return;6390}63916392if (Initializer) {6393switch (IsStringInit(Initializer, DestAT, Context)) {6394case SIF_None:6395TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);6396return;6397case SIF_NarrowStringIntoWideChar:6398SetFailed(FK_NarrowStringIntoWideCharArray);6399return;6400case SIF_WideStringIntoChar:6401SetFailed(FK_WideStringIntoCharArray);6402return;6403case SIF_IncompatWideStringIntoWideChar:6404SetFailed(FK_IncompatWideStringIntoWideChar);6405return;6406case SIF_PlainStringIntoUTF8Char:6407SetFailed(FK_PlainStringIntoUTF8Char);6408return;6409case SIF_UTF8StringIntoPlainChar:6410SetFailed(FK_UTF8StringIntoPlainChar);6411return;6412case SIF_Other:6413break;6414}6415}64166417// Some kinds of initialization permit an array to be initialized from6418// another array of the same type, and perform elementwise initialization.6419if (Initializer && isa<ConstantArrayType>(DestAT) &&6420S.Context.hasSameUnqualifiedType(Initializer->getType(),6421Entity.getType()) &&6422canPerformArrayCopy(Entity)) {6423// If source is a prvalue, use it directly.6424if (Initializer->isPRValue()) {6425AddArrayInitStep(DestType, /*IsGNUExtension*/false);6426return;6427}64286429// Emit element-at-a-time copy loop.6430InitializedEntity Element =6431InitializedEntity::InitializeElement(S.Context, 0, Entity);6432QualType InitEltT =6433Context.getAsArrayType(Initializer->getType())->getElementType();6434OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,6435Initializer->getValueKind(),6436Initializer->getObjectKind());6437Expr *OVEAsExpr = &OVE;6438InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList,6439TreatUnavailableAsInvalid);6440if (!Failed())6441AddArrayInitLoopStep(Entity.getType(), InitEltT);6442return;6443}64446445// Note: as an GNU C extension, we allow initialization of an6446// array from a compound literal that creates an array of the same6447// type, so long as the initializer has no side effects.6448if (!S.getLangOpts().CPlusPlus && Initializer &&6449isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&6450Initializer->getType()->isArrayType()) {6451const ArrayType *SourceAT6452= Context.getAsArrayType(Initializer->getType());6453if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))6454SetFailed(FK_ArrayTypeMismatch);6455else if (Initializer->HasSideEffects(S.Context))6456SetFailed(FK_NonConstantArrayInit);6457else {6458AddArrayInitStep(DestType, /*IsGNUExtension*/true);6459}6460}6461// Note: as a GNU C++ extension, we allow list-initialization of a6462// class member of array type from a parenthesized initializer list.6463else if (S.getLangOpts().CPlusPlus &&6464Entity.getKind() == InitializedEntity::EK_Member &&6465isa_and_nonnull<InitListExpr>(Initializer)) {6466TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),6467*this, TreatUnavailableAsInvalid);6468AddParenthesizedArrayInitStep(DestType);6469} else if (S.getLangOpts().CPlusPlus20 && !TopLevelOfInitList &&6470Kind.getKind() == InitializationKind::IK_Direct)6471TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,6472/*VerifyOnly=*/true);6473else if (DestAT->getElementType()->isCharType())6474SetFailed(FK_ArrayNeedsInitListOrStringLiteral);6475else if (IsWideCharCompatible(DestAT->getElementType(), Context))6476SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);6477else6478SetFailed(FK_ArrayNeedsInitList);64796480return;6481}64826483// Determine whether we should consider writeback conversions for6484// Objective-C ARC.6485bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&6486Entity.isParameterKind();64876488if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))6489return;64906491// We're at the end of the line for C: it's either a write-back conversion6492// or it's a C assignment. There's no need to check anything else.6493if (!S.getLangOpts().CPlusPlus) {6494assert(Initializer && "Initializer must be non-null");6495// If allowed, check whether this is an Objective-C writeback conversion.6496if (allowObjCWritebackConversion &&6497tryObjCWritebackConversion(S, *this, Entity, Initializer)) {6498return;6499}65006501if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer))6502return;65036504// Handle initialization in C6505AddCAssignmentStep(DestType);6506MaybeProduceObjCObject(S, *this, Entity);6507return;6508}65096510assert(S.getLangOpts().CPlusPlus);65116512// - If the destination type is a (possibly cv-qualified) class type:6513if (DestType->isRecordType()) {6514// - If the initialization is direct-initialization, or if it is6515// copy-initialization where the cv-unqualified version of the6516// source type is the same class as, or a derived class of, the6517// class of the destination, constructors are considered. [...]6518if (Kind.getKind() == InitializationKind::IK_Direct ||6519(Kind.getKind() == InitializationKind::IK_Copy &&6520(Context.hasSameUnqualifiedType(SourceType, DestType) ||6521(Initializer && S.IsDerivedFrom(Initializer->getBeginLoc(),6522SourceType, DestType))))) {6523TryConstructorInitialization(S, Entity, Kind, Args, DestType, DestType,6524*this);65256526// We fall back to the "no matching constructor" path if the6527// failed candidate set has functions other than the three default6528// constructors. For example, conversion function.6529if (const auto *RD =6530dyn_cast<CXXRecordDecl>(DestType->getAs<RecordType>()->getDecl());6531// In general, we should call isCompleteType for RD to check its6532// completeness, we don't call it here as it was already called in the6533// above TryConstructorInitialization.6534S.getLangOpts().CPlusPlus20 && RD && RD->hasDefinition() &&6535RD->isAggregate() && Failed() &&6536getFailureKind() == FK_ConstructorOverloadFailed) {6537// Do not attempt paren list initialization if overload resolution6538// resolves to a deleted function .6539//6540// We may reach this condition if we have a union wrapping a class with6541// a non-trivial copy or move constructor and we call one of those two6542// constructors. The union is an aggregate, but the matched constructor6543// is implicitly deleted, so we need to prevent aggregate initialization6544// (otherwise, it'll attempt aggregate initialization by initializing6545// the first element with a reference to the union).6546OverloadCandidateSet::iterator Best;6547OverloadingResult OR = getFailedCandidateSet().BestViableFunction(6548S, Kind.getLocation(), Best);6549if (OR != OverloadingResult::OR_Deleted) {6550// C++20 [dcl.init] 17.6.2.2:6551// - Otherwise, if no constructor is viable, the destination type is6552// an6553// aggregate class, and the initializer is a parenthesized6554// expression-list.6555TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,6556/*VerifyOnly=*/true);6557}6558}6559} else {6560// - Otherwise (i.e., for the remaining copy-initialization cases),6561// user-defined conversion sequences that can convert from the6562// source type to the destination type or (when a conversion6563// function is used) to a derived class thereof are enumerated as6564// described in 13.3.1.4, and the best one is chosen through6565// overload resolution (13.3).6566assert(Initializer && "Initializer must be non-null");6567TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,6568TopLevelOfInitList);6569}6570return;6571}65726573assert(Args.size() >= 1 && "Zero-argument case handled above");65746575// For HLSL ext vector types we allow list initialization behavior for C++6576// constructor syntax. This is accomplished by converting initialization6577// arguments an InitListExpr late.6578if (S.getLangOpts().HLSL && Args.size() > 1 && DestType->isExtVectorType() &&6579(SourceType.isNull() ||6580!Context.hasSameUnqualifiedType(SourceType, DestType))) {65816582llvm::SmallVector<Expr *> InitArgs;6583for (auto *Arg : Args) {6584if (Arg->getType()->isExtVectorType()) {6585const auto *VTy = Arg->getType()->castAs<ExtVectorType>();6586unsigned Elm = VTy->getNumElements();6587for (unsigned Idx = 0; Idx < Elm; ++Idx) {6588InitArgs.emplace_back(new (Context) ArraySubscriptExpr(6589Arg,6590IntegerLiteral::Create(6591Context, llvm::APInt(Context.getIntWidth(Context.IntTy), Idx),6592Context.IntTy, SourceLocation()),6593VTy->getElementType(), Arg->getValueKind(), Arg->getObjectKind(),6594SourceLocation()));6595}6596} else6597InitArgs.emplace_back(Arg);6598}6599InitListExpr *ILE = new (Context) InitListExpr(6600S.getASTContext(), SourceLocation(), InitArgs, SourceLocation());6601Args[0] = ILE;6602AddListInitializationStep(DestType);6603return;6604}66056606// The remaining cases all need a source type.6607if (Args.size() > 1) {6608SetFailed(FK_TooManyInitsForScalar);6609return;6610} else if (isa<InitListExpr>(Args[0])) {6611SetFailed(FK_ParenthesizedListInitForScalar);6612return;6613}66146615// - Otherwise, if the source type is a (possibly cv-qualified) class6616// type, conversion functions are considered.6617if (!SourceType.isNull() && SourceType->isRecordType()) {6618assert(Initializer && "Initializer must be non-null");6619// For a conversion to _Atomic(T) from either T or a class type derived6620// from T, initialize the T object then convert to _Atomic type.6621bool NeedAtomicConversion = false;6622if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {6623if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||6624S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType,6625Atomic->getValueType())) {6626DestType = Atomic->getValueType();6627NeedAtomicConversion = true;6628}6629}66306631TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,6632TopLevelOfInitList);6633MaybeProduceObjCObject(S, *this, Entity);6634if (!Failed() && NeedAtomicConversion)6635AddAtomicConversionStep(Entity.getType());6636return;6637}66386639// - Otherwise, if the initialization is direct-initialization, the source6640// type is std::nullptr_t, and the destination type is bool, the initial6641// value of the object being initialized is false.6642if (!SourceType.isNull() && SourceType->isNullPtrType() &&6643DestType->isBooleanType() &&6644Kind.getKind() == InitializationKind::IK_Direct) {6645AddConversionSequenceStep(6646ImplicitConversionSequence::getNullptrToBool(SourceType, DestType,6647Initializer->isGLValue()),6648DestType);6649return;6650}66516652// - Otherwise, the initial value of the object being initialized is the6653// (possibly converted) value of the initializer expression. Standard6654// conversions (Clause 4) will be used, if necessary, to convert the6655// initializer expression to the cv-unqualified version of the6656// destination type; no user-defined conversions are considered.66576658ImplicitConversionSequence ICS6659= S.TryImplicitConversion(Initializer, DestType,6660/*SuppressUserConversions*/true,6661Sema::AllowedExplicit::None,6662/*InOverloadResolution*/ false,6663/*CStyle=*/Kind.isCStyleOrFunctionalCast(),6664allowObjCWritebackConversion);66656666if (ICS.isStandard() &&6667ICS.Standard.Second == ICK_Writeback_Conversion) {6668// Objective-C ARC writeback conversion.66696670// We should copy unless we're passing to an argument explicitly6671// marked 'out'.6672bool ShouldCopy = true;6673if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))6674ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);66756676// If there was an lvalue adjustment, add it as a separate conversion.6677if (ICS.Standard.First == ICK_Array_To_Pointer ||6678ICS.Standard.First == ICK_Lvalue_To_Rvalue) {6679ImplicitConversionSequence LvalueICS;6680LvalueICS.setStandard();6681LvalueICS.Standard.setAsIdentityConversion();6682LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));6683LvalueICS.Standard.First = ICS.Standard.First;6684AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));6685}66866687AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);6688} else if (ICS.isBad()) {6689if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer))6690AddZeroInitializationStep(Entity.getType());6691else if (DeclAccessPair Found;6692Initializer->getType() == Context.OverloadTy &&6693!S.ResolveAddressOfOverloadedFunction(Initializer, DestType,6694/*Complain=*/false, Found))6695SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);6696else if (Initializer->getType()->isFunctionType() &&6697isExprAnUnaddressableFunction(S, Initializer))6698SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction);6699else6700SetFailed(InitializationSequence::FK_ConversionFailed);6701} else {6702AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);67036704MaybeProduceObjCObject(S, *this, Entity);6705}6706}67076708InitializationSequence::~InitializationSequence() {6709for (auto &S : Steps)6710S.Destroy();6711}67126713//===----------------------------------------------------------------------===//6714// Perform initialization6715//===----------------------------------------------------------------------===//6716static Sema::AssignmentAction6717getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {6718switch(Entity.getKind()) {6719case InitializedEntity::EK_Variable:6720case InitializedEntity::EK_New:6721case InitializedEntity::EK_Exception:6722case InitializedEntity::EK_Base:6723case InitializedEntity::EK_Delegating:6724return Sema::AA_Initializing;67256726case InitializedEntity::EK_Parameter:6727if (Entity.getDecl() &&6728isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))6729return Sema::AA_Sending;67306731return Sema::AA_Passing;67326733case InitializedEntity::EK_Parameter_CF_Audited:6734if (Entity.getDecl() &&6735isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))6736return Sema::AA_Sending;67376738return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;67396740case InitializedEntity::EK_Result:6741case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right.6742return Sema::AA_Returning;67436744case InitializedEntity::EK_Temporary:6745case InitializedEntity::EK_RelatedResult:6746// FIXME: Can we tell apart casting vs. converting?6747return Sema::AA_Casting;67486749case InitializedEntity::EK_TemplateParameter:6750// This is really initialization, but refer to it as conversion for6751// consistency with CheckConvertedConstantExpression.6752return Sema::AA_Converting;67536754case InitializedEntity::EK_Member:6755case InitializedEntity::EK_ParenAggInitMember:6756case InitializedEntity::EK_Binding:6757case InitializedEntity::EK_ArrayElement:6758case InitializedEntity::EK_VectorElement:6759case InitializedEntity::EK_ComplexElement:6760case InitializedEntity::EK_BlockElement:6761case InitializedEntity::EK_LambdaToBlockConversionBlockElement:6762case InitializedEntity::EK_LambdaCapture:6763case InitializedEntity::EK_CompoundLiteralInit:6764return Sema::AA_Initializing;6765}67666767llvm_unreachable("Invalid EntityKind!");6768}67696770/// Whether we should bind a created object as a temporary when6771/// initializing the given entity.6772static bool shouldBindAsTemporary(const InitializedEntity &Entity) {6773switch (Entity.getKind()) {6774case InitializedEntity::EK_ArrayElement:6775case InitializedEntity::EK_Member:6776case InitializedEntity::EK_ParenAggInitMember:6777case InitializedEntity::EK_Result:6778case InitializedEntity::EK_StmtExprResult:6779case InitializedEntity::EK_New:6780case InitializedEntity::EK_Variable:6781case InitializedEntity::EK_Base:6782case InitializedEntity::EK_Delegating:6783case InitializedEntity::EK_VectorElement:6784case InitializedEntity::EK_ComplexElement:6785case InitializedEntity::EK_Exception:6786case InitializedEntity::EK_BlockElement:6787case InitializedEntity::EK_LambdaToBlockConversionBlockElement:6788case InitializedEntity::EK_LambdaCapture:6789case InitializedEntity::EK_CompoundLiteralInit:6790case InitializedEntity::EK_TemplateParameter:6791return false;67926793case InitializedEntity::EK_Parameter:6794case InitializedEntity::EK_Parameter_CF_Audited:6795case InitializedEntity::EK_Temporary:6796case InitializedEntity::EK_RelatedResult:6797case InitializedEntity::EK_Binding:6798return true;6799}68006801llvm_unreachable("missed an InitializedEntity kind?");6802}68036804/// Whether the given entity, when initialized with an object6805/// created for that initialization, requires destruction.6806static bool shouldDestroyEntity(const InitializedEntity &Entity) {6807switch (Entity.getKind()) {6808case InitializedEntity::EK_Result:6809case InitializedEntity::EK_StmtExprResult:6810case InitializedEntity::EK_New:6811case InitializedEntity::EK_Base:6812case InitializedEntity::EK_Delegating:6813case InitializedEntity::EK_VectorElement:6814case InitializedEntity::EK_ComplexElement:6815case InitializedEntity::EK_BlockElement:6816case InitializedEntity::EK_LambdaToBlockConversionBlockElement:6817case InitializedEntity::EK_LambdaCapture:6818return false;68196820case InitializedEntity::EK_Member:6821case InitializedEntity::EK_ParenAggInitMember:6822case InitializedEntity::EK_Binding:6823case InitializedEntity::EK_Variable:6824case InitializedEntity::EK_Parameter:6825case InitializedEntity::EK_Parameter_CF_Audited:6826case InitializedEntity::EK_TemplateParameter:6827case InitializedEntity::EK_Temporary:6828case InitializedEntity::EK_ArrayElement:6829case InitializedEntity::EK_Exception:6830case InitializedEntity::EK_CompoundLiteralInit:6831case InitializedEntity::EK_RelatedResult:6832return true;6833}68346835llvm_unreachable("missed an InitializedEntity kind?");6836}68376838/// Get the location at which initialization diagnostics should appear.6839static SourceLocation getInitializationLoc(const InitializedEntity &Entity,6840Expr *Initializer) {6841switch (Entity.getKind()) {6842case InitializedEntity::EK_Result:6843case InitializedEntity::EK_StmtExprResult:6844return Entity.getReturnLoc();68456846case InitializedEntity::EK_Exception:6847return Entity.getThrowLoc();68486849case InitializedEntity::EK_Variable:6850case InitializedEntity::EK_Binding:6851return Entity.getDecl()->getLocation();68526853case InitializedEntity::EK_LambdaCapture:6854return Entity.getCaptureLoc();68556856case InitializedEntity::EK_ArrayElement:6857case InitializedEntity::EK_Member:6858case InitializedEntity::EK_ParenAggInitMember:6859case InitializedEntity::EK_Parameter:6860case InitializedEntity::EK_Parameter_CF_Audited:6861case InitializedEntity::EK_TemplateParameter:6862case InitializedEntity::EK_Temporary:6863case InitializedEntity::EK_New:6864case InitializedEntity::EK_Base:6865case InitializedEntity::EK_Delegating:6866case InitializedEntity::EK_VectorElement:6867case InitializedEntity::EK_ComplexElement:6868case InitializedEntity::EK_BlockElement:6869case InitializedEntity::EK_LambdaToBlockConversionBlockElement:6870case InitializedEntity::EK_CompoundLiteralInit:6871case InitializedEntity::EK_RelatedResult:6872return Initializer->getBeginLoc();6873}6874llvm_unreachable("missed an InitializedEntity kind?");6875}68766877/// Make a (potentially elidable) temporary copy of the object6878/// provided by the given initializer by calling the appropriate copy6879/// constructor.6880///6881/// \param S The Sema object used for type-checking.6882///6883/// \param T The type of the temporary object, which must either be6884/// the type of the initializer expression or a superclass thereof.6885///6886/// \param Entity The entity being initialized.6887///6888/// \param CurInit The initializer expression.6889///6890/// \param IsExtraneousCopy Whether this is an "extraneous" copy that6891/// is permitted in C++03 (but not C++0x) when binding a reference to6892/// an rvalue.6893///6894/// \returns An expression that copies the initializer expression into6895/// a temporary object, or an error expression if a copy could not be6896/// created.6897static ExprResult CopyObject(Sema &S,6898QualType T,6899const InitializedEntity &Entity,6900ExprResult CurInit,6901bool IsExtraneousCopy) {6902if (CurInit.isInvalid())6903return CurInit;6904// Determine which class type we're copying to.6905Expr *CurInitExpr = (Expr *)CurInit.get();6906CXXRecordDecl *Class = nullptr;6907if (const RecordType *Record = T->getAs<RecordType>())6908Class = cast<CXXRecordDecl>(Record->getDecl());6909if (!Class)6910return CurInit;69116912SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());69136914// Make sure that the type we are copying is complete.6915if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))6916return CurInit;69176918// Perform overload resolution using the class's constructors. Per6919// C++11 [dcl.init]p16, second bullet for class types, this initialization6920// is direct-initialization.6921OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);6922DeclContext::lookup_result Ctors = S.LookupConstructors(Class);69236924OverloadCandidateSet::iterator Best;6925switch (ResolveConstructorOverload(6926S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,6927/*CopyInitializing=*/false, /*AllowExplicit=*/true,6928/*OnlyListConstructors=*/false, /*IsListInit=*/false,6929/*RequireActualConstructor=*/false,6930/*SecondStepOfCopyInit=*/true)) {6931case OR_Success:6932break;69336934case OR_No_Viable_Function:6935CandidateSet.NoteCandidates(6936PartialDiagnosticAt(6937Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext()6938? diag::ext_rvalue_to_reference_temp_copy_no_viable6939: diag::err_temp_copy_no_viable)6940<< (int)Entity.getKind() << CurInitExpr->getType()6941<< CurInitExpr->getSourceRange()),6942S, OCD_AllCandidates, CurInitExpr);6943if (!IsExtraneousCopy || S.isSFINAEContext())6944return ExprError();6945return CurInit;69466947case OR_Ambiguous:6948CandidateSet.NoteCandidates(6949PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous)6950<< (int)Entity.getKind()6951<< CurInitExpr->getType()6952<< CurInitExpr->getSourceRange()),6953S, OCD_AmbiguousCandidates, CurInitExpr);6954return ExprError();69556956case OR_Deleted:6957S.Diag(Loc, diag::err_temp_copy_deleted)6958<< (int)Entity.getKind() << CurInitExpr->getType()6959<< CurInitExpr->getSourceRange();6960S.NoteDeletedFunction(Best->Function);6961return ExprError();6962}69636964bool HadMultipleCandidates = CandidateSet.size() > 1;69656966CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);6967SmallVector<Expr*, 8> ConstructorArgs;6968CurInit.get(); // Ownership transferred into MultiExprArg, below.69696970S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,6971IsExtraneousCopy);69726973if (IsExtraneousCopy) {6974// If this is a totally extraneous copy for C++03 reference6975// binding purposes, just return the original initialization6976// expression. We don't generate an (elided) copy operation here6977// because doing so would require us to pass down a flag to avoid6978// infinite recursion, where each step adds another extraneous,6979// elidable copy.69806981// Instantiate the default arguments of any extra parameters in6982// the selected copy constructor, as if we were going to create a6983// proper call to the copy constructor.6984for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {6985ParmVarDecl *Parm = Constructor->getParamDecl(I);6986if (S.RequireCompleteType(Loc, Parm->getType(),6987diag::err_call_incomplete_argument))6988break;69896990// Build the default argument expression; we don't actually care6991// if this succeeds or not, because this routine will complain6992// if there was a problem.6993S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);6994}69956996return CurInitExpr;6997}69986999// Determine the arguments required to actually perform the7000// constructor call (we might have derived-to-base conversions, or7001// the copy constructor may have default arguments).7002if (S.CompleteConstructorCall(Constructor, T, CurInitExpr, Loc,7003ConstructorArgs))7004return ExprError();70057006// C++0x [class.copy]p32:7007// When certain criteria are met, an implementation is allowed to7008// omit the copy/move construction of a class object, even if the7009// copy/move constructor and/or destructor for the object have7010// side effects. [...]7011// - when a temporary class object that has not been bound to a7012// reference (12.2) would be copied/moved to a class object7013// with the same cv-unqualified type, the copy/move operation7014// can be omitted by constructing the temporary object7015// directly into the target of the omitted copy/move7016//7017// Note that the other three bullets are handled elsewhere. Copy7018// elision for return statements and throw expressions are handled as part7019// of constructor initialization, while copy elision for exception handlers7020// is handled by the run-time.7021//7022// FIXME: If the function parameter is not the same type as the temporary, we7023// should still be able to elide the copy, but we don't have a way to7024// represent in the AST how much should be elided in this case.7025bool Elidable =7026CurInitExpr->isTemporaryObject(S.Context, Class) &&7027S.Context.hasSameUnqualifiedType(7028Best->Function->getParamDecl(0)->getType().getNonReferenceType(),7029CurInitExpr->getType());70307031// Actually perform the constructor call.7032CurInit = S.BuildCXXConstructExpr(7033Loc, T, Best->FoundDecl, Constructor, Elidable, ConstructorArgs,7034HadMultipleCandidates,7035/*ListInit*/ false,7036/*StdInitListInit*/ false,7037/*ZeroInit*/ false, CXXConstructionKind::Complete, SourceRange());70387039// If we're supposed to bind temporaries, do so.7040if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))7041CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());7042return CurInit;7043}70447045/// Check whether elidable copy construction for binding a reference to7046/// a temporary would have succeeded if we were building in C++98 mode, for7047/// -Wc++98-compat.7048static void CheckCXX98CompatAccessibleCopy(Sema &S,7049const InitializedEntity &Entity,7050Expr *CurInitExpr) {7051assert(S.getLangOpts().CPlusPlus11);70527053const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();7054if (!Record)7055return;70567057SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);7058if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))7059return;70607061// Find constructors which would have been considered.7062OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);7063DeclContext::lookup_result Ctors =7064S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl()));70657066// Perform overload resolution.7067OverloadCandidateSet::iterator Best;7068OverloadingResult OR = ResolveConstructorOverload(7069S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,7070/*CopyInitializing=*/false, /*AllowExplicit=*/true,7071/*OnlyListConstructors=*/false, /*IsListInit=*/false,7072/*RequireActualConstructor=*/false,7073/*SecondStepOfCopyInit=*/true);70747075PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)7076<< OR << (int)Entity.getKind() << CurInitExpr->getType()7077<< CurInitExpr->getSourceRange();70787079switch (OR) {7080case OR_Success:7081S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),7082Best->FoundDecl, Entity, Diag);7083// FIXME: Check default arguments as far as that's possible.7084break;70857086case OR_No_Viable_Function:7087CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,7088OCD_AllCandidates, CurInitExpr);7089break;70907091case OR_Ambiguous:7092CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,7093OCD_AmbiguousCandidates, CurInitExpr);7094break;70957096case OR_Deleted:7097S.Diag(Loc, Diag);7098S.NoteDeletedFunction(Best->Function);7099break;7100}7101}71027103void InitializationSequence::PrintInitLocationNote(Sema &S,7104const InitializedEntity &Entity) {7105if (Entity.isParamOrTemplateParamKind() && Entity.getDecl()) {7106if (Entity.getDecl()->getLocation().isInvalid())7107return;71087109if (Entity.getDecl()->getDeclName())7110S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)7111<< Entity.getDecl()->getDeclName();7112else7113S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);7114}7115else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&7116Entity.getMethodDecl())7117S.Diag(Entity.getMethodDecl()->getLocation(),7118diag::note_method_return_type_change)7119<< Entity.getMethodDecl()->getDeclName();7120}71217122/// Returns true if the parameters describe a constructor initialization of7123/// an explicit temporary object, e.g. "Point(x, y)".7124static bool isExplicitTemporary(const InitializedEntity &Entity,7125const InitializationKind &Kind,7126unsigned NumArgs) {7127switch (Entity.getKind()) {7128case InitializedEntity::EK_Temporary:7129case InitializedEntity::EK_CompoundLiteralInit:7130case InitializedEntity::EK_RelatedResult:7131break;7132default:7133return false;7134}71357136switch (Kind.getKind()) {7137case InitializationKind::IK_DirectList:7138return true;7139// FIXME: Hack to work around cast weirdness.7140case InitializationKind::IK_Direct:7141case InitializationKind::IK_Value:7142return NumArgs != 1;7143default:7144return false;7145}7146}71477148static ExprResult7149PerformConstructorInitialization(Sema &S,7150const InitializedEntity &Entity,7151const InitializationKind &Kind,7152MultiExprArg Args,7153const InitializationSequence::Step& Step,7154bool &ConstructorInitRequiresZeroInit,7155bool IsListInitialization,7156bool IsStdInitListInitialization,7157SourceLocation LBraceLoc,7158SourceLocation RBraceLoc) {7159unsigned NumArgs = Args.size();7160CXXConstructorDecl *Constructor7161= cast<CXXConstructorDecl>(Step.Function.Function);7162bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;71637164// Build a call to the selected constructor.7165SmallVector<Expr*, 8> ConstructorArgs;7166SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())7167? Kind.getEqualLoc()7168: Kind.getLocation();71697170if (Kind.getKind() == InitializationKind::IK_Default) {7171// Force even a trivial, implicit default constructor to be7172// semantically checked. We do this explicitly because we don't build7173// the definition for completely trivial constructors.7174assert(Constructor->getParent() && "No parent class for constructor.");7175if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&7176Constructor->isTrivial() && !Constructor->isUsed(false)) {7177S.runWithSufficientStackSpace(Loc, [&] {7178S.DefineImplicitDefaultConstructor(Loc, Constructor);7179});7180}7181}71827183ExprResult CurInit((Expr *)nullptr);71847185// C++ [over.match.copy]p1:7186// - When initializing a temporary to be bound to the first parameter7187// of a constructor that takes a reference to possibly cv-qualified7188// T as its first argument, called with a single argument in the7189// context of direct-initialization, explicit conversion functions7190// are also considered.7191bool AllowExplicitConv =7192Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&7193hasCopyOrMoveCtorParam(S.Context,7194getConstructorInfo(Step.Function.FoundDecl));71957196// A smart pointer constructed from a nullable pointer is nullable.7197if (NumArgs == 1 && !Kind.isExplicitCast())7198S.diagnoseNullableToNonnullConversion(7199Entity.getType(), Args.front()->getType(), Kind.getLocation());72007201// Determine the arguments required to actually perform the constructor7202// call.7203if (S.CompleteConstructorCall(Constructor, Step.Type, Args, Loc,7204ConstructorArgs, AllowExplicitConv,7205IsListInitialization))7206return ExprError();72077208if (isExplicitTemporary(Entity, Kind, NumArgs)) {7209// An explicitly-constructed temporary, e.g., X(1, 2).7210if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))7211return ExprError();72127213TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();7214if (!TSInfo)7215TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);7216SourceRange ParenOrBraceRange =7217(Kind.getKind() == InitializationKind::IK_DirectList)7218? SourceRange(LBraceLoc, RBraceLoc)7219: Kind.getParenOrBraceRange();72207221CXXConstructorDecl *CalleeDecl = Constructor;7222if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(7223Step.Function.FoundDecl.getDecl())) {7224CalleeDecl = S.findInheritingConstructor(Loc, Constructor, Shadow);7225}7226S.MarkFunctionReferenced(Loc, CalleeDecl);72277228CurInit = S.CheckForImmediateInvocation(7229CXXTemporaryObjectExpr::Create(7230S.Context, CalleeDecl,7231Entity.getType().getNonLValueExprType(S.Context), TSInfo,7232ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,7233IsListInitialization, IsStdInitListInitialization,7234ConstructorInitRequiresZeroInit),7235CalleeDecl);7236} else {7237CXXConstructionKind ConstructKind = CXXConstructionKind::Complete;72387239if (Entity.getKind() == InitializedEntity::EK_Base) {7240ConstructKind = Entity.getBaseSpecifier()->isVirtual()7241? CXXConstructionKind::VirtualBase7242: CXXConstructionKind::NonVirtualBase;7243} else if (Entity.getKind() == InitializedEntity::EK_Delegating) {7244ConstructKind = CXXConstructionKind::Delegating;7245}72467247// Only get the parenthesis or brace range if it is a list initialization or7248// direct construction.7249SourceRange ParenOrBraceRange;7250if (IsListInitialization)7251ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);7252else if (Kind.getKind() == InitializationKind::IK_Direct)7253ParenOrBraceRange = Kind.getParenOrBraceRange();72547255// If the entity allows NRVO, mark the construction as elidable7256// unconditionally.7257if (Entity.allowsNRVO())7258CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,7259Step.Function.FoundDecl,7260Constructor, /*Elidable=*/true,7261ConstructorArgs,7262HadMultipleCandidates,7263IsListInitialization,7264IsStdInitListInitialization,7265ConstructorInitRequiresZeroInit,7266ConstructKind,7267ParenOrBraceRange);7268else7269CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,7270Step.Function.FoundDecl,7271Constructor,7272ConstructorArgs,7273HadMultipleCandidates,7274IsListInitialization,7275IsStdInitListInitialization,7276ConstructorInitRequiresZeroInit,7277ConstructKind,7278ParenOrBraceRange);7279}7280if (CurInit.isInvalid())7281return ExprError();72827283// Only check access if all of that succeeded.7284S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity);7285if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))7286return ExprError();72877288if (const ArrayType *AT = S.Context.getAsArrayType(Entity.getType()))7289if (checkDestructorReference(S.Context.getBaseElementType(AT), Loc, S))7290return ExprError();72917292if (shouldBindAsTemporary(Entity))7293CurInit = S.MaybeBindToTemporary(CurInit.get());72947295return CurInit;7296}72977298void Sema::checkInitializerLifetime(const InitializedEntity &Entity,7299Expr *Init) {7300return sema::checkExprLifetime(*this, Entity, Init);7301}73027303static void DiagnoseNarrowingInInitList(Sema &S,7304const ImplicitConversionSequence &ICS,7305QualType PreNarrowingType,7306QualType EntityType,7307const Expr *PostInit);73087309static void CheckC23ConstexprInitConversion(Sema &S, QualType FromType,7310QualType ToType, Expr *Init);73117312/// Provide warnings when std::move is used on construction.7313static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,7314bool IsReturnStmt) {7315if (!InitExpr)7316return;73177318if (S.inTemplateInstantiation())7319return;73207321QualType DestType = InitExpr->getType();7322if (!DestType->isRecordType())7323return;73247325unsigned DiagID = 0;7326if (IsReturnStmt) {7327const CXXConstructExpr *CCE =7328dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());7329if (!CCE || CCE->getNumArgs() != 1)7330return;73317332if (!CCE->getConstructor()->isCopyOrMoveConstructor())7333return;73347335InitExpr = CCE->getArg(0)->IgnoreImpCasts();7336}73377338// Find the std::move call and get the argument.7339const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());7340if (!CE || !CE->isCallToStdMove())7341return;73427343const Expr *Arg = CE->getArg(0)->IgnoreImplicit();73447345if (IsReturnStmt) {7346const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());7347if (!DRE || DRE->refersToEnclosingVariableOrCapture())7348return;73497350const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());7351if (!VD || !VD->hasLocalStorage())7352return;73537354// __block variables are not moved implicitly.7355if (VD->hasAttr<BlocksAttr>())7356return;73577358QualType SourceType = VD->getType();7359if (!SourceType->isRecordType())7360return;73617362if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {7363return;7364}73657366// If we're returning a function parameter, copy elision7367// is not possible.7368if (isa<ParmVarDecl>(VD))7369DiagID = diag::warn_redundant_move_on_return;7370else7371DiagID = diag::warn_pessimizing_move_on_return;7372} else {7373DiagID = diag::warn_pessimizing_move_on_initialization;7374const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();7375if (!ArgStripped->isPRValue() || !ArgStripped->getType()->isRecordType())7376return;7377}73787379S.Diag(CE->getBeginLoc(), DiagID);73807381// Get all the locations for a fix-it. Don't emit the fix-it if any location7382// is within a macro.7383SourceLocation CallBegin = CE->getCallee()->getBeginLoc();7384if (CallBegin.isMacroID())7385return;7386SourceLocation RParen = CE->getRParenLoc();7387if (RParen.isMacroID())7388return;7389SourceLocation LParen;7390SourceLocation ArgLoc = Arg->getBeginLoc();73917392// Special testing for the argument location. Since the fix-it needs the7393// location right before the argument, the argument location can be in a7394// macro only if it is at the beginning of the macro.7395while (ArgLoc.isMacroID() &&7396S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) {7397ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).getBegin();7398}73997400if (LParen.isMacroID())7401return;74027403LParen = ArgLoc.getLocWithOffset(-1);74047405S.Diag(CE->getBeginLoc(), diag::note_remove_move)7406<< FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))7407<< FixItHint::CreateRemoval(SourceRange(RParen, RParen));7408}74097410static void CheckForNullPointerDereference(Sema &S, const Expr *E) {7411// Check to see if we are dereferencing a null pointer. If so, this is7412// undefined behavior, so warn about it. This only handles the pattern7413// "*null", which is a very syntactic check.7414if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))7415if (UO->getOpcode() == UO_Deref &&7416UO->getSubExpr()->IgnoreParenCasts()->7417isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {7418S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,7419S.PDiag(diag::warn_binding_null_to_reference)7420<< UO->getSubExpr()->getSourceRange());7421}7422}74237424MaterializeTemporaryExpr *7425Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,7426bool BoundToLvalueReference) {7427auto MTE = new (Context)7428MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);74297430// Order an ExprWithCleanups for lifetime marks.7431//7432// TODO: It'll be good to have a single place to check the access of the7433// destructor and generate ExprWithCleanups for various uses. Currently these7434// are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,7435// but there may be a chance to merge them.7436Cleanup.setExprNeedsCleanups(false);7437if (isInLifetimeExtendingContext()) {7438auto &Record = ExprEvalContexts.back();7439Record.ForRangeLifetimeExtendTemps.push_back(MTE);7440}7441return MTE;7442}74437444ExprResult Sema::TemporaryMaterializationConversion(Expr *E) {7445// In C++98, we don't want to implicitly create an xvalue.7446// FIXME: This means that AST consumers need to deal with "prvalues" that7447// denote materialized temporaries. Maybe we should add another ValueKind7448// for "xvalue pretending to be a prvalue" for C++98 support.7449if (!E->isPRValue() || !getLangOpts().CPlusPlus11)7450return E;74517452// C++1z [conv.rval]/1: T shall be a complete type.7453// FIXME: Does this ever matter (can we form a prvalue of incomplete type)?7454// If so, we should check for a non-abstract class type here too.7455QualType T = E->getType();7456if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))7457return ExprError();74587459return CreateMaterializeTemporaryExpr(E->getType(), E, false);7460}74617462ExprResult Sema::PerformQualificationConversion(Expr *E, QualType Ty,7463ExprValueKind VK,7464CheckedConversionKind CCK) {74657466CastKind CK = CK_NoOp;74677468if (VK == VK_PRValue) {7469auto PointeeTy = Ty->getPointeeType();7470auto ExprPointeeTy = E->getType()->getPointeeType();7471if (!PointeeTy.isNull() &&7472PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace())7473CK = CK_AddressSpaceConversion;7474} else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) {7475CK = CK_AddressSpaceConversion;7476}74777478return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK);7479}74807481ExprResult InitializationSequence::Perform(Sema &S,7482const InitializedEntity &Entity,7483const InitializationKind &Kind,7484MultiExprArg Args,7485QualType *ResultType) {7486if (Failed()) {7487Diagnose(S, Entity, Kind, Args);7488return ExprError();7489}7490if (!ZeroInitializationFixit.empty()) {7491const Decl *D = Entity.getDecl();7492const auto *VD = dyn_cast_or_null<VarDecl>(D);7493QualType DestType = Entity.getType();74947495// The initialization would have succeeded with this fixit. Since the fixit7496// is on the error, we need to build a valid AST in this case, so this isn't7497// handled in the Failed() branch above.7498if (!DestType->isRecordType() && VD && VD->isConstexpr()) {7499// Use a more useful diagnostic for constexpr variables.7500S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)7501<< VD7502<< FixItHint::CreateInsertion(ZeroInitializationFixitLoc,7503ZeroInitializationFixit);7504} else {7505unsigned DiagID = diag::err_default_init_const;7506if (S.getLangOpts().MSVCCompat && D && D->hasAttr<SelectAnyAttr>())7507DiagID = diag::ext_default_init_const;75087509S.Diag(Kind.getLocation(), DiagID)7510<< DestType << (bool)DestType->getAs<RecordType>()7511<< FixItHint::CreateInsertion(ZeroInitializationFixitLoc,7512ZeroInitializationFixit);7513}7514}75157516if (getKind() == DependentSequence) {7517// If the declaration is a non-dependent, incomplete array type7518// that has an initializer, then its type will be completed once7519// the initializer is instantiated.7520if (ResultType && !Entity.getType()->isDependentType() &&7521Args.size() == 1) {7522QualType DeclType = Entity.getType();7523if (const IncompleteArrayType *ArrayT7524= S.Context.getAsIncompleteArrayType(DeclType)) {7525// FIXME: We don't currently have the ability to accurately7526// compute the length of an initializer list without7527// performing full type-checking of the initializer list7528// (since we have to determine where braces are implicitly7529// introduced and such). So, we fall back to making the array7530// type a dependently-sized array type with no specified7531// bound.7532if (isa<InitListExpr>((Expr *)Args[0])) {7533SourceRange Brackets;75347535// Scavange the location of the brackets from the entity, if we can.7536if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) {7537if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {7538TypeLoc TL = TInfo->getTypeLoc();7539if (IncompleteArrayTypeLoc ArrayLoc =7540TL.getAs<IncompleteArrayTypeLoc>())7541Brackets = ArrayLoc.getBracketsRange();7542}7543}75447545*ResultType7546= S.Context.getDependentSizedArrayType(ArrayT->getElementType(),7547/*NumElts=*/nullptr,7548ArrayT->getSizeModifier(),7549ArrayT->getIndexTypeCVRQualifiers(),7550Brackets);7551}75527553}7554}7555if (Kind.getKind() == InitializationKind::IK_Direct &&7556!Kind.isExplicitCast()) {7557// Rebuild the ParenListExpr.7558SourceRange ParenRange = Kind.getParenOrBraceRange();7559return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),7560Args);7561}7562assert(Kind.getKind() == InitializationKind::IK_Copy ||7563Kind.isExplicitCast() ||7564Kind.getKind() == InitializationKind::IK_DirectList);7565return ExprResult(Args[0]);7566}75677568// No steps means no initialization.7569if (Steps.empty())7570return ExprResult((Expr *)nullptr);75717572if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&7573Args.size() == 1 && isa<InitListExpr>(Args[0]) &&7574!Entity.isParamOrTemplateParamKind()) {7575// Produce a C++98 compatibility warning if we are initializing a reference7576// from an initializer list. For parameters, we produce a better warning7577// elsewhere.7578Expr *Init = Args[0];7579S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init)7580<< Init->getSourceRange();7581}75827583if (S.getLangOpts().MicrosoftExt && Args.size() == 1 &&7584isa<PredefinedExpr>(Args[0]) && Entity.getType()->isArrayType()) {7585// Produce a Microsoft compatibility warning when initializing from a7586// predefined expression since MSVC treats predefined expressions as string7587// literals.7588Expr *Init = Args[0];7589S.Diag(Init->getBeginLoc(), diag::ext_init_from_predefined) << Init;7590}75917592// OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope7593QualType ETy = Entity.getType();7594bool HasGlobalAS = ETy.hasAddressSpace() &&7595ETy.getAddressSpace() == LangAS::opencl_global;75967597if (S.getLangOpts().OpenCLVersion >= 200 &&7598ETy->isAtomicType() && !HasGlobalAS &&7599Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {7600S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init)7601<< 17602<< SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc());7603return ExprError();7604}76057606QualType DestType = Entity.getType().getNonReferenceType();7607// FIXME: Ugly hack around the fact that Entity.getType() is not7608// the same as Entity.getDecl()->getType() in cases involving type merging,7609// and we want latter when it makes sense.7610if (ResultType)7611*ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :7612Entity.getType();76137614ExprResult CurInit((Expr *)nullptr);7615SmallVector<Expr*, 4> ArrayLoopCommonExprs;76167617// HLSL allows vector initialization to function like list initialization, but7618// use the syntax of a C++-like constructor.7619bool IsHLSLVectorInit = S.getLangOpts().HLSL && DestType->isExtVectorType() &&7620isa<InitListExpr>(Args[0]);7621(void)IsHLSLVectorInit;76227623// For initialization steps that start with a single initializer,7624// grab the only argument out the Args and place it into the "current"7625// initializer.7626switch (Steps.front().Kind) {7627case SK_ResolveAddressOfOverloadedFunction:7628case SK_CastDerivedToBasePRValue:7629case SK_CastDerivedToBaseXValue:7630case SK_CastDerivedToBaseLValue:7631case SK_BindReference:7632case SK_BindReferenceToTemporary:7633case SK_FinalCopy:7634case SK_ExtraneousCopyToTemporary:7635case SK_UserConversion:7636case SK_QualificationConversionLValue:7637case SK_QualificationConversionXValue:7638case SK_QualificationConversionPRValue:7639case SK_FunctionReferenceConversion:7640case SK_AtomicConversion:7641case SK_ConversionSequence:7642case SK_ConversionSequenceNoNarrowing:7643case SK_ListInitialization:7644case SK_UnwrapInitList:7645case SK_RewrapInitList:7646case SK_CAssignment:7647case SK_StringInit:7648case SK_ObjCObjectConversion:7649case SK_ArrayLoopIndex:7650case SK_ArrayLoopInit:7651case SK_ArrayInit:7652case SK_GNUArrayInit:7653case SK_ParenthesizedArrayInit:7654case SK_PassByIndirectCopyRestore:7655case SK_PassByIndirectRestore:7656case SK_ProduceObjCObject:7657case SK_StdInitializerList:7658case SK_OCLSamplerInit:7659case SK_OCLZeroOpaqueType: {7660assert(Args.size() == 1 || IsHLSLVectorInit);7661CurInit = Args[0];7662if (!CurInit.get()) return ExprError();7663break;7664}76657666case SK_ConstructorInitialization:7667case SK_ConstructorInitializationFromList:7668case SK_StdInitializerListConstructorCall:7669case SK_ZeroInitialization:7670case SK_ParenthesizedListInit:7671break;7672}76737674// Promote from an unevaluated context to an unevaluated list context in7675// C++11 list-initialization; we need to instantiate entities usable in7676// constant expressions here in order to perform narrowing checks =(7677EnterExpressionEvaluationContext Evaluated(7678S, EnterExpressionEvaluationContext::InitList,7679isa_and_nonnull<InitListExpr>(CurInit.get()));76807681// C++ [class.abstract]p2:7682// no objects of an abstract class can be created except as subobjects7683// of a class derived from it7684auto checkAbstractType = [&](QualType T) -> bool {7685if (Entity.getKind() == InitializedEntity::EK_Base ||7686Entity.getKind() == InitializedEntity::EK_Delegating)7687return false;7688return S.RequireNonAbstractType(Kind.getLocation(), T,7689diag::err_allocation_of_abstract_type);7690};76917692// Walk through the computed steps for the initialization sequence,7693// performing the specified conversions along the way.7694bool ConstructorInitRequiresZeroInit = false;7695for (step_iterator Step = step_begin(), StepEnd = step_end();7696Step != StepEnd; ++Step) {7697if (CurInit.isInvalid())7698return ExprError();76997700QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();77017702switch (Step->Kind) {7703case SK_ResolveAddressOfOverloadedFunction:7704// Overload resolution determined which function invoke; update the7705// initializer to reflect that choice.7706S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);7707if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))7708return ExprError();7709CurInit = S.FixOverloadedFunctionReference(CurInit,7710Step->Function.FoundDecl,7711Step->Function.Function);7712// We might get back another placeholder expression if we resolved to a7713// builtin.7714if (!CurInit.isInvalid())7715CurInit = S.CheckPlaceholderExpr(CurInit.get());7716break;77177718case SK_CastDerivedToBasePRValue:7719case SK_CastDerivedToBaseXValue:7720case SK_CastDerivedToBaseLValue: {7721// We have a derived-to-base cast that produces either an rvalue or an7722// lvalue. Perform that cast.77237724CXXCastPath BasePath;77257726// Casts to inaccessible base classes are allowed with C-style casts.7727bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();7728if (S.CheckDerivedToBaseConversion(7729SourceType, Step->Type, CurInit.get()->getBeginLoc(),7730CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess))7731return ExprError();77327733ExprValueKind VK =7734Step->Kind == SK_CastDerivedToBaseLValue7735? VK_LValue7736: (Step->Kind == SK_CastDerivedToBaseXValue ? VK_XValue7737: VK_PRValue);7738CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,7739CK_DerivedToBase, CurInit.get(),7740&BasePath, VK, FPOptionsOverride());7741break;7742}77437744case SK_BindReference:7745// Reference binding does not have any corresponding ASTs.77467747// Check exception specifications7748if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))7749return ExprError();77507751// We don't check for e.g. function pointers here, since address7752// availability checks should only occur when the function first decays7753// into a pointer or reference.7754if (CurInit.get()->getType()->isFunctionProtoType()) {7755if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {7756if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {7757if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,7758DRE->getBeginLoc()))7759return ExprError();7760}7761}7762}77637764CheckForNullPointerDereference(S, CurInit.get());7765break;77667767case SK_BindReferenceToTemporary: {7768// Make sure the "temporary" is actually an rvalue.7769assert(CurInit.get()->isPRValue() && "not a temporary");77707771// Check exception specifications7772if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))7773return ExprError();77747775QualType MTETy = Step->Type;77767777// When this is an incomplete array type (such as when this is7778// initializing an array of unknown bounds from an init list), use THAT7779// type instead so that we propagate the array bounds.7780if (MTETy->isIncompleteArrayType() &&7781!CurInit.get()->getType()->isIncompleteArrayType() &&7782S.Context.hasSameType(7783MTETy->getPointeeOrArrayElementType(),7784CurInit.get()->getType()->getPointeeOrArrayElementType()))7785MTETy = CurInit.get()->getType();77867787// Materialize the temporary into memory.7788MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(7789MTETy, CurInit.get(), Entity.getType()->isLValueReferenceType());7790CurInit = MTE;77917792// If we're extending this temporary to automatic storage duration -- we7793// need to register its cleanup during the full-expression's cleanups.7794if (MTE->getStorageDuration() == SD_Automatic &&7795MTE->getType().isDestructedType())7796S.Cleanup.setExprNeedsCleanups(true);7797break;7798}77997800case SK_FinalCopy:7801if (checkAbstractType(Step->Type))7802return ExprError();78037804// If the overall initialization is initializing a temporary, we already7805// bound our argument if it was necessary to do so. If not (if we're7806// ultimately initializing a non-temporary), our argument needs to be7807// bound since it's initializing a function parameter.7808// FIXME: This is a mess. Rationalize temporary destruction.7809if (!shouldBindAsTemporary(Entity))7810CurInit = S.MaybeBindToTemporary(CurInit.get());7811CurInit = CopyObject(S, Step->Type, Entity, CurInit,7812/*IsExtraneousCopy=*/false);7813break;78147815case SK_ExtraneousCopyToTemporary:7816CurInit = CopyObject(S, Step->Type, Entity, CurInit,7817/*IsExtraneousCopy=*/true);7818break;78197820case SK_UserConversion: {7821// We have a user-defined conversion that invokes either a constructor7822// or a conversion function.7823CastKind CastKind;7824FunctionDecl *Fn = Step->Function.Function;7825DeclAccessPair FoundFn = Step->Function.FoundDecl;7826bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;7827bool CreatedObject = false;7828if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {7829// Build a call to the selected constructor.7830SmallVector<Expr*, 8> ConstructorArgs;7831SourceLocation Loc = CurInit.get()->getBeginLoc();78327833// Determine the arguments required to actually perform the constructor7834// call.7835Expr *Arg = CurInit.get();7836if (S.CompleteConstructorCall(Constructor, Step->Type,7837MultiExprArg(&Arg, 1), Loc,7838ConstructorArgs))7839return ExprError();78407841// Build an expression that constructs a temporary.7842CurInit = S.BuildCXXConstructExpr(7843Loc, Step->Type, FoundFn, Constructor, ConstructorArgs,7844HadMultipleCandidates,7845/*ListInit*/ false,7846/*StdInitListInit*/ false,7847/*ZeroInit*/ false, CXXConstructionKind::Complete, SourceRange());7848if (CurInit.isInvalid())7849return ExprError();78507851S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,7852Entity);7853if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))7854return ExprError();78557856CastKind = CK_ConstructorConversion;7857CreatedObject = true;7858} else {7859// Build a call to the conversion function.7860CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);7861S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,7862FoundFn);7863if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))7864return ExprError();78657866CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,7867HadMultipleCandidates);7868if (CurInit.isInvalid())7869return ExprError();78707871CastKind = CK_UserDefinedConversion;7872CreatedObject = Conversion->getReturnType()->isRecordType();7873}78747875if (CreatedObject && checkAbstractType(CurInit.get()->getType()))7876return ExprError();78777878CurInit = ImplicitCastExpr::Create(7879S.Context, CurInit.get()->getType(), CastKind, CurInit.get(), nullptr,7880CurInit.get()->getValueKind(), S.CurFPFeatureOverrides());78817882if (shouldBindAsTemporary(Entity))7883// The overall entity is temporary, so this expression should be7884// destroyed at the end of its full-expression.7885CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());7886else if (CreatedObject && shouldDestroyEntity(Entity)) {7887// The object outlasts the full-expression, but we need to prepare for7888// a destructor being run on it.7889// FIXME: It makes no sense to do this here. This should happen7890// regardless of how we initialized the entity.7891QualType T = CurInit.get()->getType();7892if (const RecordType *Record = T->getAs<RecordType>()) {7893CXXDestructorDecl *Destructor7894= S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));7895S.CheckDestructorAccess(CurInit.get()->getBeginLoc(), Destructor,7896S.PDiag(diag::err_access_dtor_temp) << T);7897S.MarkFunctionReferenced(CurInit.get()->getBeginLoc(), Destructor);7898if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc()))7899return ExprError();7900}7901}7902break;7903}79047905case SK_QualificationConversionLValue:7906case SK_QualificationConversionXValue:7907case SK_QualificationConversionPRValue: {7908// Perform a qualification conversion; these can never go wrong.7909ExprValueKind VK =7910Step->Kind == SK_QualificationConversionLValue7911? VK_LValue7912: (Step->Kind == SK_QualificationConversionXValue ? VK_XValue7913: VK_PRValue);7914CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK);7915break;7916}79177918case SK_FunctionReferenceConversion:7919assert(CurInit.get()->isLValue() &&7920"function reference should be lvalue");7921CurInit =7922S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK_LValue);7923break;79247925case SK_AtomicConversion: {7926assert(CurInit.get()->isPRValue() && "cannot convert glvalue to atomic");7927CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,7928CK_NonAtomicToAtomic, VK_PRValue);7929break;7930}79317932case SK_ConversionSequence:7933case SK_ConversionSequenceNoNarrowing: {7934if (const auto *FromPtrType =7935CurInit.get()->getType()->getAs<PointerType>()) {7936if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) {7937if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&7938!ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {7939// Do not check static casts here because they are checked earlier7940// in Sema::ActOnCXXNamedCast()7941if (!Kind.isStaticCast()) {7942S.Diag(CurInit.get()->getExprLoc(),7943diag::warn_noderef_to_dereferenceable_pointer)7944<< CurInit.get()->getSourceRange();7945}7946}7947}7948}7949Expr *Init = CurInit.get();7950CheckedConversionKind CCK =7951Kind.isCStyleCast() ? CheckedConversionKind::CStyleCast7952: Kind.isFunctionalCast() ? CheckedConversionKind::FunctionalCast7953: Kind.isExplicitCast() ? CheckedConversionKind::OtherCast7954: CheckedConversionKind::Implicit;7955ExprResult CurInitExprRes = S.PerformImplicitConversion(7956Init, Step->Type, *Step->ICS, getAssignmentAction(Entity), CCK);7957if (CurInitExprRes.isInvalid())7958return ExprError();79597960S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), Init);79617962CurInit = CurInitExprRes;79637964if (Step->Kind == SK_ConversionSequenceNoNarrowing &&7965S.getLangOpts().CPlusPlus)7966DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),7967CurInit.get());79687969break;7970}79717972case SK_ListInitialization: {7973if (checkAbstractType(Step->Type))7974return ExprError();79757976InitListExpr *InitList = cast<InitListExpr>(CurInit.get());7977// If we're not initializing the top-level entity, we need to create an7978// InitializeTemporary entity for our target type.7979QualType Ty = Step->Type;7980bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);7981InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);7982InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;7983InitListChecker PerformInitList(S, InitEntity,7984InitList, Ty, /*VerifyOnly=*/false,7985/*TreatUnavailableAsInvalid=*/false);7986if (PerformInitList.HadError())7987return ExprError();79887989// Hack: We must update *ResultType if available in order to set the7990// bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.7991// Worst case: 'const int (&arref)[] = {1, 2, 3};'.7992if (ResultType &&7993ResultType->getNonReferenceType()->isIncompleteArrayType()) {7994if ((*ResultType)->isRValueReferenceType())7995Ty = S.Context.getRValueReferenceType(Ty);7996else if ((*ResultType)->isLValueReferenceType())7997Ty = S.Context.getLValueReferenceType(Ty,7998(*ResultType)->castAs<LValueReferenceType>()->isSpelledAsLValue());7999*ResultType = Ty;8000}80018002InitListExpr *StructuredInitList =8003PerformInitList.getFullyStructuredList();8004CurInit.get();8005CurInit = shouldBindAsTemporary(InitEntity)8006? S.MaybeBindToTemporary(StructuredInitList)8007: StructuredInitList;8008break;8009}80108011case SK_ConstructorInitializationFromList: {8012if (checkAbstractType(Step->Type))8013return ExprError();80148015// When an initializer list is passed for a parameter of type "reference8016// to object", we don't get an EK_Temporary entity, but instead an8017// EK_Parameter entity with reference type.8018// FIXME: This is a hack. What we really should do is create a user8019// conversion step for this case, but this makes it considerably more8020// complicated. For now, this will do.8021InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(8022Entity.getType().getNonReferenceType());8023bool UseTemporary = Entity.getType()->isReferenceType();8024assert(Args.size() == 1 && "expected a single argument for list init");8025InitListExpr *InitList = cast<InitListExpr>(Args[0]);8026S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)8027<< InitList->getSourceRange();8028MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());8029CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :8030Entity,8031Kind, Arg, *Step,8032ConstructorInitRequiresZeroInit,8033/*IsListInitialization*/true,8034/*IsStdInitListInit*/false,8035InitList->getLBraceLoc(),8036InitList->getRBraceLoc());8037break;8038}80398040case SK_UnwrapInitList:8041CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);8042break;80438044case SK_RewrapInitList: {8045Expr *E = CurInit.get();8046InitListExpr *Syntactic = Step->WrappingSyntacticList;8047InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,8048Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());8049ILE->setSyntacticForm(Syntactic);8050ILE->setType(E->getType());8051ILE->setValueKind(E->getValueKind());8052CurInit = ILE;8053break;8054}80558056case SK_ConstructorInitialization:8057case SK_StdInitializerListConstructorCall: {8058if (checkAbstractType(Step->Type))8059return ExprError();80608061// When an initializer list is passed for a parameter of type "reference8062// to object", we don't get an EK_Temporary entity, but instead an8063// EK_Parameter entity with reference type.8064// FIXME: This is a hack. What we really should do is create a user8065// conversion step for this case, but this makes it considerably more8066// complicated. For now, this will do.8067InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(8068Entity.getType().getNonReferenceType());8069bool UseTemporary = Entity.getType()->isReferenceType();8070bool IsStdInitListInit =8071Step->Kind == SK_StdInitializerListConstructorCall;8072Expr *Source = CurInit.get();8073SourceRange Range = Kind.hasParenOrBraceRange()8074? Kind.getParenOrBraceRange()8075: SourceRange();8076CurInit = PerformConstructorInitialization(8077S, UseTemporary ? TempEntity : Entity, Kind,8078Source ? MultiExprArg(Source) : Args, *Step,8079ConstructorInitRequiresZeroInit,8080/*IsListInitialization*/ IsStdInitListInit,8081/*IsStdInitListInitialization*/ IsStdInitListInit,8082/*LBraceLoc*/ Range.getBegin(),8083/*RBraceLoc*/ Range.getEnd());8084break;8085}80868087case SK_ZeroInitialization: {8088step_iterator NextStep = Step;8089++NextStep;8090if (NextStep != StepEnd &&8091(NextStep->Kind == SK_ConstructorInitialization ||8092NextStep->Kind == SK_ConstructorInitializationFromList)) {8093// The need for zero-initialization is recorded directly into8094// the call to the object's constructor within the next step.8095ConstructorInitRequiresZeroInit = true;8096} else if (Kind.getKind() == InitializationKind::IK_Value &&8097S.getLangOpts().CPlusPlus &&8098!Kind.isImplicitValueInit()) {8099TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();8100if (!TSInfo)8101TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,8102Kind.getRange().getBegin());81038104CurInit = new (S.Context) CXXScalarValueInitExpr(8105Entity.getType().getNonLValueExprType(S.Context), TSInfo,8106Kind.getRange().getEnd());8107} else {8108CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);8109}8110break;8111}81128113case SK_CAssignment: {8114QualType SourceType = CurInit.get()->getType();8115Expr *Init = CurInit.get();81168117// Save off the initial CurInit in case we need to emit a diagnostic8118ExprResult InitialCurInit = Init;8119ExprResult Result = Init;8120Sema::AssignConvertType ConvTy =8121S.CheckSingleAssignmentConstraints(Step->Type, Result, true,8122Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);8123if (Result.isInvalid())8124return ExprError();8125CurInit = Result;81268127// If this is a call, allow conversion to a transparent union.8128ExprResult CurInitExprRes = CurInit;8129if (ConvTy != Sema::Compatible &&8130Entity.isParameterKind() &&8131S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)8132== Sema::Compatible)8133ConvTy = Sema::Compatible;8134if (CurInitExprRes.isInvalid())8135return ExprError();8136CurInit = CurInitExprRes;81378138if (S.getLangOpts().C23 && initializingConstexprVariable(Entity)) {8139CheckC23ConstexprInitConversion(S, SourceType, Entity.getType(),8140CurInit.get());81418142// C23 6.7.1p6: If an object or subobject declared with storage-class8143// specifier constexpr has pointer, integer, or arithmetic type, any8144// explicit initializer value for it shall be null, an integer8145// constant expression, or an arithmetic constant expression,8146// respectively.8147Expr::EvalResult ER;8148if (Entity.getType()->getAs<PointerType>() &&8149CurInit.get()->EvaluateAsRValue(ER, S.Context) &&8150!ER.Val.isNullPointer()) {8151S.Diag(Kind.getLocation(), diag::err_c23_constexpr_pointer_not_null);8152}8153}81548155bool Complained;8156if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),8157Step->Type, SourceType,8158InitialCurInit.get(),8159getAssignmentAction(Entity, true),8160&Complained)) {8161PrintInitLocationNote(S, Entity);8162return ExprError();8163} else if (Complained)8164PrintInitLocationNote(S, Entity);8165break;8166}81678168case SK_StringInit: {8169QualType Ty = Step->Type;8170bool UpdateType = ResultType && Entity.getType()->isIncompleteArrayType();8171CheckStringInit(CurInit.get(), UpdateType ? *ResultType : Ty,8172S.Context.getAsArrayType(Ty), S,8173S.getLangOpts().C23 &&8174initializingConstexprVariable(Entity));8175break;8176}81778178case SK_ObjCObjectConversion:8179CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,8180CK_ObjCObjectLValueCast,8181CurInit.get()->getValueKind());8182break;81838184case SK_ArrayLoopIndex: {8185Expr *Cur = CurInit.get();8186Expr *BaseExpr = new (S.Context)8187OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),8188Cur->getValueKind(), Cur->getObjectKind(), Cur);8189Expr *IndexExpr =8190new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType());8191CurInit = S.CreateBuiltinArraySubscriptExpr(8192BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());8193ArrayLoopCommonExprs.push_back(BaseExpr);8194break;8195}81968197case SK_ArrayLoopInit: {8198assert(!ArrayLoopCommonExprs.empty() &&8199"mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");8200Expr *Common = ArrayLoopCommonExprs.pop_back_val();8201CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,8202CurInit.get());8203break;8204}82058206case SK_GNUArrayInit:8207// Okay: we checked everything before creating this step. Note that8208// this is a GNU extension.8209S.Diag(Kind.getLocation(), diag::ext_array_init_copy)8210<< Step->Type << CurInit.get()->getType()8211<< CurInit.get()->getSourceRange();8212updateGNUCompoundLiteralRValue(CurInit.get());8213[[fallthrough]];8214case SK_ArrayInit:8215// If the destination type is an incomplete array type, update the8216// type accordingly.8217if (ResultType) {8218if (const IncompleteArrayType *IncompleteDest8219= S.Context.getAsIncompleteArrayType(Step->Type)) {8220if (const ConstantArrayType *ConstantSource8221= S.Context.getAsConstantArrayType(CurInit.get()->getType())) {8222*ResultType = S.Context.getConstantArrayType(8223IncompleteDest->getElementType(), ConstantSource->getSize(),8224ConstantSource->getSizeExpr(), ArraySizeModifier::Normal, 0);8225}8226}8227}8228break;82298230case SK_ParenthesizedArrayInit:8231// Okay: we checked everything before creating this step. Note that8232// this is a GNU extension.8233S.Diag(Kind.getLocation(), diag::ext_array_init_parens)8234<< CurInit.get()->getSourceRange();8235break;82368237case SK_PassByIndirectCopyRestore:8238case SK_PassByIndirectRestore:8239checkIndirectCopyRestoreSource(S, CurInit.get());8240CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(8241CurInit.get(), Step->Type,8242Step->Kind == SK_PassByIndirectCopyRestore);8243break;82448245case SK_ProduceObjCObject:8246CurInit = ImplicitCastExpr::Create(8247S.Context, Step->Type, CK_ARCProduceObject, CurInit.get(), nullptr,8248VK_PRValue, FPOptionsOverride());8249break;82508251case SK_StdInitializerList: {8252S.Diag(CurInit.get()->getExprLoc(),8253diag::warn_cxx98_compat_initializer_list_init)8254<< CurInit.get()->getSourceRange();82558256// Materialize the temporary into memory.8257MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(8258CurInit.get()->getType(), CurInit.get(),8259/*BoundToLvalueReference=*/false);82608261// Wrap it in a construction of a std::initializer_list<T>.8262CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);82638264if (!Step->Type->isDependentType()) {8265QualType ElementType;8266[[maybe_unused]] bool IsStdInitializerList =8267S.isStdInitializerList(Step->Type, &ElementType);8268assert(IsStdInitializerList &&8269"StdInitializerList step to non-std::initializer_list");8270const CXXRecordDecl *Record =8271Step->Type->getAsCXXRecordDecl()->getDefinition();8272assert(Record && Record->isCompleteDefinition() &&8273"std::initializer_list should have already be "8274"complete/instantiated by this point");82758276auto InvalidType = [&] {8277S.Diag(Record->getLocation(),8278diag::err_std_initializer_list_malformed)8279<< Step->Type.getUnqualifiedType();8280return ExprError();8281};82828283if (Record->isUnion() || Record->getNumBases() != 0 ||8284Record->isPolymorphic())8285return InvalidType();82868287RecordDecl::field_iterator Field = Record->field_begin();8288if (Field == Record->field_end())8289return InvalidType();82908291// Start pointer8292if (!Field->getType()->isPointerType() ||8293!S.Context.hasSameType(Field->getType()->getPointeeType(),8294ElementType.withConst()))8295return InvalidType();82968297if (++Field == Record->field_end())8298return InvalidType();82998300// Size or end pointer8301if (const auto *PT = Field->getType()->getAs<PointerType>()) {8302if (!S.Context.hasSameType(PT->getPointeeType(),8303ElementType.withConst()))8304return InvalidType();8305} else {8306if (Field->isBitField() ||8307!S.Context.hasSameType(Field->getType(), S.Context.getSizeType()))8308return InvalidType();8309}83108311if (++Field != Record->field_end())8312return InvalidType();8313}83148315// Bind the result, in case the library has given initializer_list a8316// non-trivial destructor.8317if (shouldBindAsTemporary(Entity))8318CurInit = S.MaybeBindToTemporary(CurInit.get());8319break;8320}83218322case SK_OCLSamplerInit: {8323// Sampler initialization have 5 cases:8324// 1. function argument passing8325// 1a. argument is a file-scope variable8326// 1b. argument is a function-scope variable8327// 1c. argument is one of caller function's parameters8328// 2. variable initialization8329// 2a. initializing a file-scope variable8330// 2b. initializing a function-scope variable8331//8332// For file-scope variables, since they cannot be initialized by function8333// call of __translate_sampler_initializer in LLVM IR, their references8334// need to be replaced by a cast from their literal initializers to8335// sampler type. Since sampler variables can only be used in function8336// calls as arguments, we only need to replace them when handling the8337// argument passing.8338assert(Step->Type->isSamplerT() &&8339"Sampler initialization on non-sampler type.");8340Expr *Init = CurInit.get()->IgnoreParens();8341QualType SourceType = Init->getType();8342// Case 18343if (Entity.isParameterKind()) {8344if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {8345S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)8346<< SourceType;8347break;8348} else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {8349auto Var = cast<VarDecl>(DRE->getDecl());8350// Case 1b and 1c8351// No cast from integer to sampler is needed.8352if (!Var->hasGlobalStorage()) {8353CurInit = ImplicitCastExpr::Create(8354S.Context, Step->Type, CK_LValueToRValue, Init,8355/*BasePath=*/nullptr, VK_PRValue, FPOptionsOverride());8356break;8357}8358// Case 1a8359// For function call with a file-scope sampler variable as argument,8360// get the integer literal.8361// Do not diagnose if the file-scope variable does not have initializer8362// since this has already been diagnosed when parsing the variable8363// declaration.8364if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))8365break;8366Init = cast<ImplicitCastExpr>(const_cast<Expr*>(8367Var->getInit()))->getSubExpr();8368SourceType = Init->getType();8369}8370} else {8371// Case 28372// Check initializer is 32 bit integer constant.8373// If the initializer is taken from global variable, do not diagnose since8374// this has already been done when parsing the variable declaration.8375if (!Init->isConstantInitializer(S.Context, false))8376break;83778378if (!SourceType->isIntegerType() ||837932 != S.Context.getIntWidth(SourceType)) {8380S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)8381<< SourceType;8382break;8383}83848385Expr::EvalResult EVResult;8386Init->EvaluateAsInt(EVResult, S.Context);8387llvm::APSInt Result = EVResult.Val.getInt();8388const uint64_t SamplerValue = Result.getLimitedValue();8389// 32-bit value of sampler's initializer is interpreted as8390// bit-field with the following structure:8391// |unspecified|Filter|Addressing Mode| Normalized Coords|8392// |31 6|5 4|3 1| 0|8393// This structure corresponds to enum values of sampler properties8394// defined in SPIR spec v1.2 and also opencl-c.h8395unsigned AddressingMode = (0x0E & SamplerValue) >> 1;8396unsigned FilterMode = (0x30 & SamplerValue) >> 4;8397if (FilterMode != 1 && FilterMode != 2 &&8398!S.getOpenCLOptions().isAvailableOption(8399"cl_intel_device_side_avc_motion_estimation", S.getLangOpts()))8400S.Diag(Kind.getLocation(),8401diag::warn_sampler_initializer_invalid_bits)8402<< "Filter Mode";8403if (AddressingMode > 4)8404S.Diag(Kind.getLocation(),8405diag::warn_sampler_initializer_invalid_bits)8406<< "Addressing Mode";8407}84088409// Cases 1a, 2a and 2b8410// Insert cast from integer to sampler.8411CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy,8412CK_IntToOCLSampler);8413break;8414}8415case SK_OCLZeroOpaqueType: {8416assert((Step->Type->isEventT() || Step->Type->isQueueT() ||8417Step->Type->isOCLIntelSubgroupAVCType()) &&8418"Wrong type for initialization of OpenCL opaque type.");84198420CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,8421CK_ZeroToOCLOpaqueType,8422CurInit.get()->getValueKind());8423break;8424}8425case SK_ParenthesizedListInit: {8426CurInit = nullptr;8427TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,8428/*VerifyOnly=*/false, &CurInit);8429if (CurInit.get() && ResultType)8430*ResultType = CurInit.get()->getType();8431if (shouldBindAsTemporary(Entity))8432CurInit = S.MaybeBindToTemporary(CurInit.get());8433break;8434}8435}8436}84378438Expr *Init = CurInit.get();8439if (!Init)8440return ExprError();84418442// Check whether the initializer has a shorter lifetime than the initialized8443// entity, and if not, either lifetime-extend or warn as appropriate.8444S.checkInitializerLifetime(Entity, Init);84458446// Diagnose non-fatal problems with the completed initialization.8447if (InitializedEntity::EntityKind EK = Entity.getKind();8448(EK == InitializedEntity::EK_Member ||8449EK == InitializedEntity::EK_ParenAggInitMember) &&8450cast<FieldDecl>(Entity.getDecl())->isBitField())8451S.CheckBitFieldInitialization(Kind.getLocation(),8452cast<FieldDecl>(Entity.getDecl()), Init);84538454// Check for std::move on construction.8455CheckMoveOnConstruction(S, Init,8456Entity.getKind() == InitializedEntity::EK_Result);84578458return Init;8459}84608461/// Somewhere within T there is an uninitialized reference subobject.8462/// Dig it out and diagnose it.8463static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,8464QualType T) {8465if (T->isReferenceType()) {8466S.Diag(Loc, diag::err_reference_without_init)8467<< T.getNonReferenceType();8468return true;8469}84708471CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();8472if (!RD || !RD->hasUninitializedReferenceMember())8473return false;84748475for (const auto *FI : RD->fields()) {8476if (FI->isUnnamedBitField())8477continue;84788479if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {8480S.Diag(Loc, diag::note_value_initialization_here) << RD;8481return true;8482}8483}84848485for (const auto &BI : RD->bases()) {8486if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) {8487S.Diag(Loc, diag::note_value_initialization_here) << RD;8488return true;8489}8490}84918492return false;8493}849484958496//===----------------------------------------------------------------------===//8497// Diagnose initialization failures8498//===----------------------------------------------------------------------===//84998500/// Emit notes associated with an initialization that failed due to a8501/// "simple" conversion failure.8502static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,8503Expr *op) {8504QualType destType = entity.getType();8505if (destType.getNonReferenceType()->isObjCObjectPointerType() &&8506op->getType()->isObjCObjectPointerType()) {85078508// Emit a possible note about the conversion failing because the8509// operand is a message send with a related result type.8510S.ObjC().EmitRelatedResultTypeNote(op);85118512// Emit a possible note about a return failing because we're8513// expecting a related result type.8514if (entity.getKind() == InitializedEntity::EK_Result)8515S.ObjC().EmitRelatedResultTypeNoteForReturn(destType);8516}8517QualType fromType = op->getType();8518QualType fromPointeeType = fromType.getCanonicalType()->getPointeeType();8519QualType destPointeeType = destType.getCanonicalType()->getPointeeType();8520auto *fromDecl = fromType->getPointeeCXXRecordDecl();8521auto *destDecl = destType->getPointeeCXXRecordDecl();8522if (fromDecl && destDecl && fromDecl->getDeclKind() == Decl::CXXRecord &&8523destDecl->getDeclKind() == Decl::CXXRecord &&8524!fromDecl->isInvalidDecl() && !destDecl->isInvalidDecl() &&8525!fromDecl->hasDefinition() &&8526destPointeeType.getQualifiers().compatiblyIncludes(8527fromPointeeType.getQualifiers()))8528S.Diag(fromDecl->getLocation(), diag::note_forward_class_conversion)8529<< S.getASTContext().getTagDeclType(fromDecl)8530<< S.getASTContext().getTagDeclType(destDecl);8531}85328533static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,8534InitListExpr *InitList) {8535QualType DestType = Entity.getType();85368537QualType E;8538if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {8539QualType ArrayType = S.Context.getConstantArrayType(8540E.withConst(),8541llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),8542InitList->getNumInits()),8543nullptr, clang::ArraySizeModifier::Normal, 0);8544InitializedEntity HiddenArray =8545InitializedEntity::InitializeTemporary(ArrayType);8546return diagnoseListInit(S, HiddenArray, InitList);8547}85488549if (DestType->isReferenceType()) {8550// A list-initialization failure for a reference means that we tried to8551// create a temporary of the inner type (per [dcl.init.list]p3.6) and the8552// inner initialization failed.8553QualType T = DestType->castAs<ReferenceType>()->getPointeeType();8554diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);8555SourceLocation Loc = InitList->getBeginLoc();8556if (auto *D = Entity.getDecl())8557Loc = D->getLocation();8558S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;8559return;8560}85618562InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,8563/*VerifyOnly=*/false,8564/*TreatUnavailableAsInvalid=*/false);8565assert(DiagnoseInitList.HadError() &&8566"Inconsistent init list check result.");8567}85688569bool InitializationSequence::Diagnose(Sema &S,8570const InitializedEntity &Entity,8571const InitializationKind &Kind,8572ArrayRef<Expr *> Args) {8573if (!Failed())8574return false;85758576QualType DestType = Entity.getType();85778578// When we want to diagnose only one element of a braced-init-list,8579// we need to factor it out.8580Expr *OnlyArg;8581if (Args.size() == 1) {8582auto *List = dyn_cast<InitListExpr>(Args[0]);8583if (List && List->getNumInits() == 1)8584OnlyArg = List->getInit(0);8585else8586OnlyArg = Args[0];85878588if (OnlyArg->getType() == S.Context.OverloadTy) {8589DeclAccessPair Found;8590if (FunctionDecl *FD = S.ResolveAddressOfOverloadedFunction(8591OnlyArg, DestType.getNonReferenceType(), /*Complain=*/false,8592Found)) {8593if (Expr *Resolved =8594S.FixOverloadedFunctionReference(OnlyArg, Found, FD).get())8595OnlyArg = Resolved;8596}8597}8598}8599else8600OnlyArg = nullptr;86018602switch (Failure) {8603case FK_TooManyInitsForReference:8604// FIXME: Customize for the initialized entity?8605if (Args.empty()) {8606// Dig out the reference subobject which is uninitialized and diagnose it.8607// If this is value-initialization, this could be nested some way within8608// the target type.8609assert(Kind.getKind() == InitializationKind::IK_Value ||8610DestType->isReferenceType());8611bool Diagnosed =8612DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);8613assert(Diagnosed && "couldn't find uninitialized reference to diagnose");8614(void)Diagnosed;8615} else // FIXME: diagnostic below could be better!8616S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)8617<< SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());8618break;8619case FK_ParenthesizedListInitForReference:8620S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)8621<< 1 << Entity.getType() << Args[0]->getSourceRange();8622break;86238624case FK_ArrayNeedsInitList:8625S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;8626break;8627case FK_ArrayNeedsInitListOrStringLiteral:8628S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;8629break;8630case FK_ArrayNeedsInitListOrWideStringLiteral:8631S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;8632break;8633case FK_NarrowStringIntoWideCharArray:8634S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);8635break;8636case FK_WideStringIntoCharArray:8637S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);8638break;8639case FK_IncompatWideStringIntoWideChar:8640S.Diag(Kind.getLocation(),8641diag::err_array_init_incompat_wide_string_into_wchar);8642break;8643case FK_PlainStringIntoUTF8Char:8644S.Diag(Kind.getLocation(),8645diag::err_array_init_plain_string_into_char8_t);8646S.Diag(Args.front()->getBeginLoc(),8647diag::note_array_init_plain_string_into_char8_t)8648<< FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8");8649break;8650case FK_UTF8StringIntoPlainChar:8651S.Diag(Kind.getLocation(), diag::err_array_init_utf8_string_into_char)8652<< DestType->isSignedIntegerType() << S.getLangOpts().CPlusPlus20;8653break;8654case FK_ArrayTypeMismatch:8655case FK_NonConstantArrayInit:8656S.Diag(Kind.getLocation(),8657(Failure == FK_ArrayTypeMismatch8658? diag::err_array_init_different_type8659: diag::err_array_init_non_constant_array))8660<< DestType.getNonReferenceType()8661<< OnlyArg->getType()8662<< Args[0]->getSourceRange();8663break;86648665case FK_VariableLengthArrayHasInitializer:8666S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)8667<< Args[0]->getSourceRange();8668break;86698670case FK_AddressOfOverloadFailed: {8671DeclAccessPair Found;8672S.ResolveAddressOfOverloadedFunction(OnlyArg,8673DestType.getNonReferenceType(),8674true,8675Found);8676break;8677}86788679case FK_AddressOfUnaddressableFunction: {8680auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl());8681S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,8682OnlyArg->getBeginLoc());8683break;8684}86858686case FK_ReferenceInitOverloadFailed:8687case FK_UserConversionOverloadFailed:8688switch (FailedOverloadResult) {8689case OR_Ambiguous:86908691FailedCandidateSet.NoteCandidates(8692PartialDiagnosticAt(8693Kind.getLocation(),8694Failure == FK_UserConversionOverloadFailed8695? (S.PDiag(diag::err_typecheck_ambiguous_condition)8696<< OnlyArg->getType() << DestType8697<< Args[0]->getSourceRange())8698: (S.PDiag(diag::err_ref_init_ambiguous)8699<< DestType << OnlyArg->getType()8700<< Args[0]->getSourceRange())),8701S, OCD_AmbiguousCandidates, Args);8702break;87038704case OR_No_Viable_Function: {8705auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args);8706if (!S.RequireCompleteType(Kind.getLocation(),8707DestType.getNonReferenceType(),8708diag::err_typecheck_nonviable_condition_incomplete,8709OnlyArg->getType(), Args[0]->getSourceRange()))8710S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)8711<< (Entity.getKind() == InitializedEntity::EK_Result)8712<< OnlyArg->getType() << Args[0]->getSourceRange()8713<< DestType.getNonReferenceType();87148715FailedCandidateSet.NoteCandidates(S, Args, Cands);8716break;8717}8718case OR_Deleted: {8719OverloadCandidateSet::iterator Best;8720OverloadingResult Ovl8721= FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);87228723StringLiteral *Msg = Best->Function->getDeletedMessage();8724S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)8725<< OnlyArg->getType() << DestType.getNonReferenceType()8726<< (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())8727<< Args[0]->getSourceRange();8728if (Ovl == OR_Deleted) {8729S.NoteDeletedFunction(Best->Function);8730} else {8731llvm_unreachable("Inconsistent overload resolution?");8732}8733break;8734}87358736case OR_Success:8737llvm_unreachable("Conversion did not fail!");8738}8739break;87408741case FK_NonConstLValueReferenceBindingToTemporary:8742if (isa<InitListExpr>(Args[0])) {8743S.Diag(Kind.getLocation(),8744diag::err_lvalue_reference_bind_to_initlist)8745<< DestType.getNonReferenceType().isVolatileQualified()8746<< DestType.getNonReferenceType()8747<< Args[0]->getSourceRange();8748break;8749}8750[[fallthrough]];87518752case FK_NonConstLValueReferenceBindingToUnrelated:8753S.Diag(Kind.getLocation(),8754Failure == FK_NonConstLValueReferenceBindingToTemporary8755? diag::err_lvalue_reference_bind_to_temporary8756: diag::err_lvalue_reference_bind_to_unrelated)8757<< DestType.getNonReferenceType().isVolatileQualified()8758<< DestType.getNonReferenceType()8759<< OnlyArg->getType()8760<< Args[0]->getSourceRange();8761break;87628763case FK_NonConstLValueReferenceBindingToBitfield: {8764// We don't necessarily have an unambiguous source bit-field.8765FieldDecl *BitField = Args[0]->getSourceBitField();8766S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)8767<< DestType.isVolatileQualified()8768<< (BitField ? BitField->getDeclName() : DeclarationName())8769<< (BitField != nullptr)8770<< Args[0]->getSourceRange();8771if (BitField)8772S.Diag(BitField->getLocation(), diag::note_bitfield_decl);8773break;8774}87758776case FK_NonConstLValueReferenceBindingToVectorElement:8777S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)8778<< DestType.isVolatileQualified()8779<< Args[0]->getSourceRange();8780break;87818782case FK_NonConstLValueReferenceBindingToMatrixElement:8783S.Diag(Kind.getLocation(), diag::err_reference_bind_to_matrix_element)8784<< DestType.isVolatileQualified() << Args[0]->getSourceRange();8785break;87868787case FK_RValueReferenceBindingToLValue:8788S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)8789<< DestType.getNonReferenceType() << OnlyArg->getType()8790<< Args[0]->getSourceRange();8791break;87928793case FK_ReferenceAddrspaceMismatchTemporary:8794S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace)8795<< DestType << Args[0]->getSourceRange();8796break;87978798case FK_ReferenceInitDropsQualifiers: {8799QualType SourceType = OnlyArg->getType();8800QualType NonRefType = DestType.getNonReferenceType();8801Qualifiers DroppedQualifiers =8802SourceType.getQualifiers() - NonRefType.getQualifiers();88038804if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf(8805SourceType.getQualifiers()))8806S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)8807<< NonRefType << SourceType << 1 /*addr space*/8808<< Args[0]->getSourceRange();8809else if (DroppedQualifiers.hasQualifiers())8810S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)8811<< NonRefType << SourceType << 0 /*cv quals*/8812<< Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers())8813<< DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange();8814else8815// FIXME: Consider decomposing the type and explaining which qualifiers8816// were dropped where, or on which level a 'const' is missing, etc.8817S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)8818<< NonRefType << SourceType << 2 /*incompatible quals*/8819<< Args[0]->getSourceRange();8820break;8821}88228823case FK_ReferenceInitFailed:8824S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)8825<< DestType.getNonReferenceType()8826<< DestType.getNonReferenceType()->isIncompleteType()8827<< OnlyArg->isLValue()8828<< OnlyArg->getType()8829<< Args[0]->getSourceRange();8830emitBadConversionNotes(S, Entity, Args[0]);8831break;88328833case FK_ConversionFailed: {8834QualType FromType = OnlyArg->getType();8835PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)8836<< (int)Entity.getKind()8837<< DestType8838<< OnlyArg->isLValue()8839<< FromType8840<< Args[0]->getSourceRange();8841S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);8842S.Diag(Kind.getLocation(), PDiag);8843emitBadConversionNotes(S, Entity, Args[0]);8844break;8845}88468847case FK_ConversionFromPropertyFailed:8848// No-op. This error has already been reported.8849break;88508851case FK_TooManyInitsForScalar: {8852SourceRange R;88538854auto *InitList = dyn_cast<InitListExpr>(Args[0]);8855if (InitList && InitList->getNumInits() >= 1) {8856R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc());8857} else {8858assert(Args.size() > 1 && "Expected multiple initializers!");8859R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc());8860}88618862R.setBegin(S.getLocForEndOfToken(R.getBegin()));8863if (Kind.isCStyleOrFunctionalCast())8864S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)8865<< R;8866else8867S.Diag(Kind.getLocation(), diag::err_excess_initializers)8868<< /*scalar=*/2 << R;8869break;8870}88718872case FK_ParenthesizedListInitForScalar:8873S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)8874<< 0 << Entity.getType() << Args[0]->getSourceRange();8875break;88768877case FK_ReferenceBindingToInitList:8878S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)8879<< DestType.getNonReferenceType() << Args[0]->getSourceRange();8880break;88818882case FK_InitListBadDestinationType:8883S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)8884<< (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();8885break;88868887case FK_ListConstructorOverloadFailed:8888case FK_ConstructorOverloadFailed: {8889SourceRange ArgsRange;8890if (Args.size())8891ArgsRange =8892SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());88938894if (Failure == FK_ListConstructorOverloadFailed) {8895assert(Args.size() == 1 &&8896"List construction from other than 1 argument.");8897InitListExpr *InitList = cast<InitListExpr>(Args[0]);8898Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());8899}89008901// FIXME: Using "DestType" for the entity we're printing is probably8902// bad.8903switch (FailedOverloadResult) {8904case OR_Ambiguous:8905FailedCandidateSet.NoteCandidates(8906PartialDiagnosticAt(Kind.getLocation(),8907S.PDiag(diag::err_ovl_ambiguous_init)8908<< DestType << ArgsRange),8909S, OCD_AmbiguousCandidates, Args);8910break;89118912case OR_No_Viable_Function:8913if (Kind.getKind() == InitializationKind::IK_Default &&8914(Entity.getKind() == InitializedEntity::EK_Base ||8915Entity.getKind() == InitializedEntity::EK_Member ||8916Entity.getKind() == InitializedEntity::EK_ParenAggInitMember) &&8917isa<CXXConstructorDecl>(S.CurContext)) {8918// This is implicit default initialization of a member or8919// base within a constructor. If no viable function was8920// found, notify the user that they need to explicitly8921// initialize this base/member.8922CXXConstructorDecl *Constructor8923= cast<CXXConstructorDecl>(S.CurContext);8924const CXXRecordDecl *InheritedFrom = nullptr;8925if (auto Inherited = Constructor->getInheritedConstructor())8926InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();8927if (Entity.getKind() == InitializedEntity::EK_Base) {8928S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)8929<< (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)8930<< S.Context.getTypeDeclType(Constructor->getParent())8931<< /*base=*/08932<< Entity.getType()8933<< InheritedFrom;89348935RecordDecl *BaseDecl8936= Entity.getBaseSpecifier()->getType()->castAs<RecordType>()8937->getDecl();8938S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)8939<< S.Context.getTagDeclType(BaseDecl);8940} else {8941S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)8942<< (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)8943<< S.Context.getTypeDeclType(Constructor->getParent())8944<< /*member=*/18945<< Entity.getName()8946<< InheritedFrom;8947S.Diag(Entity.getDecl()->getLocation(),8948diag::note_member_declared_at);89498950if (const RecordType *Record8951= Entity.getType()->getAs<RecordType>())8952S.Diag(Record->getDecl()->getLocation(),8953diag::note_previous_decl)8954<< S.Context.getTagDeclType(Record->getDecl());8955}8956break;8957}89588959FailedCandidateSet.NoteCandidates(8960PartialDiagnosticAt(8961Kind.getLocation(),8962S.PDiag(diag::err_ovl_no_viable_function_in_init)8963<< DestType << ArgsRange),8964S, OCD_AllCandidates, Args);8965break;89668967case OR_Deleted: {8968OverloadCandidateSet::iterator Best;8969OverloadingResult Ovl8970= FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);8971if (Ovl != OR_Deleted) {8972S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)8973<< DestType << ArgsRange;8974llvm_unreachable("Inconsistent overload resolution?");8975break;8976}89778978// If this is a defaulted or implicitly-declared function, then8979// it was implicitly deleted. Make it clear that the deletion was8980// implicit.8981if (S.isImplicitlyDeleted(Best->Function))8982S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)8983<< llvm::to_underlying(8984S.getSpecialMember(cast<CXXMethodDecl>(Best->Function)))8985<< DestType << ArgsRange;8986else {8987StringLiteral *Msg = Best->Function->getDeletedMessage();8988S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)8989<< DestType << (Msg != nullptr)8990<< (Msg ? Msg->getString() : StringRef()) << ArgsRange;8991}89928993S.NoteDeletedFunction(Best->Function);8994break;8995}89968997case OR_Success:8998llvm_unreachable("Conversion did not fail!");8999}9000}9001break;90029003case FK_DefaultInitOfConst:9004if (Entity.getKind() == InitializedEntity::EK_Member &&9005isa<CXXConstructorDecl>(S.CurContext)) {9006// This is implicit default-initialization of a const member in9007// a constructor. Complain that it needs to be explicitly9008// initialized.9009CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);9010S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)9011<< (Constructor->getInheritedConstructor() ? 2 :9012Constructor->isImplicit() ? 1 : 0)9013<< S.Context.getTypeDeclType(Constructor->getParent())9014<< /*const=*/19015<< Entity.getName();9016S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)9017<< Entity.getName();9018} else if (const auto *VD = dyn_cast_if_present<VarDecl>(Entity.getDecl());9019VD && VD->isConstexpr()) {9020S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)9021<< VD;9022} else {9023S.Diag(Kind.getLocation(), diag::err_default_init_const)9024<< DestType << (bool)DestType->getAs<RecordType>();9025}9026break;90279028case FK_Incomplete:9029S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,9030diag::err_init_incomplete_type);9031break;90329033case FK_ListInitializationFailed: {9034// Run the init list checker again to emit diagnostics.9035InitListExpr *InitList = cast<InitListExpr>(Args[0]);9036diagnoseListInit(S, Entity, InitList);9037break;9038}90399040case FK_PlaceholderType: {9041// FIXME: Already diagnosed!9042break;9043}90449045case FK_ExplicitConstructor: {9046S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)9047<< Args[0]->getSourceRange();9048OverloadCandidateSet::iterator Best;9049OverloadingResult Ovl9050= FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);9051(void)Ovl;9052assert(Ovl == OR_Success && "Inconsistent overload resolution");9053CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);9054S.Diag(CtorDecl->getLocation(),9055diag::note_explicit_ctor_deduction_guide_here) << false;9056break;9057}90589059case FK_ParenthesizedListInitFailed:9060TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,9061/*VerifyOnly=*/false);9062break;90639064case FK_DesignatedInitForNonAggregate:9065InitListExpr *InitList = cast<InitListExpr>(Args[0]);9066S.Diag(Kind.getLocation(), diag::err_designated_init_for_non_aggregate)9067<< Entity.getType() << InitList->getSourceRange();9068break;9069}90709071PrintInitLocationNote(S, Entity);9072return true;9073}90749075void InitializationSequence::dump(raw_ostream &OS) const {9076switch (SequenceKind) {9077case FailedSequence: {9078OS << "Failed sequence: ";9079switch (Failure) {9080case FK_TooManyInitsForReference:9081OS << "too many initializers for reference";9082break;90839084case FK_ParenthesizedListInitForReference:9085OS << "parenthesized list init for reference";9086break;90879088case FK_ArrayNeedsInitList:9089OS << "array requires initializer list";9090break;90919092case FK_AddressOfUnaddressableFunction:9093OS << "address of unaddressable function was taken";9094break;90959096case FK_ArrayNeedsInitListOrStringLiteral:9097OS << "array requires initializer list or string literal";9098break;90999100case FK_ArrayNeedsInitListOrWideStringLiteral:9101OS << "array requires initializer list or wide string literal";9102break;91039104case FK_NarrowStringIntoWideCharArray:9105OS << "narrow string into wide char array";9106break;91079108case FK_WideStringIntoCharArray:9109OS << "wide string into char array";9110break;91119112case FK_IncompatWideStringIntoWideChar:9113OS << "incompatible wide string into wide char array";9114break;91159116case FK_PlainStringIntoUTF8Char:9117OS << "plain string literal into char8_t array";9118break;91199120case FK_UTF8StringIntoPlainChar:9121OS << "u8 string literal into char array";9122break;91239124case FK_ArrayTypeMismatch:9125OS << "array type mismatch";9126break;91279128case FK_NonConstantArrayInit:9129OS << "non-constant array initializer";9130break;91319132case FK_AddressOfOverloadFailed:9133OS << "address of overloaded function failed";9134break;91359136case FK_ReferenceInitOverloadFailed:9137OS << "overload resolution for reference initialization failed";9138break;91399140case FK_NonConstLValueReferenceBindingToTemporary:9141OS << "non-const lvalue reference bound to temporary";9142break;91439144case FK_NonConstLValueReferenceBindingToBitfield:9145OS << "non-const lvalue reference bound to bit-field";9146break;91479148case FK_NonConstLValueReferenceBindingToVectorElement:9149OS << "non-const lvalue reference bound to vector element";9150break;91519152case FK_NonConstLValueReferenceBindingToMatrixElement:9153OS << "non-const lvalue reference bound to matrix element";9154break;91559156case FK_NonConstLValueReferenceBindingToUnrelated:9157OS << "non-const lvalue reference bound to unrelated type";9158break;91599160case FK_RValueReferenceBindingToLValue:9161OS << "rvalue reference bound to an lvalue";9162break;91639164case FK_ReferenceInitDropsQualifiers:9165OS << "reference initialization drops qualifiers";9166break;91679168case FK_ReferenceAddrspaceMismatchTemporary:9169OS << "reference with mismatching address space bound to temporary";9170break;91719172case FK_ReferenceInitFailed:9173OS << "reference initialization failed";9174break;91759176case FK_ConversionFailed:9177OS << "conversion failed";9178break;91799180case FK_ConversionFromPropertyFailed:9181OS << "conversion from property failed";9182break;91839184case FK_TooManyInitsForScalar:9185OS << "too many initializers for scalar";9186break;91879188case FK_ParenthesizedListInitForScalar:9189OS << "parenthesized list init for reference";9190break;91919192case FK_ReferenceBindingToInitList:9193OS << "referencing binding to initializer list";9194break;91959196case FK_InitListBadDestinationType:9197OS << "initializer list for non-aggregate, non-scalar type";9198break;91999200case FK_UserConversionOverloadFailed:9201OS << "overloading failed for user-defined conversion";9202break;92039204case FK_ConstructorOverloadFailed:9205OS << "constructor overloading failed";9206break;92079208case FK_DefaultInitOfConst:9209OS << "default initialization of a const variable";9210break;92119212case FK_Incomplete:9213OS << "initialization of incomplete type";9214break;92159216case FK_ListInitializationFailed:9217OS << "list initialization checker failure";9218break;92199220case FK_VariableLengthArrayHasInitializer:9221OS << "variable length array has an initializer";9222break;92239224case FK_PlaceholderType:9225OS << "initializer expression isn't contextually valid";9226break;92279228case FK_ListConstructorOverloadFailed:9229OS << "list constructor overloading failed";9230break;92319232case FK_ExplicitConstructor:9233OS << "list copy initialization chose explicit constructor";9234break;92359236case FK_ParenthesizedListInitFailed:9237OS << "parenthesized list initialization failed";9238break;92399240case FK_DesignatedInitForNonAggregate:9241OS << "designated initializer for non-aggregate type";9242break;9243}9244OS << '\n';9245return;9246}92479248case DependentSequence:9249OS << "Dependent sequence\n";9250return;92519252case NormalSequence:9253OS << "Normal sequence: ";9254break;9255}92569257for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {9258if (S != step_begin()) {9259OS << " -> ";9260}92619262switch (S->Kind) {9263case SK_ResolveAddressOfOverloadedFunction:9264OS << "resolve address of overloaded function";9265break;92669267case SK_CastDerivedToBasePRValue:9268OS << "derived-to-base (prvalue)";9269break;92709271case SK_CastDerivedToBaseXValue:9272OS << "derived-to-base (xvalue)";9273break;92749275case SK_CastDerivedToBaseLValue:9276OS << "derived-to-base (lvalue)";9277break;92789279case SK_BindReference:9280OS << "bind reference to lvalue";9281break;92829283case SK_BindReferenceToTemporary:9284OS << "bind reference to a temporary";9285break;92869287case SK_FinalCopy:9288OS << "final copy in class direct-initialization";9289break;92909291case SK_ExtraneousCopyToTemporary:9292OS << "extraneous C++03 copy to temporary";9293break;92949295case SK_UserConversion:9296OS << "user-defined conversion via " << *S->Function.Function;9297break;92989299case SK_QualificationConversionPRValue:9300OS << "qualification conversion (prvalue)";9301break;93029303case SK_QualificationConversionXValue:9304OS << "qualification conversion (xvalue)";9305break;93069307case SK_QualificationConversionLValue:9308OS << "qualification conversion (lvalue)";9309break;93109311case SK_FunctionReferenceConversion:9312OS << "function reference conversion";9313break;93149315case SK_AtomicConversion:9316OS << "non-atomic-to-atomic conversion";9317break;93189319case SK_ConversionSequence:9320OS << "implicit conversion sequence (";9321S->ICS->dump(); // FIXME: use OS9322OS << ")";9323break;93249325case SK_ConversionSequenceNoNarrowing:9326OS << "implicit conversion sequence with narrowing prohibited (";9327S->ICS->dump(); // FIXME: use OS9328OS << ")";9329break;93309331case SK_ListInitialization:9332OS << "list aggregate initialization";9333break;93349335case SK_UnwrapInitList:9336OS << "unwrap reference initializer list";9337break;93389339case SK_RewrapInitList:9340OS << "rewrap reference initializer list";9341break;93429343case SK_ConstructorInitialization:9344OS << "constructor initialization";9345break;93469347case SK_ConstructorInitializationFromList:9348OS << "list initialization via constructor";9349break;93509351case SK_ZeroInitialization:9352OS << "zero initialization";9353break;93549355case SK_CAssignment:9356OS << "C assignment";9357break;93589359case SK_StringInit:9360OS << "string initialization";9361break;93629363case SK_ObjCObjectConversion:9364OS << "Objective-C object conversion";9365break;93669367case SK_ArrayLoopIndex:9368OS << "indexing for array initialization loop";9369break;93709371case SK_ArrayLoopInit:9372OS << "array initialization loop";9373break;93749375case SK_ArrayInit:9376OS << "array initialization";9377break;93789379case SK_GNUArrayInit:9380OS << "array initialization (GNU extension)";9381break;93829383case SK_ParenthesizedArrayInit:9384OS << "parenthesized array initialization";9385break;93869387case SK_PassByIndirectCopyRestore:9388OS << "pass by indirect copy and restore";9389break;93909391case SK_PassByIndirectRestore:9392OS << "pass by indirect restore";9393break;93949395case SK_ProduceObjCObject:9396OS << "Objective-C object retension";9397break;93989399case SK_StdInitializerList:9400OS << "std::initializer_list from initializer list";9401break;94029403case SK_StdInitializerListConstructorCall:9404OS << "list initialization from std::initializer_list";9405break;94069407case SK_OCLSamplerInit:9408OS << "OpenCL sampler_t from integer constant";9409break;94109411case SK_OCLZeroOpaqueType:9412OS << "OpenCL opaque type from zero";9413break;9414case SK_ParenthesizedListInit:9415OS << "initialization from a parenthesized list of values";9416break;9417}94189419OS << " [" << S->Type << ']';9420}94219422OS << '\n';9423}94249425void InitializationSequence::dump() const {9426dump(llvm::errs());9427}94289429static void DiagnoseNarrowingInInitList(Sema &S,9430const ImplicitConversionSequence &ICS,9431QualType PreNarrowingType,9432QualType EntityType,9433const Expr *PostInit) {9434const StandardConversionSequence *SCS = nullptr;9435switch (ICS.getKind()) {9436case ImplicitConversionSequence::StandardConversion:9437SCS = &ICS.Standard;9438break;9439case ImplicitConversionSequence::UserDefinedConversion:9440SCS = &ICS.UserDefined.After;9441break;9442case ImplicitConversionSequence::AmbiguousConversion:9443case ImplicitConversionSequence::StaticObjectArgumentConversion:9444case ImplicitConversionSequence::EllipsisConversion:9445case ImplicitConversionSequence::BadConversion:9446return;9447}94489449auto MakeDiag = [&](bool IsConstRef, unsigned DefaultDiagID,9450unsigned ConstRefDiagID, unsigned WarnDiagID) {9451unsigned DiagID;9452auto &L = S.getLangOpts();9453if (L.CPlusPlus11 &&9454(!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015)))9455DiagID = IsConstRef ? ConstRefDiagID : DefaultDiagID;9456else9457DiagID = WarnDiagID;9458return S.Diag(PostInit->getBeginLoc(), DiagID)9459<< PostInit->getSourceRange();9460};94619462// C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.9463APValue ConstantValue;9464QualType ConstantType;9465switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,9466ConstantType)) {9467case NK_Not_Narrowing:9468case NK_Dependent_Narrowing:9469// No narrowing occurred.9470return;94719472case NK_Type_Narrowing: {9473// This was a floating-to-integer conversion, which is always considered a9474// narrowing conversion even if the value is a constant and can be9475// represented exactly as an integer.9476QualType T = EntityType.getNonReferenceType();9477MakeDiag(T != EntityType, diag::ext_init_list_type_narrowing,9478diag::ext_init_list_type_narrowing_const_reference,9479diag::warn_init_list_type_narrowing)9480<< PreNarrowingType.getLocalUnqualifiedType()9481<< T.getLocalUnqualifiedType();9482break;9483}94849485case NK_Constant_Narrowing: {9486// A constant value was narrowed.9487MakeDiag(EntityType.getNonReferenceType() != EntityType,9488diag::ext_init_list_constant_narrowing,9489diag::ext_init_list_constant_narrowing_const_reference,9490diag::warn_init_list_constant_narrowing)9491<< ConstantValue.getAsString(S.getASTContext(), ConstantType)9492<< EntityType.getNonReferenceType().getLocalUnqualifiedType();9493break;9494}94959496case NK_Variable_Narrowing: {9497// A variable's value may have been narrowed.9498MakeDiag(EntityType.getNonReferenceType() != EntityType,9499diag::ext_init_list_variable_narrowing,9500diag::ext_init_list_variable_narrowing_const_reference,9501diag::warn_init_list_variable_narrowing)9502<< PreNarrowingType.getLocalUnqualifiedType()9503<< EntityType.getNonReferenceType().getLocalUnqualifiedType();9504break;9505}9506}95079508SmallString<128> StaticCast;9509llvm::raw_svector_ostream OS(StaticCast);9510OS << "static_cast<";9511if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {9512// It's important to use the typedef's name if there is one so that the9513// fixit doesn't break code using types like int64_t.9514//9515// FIXME: This will break if the typedef requires qualification. But9516// getQualifiedNameAsString() includes non-machine-parsable components.9517OS << *TT->getDecl();9518} else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())9519OS << BT->getName(S.getLangOpts());9520else {9521// Oops, we didn't find the actual type of the variable. Don't emit a fixit9522// with a broken cast.9523return;9524}9525OS << ">(";9526S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence)9527<< PostInit->getSourceRange()9528<< FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str())9529<< FixItHint::CreateInsertion(9530S.getLocForEndOfToken(PostInit->getEndLoc()), ")");9531}95329533static void CheckC23ConstexprInitConversion(Sema &S, QualType FromType,9534QualType ToType, Expr *Init) {9535assert(S.getLangOpts().C23);9536ImplicitConversionSequence ICS = S.TryImplicitConversion(9537Init->IgnoreParenImpCasts(), ToType, /*SuppressUserConversions*/ false,9538Sema::AllowedExplicit::None,9539/*InOverloadResolution*/ false,9540/*CStyle*/ false,9541/*AllowObjCWritebackConversion=*/false);95429543if (!ICS.isStandard())9544return;95459546APValue Value;9547QualType PreNarrowingType;9548// Reuse C++ narrowing check.9549switch (ICS.Standard.getNarrowingKind(9550S.Context, Init, Value, PreNarrowingType,9551/*IgnoreFloatToIntegralConversion*/ false)) {9552// The value doesn't fit.9553case NK_Constant_Narrowing:9554S.Diag(Init->getBeginLoc(), diag::err_c23_constexpr_init_not_representable)9555<< Value.getAsString(S.Context, PreNarrowingType) << ToType;9556return;95579558// Conversion to a narrower type.9559case NK_Type_Narrowing:9560S.Diag(Init->getBeginLoc(), diag::err_c23_constexpr_init_type_mismatch)9561<< ToType << FromType;9562return;95639564// Since we only reuse narrowing check for C23 constexpr variables here, we're9565// not really interested in these cases.9566case NK_Dependent_Narrowing:9567case NK_Variable_Narrowing:9568case NK_Not_Narrowing:9569return;9570}9571llvm_unreachable("unhandled case in switch");9572}95739574static void CheckC23ConstexprInitStringLiteral(const StringLiteral *SE,9575Sema &SemaRef, QualType &TT) {9576assert(SemaRef.getLangOpts().C23);9577// character that string literal contains fits into TT - target type.9578const ArrayType *AT = SemaRef.Context.getAsArrayType(TT);9579QualType CharType = AT->getElementType();9580uint32_t BitWidth = SemaRef.Context.getTypeSize(CharType);9581bool isUnsigned = CharType->isUnsignedIntegerType();9582llvm::APSInt Value(BitWidth, isUnsigned);9583for (unsigned I = 0, N = SE->getLength(); I != N; ++I) {9584int64_t C = SE->getCodeUnitS(I, SemaRef.Context.getCharWidth());9585Value = C;9586if (Value != C) {9587SemaRef.Diag(SemaRef.getLocationOfStringLiteralByte(SE, I),9588diag::err_c23_constexpr_init_not_representable)9589<< C << CharType;9590return;9591}9592}9593return;9594}95959596//===----------------------------------------------------------------------===//9597// Initialization helper functions9598//===----------------------------------------------------------------------===//9599bool9600Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,9601ExprResult Init) {9602if (Init.isInvalid())9603return false;96049605Expr *InitE = Init.get();9606assert(InitE && "No initialization expression");96079608InitializationKind Kind =9609InitializationKind::CreateCopy(InitE->getBeginLoc(), SourceLocation());9610InitializationSequence Seq(*this, Entity, Kind, InitE);9611return !Seq.Failed();9612}96139614ExprResult9615Sema::PerformCopyInitialization(const InitializedEntity &Entity,9616SourceLocation EqualLoc,9617ExprResult Init,9618bool TopLevelOfInitList,9619bool AllowExplicit) {9620if (Init.isInvalid())9621return ExprError();96229623Expr *InitE = Init.get();9624assert(InitE && "No initialization expression?");96259626if (EqualLoc.isInvalid())9627EqualLoc = InitE->getBeginLoc();96289629InitializationKind Kind = InitializationKind::CreateCopy(9630InitE->getBeginLoc(), EqualLoc, AllowExplicit);9631InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);96329633// Prevent infinite recursion when performing parameter copy-initialization.9634const bool ShouldTrackCopy =9635Entity.isParameterKind() && Seq.isConstructorInitialization();9636if (ShouldTrackCopy) {9637if (llvm::is_contained(CurrentParameterCopyTypes, Entity.getType())) {9638Seq.SetOverloadFailure(9639InitializationSequence::FK_ConstructorOverloadFailed,9640OR_No_Viable_Function);96419642// Try to give a meaningful diagnostic note for the problematic9643// constructor.9644const auto LastStep = Seq.step_end() - 1;9645assert(LastStep->Kind ==9646InitializationSequence::SK_ConstructorInitialization);9647const FunctionDecl *Function = LastStep->Function.Function;9648auto Candidate =9649llvm::find_if(Seq.getFailedCandidateSet(),9650[Function](const OverloadCandidate &Candidate) -> bool {9651return Candidate.Viable &&9652Candidate.Function == Function &&9653Candidate.Conversions.size() > 0;9654});9655if (Candidate != Seq.getFailedCandidateSet().end() &&9656Function->getNumParams() > 0) {9657Candidate->Viable = false;9658Candidate->FailureKind = ovl_fail_bad_conversion;9659Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion,9660InitE,9661Function->getParamDecl(0)->getType());9662}9663}9664CurrentParameterCopyTypes.push_back(Entity.getType());9665}96669667ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);96689669if (ShouldTrackCopy)9670CurrentParameterCopyTypes.pop_back();96719672return Result;9673}96749675/// Determine whether RD is, or is derived from, a specialization of CTD.9676static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD,9677ClassTemplateDecl *CTD) {9678auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {9679auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);9680return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);9681};9682return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));9683}96849685QualType Sema::DeduceTemplateSpecializationFromInitializer(9686TypeSourceInfo *TSInfo, const InitializedEntity &Entity,9687const InitializationKind &Kind, MultiExprArg Inits) {9688auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(9689TSInfo->getType()->getContainedDeducedType());9690assert(DeducedTST && "not a deduced template specialization type");96919692auto TemplateName = DeducedTST->getTemplateName();9693if (TemplateName.isDependent())9694return SubstAutoTypeDependent(TSInfo->getType());96959696// We can only perform deduction for class templates or alias templates.9697auto *Template =9698dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());9699TemplateDecl *LookupTemplateDecl = Template;9700if (!Template) {9701if (auto *AliasTemplate = dyn_cast_or_null<TypeAliasTemplateDecl>(9702TemplateName.getAsTemplateDecl())) {9703Diag(Kind.getLocation(),9704diag::warn_cxx17_compat_ctad_for_alias_templates);9705LookupTemplateDecl = AliasTemplate;9706auto UnderlyingType = AliasTemplate->getTemplatedDecl()9707->getUnderlyingType()9708.getCanonicalType();9709// C++ [over.match.class.deduct#3]: ..., the defining-type-id of A must be9710// of the form9711// [typename] [nested-name-specifier] [template] simple-template-id9712if (const auto *TST =9713UnderlyingType->getAs<TemplateSpecializationType>()) {9714Template = dyn_cast_or_null<ClassTemplateDecl>(9715TST->getTemplateName().getAsTemplateDecl());9716} else if (const auto *RT = UnderlyingType->getAs<RecordType>()) {9717// Cases where template arguments in the RHS of the alias are not9718// dependent. e.g.9719// using AliasFoo = Foo<bool>;9720if (const auto *CTSD = llvm::dyn_cast<ClassTemplateSpecializationDecl>(9721RT->getAsCXXRecordDecl()))9722Template = CTSD->getSpecializedTemplate();9723}9724}9725}9726if (!Template) {9727Diag(Kind.getLocation(),9728diag::err_deduced_non_class_or_alias_template_specialization_type)9729<< (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName;9730if (auto *TD = TemplateName.getAsTemplateDecl())9731NoteTemplateLocation(*TD);9732return QualType();9733}97349735// Can't deduce from dependent arguments.9736if (Expr::hasAnyTypeDependentArguments(Inits)) {9737Diag(TSInfo->getTypeLoc().getBeginLoc(),9738diag::warn_cxx14_compat_class_template_argument_deduction)9739<< TSInfo->getTypeLoc().getSourceRange() << 0;9740return SubstAutoTypeDependent(TSInfo->getType());9741}97429743// FIXME: Perform "exact type" matching first, per CWG discussion?9744// Or implement this via an implied 'T(T) -> T' deduction guide?97459746// Look up deduction guides, including those synthesized from constructors.9747//9748// C++1z [over.match.class.deduct]p1:9749// A set of functions and function templates is formed comprising:9750// - For each constructor of the class template designated by the9751// template-name, a function template [...]9752// - For each deduction-guide, a function or function template [...]9753DeclarationNameInfo NameInfo(9754Context.DeclarationNames.getCXXDeductionGuideName(LookupTemplateDecl),9755TSInfo->getTypeLoc().getEndLoc());9756LookupResult Guides(*this, NameInfo, LookupOrdinaryName);9757LookupQualifiedName(Guides, LookupTemplateDecl->getDeclContext());97589759// FIXME: Do not diagnose inaccessible deduction guides. The standard isn't9760// clear on this, but they're not found by name so access does not apply.9761Guides.suppressDiagnostics();97629763// Figure out if this is list-initialization.9764InitListExpr *ListInit =9765(Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)9766? dyn_cast<InitListExpr>(Inits[0])9767: nullptr;97689769// C++1z [over.match.class.deduct]p1:9770// Initialization and overload resolution are performed as described in9771// [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]9772// (as appropriate for the type of initialization performed) for an object9773// of a hypothetical class type, where the selected functions and function9774// templates are considered to be the constructors of that class type9775//9776// Since we know we're initializing a class type of a type unrelated to that9777// of the initializer, this reduces to something fairly reasonable.9778OverloadCandidateSet Candidates(Kind.getLocation(),9779OverloadCandidateSet::CSK_Normal);9780OverloadCandidateSet::iterator Best;97819782bool AllowExplicit = !Kind.isCopyInit() || ListInit;97839784// Return true if the candidate is added successfully, false otherwise.9785auto addDeductionCandidate = [&](FunctionTemplateDecl *TD,9786CXXDeductionGuideDecl *GD,9787DeclAccessPair FoundDecl,9788bool OnlyListConstructors,9789bool AllowAggregateDeductionCandidate) {9790// C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)9791// For copy-initialization, the candidate functions are all the9792// converting constructors (12.3.1) of that class.9793// C++ [over.match.copy]p1: (non-list copy-initialization from class)9794// The converting constructors of T are candidate functions.9795if (!AllowExplicit) {9796// Overload resolution checks whether the deduction guide is declared9797// explicit for us.97989799// When looking for a converting constructor, deduction guides that9800// could never be called with one argument are not interesting to9801// check or note.9802if (GD->getMinRequiredArguments() > 1 ||9803(GD->getNumParams() == 0 && !GD->isVariadic()))9804return;9805}98069807// C++ [over.match.list]p1.1: (first phase list initialization)9808// Initially, the candidate functions are the initializer-list9809// constructors of the class T9810if (OnlyListConstructors && !isInitListConstructor(GD))9811return;98129813if (!AllowAggregateDeductionCandidate &&9814GD->getDeductionCandidateKind() == DeductionCandidate::Aggregate)9815return;98169817// C++ [over.match.list]p1.2: (second phase list initialization)9818// the candidate functions are all the constructors of the class T9819// C++ [over.match.ctor]p1: (all other cases)9820// the candidate functions are all the constructors of the class of9821// the object being initialized98229823// C++ [over.best.ics]p4:9824// When [...] the constructor [...] is a candidate by9825// - [over.match.copy] (in all cases)9826if (TD) {9827SmallVector<Expr *, 8> TmpInits;9828for (Expr *E : Inits)9829if (auto *DI = dyn_cast<DesignatedInitExpr>(E))9830TmpInits.push_back(DI->getInit());9831else9832TmpInits.push_back(E);9833AddTemplateOverloadCandidate(9834TD, FoundDecl, /*ExplicitArgs=*/nullptr, TmpInits, Candidates,9835/*SuppressUserConversions=*/false,9836/*PartialOverloading=*/false, AllowExplicit, ADLCallKind::NotADL,9837/*PO=*/{}, AllowAggregateDeductionCandidate);9838} else {9839AddOverloadCandidate(GD, FoundDecl, Inits, Candidates,9840/*SuppressUserConversions=*/false,9841/*PartialOverloading=*/false, AllowExplicit);9842}9843};98449845bool FoundDeductionGuide = false;98469847auto TryToResolveOverload =9848[&](bool OnlyListConstructors) -> OverloadingResult {9849Candidates.clear(OverloadCandidateSet::CSK_Normal);9850bool HasAnyDeductionGuide = false;98519852auto SynthesizeAggrGuide = [&](InitListExpr *ListInit) {9853auto *Pattern = Template;9854while (Pattern->getInstantiatedFromMemberTemplate()) {9855if (Pattern->isMemberSpecialization())9856break;9857Pattern = Pattern->getInstantiatedFromMemberTemplate();9858}98599860auto *RD = cast<CXXRecordDecl>(Pattern->getTemplatedDecl());9861if (!(RD->getDefinition() && RD->isAggregate()))9862return;9863QualType Ty = Context.getRecordType(RD);9864SmallVector<QualType, 8> ElementTypes;98659866InitListChecker CheckInitList(*this, Entity, ListInit, Ty, ElementTypes);9867if (!CheckInitList.HadError()) {9868// C++ [over.match.class.deduct]p1.8:9869// if e_i is of array type and x_i is a braced-init-list, T_i is an9870// rvalue reference to the declared type of e_i and9871// C++ [over.match.class.deduct]p1.9:9872// if e_i is of array type and x_i is a string-literal, T_i is an9873// lvalue reference to the const-qualified declared type of e_i and9874// C++ [over.match.class.deduct]p1.10:9875// otherwise, T_i is the declared type of e_i9876for (int I = 0, E = ListInit->getNumInits();9877I < E && !isa<PackExpansionType>(ElementTypes[I]); ++I)9878if (ElementTypes[I]->isArrayType()) {9879if (isa<InitListExpr, DesignatedInitExpr>(ListInit->getInit(I)))9880ElementTypes[I] = Context.getRValueReferenceType(ElementTypes[I]);9881else if (isa<StringLiteral>(9882ListInit->getInit(I)->IgnoreParenImpCasts()))9883ElementTypes[I] =9884Context.getLValueReferenceType(ElementTypes[I].withConst());9885}98869887if (FunctionTemplateDecl *TD =9888DeclareAggregateDeductionGuideFromInitList(9889LookupTemplateDecl, ElementTypes,9890TSInfo->getTypeLoc().getEndLoc())) {9891auto *GD = cast<CXXDeductionGuideDecl>(TD->getTemplatedDecl());9892addDeductionCandidate(TD, GD, DeclAccessPair::make(TD, AS_public),9893OnlyListConstructors,9894/*AllowAggregateDeductionCandidate=*/true);9895HasAnyDeductionGuide = true;9896}9897}9898};98999900for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {9901NamedDecl *D = (*I)->getUnderlyingDecl();9902if (D->isInvalidDecl())9903continue;99049905auto *TD = dyn_cast<FunctionTemplateDecl>(D);9906auto *GD = dyn_cast_if_present<CXXDeductionGuideDecl>(9907TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));9908if (!GD)9909continue;99109911if (!GD->isImplicit())9912HasAnyDeductionGuide = true;99139914addDeductionCandidate(TD, GD, I.getPair(), OnlyListConstructors,9915/*AllowAggregateDeductionCandidate=*/false);9916}99179918// C++ [over.match.class.deduct]p1.4:9919// if C is defined and its definition satisfies the conditions for an9920// aggregate class ([dcl.init.aggr]) with the assumption that any9921// dependent base class has no virtual functions and no virtual base9922// classes, and the initializer is a non-empty braced-init-list or9923// parenthesized expression-list, and there are no deduction-guides for9924// C, the set contains an additional function template, called the9925// aggregate deduction candidate, defined as follows.9926if (getLangOpts().CPlusPlus20 && !HasAnyDeductionGuide) {9927if (ListInit && ListInit->getNumInits()) {9928SynthesizeAggrGuide(ListInit);9929} else if (Inits.size()) { // parenthesized expression-list9930// Inits are expressions inside the parentheses. We don't have9931// the parentheses source locations, use the begin/end of Inits as the9932// best heuristic.9933InitListExpr TempListInit(getASTContext(), Inits.front()->getBeginLoc(),9934Inits, Inits.back()->getEndLoc());9935SynthesizeAggrGuide(&TempListInit);9936}9937}99389939FoundDeductionGuide = FoundDeductionGuide || HasAnyDeductionGuide;99409941return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);9942};99439944OverloadingResult Result = OR_No_Viable_Function;99459946// C++11 [over.match.list]p1, per DR1467: for list-initialization, first9947// try initializer-list constructors.9948if (ListInit) {9949bool TryListConstructors = true;99509951// Try list constructors unless the list is empty and the class has one or9952// more default constructors, in which case those constructors win.9953if (!ListInit->getNumInits()) {9954for (NamedDecl *D : Guides) {9955auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());9956if (FD && FD->getMinRequiredArguments() == 0) {9957TryListConstructors = false;9958break;9959}9960}9961} else if (ListInit->getNumInits() == 1) {9962// C++ [over.match.class.deduct]:9963// As an exception, the first phase in [over.match.list] (considering9964// initializer-list constructors) is omitted if the initializer list9965// consists of a single expression of type cv U, where U is a9966// specialization of C or a class derived from a specialization of C.9967Expr *E = ListInit->getInit(0);9968auto *RD = E->getType()->getAsCXXRecordDecl();9969if (!isa<InitListExpr>(E) && RD &&9970isCompleteType(Kind.getLocation(), E->getType()) &&9971isOrIsDerivedFromSpecializationOf(RD, Template))9972TryListConstructors = false;9973}99749975if (TryListConstructors)9976Result = TryToResolveOverload(/*OnlyListConstructor*/true);9977// Then unwrap the initializer list and try again considering all9978// constructors.9979Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());9980}99819982// If list-initialization fails, or if we're doing any other kind of9983// initialization, we (eventually) consider constructors.9984if (Result == OR_No_Viable_Function)9985Result = TryToResolveOverload(/*OnlyListConstructor*/false);99869987switch (Result) {9988case OR_Ambiguous:9989// FIXME: For list-initialization candidates, it'd usually be better to9990// list why they were not viable when given the initializer list itself as9991// an argument.9992Candidates.NoteCandidates(9993PartialDiagnosticAt(9994Kind.getLocation(),9995PDiag(diag::err_deduced_class_template_ctor_ambiguous)9996<< TemplateName),9997*this, OCD_AmbiguousCandidates, Inits);9998return QualType();999910000case OR_No_Viable_Function: {10001CXXRecordDecl *Primary =10002cast<ClassTemplateDecl>(Template)->getTemplatedDecl();10003bool Complete =10004isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary));10005Candidates.NoteCandidates(10006PartialDiagnosticAt(10007Kind.getLocation(),10008PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable10009: diag::err_deduced_class_template_incomplete)10010<< TemplateName << !Guides.empty()),10011*this, OCD_AllCandidates, Inits);10012return QualType();10013}1001410015case OR_Deleted: {10016// FIXME: There are no tests for this diagnostic, and it doesn't seem10017// like we ever get here; attempts to trigger this seem to yield a10018// generic c'all to deleted function' diagnostic instead.10019Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)10020<< TemplateName;10021NoteDeletedFunction(Best->Function);10022return QualType();10023}1002410025case OR_Success:10026// C++ [over.match.list]p1:10027// In copy-list-initialization, if an explicit constructor is chosen, the10028// initialization is ill-formed.10029if (Kind.isCopyInit() && ListInit &&10030cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {10031bool IsDeductionGuide = !Best->Function->isImplicit();10032Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)10033<< TemplateName << IsDeductionGuide;10034Diag(Best->Function->getLocation(),10035diag::note_explicit_ctor_deduction_guide_here)10036<< IsDeductionGuide;10037return QualType();10038}1003910040// Make sure we didn't select an unusable deduction guide, and mark it10041// as referenced.10042DiagnoseUseOfDecl(Best->FoundDecl, Kind.getLocation());10043MarkFunctionReferenced(Kind.getLocation(), Best->Function);10044break;10045}1004610047// C++ [dcl.type.class.deduct]p1:10048// The placeholder is replaced by the return type of the function selected10049// by overload resolution for class template deduction.10050QualType DeducedType =10051SubstAutoType(TSInfo->getType(), Best->Function->getReturnType());10052Diag(TSInfo->getTypeLoc().getBeginLoc(),10053diag::warn_cxx14_compat_class_template_argument_deduction)10054<< TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType;1005510056// Warn if CTAD was used on a type that does not have any user-defined10057// deduction guides.10058if (!FoundDeductionGuide) {10059Diag(TSInfo->getTypeLoc().getBeginLoc(),10060diag::warn_ctad_maybe_unsupported)10061<< TemplateName;10062Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported);10063}1006410065return DeducedType;10066}100671006810069