1 //===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for initializers. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/ASTContext.h" 14 #include "clang/AST/DeclObjC.h" 15 #include "clang/AST/ExprCXX.h" 16 #include "clang/AST/ExprObjC.h" 17 #include "clang/AST/ExprOpenMP.h" 18 #include "clang/AST/TypeLoc.h" 19 #include "clang/Basic/CharInfo.h" 20 #include "clang/Basic/SourceManager.h" 21 #include "clang/Basic/TargetInfo.h" 22 #include "clang/Sema/Designator.h" 23 #include "clang/Sema/Initialization.h" 24 #include "clang/Sema/Lookup.h" 25 #include "clang/Sema/SemaInternal.h" 26 #include "llvm/ADT/APInt.h" 27 #include "llvm/ADT/PointerIntPair.h" 28 #include "llvm/ADT/SmallString.h" 29 #include "llvm/Support/ErrorHandling.h" 30 #include "llvm/Support/raw_ostream.h" 31 32 using namespace clang; 33 34 //===----------------------------------------------------------------------===// 35 // Sema Initialization Checking 36 //===----------------------------------------------------------------------===// 37 38 /// Check whether T is compatible with a wide character type (wchar_t, 39 /// char16_t or char32_t). 40 static bool IsWideCharCompatible(QualType T, ASTContext &Context) { 41 if (Context.typesAreCompatible(Context.getWideCharType(), T)) 42 return true; 43 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) { 44 return Context.typesAreCompatible(Context.Char16Ty, T) || 45 Context.typesAreCompatible(Context.Char32Ty, T); 46 } 47 return false; 48 } 49 50 enum StringInitFailureKind { 51 SIF_None, 52 SIF_NarrowStringIntoWideChar, 53 SIF_WideStringIntoChar, 54 SIF_IncompatWideStringIntoWideChar, 55 SIF_UTF8StringIntoPlainChar, 56 SIF_PlainStringIntoUTF8Char, 57 SIF_Other 58 }; 59 60 /// Check whether the array of type AT can be initialized by the Init 61 /// expression by means of string initialization. Returns SIF_None if so, 62 /// otherwise returns a StringInitFailureKind that describes why the 63 /// initialization would not work. 64 static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT, 65 ASTContext &Context) { 66 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT)) 67 return SIF_Other; 68 69 // See if this is a string literal or @encode. 70 Init = Init->IgnoreParens(); 71 72 // Handle @encode, which is a narrow string. 73 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType()) 74 return SIF_None; 75 76 // Otherwise we can only handle string literals. 77 StringLiteral *SL = dyn_cast<StringLiteral>(Init); 78 if (!SL) 79 return SIF_Other; 80 81 const QualType ElemTy = 82 Context.getCanonicalType(AT->getElementType()).getUnqualifiedType(); 83 84 switch (SL->getKind()) { 85 case StringLiteral::UTF8: 86 // char8_t array can be initialized with a UTF-8 string. 87 if (ElemTy->isChar8Type()) 88 return SIF_None; 89 LLVM_FALLTHROUGH; 90 case StringLiteral::Ascii: 91 // char array can be initialized with a narrow string. 92 // Only allow char x[] = "foo"; not char x[] = L"foo"; 93 if (ElemTy->isCharType()) 94 return (SL->getKind() == StringLiteral::UTF8 && 95 Context.getLangOpts().Char8) 96 ? SIF_UTF8StringIntoPlainChar 97 : SIF_None; 98 if (ElemTy->isChar8Type()) 99 return SIF_PlainStringIntoUTF8Char; 100 if (IsWideCharCompatible(ElemTy, Context)) 101 return SIF_NarrowStringIntoWideChar; 102 return SIF_Other; 103 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15: 104 // "An array with element type compatible with a qualified or unqualified 105 // version of wchar_t, char16_t, or char32_t may be initialized by a wide 106 // string literal with the corresponding encoding prefix (L, u, or U, 107 // respectively), optionally enclosed in braces. 108 case StringLiteral::UTF16: 109 if (Context.typesAreCompatible(Context.Char16Ty, ElemTy)) 110 return SIF_None; 111 if (ElemTy->isCharType() || ElemTy->isChar8Type()) 112 return SIF_WideStringIntoChar; 113 if (IsWideCharCompatible(ElemTy, Context)) 114 return SIF_IncompatWideStringIntoWideChar; 115 return SIF_Other; 116 case StringLiteral::UTF32: 117 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy)) 118 return SIF_None; 119 if (ElemTy->isCharType() || ElemTy->isChar8Type()) 120 return SIF_WideStringIntoChar; 121 if (IsWideCharCompatible(ElemTy, Context)) 122 return SIF_IncompatWideStringIntoWideChar; 123 return SIF_Other; 124 case StringLiteral::Wide: 125 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy)) 126 return SIF_None; 127 if (ElemTy->isCharType() || ElemTy->isChar8Type()) 128 return SIF_WideStringIntoChar; 129 if (IsWideCharCompatible(ElemTy, Context)) 130 return SIF_IncompatWideStringIntoWideChar; 131 return SIF_Other; 132 } 133 134 llvm_unreachable("missed a StringLiteral kind?"); 135 } 136 137 static StringInitFailureKind IsStringInit(Expr *init, QualType declType, 138 ASTContext &Context) { 139 const ArrayType *arrayType = Context.getAsArrayType(declType); 140 if (!arrayType) 141 return SIF_Other; 142 return IsStringInit(init, arrayType, Context); 143 } 144 145 bool Sema::IsStringInit(Expr *Init, const ArrayType *AT) { 146 return ::IsStringInit(Init, AT, Context) == SIF_None; 147 } 148 149 /// Update the type of a string literal, including any surrounding parentheses, 150 /// to match the type of the object which it is initializing. 151 static void updateStringLiteralType(Expr *E, QualType Ty) { 152 while (true) { 153 E->setType(Ty); 154 E->setValueKind(VK_RValue); 155 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E)) { 156 break; 157 } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 158 E = PE->getSubExpr(); 159 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 160 assert(UO->getOpcode() == UO_Extension); 161 E = UO->getSubExpr(); 162 } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) { 163 E = GSE->getResultExpr(); 164 } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) { 165 E = CE->getChosenSubExpr(); 166 } else { 167 llvm_unreachable("unexpected expr in string literal init"); 168 } 169 } 170 } 171 172 /// Fix a compound literal initializing an array so it's correctly marked 173 /// as an rvalue. 174 static void updateGNUCompoundLiteralRValue(Expr *E) { 175 while (true) { 176 E->setValueKind(VK_RValue); 177 if (isa<CompoundLiteralExpr>(E)) { 178 break; 179 } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 180 E = PE->getSubExpr(); 181 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 182 assert(UO->getOpcode() == UO_Extension); 183 E = UO->getSubExpr(); 184 } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) { 185 E = GSE->getResultExpr(); 186 } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) { 187 E = CE->getChosenSubExpr(); 188 } else { 189 llvm_unreachable("unexpected expr in array compound literal init"); 190 } 191 } 192 } 193 194 static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT, 195 Sema &S) { 196 // Get the length of the string as parsed. 197 auto *ConstantArrayTy = 198 cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe()); 199 uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue(); 200 201 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) { 202 // C99 6.7.8p14. We have an array of character type with unknown size 203 // being initialized to a string literal. 204 llvm::APInt ConstVal(32, StrLength); 205 // Return a new array type (C99 6.7.8p22). 206 DeclT = S.Context.getConstantArrayType(IAT->getElementType(), 207 ConstVal, nullptr, 208 ArrayType::Normal, 0); 209 updateStringLiteralType(Str, DeclT); 210 return; 211 } 212 213 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT); 214 215 // We have an array of character type with known size. However, 216 // the size may be smaller or larger than the string we are initializing. 217 // FIXME: Avoid truncation for 64-bit length strings. 218 if (S.getLangOpts().CPlusPlus) { 219 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) { 220 // For Pascal strings it's OK to strip off the terminating null character, 221 // so the example below is valid: 222 // 223 // unsigned char a[2] = "\pa"; 224 if (SL->isPascal()) 225 StrLength--; 226 } 227 228 // [dcl.init.string]p2 229 if (StrLength > CAT->getSize().getZExtValue()) 230 S.Diag(Str->getBeginLoc(), 231 diag::err_initializer_string_for_char_array_too_long) 232 << Str->getSourceRange(); 233 } else { 234 // C99 6.7.8p14. 235 if (StrLength-1 > CAT->getSize().getZExtValue()) 236 S.Diag(Str->getBeginLoc(), 237 diag::ext_initializer_string_for_char_array_too_long) 238 << Str->getSourceRange(); 239 } 240 241 // Set the type to the actual size that we are initializing. If we have 242 // something like: 243 // char x[1] = "foo"; 244 // then this will set the string literal's type to char[1]. 245 updateStringLiteralType(Str, DeclT); 246 } 247 248 //===----------------------------------------------------------------------===// 249 // Semantic checking for initializer lists. 250 //===----------------------------------------------------------------------===// 251 252 namespace { 253 254 /// Semantic checking for initializer lists. 255 /// 256 /// The InitListChecker class contains a set of routines that each 257 /// handle the initialization of a certain kind of entity, e.g., 258 /// arrays, vectors, struct/union types, scalars, etc. The 259 /// InitListChecker itself performs a recursive walk of the subobject 260 /// structure of the type to be initialized, while stepping through 261 /// the initializer list one element at a time. The IList and Index 262 /// parameters to each of the Check* routines contain the active 263 /// (syntactic) initializer list and the index into that initializer 264 /// list that represents the current initializer. Each routine is 265 /// responsible for moving that Index forward as it consumes elements. 266 /// 267 /// Each Check* routine also has a StructuredList/StructuredIndex 268 /// arguments, which contains the current "structured" (semantic) 269 /// initializer list and the index into that initializer list where we 270 /// are copying initializers as we map them over to the semantic 271 /// list. Once we have completed our recursive walk of the subobject 272 /// structure, we will have constructed a full semantic initializer 273 /// list. 274 /// 275 /// C99 designators cause changes in the initializer list traversal, 276 /// because they make the initialization "jump" into a specific 277 /// subobject and then continue the initialization from that 278 /// point. CheckDesignatedInitializer() recursively steps into the 279 /// designated subobject and manages backing out the recursion to 280 /// initialize the subobjects after the one designated. 281 /// 282 /// If an initializer list contains any designators, we build a placeholder 283 /// structured list even in 'verify only' mode, so that we can track which 284 /// elements need 'empty' initializtion. 285 class InitListChecker { 286 Sema &SemaRef; 287 bool hadError = false; 288 bool VerifyOnly; // No diagnostics. 289 bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode. 290 bool InOverloadResolution; 291 InitListExpr *FullyStructuredList = nullptr; 292 NoInitExpr *DummyExpr = nullptr; 293 294 NoInitExpr *getDummyInit() { 295 if (!DummyExpr) 296 DummyExpr = new (SemaRef.Context) NoInitExpr(SemaRef.Context.VoidTy); 297 return DummyExpr; 298 } 299 300 void CheckImplicitInitList(const InitializedEntity &Entity, 301 InitListExpr *ParentIList, QualType T, 302 unsigned &Index, InitListExpr *StructuredList, 303 unsigned &StructuredIndex); 304 void CheckExplicitInitList(const InitializedEntity &Entity, 305 InitListExpr *IList, QualType &T, 306 InitListExpr *StructuredList, 307 bool TopLevelObject = false); 308 void CheckListElementTypes(const InitializedEntity &Entity, 309 InitListExpr *IList, QualType &DeclType, 310 bool SubobjectIsDesignatorContext, 311 unsigned &Index, 312 InitListExpr *StructuredList, 313 unsigned &StructuredIndex, 314 bool TopLevelObject = false); 315 void CheckSubElementType(const InitializedEntity &Entity, 316 InitListExpr *IList, QualType ElemType, 317 unsigned &Index, 318 InitListExpr *StructuredList, 319 unsigned &StructuredIndex, 320 bool DirectlyDesignated = false); 321 void CheckComplexType(const InitializedEntity &Entity, 322 InitListExpr *IList, QualType DeclType, 323 unsigned &Index, 324 InitListExpr *StructuredList, 325 unsigned &StructuredIndex); 326 void CheckScalarType(const InitializedEntity &Entity, 327 InitListExpr *IList, QualType DeclType, 328 unsigned &Index, 329 InitListExpr *StructuredList, 330 unsigned &StructuredIndex); 331 void CheckReferenceType(const InitializedEntity &Entity, 332 InitListExpr *IList, QualType DeclType, 333 unsigned &Index, 334 InitListExpr *StructuredList, 335 unsigned &StructuredIndex); 336 void CheckVectorType(const InitializedEntity &Entity, 337 InitListExpr *IList, QualType DeclType, unsigned &Index, 338 InitListExpr *StructuredList, 339 unsigned &StructuredIndex); 340 void CheckStructUnionTypes(const InitializedEntity &Entity, 341 InitListExpr *IList, QualType DeclType, 342 CXXRecordDecl::base_class_range Bases, 343 RecordDecl::field_iterator Field, 344 bool SubobjectIsDesignatorContext, unsigned &Index, 345 InitListExpr *StructuredList, 346 unsigned &StructuredIndex, 347 bool TopLevelObject = false); 348 void CheckArrayType(const InitializedEntity &Entity, 349 InitListExpr *IList, QualType &DeclType, 350 llvm::APSInt elementIndex, 351 bool SubobjectIsDesignatorContext, unsigned &Index, 352 InitListExpr *StructuredList, 353 unsigned &StructuredIndex); 354 bool CheckDesignatedInitializer(const InitializedEntity &Entity, 355 InitListExpr *IList, DesignatedInitExpr *DIE, 356 unsigned DesigIdx, 357 QualType &CurrentObjectType, 358 RecordDecl::field_iterator *NextField, 359 llvm::APSInt *NextElementIndex, 360 unsigned &Index, 361 InitListExpr *StructuredList, 362 unsigned &StructuredIndex, 363 bool FinishSubobjectInit, 364 bool TopLevelObject); 365 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, 366 QualType CurrentObjectType, 367 InitListExpr *StructuredList, 368 unsigned StructuredIndex, 369 SourceRange InitRange, 370 bool IsFullyOverwritten = false); 371 void UpdateStructuredListElement(InitListExpr *StructuredList, 372 unsigned &StructuredIndex, 373 Expr *expr); 374 InitListExpr *createInitListExpr(QualType CurrentObjectType, 375 SourceRange InitRange, 376 unsigned ExpectedNumInits); 377 int numArrayElements(QualType DeclType); 378 int numStructUnionElements(QualType DeclType); 379 380 ExprResult PerformEmptyInit(SourceLocation Loc, 381 const InitializedEntity &Entity); 382 383 /// Diagnose that OldInit (or part thereof) has been overridden by NewInit. 384 void diagnoseInitOverride(Expr *OldInit, SourceRange NewInitRange, 385 bool FullyOverwritten = true) { 386 // Overriding an initializer via a designator is valid with C99 designated 387 // initializers, but ill-formed with C++20 designated initializers. 388 unsigned DiagID = SemaRef.getLangOpts().CPlusPlus 389 ? diag::ext_initializer_overrides 390 : diag::warn_initializer_overrides; 391 392 if (InOverloadResolution && SemaRef.getLangOpts().CPlusPlus) { 393 // In overload resolution, we have to strictly enforce the rules, and so 394 // don't allow any overriding of prior initializers. This matters for a 395 // case such as: 396 // 397 // union U { int a, b; }; 398 // struct S { int a, b; }; 399 // void f(U), f(S); 400 // 401 // Here, f({.a = 1, .b = 2}) is required to call the struct overload. For 402 // consistency, we disallow all overriding of prior initializers in 403 // overload resolution, not only overriding of union members. 404 hadError = true; 405 } else if (OldInit->getType().isDestructedType() && !FullyOverwritten) { 406 // If we'll be keeping around the old initializer but overwriting part of 407 // the object it initialized, and that object is not trivially 408 // destructible, this can leak. Don't allow that, not even as an 409 // extension. 410 // 411 // FIXME: It might be reasonable to allow this in cases where the part of 412 // the initializer that we're overriding has trivial destruction. 413 DiagID = diag::err_initializer_overrides_destructed; 414 } else if (!OldInit->getSourceRange().isValid()) { 415 // We need to check on source range validity because the previous 416 // initializer does not have to be an explicit initializer. e.g., 417 // 418 // struct P { int a, b; }; 419 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 }; 420 // 421 // There is an overwrite taking place because the first braced initializer 422 // list "{ .a = 2 }" already provides value for .p.b (which is zero). 423 // 424 // Such overwrites are harmless, so we don't diagnose them. (Note that in 425 // C++, this cannot be reached unless we've already seen and diagnosed a 426 // different conformance issue, such as a mixture of designated and 427 // non-designated initializers or a multi-level designator.) 428 return; 429 } 430 431 if (!VerifyOnly) { 432 SemaRef.Diag(NewInitRange.getBegin(), DiagID) 433 << NewInitRange << FullyOverwritten << OldInit->getType(); 434 SemaRef.Diag(OldInit->getBeginLoc(), diag::note_previous_initializer) 435 << (OldInit->HasSideEffects(SemaRef.Context) && FullyOverwritten) 436 << OldInit->getSourceRange(); 437 } 438 } 439 440 // Explanation on the "FillWithNoInit" mode: 441 // 442 // Assume we have the following definitions (Case#1): 443 // struct P { char x[6][6]; } xp = { .x[1] = "bar" }; 444 // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' }; 445 // 446 // l.lp.x[1][0..1] should not be filled with implicit initializers because the 447 // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf". 448 // 449 // But if we have (Case#2): 450 // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } }; 451 // 452 // l.lp.x[1][0..1] are implicitly initialized and do not use values from the 453 // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0". 454 // 455 // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes" 456 // in the InitListExpr, the "holes" in Case#1 are filled not with empty 457 // initializers but with special "NoInitExpr" place holders, which tells the 458 // CodeGen not to generate any initializers for these parts. 459 void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base, 460 const InitializedEntity &ParentEntity, 461 InitListExpr *ILE, bool &RequiresSecondPass, 462 bool FillWithNoInit); 463 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field, 464 const InitializedEntity &ParentEntity, 465 InitListExpr *ILE, bool &RequiresSecondPass, 466 bool FillWithNoInit = false); 467 void FillInEmptyInitializations(const InitializedEntity &Entity, 468 InitListExpr *ILE, bool &RequiresSecondPass, 469 InitListExpr *OuterILE, unsigned OuterIndex, 470 bool FillWithNoInit = false); 471 bool CheckFlexibleArrayInit(const InitializedEntity &Entity, 472 Expr *InitExpr, FieldDecl *Field, 473 bool TopLevelObject); 474 void CheckEmptyInitializable(const InitializedEntity &Entity, 475 SourceLocation Loc); 476 477 public: 478 InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL, 479 QualType &T, bool VerifyOnly, bool TreatUnavailableAsInvalid, 480 bool InOverloadResolution = false); 481 bool HadError() { return hadError; } 482 483 // Retrieves the fully-structured initializer list used for 484 // semantic analysis and code generation. 485 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; } 486 }; 487 488 } // end anonymous namespace 489 490 ExprResult InitListChecker::PerformEmptyInit(SourceLocation Loc, 491 const InitializedEntity &Entity) { 492 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc, 493 true); 494 MultiExprArg SubInit; 495 Expr *InitExpr; 496 InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc); 497 498 // C++ [dcl.init.aggr]p7: 499 // If there are fewer initializer-clauses in the list than there are 500 // members in the aggregate, then each member not explicitly initialized 501 // ... 502 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 && 503 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType(); 504 if (EmptyInitList) { 505 // C++1y / DR1070: 506 // shall be initialized [...] from an empty initializer list. 507 // 508 // We apply the resolution of this DR to C++11 but not C++98, since C++98 509 // does not have useful semantics for initialization from an init list. 510 // We treat this as copy-initialization, because aggregate initialization 511 // always performs copy-initialization on its elements. 512 // 513 // Only do this if we're initializing a class type, to avoid filling in 514 // the initializer list where possible. 515 InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context) 516 InitListExpr(SemaRef.Context, Loc, None, Loc); 517 InitExpr->setType(SemaRef.Context.VoidTy); 518 SubInit = InitExpr; 519 Kind = InitializationKind::CreateCopy(Loc, Loc); 520 } else { 521 // C++03: 522 // shall be value-initialized. 523 } 524 525 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit); 526 // libstdc++4.6 marks the vector default constructor as explicit in 527 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case. 528 // stlport does so too. Look for std::__debug for libstdc++, and for 529 // std:: for stlport. This is effectively a compiler-side implementation of 530 // LWG2193. 531 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() == 532 InitializationSequence::FK_ExplicitConstructor) { 533 OverloadCandidateSet::iterator Best; 534 OverloadingResult O = 535 InitSeq.getFailedCandidateSet() 536 .BestViableFunction(SemaRef, Kind.getLocation(), Best); 537 (void)O; 538 assert(O == OR_Success && "Inconsistent overload resolution"); 539 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function); 540 CXXRecordDecl *R = CtorDecl->getParent(); 541 542 if (CtorDecl->getMinRequiredArguments() == 0 && 543 CtorDecl->isExplicit() && R->getDeclName() && 544 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) { 545 bool IsInStd = false; 546 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext()); 547 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) { 548 if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND)) 549 IsInStd = true; 550 } 551 552 if (IsInStd && llvm::StringSwitch<bool>(R->getName()) 553 .Cases("basic_string", "deque", "forward_list", true) 554 .Cases("list", "map", "multimap", "multiset", true) 555 .Cases("priority_queue", "queue", "set", "stack", true) 556 .Cases("unordered_map", "unordered_set", "vector", true) 557 .Default(false)) { 558 InitSeq.InitializeFrom( 559 SemaRef, Entity, 560 InitializationKind::CreateValue(Loc, Loc, Loc, true), 561 MultiExprArg(), /*TopLevelOfInitList=*/false, 562 TreatUnavailableAsInvalid); 563 // Emit a warning for this. System header warnings aren't shown 564 // by default, but people working on system headers should see it. 565 if (!VerifyOnly) { 566 SemaRef.Diag(CtorDecl->getLocation(), 567 diag::warn_invalid_initializer_from_system_header); 568 if (Entity.getKind() == InitializedEntity::EK_Member) 569 SemaRef.Diag(Entity.getDecl()->getLocation(), 570 diag::note_used_in_initialization_here); 571 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) 572 SemaRef.Diag(Loc, diag::note_used_in_initialization_here); 573 } 574 } 575 } 576 } 577 if (!InitSeq) { 578 if (!VerifyOnly) { 579 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit); 580 if (Entity.getKind() == InitializedEntity::EK_Member) 581 SemaRef.Diag(Entity.getDecl()->getLocation(), 582 diag::note_in_omitted_aggregate_initializer) 583 << /*field*/1 << Entity.getDecl(); 584 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) { 585 bool IsTrailingArrayNewMember = 586 Entity.getParent() && 587 Entity.getParent()->isVariableLengthArrayNew(); 588 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer) 589 << (IsTrailingArrayNewMember ? 2 : /*array element*/0) 590 << Entity.getElementIndex(); 591 } 592 } 593 hadError = true; 594 return ExprError(); 595 } 596 597 return VerifyOnly ? ExprResult() 598 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit); 599 } 600 601 void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity, 602 SourceLocation Loc) { 603 // If we're building a fully-structured list, we'll check this at the end 604 // once we know which elements are actually initialized. Otherwise, we know 605 // that there are no designators so we can just check now. 606 if (FullyStructuredList) 607 return; 608 PerformEmptyInit(Loc, Entity); 609 } 610 611 void InitListChecker::FillInEmptyInitForBase( 612 unsigned Init, const CXXBaseSpecifier &Base, 613 const InitializedEntity &ParentEntity, InitListExpr *ILE, 614 bool &RequiresSecondPass, bool FillWithNoInit) { 615 InitializedEntity BaseEntity = InitializedEntity::InitializeBase( 616 SemaRef.Context, &Base, false, &ParentEntity); 617 618 if (Init >= ILE->getNumInits() || !ILE->getInit(Init)) { 619 ExprResult BaseInit = FillWithNoInit 620 ? new (SemaRef.Context) NoInitExpr(Base.getType()) 621 : PerformEmptyInit(ILE->getEndLoc(), BaseEntity); 622 if (BaseInit.isInvalid()) { 623 hadError = true; 624 return; 625 } 626 627 if (!VerifyOnly) { 628 assert(Init < ILE->getNumInits() && "should have been expanded"); 629 ILE->setInit(Init, BaseInit.getAs<Expr>()); 630 } 631 } else if (InitListExpr *InnerILE = 632 dyn_cast<InitListExpr>(ILE->getInit(Init))) { 633 FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass, 634 ILE, Init, FillWithNoInit); 635 } else if (DesignatedInitUpdateExpr *InnerDIUE = 636 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) { 637 FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(), 638 RequiresSecondPass, ILE, Init, 639 /*FillWithNoInit =*/true); 640 } 641 } 642 643 void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field, 644 const InitializedEntity &ParentEntity, 645 InitListExpr *ILE, 646 bool &RequiresSecondPass, 647 bool FillWithNoInit) { 648 SourceLocation Loc = ILE->getEndLoc(); 649 unsigned NumInits = ILE->getNumInits(); 650 InitializedEntity MemberEntity 651 = InitializedEntity::InitializeMember(Field, &ParentEntity); 652 653 if (Init >= NumInits || !ILE->getInit(Init)) { 654 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) 655 if (!RType->getDecl()->isUnion()) 656 assert((Init < NumInits || VerifyOnly) && 657 "This ILE should have been expanded"); 658 659 if (FillWithNoInit) { 660 assert(!VerifyOnly && "should not fill with no-init in verify-only mode"); 661 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType()); 662 if (Init < NumInits) 663 ILE->setInit(Init, Filler); 664 else 665 ILE->updateInit(SemaRef.Context, Init, Filler); 666 return; 667 } 668 // C++1y [dcl.init.aggr]p7: 669 // If there are fewer initializer-clauses in the list than there are 670 // members in the aggregate, then each member not explicitly initialized 671 // shall be initialized from its brace-or-equal-initializer [...] 672 if (Field->hasInClassInitializer()) { 673 if (VerifyOnly) 674 return; 675 676 ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field); 677 if (DIE.isInvalid()) { 678 hadError = true; 679 return; 680 } 681 SemaRef.checkInitializerLifetime(MemberEntity, DIE.get()); 682 if (Init < NumInits) 683 ILE->setInit(Init, DIE.get()); 684 else { 685 ILE->updateInit(SemaRef.Context, Init, DIE.get()); 686 RequiresSecondPass = true; 687 } 688 return; 689 } 690 691 if (Field->getType()->isReferenceType()) { 692 if (!VerifyOnly) { 693 // C++ [dcl.init.aggr]p9: 694 // If an incomplete or empty initializer-list leaves a 695 // member of reference type uninitialized, the program is 696 // ill-formed. 697 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized) 698 << Field->getType() 699 << ILE->getSyntacticForm()->getSourceRange(); 700 SemaRef.Diag(Field->getLocation(), 701 diag::note_uninit_reference_member); 702 } 703 hadError = true; 704 return; 705 } 706 707 ExprResult MemberInit = PerformEmptyInit(Loc, MemberEntity); 708 if (MemberInit.isInvalid()) { 709 hadError = true; 710 return; 711 } 712 713 if (hadError || VerifyOnly) { 714 // Do nothing 715 } else if (Init < NumInits) { 716 ILE->setInit(Init, MemberInit.getAs<Expr>()); 717 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) { 718 // Empty initialization requires a constructor call, so 719 // extend the initializer list to include the constructor 720 // call and make a note that we'll need to take another pass 721 // through the initializer list. 722 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>()); 723 RequiresSecondPass = true; 724 } 725 } else if (InitListExpr *InnerILE 726 = dyn_cast<InitListExpr>(ILE->getInit(Init))) { 727 FillInEmptyInitializations(MemberEntity, InnerILE, 728 RequiresSecondPass, ILE, Init, FillWithNoInit); 729 } else if (DesignatedInitUpdateExpr *InnerDIUE = 730 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) { 731 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(), 732 RequiresSecondPass, ILE, Init, 733 /*FillWithNoInit =*/true); 734 } 735 } 736 737 /// Recursively replaces NULL values within the given initializer list 738 /// with expressions that perform value-initialization of the 739 /// appropriate type, and finish off the InitListExpr formation. 740 void 741 InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity, 742 InitListExpr *ILE, 743 bool &RequiresSecondPass, 744 InitListExpr *OuterILE, 745 unsigned OuterIndex, 746 bool FillWithNoInit) { 747 assert((ILE->getType() != SemaRef.Context.VoidTy) && 748 "Should not have void type"); 749 750 // We don't need to do any checks when just filling NoInitExprs; that can't 751 // fail. 752 if (FillWithNoInit && VerifyOnly) 753 return; 754 755 // If this is a nested initializer list, we might have changed its contents 756 // (and therefore some of its properties, such as instantiation-dependence) 757 // while filling it in. Inform the outer initializer list so that its state 758 // can be updated to match. 759 // FIXME: We should fully build the inner initializers before constructing 760 // the outer InitListExpr instead of mutating AST nodes after they have 761 // been used as subexpressions of other nodes. 762 struct UpdateOuterILEWithUpdatedInit { 763 InitListExpr *Outer; 764 unsigned OuterIndex; 765 ~UpdateOuterILEWithUpdatedInit() { 766 if (Outer) 767 Outer->setInit(OuterIndex, Outer->getInit(OuterIndex)); 768 } 769 } UpdateOuterRAII = {OuterILE, OuterIndex}; 770 771 // A transparent ILE is not performing aggregate initialization and should 772 // not be filled in. 773 if (ILE->isTransparent()) 774 return; 775 776 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) { 777 const RecordDecl *RDecl = RType->getDecl(); 778 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion()) 779 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(), 780 Entity, ILE, RequiresSecondPass, FillWithNoInit); 781 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) && 782 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) { 783 for (auto *Field : RDecl->fields()) { 784 if (Field->hasInClassInitializer()) { 785 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass, 786 FillWithNoInit); 787 break; 788 } 789 } 790 } else { 791 // The fields beyond ILE->getNumInits() are default initialized, so in 792 // order to leave them uninitialized, the ILE is expanded and the extra 793 // fields are then filled with NoInitExpr. 794 unsigned NumElems = numStructUnionElements(ILE->getType()); 795 if (RDecl->hasFlexibleArrayMember()) 796 ++NumElems; 797 if (!VerifyOnly && ILE->getNumInits() < NumElems) 798 ILE->resizeInits(SemaRef.Context, NumElems); 799 800 unsigned Init = 0; 801 802 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) { 803 for (auto &Base : CXXRD->bases()) { 804 if (hadError) 805 return; 806 807 FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass, 808 FillWithNoInit); 809 ++Init; 810 } 811 } 812 813 for (auto *Field : RDecl->fields()) { 814 if (Field->isUnnamedBitfield()) 815 continue; 816 817 if (hadError) 818 return; 819 820 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass, 821 FillWithNoInit); 822 if (hadError) 823 return; 824 825 ++Init; 826 827 // Only look at the first initialization of a union. 828 if (RDecl->isUnion()) 829 break; 830 } 831 } 832 833 return; 834 } 835 836 QualType ElementType; 837 838 InitializedEntity ElementEntity = Entity; 839 unsigned NumInits = ILE->getNumInits(); 840 unsigned NumElements = NumInits; 841 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) { 842 ElementType = AType->getElementType(); 843 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType)) 844 NumElements = CAType->getSize().getZExtValue(); 845 // For an array new with an unknown bound, ask for one additional element 846 // in order to populate the array filler. 847 if (Entity.isVariableLengthArrayNew()) 848 ++NumElements; 849 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context, 850 0, Entity); 851 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) { 852 ElementType = VType->getElementType(); 853 NumElements = VType->getNumElements(); 854 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context, 855 0, Entity); 856 } else 857 ElementType = ILE->getType(); 858 859 bool SkipEmptyInitChecks = false; 860 for (unsigned Init = 0; Init != NumElements; ++Init) { 861 if (hadError) 862 return; 863 864 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement || 865 ElementEntity.getKind() == InitializedEntity::EK_VectorElement) 866 ElementEntity.setElementIndex(Init); 867 868 if (Init >= NumInits && (ILE->hasArrayFiller() || SkipEmptyInitChecks)) 869 return; 870 871 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr); 872 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller()) 873 ILE->setInit(Init, ILE->getArrayFiller()); 874 else if (!InitExpr && !ILE->hasArrayFiller()) { 875 // In VerifyOnly mode, there's no point performing empty initialization 876 // more than once. 877 if (SkipEmptyInitChecks) 878 continue; 879 880 Expr *Filler = nullptr; 881 882 if (FillWithNoInit) 883 Filler = new (SemaRef.Context) NoInitExpr(ElementType); 884 else { 885 ExprResult ElementInit = 886 PerformEmptyInit(ILE->getEndLoc(), ElementEntity); 887 if (ElementInit.isInvalid()) { 888 hadError = true; 889 return; 890 } 891 892 Filler = ElementInit.getAs<Expr>(); 893 } 894 895 if (hadError) { 896 // Do nothing 897 } else if (VerifyOnly) { 898 SkipEmptyInitChecks = true; 899 } else if (Init < NumInits) { 900 // For arrays, just set the expression used for value-initialization 901 // of the "holes" in the array. 902 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) 903 ILE->setArrayFiller(Filler); 904 else 905 ILE->setInit(Init, Filler); 906 } else { 907 // For arrays, just set the expression used for value-initialization 908 // of the rest of elements and exit. 909 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) { 910 ILE->setArrayFiller(Filler); 911 return; 912 } 913 914 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) { 915 // Empty initialization requires a constructor call, so 916 // extend the initializer list to include the constructor 917 // call and make a note that we'll need to take another pass 918 // through the initializer list. 919 ILE->updateInit(SemaRef.Context, Init, Filler); 920 RequiresSecondPass = true; 921 } 922 } 923 } else if (InitListExpr *InnerILE 924 = dyn_cast_or_null<InitListExpr>(InitExpr)) { 925 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass, 926 ILE, Init, FillWithNoInit); 927 } else if (DesignatedInitUpdateExpr *InnerDIUE = 928 dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr)) { 929 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(), 930 RequiresSecondPass, ILE, Init, 931 /*FillWithNoInit =*/true); 932 } 933 } 934 } 935 936 static bool hasAnyDesignatedInits(const InitListExpr *IL) { 937 for (const Stmt *Init : *IL) 938 if (Init && isa<DesignatedInitExpr>(Init)) 939 return true; 940 return false; 941 } 942 943 InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity, 944 InitListExpr *IL, QualType &T, bool VerifyOnly, 945 bool TreatUnavailableAsInvalid, 946 bool InOverloadResolution) 947 : SemaRef(S), VerifyOnly(VerifyOnly), 948 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid), 949 InOverloadResolution(InOverloadResolution) { 950 if (!VerifyOnly || hasAnyDesignatedInits(IL)) { 951 FullyStructuredList = 952 createInitListExpr(T, IL->getSourceRange(), IL->getNumInits()); 953 954 // FIXME: Check that IL isn't already the semantic form of some other 955 // InitListExpr. If it is, we'd create a broken AST. 956 if (!VerifyOnly) 957 FullyStructuredList->setSyntacticForm(IL); 958 } 959 960 CheckExplicitInitList(Entity, IL, T, FullyStructuredList, 961 /*TopLevelObject=*/true); 962 963 if (!hadError && FullyStructuredList) { 964 bool RequiresSecondPass = false; 965 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass, 966 /*OuterILE=*/nullptr, /*OuterIndex=*/0); 967 if (RequiresSecondPass && !hadError) 968 FillInEmptyInitializations(Entity, FullyStructuredList, 969 RequiresSecondPass, nullptr, 0); 970 } 971 if (hadError && FullyStructuredList) 972 FullyStructuredList->markError(); 973 } 974 975 int InitListChecker::numArrayElements(QualType DeclType) { 976 // FIXME: use a proper constant 977 int maxElements = 0x7FFFFFFF; 978 if (const ConstantArrayType *CAT = 979 SemaRef.Context.getAsConstantArrayType(DeclType)) { 980 maxElements = static_cast<int>(CAT->getSize().getZExtValue()); 981 } 982 return maxElements; 983 } 984 985 int InitListChecker::numStructUnionElements(QualType DeclType) { 986 RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl(); 987 int InitializableMembers = 0; 988 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl)) 989 InitializableMembers += CXXRD->getNumBases(); 990 for (const auto *Field : structDecl->fields()) 991 if (!Field->isUnnamedBitfield()) 992 ++InitializableMembers; 993 994 if (structDecl->isUnion()) 995 return std::min(InitializableMembers, 1); 996 return InitializableMembers - structDecl->hasFlexibleArrayMember(); 997 } 998 999 /// Determine whether Entity is an entity for which it is idiomatic to elide 1000 /// the braces in aggregate initialization. 1001 static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) { 1002 // Recursive initialization of the one and only field within an aggregate 1003 // class is considered idiomatic. This case arises in particular for 1004 // initialization of std::array, where the C++ standard suggests the idiom of 1005 // 1006 // std::array<T, N> arr = {1, 2, 3}; 1007 // 1008 // (where std::array is an aggregate struct containing a single array field. 1009 1010 // FIXME: Should aggregate initialization of a struct with a single 1011 // base class and no members also suppress the warning? 1012 if (Entity.getKind() != InitializedEntity::EK_Member || !Entity.getParent()) 1013 return false; 1014 1015 auto *ParentRD = 1016 Entity.getParent()->getType()->castAs<RecordType>()->getDecl(); 1017 if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD)) 1018 if (CXXRD->getNumBases()) 1019 return false; 1020 1021 auto FieldIt = ParentRD->field_begin(); 1022 assert(FieldIt != ParentRD->field_end() && 1023 "no fields but have initializer for member?"); 1024 return ++FieldIt == ParentRD->field_end(); 1025 } 1026 1027 /// Check whether the range of the initializer \p ParentIList from element 1028 /// \p Index onwards can be used to initialize an object of type \p T. Update 1029 /// \p Index to indicate how many elements of the list were consumed. 1030 /// 1031 /// This also fills in \p StructuredList, from element \p StructuredIndex 1032 /// onwards, with the fully-braced, desugared form of the initialization. 1033 void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity, 1034 InitListExpr *ParentIList, 1035 QualType T, unsigned &Index, 1036 InitListExpr *StructuredList, 1037 unsigned &StructuredIndex) { 1038 int maxElements = 0; 1039 1040 if (T->isArrayType()) 1041 maxElements = numArrayElements(T); 1042 else if (T->isRecordType()) 1043 maxElements = numStructUnionElements(T); 1044 else if (T->isVectorType()) 1045 maxElements = T->castAs<VectorType>()->getNumElements(); 1046 else 1047 llvm_unreachable("CheckImplicitInitList(): Illegal type"); 1048 1049 if (maxElements == 0) { 1050 if (!VerifyOnly) 1051 SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(), 1052 diag::err_implicit_empty_initializer); 1053 ++Index; 1054 hadError = true; 1055 return; 1056 } 1057 1058 // Build a structured initializer list corresponding to this subobject. 1059 InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit( 1060 ParentIList, Index, T, StructuredList, StructuredIndex, 1061 SourceRange(ParentIList->getInit(Index)->getBeginLoc(), 1062 ParentIList->getSourceRange().getEnd())); 1063 unsigned StructuredSubobjectInitIndex = 0; 1064 1065 // Check the element types and build the structural subobject. 1066 unsigned StartIndex = Index; 1067 CheckListElementTypes(Entity, ParentIList, T, 1068 /*SubobjectIsDesignatorContext=*/false, Index, 1069 StructuredSubobjectInitList, 1070 StructuredSubobjectInitIndex); 1071 1072 if (StructuredSubobjectInitList) { 1073 StructuredSubobjectInitList->setType(T); 1074 1075 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1); 1076 // Update the structured sub-object initializer so that it's ending 1077 // range corresponds with the end of the last initializer it used. 1078 if (EndIndex < ParentIList->getNumInits() && 1079 ParentIList->getInit(EndIndex)) { 1080 SourceLocation EndLoc 1081 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd(); 1082 StructuredSubobjectInitList->setRBraceLoc(EndLoc); 1083 } 1084 1085 // Complain about missing braces. 1086 if (!VerifyOnly && (T->isArrayType() || T->isRecordType()) && 1087 !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) && 1088 !isIdiomaticBraceElisionEntity(Entity)) { 1089 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(), 1090 diag::warn_missing_braces) 1091 << StructuredSubobjectInitList->getSourceRange() 1092 << FixItHint::CreateInsertion( 1093 StructuredSubobjectInitList->getBeginLoc(), "{") 1094 << FixItHint::CreateInsertion( 1095 SemaRef.getLocForEndOfToken( 1096 StructuredSubobjectInitList->getEndLoc()), 1097 "}"); 1098 } 1099 1100 // Warn if this type won't be an aggregate in future versions of C++. 1101 auto *CXXRD = T->getAsCXXRecordDecl(); 1102 if (!VerifyOnly && CXXRD && CXXRD->hasUserDeclaredConstructor()) { 1103 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(), 1104 diag::warn_cxx20_compat_aggregate_init_with_ctors) 1105 << StructuredSubobjectInitList->getSourceRange() << T; 1106 } 1107 } 1108 } 1109 1110 /// Warn that \p Entity was of scalar type and was initialized by a 1111 /// single-element braced initializer list. 1112 static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity, 1113 SourceRange Braces) { 1114 // Don't warn during template instantiation. If the initialization was 1115 // non-dependent, we warned during the initial parse; otherwise, the 1116 // type might not be scalar in some uses of the template. 1117 if (S.inTemplateInstantiation()) 1118 return; 1119 1120 unsigned DiagID = 0; 1121 1122 switch (Entity.getKind()) { 1123 case InitializedEntity::EK_VectorElement: 1124 case InitializedEntity::EK_ComplexElement: 1125 case InitializedEntity::EK_ArrayElement: 1126 case InitializedEntity::EK_Parameter: 1127 case InitializedEntity::EK_Parameter_CF_Audited: 1128 case InitializedEntity::EK_TemplateParameter: 1129 case InitializedEntity::EK_Result: 1130 // Extra braces here are suspicious. 1131 DiagID = diag::warn_braces_around_init; 1132 break; 1133 1134 case InitializedEntity::EK_Member: 1135 // Warn on aggregate initialization but not on ctor init list or 1136 // default member initializer. 1137 if (Entity.getParent()) 1138 DiagID = diag::warn_braces_around_init; 1139 break; 1140 1141 case InitializedEntity::EK_Variable: 1142 case InitializedEntity::EK_LambdaCapture: 1143 // No warning, might be direct-list-initialization. 1144 // FIXME: Should we warn for copy-list-initialization in these cases? 1145 break; 1146 1147 case InitializedEntity::EK_New: 1148 case InitializedEntity::EK_Temporary: 1149 case InitializedEntity::EK_CompoundLiteralInit: 1150 // No warning, braces are part of the syntax of the underlying construct. 1151 break; 1152 1153 case InitializedEntity::EK_RelatedResult: 1154 // No warning, we already warned when initializing the result. 1155 break; 1156 1157 case InitializedEntity::EK_Exception: 1158 case InitializedEntity::EK_Base: 1159 case InitializedEntity::EK_Delegating: 1160 case InitializedEntity::EK_BlockElement: 1161 case InitializedEntity::EK_LambdaToBlockConversionBlockElement: 1162 case InitializedEntity::EK_Binding: 1163 case InitializedEntity::EK_StmtExprResult: 1164 llvm_unreachable("unexpected braced scalar init"); 1165 } 1166 1167 if (DiagID) { 1168 S.Diag(Braces.getBegin(), DiagID) 1169 << Entity.getType()->isSizelessBuiltinType() << Braces 1170 << FixItHint::CreateRemoval(Braces.getBegin()) 1171 << FixItHint::CreateRemoval(Braces.getEnd()); 1172 } 1173 } 1174 1175 /// Check whether the initializer \p IList (that was written with explicit 1176 /// braces) can be used to initialize an object of type \p T. 1177 /// 1178 /// This also fills in \p StructuredList with the fully-braced, desugared 1179 /// form of the initialization. 1180 void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity, 1181 InitListExpr *IList, QualType &T, 1182 InitListExpr *StructuredList, 1183 bool TopLevelObject) { 1184 unsigned Index = 0, StructuredIndex = 0; 1185 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true, 1186 Index, StructuredList, StructuredIndex, TopLevelObject); 1187 if (StructuredList) { 1188 QualType ExprTy = T; 1189 if (!ExprTy->isArrayType()) 1190 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context); 1191 if (!VerifyOnly) 1192 IList->setType(ExprTy); 1193 StructuredList->setType(ExprTy); 1194 } 1195 if (hadError) 1196 return; 1197 1198 // Don't complain for incomplete types, since we'll get an error elsewhere. 1199 if (Index < IList->getNumInits() && !T->isIncompleteType()) { 1200 // We have leftover initializers 1201 bool ExtraInitsIsError = SemaRef.getLangOpts().CPlusPlus || 1202 (SemaRef.getLangOpts().OpenCL && T->isVectorType()); 1203 hadError = ExtraInitsIsError; 1204 if (VerifyOnly) { 1205 return; 1206 } else if (StructuredIndex == 1 && 1207 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) == 1208 SIF_None) { 1209 unsigned DK = 1210 ExtraInitsIsError 1211 ? diag::err_excess_initializers_in_char_array_initializer 1212 : diag::ext_excess_initializers_in_char_array_initializer; 1213 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK) 1214 << IList->getInit(Index)->getSourceRange(); 1215 } else if (T->isSizelessBuiltinType()) { 1216 unsigned DK = ExtraInitsIsError 1217 ? diag::err_excess_initializers_for_sizeless_type 1218 : diag::ext_excess_initializers_for_sizeless_type; 1219 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK) 1220 << T << IList->getInit(Index)->getSourceRange(); 1221 } else { 1222 int initKind = T->isArrayType() ? 0 : 1223 T->isVectorType() ? 1 : 1224 T->isScalarType() ? 2 : 1225 T->isUnionType() ? 3 : 1226 4; 1227 1228 unsigned DK = ExtraInitsIsError ? diag::err_excess_initializers 1229 : diag::ext_excess_initializers; 1230 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK) 1231 << initKind << IList->getInit(Index)->getSourceRange(); 1232 } 1233 } 1234 1235 if (!VerifyOnly) { 1236 if (T->isScalarType() && IList->getNumInits() == 1 && 1237 !isa<InitListExpr>(IList->getInit(0))) 1238 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange()); 1239 1240 // Warn if this is a class type that won't be an aggregate in future 1241 // versions of C++. 1242 auto *CXXRD = T->getAsCXXRecordDecl(); 1243 if (CXXRD && CXXRD->hasUserDeclaredConstructor()) { 1244 // Don't warn if there's an equivalent default constructor that would be 1245 // used instead. 1246 bool HasEquivCtor = false; 1247 if (IList->getNumInits() == 0) { 1248 auto *CD = SemaRef.LookupDefaultConstructor(CXXRD); 1249 HasEquivCtor = CD && !CD->isDeleted(); 1250 } 1251 1252 if (!HasEquivCtor) { 1253 SemaRef.Diag(IList->getBeginLoc(), 1254 diag::warn_cxx20_compat_aggregate_init_with_ctors) 1255 << IList->getSourceRange() << T; 1256 } 1257 } 1258 } 1259 } 1260 1261 void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity, 1262 InitListExpr *IList, 1263 QualType &DeclType, 1264 bool SubobjectIsDesignatorContext, 1265 unsigned &Index, 1266 InitListExpr *StructuredList, 1267 unsigned &StructuredIndex, 1268 bool TopLevelObject) { 1269 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) { 1270 // Explicitly braced initializer for complex type can be real+imaginary 1271 // parts. 1272 CheckComplexType(Entity, IList, DeclType, Index, 1273 StructuredList, StructuredIndex); 1274 } else if (DeclType->isScalarType()) { 1275 CheckScalarType(Entity, IList, DeclType, Index, 1276 StructuredList, StructuredIndex); 1277 } else if (DeclType->isVectorType()) { 1278 CheckVectorType(Entity, IList, DeclType, Index, 1279 StructuredList, StructuredIndex); 1280 } else if (DeclType->isRecordType()) { 1281 assert(DeclType->isAggregateType() && 1282 "non-aggregate records should be handed in CheckSubElementType"); 1283 RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl(); 1284 auto Bases = 1285 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(), 1286 CXXRecordDecl::base_class_iterator()); 1287 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 1288 Bases = CXXRD->bases(); 1289 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(), 1290 SubobjectIsDesignatorContext, Index, StructuredList, 1291 StructuredIndex, TopLevelObject); 1292 } else if (DeclType->isArrayType()) { 1293 llvm::APSInt Zero( 1294 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()), 1295 false); 1296 CheckArrayType(Entity, IList, DeclType, Zero, 1297 SubobjectIsDesignatorContext, Index, 1298 StructuredList, StructuredIndex); 1299 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) { 1300 // This type is invalid, issue a diagnostic. 1301 ++Index; 1302 if (!VerifyOnly) 1303 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type) 1304 << DeclType; 1305 hadError = true; 1306 } else if (DeclType->isReferenceType()) { 1307 CheckReferenceType(Entity, IList, DeclType, Index, 1308 StructuredList, StructuredIndex); 1309 } else if (DeclType->isObjCObjectType()) { 1310 if (!VerifyOnly) 1311 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType; 1312 hadError = true; 1313 } else if (DeclType->isOCLIntelSubgroupAVCType() || 1314 DeclType->isSizelessBuiltinType()) { 1315 // Checks for scalar type are sufficient for these types too. 1316 CheckScalarType(Entity, IList, DeclType, Index, StructuredList, 1317 StructuredIndex); 1318 } else { 1319 if (!VerifyOnly) 1320 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type) 1321 << DeclType; 1322 hadError = true; 1323 } 1324 } 1325 1326 void InitListChecker::CheckSubElementType(const InitializedEntity &Entity, 1327 InitListExpr *IList, 1328 QualType ElemType, 1329 unsigned &Index, 1330 InitListExpr *StructuredList, 1331 unsigned &StructuredIndex, 1332 bool DirectlyDesignated) { 1333 Expr *expr = IList->getInit(Index); 1334 1335 if (ElemType->isReferenceType()) 1336 return CheckReferenceType(Entity, IList, ElemType, Index, 1337 StructuredList, StructuredIndex); 1338 1339 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) { 1340 if (SubInitList->getNumInits() == 1 && 1341 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) == 1342 SIF_None) { 1343 // FIXME: It would be more faithful and no less correct to include an 1344 // InitListExpr in the semantic form of the initializer list in this case. 1345 expr = SubInitList->getInit(0); 1346 } 1347 // Nested aggregate initialization and C++ initialization are handled later. 1348 } else if (isa<ImplicitValueInitExpr>(expr)) { 1349 // This happens during template instantiation when we see an InitListExpr 1350 // that we've already checked once. 1351 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) && 1352 "found implicit initialization for the wrong type"); 1353 UpdateStructuredListElement(StructuredList, StructuredIndex, expr); 1354 ++Index; 1355 return; 1356 } 1357 1358 if (SemaRef.getLangOpts().CPlusPlus || isa<InitListExpr>(expr)) { 1359 // C++ [dcl.init.aggr]p2: 1360 // Each member is copy-initialized from the corresponding 1361 // initializer-clause. 1362 1363 // FIXME: Better EqualLoc? 1364 InitializationKind Kind = 1365 InitializationKind::CreateCopy(expr->getBeginLoc(), SourceLocation()); 1366 1367 // Vector elements can be initialized from other vectors in which case 1368 // we need initialization entity with a type of a vector (and not a vector 1369 // element!) initializing multiple vector elements. 1370 auto TmpEntity = 1371 (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType()) 1372 ? InitializedEntity::InitializeTemporary(ElemType) 1373 : Entity; 1374 1375 InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr, 1376 /*TopLevelOfInitList*/ true); 1377 1378 // C++14 [dcl.init.aggr]p13: 1379 // If the assignment-expression can initialize a member, the member is 1380 // initialized. Otherwise [...] brace elision is assumed 1381 // 1382 // Brace elision is never performed if the element is not an 1383 // assignment-expression. 1384 if (Seq || isa<InitListExpr>(expr)) { 1385 if (!VerifyOnly) { 1386 ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr); 1387 if (Result.isInvalid()) 1388 hadError = true; 1389 1390 UpdateStructuredListElement(StructuredList, StructuredIndex, 1391 Result.getAs<Expr>()); 1392 } else if (!Seq) { 1393 hadError = true; 1394 } else if (StructuredList) { 1395 UpdateStructuredListElement(StructuredList, StructuredIndex, 1396 getDummyInit()); 1397 } 1398 ++Index; 1399 return; 1400 } 1401 1402 // Fall through for subaggregate initialization 1403 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) { 1404 // FIXME: Need to handle atomic aggregate types with implicit init lists. 1405 return CheckScalarType(Entity, IList, ElemType, Index, 1406 StructuredList, StructuredIndex); 1407 } else if (const ArrayType *arrayType = 1408 SemaRef.Context.getAsArrayType(ElemType)) { 1409 // arrayType can be incomplete if we're initializing a flexible 1410 // array member. There's nothing we can do with the completed 1411 // type here, though. 1412 1413 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) { 1414 // FIXME: Should we do this checking in verify-only mode? 1415 if (!VerifyOnly) 1416 CheckStringInit(expr, ElemType, arrayType, SemaRef); 1417 if (StructuredList) 1418 UpdateStructuredListElement(StructuredList, StructuredIndex, expr); 1419 ++Index; 1420 return; 1421 } 1422 1423 // Fall through for subaggregate initialization. 1424 1425 } else { 1426 assert((ElemType->isRecordType() || ElemType->isVectorType() || 1427 ElemType->isOpenCLSpecificType()) && "Unexpected type"); 1428 1429 // C99 6.7.8p13: 1430 // 1431 // The initializer for a structure or union object that has 1432 // automatic storage duration shall be either an initializer 1433 // list as described below, or a single expression that has 1434 // compatible structure or union type. In the latter case, the 1435 // initial value of the object, including unnamed members, is 1436 // that of the expression. 1437 ExprResult ExprRes = expr; 1438 if (SemaRef.CheckSingleAssignmentConstraints( 1439 ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) { 1440 if (ExprRes.isInvalid()) 1441 hadError = true; 1442 else { 1443 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get()); 1444 if (ExprRes.isInvalid()) 1445 hadError = true; 1446 } 1447 UpdateStructuredListElement(StructuredList, StructuredIndex, 1448 ExprRes.getAs<Expr>()); 1449 ++Index; 1450 return; 1451 } 1452 ExprRes.get(); 1453 // Fall through for subaggregate initialization 1454 } 1455 1456 // C++ [dcl.init.aggr]p12: 1457 // 1458 // [...] Otherwise, if the member is itself a non-empty 1459 // subaggregate, brace elision is assumed and the initializer is 1460 // considered for the initialization of the first member of 1461 // the subaggregate. 1462 // OpenCL vector initializer is handled elsewhere. 1463 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) || 1464 ElemType->isAggregateType()) { 1465 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList, 1466 StructuredIndex); 1467 ++StructuredIndex; 1468 1469 // In C++20, brace elision is not permitted for a designated initializer. 1470 if (DirectlyDesignated && SemaRef.getLangOpts().CPlusPlus && !hadError) { 1471 if (InOverloadResolution) 1472 hadError = true; 1473 if (!VerifyOnly) { 1474 SemaRef.Diag(expr->getBeginLoc(), 1475 diag::ext_designated_init_brace_elision) 1476 << expr->getSourceRange() 1477 << FixItHint::CreateInsertion(expr->getBeginLoc(), "{") 1478 << FixItHint::CreateInsertion( 1479 SemaRef.getLocForEndOfToken(expr->getEndLoc()), "}"); 1480 } 1481 } 1482 } else { 1483 if (!VerifyOnly) { 1484 // We cannot initialize this element, so let PerformCopyInitialization 1485 // produce the appropriate diagnostic. We already checked that this 1486 // initialization will fail. 1487 ExprResult Copy = 1488 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr, 1489 /*TopLevelOfInitList=*/true); 1490 (void)Copy; 1491 assert(Copy.isInvalid() && 1492 "expected non-aggregate initialization to fail"); 1493 } 1494 hadError = true; 1495 ++Index; 1496 ++StructuredIndex; 1497 } 1498 } 1499 1500 void InitListChecker::CheckComplexType(const InitializedEntity &Entity, 1501 InitListExpr *IList, QualType DeclType, 1502 unsigned &Index, 1503 InitListExpr *StructuredList, 1504 unsigned &StructuredIndex) { 1505 assert(Index == 0 && "Index in explicit init list must be zero"); 1506 1507 // As an extension, clang supports complex initializers, which initialize 1508 // a complex number component-wise. When an explicit initializer list for 1509 // a complex number contains two two initializers, this extension kicks in: 1510 // it exepcts the initializer list to contain two elements convertible to 1511 // the element type of the complex type. The first element initializes 1512 // the real part, and the second element intitializes the imaginary part. 1513 1514 if (IList->getNumInits() != 2) 1515 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList, 1516 StructuredIndex); 1517 1518 // This is an extension in C. (The builtin _Complex type does not exist 1519 // in the C++ standard.) 1520 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly) 1521 SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init) 1522 << IList->getSourceRange(); 1523 1524 // Initialize the complex number. 1525 QualType elementType = DeclType->castAs<ComplexType>()->getElementType(); 1526 InitializedEntity ElementEntity = 1527 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); 1528 1529 for (unsigned i = 0; i < 2; ++i) { 1530 ElementEntity.setElementIndex(Index); 1531 CheckSubElementType(ElementEntity, IList, elementType, Index, 1532 StructuredList, StructuredIndex); 1533 } 1534 } 1535 1536 void InitListChecker::CheckScalarType(const InitializedEntity &Entity, 1537 InitListExpr *IList, QualType DeclType, 1538 unsigned &Index, 1539 InitListExpr *StructuredList, 1540 unsigned &StructuredIndex) { 1541 if (Index >= IList->getNumInits()) { 1542 if (!VerifyOnly) { 1543 if (DeclType->isSizelessBuiltinType()) 1544 SemaRef.Diag(IList->getBeginLoc(), 1545 SemaRef.getLangOpts().CPlusPlus11 1546 ? diag::warn_cxx98_compat_empty_sizeless_initializer 1547 : diag::err_empty_sizeless_initializer) 1548 << DeclType << IList->getSourceRange(); 1549 else 1550 SemaRef.Diag(IList->getBeginLoc(), 1551 SemaRef.getLangOpts().CPlusPlus11 1552 ? diag::warn_cxx98_compat_empty_scalar_initializer 1553 : diag::err_empty_scalar_initializer) 1554 << IList->getSourceRange(); 1555 } 1556 hadError = !SemaRef.getLangOpts().CPlusPlus11; 1557 ++Index; 1558 ++StructuredIndex; 1559 return; 1560 } 1561 1562 Expr *expr = IList->getInit(Index); 1563 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) { 1564 // FIXME: This is invalid, and accepting it causes overload resolution 1565 // to pick the wrong overload in some corner cases. 1566 if (!VerifyOnly) 1567 SemaRef.Diag(SubIList->getBeginLoc(), diag::ext_many_braces_around_init) 1568 << DeclType->isSizelessBuiltinType() << SubIList->getSourceRange(); 1569 1570 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList, 1571 StructuredIndex); 1572 return; 1573 } else if (isa<DesignatedInitExpr>(expr)) { 1574 if (!VerifyOnly) 1575 SemaRef.Diag(expr->getBeginLoc(), 1576 diag::err_designator_for_scalar_or_sizeless_init) 1577 << DeclType->isSizelessBuiltinType() << DeclType 1578 << expr->getSourceRange(); 1579 hadError = true; 1580 ++Index; 1581 ++StructuredIndex; 1582 return; 1583 } 1584 1585 ExprResult Result; 1586 if (VerifyOnly) { 1587 if (SemaRef.CanPerformCopyInitialization(Entity, expr)) 1588 Result = getDummyInit(); 1589 else 1590 Result = ExprError(); 1591 } else { 1592 Result = 1593 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr, 1594 /*TopLevelOfInitList=*/true); 1595 } 1596 1597 Expr *ResultExpr = nullptr; 1598 1599 if (Result.isInvalid()) 1600 hadError = true; // types weren't compatible. 1601 else { 1602 ResultExpr = Result.getAs<Expr>(); 1603 1604 if (ResultExpr != expr && !VerifyOnly) { 1605 // The type was promoted, update initializer list. 1606 // FIXME: Why are we updating the syntactic init list? 1607 IList->setInit(Index, ResultExpr); 1608 } 1609 } 1610 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr); 1611 ++Index; 1612 } 1613 1614 void InitListChecker::CheckReferenceType(const InitializedEntity &Entity, 1615 InitListExpr *IList, QualType DeclType, 1616 unsigned &Index, 1617 InitListExpr *StructuredList, 1618 unsigned &StructuredIndex) { 1619 if (Index >= IList->getNumInits()) { 1620 // FIXME: It would be wonderful if we could point at the actual member. In 1621 // general, it would be useful to pass location information down the stack, 1622 // so that we know the location (or decl) of the "current object" being 1623 // initialized. 1624 if (!VerifyOnly) 1625 SemaRef.Diag(IList->getBeginLoc(), 1626 diag::err_init_reference_member_uninitialized) 1627 << DeclType << IList->getSourceRange(); 1628 hadError = true; 1629 ++Index; 1630 ++StructuredIndex; 1631 return; 1632 } 1633 1634 Expr *expr = IList->getInit(Index); 1635 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) { 1636 if (!VerifyOnly) 1637 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list) 1638 << DeclType << IList->getSourceRange(); 1639 hadError = true; 1640 ++Index; 1641 ++StructuredIndex; 1642 return; 1643 } 1644 1645 ExprResult Result; 1646 if (VerifyOnly) { 1647 if (SemaRef.CanPerformCopyInitialization(Entity,expr)) 1648 Result = getDummyInit(); 1649 else 1650 Result = ExprError(); 1651 } else { 1652 Result = 1653 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr, 1654 /*TopLevelOfInitList=*/true); 1655 } 1656 1657 if (Result.isInvalid()) 1658 hadError = true; 1659 1660 expr = Result.getAs<Expr>(); 1661 // FIXME: Why are we updating the syntactic init list? 1662 if (!VerifyOnly && expr) 1663 IList->setInit(Index, expr); 1664 1665 UpdateStructuredListElement(StructuredList, StructuredIndex, expr); 1666 ++Index; 1667 } 1668 1669 void InitListChecker::CheckVectorType(const InitializedEntity &Entity, 1670 InitListExpr *IList, QualType DeclType, 1671 unsigned &Index, 1672 InitListExpr *StructuredList, 1673 unsigned &StructuredIndex) { 1674 const VectorType *VT = DeclType->castAs<VectorType>(); 1675 unsigned maxElements = VT->getNumElements(); 1676 unsigned numEltsInit = 0; 1677 QualType elementType = VT->getElementType(); 1678 1679 if (Index >= IList->getNumInits()) { 1680 // Make sure the element type can be value-initialized. 1681 CheckEmptyInitializable( 1682 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity), 1683 IList->getEndLoc()); 1684 return; 1685 } 1686 1687 if (!SemaRef.getLangOpts().OpenCL) { 1688 // If the initializing element is a vector, try to copy-initialize 1689 // instead of breaking it apart (which is doomed to failure anyway). 1690 Expr *Init = IList->getInit(Index); 1691 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) { 1692 ExprResult Result; 1693 if (VerifyOnly) { 1694 if (SemaRef.CanPerformCopyInitialization(Entity, Init)) 1695 Result = getDummyInit(); 1696 else 1697 Result = ExprError(); 1698 } else { 1699 Result = 1700 SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init, 1701 /*TopLevelOfInitList=*/true); 1702 } 1703 1704 Expr *ResultExpr = nullptr; 1705 if (Result.isInvalid()) 1706 hadError = true; // types weren't compatible. 1707 else { 1708 ResultExpr = Result.getAs<Expr>(); 1709 1710 if (ResultExpr != Init && !VerifyOnly) { 1711 // The type was promoted, update initializer list. 1712 // FIXME: Why are we updating the syntactic init list? 1713 IList->setInit(Index, ResultExpr); 1714 } 1715 } 1716 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr); 1717 ++Index; 1718 return; 1719 } 1720 1721 InitializedEntity ElementEntity = 1722 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); 1723 1724 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) { 1725 // Don't attempt to go past the end of the init list 1726 if (Index >= IList->getNumInits()) { 1727 CheckEmptyInitializable(ElementEntity, IList->getEndLoc()); 1728 break; 1729 } 1730 1731 ElementEntity.setElementIndex(Index); 1732 CheckSubElementType(ElementEntity, IList, elementType, Index, 1733 StructuredList, StructuredIndex); 1734 } 1735 1736 if (VerifyOnly) 1737 return; 1738 1739 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian(); 1740 const VectorType *T = Entity.getType()->castAs<VectorType>(); 1741 if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector || 1742 T->getVectorKind() == VectorType::NeonPolyVector)) { 1743 // The ability to use vector initializer lists is a GNU vector extension 1744 // and is unrelated to the NEON intrinsics in arm_neon.h. On little 1745 // endian machines it works fine, however on big endian machines it 1746 // exhibits surprising behaviour: 1747 // 1748 // uint32x2_t x = {42, 64}; 1749 // return vget_lane_u32(x, 0); // Will return 64. 1750 // 1751 // Because of this, explicitly call out that it is non-portable. 1752 // 1753 SemaRef.Diag(IList->getBeginLoc(), 1754 diag::warn_neon_vector_initializer_non_portable); 1755 1756 const char *typeCode; 1757 unsigned typeSize = SemaRef.Context.getTypeSize(elementType); 1758 1759 if (elementType->isFloatingType()) 1760 typeCode = "f"; 1761 else if (elementType->isSignedIntegerType()) 1762 typeCode = "s"; 1763 else if (elementType->isUnsignedIntegerType()) 1764 typeCode = "u"; 1765 else 1766 llvm_unreachable("Invalid element type!"); 1767 1768 SemaRef.Diag(IList->getBeginLoc(), 1769 SemaRef.Context.getTypeSize(VT) > 64 1770 ? diag::note_neon_vector_initializer_non_portable_q 1771 : diag::note_neon_vector_initializer_non_portable) 1772 << typeCode << typeSize; 1773 } 1774 1775 return; 1776 } 1777 1778 InitializedEntity ElementEntity = 1779 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); 1780 1781 // OpenCL initializers allows vectors to be constructed from vectors. 1782 for (unsigned i = 0; i < maxElements; ++i) { 1783 // Don't attempt to go past the end of the init list 1784 if (Index >= IList->getNumInits()) 1785 break; 1786 1787 ElementEntity.setElementIndex(Index); 1788 1789 QualType IType = IList->getInit(Index)->getType(); 1790 if (!IType->isVectorType()) { 1791 CheckSubElementType(ElementEntity, IList, elementType, Index, 1792 StructuredList, StructuredIndex); 1793 ++numEltsInit; 1794 } else { 1795 QualType VecType; 1796 const VectorType *IVT = IType->castAs<VectorType>(); 1797 unsigned numIElts = IVT->getNumElements(); 1798 1799 if (IType->isExtVectorType()) 1800 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts); 1801 else 1802 VecType = SemaRef.Context.getVectorType(elementType, numIElts, 1803 IVT->getVectorKind()); 1804 CheckSubElementType(ElementEntity, IList, VecType, Index, 1805 StructuredList, StructuredIndex); 1806 numEltsInit += numIElts; 1807 } 1808 } 1809 1810 // OpenCL requires all elements to be initialized. 1811 if (numEltsInit != maxElements) { 1812 if (!VerifyOnly) 1813 SemaRef.Diag(IList->getBeginLoc(), 1814 diag::err_vector_incorrect_num_initializers) 1815 << (numEltsInit < maxElements) << maxElements << numEltsInit; 1816 hadError = true; 1817 } 1818 } 1819 1820 /// Check if the type of a class element has an accessible destructor, and marks 1821 /// it referenced. Returns true if we shouldn't form a reference to the 1822 /// destructor. 1823 /// 1824 /// Aggregate initialization requires a class element's destructor be 1825 /// accessible per 11.6.1 [dcl.init.aggr]: 1826 /// 1827 /// The destructor for each element of class type is potentially invoked 1828 /// (15.4 [class.dtor]) from the context where the aggregate initialization 1829 /// occurs. 1830 static bool checkDestructorReference(QualType ElementType, SourceLocation Loc, 1831 Sema &SemaRef) { 1832 auto *CXXRD = ElementType->getAsCXXRecordDecl(); 1833 if (!CXXRD) 1834 return false; 1835 1836 CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(CXXRD); 1837 SemaRef.CheckDestructorAccess(Loc, Destructor, 1838 SemaRef.PDiag(diag::err_access_dtor_temp) 1839 << ElementType); 1840 SemaRef.MarkFunctionReferenced(Loc, Destructor); 1841 return SemaRef.DiagnoseUseOfDecl(Destructor, Loc); 1842 } 1843 1844 void InitListChecker::CheckArrayType(const InitializedEntity &Entity, 1845 InitListExpr *IList, QualType &DeclType, 1846 llvm::APSInt elementIndex, 1847 bool SubobjectIsDesignatorContext, 1848 unsigned &Index, 1849 InitListExpr *StructuredList, 1850 unsigned &StructuredIndex) { 1851 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType); 1852 1853 if (!VerifyOnly) { 1854 if (checkDestructorReference(arrayType->getElementType(), 1855 IList->getEndLoc(), SemaRef)) { 1856 hadError = true; 1857 return; 1858 } 1859 } 1860 1861 // Check for the special-case of initializing an array with a string. 1862 if (Index < IList->getNumInits()) { 1863 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) == 1864 SIF_None) { 1865 // We place the string literal directly into the resulting 1866 // initializer list. This is the only place where the structure 1867 // of the structured initializer list doesn't match exactly, 1868 // because doing so would involve allocating one character 1869 // constant for each string. 1870 // FIXME: Should we do these checks in verify-only mode too? 1871 if (!VerifyOnly) 1872 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef); 1873 if (StructuredList) { 1874 UpdateStructuredListElement(StructuredList, StructuredIndex, 1875 IList->getInit(Index)); 1876 StructuredList->resizeInits(SemaRef.Context, StructuredIndex); 1877 } 1878 ++Index; 1879 return; 1880 } 1881 } 1882 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) { 1883 // Check for VLAs; in standard C it would be possible to check this 1884 // earlier, but I don't know where clang accepts VLAs (gcc accepts 1885 // them in all sorts of strange places). 1886 if (!VerifyOnly) 1887 SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(), 1888 diag::err_variable_object_no_init) 1889 << VAT->getSizeExpr()->getSourceRange(); 1890 hadError = true; 1891 ++Index; 1892 ++StructuredIndex; 1893 return; 1894 } 1895 1896 // We might know the maximum number of elements in advance. 1897 llvm::APSInt maxElements(elementIndex.getBitWidth(), 1898 elementIndex.isUnsigned()); 1899 bool maxElementsKnown = false; 1900 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) { 1901 maxElements = CAT->getSize(); 1902 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth()); 1903 elementIndex.setIsUnsigned(maxElements.isUnsigned()); 1904 maxElementsKnown = true; 1905 } 1906 1907 QualType elementType = arrayType->getElementType(); 1908 while (Index < IList->getNumInits()) { 1909 Expr *Init = IList->getInit(Index); 1910 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) { 1911 // If we're not the subobject that matches up with the '{' for 1912 // the designator, we shouldn't be handling the 1913 // designator. Return immediately. 1914 if (!SubobjectIsDesignatorContext) 1915 return; 1916 1917 // Handle this designated initializer. elementIndex will be 1918 // updated to be the next array element we'll initialize. 1919 if (CheckDesignatedInitializer(Entity, IList, DIE, 0, 1920 DeclType, nullptr, &elementIndex, Index, 1921 StructuredList, StructuredIndex, true, 1922 false)) { 1923 hadError = true; 1924 continue; 1925 } 1926 1927 if (elementIndex.getBitWidth() > maxElements.getBitWidth()) 1928 maxElements = maxElements.extend(elementIndex.getBitWidth()); 1929 else if (elementIndex.getBitWidth() < maxElements.getBitWidth()) 1930 elementIndex = elementIndex.extend(maxElements.getBitWidth()); 1931 elementIndex.setIsUnsigned(maxElements.isUnsigned()); 1932 1933 // If the array is of incomplete type, keep track of the number of 1934 // elements in the initializer. 1935 if (!maxElementsKnown && elementIndex > maxElements) 1936 maxElements = elementIndex; 1937 1938 continue; 1939 } 1940 1941 // If we know the maximum number of elements, and we've already 1942 // hit it, stop consuming elements in the initializer list. 1943 if (maxElementsKnown && elementIndex == maxElements) 1944 break; 1945 1946 InitializedEntity ElementEntity = 1947 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex, 1948 Entity); 1949 // Check this element. 1950 CheckSubElementType(ElementEntity, IList, elementType, Index, 1951 StructuredList, StructuredIndex); 1952 ++elementIndex; 1953 1954 // If the array is of incomplete type, keep track of the number of 1955 // elements in the initializer. 1956 if (!maxElementsKnown && elementIndex > maxElements) 1957 maxElements = elementIndex; 1958 } 1959 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) { 1960 // If this is an incomplete array type, the actual type needs to 1961 // be calculated here. 1962 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned()); 1963 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) { 1964 // Sizing an array implicitly to zero is not allowed by ISO C, 1965 // but is supported by GNU. 1966 SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size); 1967 } 1968 1969 DeclType = SemaRef.Context.getConstantArrayType( 1970 elementType, maxElements, nullptr, ArrayType::Normal, 0); 1971 } 1972 if (!hadError) { 1973 // If there are any members of the array that get value-initialized, check 1974 // that is possible. That happens if we know the bound and don't have 1975 // enough elements, or if we're performing an array new with an unknown 1976 // bound. 1977 if ((maxElementsKnown && elementIndex < maxElements) || 1978 Entity.isVariableLengthArrayNew()) 1979 CheckEmptyInitializable( 1980 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity), 1981 IList->getEndLoc()); 1982 } 1983 } 1984 1985 bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity, 1986 Expr *InitExpr, 1987 FieldDecl *Field, 1988 bool TopLevelObject) { 1989 // Handle GNU flexible array initializers. 1990 unsigned FlexArrayDiag; 1991 if (isa<InitListExpr>(InitExpr) && 1992 cast<InitListExpr>(InitExpr)->getNumInits() == 0) { 1993 // Empty flexible array init always allowed as an extension 1994 FlexArrayDiag = diag::ext_flexible_array_init; 1995 } else if (SemaRef.getLangOpts().CPlusPlus) { 1996 // Disallow flexible array init in C++; it is not required for gcc 1997 // compatibility, and it needs work to IRGen correctly in general. 1998 FlexArrayDiag = diag::err_flexible_array_init; 1999 } else if (!TopLevelObject) { 2000 // Disallow flexible array init on non-top-level object 2001 FlexArrayDiag = diag::err_flexible_array_init; 2002 } else if (Entity.getKind() != InitializedEntity::EK_Variable) { 2003 // Disallow flexible array init on anything which is not a variable. 2004 FlexArrayDiag = diag::err_flexible_array_init; 2005 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) { 2006 // Disallow flexible array init on local variables. 2007 FlexArrayDiag = diag::err_flexible_array_init; 2008 } else { 2009 // Allow other cases. 2010 FlexArrayDiag = diag::ext_flexible_array_init; 2011 } 2012 2013 if (!VerifyOnly) { 2014 SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag) 2015 << InitExpr->getBeginLoc(); 2016 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 2017 << Field; 2018 } 2019 2020 return FlexArrayDiag != diag::ext_flexible_array_init; 2021 } 2022 2023 void InitListChecker::CheckStructUnionTypes( 2024 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType, 2025 CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field, 2026 bool SubobjectIsDesignatorContext, unsigned &Index, 2027 InitListExpr *StructuredList, unsigned &StructuredIndex, 2028 bool TopLevelObject) { 2029 RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl(); 2030 2031 // If the record is invalid, some of it's members are invalid. To avoid 2032 // confusion, we forgo checking the intializer for the entire record. 2033 if (structDecl->isInvalidDecl()) { 2034 // Assume it was supposed to consume a single initializer. 2035 ++Index; 2036 hadError = true; 2037 return; 2038 } 2039 2040 if (DeclType->isUnionType() && IList->getNumInits() == 0) { 2041 RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl(); 2042 2043 if (!VerifyOnly) 2044 for (FieldDecl *FD : RD->fields()) { 2045 QualType ET = SemaRef.Context.getBaseElementType(FD->getType()); 2046 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) { 2047 hadError = true; 2048 return; 2049 } 2050 } 2051 2052 // If there's a default initializer, use it. 2053 if (isa<CXXRecordDecl>(RD) && 2054 cast<CXXRecordDecl>(RD)->hasInClassInitializer()) { 2055 if (!StructuredList) 2056 return; 2057 for (RecordDecl::field_iterator FieldEnd = RD->field_end(); 2058 Field != FieldEnd; ++Field) { 2059 if (Field->hasInClassInitializer()) { 2060 StructuredList->setInitializedFieldInUnion(*Field); 2061 // FIXME: Actually build a CXXDefaultInitExpr? 2062 return; 2063 } 2064 } 2065 } 2066 2067 // Value-initialize the first member of the union that isn't an unnamed 2068 // bitfield. 2069 for (RecordDecl::field_iterator FieldEnd = RD->field_end(); 2070 Field != FieldEnd; ++Field) { 2071 if (!Field->isUnnamedBitfield()) { 2072 CheckEmptyInitializable( 2073 InitializedEntity::InitializeMember(*Field, &Entity), 2074 IList->getEndLoc()); 2075 if (StructuredList) 2076 StructuredList->setInitializedFieldInUnion(*Field); 2077 break; 2078 } 2079 } 2080 return; 2081 } 2082 2083 bool InitializedSomething = false; 2084 2085 // If we have any base classes, they are initialized prior to the fields. 2086 for (auto &Base : Bases) { 2087 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr; 2088 2089 // Designated inits always initialize fields, so if we see one, all 2090 // remaining base classes have no explicit initializer. 2091 if (Init && isa<DesignatedInitExpr>(Init)) 2092 Init = nullptr; 2093 2094 SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc(); 2095 InitializedEntity BaseEntity = InitializedEntity::InitializeBase( 2096 SemaRef.Context, &Base, false, &Entity); 2097 if (Init) { 2098 CheckSubElementType(BaseEntity, IList, Base.getType(), Index, 2099 StructuredList, StructuredIndex); 2100 InitializedSomething = true; 2101 } else { 2102 CheckEmptyInitializable(BaseEntity, InitLoc); 2103 } 2104 2105 if (!VerifyOnly) 2106 if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) { 2107 hadError = true; 2108 return; 2109 } 2110 } 2111 2112 // If structDecl is a forward declaration, this loop won't do 2113 // anything except look at designated initializers; That's okay, 2114 // because an error should get printed out elsewhere. It might be 2115 // worthwhile to skip over the rest of the initializer, though. 2116 RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl(); 2117 RecordDecl::field_iterator FieldEnd = RD->field_end(); 2118 bool CheckForMissingFields = 2119 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()); 2120 bool HasDesignatedInit = false; 2121 2122 while (Index < IList->getNumInits()) { 2123 Expr *Init = IList->getInit(Index); 2124 SourceLocation InitLoc = Init->getBeginLoc(); 2125 2126 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) { 2127 // If we're not the subobject that matches up with the '{' for 2128 // the designator, we shouldn't be handling the 2129 // designator. Return immediately. 2130 if (!SubobjectIsDesignatorContext) 2131 return; 2132 2133 HasDesignatedInit = true; 2134 2135 // Handle this designated initializer. Field will be updated to 2136 // the next field that we'll be initializing. 2137 if (CheckDesignatedInitializer(Entity, IList, DIE, 0, 2138 DeclType, &Field, nullptr, Index, 2139 StructuredList, StructuredIndex, 2140 true, TopLevelObject)) 2141 hadError = true; 2142 else if (!VerifyOnly) { 2143 // Find the field named by the designated initializer. 2144 RecordDecl::field_iterator F = RD->field_begin(); 2145 while (std::next(F) != Field) 2146 ++F; 2147 QualType ET = SemaRef.Context.getBaseElementType(F->getType()); 2148 if (checkDestructorReference(ET, InitLoc, SemaRef)) { 2149 hadError = true; 2150 return; 2151 } 2152 } 2153 2154 InitializedSomething = true; 2155 2156 // Disable check for missing fields when designators are used. 2157 // This matches gcc behaviour. 2158 CheckForMissingFields = false; 2159 continue; 2160 } 2161 2162 if (Field == FieldEnd) { 2163 // We've run out of fields. We're done. 2164 break; 2165 } 2166 2167 // We've already initialized a member of a union. We're done. 2168 if (InitializedSomething && DeclType->isUnionType()) 2169 break; 2170 2171 // If we've hit the flexible array member at the end, we're done. 2172 if (Field->getType()->isIncompleteArrayType()) 2173 break; 2174 2175 if (Field->isUnnamedBitfield()) { 2176 // Don't initialize unnamed bitfields, e.g. "int : 20;" 2177 ++Field; 2178 continue; 2179 } 2180 2181 // Make sure we can use this declaration. 2182 bool InvalidUse; 2183 if (VerifyOnly) 2184 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid); 2185 else 2186 InvalidUse = SemaRef.DiagnoseUseOfDecl( 2187 *Field, IList->getInit(Index)->getBeginLoc()); 2188 if (InvalidUse) { 2189 ++Index; 2190 ++Field; 2191 hadError = true; 2192 continue; 2193 } 2194 2195 if (!VerifyOnly) { 2196 QualType ET = SemaRef.Context.getBaseElementType(Field->getType()); 2197 if (checkDestructorReference(ET, InitLoc, SemaRef)) { 2198 hadError = true; 2199 return; 2200 } 2201 } 2202 2203 InitializedEntity MemberEntity = 2204 InitializedEntity::InitializeMember(*Field, &Entity); 2205 CheckSubElementType(MemberEntity, IList, Field->getType(), Index, 2206 StructuredList, StructuredIndex); 2207 InitializedSomething = true; 2208 2209 if (DeclType->isUnionType() && StructuredList) { 2210 // Initialize the first field within the union. 2211 StructuredList->setInitializedFieldInUnion(*Field); 2212 } 2213 2214 ++Field; 2215 } 2216 2217 // Emit warnings for missing struct field initializers. 2218 if (!VerifyOnly && InitializedSomething && CheckForMissingFields && 2219 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() && 2220 !DeclType->isUnionType()) { 2221 // It is possible we have one or more unnamed bitfields remaining. 2222 // Find first (if any) named field and emit warning. 2223 for (RecordDecl::field_iterator it = Field, end = RD->field_end(); 2224 it != end; ++it) { 2225 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) { 2226 SemaRef.Diag(IList->getSourceRange().getEnd(), 2227 diag::warn_missing_field_initializers) << *it; 2228 break; 2229 } 2230 } 2231 } 2232 2233 // Check that any remaining fields can be value-initialized if we're not 2234 // building a structured list. (If we are, we'll check this later.) 2235 if (!StructuredList && Field != FieldEnd && !DeclType->isUnionType() && 2236 !Field->getType()->isIncompleteArrayType()) { 2237 for (; Field != FieldEnd && !hadError; ++Field) { 2238 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer()) 2239 CheckEmptyInitializable( 2240 InitializedEntity::InitializeMember(*Field, &Entity), 2241 IList->getEndLoc()); 2242 } 2243 } 2244 2245 // Check that the types of the remaining fields have accessible destructors. 2246 if (!VerifyOnly) { 2247 // If the initializer expression has a designated initializer, check the 2248 // elements for which a designated initializer is not provided too. 2249 RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin() 2250 : Field; 2251 for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) { 2252 QualType ET = SemaRef.Context.getBaseElementType(I->getType()); 2253 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) { 2254 hadError = true; 2255 return; 2256 } 2257 } 2258 } 2259 2260 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() || 2261 Index >= IList->getNumInits()) 2262 return; 2263 2264 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field, 2265 TopLevelObject)) { 2266 hadError = true; 2267 ++Index; 2268 return; 2269 } 2270 2271 InitializedEntity MemberEntity = 2272 InitializedEntity::InitializeMember(*Field, &Entity); 2273 2274 if (isa<InitListExpr>(IList->getInit(Index))) 2275 CheckSubElementType(MemberEntity, IList, Field->getType(), Index, 2276 StructuredList, StructuredIndex); 2277 else 2278 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index, 2279 StructuredList, StructuredIndex); 2280 } 2281 2282 /// Expand a field designator that refers to a member of an 2283 /// anonymous struct or union into a series of field designators that 2284 /// refers to the field within the appropriate subobject. 2285 /// 2286 static void ExpandAnonymousFieldDesignator(Sema &SemaRef, 2287 DesignatedInitExpr *DIE, 2288 unsigned DesigIdx, 2289 IndirectFieldDecl *IndirectField) { 2290 typedef DesignatedInitExpr::Designator Designator; 2291 2292 // Build the replacement designators. 2293 SmallVector<Designator, 4> Replacements; 2294 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(), 2295 PE = IndirectField->chain_end(); PI != PE; ++PI) { 2296 if (PI + 1 == PE) 2297 Replacements.push_back(Designator((IdentifierInfo *)nullptr, 2298 DIE->getDesignator(DesigIdx)->getDotLoc(), 2299 DIE->getDesignator(DesigIdx)->getFieldLoc())); 2300 else 2301 Replacements.push_back(Designator((IdentifierInfo *)nullptr, 2302 SourceLocation(), SourceLocation())); 2303 assert(isa<FieldDecl>(*PI)); 2304 Replacements.back().setField(cast<FieldDecl>(*PI)); 2305 } 2306 2307 // Expand the current designator into the set of replacement 2308 // designators, so we have a full subobject path down to where the 2309 // member of the anonymous struct/union is actually stored. 2310 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0], 2311 &Replacements[0] + Replacements.size()); 2312 } 2313 2314 static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef, 2315 DesignatedInitExpr *DIE) { 2316 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1; 2317 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs); 2318 for (unsigned I = 0; I < NumIndexExprs; ++I) 2319 IndexExprs[I] = DIE->getSubExpr(I + 1); 2320 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(), 2321 IndexExprs, 2322 DIE->getEqualOrColonLoc(), 2323 DIE->usesGNUSyntax(), DIE->getInit()); 2324 } 2325 2326 namespace { 2327 2328 // Callback to only accept typo corrections that are for field members of 2329 // the given struct or union. 2330 class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback { 2331 public: 2332 explicit FieldInitializerValidatorCCC(RecordDecl *RD) 2333 : Record(RD) {} 2334 2335 bool ValidateCandidate(const TypoCorrection &candidate) override { 2336 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>(); 2337 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record); 2338 } 2339 2340 std::unique_ptr<CorrectionCandidateCallback> clone() override { 2341 return std::make_unique<FieldInitializerValidatorCCC>(*this); 2342 } 2343 2344 private: 2345 RecordDecl *Record; 2346 }; 2347 2348 } // end anonymous namespace 2349 2350 /// Check the well-formedness of a C99 designated initializer. 2351 /// 2352 /// Determines whether the designated initializer @p DIE, which 2353 /// resides at the given @p Index within the initializer list @p 2354 /// IList, is well-formed for a current object of type @p DeclType 2355 /// (C99 6.7.8). The actual subobject that this designator refers to 2356 /// within the current subobject is returned in either 2357 /// @p NextField or @p NextElementIndex (whichever is appropriate). 2358 /// 2359 /// @param IList The initializer list in which this designated 2360 /// initializer occurs. 2361 /// 2362 /// @param DIE The designated initializer expression. 2363 /// 2364 /// @param DesigIdx The index of the current designator. 2365 /// 2366 /// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17), 2367 /// into which the designation in @p DIE should refer. 2368 /// 2369 /// @param NextField If non-NULL and the first designator in @p DIE is 2370 /// a field, this will be set to the field declaration corresponding 2371 /// to the field named by the designator. On input, this is expected to be 2372 /// the next field that would be initialized in the absence of designation, 2373 /// if the complete object being initialized is a struct. 2374 /// 2375 /// @param NextElementIndex If non-NULL and the first designator in @p 2376 /// DIE is an array designator or GNU array-range designator, this 2377 /// will be set to the last index initialized by this designator. 2378 /// 2379 /// @param Index Index into @p IList where the designated initializer 2380 /// @p DIE occurs. 2381 /// 2382 /// @param StructuredList The initializer list expression that 2383 /// describes all of the subobject initializers in the order they'll 2384 /// actually be initialized. 2385 /// 2386 /// @returns true if there was an error, false otherwise. 2387 bool 2388 InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity, 2389 InitListExpr *IList, 2390 DesignatedInitExpr *DIE, 2391 unsigned DesigIdx, 2392 QualType &CurrentObjectType, 2393 RecordDecl::field_iterator *NextField, 2394 llvm::APSInt *NextElementIndex, 2395 unsigned &Index, 2396 InitListExpr *StructuredList, 2397 unsigned &StructuredIndex, 2398 bool FinishSubobjectInit, 2399 bool TopLevelObject) { 2400 if (DesigIdx == DIE->size()) { 2401 // C++20 designated initialization can result in direct-list-initialization 2402 // of the designated subobject. This is the only way that we can end up 2403 // performing direct initialization as part of aggregate initialization, so 2404 // it needs special handling. 2405 if (DIE->isDirectInit()) { 2406 Expr *Init = DIE->getInit(); 2407 assert(isa<InitListExpr>(Init) && 2408 "designator result in direct non-list initialization?"); 2409 InitializationKind Kind = InitializationKind::CreateDirectList( 2410 DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc()); 2411 InitializationSequence Seq(SemaRef, Entity, Kind, Init, 2412 /*TopLevelOfInitList*/ true); 2413 if (StructuredList) { 2414 ExprResult Result = VerifyOnly 2415 ? getDummyInit() 2416 : Seq.Perform(SemaRef, Entity, Kind, Init); 2417 UpdateStructuredListElement(StructuredList, StructuredIndex, 2418 Result.get()); 2419 } 2420 ++Index; 2421 return !Seq; 2422 } 2423 2424 // Check the actual initialization for the designated object type. 2425 bool prevHadError = hadError; 2426 2427 // Temporarily remove the designator expression from the 2428 // initializer list that the child calls see, so that we don't try 2429 // to re-process the designator. 2430 unsigned OldIndex = Index; 2431 IList->setInit(OldIndex, DIE->getInit()); 2432 2433 CheckSubElementType(Entity, IList, CurrentObjectType, Index, StructuredList, 2434 StructuredIndex, /*DirectlyDesignated=*/true); 2435 2436 // Restore the designated initializer expression in the syntactic 2437 // form of the initializer list. 2438 if (IList->getInit(OldIndex) != DIE->getInit()) 2439 DIE->setInit(IList->getInit(OldIndex)); 2440 IList->setInit(OldIndex, DIE); 2441 2442 return hadError && !prevHadError; 2443 } 2444 2445 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx); 2446 bool IsFirstDesignator = (DesigIdx == 0); 2447 if (IsFirstDesignator ? FullyStructuredList : StructuredList) { 2448 // Determine the structural initializer list that corresponds to the 2449 // current subobject. 2450 if (IsFirstDesignator) 2451 StructuredList = FullyStructuredList; 2452 else { 2453 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ? 2454 StructuredList->getInit(StructuredIndex) : nullptr; 2455 if (!ExistingInit && StructuredList->hasArrayFiller()) 2456 ExistingInit = StructuredList->getArrayFiller(); 2457 2458 if (!ExistingInit) 2459 StructuredList = getStructuredSubobjectInit( 2460 IList, Index, CurrentObjectType, StructuredList, StructuredIndex, 2461 SourceRange(D->getBeginLoc(), DIE->getEndLoc())); 2462 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit)) 2463 StructuredList = Result; 2464 else { 2465 // We are creating an initializer list that initializes the 2466 // subobjects of the current object, but there was already an 2467 // initialization that completely initialized the current 2468 // subobject, e.g., by a compound literal: 2469 // 2470 // struct X { int a, b; }; 2471 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 }; 2472 // 2473 // Here, xs[0].a == 1 and xs[0].b == 3, since the second, 2474 // designated initializer re-initializes only its current object 2475 // subobject [0].b. 2476 diagnoseInitOverride(ExistingInit, 2477 SourceRange(D->getBeginLoc(), DIE->getEndLoc()), 2478 /*FullyOverwritten=*/false); 2479 2480 if (!VerifyOnly) { 2481 if (DesignatedInitUpdateExpr *E = 2482 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit)) 2483 StructuredList = E->getUpdater(); 2484 else { 2485 DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context) 2486 DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(), 2487 ExistingInit, DIE->getEndLoc()); 2488 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE); 2489 StructuredList = DIUE->getUpdater(); 2490 } 2491 } else { 2492 // We don't need to track the structured representation of a 2493 // designated init update of an already-fully-initialized object in 2494 // verify-only mode. The only reason we would need the structure is 2495 // to determine where the uninitialized "holes" are, and in this 2496 // case, we know there aren't any and we can't introduce any. 2497 StructuredList = nullptr; 2498 } 2499 } 2500 } 2501 } 2502 2503 if (D->isFieldDesignator()) { 2504 // C99 6.7.8p7: 2505 // 2506 // If a designator has the form 2507 // 2508 // . identifier 2509 // 2510 // then the current object (defined below) shall have 2511 // structure or union type and the identifier shall be the 2512 // name of a member of that type. 2513 const RecordType *RT = CurrentObjectType->getAs<RecordType>(); 2514 if (!RT) { 2515 SourceLocation Loc = D->getDotLoc(); 2516 if (Loc.isInvalid()) 2517 Loc = D->getFieldLoc(); 2518 if (!VerifyOnly) 2519 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr) 2520 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType; 2521 ++Index; 2522 return true; 2523 } 2524 2525 FieldDecl *KnownField = D->getField(); 2526 if (!KnownField) { 2527 IdentifierInfo *FieldName = D->getFieldName(); 2528 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName); 2529 for (NamedDecl *ND : Lookup) { 2530 if (auto *FD = dyn_cast<FieldDecl>(ND)) { 2531 KnownField = FD; 2532 break; 2533 } 2534 if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) { 2535 // In verify mode, don't modify the original. 2536 if (VerifyOnly) 2537 DIE = CloneDesignatedInitExpr(SemaRef, DIE); 2538 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD); 2539 D = DIE->getDesignator(DesigIdx); 2540 KnownField = cast<FieldDecl>(*IFD->chain_begin()); 2541 break; 2542 } 2543 } 2544 if (!KnownField) { 2545 if (VerifyOnly) { 2546 ++Index; 2547 return true; // No typo correction when just trying this out. 2548 } 2549 2550 // Name lookup found something, but it wasn't a field. 2551 if (!Lookup.empty()) { 2552 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield) 2553 << FieldName; 2554 SemaRef.Diag(Lookup.front()->getLocation(), 2555 diag::note_field_designator_found); 2556 ++Index; 2557 return true; 2558 } 2559 2560 // Name lookup didn't find anything. 2561 // Determine whether this was a typo for another field name. 2562 FieldInitializerValidatorCCC CCC(RT->getDecl()); 2563 if (TypoCorrection Corrected = SemaRef.CorrectTypo( 2564 DeclarationNameInfo(FieldName, D->getFieldLoc()), 2565 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC, 2566 Sema::CTK_ErrorRecovery, RT->getDecl())) { 2567 SemaRef.diagnoseTypo( 2568 Corrected, 2569 SemaRef.PDiag(diag::err_field_designator_unknown_suggest) 2570 << FieldName << CurrentObjectType); 2571 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>(); 2572 hadError = true; 2573 } else { 2574 // Typo correction didn't find anything. 2575 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown) 2576 << FieldName << CurrentObjectType; 2577 ++Index; 2578 return true; 2579 } 2580 } 2581 } 2582 2583 unsigned NumBases = 0; 2584 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) 2585 NumBases = CXXRD->getNumBases(); 2586 2587 unsigned FieldIndex = NumBases; 2588 2589 for (auto *FI : RT->getDecl()->fields()) { 2590 if (FI->isUnnamedBitfield()) 2591 continue; 2592 if (declaresSameEntity(KnownField, FI)) { 2593 KnownField = FI; 2594 break; 2595 } 2596 ++FieldIndex; 2597 } 2598 2599 RecordDecl::field_iterator Field = 2600 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField)); 2601 2602 // All of the fields of a union are located at the same place in 2603 // the initializer list. 2604 if (RT->getDecl()->isUnion()) { 2605 FieldIndex = 0; 2606 if (StructuredList) { 2607 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion(); 2608 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) { 2609 assert(StructuredList->getNumInits() == 1 2610 && "A union should never have more than one initializer!"); 2611 2612 Expr *ExistingInit = StructuredList->getInit(0); 2613 if (ExistingInit) { 2614 // We're about to throw away an initializer, emit warning. 2615 diagnoseInitOverride( 2616 ExistingInit, SourceRange(D->getBeginLoc(), DIE->getEndLoc())); 2617 } 2618 2619 // remove existing initializer 2620 StructuredList->resizeInits(SemaRef.Context, 0); 2621 StructuredList->setInitializedFieldInUnion(nullptr); 2622 } 2623 2624 StructuredList->setInitializedFieldInUnion(*Field); 2625 } 2626 } 2627 2628 // Make sure we can use this declaration. 2629 bool InvalidUse; 2630 if (VerifyOnly) 2631 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid); 2632 else 2633 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc()); 2634 if (InvalidUse) { 2635 ++Index; 2636 return true; 2637 } 2638 2639 // C++20 [dcl.init.list]p3: 2640 // The ordered identifiers in the designators of the designated- 2641 // initializer-list shall form a subsequence of the ordered identifiers 2642 // in the direct non-static data members of T. 2643 // 2644 // Note that this is not a condition on forming the aggregate 2645 // initialization, only on actually performing initialization, 2646 // so it is not checked in VerifyOnly mode. 2647 // 2648 // FIXME: This is the only reordering diagnostic we produce, and it only 2649 // catches cases where we have a top-level field designator that jumps 2650 // backwards. This is the only such case that is reachable in an 2651 // otherwise-valid C++20 program, so is the only case that's required for 2652 // conformance, but for consistency, we should diagnose all the other 2653 // cases where a designator takes us backwards too. 2654 if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus && 2655 NextField && 2656 (*NextField == RT->getDecl()->field_end() || 2657 (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) { 2658 // Find the field that we just initialized. 2659 FieldDecl *PrevField = nullptr; 2660 for (auto FI = RT->getDecl()->field_begin(); 2661 FI != RT->getDecl()->field_end(); ++FI) { 2662 if (FI->isUnnamedBitfield()) 2663 continue; 2664 if (*NextField != RT->getDecl()->field_end() && 2665 declaresSameEntity(*FI, **NextField)) 2666 break; 2667 PrevField = *FI; 2668 } 2669 2670 if (PrevField && 2671 PrevField->getFieldIndex() > KnownField->getFieldIndex()) { 2672 SemaRef.Diag(DIE->getBeginLoc(), diag::ext_designated_init_reordered) 2673 << KnownField << PrevField << DIE->getSourceRange(); 2674 2675 unsigned OldIndex = NumBases + PrevField->getFieldIndex(); 2676 if (StructuredList && OldIndex <= StructuredList->getNumInits()) { 2677 if (Expr *PrevInit = StructuredList->getInit(OldIndex)) { 2678 SemaRef.Diag(PrevInit->getBeginLoc(), 2679 diag::note_previous_field_init) 2680 << PrevField << PrevInit->getSourceRange(); 2681 } 2682 } 2683 } 2684 } 2685 2686 2687 // Update the designator with the field declaration. 2688 if (!VerifyOnly) 2689 D->setField(*Field); 2690 2691 // Make sure that our non-designated initializer list has space 2692 // for a subobject corresponding to this field. 2693 if (StructuredList && FieldIndex >= StructuredList->getNumInits()) 2694 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1); 2695 2696 // This designator names a flexible array member. 2697 if (Field->getType()->isIncompleteArrayType()) { 2698 bool Invalid = false; 2699 if ((DesigIdx + 1) != DIE->size()) { 2700 // We can't designate an object within the flexible array 2701 // member (because GCC doesn't allow it). 2702 if (!VerifyOnly) { 2703 DesignatedInitExpr::Designator *NextD 2704 = DIE->getDesignator(DesigIdx + 1); 2705 SemaRef.Diag(NextD->getBeginLoc(), 2706 diag::err_designator_into_flexible_array_member) 2707 << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc()); 2708 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 2709 << *Field; 2710 } 2711 Invalid = true; 2712 } 2713 2714 if (!hadError && !isa<InitListExpr>(DIE->getInit()) && 2715 !isa<StringLiteral>(DIE->getInit())) { 2716 // The initializer is not an initializer list. 2717 if (!VerifyOnly) { 2718 SemaRef.Diag(DIE->getInit()->getBeginLoc(), 2719 diag::err_flexible_array_init_needs_braces) 2720 << DIE->getInit()->getSourceRange(); 2721 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 2722 << *Field; 2723 } 2724 Invalid = true; 2725 } 2726 2727 // Check GNU flexible array initializer. 2728 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field, 2729 TopLevelObject)) 2730 Invalid = true; 2731 2732 if (Invalid) { 2733 ++Index; 2734 return true; 2735 } 2736 2737 // Initialize the array. 2738 bool prevHadError = hadError; 2739 unsigned newStructuredIndex = FieldIndex; 2740 unsigned OldIndex = Index; 2741 IList->setInit(Index, DIE->getInit()); 2742 2743 InitializedEntity MemberEntity = 2744 InitializedEntity::InitializeMember(*Field, &Entity); 2745 CheckSubElementType(MemberEntity, IList, Field->getType(), Index, 2746 StructuredList, newStructuredIndex); 2747 2748 IList->setInit(OldIndex, DIE); 2749 if (hadError && !prevHadError) { 2750 ++Field; 2751 ++FieldIndex; 2752 if (NextField) 2753 *NextField = Field; 2754 StructuredIndex = FieldIndex; 2755 return true; 2756 } 2757 } else { 2758 // Recurse to check later designated subobjects. 2759 QualType FieldType = Field->getType(); 2760 unsigned newStructuredIndex = FieldIndex; 2761 2762 InitializedEntity MemberEntity = 2763 InitializedEntity::InitializeMember(*Field, &Entity); 2764 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1, 2765 FieldType, nullptr, nullptr, Index, 2766 StructuredList, newStructuredIndex, 2767 FinishSubobjectInit, false)) 2768 return true; 2769 } 2770 2771 // Find the position of the next field to be initialized in this 2772 // subobject. 2773 ++Field; 2774 ++FieldIndex; 2775 2776 // If this the first designator, our caller will continue checking 2777 // the rest of this struct/class/union subobject. 2778 if (IsFirstDesignator) { 2779 if (NextField) 2780 *NextField = Field; 2781 StructuredIndex = FieldIndex; 2782 return false; 2783 } 2784 2785 if (!FinishSubobjectInit) 2786 return false; 2787 2788 // We've already initialized something in the union; we're done. 2789 if (RT->getDecl()->isUnion()) 2790 return hadError; 2791 2792 // Check the remaining fields within this class/struct/union subobject. 2793 bool prevHadError = hadError; 2794 2795 auto NoBases = 2796 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(), 2797 CXXRecordDecl::base_class_iterator()); 2798 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field, 2799 false, Index, StructuredList, FieldIndex); 2800 return hadError && !prevHadError; 2801 } 2802 2803 // C99 6.7.8p6: 2804 // 2805 // If a designator has the form 2806 // 2807 // [ constant-expression ] 2808 // 2809 // then the current object (defined below) shall have array 2810 // type and the expression shall be an integer constant 2811 // expression. If the array is of unknown size, any 2812 // nonnegative value is valid. 2813 // 2814 // Additionally, cope with the GNU extension that permits 2815 // designators of the form 2816 // 2817 // [ constant-expression ... constant-expression ] 2818 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType); 2819 if (!AT) { 2820 if (!VerifyOnly) 2821 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array) 2822 << CurrentObjectType; 2823 ++Index; 2824 return true; 2825 } 2826 2827 Expr *IndexExpr = nullptr; 2828 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex; 2829 if (D->isArrayDesignator()) { 2830 IndexExpr = DIE->getArrayIndex(*D); 2831 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context); 2832 DesignatedEndIndex = DesignatedStartIndex; 2833 } else { 2834 assert(D->isArrayRangeDesignator() && "Need array-range designator"); 2835 2836 DesignatedStartIndex = 2837 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context); 2838 DesignatedEndIndex = 2839 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context); 2840 IndexExpr = DIE->getArrayRangeEnd(*D); 2841 2842 // Codegen can't handle evaluating array range designators that have side 2843 // effects, because we replicate the AST value for each initialized element. 2844 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple 2845 // elements with something that has a side effect, so codegen can emit an 2846 // "error unsupported" error instead of miscompiling the app. 2847 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&& 2848 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly) 2849 FullyStructuredList->sawArrayRangeDesignator(); 2850 } 2851 2852 if (isa<ConstantArrayType>(AT)) { 2853 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false); 2854 DesignatedStartIndex 2855 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth()); 2856 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned()); 2857 DesignatedEndIndex 2858 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth()); 2859 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned()); 2860 if (DesignatedEndIndex >= MaxElements) { 2861 if (!VerifyOnly) 2862 SemaRef.Diag(IndexExpr->getBeginLoc(), 2863 diag::err_array_designator_too_large) 2864 << DesignatedEndIndex.toString(10) << MaxElements.toString(10) 2865 << IndexExpr->getSourceRange(); 2866 ++Index; 2867 return true; 2868 } 2869 } else { 2870 unsigned DesignatedIndexBitWidth = 2871 ConstantArrayType::getMaxSizeBits(SemaRef.Context); 2872 DesignatedStartIndex = 2873 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth); 2874 DesignatedEndIndex = 2875 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth); 2876 DesignatedStartIndex.setIsUnsigned(true); 2877 DesignatedEndIndex.setIsUnsigned(true); 2878 } 2879 2880 bool IsStringLiteralInitUpdate = 2881 StructuredList && StructuredList->isStringLiteralInit(); 2882 if (IsStringLiteralInitUpdate && VerifyOnly) { 2883 // We're just verifying an update to a string literal init. We don't need 2884 // to split the string up into individual characters to do that. 2885 StructuredList = nullptr; 2886 } else if (IsStringLiteralInitUpdate) { 2887 // We're modifying a string literal init; we have to decompose the string 2888 // so we can modify the individual characters. 2889 ASTContext &Context = SemaRef.Context; 2890 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens(); 2891 2892 // Compute the character type 2893 QualType CharTy = AT->getElementType(); 2894 2895 // Compute the type of the integer literals. 2896 QualType PromotedCharTy = CharTy; 2897 if (CharTy->isPromotableIntegerType()) 2898 PromotedCharTy = Context.getPromotedIntegerType(CharTy); 2899 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy); 2900 2901 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) { 2902 // Get the length of the string. 2903 uint64_t StrLen = SL->getLength(); 2904 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen)) 2905 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue(); 2906 StructuredList->resizeInits(Context, StrLen); 2907 2908 // Build a literal for each character in the string, and put them into 2909 // the init list. 2910 for (unsigned i = 0, e = StrLen; i != e; ++i) { 2911 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i)); 2912 Expr *Init = new (Context) IntegerLiteral( 2913 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc()); 2914 if (CharTy != PromotedCharTy) 2915 Init = 2916 ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast, Init, 2917 nullptr, VK_RValue, FPOptionsOverride()); 2918 StructuredList->updateInit(Context, i, Init); 2919 } 2920 } else { 2921 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr); 2922 std::string Str; 2923 Context.getObjCEncodingForType(E->getEncodedType(), Str); 2924 2925 // Get the length of the string. 2926 uint64_t StrLen = Str.size(); 2927 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen)) 2928 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue(); 2929 StructuredList->resizeInits(Context, StrLen); 2930 2931 // Build a literal for each character in the string, and put them into 2932 // the init list. 2933 for (unsigned i = 0, e = StrLen; i != e; ++i) { 2934 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]); 2935 Expr *Init = new (Context) IntegerLiteral( 2936 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc()); 2937 if (CharTy != PromotedCharTy) 2938 Init = 2939 ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast, Init, 2940 nullptr, VK_RValue, FPOptionsOverride()); 2941 StructuredList->updateInit(Context, i, Init); 2942 } 2943 } 2944 } 2945 2946 // Make sure that our non-designated initializer list has space 2947 // for a subobject corresponding to this array element. 2948 if (StructuredList && 2949 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits()) 2950 StructuredList->resizeInits(SemaRef.Context, 2951 DesignatedEndIndex.getZExtValue() + 1); 2952 2953 // Repeatedly perform subobject initializations in the range 2954 // [DesignatedStartIndex, DesignatedEndIndex]. 2955 2956 // Move to the next designator 2957 unsigned ElementIndex = DesignatedStartIndex.getZExtValue(); 2958 unsigned OldIndex = Index; 2959 2960 InitializedEntity ElementEntity = 2961 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); 2962 2963 while (DesignatedStartIndex <= DesignatedEndIndex) { 2964 // Recurse to check later designated subobjects. 2965 QualType ElementType = AT->getElementType(); 2966 Index = OldIndex; 2967 2968 ElementEntity.setElementIndex(ElementIndex); 2969 if (CheckDesignatedInitializer( 2970 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr, 2971 nullptr, Index, StructuredList, ElementIndex, 2972 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex), 2973 false)) 2974 return true; 2975 2976 // Move to the next index in the array that we'll be initializing. 2977 ++DesignatedStartIndex; 2978 ElementIndex = DesignatedStartIndex.getZExtValue(); 2979 } 2980 2981 // If this the first designator, our caller will continue checking 2982 // the rest of this array subobject. 2983 if (IsFirstDesignator) { 2984 if (NextElementIndex) 2985 *NextElementIndex = DesignatedStartIndex; 2986 StructuredIndex = ElementIndex; 2987 return false; 2988 } 2989 2990 if (!FinishSubobjectInit) 2991 return false; 2992 2993 // Check the remaining elements within this array subobject. 2994 bool prevHadError = hadError; 2995 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex, 2996 /*SubobjectIsDesignatorContext=*/false, Index, 2997 StructuredList, ElementIndex); 2998 return hadError && !prevHadError; 2999 } 3000 3001 // Get the structured initializer list for a subobject of type 3002 // @p CurrentObjectType. 3003 InitListExpr * 3004 InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, 3005 QualType CurrentObjectType, 3006 InitListExpr *StructuredList, 3007 unsigned StructuredIndex, 3008 SourceRange InitRange, 3009 bool IsFullyOverwritten) { 3010 if (!StructuredList) 3011 return nullptr; 3012 3013 Expr *ExistingInit = nullptr; 3014 if (StructuredIndex < StructuredList->getNumInits()) 3015 ExistingInit = StructuredList->getInit(StructuredIndex); 3016 3017 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit)) 3018 // There might have already been initializers for subobjects of the current 3019 // object, but a subsequent initializer list will overwrite the entirety 3020 // of the current object. (See DR 253 and C99 6.7.8p21). e.g., 3021 // 3022 // struct P { char x[6]; }; 3023 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } }; 3024 // 3025 // The first designated initializer is ignored, and l.x is just "f". 3026 if (!IsFullyOverwritten) 3027 return Result; 3028 3029 if (ExistingInit) { 3030 // We are creating an initializer list that initializes the 3031 // subobjects of the current object, but there was already an 3032 // initialization that completely initialized the current 3033 // subobject: 3034 // 3035 // struct X { int a, b; }; 3036 // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 }; 3037 // 3038 // Here, xs[0].a == 1 and xs[0].b == 3, since the second, 3039 // designated initializer overwrites the [0].b initializer 3040 // from the prior initialization. 3041 // 3042 // When the existing initializer is an expression rather than an 3043 // initializer list, we cannot decompose and update it in this way. 3044 // For example: 3045 // 3046 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 }; 3047 // 3048 // This case is handled by CheckDesignatedInitializer. 3049 diagnoseInitOverride(ExistingInit, InitRange); 3050 } 3051 3052 unsigned ExpectedNumInits = 0; 3053 if (Index < IList->getNumInits()) { 3054 if (auto *Init = dyn_cast_or_null<InitListExpr>(IList->getInit(Index))) 3055 ExpectedNumInits = Init->getNumInits(); 3056 else 3057 ExpectedNumInits = IList->getNumInits() - Index; 3058 } 3059 3060 InitListExpr *Result = 3061 createInitListExpr(CurrentObjectType, InitRange, ExpectedNumInits); 3062 3063 // Link this new initializer list into the structured initializer 3064 // lists. 3065 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result); 3066 return Result; 3067 } 3068 3069 InitListExpr * 3070 InitListChecker::createInitListExpr(QualType CurrentObjectType, 3071 SourceRange InitRange, 3072 unsigned ExpectedNumInits) { 3073 InitListExpr *Result 3074 = new (SemaRef.Context) InitListExpr(SemaRef.Context, 3075 InitRange.getBegin(), None, 3076 InitRange.getEnd()); 3077 3078 QualType ResultType = CurrentObjectType; 3079 if (!ResultType->isArrayType()) 3080 ResultType = ResultType.getNonLValueExprType(SemaRef.Context); 3081 Result->setType(ResultType); 3082 3083 // Pre-allocate storage for the structured initializer list. 3084 unsigned NumElements = 0; 3085 3086 if (const ArrayType *AType 3087 = SemaRef.Context.getAsArrayType(CurrentObjectType)) { 3088 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) { 3089 NumElements = CAType->getSize().getZExtValue(); 3090 // Simple heuristic so that we don't allocate a very large 3091 // initializer with many empty entries at the end. 3092 if (NumElements > ExpectedNumInits) 3093 NumElements = 0; 3094 } 3095 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) { 3096 NumElements = VType->getNumElements(); 3097 } else if (CurrentObjectType->isRecordType()) { 3098 NumElements = numStructUnionElements(CurrentObjectType); 3099 } 3100 3101 Result->reserveInits(SemaRef.Context, NumElements); 3102 3103 return Result; 3104 } 3105 3106 /// Update the initializer at index @p StructuredIndex within the 3107 /// structured initializer list to the value @p expr. 3108 void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList, 3109 unsigned &StructuredIndex, 3110 Expr *expr) { 3111 // No structured initializer list to update 3112 if (!StructuredList) 3113 return; 3114 3115 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context, 3116 StructuredIndex, expr)) { 3117 // This initializer overwrites a previous initializer. 3118 // No need to diagnose when `expr` is nullptr because a more relevant 3119 // diagnostic has already been issued and this diagnostic is potentially 3120 // noise. 3121 if (expr) 3122 diagnoseInitOverride(PrevInit, expr->getSourceRange()); 3123 } 3124 3125 ++StructuredIndex; 3126 } 3127 3128 /// Determine whether we can perform aggregate initialization for the purposes 3129 /// of overload resolution. 3130 bool Sema::CanPerformAggregateInitializationForOverloadResolution( 3131 const InitializedEntity &Entity, InitListExpr *From) { 3132 QualType Type = Entity.getType(); 3133 InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true, 3134 /*TreatUnavailableAsInvalid=*/false, 3135 /*InOverloadResolution=*/true); 3136 return !Check.HadError(); 3137 } 3138 3139 /// Check that the given Index expression is a valid array designator 3140 /// value. This is essentially just a wrapper around 3141 /// VerifyIntegerConstantExpression that also checks for negative values 3142 /// and produces a reasonable diagnostic if there is a 3143 /// failure. Returns the index expression, possibly with an implicit cast 3144 /// added, on success. If everything went okay, Value will receive the 3145 /// value of the constant expression. 3146 static ExprResult 3147 CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) { 3148 SourceLocation Loc = Index->getBeginLoc(); 3149 3150 // Make sure this is an integer constant expression. 3151 ExprResult Result = 3152 S.VerifyIntegerConstantExpression(Index, &Value, Sema::AllowFold); 3153 if (Result.isInvalid()) 3154 return Result; 3155 3156 if (Value.isSigned() && Value.isNegative()) 3157 return S.Diag(Loc, diag::err_array_designator_negative) 3158 << Value.toString(10) << Index->getSourceRange(); 3159 3160 Value.setIsUnsigned(true); 3161 return Result; 3162 } 3163 3164 ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig, 3165 SourceLocation EqualOrColonLoc, 3166 bool GNUSyntax, 3167 ExprResult Init) { 3168 typedef DesignatedInitExpr::Designator ASTDesignator; 3169 3170 bool Invalid = false; 3171 SmallVector<ASTDesignator, 32> Designators; 3172 SmallVector<Expr *, 32> InitExpressions; 3173 3174 // Build designators and check array designator expressions. 3175 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) { 3176 const Designator &D = Desig.getDesignator(Idx); 3177 switch (D.getKind()) { 3178 case Designator::FieldDesignator: 3179 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(), 3180 D.getFieldLoc())); 3181 break; 3182 3183 case Designator::ArrayDesignator: { 3184 Expr *Index = static_cast<Expr *>(D.getArrayIndex()); 3185 llvm::APSInt IndexValue; 3186 if (!Index->isTypeDependent() && !Index->isValueDependent()) 3187 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get(); 3188 if (!Index) 3189 Invalid = true; 3190 else { 3191 Designators.push_back(ASTDesignator(InitExpressions.size(), 3192 D.getLBracketLoc(), 3193 D.getRBracketLoc())); 3194 InitExpressions.push_back(Index); 3195 } 3196 break; 3197 } 3198 3199 case Designator::ArrayRangeDesignator: { 3200 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart()); 3201 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd()); 3202 llvm::APSInt StartValue; 3203 llvm::APSInt EndValue; 3204 bool StartDependent = StartIndex->isTypeDependent() || 3205 StartIndex->isValueDependent(); 3206 bool EndDependent = EndIndex->isTypeDependent() || 3207 EndIndex->isValueDependent(); 3208 if (!StartDependent) 3209 StartIndex = 3210 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get(); 3211 if (!EndDependent) 3212 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get(); 3213 3214 if (!StartIndex || !EndIndex) 3215 Invalid = true; 3216 else { 3217 // Make sure we're comparing values with the same bit width. 3218 if (StartDependent || EndDependent) { 3219 // Nothing to compute. 3220 } else if (StartValue.getBitWidth() > EndValue.getBitWidth()) 3221 EndValue = EndValue.extend(StartValue.getBitWidth()); 3222 else if (StartValue.getBitWidth() < EndValue.getBitWidth()) 3223 StartValue = StartValue.extend(EndValue.getBitWidth()); 3224 3225 if (!StartDependent && !EndDependent && EndValue < StartValue) { 3226 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range) 3227 << StartValue.toString(10) << EndValue.toString(10) 3228 << StartIndex->getSourceRange() << EndIndex->getSourceRange(); 3229 Invalid = true; 3230 } else { 3231 Designators.push_back(ASTDesignator(InitExpressions.size(), 3232 D.getLBracketLoc(), 3233 D.getEllipsisLoc(), 3234 D.getRBracketLoc())); 3235 InitExpressions.push_back(StartIndex); 3236 InitExpressions.push_back(EndIndex); 3237 } 3238 } 3239 break; 3240 } 3241 } 3242 } 3243 3244 if (Invalid || Init.isInvalid()) 3245 return ExprError(); 3246 3247 // Clear out the expressions within the designation. 3248 Desig.ClearExprs(*this); 3249 3250 return DesignatedInitExpr::Create(Context, Designators, InitExpressions, 3251 EqualOrColonLoc, GNUSyntax, 3252 Init.getAs<Expr>()); 3253 } 3254 3255 //===----------------------------------------------------------------------===// 3256 // Initialization entity 3257 //===----------------------------------------------------------------------===// 3258 3259 InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index, 3260 const InitializedEntity &Parent) 3261 : Parent(&Parent), Index(Index) 3262 { 3263 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) { 3264 Kind = EK_ArrayElement; 3265 Type = AT->getElementType(); 3266 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) { 3267 Kind = EK_VectorElement; 3268 Type = VT->getElementType(); 3269 } else { 3270 const ComplexType *CT = Parent.getType()->getAs<ComplexType>(); 3271 assert(CT && "Unexpected type"); 3272 Kind = EK_ComplexElement; 3273 Type = CT->getElementType(); 3274 } 3275 } 3276 3277 InitializedEntity 3278 InitializedEntity::InitializeBase(ASTContext &Context, 3279 const CXXBaseSpecifier *Base, 3280 bool IsInheritedVirtualBase, 3281 const InitializedEntity *Parent) { 3282 InitializedEntity Result; 3283 Result.Kind = EK_Base; 3284 Result.Parent = Parent; 3285 Result.Base = {Base, IsInheritedVirtualBase}; 3286 Result.Type = Base->getType(); 3287 return Result; 3288 } 3289 3290 DeclarationName InitializedEntity::getName() const { 3291 switch (getKind()) { 3292 case EK_Parameter: 3293 case EK_Parameter_CF_Audited: { 3294 ParmVarDecl *D = Parameter.getPointer(); 3295 return (D ? D->getDeclName() : DeclarationName()); 3296 } 3297 3298 case EK_Variable: 3299 case EK_Member: 3300 case EK_Binding: 3301 case EK_TemplateParameter: 3302 return Variable.VariableOrMember->getDeclName(); 3303 3304 case EK_LambdaCapture: 3305 return DeclarationName(Capture.VarID); 3306 3307 case EK_Result: 3308 case EK_StmtExprResult: 3309 case EK_Exception: 3310 case EK_New: 3311 case EK_Temporary: 3312 case EK_Base: 3313 case EK_Delegating: 3314 case EK_ArrayElement: 3315 case EK_VectorElement: 3316 case EK_ComplexElement: 3317 case EK_BlockElement: 3318 case EK_LambdaToBlockConversionBlockElement: 3319 case EK_CompoundLiteralInit: 3320 case EK_RelatedResult: 3321 return DeclarationName(); 3322 } 3323 3324 llvm_unreachable("Invalid EntityKind!"); 3325 } 3326 3327 ValueDecl *InitializedEntity::getDecl() const { 3328 switch (getKind()) { 3329 case EK_Variable: 3330 case EK_Member: 3331 case EK_Binding: 3332 case EK_TemplateParameter: 3333 return Variable.VariableOrMember; 3334 3335 case EK_Parameter: 3336 case EK_Parameter_CF_Audited: 3337 return Parameter.getPointer(); 3338 3339 case EK_Result: 3340 case EK_StmtExprResult: 3341 case EK_Exception: 3342 case EK_New: 3343 case EK_Temporary: 3344 case EK_Base: 3345 case EK_Delegating: 3346 case EK_ArrayElement: 3347 case EK_VectorElement: 3348 case EK_ComplexElement: 3349 case EK_BlockElement: 3350 case EK_LambdaToBlockConversionBlockElement: 3351 case EK_LambdaCapture: 3352 case EK_CompoundLiteralInit: 3353 case EK_RelatedResult: 3354 return nullptr; 3355 } 3356 3357 llvm_unreachable("Invalid EntityKind!"); 3358 } 3359 3360 bool InitializedEntity::allowsNRVO() const { 3361 switch (getKind()) { 3362 case EK_Result: 3363 case EK_Exception: 3364 return LocAndNRVO.NRVO; 3365 3366 case EK_StmtExprResult: 3367 case EK_Variable: 3368 case EK_Parameter: 3369 case EK_Parameter_CF_Audited: 3370 case EK_TemplateParameter: 3371 case EK_Member: 3372 case EK_Binding: 3373 case EK_New: 3374 case EK_Temporary: 3375 case EK_CompoundLiteralInit: 3376 case EK_Base: 3377 case EK_Delegating: 3378 case EK_ArrayElement: 3379 case EK_VectorElement: 3380 case EK_ComplexElement: 3381 case EK_BlockElement: 3382 case EK_LambdaToBlockConversionBlockElement: 3383 case EK_LambdaCapture: 3384 case EK_RelatedResult: 3385 break; 3386 } 3387 3388 return false; 3389 } 3390 3391 unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const { 3392 assert(getParent() != this); 3393 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0; 3394 for (unsigned I = 0; I != Depth; ++I) 3395 OS << "`-"; 3396 3397 switch (getKind()) { 3398 case EK_Variable: OS << "Variable"; break; 3399 case EK_Parameter: OS << "Parameter"; break; 3400 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter"; 3401 break; 3402 case EK_TemplateParameter: OS << "TemplateParameter"; break; 3403 case EK_Result: OS << "Result"; break; 3404 case EK_StmtExprResult: OS << "StmtExprResult"; break; 3405 case EK_Exception: OS << "Exception"; break; 3406 case EK_Member: OS << "Member"; break; 3407 case EK_Binding: OS << "Binding"; break; 3408 case EK_New: OS << "New"; break; 3409 case EK_Temporary: OS << "Temporary"; break; 3410 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break; 3411 case EK_RelatedResult: OS << "RelatedResult"; break; 3412 case EK_Base: OS << "Base"; break; 3413 case EK_Delegating: OS << "Delegating"; break; 3414 case EK_ArrayElement: OS << "ArrayElement " << Index; break; 3415 case EK_VectorElement: OS << "VectorElement " << Index; break; 3416 case EK_ComplexElement: OS << "ComplexElement " << Index; break; 3417 case EK_BlockElement: OS << "Block"; break; 3418 case EK_LambdaToBlockConversionBlockElement: 3419 OS << "Block (lambda)"; 3420 break; 3421 case EK_LambdaCapture: 3422 OS << "LambdaCapture "; 3423 OS << DeclarationName(Capture.VarID); 3424 break; 3425 } 3426 3427 if (auto *D = getDecl()) { 3428 OS << " "; 3429 D->printQualifiedName(OS); 3430 } 3431 3432 OS << " '" << getType().getAsString() << "'\n"; 3433 3434 return Depth + 1; 3435 } 3436 3437 LLVM_DUMP_METHOD void InitializedEntity::dump() const { 3438 dumpImpl(llvm::errs()); 3439 } 3440 3441 //===----------------------------------------------------------------------===// 3442 // Initialization sequence 3443 //===----------------------------------------------------------------------===// 3444 3445 void InitializationSequence::Step::Destroy() { 3446 switch (Kind) { 3447 case SK_ResolveAddressOfOverloadedFunction: 3448 case SK_CastDerivedToBaseRValue: 3449 case SK_CastDerivedToBaseXValue: 3450 case SK_CastDerivedToBaseLValue: 3451 case SK_BindReference: 3452 case SK_BindReferenceToTemporary: 3453 case SK_FinalCopy: 3454 case SK_ExtraneousCopyToTemporary: 3455 case SK_UserConversion: 3456 case SK_QualificationConversionRValue: 3457 case SK_QualificationConversionXValue: 3458 case SK_QualificationConversionLValue: 3459 case SK_FunctionReferenceConversion: 3460 case SK_AtomicConversion: 3461 case SK_ListInitialization: 3462 case SK_UnwrapInitList: 3463 case SK_RewrapInitList: 3464 case SK_ConstructorInitialization: 3465 case SK_ConstructorInitializationFromList: 3466 case SK_ZeroInitialization: 3467 case SK_CAssignment: 3468 case SK_StringInit: 3469 case SK_ObjCObjectConversion: 3470 case SK_ArrayLoopIndex: 3471 case SK_ArrayLoopInit: 3472 case SK_ArrayInit: 3473 case SK_GNUArrayInit: 3474 case SK_ParenthesizedArrayInit: 3475 case SK_PassByIndirectCopyRestore: 3476 case SK_PassByIndirectRestore: 3477 case SK_ProduceObjCObject: 3478 case SK_StdInitializerList: 3479 case SK_StdInitializerListConstructorCall: 3480 case SK_OCLSamplerInit: 3481 case SK_OCLZeroOpaqueType: 3482 break; 3483 3484 case SK_ConversionSequence: 3485 case SK_ConversionSequenceNoNarrowing: 3486 delete ICS; 3487 } 3488 } 3489 3490 bool InitializationSequence::isDirectReferenceBinding() const { 3491 // There can be some lvalue adjustments after the SK_BindReference step. 3492 for (auto I = Steps.rbegin(); I != Steps.rend(); ++I) { 3493 if (I->Kind == SK_BindReference) 3494 return true; 3495 if (I->Kind == SK_BindReferenceToTemporary) 3496 return false; 3497 } 3498 return false; 3499 } 3500 3501 bool InitializationSequence::isAmbiguous() const { 3502 if (!Failed()) 3503 return false; 3504 3505 switch (getFailureKind()) { 3506 case FK_TooManyInitsForReference: 3507 case FK_ParenthesizedListInitForReference: 3508 case FK_ArrayNeedsInitList: 3509 case FK_ArrayNeedsInitListOrStringLiteral: 3510 case FK_ArrayNeedsInitListOrWideStringLiteral: 3511 case FK_NarrowStringIntoWideCharArray: 3512 case FK_WideStringIntoCharArray: 3513 case FK_IncompatWideStringIntoWideChar: 3514 case FK_PlainStringIntoUTF8Char: 3515 case FK_UTF8StringIntoPlainChar: 3516 case FK_AddressOfOverloadFailed: // FIXME: Could do better 3517 case FK_NonConstLValueReferenceBindingToTemporary: 3518 case FK_NonConstLValueReferenceBindingToBitfield: 3519 case FK_NonConstLValueReferenceBindingToVectorElement: 3520 case FK_NonConstLValueReferenceBindingToMatrixElement: 3521 case FK_NonConstLValueReferenceBindingToUnrelated: 3522 case FK_RValueReferenceBindingToLValue: 3523 case FK_ReferenceAddrspaceMismatchTemporary: 3524 case FK_ReferenceInitDropsQualifiers: 3525 case FK_ReferenceInitFailed: 3526 case FK_ConversionFailed: 3527 case FK_ConversionFromPropertyFailed: 3528 case FK_TooManyInitsForScalar: 3529 case FK_ParenthesizedListInitForScalar: 3530 case FK_ReferenceBindingToInitList: 3531 case FK_InitListBadDestinationType: 3532 case FK_DefaultInitOfConst: 3533 case FK_Incomplete: 3534 case FK_ArrayTypeMismatch: 3535 case FK_NonConstantArrayInit: 3536 case FK_ListInitializationFailed: 3537 case FK_VariableLengthArrayHasInitializer: 3538 case FK_PlaceholderType: 3539 case FK_ExplicitConstructor: 3540 case FK_AddressOfUnaddressableFunction: 3541 return false; 3542 3543 case FK_ReferenceInitOverloadFailed: 3544 case FK_UserConversionOverloadFailed: 3545 case FK_ConstructorOverloadFailed: 3546 case FK_ListConstructorOverloadFailed: 3547 return FailedOverloadResult == OR_Ambiguous; 3548 } 3549 3550 llvm_unreachable("Invalid EntityKind!"); 3551 } 3552 3553 bool InitializationSequence::isConstructorInitialization() const { 3554 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization; 3555 } 3556 3557 void 3558 InitializationSequence 3559 ::AddAddressOverloadResolutionStep(FunctionDecl *Function, 3560 DeclAccessPair Found, 3561 bool HadMultipleCandidates) { 3562 Step S; 3563 S.Kind = SK_ResolveAddressOfOverloadedFunction; 3564 S.Type = Function->getType(); 3565 S.Function.HadMultipleCandidates = HadMultipleCandidates; 3566 S.Function.Function = Function; 3567 S.Function.FoundDecl = Found; 3568 Steps.push_back(S); 3569 } 3570 3571 void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType, 3572 ExprValueKind VK) { 3573 Step S; 3574 switch (VK) { 3575 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break; 3576 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break; 3577 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break; 3578 } 3579 S.Type = BaseType; 3580 Steps.push_back(S); 3581 } 3582 3583 void InitializationSequence::AddReferenceBindingStep(QualType T, 3584 bool BindingTemporary) { 3585 Step S; 3586 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference; 3587 S.Type = T; 3588 Steps.push_back(S); 3589 } 3590 3591 void InitializationSequence::AddFinalCopy(QualType T) { 3592 Step S; 3593 S.Kind = SK_FinalCopy; 3594 S.Type = T; 3595 Steps.push_back(S); 3596 } 3597 3598 void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) { 3599 Step S; 3600 S.Kind = SK_ExtraneousCopyToTemporary; 3601 S.Type = T; 3602 Steps.push_back(S); 3603 } 3604 3605 void 3606 InitializationSequence::AddUserConversionStep(FunctionDecl *Function, 3607 DeclAccessPair FoundDecl, 3608 QualType T, 3609 bool HadMultipleCandidates) { 3610 Step S; 3611 S.Kind = SK_UserConversion; 3612 S.Type = T; 3613 S.Function.HadMultipleCandidates = HadMultipleCandidates; 3614 S.Function.Function = Function; 3615 S.Function.FoundDecl = FoundDecl; 3616 Steps.push_back(S); 3617 } 3618 3619 void InitializationSequence::AddQualificationConversionStep(QualType Ty, 3620 ExprValueKind VK) { 3621 Step S; 3622 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning 3623 switch (VK) { 3624 case VK_RValue: 3625 S.Kind = SK_QualificationConversionRValue; 3626 break; 3627 case VK_XValue: 3628 S.Kind = SK_QualificationConversionXValue; 3629 break; 3630 case VK_LValue: 3631 S.Kind = SK_QualificationConversionLValue; 3632 break; 3633 } 3634 S.Type = Ty; 3635 Steps.push_back(S); 3636 } 3637 3638 void InitializationSequence::AddFunctionReferenceConversionStep(QualType Ty) { 3639 Step S; 3640 S.Kind = SK_FunctionReferenceConversion; 3641 S.Type = Ty; 3642 Steps.push_back(S); 3643 } 3644 3645 void InitializationSequence::AddAtomicConversionStep(QualType Ty) { 3646 Step S; 3647 S.Kind = SK_AtomicConversion; 3648 S.Type = Ty; 3649 Steps.push_back(S); 3650 } 3651 3652 void InitializationSequence::AddConversionSequenceStep( 3653 const ImplicitConversionSequence &ICS, QualType T, 3654 bool TopLevelOfInitList) { 3655 Step S; 3656 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing 3657 : SK_ConversionSequence; 3658 S.Type = T; 3659 S.ICS = new ImplicitConversionSequence(ICS); 3660 Steps.push_back(S); 3661 } 3662 3663 void InitializationSequence::AddListInitializationStep(QualType T) { 3664 Step S; 3665 S.Kind = SK_ListInitialization; 3666 S.Type = T; 3667 Steps.push_back(S); 3668 } 3669 3670 void InitializationSequence::AddConstructorInitializationStep( 3671 DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T, 3672 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) { 3673 Step S; 3674 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall 3675 : SK_ConstructorInitializationFromList 3676 : SK_ConstructorInitialization; 3677 S.Type = T; 3678 S.Function.HadMultipleCandidates = HadMultipleCandidates; 3679 S.Function.Function = Constructor; 3680 S.Function.FoundDecl = FoundDecl; 3681 Steps.push_back(S); 3682 } 3683 3684 void InitializationSequence::AddZeroInitializationStep(QualType T) { 3685 Step S; 3686 S.Kind = SK_ZeroInitialization; 3687 S.Type = T; 3688 Steps.push_back(S); 3689 } 3690 3691 void InitializationSequence::AddCAssignmentStep(QualType T) { 3692 Step S; 3693 S.Kind = SK_CAssignment; 3694 S.Type = T; 3695 Steps.push_back(S); 3696 } 3697 3698 void InitializationSequence::AddStringInitStep(QualType T) { 3699 Step S; 3700 S.Kind = SK_StringInit; 3701 S.Type = T; 3702 Steps.push_back(S); 3703 } 3704 3705 void InitializationSequence::AddObjCObjectConversionStep(QualType T) { 3706 Step S; 3707 S.Kind = SK_ObjCObjectConversion; 3708 S.Type = T; 3709 Steps.push_back(S); 3710 } 3711 3712 void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) { 3713 Step S; 3714 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit; 3715 S.Type = T; 3716 Steps.push_back(S); 3717 } 3718 3719 void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) { 3720 Step S; 3721 S.Kind = SK_ArrayLoopIndex; 3722 S.Type = EltT; 3723 Steps.insert(Steps.begin(), S); 3724 3725 S.Kind = SK_ArrayLoopInit; 3726 S.Type = T; 3727 Steps.push_back(S); 3728 } 3729 3730 void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) { 3731 Step S; 3732 S.Kind = SK_ParenthesizedArrayInit; 3733 S.Type = T; 3734 Steps.push_back(S); 3735 } 3736 3737 void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type, 3738 bool shouldCopy) { 3739 Step s; 3740 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore 3741 : SK_PassByIndirectRestore); 3742 s.Type = type; 3743 Steps.push_back(s); 3744 } 3745 3746 void InitializationSequence::AddProduceObjCObjectStep(QualType T) { 3747 Step S; 3748 S.Kind = SK_ProduceObjCObject; 3749 S.Type = T; 3750 Steps.push_back(S); 3751 } 3752 3753 void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) { 3754 Step S; 3755 S.Kind = SK_StdInitializerList; 3756 S.Type = T; 3757 Steps.push_back(S); 3758 } 3759 3760 void InitializationSequence::AddOCLSamplerInitStep(QualType T) { 3761 Step S; 3762 S.Kind = SK_OCLSamplerInit; 3763 S.Type = T; 3764 Steps.push_back(S); 3765 } 3766 3767 void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T) { 3768 Step S; 3769 S.Kind = SK_OCLZeroOpaqueType; 3770 S.Type = T; 3771 Steps.push_back(S); 3772 } 3773 3774 void InitializationSequence::RewrapReferenceInitList(QualType T, 3775 InitListExpr *Syntactic) { 3776 assert(Syntactic->getNumInits() == 1 && 3777 "Can only rewrap trivial init lists."); 3778 Step S; 3779 S.Kind = SK_UnwrapInitList; 3780 S.Type = Syntactic->getInit(0)->getType(); 3781 Steps.insert(Steps.begin(), S); 3782 3783 S.Kind = SK_RewrapInitList; 3784 S.Type = T; 3785 S.WrappingSyntacticList = Syntactic; 3786 Steps.push_back(S); 3787 } 3788 3789 void InitializationSequence::SetOverloadFailure(FailureKind Failure, 3790 OverloadingResult Result) { 3791 setSequenceKind(FailedSequence); 3792 this->Failure = Failure; 3793 this->FailedOverloadResult = Result; 3794 } 3795 3796 //===----------------------------------------------------------------------===// 3797 // Attempt initialization 3798 //===----------------------------------------------------------------------===// 3799 3800 /// Tries to add a zero initializer. Returns true if that worked. 3801 static bool 3802 maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence, 3803 const InitializedEntity &Entity) { 3804 if (Entity.getKind() != InitializedEntity::EK_Variable) 3805 return false; 3806 3807 VarDecl *VD = cast<VarDecl>(Entity.getDecl()); 3808 if (VD->getInit() || VD->getEndLoc().isMacroID()) 3809 return false; 3810 3811 QualType VariableTy = VD->getType().getCanonicalType(); 3812 SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc()); 3813 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc); 3814 if (!Init.empty()) { 3815 Sequence.AddZeroInitializationStep(Entity.getType()); 3816 Sequence.SetZeroInitializationFixit(Init, Loc); 3817 return true; 3818 } 3819 return false; 3820 } 3821 3822 static void MaybeProduceObjCObject(Sema &S, 3823 InitializationSequence &Sequence, 3824 const InitializedEntity &Entity) { 3825 if (!S.getLangOpts().ObjCAutoRefCount) return; 3826 3827 /// When initializing a parameter, produce the value if it's marked 3828 /// __attribute__((ns_consumed)). 3829 if (Entity.isParameterKind()) { 3830 if (!Entity.isParameterConsumed()) 3831 return; 3832 3833 assert(Entity.getType()->isObjCRetainableType() && 3834 "consuming an object of unretainable type?"); 3835 Sequence.AddProduceObjCObjectStep(Entity.getType()); 3836 3837 /// When initializing a return value, if the return type is a 3838 /// retainable type, then returns need to immediately retain the 3839 /// object. If an autorelease is required, it will be done at the 3840 /// last instant. 3841 } else if (Entity.getKind() == InitializedEntity::EK_Result || 3842 Entity.getKind() == InitializedEntity::EK_StmtExprResult) { 3843 if (!Entity.getType()->isObjCRetainableType()) 3844 return; 3845 3846 Sequence.AddProduceObjCObjectStep(Entity.getType()); 3847 } 3848 } 3849 3850 static void TryListInitialization(Sema &S, 3851 const InitializedEntity &Entity, 3852 const InitializationKind &Kind, 3853 InitListExpr *InitList, 3854 InitializationSequence &Sequence, 3855 bool TreatUnavailableAsInvalid); 3856 3857 /// When initializing from init list via constructor, handle 3858 /// initialization of an object of type std::initializer_list<T>. 3859 /// 3860 /// \return true if we have handled initialization of an object of type 3861 /// std::initializer_list<T>, false otherwise. 3862 static bool TryInitializerListConstruction(Sema &S, 3863 InitListExpr *List, 3864 QualType DestType, 3865 InitializationSequence &Sequence, 3866 bool TreatUnavailableAsInvalid) { 3867 QualType E; 3868 if (!S.isStdInitializerList(DestType, &E)) 3869 return false; 3870 3871 if (!S.isCompleteType(List->getExprLoc(), E)) { 3872 Sequence.setIncompleteTypeFailure(E); 3873 return true; 3874 } 3875 3876 // Try initializing a temporary array from the init list. 3877 QualType ArrayType = S.Context.getConstantArrayType( 3878 E.withConst(), 3879 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()), 3880 List->getNumInits()), 3881 nullptr, clang::ArrayType::Normal, 0); 3882 InitializedEntity HiddenArray = 3883 InitializedEntity::InitializeTemporary(ArrayType); 3884 InitializationKind Kind = InitializationKind::CreateDirectList( 3885 List->getExprLoc(), List->getBeginLoc(), List->getEndLoc()); 3886 TryListInitialization(S, HiddenArray, Kind, List, Sequence, 3887 TreatUnavailableAsInvalid); 3888 if (Sequence) 3889 Sequence.AddStdInitializerListConstructionStep(DestType); 3890 return true; 3891 } 3892 3893 /// Determine if the constructor has the signature of a copy or move 3894 /// constructor for the type T of the class in which it was found. That is, 3895 /// determine if its first parameter is of type T or reference to (possibly 3896 /// cv-qualified) T. 3897 static bool hasCopyOrMoveCtorParam(ASTContext &Ctx, 3898 const ConstructorInfo &Info) { 3899 if (Info.Constructor->getNumParams() == 0) 3900 return false; 3901 3902 QualType ParmT = 3903 Info.Constructor->getParamDecl(0)->getType().getNonReferenceType(); 3904 QualType ClassT = 3905 Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext())); 3906 3907 return Ctx.hasSameUnqualifiedType(ParmT, ClassT); 3908 } 3909 3910 static OverloadingResult 3911 ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc, 3912 MultiExprArg Args, 3913 OverloadCandidateSet &CandidateSet, 3914 QualType DestType, 3915 DeclContext::lookup_result Ctors, 3916 OverloadCandidateSet::iterator &Best, 3917 bool CopyInitializing, bool AllowExplicit, 3918 bool OnlyListConstructors, bool IsListInit, 3919 bool SecondStepOfCopyInit = false) { 3920 CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor); 3921 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace()); 3922 3923 for (NamedDecl *D : Ctors) { 3924 auto Info = getConstructorInfo(D); 3925 if (!Info.Constructor || Info.Constructor->isInvalidDecl()) 3926 continue; 3927 3928 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor)) 3929 continue; 3930 3931 // C++11 [over.best.ics]p4: 3932 // ... and the constructor or user-defined conversion function is a 3933 // candidate by 3934 // - 13.3.1.3, when the argument is the temporary in the second step 3935 // of a class copy-initialization, or 3936 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here] 3937 // - the second phase of 13.3.1.7 when the initializer list has exactly 3938 // one element that is itself an initializer list, and the target is 3939 // the first parameter of a constructor of class X, and the conversion 3940 // is to X or reference to (possibly cv-qualified X), 3941 // user-defined conversion sequences are not considered. 3942 bool SuppressUserConversions = 3943 SecondStepOfCopyInit || 3944 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) && 3945 hasCopyOrMoveCtorParam(S.Context, Info)); 3946 3947 if (Info.ConstructorTmpl) 3948 S.AddTemplateOverloadCandidate( 3949 Info.ConstructorTmpl, Info.FoundDecl, 3950 /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions, 3951 /*PartialOverloading=*/false, AllowExplicit); 3952 else { 3953 // C++ [over.match.copy]p1: 3954 // - When initializing a temporary to be bound to the first parameter 3955 // of a constructor [for type T] that takes a reference to possibly 3956 // cv-qualified T as its first argument, called with a single 3957 // argument in the context of direct-initialization, explicit 3958 // conversion functions are also considered. 3959 // FIXME: What if a constructor template instantiates to such a signature? 3960 bool AllowExplicitConv = AllowExplicit && !CopyInitializing && 3961 Args.size() == 1 && 3962 hasCopyOrMoveCtorParam(S.Context, Info); 3963 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args, 3964 CandidateSet, SuppressUserConversions, 3965 /*PartialOverloading=*/false, AllowExplicit, 3966 AllowExplicitConv); 3967 } 3968 } 3969 3970 // FIXME: Work around a bug in C++17 guaranteed copy elision. 3971 // 3972 // When initializing an object of class type T by constructor 3973 // ([over.match.ctor]) or by list-initialization ([over.match.list]) 3974 // from a single expression of class type U, conversion functions of 3975 // U that convert to the non-reference type cv T are candidates. 3976 // Explicit conversion functions are only candidates during 3977 // direct-initialization. 3978 // 3979 // Note: SecondStepOfCopyInit is only ever true in this case when 3980 // evaluating whether to produce a C++98 compatibility warning. 3981 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 && 3982 !SecondStepOfCopyInit) { 3983 Expr *Initializer = Args[0]; 3984 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl(); 3985 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) { 3986 const auto &Conversions = SourceRD->getVisibleConversionFunctions(); 3987 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3988 NamedDecl *D = *I; 3989 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 3990 D = D->getUnderlyingDecl(); 3991 3992 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 3993 CXXConversionDecl *Conv; 3994 if (ConvTemplate) 3995 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3996 else 3997 Conv = cast<CXXConversionDecl>(D); 3998 3999 if (ConvTemplate) 4000 S.AddTemplateConversionCandidate( 4001 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType, 4002 CandidateSet, AllowExplicit, AllowExplicit, 4003 /*AllowResultConversion*/ false); 4004 else 4005 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer, 4006 DestType, CandidateSet, AllowExplicit, 4007 AllowExplicit, 4008 /*AllowResultConversion*/ false); 4009 } 4010 } 4011 } 4012 4013 // Perform overload resolution and return the result. 4014 return CandidateSet.BestViableFunction(S, DeclLoc, Best); 4015 } 4016 4017 /// Attempt initialization by constructor (C++ [dcl.init]), which 4018 /// enumerates the constructors of the initialized entity and performs overload 4019 /// resolution to select the best. 4020 /// \param DestType The destination class type. 4021 /// \param DestArrayType The destination type, which is either DestType or 4022 /// a (possibly multidimensional) array of DestType. 4023 /// \param IsListInit Is this list-initialization? 4024 /// \param IsInitListCopy Is this non-list-initialization resulting from a 4025 /// list-initialization from {x} where x is the same 4026 /// type as the entity? 4027 static void TryConstructorInitialization(Sema &S, 4028 const InitializedEntity &Entity, 4029 const InitializationKind &Kind, 4030 MultiExprArg Args, QualType DestType, 4031 QualType DestArrayType, 4032 InitializationSequence &Sequence, 4033 bool IsListInit = false, 4034 bool IsInitListCopy = false) { 4035 assert(((!IsListInit && !IsInitListCopy) || 4036 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && 4037 "IsListInit/IsInitListCopy must come with a single initializer list " 4038 "argument."); 4039 InitListExpr *ILE = 4040 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr; 4041 MultiExprArg UnwrappedArgs = 4042 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args; 4043 4044 // The type we're constructing needs to be complete. 4045 if (!S.isCompleteType(Kind.getLocation(), DestType)) { 4046 Sequence.setIncompleteTypeFailure(DestType); 4047 return; 4048 } 4049 4050 // C++17 [dcl.init]p17: 4051 // - If the initializer expression is a prvalue and the cv-unqualified 4052 // version of the source type is the same class as the class of the 4053 // destination, the initializer expression is used to initialize the 4054 // destination object. 4055 // Per DR (no number yet), this does not apply when initializing a base 4056 // class or delegating to another constructor from a mem-initializer. 4057 // ObjC++: Lambda captured by the block in the lambda to block conversion 4058 // should avoid copy elision. 4059 if (S.getLangOpts().CPlusPlus17 && 4060 Entity.getKind() != InitializedEntity::EK_Base && 4061 Entity.getKind() != InitializedEntity::EK_Delegating && 4062 Entity.getKind() != 4063 InitializedEntity::EK_LambdaToBlockConversionBlockElement && 4064 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isRValue() && 4065 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) { 4066 // Convert qualifications if necessary. 4067 Sequence.AddQualificationConversionStep(DestType, VK_RValue); 4068 if (ILE) 4069 Sequence.RewrapReferenceInitList(DestType, ILE); 4070 return; 4071 } 4072 4073 const RecordType *DestRecordType = DestType->getAs<RecordType>(); 4074 assert(DestRecordType && "Constructor initialization requires record type"); 4075 CXXRecordDecl *DestRecordDecl 4076 = cast<CXXRecordDecl>(DestRecordType->getDecl()); 4077 4078 // Build the candidate set directly in the initialization sequence 4079 // structure, so that it will persist if we fail. 4080 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 4081 4082 // Determine whether we are allowed to call explicit constructors or 4083 // explicit conversion operators. 4084 bool AllowExplicit = Kind.AllowExplicit() || IsListInit; 4085 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy; 4086 4087 // - Otherwise, if T is a class type, constructors are considered. The 4088 // applicable constructors are enumerated, and the best one is chosen 4089 // through overload resolution. 4090 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl); 4091 4092 OverloadingResult Result = OR_No_Viable_Function; 4093 OverloadCandidateSet::iterator Best; 4094 bool AsInitializerList = false; 4095 4096 // C++11 [over.match.list]p1, per DR1467: 4097 // When objects of non-aggregate type T are list-initialized, such that 4098 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed 4099 // according to the rules in this section, overload resolution selects 4100 // the constructor in two phases: 4101 // 4102 // - Initially, the candidate functions are the initializer-list 4103 // constructors of the class T and the argument list consists of the 4104 // initializer list as a single argument. 4105 if (IsListInit) { 4106 AsInitializerList = true; 4107 4108 // If the initializer list has no elements and T has a default constructor, 4109 // the first phase is omitted. 4110 if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(DestRecordDecl))) 4111 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, 4112 CandidateSet, DestType, Ctors, Best, 4113 CopyInitialization, AllowExplicit, 4114 /*OnlyListConstructors=*/true, 4115 IsListInit); 4116 } 4117 4118 // C++11 [over.match.list]p1: 4119 // - If no viable initializer-list constructor is found, overload resolution 4120 // is performed again, where the candidate functions are all the 4121 // constructors of the class T and the argument list consists of the 4122 // elements of the initializer list. 4123 if (Result == OR_No_Viable_Function) { 4124 AsInitializerList = false; 4125 Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs, 4126 CandidateSet, DestType, Ctors, Best, 4127 CopyInitialization, AllowExplicit, 4128 /*OnlyListConstructors=*/false, 4129 IsListInit); 4130 } 4131 if (Result) { 4132 Sequence.SetOverloadFailure( 4133 IsListInit ? InitializationSequence::FK_ListConstructorOverloadFailed 4134 : InitializationSequence::FK_ConstructorOverloadFailed, 4135 Result); 4136 4137 if (Result != OR_Deleted) 4138 return; 4139 } 4140 4141 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4142 4143 // In C++17, ResolveConstructorOverload can select a conversion function 4144 // instead of a constructor. 4145 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) { 4146 // Add the user-defined conversion step that calls the conversion function. 4147 QualType ConvType = CD->getConversionType(); 4148 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) && 4149 "should not have selected this conversion function"); 4150 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType, 4151 HadMultipleCandidates); 4152 if (!S.Context.hasSameType(ConvType, DestType)) 4153 Sequence.AddQualificationConversionStep(DestType, VK_RValue); 4154 if (IsListInit) 4155 Sequence.RewrapReferenceInitList(Entity.getType(), ILE); 4156 return; 4157 } 4158 4159 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function); 4160 if (Result != OR_Deleted) { 4161 // C++11 [dcl.init]p6: 4162 // If a program calls for the default initialization of an object 4163 // of a const-qualified type T, T shall be a class type with a 4164 // user-provided default constructor. 4165 // C++ core issue 253 proposal: 4166 // If the implicit default constructor initializes all subobjects, no 4167 // initializer should be required. 4168 // The 253 proposal is for example needed to process libstdc++ headers 4169 // in 5.x. 4170 if (Kind.getKind() == InitializationKind::IK_Default && 4171 Entity.getType().isConstQualified()) { 4172 if (!CtorDecl->getParent()->allowConstDefaultInit()) { 4173 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity)) 4174 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); 4175 return; 4176 } 4177 } 4178 4179 // C++11 [over.match.list]p1: 4180 // In copy-list-initialization, if an explicit constructor is chosen, the 4181 // initializer is ill-formed. 4182 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) { 4183 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor); 4184 return; 4185 } 4186 } 4187 4188 // [class.copy.elision]p3: 4189 // In some copy-initialization contexts, a two-stage overload resolution 4190 // is performed. 4191 // If the first overload resolution selects a deleted function, we also 4192 // need the initialization sequence to decide whether to perform the second 4193 // overload resolution. 4194 // For deleted functions in other contexts, there is no need to get the 4195 // initialization sequence. 4196 if (Result == OR_Deleted && Kind.getKind() != InitializationKind::IK_Copy) 4197 return; 4198 4199 // Add the constructor initialization step. Any cv-qualification conversion is 4200 // subsumed by the initialization. 4201 Sequence.AddConstructorInitializationStep( 4202 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates, 4203 IsListInit | IsInitListCopy, AsInitializerList); 4204 } 4205 4206 static bool 4207 ResolveOverloadedFunctionForReferenceBinding(Sema &S, 4208 Expr *Initializer, 4209 QualType &SourceType, 4210 QualType &UnqualifiedSourceType, 4211 QualType UnqualifiedTargetType, 4212 InitializationSequence &Sequence) { 4213 if (S.Context.getCanonicalType(UnqualifiedSourceType) == 4214 S.Context.OverloadTy) { 4215 DeclAccessPair Found; 4216 bool HadMultipleCandidates = false; 4217 if (FunctionDecl *Fn 4218 = S.ResolveAddressOfOverloadedFunction(Initializer, 4219 UnqualifiedTargetType, 4220 false, Found, 4221 &HadMultipleCandidates)) { 4222 Sequence.AddAddressOverloadResolutionStep(Fn, Found, 4223 HadMultipleCandidates); 4224 SourceType = Fn->getType(); 4225 UnqualifiedSourceType = SourceType.getUnqualifiedType(); 4226 } else if (!UnqualifiedTargetType->isRecordType()) { 4227 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 4228 return true; 4229 } 4230 } 4231 return false; 4232 } 4233 4234 static void TryReferenceInitializationCore(Sema &S, 4235 const InitializedEntity &Entity, 4236 const InitializationKind &Kind, 4237 Expr *Initializer, 4238 QualType cv1T1, QualType T1, 4239 Qualifiers T1Quals, 4240 QualType cv2T2, QualType T2, 4241 Qualifiers T2Quals, 4242 InitializationSequence &Sequence); 4243 4244 static void TryValueInitialization(Sema &S, 4245 const InitializedEntity &Entity, 4246 const InitializationKind &Kind, 4247 InitializationSequence &Sequence, 4248 InitListExpr *InitList = nullptr); 4249 4250 /// Attempt list initialization of a reference. 4251 static void TryReferenceListInitialization(Sema &S, 4252 const InitializedEntity &Entity, 4253 const InitializationKind &Kind, 4254 InitListExpr *InitList, 4255 InitializationSequence &Sequence, 4256 bool TreatUnavailableAsInvalid) { 4257 // First, catch C++03 where this isn't possible. 4258 if (!S.getLangOpts().CPlusPlus11) { 4259 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList); 4260 return; 4261 } 4262 // Can't reference initialize a compound literal. 4263 if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) { 4264 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList); 4265 return; 4266 } 4267 4268 QualType DestType = Entity.getType(); 4269 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType(); 4270 Qualifiers T1Quals; 4271 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals); 4272 4273 // Reference initialization via an initializer list works thus: 4274 // If the initializer list consists of a single element that is 4275 // reference-related to the referenced type, bind directly to that element 4276 // (possibly creating temporaries). 4277 // Otherwise, initialize a temporary with the initializer list and 4278 // bind to that. 4279 if (InitList->getNumInits() == 1) { 4280 Expr *Initializer = InitList->getInit(0); 4281 QualType cv2T2 = S.getCompletedType(Initializer); 4282 Qualifiers T2Quals; 4283 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals); 4284 4285 // If this fails, creating a temporary wouldn't work either. 4286 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2, 4287 T1, Sequence)) 4288 return; 4289 4290 SourceLocation DeclLoc = Initializer->getBeginLoc(); 4291 Sema::ReferenceCompareResult RefRelationship 4292 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2); 4293 if (RefRelationship >= Sema::Ref_Related) { 4294 // Try to bind the reference here. 4295 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1, 4296 T1Quals, cv2T2, T2, T2Quals, Sequence); 4297 if (Sequence) 4298 Sequence.RewrapReferenceInitList(cv1T1, InitList); 4299 return; 4300 } 4301 4302 // Update the initializer if we've resolved an overloaded function. 4303 if (Sequence.step_begin() != Sequence.step_end()) 4304 Sequence.RewrapReferenceInitList(cv1T1, InitList); 4305 } 4306 // Perform address space compatibility check. 4307 QualType cv1T1IgnoreAS = cv1T1; 4308 if (T1Quals.hasAddressSpace()) { 4309 Qualifiers T2Quals; 4310 (void)S.Context.getUnqualifiedArrayType(InitList->getType(), T2Quals); 4311 if (!T1Quals.isAddressSpaceSupersetOf(T2Quals)) { 4312 Sequence.SetFailed( 4313 InitializationSequence::FK_ReferenceInitDropsQualifiers); 4314 return; 4315 } 4316 // Ignore address space of reference type at this point and perform address 4317 // space conversion after the reference binding step. 4318 cv1T1IgnoreAS = 4319 S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace()); 4320 } 4321 // Not reference-related. Create a temporary and bind to that. 4322 InitializedEntity TempEntity = 4323 InitializedEntity::InitializeTemporary(cv1T1IgnoreAS); 4324 4325 TryListInitialization(S, TempEntity, Kind, InitList, Sequence, 4326 TreatUnavailableAsInvalid); 4327 if (Sequence) { 4328 if (DestType->isRValueReferenceType() || 4329 (T1Quals.hasConst() && !T1Quals.hasVolatile())) { 4330 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, 4331 /*BindingTemporary=*/true); 4332 if (T1Quals.hasAddressSpace()) 4333 Sequence.AddQualificationConversionStep( 4334 cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue); 4335 } else 4336 Sequence.SetFailed( 4337 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary); 4338 } 4339 } 4340 4341 /// Attempt list initialization (C++0x [dcl.init.list]) 4342 static void TryListInitialization(Sema &S, 4343 const InitializedEntity &Entity, 4344 const InitializationKind &Kind, 4345 InitListExpr *InitList, 4346 InitializationSequence &Sequence, 4347 bool TreatUnavailableAsInvalid) { 4348 QualType DestType = Entity.getType(); 4349 4350 // C++ doesn't allow scalar initialization with more than one argument. 4351 // But C99 complex numbers are scalars and it makes sense there. 4352 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() && 4353 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) { 4354 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar); 4355 return; 4356 } 4357 if (DestType->isReferenceType()) { 4358 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence, 4359 TreatUnavailableAsInvalid); 4360 return; 4361 } 4362 4363 if (DestType->isRecordType() && 4364 !S.isCompleteType(InitList->getBeginLoc(), DestType)) { 4365 Sequence.setIncompleteTypeFailure(DestType); 4366 return; 4367 } 4368 4369 // C++11 [dcl.init.list]p3, per DR1467: 4370 // - If T is a class type and the initializer list has a single element of 4371 // type cv U, where U is T or a class derived from T, the object is 4372 // initialized from that element (by copy-initialization for 4373 // copy-list-initialization, or by direct-initialization for 4374 // direct-list-initialization). 4375 // - Otherwise, if T is a character array and the initializer list has a 4376 // single element that is an appropriately-typed string literal 4377 // (8.5.2 [dcl.init.string]), initialization is performed as described 4378 // in that section. 4379 // - Otherwise, if T is an aggregate, [...] (continue below). 4380 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) { 4381 if (DestType->isRecordType()) { 4382 QualType InitType = InitList->getInit(0)->getType(); 4383 if (S.Context.hasSameUnqualifiedType(InitType, DestType) || 4384 S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) { 4385 Expr *InitListAsExpr = InitList; 4386 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType, 4387 DestType, Sequence, 4388 /*InitListSyntax*/false, 4389 /*IsInitListCopy*/true); 4390 return; 4391 } 4392 } 4393 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) { 4394 Expr *SubInit[1] = {InitList->getInit(0)}; 4395 if (!isa<VariableArrayType>(DestAT) && 4396 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) { 4397 InitializationKind SubKind = 4398 Kind.getKind() == InitializationKind::IK_DirectList 4399 ? InitializationKind::CreateDirect(Kind.getLocation(), 4400 InitList->getLBraceLoc(), 4401 InitList->getRBraceLoc()) 4402 : Kind; 4403 Sequence.InitializeFrom(S, Entity, SubKind, SubInit, 4404 /*TopLevelOfInitList*/ true, 4405 TreatUnavailableAsInvalid); 4406 4407 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if 4408 // the element is not an appropriately-typed string literal, in which 4409 // case we should proceed as in C++11 (below). 4410 if (Sequence) { 4411 Sequence.RewrapReferenceInitList(Entity.getType(), InitList); 4412 return; 4413 } 4414 } 4415 } 4416 } 4417 4418 // C++11 [dcl.init.list]p3: 4419 // - If T is an aggregate, aggregate initialization is performed. 4420 if ((DestType->isRecordType() && !DestType->isAggregateType()) || 4421 (S.getLangOpts().CPlusPlus11 && 4422 S.isStdInitializerList(DestType, nullptr))) { 4423 if (S.getLangOpts().CPlusPlus11) { 4424 // - Otherwise, if the initializer list has no elements and T is a 4425 // class type with a default constructor, the object is 4426 // value-initialized. 4427 if (InitList->getNumInits() == 0) { 4428 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl(); 4429 if (S.LookupDefaultConstructor(RD)) { 4430 TryValueInitialization(S, Entity, Kind, Sequence, InitList); 4431 return; 4432 } 4433 } 4434 4435 // - Otherwise, if T is a specialization of std::initializer_list<E>, 4436 // an initializer_list object constructed [...] 4437 if (TryInitializerListConstruction(S, InitList, DestType, Sequence, 4438 TreatUnavailableAsInvalid)) 4439 return; 4440 4441 // - Otherwise, if T is a class type, constructors are considered. 4442 Expr *InitListAsExpr = InitList; 4443 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType, 4444 DestType, Sequence, /*InitListSyntax*/true); 4445 } else 4446 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType); 4447 return; 4448 } 4449 4450 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() && 4451 InitList->getNumInits() == 1) { 4452 Expr *E = InitList->getInit(0); 4453 4454 // - Otherwise, if T is an enumeration with a fixed underlying type, 4455 // the initializer-list has a single element v, and the initialization 4456 // is direct-list-initialization, the object is initialized with the 4457 // value T(v); if a narrowing conversion is required to convert v to 4458 // the underlying type of T, the program is ill-formed. 4459 auto *ET = DestType->getAs<EnumType>(); 4460 if (S.getLangOpts().CPlusPlus17 && 4461 Kind.getKind() == InitializationKind::IK_DirectList && 4462 ET && ET->getDecl()->isFixed() && 4463 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) && 4464 (E->getType()->isIntegralOrEnumerationType() || 4465 E->getType()->isFloatingType())) { 4466 // There are two ways that T(v) can work when T is an enumeration type. 4467 // If there is either an implicit conversion sequence from v to T or 4468 // a conversion function that can convert from v to T, then we use that. 4469 // Otherwise, if v is of integral, enumeration, or floating-point type, 4470 // it is converted to the enumeration type via its underlying type. 4471 // There is no overlap possible between these two cases (except when the 4472 // source value is already of the destination type), and the first 4473 // case is handled by the general case for single-element lists below. 4474 ImplicitConversionSequence ICS; 4475 ICS.setStandard(); 4476 ICS.Standard.setAsIdentityConversion(); 4477 if (!E->isRValue()) 4478 ICS.Standard.First = ICK_Lvalue_To_Rvalue; 4479 // If E is of a floating-point type, then the conversion is ill-formed 4480 // due to narrowing, but go through the motions in order to produce the 4481 // right diagnostic. 4482 ICS.Standard.Second = E->getType()->isFloatingType() 4483 ? ICK_Floating_Integral 4484 : ICK_Integral_Conversion; 4485 ICS.Standard.setFromType(E->getType()); 4486 ICS.Standard.setToType(0, E->getType()); 4487 ICS.Standard.setToType(1, DestType); 4488 ICS.Standard.setToType(2, DestType); 4489 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2), 4490 /*TopLevelOfInitList*/true); 4491 Sequence.RewrapReferenceInitList(Entity.getType(), InitList); 4492 return; 4493 } 4494 4495 // - Otherwise, if the initializer list has a single element of type E 4496 // [...references are handled above...], the object or reference is 4497 // initialized from that element (by copy-initialization for 4498 // copy-list-initialization, or by direct-initialization for 4499 // direct-list-initialization); if a narrowing conversion is required 4500 // to convert the element to T, the program is ill-formed. 4501 // 4502 // Per core-24034, this is direct-initialization if we were performing 4503 // direct-list-initialization and copy-initialization otherwise. 4504 // We can't use InitListChecker for this, because it always performs 4505 // copy-initialization. This only matters if we might use an 'explicit' 4506 // conversion operator, or for the special case conversion of nullptr_t to 4507 // bool, so we only need to handle those cases. 4508 // 4509 // FIXME: Why not do this in all cases? 4510 Expr *Init = InitList->getInit(0); 4511 if (Init->getType()->isRecordType() || 4512 (Init->getType()->isNullPtrType() && DestType->isBooleanType())) { 4513 InitializationKind SubKind = 4514 Kind.getKind() == InitializationKind::IK_DirectList 4515 ? InitializationKind::CreateDirect(Kind.getLocation(), 4516 InitList->getLBraceLoc(), 4517 InitList->getRBraceLoc()) 4518 : Kind; 4519 Expr *SubInit[1] = { Init }; 4520 Sequence.InitializeFrom(S, Entity, SubKind, SubInit, 4521 /*TopLevelOfInitList*/true, 4522 TreatUnavailableAsInvalid); 4523 if (Sequence) 4524 Sequence.RewrapReferenceInitList(Entity.getType(), InitList); 4525 return; 4526 } 4527 } 4528 4529 InitListChecker CheckInitList(S, Entity, InitList, 4530 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid); 4531 if (CheckInitList.HadError()) { 4532 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed); 4533 return; 4534 } 4535 4536 // Add the list initialization step with the built init list. 4537 Sequence.AddListInitializationStep(DestType); 4538 } 4539 4540 /// Try a reference initialization that involves calling a conversion 4541 /// function. 4542 static OverloadingResult TryRefInitWithConversionFunction( 4543 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, 4544 Expr *Initializer, bool AllowRValues, bool IsLValueRef, 4545 InitializationSequence &Sequence) { 4546 QualType DestType = Entity.getType(); 4547 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType(); 4548 QualType T1 = cv1T1.getUnqualifiedType(); 4549 QualType cv2T2 = Initializer->getType(); 4550 QualType T2 = cv2T2.getUnqualifiedType(); 4551 4552 assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) && 4553 "Must have incompatible references when binding via conversion"); 4554 4555 // Build the candidate set directly in the initialization sequence 4556 // structure, so that it will persist if we fail. 4557 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 4558 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4559 4560 // Determine whether we are allowed to call explicit conversion operators. 4561 // Note that none of [over.match.copy], [over.match.conv], nor 4562 // [over.match.ref] permit an explicit constructor to be chosen when 4563 // initializing a reference, not even for direct-initialization. 4564 bool AllowExplicitCtors = false; 4565 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding(); 4566 4567 const RecordType *T1RecordType = nullptr; 4568 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) && 4569 S.isCompleteType(Kind.getLocation(), T1)) { 4570 // The type we're converting to is a class type. Enumerate its constructors 4571 // to see if there is a suitable conversion. 4572 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl()); 4573 4574 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) { 4575 auto Info = getConstructorInfo(D); 4576 if (!Info.Constructor) 4577 continue; 4578 4579 if (!Info.Constructor->isInvalidDecl() && 4580 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) { 4581 if (Info.ConstructorTmpl) 4582 S.AddTemplateOverloadCandidate( 4583 Info.ConstructorTmpl, Info.FoundDecl, 4584 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet, 4585 /*SuppressUserConversions=*/true, 4586 /*PartialOverloading*/ false, AllowExplicitCtors); 4587 else 4588 S.AddOverloadCandidate( 4589 Info.Constructor, Info.FoundDecl, Initializer, CandidateSet, 4590 /*SuppressUserConversions=*/true, 4591 /*PartialOverloading*/ false, AllowExplicitCtors); 4592 } 4593 } 4594 } 4595 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl()) 4596 return OR_No_Viable_Function; 4597 4598 const RecordType *T2RecordType = nullptr; 4599 if ((T2RecordType = T2->getAs<RecordType>()) && 4600 S.isCompleteType(Kind.getLocation(), T2)) { 4601 // The type we're converting from is a class type, enumerate its conversion 4602 // functions. 4603 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl()); 4604 4605 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4606 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4607 NamedDecl *D = *I; 4608 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4609 if (isa<UsingShadowDecl>(D)) 4610 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4611 4612 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 4613 CXXConversionDecl *Conv; 4614 if (ConvTemplate) 4615 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4616 else 4617 Conv = cast<CXXConversionDecl>(D); 4618 4619 // If the conversion function doesn't return a reference type, 4620 // it can't be considered for this conversion unless we're allowed to 4621 // consider rvalues. 4622 // FIXME: Do we need to make sure that we only consider conversion 4623 // candidates with reference-compatible results? That might be needed to 4624 // break recursion. 4625 if ((AllowRValues || 4626 Conv->getConversionType()->isLValueReferenceType())) { 4627 if (ConvTemplate) 4628 S.AddTemplateConversionCandidate( 4629 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType, 4630 CandidateSet, 4631 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs); 4632 else 4633 S.AddConversionCandidate( 4634 Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet, 4635 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs); 4636 } 4637 } 4638 } 4639 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl()) 4640 return OR_No_Viable_Function; 4641 4642 SourceLocation DeclLoc = Initializer->getBeginLoc(); 4643 4644 // Perform overload resolution. If it fails, return the failed result. 4645 OverloadCandidateSet::iterator Best; 4646 if (OverloadingResult Result 4647 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) 4648 return Result; 4649 4650 FunctionDecl *Function = Best->Function; 4651 // This is the overload that will be used for this initialization step if we 4652 // use this initialization. Mark it as referenced. 4653 Function->setReferenced(); 4654 4655 // Compute the returned type and value kind of the conversion. 4656 QualType cv3T3; 4657 if (isa<CXXConversionDecl>(Function)) 4658 cv3T3 = Function->getReturnType(); 4659 else 4660 cv3T3 = T1; 4661 4662 ExprValueKind VK = VK_RValue; 4663 if (cv3T3->isLValueReferenceType()) 4664 VK = VK_LValue; 4665 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>()) 4666 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue; 4667 cv3T3 = cv3T3.getNonLValueExprType(S.Context); 4668 4669 // Add the user-defined conversion step. 4670 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4671 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3, 4672 HadMultipleCandidates); 4673 4674 // Determine whether we'll need to perform derived-to-base adjustments or 4675 // other conversions. 4676 Sema::ReferenceConversions RefConv; 4677 Sema::ReferenceCompareResult NewRefRelationship = 4678 S.CompareReferenceRelationship(DeclLoc, T1, cv3T3, &RefConv); 4679 4680 // Add the final conversion sequence, if necessary. 4681 if (NewRefRelationship == Sema::Ref_Incompatible) { 4682 assert(!isa<CXXConstructorDecl>(Function) && 4683 "should not have conversion after constructor"); 4684 4685 ImplicitConversionSequence ICS; 4686 ICS.setStandard(); 4687 ICS.Standard = Best->FinalConversion; 4688 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2)); 4689 4690 // Every implicit conversion results in a prvalue, except for a glvalue 4691 // derived-to-base conversion, which we handle below. 4692 cv3T3 = ICS.Standard.getToType(2); 4693 VK = VK_RValue; 4694 } 4695 4696 // If the converted initializer is a prvalue, its type T4 is adjusted to 4697 // type "cv1 T4" and the temporary materialization conversion is applied. 4698 // 4699 // We adjust the cv-qualifications to match the reference regardless of 4700 // whether we have a prvalue so that the AST records the change. In this 4701 // case, T4 is "cv3 T3". 4702 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers()); 4703 if (cv1T4.getQualifiers() != cv3T3.getQualifiers()) 4704 Sequence.AddQualificationConversionStep(cv1T4, VK); 4705 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_RValue); 4706 VK = IsLValueRef ? VK_LValue : VK_XValue; 4707 4708 if (RefConv & Sema::ReferenceConversions::DerivedToBase) 4709 Sequence.AddDerivedToBaseCastStep(cv1T1, VK); 4710 else if (RefConv & Sema::ReferenceConversions::ObjC) 4711 Sequence.AddObjCObjectConversionStep(cv1T1); 4712 else if (RefConv & Sema::ReferenceConversions::Function) 4713 Sequence.AddFunctionReferenceConversionStep(cv1T1); 4714 else if (RefConv & Sema::ReferenceConversions::Qualification) { 4715 if (!S.Context.hasSameType(cv1T4, cv1T1)) 4716 Sequence.AddQualificationConversionStep(cv1T1, VK); 4717 } 4718 4719 return OR_Success; 4720 } 4721 4722 static void CheckCXX98CompatAccessibleCopy(Sema &S, 4723 const InitializedEntity &Entity, 4724 Expr *CurInitExpr); 4725 4726 /// Attempt reference initialization (C++0x [dcl.init.ref]) 4727 static void TryReferenceInitialization(Sema &S, 4728 const InitializedEntity &Entity, 4729 const InitializationKind &Kind, 4730 Expr *Initializer, 4731 InitializationSequence &Sequence) { 4732 QualType DestType = Entity.getType(); 4733 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType(); 4734 Qualifiers T1Quals; 4735 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals); 4736 QualType cv2T2 = S.getCompletedType(Initializer); 4737 Qualifiers T2Quals; 4738 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals); 4739 4740 // If the initializer is the address of an overloaded function, try 4741 // to resolve the overloaded function. If all goes well, T2 is the 4742 // type of the resulting function. 4743 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2, 4744 T1, Sequence)) 4745 return; 4746 4747 // Delegate everything else to a subfunction. 4748 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1, 4749 T1Quals, cv2T2, T2, T2Quals, Sequence); 4750 } 4751 4752 /// Determine whether an expression is a non-referenceable glvalue (one to 4753 /// which a reference can never bind). Attempting to bind a reference to 4754 /// such a glvalue will always create a temporary. 4755 static bool isNonReferenceableGLValue(Expr *E) { 4756 return E->refersToBitField() || E->refersToVectorElement() || 4757 E->refersToMatrixElement(); 4758 } 4759 4760 /// Reference initialization without resolving overloaded functions. 4761 /// 4762 /// We also can get here in C if we call a builtin which is declared as 4763 /// a function with a parameter of reference type (such as __builtin_va_end()). 4764 static void TryReferenceInitializationCore(Sema &S, 4765 const InitializedEntity &Entity, 4766 const InitializationKind &Kind, 4767 Expr *Initializer, 4768 QualType cv1T1, QualType T1, 4769 Qualifiers T1Quals, 4770 QualType cv2T2, QualType T2, 4771 Qualifiers T2Quals, 4772 InitializationSequence &Sequence) { 4773 QualType DestType = Entity.getType(); 4774 SourceLocation DeclLoc = Initializer->getBeginLoc(); 4775 4776 // Compute some basic properties of the types and the initializer. 4777 bool isLValueRef = DestType->isLValueReferenceType(); 4778 bool isRValueRef = !isLValueRef; 4779 Expr::Classification InitCategory = Initializer->Classify(S.Context); 4780 4781 Sema::ReferenceConversions RefConv; 4782 Sema::ReferenceCompareResult RefRelationship = 4783 S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, &RefConv); 4784 4785 // C++0x [dcl.init.ref]p5: 4786 // A reference to type "cv1 T1" is initialized by an expression of type 4787 // "cv2 T2" as follows: 4788 // 4789 // - If the reference is an lvalue reference and the initializer 4790 // expression 4791 // Note the analogous bullet points for rvalue refs to functions. Because 4792 // there are no function rvalues in C++, rvalue refs to functions are treated 4793 // like lvalue refs. 4794 OverloadingResult ConvOvlResult = OR_Success; 4795 bool T1Function = T1->isFunctionType(); 4796 if (isLValueRef || T1Function) { 4797 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) && 4798 (RefRelationship == Sema::Ref_Compatible || 4799 (Kind.isCStyleOrFunctionalCast() && 4800 RefRelationship == Sema::Ref_Related))) { 4801 // - is an lvalue (but is not a bit-field), and "cv1 T1" is 4802 // reference-compatible with "cv2 T2," or 4803 if (RefConv & (Sema::ReferenceConversions::DerivedToBase | 4804 Sema::ReferenceConversions::ObjC)) { 4805 // If we're converting the pointee, add any qualifiers first; 4806 // these qualifiers must all be top-level, so just convert to "cv1 T2". 4807 if (RefConv & (Sema::ReferenceConversions::Qualification)) 4808 Sequence.AddQualificationConversionStep( 4809 S.Context.getQualifiedType(T2, T1Quals), 4810 Initializer->getValueKind()); 4811 if (RefConv & Sema::ReferenceConversions::DerivedToBase) 4812 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue); 4813 else 4814 Sequence.AddObjCObjectConversionStep(cv1T1); 4815 } else if (RefConv & Sema::ReferenceConversions::Qualification) { 4816 // Perform a (possibly multi-level) qualification conversion. 4817 Sequence.AddQualificationConversionStep(cv1T1, 4818 Initializer->getValueKind()); 4819 } else if (RefConv & Sema::ReferenceConversions::Function) { 4820 Sequence.AddFunctionReferenceConversionStep(cv1T1); 4821 } 4822 4823 // We only create a temporary here when binding a reference to a 4824 // bit-field or vector element. Those cases are't supposed to be 4825 // handled by this bullet, but the outcome is the same either way. 4826 Sequence.AddReferenceBindingStep(cv1T1, false); 4827 return; 4828 } 4829 4830 // - has a class type (i.e., T2 is a class type), where T1 is not 4831 // reference-related to T2, and can be implicitly converted to an 4832 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible 4833 // with "cv3 T3" (this conversion is selected by enumerating the 4834 // applicable conversion functions (13.3.1.6) and choosing the best 4835 // one through overload resolution (13.3)), 4836 // If we have an rvalue ref to function type here, the rhs must be 4837 // an rvalue. DR1287 removed the "implicitly" here. 4838 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() && 4839 (isLValueRef || InitCategory.isRValue())) { 4840 if (S.getLangOpts().CPlusPlus) { 4841 // Try conversion functions only for C++. 4842 ConvOvlResult = TryRefInitWithConversionFunction( 4843 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef, 4844 /*IsLValueRef*/ isLValueRef, Sequence); 4845 if (ConvOvlResult == OR_Success) 4846 return; 4847 if (ConvOvlResult != OR_No_Viable_Function) 4848 Sequence.SetOverloadFailure( 4849 InitializationSequence::FK_ReferenceInitOverloadFailed, 4850 ConvOvlResult); 4851 } else { 4852 ConvOvlResult = OR_No_Viable_Function; 4853 } 4854 } 4855 } 4856 4857 // - Otherwise, the reference shall be an lvalue reference to a 4858 // non-volatile const type (i.e., cv1 shall be const), or the reference 4859 // shall be an rvalue reference. 4860 // For address spaces, we interpret this to mean that an addr space 4861 // of a reference "cv1 T1" is a superset of addr space of "cv2 T2". 4862 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile() && 4863 T1Quals.isAddressSpaceSupersetOf(T2Quals))) { 4864 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) 4865 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 4866 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) 4867 Sequence.SetOverloadFailure( 4868 InitializationSequence::FK_ReferenceInitOverloadFailed, 4869 ConvOvlResult); 4870 else if (!InitCategory.isLValue()) 4871 Sequence.SetFailed( 4872 T1Quals.isAddressSpaceSupersetOf(T2Quals) 4873 ? InitializationSequence:: 4874 FK_NonConstLValueReferenceBindingToTemporary 4875 : InitializationSequence::FK_ReferenceInitDropsQualifiers); 4876 else { 4877 InitializationSequence::FailureKind FK; 4878 switch (RefRelationship) { 4879 case Sema::Ref_Compatible: 4880 if (Initializer->refersToBitField()) 4881 FK = InitializationSequence:: 4882 FK_NonConstLValueReferenceBindingToBitfield; 4883 else if (Initializer->refersToVectorElement()) 4884 FK = InitializationSequence:: 4885 FK_NonConstLValueReferenceBindingToVectorElement; 4886 else if (Initializer->refersToMatrixElement()) 4887 FK = InitializationSequence:: 4888 FK_NonConstLValueReferenceBindingToMatrixElement; 4889 else 4890 llvm_unreachable("unexpected kind of compatible initializer"); 4891 break; 4892 case Sema::Ref_Related: 4893 FK = InitializationSequence::FK_ReferenceInitDropsQualifiers; 4894 break; 4895 case Sema::Ref_Incompatible: 4896 FK = InitializationSequence:: 4897 FK_NonConstLValueReferenceBindingToUnrelated; 4898 break; 4899 } 4900 Sequence.SetFailed(FK); 4901 } 4902 return; 4903 } 4904 4905 // - If the initializer expression 4906 // - is an 4907 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or 4908 // [1z] rvalue (but not a bit-field) or 4909 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2" 4910 // 4911 // Note: functions are handled above and below rather than here... 4912 if (!T1Function && 4913 (RefRelationship == Sema::Ref_Compatible || 4914 (Kind.isCStyleOrFunctionalCast() && 4915 RefRelationship == Sema::Ref_Related)) && 4916 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) || 4917 (InitCategory.isPRValue() && 4918 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() || 4919 T2->isArrayType())))) { 4920 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_RValue; 4921 if (InitCategory.isPRValue() && T2->isRecordType()) { 4922 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the 4923 // compiler the freedom to perform a copy here or bind to the 4924 // object, while C++0x requires that we bind directly to the 4925 // object. Hence, we always bind to the object without making an 4926 // extra copy. However, in C++03 requires that we check for the 4927 // presence of a suitable copy constructor: 4928 // 4929 // The constructor that would be used to make the copy shall 4930 // be callable whether or not the copy is actually done. 4931 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt) 4932 Sequence.AddExtraneousCopyToTemporary(cv2T2); 4933 else if (S.getLangOpts().CPlusPlus11) 4934 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer); 4935 } 4936 4937 // C++1z [dcl.init.ref]/5.2.1.2: 4938 // If the converted initializer is a prvalue, its type T4 is adjusted 4939 // to type "cv1 T4" and the temporary materialization conversion is 4940 // applied. 4941 // Postpone address space conversions to after the temporary materialization 4942 // conversion to allow creating temporaries in the alloca address space. 4943 auto T1QualsIgnoreAS = T1Quals; 4944 auto T2QualsIgnoreAS = T2Quals; 4945 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) { 4946 T1QualsIgnoreAS.removeAddressSpace(); 4947 T2QualsIgnoreAS.removeAddressSpace(); 4948 } 4949 QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1QualsIgnoreAS); 4950 if (T1QualsIgnoreAS != T2QualsIgnoreAS) 4951 Sequence.AddQualificationConversionStep(cv1T4, ValueKind); 4952 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_RValue); 4953 ValueKind = isLValueRef ? VK_LValue : VK_XValue; 4954 // Add addr space conversion if required. 4955 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) { 4956 auto T4Quals = cv1T4.getQualifiers(); 4957 T4Quals.addAddressSpace(T1Quals.getAddressSpace()); 4958 QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals); 4959 Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind); 4960 cv1T4 = cv1T4WithAS; 4961 } 4962 4963 // In any case, the reference is bound to the resulting glvalue (or to 4964 // an appropriate base class subobject). 4965 if (RefConv & Sema::ReferenceConversions::DerivedToBase) 4966 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind); 4967 else if (RefConv & Sema::ReferenceConversions::ObjC) 4968 Sequence.AddObjCObjectConversionStep(cv1T1); 4969 else if (RefConv & Sema::ReferenceConversions::Qualification) { 4970 if (!S.Context.hasSameType(cv1T4, cv1T1)) 4971 Sequence.AddQualificationConversionStep(cv1T1, ValueKind); 4972 } 4973 return; 4974 } 4975 4976 // - has a class type (i.e., T2 is a class type), where T1 is not 4977 // reference-related to T2, and can be implicitly converted to an 4978 // xvalue, class prvalue, or function lvalue of type "cv3 T3", 4979 // where "cv1 T1" is reference-compatible with "cv3 T3", 4980 // 4981 // DR1287 removes the "implicitly" here. 4982 if (T2->isRecordType()) { 4983 if (RefRelationship == Sema::Ref_Incompatible) { 4984 ConvOvlResult = TryRefInitWithConversionFunction( 4985 S, Entity, Kind, Initializer, /*AllowRValues*/ true, 4986 /*IsLValueRef*/ isLValueRef, Sequence); 4987 if (ConvOvlResult) 4988 Sequence.SetOverloadFailure( 4989 InitializationSequence::FK_ReferenceInitOverloadFailed, 4990 ConvOvlResult); 4991 4992 return; 4993 } 4994 4995 if (RefRelationship == Sema::Ref_Compatible && 4996 isRValueRef && InitCategory.isLValue()) { 4997 Sequence.SetFailed( 4998 InitializationSequence::FK_RValueReferenceBindingToLValue); 4999 return; 5000 } 5001 5002 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); 5003 return; 5004 } 5005 5006 // - Otherwise, a temporary of type "cv1 T1" is created and initialized 5007 // from the initializer expression using the rules for a non-reference 5008 // copy-initialization (8.5). The reference is then bound to the 5009 // temporary. [...] 5010 5011 // Ignore address space of reference type at this point and perform address 5012 // space conversion after the reference binding step. 5013 QualType cv1T1IgnoreAS = 5014 T1Quals.hasAddressSpace() 5015 ? S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace()) 5016 : cv1T1; 5017 5018 InitializedEntity TempEntity = 5019 InitializedEntity::InitializeTemporary(cv1T1IgnoreAS); 5020 5021 // FIXME: Why do we use an implicit conversion here rather than trying 5022 // copy-initialization? 5023 ImplicitConversionSequence ICS 5024 = S.TryImplicitConversion(Initializer, TempEntity.getType(), 5025 /*SuppressUserConversions=*/false, 5026 Sema::AllowedExplicit::None, 5027 /*FIXME:InOverloadResolution=*/false, 5028 /*CStyle=*/Kind.isCStyleOrFunctionalCast(), 5029 /*AllowObjCWritebackConversion=*/false); 5030 5031 if (ICS.isBad()) { 5032 // FIXME: Use the conversion function set stored in ICS to turn 5033 // this into an overloading ambiguity diagnostic. However, we need 5034 // to keep that set as an OverloadCandidateSet rather than as some 5035 // other kind of set. 5036 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) 5037 Sequence.SetOverloadFailure( 5038 InitializationSequence::FK_ReferenceInitOverloadFailed, 5039 ConvOvlResult); 5040 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) 5041 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 5042 else 5043 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed); 5044 return; 5045 } else { 5046 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType()); 5047 } 5048 5049 // [...] If T1 is reference-related to T2, cv1 must be the 5050 // same cv-qualification as, or greater cv-qualification 5051 // than, cv2; otherwise, the program is ill-formed. 5052 unsigned T1CVRQuals = T1Quals.getCVRQualifiers(); 5053 unsigned T2CVRQuals = T2Quals.getCVRQualifiers(); 5054 if ((RefRelationship == Sema::Ref_Related && 5055 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) || 5056 !T1Quals.isAddressSpaceSupersetOf(T2Quals)) { 5057 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); 5058 return; 5059 } 5060 5061 // [...] If T1 is reference-related to T2 and the reference is an rvalue 5062 // reference, the initializer expression shall not be an lvalue. 5063 if (RefRelationship >= Sema::Ref_Related && !isLValueRef && 5064 InitCategory.isLValue()) { 5065 Sequence.SetFailed( 5066 InitializationSequence::FK_RValueReferenceBindingToLValue); 5067 return; 5068 } 5069 5070 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true); 5071 5072 if (T1Quals.hasAddressSpace()) { 5073 if (!Qualifiers::isAddressSpaceSupersetOf(T1Quals.getAddressSpace(), 5074 LangAS::Default)) { 5075 Sequence.SetFailed( 5076 InitializationSequence::FK_ReferenceAddrspaceMismatchTemporary); 5077 return; 5078 } 5079 Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue 5080 : VK_XValue); 5081 } 5082 } 5083 5084 /// Attempt character array initialization from a string literal 5085 /// (C++ [dcl.init.string], C99 6.7.8). 5086 static void TryStringLiteralInitialization(Sema &S, 5087 const InitializedEntity &Entity, 5088 const InitializationKind &Kind, 5089 Expr *Initializer, 5090 InitializationSequence &Sequence) { 5091 Sequence.AddStringInitStep(Entity.getType()); 5092 } 5093 5094 /// Attempt value initialization (C++ [dcl.init]p7). 5095 static void TryValueInitialization(Sema &S, 5096 const InitializedEntity &Entity, 5097 const InitializationKind &Kind, 5098 InitializationSequence &Sequence, 5099 InitListExpr *InitList) { 5100 assert((!InitList || InitList->getNumInits() == 0) && 5101 "Shouldn't use value-init for non-empty init lists"); 5102 5103 // C++98 [dcl.init]p5, C++11 [dcl.init]p7: 5104 // 5105 // To value-initialize an object of type T means: 5106 QualType T = Entity.getType(); 5107 5108 // -- if T is an array type, then each element is value-initialized; 5109 T = S.Context.getBaseElementType(T); 5110 5111 if (const RecordType *RT = T->getAs<RecordType>()) { 5112 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 5113 bool NeedZeroInitialization = true; 5114 // C++98: 5115 // -- if T is a class type (clause 9) with a user-declared constructor 5116 // (12.1), then the default constructor for T is called (and the 5117 // initialization is ill-formed if T has no accessible default 5118 // constructor); 5119 // C++11: 5120 // -- if T is a class type (clause 9) with either no default constructor 5121 // (12.1 [class.ctor]) or a default constructor that is user-provided 5122 // or deleted, then the object is default-initialized; 5123 // 5124 // Note that the C++11 rule is the same as the C++98 rule if there are no 5125 // defaulted or deleted constructors, so we just use it unconditionally. 5126 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl); 5127 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted()) 5128 NeedZeroInitialization = false; 5129 5130 // -- if T is a (possibly cv-qualified) non-union class type without a 5131 // user-provided or deleted default constructor, then the object is 5132 // zero-initialized and, if T has a non-trivial default constructor, 5133 // default-initialized; 5134 // The 'non-union' here was removed by DR1502. The 'non-trivial default 5135 // constructor' part was removed by DR1507. 5136 if (NeedZeroInitialization) 5137 Sequence.AddZeroInitializationStep(Entity.getType()); 5138 5139 // C++03: 5140 // -- if T is a non-union class type without a user-declared constructor, 5141 // then every non-static data member and base class component of T is 5142 // value-initialized; 5143 // [...] A program that calls for [...] value-initialization of an 5144 // entity of reference type is ill-formed. 5145 // 5146 // C++11 doesn't need this handling, because value-initialization does not 5147 // occur recursively there, and the implicit default constructor is 5148 // defined as deleted in the problematic cases. 5149 if (!S.getLangOpts().CPlusPlus11 && 5150 ClassDecl->hasUninitializedReferenceMember()) { 5151 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference); 5152 return; 5153 } 5154 5155 // If this is list-value-initialization, pass the empty init list on when 5156 // building the constructor call. This affects the semantics of a few 5157 // things (such as whether an explicit default constructor can be called). 5158 Expr *InitListAsExpr = InitList; 5159 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0); 5160 bool InitListSyntax = InitList; 5161 5162 // FIXME: Instead of creating a CXXConstructExpr of array type here, 5163 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr. 5164 return TryConstructorInitialization( 5165 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax); 5166 } 5167 } 5168 5169 Sequence.AddZeroInitializationStep(Entity.getType()); 5170 } 5171 5172 /// Attempt default initialization (C++ [dcl.init]p6). 5173 static void TryDefaultInitialization(Sema &S, 5174 const InitializedEntity &Entity, 5175 const InitializationKind &Kind, 5176 InitializationSequence &Sequence) { 5177 assert(Kind.getKind() == InitializationKind::IK_Default); 5178 5179 // C++ [dcl.init]p6: 5180 // To default-initialize an object of type T means: 5181 // - if T is an array type, each element is default-initialized; 5182 QualType DestType = S.Context.getBaseElementType(Entity.getType()); 5183 5184 // - if T is a (possibly cv-qualified) class type (Clause 9), the default 5185 // constructor for T is called (and the initialization is ill-formed if 5186 // T has no accessible default constructor); 5187 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) { 5188 TryConstructorInitialization(S, Entity, Kind, None, DestType, 5189 Entity.getType(), Sequence); 5190 return; 5191 } 5192 5193 // - otherwise, no initialization is performed. 5194 5195 // If a program calls for the default initialization of an object of 5196 // a const-qualified type T, T shall be a class type with a user-provided 5197 // default constructor. 5198 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) { 5199 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity)) 5200 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); 5201 return; 5202 } 5203 5204 // If the destination type has a lifetime property, zero-initialize it. 5205 if (DestType.getQualifiers().hasObjCLifetime()) { 5206 Sequence.AddZeroInitializationStep(Entity.getType()); 5207 return; 5208 } 5209 } 5210 5211 /// Attempt a user-defined conversion between two types (C++ [dcl.init]), 5212 /// which enumerates all conversion functions and performs overload resolution 5213 /// to select the best. 5214 static void TryUserDefinedConversion(Sema &S, 5215 QualType DestType, 5216 const InitializationKind &Kind, 5217 Expr *Initializer, 5218 InitializationSequence &Sequence, 5219 bool TopLevelOfInitList) { 5220 assert(!DestType->isReferenceType() && "References are handled elsewhere"); 5221 QualType SourceType = Initializer->getType(); 5222 assert((DestType->isRecordType() || SourceType->isRecordType()) && 5223 "Must have a class type to perform a user-defined conversion"); 5224 5225 // Build the candidate set directly in the initialization sequence 5226 // structure, so that it will persist if we fail. 5227 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 5228 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 5229 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace()); 5230 5231 // Determine whether we are allowed to call explicit constructors or 5232 // explicit conversion operators. 5233 bool AllowExplicit = Kind.AllowExplicit(); 5234 5235 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) { 5236 // The type we're converting to is a class type. Enumerate its constructors 5237 // to see if there is a suitable conversion. 5238 CXXRecordDecl *DestRecordDecl 5239 = cast<CXXRecordDecl>(DestRecordType->getDecl()); 5240 5241 // Try to complete the type we're converting to. 5242 if (S.isCompleteType(Kind.getLocation(), DestType)) { 5243 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) { 5244 auto Info = getConstructorInfo(D); 5245 if (!Info.Constructor) 5246 continue; 5247 5248 if (!Info.Constructor->isInvalidDecl() && 5249 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) { 5250 if (Info.ConstructorTmpl) 5251 S.AddTemplateOverloadCandidate( 5252 Info.ConstructorTmpl, Info.FoundDecl, 5253 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet, 5254 /*SuppressUserConversions=*/true, 5255 /*PartialOverloading*/ false, AllowExplicit); 5256 else 5257 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 5258 Initializer, CandidateSet, 5259 /*SuppressUserConversions=*/true, 5260 /*PartialOverloading*/ false, AllowExplicit); 5261 } 5262 } 5263 } 5264 } 5265 5266 SourceLocation DeclLoc = Initializer->getBeginLoc(); 5267 5268 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) { 5269 // The type we're converting from is a class type, enumerate its conversion 5270 // functions. 5271 5272 // We can only enumerate the conversion functions for a complete type; if 5273 // the type isn't complete, simply skip this step. 5274 if (S.isCompleteType(DeclLoc, SourceType)) { 5275 CXXRecordDecl *SourceRecordDecl 5276 = cast<CXXRecordDecl>(SourceRecordType->getDecl()); 5277 5278 const auto &Conversions = 5279 SourceRecordDecl->getVisibleConversionFunctions(); 5280 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5281 NamedDecl *D = *I; 5282 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 5283 if (isa<UsingShadowDecl>(D)) 5284 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5285 5286 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5287 CXXConversionDecl *Conv; 5288 if (ConvTemplate) 5289 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5290 else 5291 Conv = cast<CXXConversionDecl>(D); 5292 5293 if (ConvTemplate) 5294 S.AddTemplateConversionCandidate( 5295 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType, 5296 CandidateSet, AllowExplicit, AllowExplicit); 5297 else 5298 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer, 5299 DestType, CandidateSet, AllowExplicit, 5300 AllowExplicit); 5301 } 5302 } 5303 } 5304 5305 // Perform overload resolution. If it fails, return the failed result. 5306 OverloadCandidateSet::iterator Best; 5307 if (OverloadingResult Result 5308 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 5309 Sequence.SetOverloadFailure( 5310 InitializationSequence::FK_UserConversionOverloadFailed, Result); 5311 5312 // [class.copy.elision]p3: 5313 // In some copy-initialization contexts, a two-stage overload resolution 5314 // is performed. 5315 // If the first overload resolution selects a deleted function, we also 5316 // need the initialization sequence to decide whether to perform the second 5317 // overload resolution. 5318 if (!(Result == OR_Deleted && 5319 Kind.getKind() == InitializationKind::IK_Copy)) 5320 return; 5321 } 5322 5323 FunctionDecl *Function = Best->Function; 5324 Function->setReferenced(); 5325 bool HadMultipleCandidates = (CandidateSet.size() > 1); 5326 5327 if (isa<CXXConstructorDecl>(Function)) { 5328 // Add the user-defined conversion step. Any cv-qualification conversion is 5329 // subsumed by the initialization. Per DR5, the created temporary is of the 5330 // cv-unqualified type of the destination. 5331 Sequence.AddUserConversionStep(Function, Best->FoundDecl, 5332 DestType.getUnqualifiedType(), 5333 HadMultipleCandidates); 5334 5335 // C++14 and before: 5336 // - if the function is a constructor, the call initializes a temporary 5337 // of the cv-unqualified version of the destination type. The [...] 5338 // temporary [...] is then used to direct-initialize, according to the 5339 // rules above, the object that is the destination of the 5340 // copy-initialization. 5341 // Note that this just performs a simple object copy from the temporary. 5342 // 5343 // C++17: 5344 // - if the function is a constructor, the call is a prvalue of the 5345 // cv-unqualified version of the destination type whose return object 5346 // is initialized by the constructor. The call is used to 5347 // direct-initialize, according to the rules above, the object that 5348 // is the destination of the copy-initialization. 5349 // Therefore we need to do nothing further. 5350 // 5351 // FIXME: Mark this copy as extraneous. 5352 if (!S.getLangOpts().CPlusPlus17) 5353 Sequence.AddFinalCopy(DestType); 5354 else if (DestType.hasQualifiers()) 5355 Sequence.AddQualificationConversionStep(DestType, VK_RValue); 5356 return; 5357 } 5358 5359 // Add the user-defined conversion step that calls the conversion function. 5360 QualType ConvType = Function->getCallResultType(); 5361 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType, 5362 HadMultipleCandidates); 5363 5364 if (ConvType->getAs<RecordType>()) { 5365 // The call is used to direct-initialize [...] the object that is the 5366 // destination of the copy-initialization. 5367 // 5368 // In C++17, this does not call a constructor if we enter /17.6.1: 5369 // - If the initializer expression is a prvalue and the cv-unqualified 5370 // version of the source type is the same as the class of the 5371 // destination [... do not make an extra copy] 5372 // 5373 // FIXME: Mark this copy as extraneous. 5374 if (!S.getLangOpts().CPlusPlus17 || 5375 Function->getReturnType()->isReferenceType() || 5376 !S.Context.hasSameUnqualifiedType(ConvType, DestType)) 5377 Sequence.AddFinalCopy(DestType); 5378 else if (!S.Context.hasSameType(ConvType, DestType)) 5379 Sequence.AddQualificationConversionStep(DestType, VK_RValue); 5380 return; 5381 } 5382 5383 // If the conversion following the call to the conversion function 5384 // is interesting, add it as a separate step. 5385 if (Best->FinalConversion.First || Best->FinalConversion.Second || 5386 Best->FinalConversion.Third) { 5387 ImplicitConversionSequence ICS; 5388 ICS.setStandard(); 5389 ICS.Standard = Best->FinalConversion; 5390 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList); 5391 } 5392 } 5393 5394 /// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>, 5395 /// a function with a pointer return type contains a 'return false;' statement. 5396 /// In C++11, 'false' is not a null pointer, so this breaks the build of any 5397 /// code using that header. 5398 /// 5399 /// Work around this by treating 'return false;' as zero-initializing the result 5400 /// if it's used in a pointer-returning function in a system header. 5401 static bool isLibstdcxxPointerReturnFalseHack(Sema &S, 5402 const InitializedEntity &Entity, 5403 const Expr *Init) { 5404 return S.getLangOpts().CPlusPlus11 && 5405 Entity.getKind() == InitializedEntity::EK_Result && 5406 Entity.getType()->isPointerType() && 5407 isa<CXXBoolLiteralExpr>(Init) && 5408 !cast<CXXBoolLiteralExpr>(Init)->getValue() && 5409 S.getSourceManager().isInSystemHeader(Init->getExprLoc()); 5410 } 5411 5412 /// The non-zero enum values here are indexes into diagnostic alternatives. 5413 enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar }; 5414 5415 /// Determines whether this expression is an acceptable ICR source. 5416 static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e, 5417 bool isAddressOf, bool &isWeakAccess) { 5418 // Skip parens. 5419 e = e->IgnoreParens(); 5420 5421 // Skip address-of nodes. 5422 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) { 5423 if (op->getOpcode() == UO_AddrOf) 5424 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true, 5425 isWeakAccess); 5426 5427 // Skip certain casts. 5428 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) { 5429 switch (ce->getCastKind()) { 5430 case CK_Dependent: 5431 case CK_BitCast: 5432 case CK_LValueBitCast: 5433 case CK_NoOp: 5434 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess); 5435 5436 case CK_ArrayToPointerDecay: 5437 return IIK_nonscalar; 5438 5439 case CK_NullToPointer: 5440 return IIK_okay; 5441 5442 default: 5443 break; 5444 } 5445 5446 // If we have a declaration reference, it had better be a local variable. 5447 } else if (isa<DeclRefExpr>(e)) { 5448 // set isWeakAccess to true, to mean that there will be an implicit 5449 // load which requires a cleanup. 5450 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 5451 isWeakAccess = true; 5452 5453 if (!isAddressOf) return IIK_nonlocal; 5454 5455 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl()); 5456 if (!var) return IIK_nonlocal; 5457 5458 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal); 5459 5460 // If we have a conditional operator, check both sides. 5461 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) { 5462 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf, 5463 isWeakAccess)) 5464 return iik; 5465 5466 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess); 5467 5468 // These are never scalar. 5469 } else if (isa<ArraySubscriptExpr>(e)) { 5470 return IIK_nonscalar; 5471 5472 // Otherwise, it needs to be a null pointer constant. 5473 } else { 5474 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull) 5475 ? IIK_okay : IIK_nonlocal); 5476 } 5477 5478 return IIK_nonlocal; 5479 } 5480 5481 /// Check whether the given expression is a valid operand for an 5482 /// indirect copy/restore. 5483 static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) { 5484 assert(src->isRValue()); 5485 bool isWeakAccess = false; 5486 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess); 5487 // If isWeakAccess to true, there will be an implicit 5488 // load which requires a cleanup. 5489 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess) 5490 S.Cleanup.setExprNeedsCleanups(true); 5491 5492 if (iik == IIK_okay) return; 5493 5494 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback) 5495 << ((unsigned) iik - 1) // shift index into diagnostic explanations 5496 << src->getSourceRange(); 5497 } 5498 5499 /// Determine whether we have compatible array types for the 5500 /// purposes of GNU by-copy array initialization. 5501 static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest, 5502 const ArrayType *Source) { 5503 // If the source and destination array types are equivalent, we're 5504 // done. 5505 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0))) 5506 return true; 5507 5508 // Make sure that the element types are the same. 5509 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType())) 5510 return false; 5511 5512 // The only mismatch we allow is when the destination is an 5513 // incomplete array type and the source is a constant array type. 5514 return Source->isConstantArrayType() && Dest->isIncompleteArrayType(); 5515 } 5516 5517 static bool tryObjCWritebackConversion(Sema &S, 5518 InitializationSequence &Sequence, 5519 const InitializedEntity &Entity, 5520 Expr *Initializer) { 5521 bool ArrayDecay = false; 5522 QualType ArgType = Initializer->getType(); 5523 QualType ArgPointee; 5524 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) { 5525 ArrayDecay = true; 5526 ArgPointee = ArgArrayType->getElementType(); 5527 ArgType = S.Context.getPointerType(ArgPointee); 5528 } 5529 5530 // Handle write-back conversion. 5531 QualType ConvertedArgType; 5532 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(), 5533 ConvertedArgType)) 5534 return false; 5535 5536 // We should copy unless we're passing to an argument explicitly 5537 // marked 'out'. 5538 bool ShouldCopy = true; 5539 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl())) 5540 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); 5541 5542 // Do we need an lvalue conversion? 5543 if (ArrayDecay || Initializer->isGLValue()) { 5544 ImplicitConversionSequence ICS; 5545 ICS.setStandard(); 5546 ICS.Standard.setAsIdentityConversion(); 5547 5548 QualType ResultType; 5549 if (ArrayDecay) { 5550 ICS.Standard.First = ICK_Array_To_Pointer; 5551 ResultType = S.Context.getPointerType(ArgPointee); 5552 } else { 5553 ICS.Standard.First = ICK_Lvalue_To_Rvalue; 5554 ResultType = Initializer->getType().getNonLValueExprType(S.Context); 5555 } 5556 5557 Sequence.AddConversionSequenceStep(ICS, ResultType); 5558 } 5559 5560 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy); 5561 return true; 5562 } 5563 5564 static bool TryOCLSamplerInitialization(Sema &S, 5565 InitializationSequence &Sequence, 5566 QualType DestType, 5567 Expr *Initializer) { 5568 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() || 5569 (!Initializer->isIntegerConstantExpr(S.Context) && 5570 !Initializer->getType()->isSamplerT())) 5571 return false; 5572 5573 Sequence.AddOCLSamplerInitStep(DestType); 5574 return true; 5575 } 5576 5577 static bool IsZeroInitializer(Expr *Initializer, Sema &S) { 5578 return Initializer->isIntegerConstantExpr(S.getASTContext()) && 5579 (Initializer->EvaluateKnownConstInt(S.getASTContext()) == 0); 5580 } 5581 5582 static bool TryOCLZeroOpaqueTypeInitialization(Sema &S, 5583 InitializationSequence &Sequence, 5584 QualType DestType, 5585 Expr *Initializer) { 5586 if (!S.getLangOpts().OpenCL) 5587 return false; 5588 5589 // 5590 // OpenCL 1.2 spec, s6.12.10 5591 // 5592 // The event argument can also be used to associate the 5593 // async_work_group_copy with a previous async copy allowing 5594 // an event to be shared by multiple async copies; otherwise 5595 // event should be zero. 5596 // 5597 if (DestType->isEventT() || DestType->isQueueT()) { 5598 if (!IsZeroInitializer(Initializer, S)) 5599 return false; 5600 5601 Sequence.AddOCLZeroOpaqueTypeStep(DestType); 5602 return true; 5603 } 5604 5605 // We should allow zero initialization for all types defined in the 5606 // cl_intel_device_side_avc_motion_estimation extension, except 5607 // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t. 5608 if (S.getOpenCLOptions().isAvailableOption( 5609 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()) && 5610 DestType->isOCLIntelSubgroupAVCType()) { 5611 if (DestType->isOCLIntelSubgroupAVCMcePayloadType() || 5612 DestType->isOCLIntelSubgroupAVCMceResultType()) 5613 return false; 5614 if (!IsZeroInitializer(Initializer, S)) 5615 return false; 5616 5617 Sequence.AddOCLZeroOpaqueTypeStep(DestType); 5618 return true; 5619 } 5620 5621 return false; 5622 } 5623 5624 InitializationSequence::InitializationSequence( 5625 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, 5626 MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid) 5627 : FailedOverloadResult(OR_Success), 5628 FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) { 5629 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList, 5630 TreatUnavailableAsInvalid); 5631 } 5632 5633 /// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the 5634 /// address of that function, this returns true. Otherwise, it returns false. 5635 static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) { 5636 auto *DRE = dyn_cast<DeclRefExpr>(E); 5637 if (!DRE || !isa<FunctionDecl>(DRE->getDecl())) 5638 return false; 5639 5640 return !S.checkAddressOfFunctionIsAvailable( 5641 cast<FunctionDecl>(DRE->getDecl())); 5642 } 5643 5644 /// Determine whether we can perform an elementwise array copy for this kind 5645 /// of entity. 5646 static bool canPerformArrayCopy(const InitializedEntity &Entity) { 5647 switch (Entity.getKind()) { 5648 case InitializedEntity::EK_LambdaCapture: 5649 // C++ [expr.prim.lambda]p24: 5650 // For array members, the array elements are direct-initialized in 5651 // increasing subscript order. 5652 return true; 5653 5654 case InitializedEntity::EK_Variable: 5655 // C++ [dcl.decomp]p1: 5656 // [...] each element is copy-initialized or direct-initialized from the 5657 // corresponding element of the assignment-expression [...] 5658 return isa<DecompositionDecl>(Entity.getDecl()); 5659 5660 case InitializedEntity::EK_Member: 5661 // C++ [class.copy.ctor]p14: 5662 // - if the member is an array, each element is direct-initialized with 5663 // the corresponding subobject of x 5664 return Entity.isImplicitMemberInitializer(); 5665 5666 case InitializedEntity::EK_ArrayElement: 5667 // All the above cases are intended to apply recursively, even though none 5668 // of them actually say that. 5669 if (auto *E = Entity.getParent()) 5670 return canPerformArrayCopy(*E); 5671 break; 5672 5673 default: 5674 break; 5675 } 5676 5677 return false; 5678 } 5679 5680 void InitializationSequence::InitializeFrom(Sema &S, 5681 const InitializedEntity &Entity, 5682 const InitializationKind &Kind, 5683 MultiExprArg Args, 5684 bool TopLevelOfInitList, 5685 bool TreatUnavailableAsInvalid) { 5686 ASTContext &Context = S.Context; 5687 5688 // Eliminate non-overload placeholder types in the arguments. We 5689 // need to do this before checking whether types are dependent 5690 // because lowering a pseudo-object expression might well give us 5691 // something of dependent type. 5692 for (unsigned I = 0, E = Args.size(); I != E; ++I) 5693 if (Args[I]->getType()->isNonOverloadPlaceholderType()) { 5694 // FIXME: should we be doing this here? 5695 ExprResult result = S.CheckPlaceholderExpr(Args[I]); 5696 if (result.isInvalid()) { 5697 SetFailed(FK_PlaceholderType); 5698 return; 5699 } 5700 Args[I] = result.get(); 5701 } 5702 5703 // C++0x [dcl.init]p16: 5704 // The semantics of initializers are as follows. The destination type is 5705 // the type of the object or reference being initialized and the source 5706 // type is the type of the initializer expression. The source type is not 5707 // defined when the initializer is a braced-init-list or when it is a 5708 // parenthesized list of expressions. 5709 QualType DestType = Entity.getType(); 5710 5711 if (DestType->isDependentType() || 5712 Expr::hasAnyTypeDependentArguments(Args)) { 5713 SequenceKind = DependentSequence; 5714 return; 5715 } 5716 5717 // Almost everything is a normal sequence. 5718 setSequenceKind(NormalSequence); 5719 5720 QualType SourceType; 5721 Expr *Initializer = nullptr; 5722 if (Args.size() == 1) { 5723 Initializer = Args[0]; 5724 if (S.getLangOpts().ObjC) { 5725 if (S.CheckObjCBridgeRelatedConversions(Initializer->getBeginLoc(), 5726 DestType, Initializer->getType(), 5727 Initializer) || 5728 S.CheckConversionToObjCLiteral(DestType, Initializer)) 5729 Args[0] = Initializer; 5730 } 5731 if (!isa<InitListExpr>(Initializer)) 5732 SourceType = Initializer->getType(); 5733 } 5734 5735 // - If the initializer is a (non-parenthesized) braced-init-list, the 5736 // object is list-initialized (8.5.4). 5737 if (Kind.getKind() != InitializationKind::IK_Direct) { 5738 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) { 5739 TryListInitialization(S, Entity, Kind, InitList, *this, 5740 TreatUnavailableAsInvalid); 5741 return; 5742 } 5743 } 5744 5745 // - If the destination type is a reference type, see 8.5.3. 5746 if (DestType->isReferenceType()) { 5747 // C++0x [dcl.init.ref]p1: 5748 // A variable declared to be a T& or T&&, that is, "reference to type T" 5749 // (8.3.2), shall be initialized by an object, or function, of type T or 5750 // by an object that can be converted into a T. 5751 // (Therefore, multiple arguments are not permitted.) 5752 if (Args.size() != 1) 5753 SetFailed(FK_TooManyInitsForReference); 5754 // C++17 [dcl.init.ref]p5: 5755 // A reference [...] is initialized by an expression [...] as follows: 5756 // If the initializer is not an expression, presumably we should reject, 5757 // but the standard fails to actually say so. 5758 else if (isa<InitListExpr>(Args[0])) 5759 SetFailed(FK_ParenthesizedListInitForReference); 5760 else 5761 TryReferenceInitialization(S, Entity, Kind, Args[0], *this); 5762 return; 5763 } 5764 5765 // - If the initializer is (), the object is value-initialized. 5766 if (Kind.getKind() == InitializationKind::IK_Value || 5767 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) { 5768 TryValueInitialization(S, Entity, Kind, *this); 5769 return; 5770 } 5771 5772 // Handle default initialization. 5773 if (Kind.getKind() == InitializationKind::IK_Default) { 5774 TryDefaultInitialization(S, Entity, Kind, *this); 5775 return; 5776 } 5777 5778 // - If the destination type is an array of characters, an array of 5779 // char16_t, an array of char32_t, or an array of wchar_t, and the 5780 // initializer is a string literal, see 8.5.2. 5781 // - Otherwise, if the destination type is an array, the program is 5782 // ill-formed. 5783 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) { 5784 if (Initializer && isa<VariableArrayType>(DestAT)) { 5785 SetFailed(FK_VariableLengthArrayHasInitializer); 5786 return; 5787 } 5788 5789 if (Initializer) { 5790 switch (IsStringInit(Initializer, DestAT, Context)) { 5791 case SIF_None: 5792 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this); 5793 return; 5794 case SIF_NarrowStringIntoWideChar: 5795 SetFailed(FK_NarrowStringIntoWideCharArray); 5796 return; 5797 case SIF_WideStringIntoChar: 5798 SetFailed(FK_WideStringIntoCharArray); 5799 return; 5800 case SIF_IncompatWideStringIntoWideChar: 5801 SetFailed(FK_IncompatWideStringIntoWideChar); 5802 return; 5803 case SIF_PlainStringIntoUTF8Char: 5804 SetFailed(FK_PlainStringIntoUTF8Char); 5805 return; 5806 case SIF_UTF8StringIntoPlainChar: 5807 SetFailed(FK_UTF8StringIntoPlainChar); 5808 return; 5809 case SIF_Other: 5810 break; 5811 } 5812 } 5813 5814 // Some kinds of initialization permit an array to be initialized from 5815 // another array of the same type, and perform elementwise initialization. 5816 if (Initializer && isa<ConstantArrayType>(DestAT) && 5817 S.Context.hasSameUnqualifiedType(Initializer->getType(), 5818 Entity.getType()) && 5819 canPerformArrayCopy(Entity)) { 5820 // If source is a prvalue, use it directly. 5821 if (Initializer->getValueKind() == VK_RValue) { 5822 AddArrayInitStep(DestType, /*IsGNUExtension*/false); 5823 return; 5824 } 5825 5826 // Emit element-at-a-time copy loop. 5827 InitializedEntity Element = 5828 InitializedEntity::InitializeElement(S.Context, 0, Entity); 5829 QualType InitEltT = 5830 Context.getAsArrayType(Initializer->getType())->getElementType(); 5831 OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT, 5832 Initializer->getValueKind(), 5833 Initializer->getObjectKind()); 5834 Expr *OVEAsExpr = &OVE; 5835 InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList, 5836 TreatUnavailableAsInvalid); 5837 if (!Failed()) 5838 AddArrayInitLoopStep(Entity.getType(), InitEltT); 5839 return; 5840 } 5841 5842 // Note: as an GNU C extension, we allow initialization of an 5843 // array from a compound literal that creates an array of the same 5844 // type, so long as the initializer has no side effects. 5845 if (!S.getLangOpts().CPlusPlus && Initializer && 5846 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) && 5847 Initializer->getType()->isArrayType()) { 5848 const ArrayType *SourceAT 5849 = Context.getAsArrayType(Initializer->getType()); 5850 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT)) 5851 SetFailed(FK_ArrayTypeMismatch); 5852 else if (Initializer->HasSideEffects(S.Context)) 5853 SetFailed(FK_NonConstantArrayInit); 5854 else { 5855 AddArrayInitStep(DestType, /*IsGNUExtension*/true); 5856 } 5857 } 5858 // Note: as a GNU C++ extension, we allow list-initialization of a 5859 // class member of array type from a parenthesized initializer list. 5860 else if (S.getLangOpts().CPlusPlus && 5861 Entity.getKind() == InitializedEntity::EK_Member && 5862 Initializer && isa<InitListExpr>(Initializer)) { 5863 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer), 5864 *this, TreatUnavailableAsInvalid); 5865 AddParenthesizedArrayInitStep(DestType); 5866 } else if (DestAT->getElementType()->isCharType()) 5867 SetFailed(FK_ArrayNeedsInitListOrStringLiteral); 5868 else if (IsWideCharCompatible(DestAT->getElementType(), Context)) 5869 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral); 5870 else 5871 SetFailed(FK_ArrayNeedsInitList); 5872 5873 return; 5874 } 5875 5876 // Determine whether we should consider writeback conversions for 5877 // Objective-C ARC. 5878 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount && 5879 Entity.isParameterKind(); 5880 5881 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer)) 5882 return; 5883 5884 // We're at the end of the line for C: it's either a write-back conversion 5885 // or it's a C assignment. There's no need to check anything else. 5886 if (!S.getLangOpts().CPlusPlus) { 5887 // If allowed, check whether this is an Objective-C writeback conversion. 5888 if (allowObjCWritebackConversion && 5889 tryObjCWritebackConversion(S, *this, Entity, Initializer)) { 5890 return; 5891 } 5892 5893 if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer)) 5894 return; 5895 5896 // Handle initialization in C 5897 AddCAssignmentStep(DestType); 5898 MaybeProduceObjCObject(S, *this, Entity); 5899 return; 5900 } 5901 5902 assert(S.getLangOpts().CPlusPlus); 5903 5904 // - If the destination type is a (possibly cv-qualified) class type: 5905 if (DestType->isRecordType()) { 5906 // - If the initialization is direct-initialization, or if it is 5907 // copy-initialization where the cv-unqualified version of the 5908 // source type is the same class as, or a derived class of, the 5909 // class of the destination, constructors are considered. [...] 5910 if (Kind.getKind() == InitializationKind::IK_Direct || 5911 (Kind.getKind() == InitializationKind::IK_Copy && 5912 (Context.hasSameUnqualifiedType(SourceType, DestType) || 5913 S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType, DestType)))) 5914 TryConstructorInitialization(S, Entity, Kind, Args, 5915 DestType, DestType, *this); 5916 // - Otherwise (i.e., for the remaining copy-initialization cases), 5917 // user-defined conversion sequences that can convert from the source 5918 // type to the destination type or (when a conversion function is 5919 // used) to a derived class thereof are enumerated as described in 5920 // 13.3.1.4, and the best one is chosen through overload resolution 5921 // (13.3). 5922 else 5923 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this, 5924 TopLevelOfInitList); 5925 return; 5926 } 5927 5928 assert(Args.size() >= 1 && "Zero-argument case handled above"); 5929 5930 // The remaining cases all need a source type. 5931 if (Args.size() > 1) { 5932 SetFailed(FK_TooManyInitsForScalar); 5933 return; 5934 } else if (isa<InitListExpr>(Args[0])) { 5935 SetFailed(FK_ParenthesizedListInitForScalar); 5936 return; 5937 } 5938 5939 // - Otherwise, if the source type is a (possibly cv-qualified) class 5940 // type, conversion functions are considered. 5941 if (!SourceType.isNull() && SourceType->isRecordType()) { 5942 // For a conversion to _Atomic(T) from either T or a class type derived 5943 // from T, initialize the T object then convert to _Atomic type. 5944 bool NeedAtomicConversion = false; 5945 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) { 5946 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) || 5947 S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType, 5948 Atomic->getValueType())) { 5949 DestType = Atomic->getValueType(); 5950 NeedAtomicConversion = true; 5951 } 5952 } 5953 5954 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this, 5955 TopLevelOfInitList); 5956 MaybeProduceObjCObject(S, *this, Entity); 5957 if (!Failed() && NeedAtomicConversion) 5958 AddAtomicConversionStep(Entity.getType()); 5959 return; 5960 } 5961 5962 // - Otherwise, if the initialization is direct-initialization, the source 5963 // type is std::nullptr_t, and the destination type is bool, the initial 5964 // value of the object being initialized is false. 5965 if (!SourceType.isNull() && SourceType->isNullPtrType() && 5966 DestType->isBooleanType() && 5967 Kind.getKind() == InitializationKind::IK_Direct) { 5968 AddConversionSequenceStep( 5969 ImplicitConversionSequence::getNullptrToBool(SourceType, DestType, 5970 Initializer->isGLValue()), 5971 DestType); 5972 return; 5973 } 5974 5975 // - Otherwise, the initial value of the object being initialized is the 5976 // (possibly converted) value of the initializer expression. Standard 5977 // conversions (Clause 4) will be used, if necessary, to convert the 5978 // initializer expression to the cv-unqualified version of the 5979 // destination type; no user-defined conversions are considered. 5980 5981 ImplicitConversionSequence ICS 5982 = S.TryImplicitConversion(Initializer, DestType, 5983 /*SuppressUserConversions*/true, 5984 Sema::AllowedExplicit::None, 5985 /*InOverloadResolution*/ false, 5986 /*CStyle=*/Kind.isCStyleOrFunctionalCast(), 5987 allowObjCWritebackConversion); 5988 5989 if (ICS.isStandard() && 5990 ICS.Standard.Second == ICK_Writeback_Conversion) { 5991 // Objective-C ARC writeback conversion. 5992 5993 // We should copy unless we're passing to an argument explicitly 5994 // marked 'out'. 5995 bool ShouldCopy = true; 5996 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl())) 5997 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); 5998 5999 // If there was an lvalue adjustment, add it as a separate conversion. 6000 if (ICS.Standard.First == ICK_Array_To_Pointer || 6001 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 6002 ImplicitConversionSequence LvalueICS; 6003 LvalueICS.setStandard(); 6004 LvalueICS.Standard.setAsIdentityConversion(); 6005 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0)); 6006 LvalueICS.Standard.First = ICS.Standard.First; 6007 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0)); 6008 } 6009 6010 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy); 6011 } else if (ICS.isBad()) { 6012 DeclAccessPair dap; 6013 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) { 6014 AddZeroInitializationStep(Entity.getType()); 6015 } else if (Initializer->getType() == Context.OverloadTy && 6016 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType, 6017 false, dap)) 6018 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 6019 else if (Initializer->getType()->isFunctionType() && 6020 isExprAnUnaddressableFunction(S, Initializer)) 6021 SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction); 6022 else 6023 SetFailed(InitializationSequence::FK_ConversionFailed); 6024 } else { 6025 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList); 6026 6027 MaybeProduceObjCObject(S, *this, Entity); 6028 } 6029 } 6030 6031 InitializationSequence::~InitializationSequence() { 6032 for (auto &S : Steps) 6033 S.Destroy(); 6034 } 6035 6036 //===----------------------------------------------------------------------===// 6037 // Perform initialization 6038 //===----------------------------------------------------------------------===// 6039 static Sema::AssignmentAction 6040 getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) { 6041 switch(Entity.getKind()) { 6042 case InitializedEntity::EK_Variable: 6043 case InitializedEntity::EK_New: 6044 case InitializedEntity::EK_Exception: 6045 case InitializedEntity::EK_Base: 6046 case InitializedEntity::EK_Delegating: 6047 return Sema::AA_Initializing; 6048 6049 case InitializedEntity::EK_Parameter: 6050 if (Entity.getDecl() && 6051 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext())) 6052 return Sema::AA_Sending; 6053 6054 return Sema::AA_Passing; 6055 6056 case InitializedEntity::EK_Parameter_CF_Audited: 6057 if (Entity.getDecl() && 6058 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext())) 6059 return Sema::AA_Sending; 6060 6061 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited; 6062 6063 case InitializedEntity::EK_Result: 6064 case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right. 6065 return Sema::AA_Returning; 6066 6067 case InitializedEntity::EK_Temporary: 6068 case InitializedEntity::EK_RelatedResult: 6069 // FIXME: Can we tell apart casting vs. converting? 6070 return Sema::AA_Casting; 6071 6072 case InitializedEntity::EK_TemplateParameter: 6073 // This is really initialization, but refer to it as conversion for 6074 // consistency with CheckConvertedConstantExpression. 6075 return Sema::AA_Converting; 6076 6077 case InitializedEntity::EK_Member: 6078 case InitializedEntity::EK_Binding: 6079 case InitializedEntity::EK_ArrayElement: 6080 case InitializedEntity::EK_VectorElement: 6081 case InitializedEntity::EK_ComplexElement: 6082 case InitializedEntity::EK_BlockElement: 6083 case InitializedEntity::EK_LambdaToBlockConversionBlockElement: 6084 case InitializedEntity::EK_LambdaCapture: 6085 case InitializedEntity::EK_CompoundLiteralInit: 6086 return Sema::AA_Initializing; 6087 } 6088 6089 llvm_unreachable("Invalid EntityKind!"); 6090 } 6091 6092 /// Whether we should bind a created object as a temporary when 6093 /// initializing the given entity. 6094 static bool shouldBindAsTemporary(const InitializedEntity &Entity) { 6095 switch (Entity.getKind()) { 6096 case InitializedEntity::EK_ArrayElement: 6097 case InitializedEntity::EK_Member: 6098 case InitializedEntity::EK_Result: 6099 case InitializedEntity::EK_StmtExprResult: 6100 case InitializedEntity::EK_New: 6101 case InitializedEntity::EK_Variable: 6102 case InitializedEntity::EK_Base: 6103 case InitializedEntity::EK_Delegating: 6104 case InitializedEntity::EK_VectorElement: 6105 case InitializedEntity::EK_ComplexElement: 6106 case InitializedEntity::EK_Exception: 6107 case InitializedEntity::EK_BlockElement: 6108 case InitializedEntity::EK_LambdaToBlockConversionBlockElement: 6109 case InitializedEntity::EK_LambdaCapture: 6110 case InitializedEntity::EK_CompoundLiteralInit: 6111 case InitializedEntity::EK_TemplateParameter: 6112 return false; 6113 6114 case InitializedEntity::EK_Parameter: 6115 case InitializedEntity::EK_Parameter_CF_Audited: 6116 case InitializedEntity::EK_Temporary: 6117 case InitializedEntity::EK_RelatedResult: 6118 case InitializedEntity::EK_Binding: 6119 return true; 6120 } 6121 6122 llvm_unreachable("missed an InitializedEntity kind?"); 6123 } 6124 6125 /// Whether the given entity, when initialized with an object 6126 /// created for that initialization, requires destruction. 6127 static bool shouldDestroyEntity(const InitializedEntity &Entity) { 6128 switch (Entity.getKind()) { 6129 case InitializedEntity::EK_Result: 6130 case InitializedEntity::EK_StmtExprResult: 6131 case InitializedEntity::EK_New: 6132 case InitializedEntity::EK_Base: 6133 case InitializedEntity::EK_Delegating: 6134 case InitializedEntity::EK_VectorElement: 6135 case InitializedEntity::EK_ComplexElement: 6136 case InitializedEntity::EK_BlockElement: 6137 case InitializedEntity::EK_LambdaToBlockConversionBlockElement: 6138 case InitializedEntity::EK_LambdaCapture: 6139 return false; 6140 6141 case InitializedEntity::EK_Member: 6142 case InitializedEntity::EK_Binding: 6143 case InitializedEntity::EK_Variable: 6144 case InitializedEntity::EK_Parameter: 6145 case InitializedEntity::EK_Parameter_CF_Audited: 6146 case InitializedEntity::EK_TemplateParameter: 6147 case InitializedEntity::EK_Temporary: 6148 case InitializedEntity::EK_ArrayElement: 6149 case InitializedEntity::EK_Exception: 6150 case InitializedEntity::EK_CompoundLiteralInit: 6151 case InitializedEntity::EK_RelatedResult: 6152 return true; 6153 } 6154 6155 llvm_unreachable("missed an InitializedEntity kind?"); 6156 } 6157 6158 /// Get the location at which initialization diagnostics should appear. 6159 static SourceLocation getInitializationLoc(const InitializedEntity &Entity, 6160 Expr *Initializer) { 6161 switch (Entity.getKind()) { 6162 case InitializedEntity::EK_Result: 6163 case InitializedEntity::EK_StmtExprResult: 6164 return Entity.getReturnLoc(); 6165 6166 case InitializedEntity::EK_Exception: 6167 return Entity.getThrowLoc(); 6168 6169 case InitializedEntity::EK_Variable: 6170 case InitializedEntity::EK_Binding: 6171 return Entity.getDecl()->getLocation(); 6172 6173 case InitializedEntity::EK_LambdaCapture: 6174 return Entity.getCaptureLoc(); 6175 6176 case InitializedEntity::EK_ArrayElement: 6177 case InitializedEntity::EK_Member: 6178 case InitializedEntity::EK_Parameter: 6179 case InitializedEntity::EK_Parameter_CF_Audited: 6180 case InitializedEntity::EK_TemplateParameter: 6181 case InitializedEntity::EK_Temporary: 6182 case InitializedEntity::EK_New: 6183 case InitializedEntity::EK_Base: 6184 case InitializedEntity::EK_Delegating: 6185 case InitializedEntity::EK_VectorElement: 6186 case InitializedEntity::EK_ComplexElement: 6187 case InitializedEntity::EK_BlockElement: 6188 case InitializedEntity::EK_LambdaToBlockConversionBlockElement: 6189 case InitializedEntity::EK_CompoundLiteralInit: 6190 case InitializedEntity::EK_RelatedResult: 6191 return Initializer->getBeginLoc(); 6192 } 6193 llvm_unreachable("missed an InitializedEntity kind?"); 6194 } 6195 6196 /// Make a (potentially elidable) temporary copy of the object 6197 /// provided by the given initializer by calling the appropriate copy 6198 /// constructor. 6199 /// 6200 /// \param S The Sema object used for type-checking. 6201 /// 6202 /// \param T The type of the temporary object, which must either be 6203 /// the type of the initializer expression or a superclass thereof. 6204 /// 6205 /// \param Entity The entity being initialized. 6206 /// 6207 /// \param CurInit The initializer expression. 6208 /// 6209 /// \param IsExtraneousCopy Whether this is an "extraneous" copy that 6210 /// is permitted in C++03 (but not C++0x) when binding a reference to 6211 /// an rvalue. 6212 /// 6213 /// \returns An expression that copies the initializer expression into 6214 /// a temporary object, or an error expression if a copy could not be 6215 /// created. 6216 static ExprResult CopyObject(Sema &S, 6217 QualType T, 6218 const InitializedEntity &Entity, 6219 ExprResult CurInit, 6220 bool IsExtraneousCopy) { 6221 if (CurInit.isInvalid()) 6222 return CurInit; 6223 // Determine which class type we're copying to. 6224 Expr *CurInitExpr = (Expr *)CurInit.get(); 6225 CXXRecordDecl *Class = nullptr; 6226 if (const RecordType *Record = T->getAs<RecordType>()) 6227 Class = cast<CXXRecordDecl>(Record->getDecl()); 6228 if (!Class) 6229 return CurInit; 6230 6231 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get()); 6232 6233 // Make sure that the type we are copying is complete. 6234 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete)) 6235 return CurInit; 6236 6237 // Perform overload resolution using the class's constructors. Per 6238 // C++11 [dcl.init]p16, second bullet for class types, this initialization 6239 // is direct-initialization. 6240 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 6241 DeclContext::lookup_result Ctors = S.LookupConstructors(Class); 6242 6243 OverloadCandidateSet::iterator Best; 6244 switch (ResolveConstructorOverload( 6245 S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best, 6246 /*CopyInitializing=*/false, /*AllowExplicit=*/true, 6247 /*OnlyListConstructors=*/false, /*IsListInit=*/false, 6248 /*SecondStepOfCopyInit=*/true)) { 6249 case OR_Success: 6250 break; 6251 6252 case OR_No_Viable_Function: 6253 CandidateSet.NoteCandidates( 6254 PartialDiagnosticAt( 6255 Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext() 6256 ? diag::ext_rvalue_to_reference_temp_copy_no_viable 6257 : diag::err_temp_copy_no_viable) 6258 << (int)Entity.getKind() << CurInitExpr->getType() 6259 << CurInitExpr->getSourceRange()), 6260 S, OCD_AllCandidates, CurInitExpr); 6261 if (!IsExtraneousCopy || S.isSFINAEContext()) 6262 return ExprError(); 6263 return CurInit; 6264 6265 case OR_Ambiguous: 6266 CandidateSet.NoteCandidates( 6267 PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous) 6268 << (int)Entity.getKind() 6269 << CurInitExpr->getType() 6270 << CurInitExpr->getSourceRange()), 6271 S, OCD_AmbiguousCandidates, CurInitExpr); 6272 return ExprError(); 6273 6274 case OR_Deleted: 6275 S.Diag(Loc, diag::err_temp_copy_deleted) 6276 << (int)Entity.getKind() << CurInitExpr->getType() 6277 << CurInitExpr->getSourceRange(); 6278 S.NoteDeletedFunction(Best->Function); 6279 return ExprError(); 6280 } 6281 6282 bool HadMultipleCandidates = CandidateSet.size() > 1; 6283 6284 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 6285 SmallVector<Expr*, 8> ConstructorArgs; 6286 CurInit.get(); // Ownership transferred into MultiExprArg, below. 6287 6288 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity, 6289 IsExtraneousCopy); 6290 6291 if (IsExtraneousCopy) { 6292 // If this is a totally extraneous copy for C++03 reference 6293 // binding purposes, just return the original initialization 6294 // expression. We don't generate an (elided) copy operation here 6295 // because doing so would require us to pass down a flag to avoid 6296 // infinite recursion, where each step adds another extraneous, 6297 // elidable copy. 6298 6299 // Instantiate the default arguments of any extra parameters in 6300 // the selected copy constructor, as if we were going to create a 6301 // proper call to the copy constructor. 6302 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) { 6303 ParmVarDecl *Parm = Constructor->getParamDecl(I); 6304 if (S.RequireCompleteType(Loc, Parm->getType(), 6305 diag::err_call_incomplete_argument)) 6306 break; 6307 6308 // Build the default argument expression; we don't actually care 6309 // if this succeeds or not, because this routine will complain 6310 // if there was a problem. 6311 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm); 6312 } 6313 6314 return CurInitExpr; 6315 } 6316 6317 // Determine the arguments required to actually perform the 6318 // constructor call (we might have derived-to-base conversions, or 6319 // the copy constructor may have default arguments). 6320 if (S.CompleteConstructorCall(Constructor, T, CurInitExpr, Loc, 6321 ConstructorArgs)) 6322 return ExprError(); 6323 6324 // C++0x [class.copy]p32: 6325 // When certain criteria are met, an implementation is allowed to 6326 // omit the copy/move construction of a class object, even if the 6327 // copy/move constructor and/or destructor for the object have 6328 // side effects. [...] 6329 // - when a temporary class object that has not been bound to a 6330 // reference (12.2) would be copied/moved to a class object 6331 // with the same cv-unqualified type, the copy/move operation 6332 // can be omitted by constructing the temporary object 6333 // directly into the target of the omitted copy/move 6334 // 6335 // Note that the other three bullets are handled elsewhere. Copy 6336 // elision for return statements and throw expressions are handled as part 6337 // of constructor initialization, while copy elision for exception handlers 6338 // is handled by the run-time. 6339 // 6340 // FIXME: If the function parameter is not the same type as the temporary, we 6341 // should still be able to elide the copy, but we don't have a way to 6342 // represent in the AST how much should be elided in this case. 6343 bool Elidable = 6344 CurInitExpr->isTemporaryObject(S.Context, Class) && 6345 S.Context.hasSameUnqualifiedType( 6346 Best->Function->getParamDecl(0)->getType().getNonReferenceType(), 6347 CurInitExpr->getType()); 6348 6349 // Actually perform the constructor call. 6350 CurInit = S.BuildCXXConstructExpr(Loc, T, Best->FoundDecl, Constructor, 6351 Elidable, 6352 ConstructorArgs, 6353 HadMultipleCandidates, 6354 /*ListInit*/ false, 6355 /*StdInitListInit*/ false, 6356 /*ZeroInit*/ false, 6357 CXXConstructExpr::CK_Complete, 6358 SourceRange()); 6359 6360 // If we're supposed to bind temporaries, do so. 6361 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity)) 6362 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>()); 6363 return CurInit; 6364 } 6365 6366 /// Check whether elidable copy construction for binding a reference to 6367 /// a temporary would have succeeded if we were building in C++98 mode, for 6368 /// -Wc++98-compat. 6369 static void CheckCXX98CompatAccessibleCopy(Sema &S, 6370 const InitializedEntity &Entity, 6371 Expr *CurInitExpr) { 6372 assert(S.getLangOpts().CPlusPlus11); 6373 6374 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>(); 6375 if (!Record) 6376 return; 6377 6378 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr); 6379 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc)) 6380 return; 6381 6382 // Find constructors which would have been considered. 6383 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 6384 DeclContext::lookup_result Ctors = 6385 S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl())); 6386 6387 // Perform overload resolution. 6388 OverloadCandidateSet::iterator Best; 6389 OverloadingResult OR = ResolveConstructorOverload( 6390 S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best, 6391 /*CopyInitializing=*/false, /*AllowExplicit=*/true, 6392 /*OnlyListConstructors=*/false, /*IsListInit=*/false, 6393 /*SecondStepOfCopyInit=*/true); 6394 6395 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy) 6396 << OR << (int)Entity.getKind() << CurInitExpr->getType() 6397 << CurInitExpr->getSourceRange(); 6398 6399 switch (OR) { 6400 case OR_Success: 6401 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function), 6402 Best->FoundDecl, Entity, Diag); 6403 // FIXME: Check default arguments as far as that's possible. 6404 break; 6405 6406 case OR_No_Viable_Function: 6407 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, 6408 OCD_AllCandidates, CurInitExpr); 6409 break; 6410 6411 case OR_Ambiguous: 6412 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, 6413 OCD_AmbiguousCandidates, CurInitExpr); 6414 break; 6415 6416 case OR_Deleted: 6417 S.Diag(Loc, Diag); 6418 S.NoteDeletedFunction(Best->Function); 6419 break; 6420 } 6421 } 6422 6423 void InitializationSequence::PrintInitLocationNote(Sema &S, 6424 const InitializedEntity &Entity) { 6425 if (Entity.isParamOrTemplateParamKind() && Entity.getDecl()) { 6426 if (Entity.getDecl()->getLocation().isInvalid()) 6427 return; 6428 6429 if (Entity.getDecl()->getDeclName()) 6430 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here) 6431 << Entity.getDecl()->getDeclName(); 6432 else 6433 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here); 6434 } 6435 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult && 6436 Entity.getMethodDecl()) 6437 S.Diag(Entity.getMethodDecl()->getLocation(), 6438 diag::note_method_return_type_change) 6439 << Entity.getMethodDecl()->getDeclName(); 6440 } 6441 6442 /// Returns true if the parameters describe a constructor initialization of 6443 /// an explicit temporary object, e.g. "Point(x, y)". 6444 static bool isExplicitTemporary(const InitializedEntity &Entity, 6445 const InitializationKind &Kind, 6446 unsigned NumArgs) { 6447 switch (Entity.getKind()) { 6448 case InitializedEntity::EK_Temporary: 6449 case InitializedEntity::EK_CompoundLiteralInit: 6450 case InitializedEntity::EK_RelatedResult: 6451 break; 6452 default: 6453 return false; 6454 } 6455 6456 switch (Kind.getKind()) { 6457 case InitializationKind::IK_DirectList: 6458 return true; 6459 // FIXME: Hack to work around cast weirdness. 6460 case InitializationKind::IK_Direct: 6461 case InitializationKind::IK_Value: 6462 return NumArgs != 1; 6463 default: 6464 return false; 6465 } 6466 } 6467 6468 static ExprResult 6469 PerformConstructorInitialization(Sema &S, 6470 const InitializedEntity &Entity, 6471 const InitializationKind &Kind, 6472 MultiExprArg Args, 6473 const InitializationSequence::Step& Step, 6474 bool &ConstructorInitRequiresZeroInit, 6475 bool IsListInitialization, 6476 bool IsStdInitListInitialization, 6477 SourceLocation LBraceLoc, 6478 SourceLocation RBraceLoc) { 6479 unsigned NumArgs = Args.size(); 6480 CXXConstructorDecl *Constructor 6481 = cast<CXXConstructorDecl>(Step.Function.Function); 6482 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates; 6483 6484 // Build a call to the selected constructor. 6485 SmallVector<Expr*, 8> ConstructorArgs; 6486 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid()) 6487 ? Kind.getEqualLoc() 6488 : Kind.getLocation(); 6489 6490 if (Kind.getKind() == InitializationKind::IK_Default) { 6491 // Force even a trivial, implicit default constructor to be 6492 // semantically checked. We do this explicitly because we don't build 6493 // the definition for completely trivial constructors. 6494 assert(Constructor->getParent() && "No parent class for constructor."); 6495 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 6496 Constructor->isTrivial() && !Constructor->isUsed(false)) { 6497 S.runWithSufficientStackSpace(Loc, [&] { 6498 S.DefineImplicitDefaultConstructor(Loc, Constructor); 6499 }); 6500 } 6501 } 6502 6503 ExprResult CurInit((Expr *)nullptr); 6504 6505 // C++ [over.match.copy]p1: 6506 // - When initializing a temporary to be bound to the first parameter 6507 // of a constructor that takes a reference to possibly cv-qualified 6508 // T as its first argument, called with a single argument in the 6509 // context of direct-initialization, explicit conversion functions 6510 // are also considered. 6511 bool AllowExplicitConv = 6512 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 && 6513 hasCopyOrMoveCtorParam(S.Context, 6514 getConstructorInfo(Step.Function.FoundDecl)); 6515 6516 // Determine the arguments required to actually perform the constructor 6517 // call. 6518 if (S.CompleteConstructorCall(Constructor, Step.Type, Args, Loc, 6519 ConstructorArgs, AllowExplicitConv, 6520 IsListInitialization)) 6521 return ExprError(); 6522 6523 if (isExplicitTemporary(Entity, Kind, NumArgs)) { 6524 // An explicitly-constructed temporary, e.g., X(1, 2). 6525 if (S.DiagnoseUseOfDecl(Constructor, Loc)) 6526 return ExprError(); 6527 6528 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo(); 6529 if (!TSInfo) 6530 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc); 6531 SourceRange ParenOrBraceRange = 6532 (Kind.getKind() == InitializationKind::IK_DirectList) 6533 ? SourceRange(LBraceLoc, RBraceLoc) 6534 : Kind.getParenOrBraceRange(); 6535 6536 CXXConstructorDecl *CalleeDecl = Constructor; 6537 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>( 6538 Step.Function.FoundDecl.getDecl())) { 6539 CalleeDecl = S.findInheritingConstructor(Loc, Constructor, Shadow); 6540 if (S.DiagnoseUseOfDecl(CalleeDecl, Loc)) 6541 return ExprError(); 6542 } 6543 S.MarkFunctionReferenced(Loc, CalleeDecl); 6544 6545 CurInit = S.CheckForImmediateInvocation( 6546 CXXTemporaryObjectExpr::Create( 6547 S.Context, CalleeDecl, 6548 Entity.getType().getNonLValueExprType(S.Context), TSInfo, 6549 ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates, 6550 IsListInitialization, IsStdInitListInitialization, 6551 ConstructorInitRequiresZeroInit), 6552 CalleeDecl); 6553 } else { 6554 CXXConstructExpr::ConstructionKind ConstructKind = 6555 CXXConstructExpr::CK_Complete; 6556 6557 if (Entity.getKind() == InitializedEntity::EK_Base) { 6558 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ? 6559 CXXConstructExpr::CK_VirtualBase : 6560 CXXConstructExpr::CK_NonVirtualBase; 6561 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) { 6562 ConstructKind = CXXConstructExpr::CK_Delegating; 6563 } 6564 6565 // Only get the parenthesis or brace range if it is a list initialization or 6566 // direct construction. 6567 SourceRange ParenOrBraceRange; 6568 if (IsListInitialization) 6569 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc); 6570 else if (Kind.getKind() == InitializationKind::IK_Direct) 6571 ParenOrBraceRange = Kind.getParenOrBraceRange(); 6572 6573 // If the entity allows NRVO, mark the construction as elidable 6574 // unconditionally. 6575 if (Entity.allowsNRVO()) 6576 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type, 6577 Step.Function.FoundDecl, 6578 Constructor, /*Elidable=*/true, 6579 ConstructorArgs, 6580 HadMultipleCandidates, 6581 IsListInitialization, 6582 IsStdInitListInitialization, 6583 ConstructorInitRequiresZeroInit, 6584 ConstructKind, 6585 ParenOrBraceRange); 6586 else 6587 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type, 6588 Step.Function.FoundDecl, 6589 Constructor, 6590 ConstructorArgs, 6591 HadMultipleCandidates, 6592 IsListInitialization, 6593 IsStdInitListInitialization, 6594 ConstructorInitRequiresZeroInit, 6595 ConstructKind, 6596 ParenOrBraceRange); 6597 } 6598 if (CurInit.isInvalid()) 6599 return ExprError(); 6600 6601 // Only check access if all of that succeeded. 6602 S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity); 6603 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc)) 6604 return ExprError(); 6605 6606 if (const ArrayType *AT = S.Context.getAsArrayType(Entity.getType())) 6607 if (checkDestructorReference(S.Context.getBaseElementType(AT), Loc, S)) 6608 return ExprError(); 6609 6610 if (shouldBindAsTemporary(Entity)) 6611 CurInit = S.MaybeBindToTemporary(CurInit.get()); 6612 6613 return CurInit; 6614 } 6615 6616 namespace { 6617 enum LifetimeKind { 6618 /// The lifetime of a temporary bound to this entity ends at the end of the 6619 /// full-expression, and that's (probably) fine. 6620 LK_FullExpression, 6621 6622 /// The lifetime of a temporary bound to this entity is extended to the 6623 /// lifeitme of the entity itself. 6624 LK_Extended, 6625 6626 /// The lifetime of a temporary bound to this entity probably ends too soon, 6627 /// because the entity is allocated in a new-expression. 6628 LK_New, 6629 6630 /// The lifetime of a temporary bound to this entity ends too soon, because 6631 /// the entity is a return object. 6632 LK_Return, 6633 6634 /// The lifetime of a temporary bound to this entity ends too soon, because 6635 /// the entity is the result of a statement expression. 6636 LK_StmtExprResult, 6637 6638 /// This is a mem-initializer: if it would extend a temporary (other than via 6639 /// a default member initializer), the program is ill-formed. 6640 LK_MemInitializer, 6641 }; 6642 using LifetimeResult = 6643 llvm::PointerIntPair<const InitializedEntity *, 3, LifetimeKind>; 6644 } 6645 6646 /// Determine the declaration which an initialized entity ultimately refers to, 6647 /// for the purpose of lifetime-extending a temporary bound to a reference in 6648 /// the initialization of \p Entity. 6649 static LifetimeResult getEntityLifetime( 6650 const InitializedEntity *Entity, 6651 const InitializedEntity *InitField = nullptr) { 6652 // C++11 [class.temporary]p5: 6653 switch (Entity->getKind()) { 6654 case InitializedEntity::EK_Variable: 6655 // The temporary [...] persists for the lifetime of the reference 6656 return {Entity, LK_Extended}; 6657 6658 case InitializedEntity::EK_Member: 6659 // For subobjects, we look at the complete object. 6660 if (Entity->getParent()) 6661 return getEntityLifetime(Entity->getParent(), Entity); 6662 6663 // except: 6664 // C++17 [class.base.init]p8: 6665 // A temporary expression bound to a reference member in a 6666 // mem-initializer is ill-formed. 6667 // C++17 [class.base.init]p11: 6668 // A temporary expression bound to a reference member from a 6669 // default member initializer is ill-formed. 6670 // 6671 // The context of p11 and its example suggest that it's only the use of a 6672 // default member initializer from a constructor that makes the program 6673 // ill-formed, not its mere existence, and that it can even be used by 6674 // aggregate initialization. 6675 return {Entity, Entity->isDefaultMemberInitializer() ? LK_Extended 6676 : LK_MemInitializer}; 6677 6678 case InitializedEntity::EK_Binding: 6679 // Per [dcl.decomp]p3, the binding is treated as a variable of reference 6680 // type. 6681 return {Entity, LK_Extended}; 6682 6683 case InitializedEntity::EK_Parameter: 6684 case InitializedEntity::EK_Parameter_CF_Audited: 6685 // -- A temporary bound to a reference parameter in a function call 6686 // persists until the completion of the full-expression containing 6687 // the call. 6688 return {nullptr, LK_FullExpression}; 6689 6690 case InitializedEntity::EK_TemplateParameter: 6691 // FIXME: This will always be ill-formed; should we eagerly diagnose it here? 6692 return {nullptr, LK_FullExpression}; 6693 6694 case InitializedEntity::EK_Result: 6695 // -- The lifetime of a temporary bound to the returned value in a 6696 // function return statement is not extended; the temporary is 6697 // destroyed at the end of the full-expression in the return statement. 6698 return {nullptr, LK_Return}; 6699 6700 case InitializedEntity::EK_StmtExprResult: 6701 // FIXME: Should we lifetime-extend through the result of a statement 6702 // expression? 6703 return {nullptr, LK_StmtExprResult}; 6704 6705 case InitializedEntity::EK_New: 6706 // -- A temporary bound to a reference in a new-initializer persists 6707 // until the completion of the full-expression containing the 6708 // new-initializer. 6709 return {nullptr, LK_New}; 6710 6711 case InitializedEntity::EK_Temporary: 6712 case InitializedEntity::EK_CompoundLiteralInit: 6713 case InitializedEntity::EK_RelatedResult: 6714 // We don't yet know the storage duration of the surrounding temporary. 6715 // Assume it's got full-expression duration for now, it will patch up our 6716 // storage duration if that's not correct. 6717 return {nullptr, LK_FullExpression}; 6718 6719 case InitializedEntity::EK_ArrayElement: 6720 // For subobjects, we look at the complete object. 6721 return getEntityLifetime(Entity->getParent(), InitField); 6722 6723 case InitializedEntity::EK_Base: 6724 // For subobjects, we look at the complete object. 6725 if (Entity->getParent()) 6726 return getEntityLifetime(Entity->getParent(), InitField); 6727 return {InitField, LK_MemInitializer}; 6728 6729 case InitializedEntity::EK_Delegating: 6730 // We can reach this case for aggregate initialization in a constructor: 6731 // struct A { int &&r; }; 6732 // struct B : A { B() : A{0} {} }; 6733 // In this case, use the outermost field decl as the context. 6734 return {InitField, LK_MemInitializer}; 6735 6736 case InitializedEntity::EK_BlockElement: 6737 case InitializedEntity::EK_LambdaToBlockConversionBlockElement: 6738 case InitializedEntity::EK_LambdaCapture: 6739 case InitializedEntity::EK_VectorElement: 6740 case InitializedEntity::EK_ComplexElement: 6741 return {nullptr, LK_FullExpression}; 6742 6743 case InitializedEntity::EK_Exception: 6744 // FIXME: Can we diagnose lifetime problems with exceptions? 6745 return {nullptr, LK_FullExpression}; 6746 } 6747 llvm_unreachable("unknown entity kind"); 6748 } 6749 6750 namespace { 6751 enum ReferenceKind { 6752 /// Lifetime would be extended by a reference binding to a temporary. 6753 RK_ReferenceBinding, 6754 /// Lifetime would be extended by a std::initializer_list object binding to 6755 /// its backing array. 6756 RK_StdInitializerList, 6757 }; 6758 6759 /// A temporary or local variable. This will be one of: 6760 /// * A MaterializeTemporaryExpr. 6761 /// * A DeclRefExpr whose declaration is a local. 6762 /// * An AddrLabelExpr. 6763 /// * A BlockExpr for a block with captures. 6764 using Local = Expr*; 6765 6766 /// Expressions we stepped over when looking for the local state. Any steps 6767 /// that would inhibit lifetime extension or take us out of subexpressions of 6768 /// the initializer are included. 6769 struct IndirectLocalPathEntry { 6770 enum EntryKind { 6771 DefaultInit, 6772 AddressOf, 6773 VarInit, 6774 LValToRVal, 6775 LifetimeBoundCall, 6776 TemporaryCopy, 6777 LambdaCaptureInit, 6778 GslReferenceInit, 6779 GslPointerInit 6780 } Kind; 6781 Expr *E; 6782 union { 6783 const Decl *D = nullptr; 6784 const LambdaCapture *Capture; 6785 }; 6786 IndirectLocalPathEntry() {} 6787 IndirectLocalPathEntry(EntryKind K, Expr *E) : Kind(K), E(E) {} 6788 IndirectLocalPathEntry(EntryKind K, Expr *E, const Decl *D) 6789 : Kind(K), E(E), D(D) {} 6790 IndirectLocalPathEntry(EntryKind K, Expr *E, const LambdaCapture *Capture) 6791 : Kind(K), E(E), Capture(Capture) {} 6792 }; 6793 6794 using IndirectLocalPath = llvm::SmallVectorImpl<IndirectLocalPathEntry>; 6795 6796 struct RevertToOldSizeRAII { 6797 IndirectLocalPath &Path; 6798 unsigned OldSize = Path.size(); 6799 RevertToOldSizeRAII(IndirectLocalPath &Path) : Path(Path) {} 6800 ~RevertToOldSizeRAII() { Path.resize(OldSize); } 6801 }; 6802 6803 using LocalVisitor = llvm::function_ref<bool(IndirectLocalPath &Path, Local L, 6804 ReferenceKind RK)>; 6805 } 6806 6807 static bool isVarOnPath(IndirectLocalPath &Path, VarDecl *VD) { 6808 for (auto E : Path) 6809 if (E.Kind == IndirectLocalPathEntry::VarInit && E.D == VD) 6810 return true; 6811 return false; 6812 } 6813 6814 static bool pathContainsInit(IndirectLocalPath &Path) { 6815 return llvm::any_of(Path, [=](IndirectLocalPathEntry E) { 6816 return E.Kind == IndirectLocalPathEntry::DefaultInit || 6817 E.Kind == IndirectLocalPathEntry::VarInit; 6818 }); 6819 } 6820 6821 static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path, 6822 Expr *Init, LocalVisitor Visit, 6823 bool RevisitSubinits, 6824 bool EnableLifetimeWarnings); 6825 6826 static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path, 6827 Expr *Init, ReferenceKind RK, 6828 LocalVisitor Visit, 6829 bool EnableLifetimeWarnings); 6830 6831 template <typename T> static bool isRecordWithAttr(QualType Type) { 6832 if (auto *RD = Type->getAsCXXRecordDecl()) 6833 return RD->hasAttr<T>(); 6834 return false; 6835 } 6836 6837 // Decl::isInStdNamespace will return false for iterators in some STL 6838 // implementations due to them being defined in a namespace outside of the std 6839 // namespace. 6840 static bool isInStlNamespace(const Decl *D) { 6841 const DeclContext *DC = D->getDeclContext(); 6842 if (!DC) 6843 return false; 6844 if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) 6845 if (const IdentifierInfo *II = ND->getIdentifier()) { 6846 StringRef Name = II->getName(); 6847 if (Name.size() >= 2 && Name.front() == '_' && 6848 (Name[1] == '_' || isUppercase(Name[1]))) 6849 return true; 6850 } 6851 6852 return DC->isStdNamespace(); 6853 } 6854 6855 static bool shouldTrackImplicitObjectArg(const CXXMethodDecl *Callee) { 6856 if (auto *Conv = dyn_cast_or_null<CXXConversionDecl>(Callee)) 6857 if (isRecordWithAttr<PointerAttr>(Conv->getConversionType())) 6858 return true; 6859 if (!isInStlNamespace(Callee->getParent())) 6860 return false; 6861 if (!isRecordWithAttr<PointerAttr>(Callee->getThisObjectType()) && 6862 !isRecordWithAttr<OwnerAttr>(Callee->getThisObjectType())) 6863 return false; 6864 if (Callee->getReturnType()->isPointerType() || 6865 isRecordWithAttr<PointerAttr>(Callee->getReturnType())) { 6866 if (!Callee->getIdentifier()) 6867 return false; 6868 return llvm::StringSwitch<bool>(Callee->getName()) 6869 .Cases("begin", "rbegin", "cbegin", "crbegin", true) 6870 .Cases("end", "rend", "cend", "crend", true) 6871 .Cases("c_str", "data", "get", true) 6872 // Map and set types. 6873 .Cases("find", "equal_range", "lower_bound", "upper_bound", true) 6874 .Default(false); 6875 } else if (Callee->getReturnType()->isReferenceType()) { 6876 if (!Callee->getIdentifier()) { 6877 auto OO = Callee->getOverloadedOperator(); 6878 return OO == OverloadedOperatorKind::OO_Subscript || 6879 OO == OverloadedOperatorKind::OO_Star; 6880 } 6881 return llvm::StringSwitch<bool>(Callee->getName()) 6882 .Cases("front", "back", "at", "top", "value", true) 6883 .Default(false); 6884 } 6885 return false; 6886 } 6887 6888 static bool shouldTrackFirstArgument(const FunctionDecl *FD) { 6889 if (!FD->getIdentifier() || FD->getNumParams() != 1) 6890 return false; 6891 const auto *RD = FD->getParamDecl(0)->getType()->getPointeeCXXRecordDecl(); 6892 if (!FD->isInStdNamespace() || !RD || !RD->isInStdNamespace()) 6893 return false; 6894 if (!isRecordWithAttr<PointerAttr>(QualType(RD->getTypeForDecl(), 0)) && 6895 !isRecordWithAttr<OwnerAttr>(QualType(RD->getTypeForDecl(), 0))) 6896 return false; 6897 if (FD->getReturnType()->isPointerType() || 6898 isRecordWithAttr<PointerAttr>(FD->getReturnType())) { 6899 return llvm::StringSwitch<bool>(FD->getName()) 6900 .Cases("begin", "rbegin", "cbegin", "crbegin", true) 6901 .Cases("end", "rend", "cend", "crend", true) 6902 .Case("data", true) 6903 .Default(false); 6904 } else if (FD->getReturnType()->isReferenceType()) { 6905 return llvm::StringSwitch<bool>(FD->getName()) 6906 .Cases("get", "any_cast", true) 6907 .Default(false); 6908 } 6909 return false; 6910 } 6911 6912 static void handleGslAnnotatedTypes(IndirectLocalPath &Path, Expr *Call, 6913 LocalVisitor Visit) { 6914 auto VisitPointerArg = [&](const Decl *D, Expr *Arg, bool Value) { 6915 // We are not interested in the temporary base objects of gsl Pointers: 6916 // Temp().ptr; // Here ptr might not dangle. 6917 if (isa<MemberExpr>(Arg->IgnoreImpCasts())) 6918 return; 6919 // Once we initialized a value with a reference, it can no longer dangle. 6920 if (!Value) { 6921 for (auto It = Path.rbegin(), End = Path.rend(); It != End; ++It) { 6922 if (It->Kind == IndirectLocalPathEntry::GslReferenceInit) 6923 continue; 6924 if (It->Kind == IndirectLocalPathEntry::GslPointerInit) 6925 return; 6926 break; 6927 } 6928 } 6929 Path.push_back({Value ? IndirectLocalPathEntry::GslPointerInit 6930 : IndirectLocalPathEntry::GslReferenceInit, 6931 Arg, D}); 6932 if (Arg->isGLValue()) 6933 visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding, 6934 Visit, 6935 /*EnableLifetimeWarnings=*/true); 6936 else 6937 visitLocalsRetainedByInitializer(Path, Arg, Visit, true, 6938 /*EnableLifetimeWarnings=*/true); 6939 Path.pop_back(); 6940 }; 6941 6942 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) { 6943 const auto *MD = cast_or_null<CXXMethodDecl>(MCE->getDirectCallee()); 6944 if (MD && shouldTrackImplicitObjectArg(MD)) 6945 VisitPointerArg(MD, MCE->getImplicitObjectArgument(), 6946 !MD->getReturnType()->isReferenceType()); 6947 return; 6948 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(Call)) { 6949 FunctionDecl *Callee = OCE->getDirectCallee(); 6950 if (Callee && Callee->isCXXInstanceMember() && 6951 shouldTrackImplicitObjectArg(cast<CXXMethodDecl>(Callee))) 6952 VisitPointerArg(Callee, OCE->getArg(0), 6953 !Callee->getReturnType()->isReferenceType()); 6954 return; 6955 } else if (auto *CE = dyn_cast<CallExpr>(Call)) { 6956 FunctionDecl *Callee = CE->getDirectCallee(); 6957 if (Callee && shouldTrackFirstArgument(Callee)) 6958 VisitPointerArg(Callee, CE->getArg(0), 6959 !Callee->getReturnType()->isReferenceType()); 6960 return; 6961 } 6962 6963 if (auto *CCE = dyn_cast<CXXConstructExpr>(Call)) { 6964 const auto *Ctor = CCE->getConstructor(); 6965 const CXXRecordDecl *RD = Ctor->getParent(); 6966 if (CCE->getNumArgs() > 0 && RD->hasAttr<PointerAttr>()) 6967 VisitPointerArg(Ctor->getParamDecl(0), CCE->getArgs()[0], true); 6968 } 6969 } 6970 6971 static bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD) { 6972 const TypeSourceInfo *TSI = FD->getTypeSourceInfo(); 6973 if (!TSI) 6974 return false; 6975 // Don't declare this variable in the second operand of the for-statement; 6976 // GCC miscompiles that by ending its lifetime before evaluating the 6977 // third operand. See gcc.gnu.org/PR86769. 6978 AttributedTypeLoc ATL; 6979 for (TypeLoc TL = TSI->getTypeLoc(); 6980 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6981 TL = ATL.getModifiedLoc()) { 6982 if (ATL.getAttrAs<LifetimeBoundAttr>()) 6983 return true; 6984 } 6985 6986 // Assume that all assignment operators with a "normal" return type return 6987 // *this, that is, an lvalue reference that is the same type as the implicit 6988 // object parameter (or the LHS for a non-member operator$=). 6989 OverloadedOperatorKind OO = FD->getDeclName().getCXXOverloadedOperator(); 6990 if (OO == OO_Equal || isCompoundAssignmentOperator(OO)) { 6991 QualType RetT = FD->getReturnType(); 6992 if (RetT->isLValueReferenceType()) { 6993 ASTContext &Ctx = FD->getASTContext(); 6994 QualType LHST; 6995 auto *MD = dyn_cast<CXXMethodDecl>(FD); 6996 if (MD && MD->isCXXInstanceMember()) 6997 LHST = Ctx.getLValueReferenceType(MD->getThisObjectType()); 6998 else 6999 LHST = MD->getParamDecl(0)->getType(); 7000 if (Ctx.hasSameType(RetT, LHST)) 7001 return true; 7002 } 7003 } 7004 7005 return false; 7006 } 7007 7008 static void visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call, 7009 LocalVisitor Visit) { 7010 const FunctionDecl *Callee; 7011 ArrayRef<Expr*> Args; 7012 7013 if (auto *CE = dyn_cast<CallExpr>(Call)) { 7014 Callee = CE->getDirectCallee(); 7015 Args = llvm::makeArrayRef(CE->getArgs(), CE->getNumArgs()); 7016 } else { 7017 auto *CCE = cast<CXXConstructExpr>(Call); 7018 Callee = CCE->getConstructor(); 7019 Args = llvm::makeArrayRef(CCE->getArgs(), CCE->getNumArgs()); 7020 } 7021 if (!Callee) 7022 return; 7023 7024 Expr *ObjectArg = nullptr; 7025 if (isa<CXXOperatorCallExpr>(Call) && Callee->isCXXInstanceMember()) { 7026 ObjectArg = Args[0]; 7027 Args = Args.slice(1); 7028 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) { 7029 ObjectArg = MCE->getImplicitObjectArgument(); 7030 } 7031 7032 auto VisitLifetimeBoundArg = [&](const Decl *D, Expr *Arg) { 7033 Path.push_back({IndirectLocalPathEntry::LifetimeBoundCall, Arg, D}); 7034 if (Arg->isGLValue()) 7035 visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding, 7036 Visit, 7037 /*EnableLifetimeWarnings=*/false); 7038 else 7039 visitLocalsRetainedByInitializer(Path, Arg, Visit, true, 7040 /*EnableLifetimeWarnings=*/false); 7041 Path.pop_back(); 7042 }; 7043 7044 if (ObjectArg && implicitObjectParamIsLifetimeBound(Callee)) 7045 VisitLifetimeBoundArg(Callee, ObjectArg); 7046 7047 for (unsigned I = 0, 7048 N = std::min<unsigned>(Callee->getNumParams(), Args.size()); 7049 I != N; ++I) { 7050 if (Callee->getParamDecl(I)->hasAttr<LifetimeBoundAttr>()) 7051 VisitLifetimeBoundArg(Callee->getParamDecl(I), Args[I]); 7052 } 7053 } 7054 7055 /// Visit the locals that would be reachable through a reference bound to the 7056 /// glvalue expression \c Init. 7057 static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path, 7058 Expr *Init, ReferenceKind RK, 7059 LocalVisitor Visit, 7060 bool EnableLifetimeWarnings) { 7061 RevertToOldSizeRAII RAII(Path); 7062 7063 // Walk past any constructs which we can lifetime-extend across. 7064 Expr *Old; 7065 do { 7066 Old = Init; 7067 7068 if (auto *FE = dyn_cast<FullExpr>(Init)) 7069 Init = FE->getSubExpr(); 7070 7071 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) { 7072 // If this is just redundant braces around an initializer, step over it. 7073 if (ILE->isTransparent()) 7074 Init = ILE->getInit(0); 7075 } 7076 7077 // Step over any subobject adjustments; we may have a materialized 7078 // temporary inside them. 7079 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments()); 7080 7081 // Per current approach for DR1376, look through casts to reference type 7082 // when performing lifetime extension. 7083 if (CastExpr *CE = dyn_cast<CastExpr>(Init)) 7084 if (CE->getSubExpr()->isGLValue()) 7085 Init = CE->getSubExpr(); 7086 7087 // Per the current approach for DR1299, look through array element access 7088 // on array glvalues when performing lifetime extension. 7089 if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init)) { 7090 Init = ASE->getBase(); 7091 auto *ICE = dyn_cast<ImplicitCastExpr>(Init); 7092 if (ICE && ICE->getCastKind() == CK_ArrayToPointerDecay) 7093 Init = ICE->getSubExpr(); 7094 else 7095 // We can't lifetime extend through this but we might still find some 7096 // retained temporaries. 7097 return visitLocalsRetainedByInitializer(Path, Init, Visit, true, 7098 EnableLifetimeWarnings); 7099 } 7100 7101 // Step into CXXDefaultInitExprs so we can diagnose cases where a 7102 // constructor inherits one as an implicit mem-initializer. 7103 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) { 7104 Path.push_back( 7105 {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()}); 7106 Init = DIE->getExpr(); 7107 } 7108 } while (Init != Old); 7109 7110 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) { 7111 if (Visit(Path, Local(MTE), RK)) 7112 visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit, true, 7113 EnableLifetimeWarnings); 7114 } 7115 7116 if (isa<CallExpr>(Init)) { 7117 if (EnableLifetimeWarnings) 7118 handleGslAnnotatedTypes(Path, Init, Visit); 7119 return visitLifetimeBoundArguments(Path, Init, Visit); 7120 } 7121 7122 switch (Init->getStmtClass()) { 7123 case Stmt::DeclRefExprClass: { 7124 // If we find the name of a local non-reference parameter, we could have a 7125 // lifetime problem. 7126 auto *DRE = cast<DeclRefExpr>(Init); 7127 auto *VD = dyn_cast<VarDecl>(DRE->getDecl()); 7128 if (VD && VD->hasLocalStorage() && 7129 !DRE->refersToEnclosingVariableOrCapture()) { 7130 if (!VD->getType()->isReferenceType()) { 7131 Visit(Path, Local(DRE), RK); 7132 } else if (isa<ParmVarDecl>(DRE->getDecl())) { 7133 // The lifetime of a reference parameter is unknown; assume it's OK 7134 // for now. 7135 break; 7136 } else if (VD->getInit() && !isVarOnPath(Path, VD)) { 7137 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD}); 7138 visitLocalsRetainedByReferenceBinding(Path, VD->getInit(), 7139 RK_ReferenceBinding, Visit, 7140 EnableLifetimeWarnings); 7141 } 7142 } 7143 break; 7144 } 7145 7146 case Stmt::UnaryOperatorClass: { 7147 // The only unary operator that make sense to handle here 7148 // is Deref. All others don't resolve to a "name." This includes 7149 // handling all sorts of rvalues passed to a unary operator. 7150 const UnaryOperator *U = cast<UnaryOperator>(Init); 7151 if (U->getOpcode() == UO_Deref) 7152 visitLocalsRetainedByInitializer(Path, U->getSubExpr(), Visit, true, 7153 EnableLifetimeWarnings); 7154 break; 7155 } 7156 7157 case Stmt::OMPArraySectionExprClass: { 7158 visitLocalsRetainedByInitializer(Path, 7159 cast<OMPArraySectionExpr>(Init)->getBase(), 7160 Visit, true, EnableLifetimeWarnings); 7161 break; 7162 } 7163 7164 case Stmt::ConditionalOperatorClass: 7165 case Stmt::BinaryConditionalOperatorClass: { 7166 auto *C = cast<AbstractConditionalOperator>(Init); 7167 if (!C->getTrueExpr()->getType()->isVoidType()) 7168 visitLocalsRetainedByReferenceBinding(Path, C->getTrueExpr(), RK, Visit, 7169 EnableLifetimeWarnings); 7170 if (!C->getFalseExpr()->getType()->isVoidType()) 7171 visitLocalsRetainedByReferenceBinding(Path, C->getFalseExpr(), RK, Visit, 7172 EnableLifetimeWarnings); 7173 break; 7174 } 7175 7176 // FIXME: Visit the left-hand side of an -> or ->*. 7177 7178 default: 7179 break; 7180 } 7181 } 7182 7183 /// Visit the locals that would be reachable through an object initialized by 7184 /// the prvalue expression \c Init. 7185 static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path, 7186 Expr *Init, LocalVisitor Visit, 7187 bool RevisitSubinits, 7188 bool EnableLifetimeWarnings) { 7189 RevertToOldSizeRAII RAII(Path); 7190 7191 Expr *Old; 7192 do { 7193 Old = Init; 7194 7195 // Step into CXXDefaultInitExprs so we can diagnose cases where a 7196 // constructor inherits one as an implicit mem-initializer. 7197 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) { 7198 Path.push_back({IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()}); 7199 Init = DIE->getExpr(); 7200 } 7201 7202 if (auto *FE = dyn_cast<FullExpr>(Init)) 7203 Init = FE->getSubExpr(); 7204 7205 // Dig out the expression which constructs the extended temporary. 7206 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments()); 7207 7208 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init)) 7209 Init = BTE->getSubExpr(); 7210 7211 Init = Init->IgnoreParens(); 7212 7213 // Step over value-preserving rvalue casts. 7214 if (auto *CE = dyn_cast<CastExpr>(Init)) { 7215 switch (CE->getCastKind()) { 7216 case CK_LValueToRValue: 7217 // If we can match the lvalue to a const object, we can look at its 7218 // initializer. 7219 Path.push_back({IndirectLocalPathEntry::LValToRVal, CE}); 7220 return visitLocalsRetainedByReferenceBinding( 7221 Path, Init, RK_ReferenceBinding, 7222 [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool { 7223 if (auto *DRE = dyn_cast<DeclRefExpr>(L)) { 7224 auto *VD = dyn_cast<VarDecl>(DRE->getDecl()); 7225 if (VD && VD->getType().isConstQualified() && VD->getInit() && 7226 !isVarOnPath(Path, VD)) { 7227 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD}); 7228 visitLocalsRetainedByInitializer(Path, VD->getInit(), Visit, true, 7229 EnableLifetimeWarnings); 7230 } 7231 } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L)) { 7232 if (MTE->getType().isConstQualified()) 7233 visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit, 7234 true, EnableLifetimeWarnings); 7235 } 7236 return false; 7237 }, EnableLifetimeWarnings); 7238 7239 // We assume that objects can be retained by pointers cast to integers, 7240 // but not if the integer is cast to floating-point type or to _Complex. 7241 // We assume that casts to 'bool' do not preserve enough information to 7242 // retain a local object. 7243 case CK_NoOp: 7244 case CK_BitCast: 7245 case CK_BaseToDerived: 7246 case CK_DerivedToBase: 7247 case CK_UncheckedDerivedToBase: 7248 case CK_Dynamic: 7249 case CK_ToUnion: 7250 case CK_UserDefinedConversion: 7251 case CK_ConstructorConversion: 7252 case CK_IntegralToPointer: 7253 case CK_PointerToIntegral: 7254 case CK_VectorSplat: 7255 case CK_IntegralCast: 7256 case CK_CPointerToObjCPointerCast: 7257 case CK_BlockPointerToObjCPointerCast: 7258 case CK_AnyPointerToBlockPointerCast: 7259 case CK_AddressSpaceConversion: 7260 break; 7261 7262 case CK_ArrayToPointerDecay: 7263 // Model array-to-pointer decay as taking the address of the array 7264 // lvalue. 7265 Path.push_back({IndirectLocalPathEntry::AddressOf, CE}); 7266 return visitLocalsRetainedByReferenceBinding(Path, CE->getSubExpr(), 7267 RK_ReferenceBinding, Visit, 7268 EnableLifetimeWarnings); 7269 7270 default: 7271 return; 7272 } 7273 7274 Init = CE->getSubExpr(); 7275 } 7276 } while (Old != Init); 7277 7278 // C++17 [dcl.init.list]p6: 7279 // initializing an initializer_list object from the array extends the 7280 // lifetime of the array exactly like binding a reference to a temporary. 7281 if (auto *ILE = dyn_cast<CXXStdInitializerListExpr>(Init)) 7282 return visitLocalsRetainedByReferenceBinding(Path, ILE->getSubExpr(), 7283 RK_StdInitializerList, Visit, 7284 EnableLifetimeWarnings); 7285 7286 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) { 7287 // We already visited the elements of this initializer list while 7288 // performing the initialization. Don't visit them again unless we've 7289 // changed the lifetime of the initialized entity. 7290 if (!RevisitSubinits) 7291 return; 7292 7293 if (ILE->isTransparent()) 7294 return visitLocalsRetainedByInitializer(Path, ILE->getInit(0), Visit, 7295 RevisitSubinits, 7296 EnableLifetimeWarnings); 7297 7298 if (ILE->getType()->isArrayType()) { 7299 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I) 7300 visitLocalsRetainedByInitializer(Path, ILE->getInit(I), Visit, 7301 RevisitSubinits, 7302 EnableLifetimeWarnings); 7303 return; 7304 } 7305 7306 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) { 7307 assert(RD->isAggregate() && "aggregate init on non-aggregate"); 7308 7309 // If we lifetime-extend a braced initializer which is initializing an 7310 // aggregate, and that aggregate contains reference members which are 7311 // bound to temporaries, those temporaries are also lifetime-extended. 7312 if (RD->isUnion() && ILE->getInitializedFieldInUnion() && 7313 ILE->getInitializedFieldInUnion()->getType()->isReferenceType()) 7314 visitLocalsRetainedByReferenceBinding(Path, ILE->getInit(0), 7315 RK_ReferenceBinding, Visit, 7316 EnableLifetimeWarnings); 7317 else { 7318 unsigned Index = 0; 7319 for (; Index < RD->getNumBases() && Index < ILE->getNumInits(); ++Index) 7320 visitLocalsRetainedByInitializer(Path, ILE->getInit(Index), Visit, 7321 RevisitSubinits, 7322 EnableLifetimeWarnings); 7323 for (const auto *I : RD->fields()) { 7324 if (Index >= ILE->getNumInits()) 7325 break; 7326 if (I->isUnnamedBitfield()) 7327 continue; 7328 Expr *SubInit = ILE->getInit(Index); 7329 if (I->getType()->isReferenceType()) 7330 visitLocalsRetainedByReferenceBinding(Path, SubInit, 7331 RK_ReferenceBinding, Visit, 7332 EnableLifetimeWarnings); 7333 else 7334 // This might be either aggregate-initialization of a member or 7335 // initialization of a std::initializer_list object. Regardless, 7336 // we should recursively lifetime-extend that initializer. 7337 visitLocalsRetainedByInitializer(Path, SubInit, Visit, 7338 RevisitSubinits, 7339 EnableLifetimeWarnings); 7340 ++Index; 7341 } 7342 } 7343 } 7344 return; 7345 } 7346 7347 // The lifetime of an init-capture is that of the closure object constructed 7348 // by a lambda-expression. 7349 if (auto *LE = dyn_cast<LambdaExpr>(Init)) { 7350 LambdaExpr::capture_iterator CapI = LE->capture_begin(); 7351 for (Expr *E : LE->capture_inits()) { 7352 assert(CapI != LE->capture_end()); 7353 const LambdaCapture &Cap = *CapI++; 7354 if (!E) 7355 continue; 7356 if (Cap.capturesVariable()) 7357 Path.push_back({IndirectLocalPathEntry::LambdaCaptureInit, E, &Cap}); 7358 if (E->isGLValue()) 7359 visitLocalsRetainedByReferenceBinding(Path, E, RK_ReferenceBinding, 7360 Visit, EnableLifetimeWarnings); 7361 else 7362 visitLocalsRetainedByInitializer(Path, E, Visit, true, 7363 EnableLifetimeWarnings); 7364 if (Cap.capturesVariable()) 7365 Path.pop_back(); 7366 } 7367 } 7368 7369 // Assume that a copy or move from a temporary references the same objects 7370 // that the temporary does. 7371 if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) { 7372 if (CCE->getConstructor()->isCopyOrMoveConstructor()) { 7373 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(CCE->getArg(0))) { 7374 Expr *Arg = MTE->getSubExpr(); 7375 Path.push_back({IndirectLocalPathEntry::TemporaryCopy, Arg, 7376 CCE->getConstructor()}); 7377 visitLocalsRetainedByInitializer(Path, Arg, Visit, true, 7378 /*EnableLifetimeWarnings*/false); 7379 Path.pop_back(); 7380 } 7381 } 7382 } 7383 7384 if (isa<CallExpr>(Init) || isa<CXXConstructExpr>(Init)) { 7385 if (EnableLifetimeWarnings) 7386 handleGslAnnotatedTypes(Path, Init, Visit); 7387 return visitLifetimeBoundArguments(Path, Init, Visit); 7388 } 7389 7390 switch (Init->getStmtClass()) { 7391 case Stmt::UnaryOperatorClass: { 7392 auto *UO = cast<UnaryOperator>(Init); 7393 // If the initializer is the address of a local, we could have a lifetime 7394 // problem. 7395 if (UO->getOpcode() == UO_AddrOf) { 7396 // If this is &rvalue, then it's ill-formed and we have already diagnosed 7397 // it. Don't produce a redundant warning about the lifetime of the 7398 // temporary. 7399 if (isa<MaterializeTemporaryExpr>(UO->getSubExpr())) 7400 return; 7401 7402 Path.push_back({IndirectLocalPathEntry::AddressOf, UO}); 7403 visitLocalsRetainedByReferenceBinding(Path, UO->getSubExpr(), 7404 RK_ReferenceBinding, Visit, 7405 EnableLifetimeWarnings); 7406 } 7407 break; 7408 } 7409 7410 case Stmt::BinaryOperatorClass: { 7411 // Handle pointer arithmetic. 7412 auto *BO = cast<BinaryOperator>(Init); 7413 BinaryOperatorKind BOK = BO->getOpcode(); 7414 if (!BO->getType()->isPointerType() || (BOK != BO_Add && BOK != BO_Sub)) 7415 break; 7416 7417 if (BO->getLHS()->getType()->isPointerType()) 7418 visitLocalsRetainedByInitializer(Path, BO->getLHS(), Visit, true, 7419 EnableLifetimeWarnings); 7420 else if (BO->getRHS()->getType()->isPointerType()) 7421 visitLocalsRetainedByInitializer(Path, BO->getRHS(), Visit, true, 7422 EnableLifetimeWarnings); 7423 break; 7424 } 7425 7426 case Stmt::ConditionalOperatorClass: 7427 case Stmt::BinaryConditionalOperatorClass: { 7428 auto *C = cast<AbstractConditionalOperator>(Init); 7429 // In C++, we can have a throw-expression operand, which has 'void' type 7430 // and isn't interesting from a lifetime perspective. 7431 if (!C->getTrueExpr()->getType()->isVoidType()) 7432 visitLocalsRetainedByInitializer(Path, C->getTrueExpr(), Visit, true, 7433 EnableLifetimeWarnings); 7434 if (!C->getFalseExpr()->getType()->isVoidType()) 7435 visitLocalsRetainedByInitializer(Path, C->getFalseExpr(), Visit, true, 7436 EnableLifetimeWarnings); 7437 break; 7438 } 7439 7440 case Stmt::BlockExprClass: 7441 if (cast<BlockExpr>(Init)->getBlockDecl()->hasCaptures()) { 7442 // This is a local block, whose lifetime is that of the function. 7443 Visit(Path, Local(cast<BlockExpr>(Init)), RK_ReferenceBinding); 7444 } 7445 break; 7446 7447 case Stmt::AddrLabelExprClass: 7448 // We want to warn if the address of a label would escape the function. 7449 Visit(Path, Local(cast<AddrLabelExpr>(Init)), RK_ReferenceBinding); 7450 break; 7451 7452 default: 7453 break; 7454 } 7455 } 7456 7457 /// Whether a path to an object supports lifetime extension. 7458 enum PathLifetimeKind { 7459 /// Lifetime-extend along this path. 7460 Extend, 7461 /// We should lifetime-extend, but we don't because (due to technical 7462 /// limitations) we can't. This happens for default member initializers, 7463 /// which we don't clone for every use, so we don't have a unique 7464 /// MaterializeTemporaryExpr to update. 7465 ShouldExtend, 7466 /// Do not lifetime extend along this path. 7467 NoExtend 7468 }; 7469 7470 /// Determine whether this is an indirect path to a temporary that we are 7471 /// supposed to lifetime-extend along. 7472 static PathLifetimeKind 7473 shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path) { 7474 PathLifetimeKind Kind = PathLifetimeKind::Extend; 7475 for (auto Elem : Path) { 7476 if (Elem.Kind == IndirectLocalPathEntry::DefaultInit) 7477 Kind = PathLifetimeKind::ShouldExtend; 7478 else if (Elem.Kind != IndirectLocalPathEntry::LambdaCaptureInit) 7479 return PathLifetimeKind::NoExtend; 7480 } 7481 return Kind; 7482 } 7483 7484 /// Find the range for the first interesting entry in the path at or after I. 7485 static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I, 7486 Expr *E) { 7487 for (unsigned N = Path.size(); I != N; ++I) { 7488 switch (Path[I].Kind) { 7489 case IndirectLocalPathEntry::AddressOf: 7490 case IndirectLocalPathEntry::LValToRVal: 7491 case IndirectLocalPathEntry::LifetimeBoundCall: 7492 case IndirectLocalPathEntry::TemporaryCopy: 7493 case IndirectLocalPathEntry::GslReferenceInit: 7494 case IndirectLocalPathEntry::GslPointerInit: 7495 // These exist primarily to mark the path as not permitting or 7496 // supporting lifetime extension. 7497 break; 7498 7499 case IndirectLocalPathEntry::VarInit: 7500 if (cast<VarDecl>(Path[I].D)->isImplicit()) 7501 return SourceRange(); 7502 LLVM_FALLTHROUGH; 7503 case IndirectLocalPathEntry::DefaultInit: 7504 return Path[I].E->getSourceRange(); 7505 7506 case IndirectLocalPathEntry::LambdaCaptureInit: 7507 if (!Path[I].Capture->capturesVariable()) 7508 continue; 7509 return Path[I].E->getSourceRange(); 7510 } 7511 } 7512 return E->getSourceRange(); 7513 } 7514 7515 static bool pathOnlyInitializesGslPointer(IndirectLocalPath &Path) { 7516 for (auto It = Path.rbegin(), End = Path.rend(); It != End; ++It) { 7517 if (It->Kind == IndirectLocalPathEntry::VarInit) 7518 continue; 7519 if (It->Kind == IndirectLocalPathEntry::AddressOf) 7520 continue; 7521 if (It->Kind == IndirectLocalPathEntry::LifetimeBoundCall) 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, Step->Type, 8300 MultiExprArg(&Arg, 1), Loc, 8301 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().isAvailableOption( 8797 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts())) 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