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