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