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