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