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