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