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