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