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