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