SemaInit.cpp revision cfdc81a83467973b14e4ea5e9e9af1690f135415
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. The main entry 11// point is Sema::CheckInitList(), but all of the work is performed 12// within the InitListChecker class. 13// 14// This file also implements Sema::CheckInitializerTypes. 15// 16//===----------------------------------------------------------------------===// 17 18#include "SemaInit.h" 19#include "Sema.h" 20#include "clang/Parse/Designator.h" 21#include "clang/AST/ASTContext.h" 22#include "clang/AST/ExprCXX.h" 23#include "clang/AST/ExprObjC.h" 24#include "llvm/Support/ErrorHandling.h" 25#include <map> 26using namespace clang; 27 28//===----------------------------------------------------------------------===// 29// Sema Initialization Checking 30//===----------------------------------------------------------------------===// 31 32static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) { 33 const ArrayType *AT = Context.getAsArrayType(DeclType); 34 if (!AT) return 0; 35 36 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT)) 37 return 0; 38 39 // See if this is a string literal or @encode. 40 Init = Init->IgnoreParens(); 41 42 // Handle @encode, which is a narrow string. 43 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType()) 44 return Init; 45 46 // Otherwise we can only handle string literals. 47 StringLiteral *SL = dyn_cast<StringLiteral>(Init); 48 if (SL == 0) return 0; 49 50 QualType ElemTy = Context.getCanonicalType(AT->getElementType()); 51 // char array can be initialized with a narrow string. 52 // Only allow char x[] = "foo"; not char x[] = L"foo"; 53 if (!SL->isWide()) 54 return ElemTy->isCharType() ? Init : 0; 55 56 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with 57 // correction from DR343): "An array with element type compatible with a 58 // qualified or unqualified version of wchar_t may be initialized by a wide 59 // string literal, optionally enclosed in braces." 60 if (Context.typesAreCompatible(Context.getWCharType(), 61 ElemTy.getUnqualifiedType())) 62 return Init; 63 64 return 0; 65} 66 67static bool CheckSingleInitializer(Expr *&Init, QualType DeclType, 68 bool DirectInit, Sema &S) { 69 // Get the type before calling CheckSingleAssignmentConstraints(), since 70 // it can promote the expression. 71 QualType InitType = Init->getType(); 72 73 if (S.getLangOptions().CPlusPlus) { 74 // FIXME: I dislike this error message. A lot. 75 if (S.PerformImplicitConversion(Init, DeclType, 76 Sema::AA_Initializing, DirectInit)) { 77 ImplicitConversionSequence ICS; 78 OverloadCandidateSet CandidateSet; 79 if (S.IsUserDefinedConversion(Init, DeclType, ICS.UserDefined, 80 CandidateSet, 81 true, false, false) != OR_Ambiguous) 82 return S.Diag(Init->getSourceRange().getBegin(), 83 diag::err_typecheck_convert_incompatible) 84 << DeclType << Init->getType() << Sema::AA_Initializing 85 << Init->getSourceRange(); 86 S.Diag(Init->getSourceRange().getBegin(), 87 diag::err_typecheck_convert_ambiguous) 88 << DeclType << Init->getType() << Init->getSourceRange(); 89 S.PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 90 return true; 91 } 92 return false; 93 } 94 95 Sema::AssignConvertType ConvTy = 96 S.CheckSingleAssignmentConstraints(DeclType, Init); 97 return S.DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType, 98 InitType, Init, Sema::AA_Initializing); 99} 100 101static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) { 102 // Get the length of the string as parsed. 103 uint64_t StrLength = 104 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue(); 105 106 107 const ArrayType *AT = S.Context.getAsArrayType(DeclT); 108 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) { 109 // C99 6.7.8p14. We have an array of character type with unknown size 110 // being initialized to a string literal. 111 llvm::APSInt ConstVal(32); 112 ConstVal = StrLength; 113 // Return a new array type (C99 6.7.8p22). 114 DeclT = S.Context.getConstantArrayType(IAT->getElementType(), 115 ConstVal, 116 ArrayType::Normal, 0); 117 return; 118 } 119 120 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT); 121 122 // C99 6.7.8p14. We have an array of character type with known size. However, 123 // the size may be smaller or larger than the string we are initializing. 124 // FIXME: Avoid truncation for 64-bit length strings. 125 if (StrLength-1 > CAT->getSize().getZExtValue()) 126 S.Diag(Str->getSourceRange().getBegin(), 127 diag::warn_initializer_string_for_char_array_too_long) 128 << Str->getSourceRange(); 129 130 // Set the type to the actual size that we are initializing. If we have 131 // something like: 132 // char x[1] = "foo"; 133 // then this will set the string literal's type to char[1]. 134 Str->setType(DeclT); 135} 136 137bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType, 138 const InitializedEntity &Entity, 139 const InitializationKind &Kind) { 140 SourceLocation InitLoc = Kind.getLocation(); 141 DeclarationName InitEntity = Entity.getName(); 142 bool DirectInit = (Kind.getKind() == InitializationKind::IK_Direct); 143 144 if (DeclType->isDependentType() || 145 Init->isTypeDependent() || Init->isValueDependent()) { 146 // We have either a dependent type or a type- or value-dependent 147 // initializer, so we don't perform any additional checking at 148 // this point. 149 150 // If the declaration is a non-dependent, incomplete array type 151 // that has an initializer, then its type will be completed once 152 // the initializer is instantiated. 153 if (!DeclType->isDependentType()) { 154 if (const IncompleteArrayType *ArrayT 155 = Context.getAsIncompleteArrayType(DeclType)) { 156 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) { 157 if (!ILE->isTypeDependent()) { 158 // Compute the constant array type from the length of the 159 // initializer list. 160 // FIXME: This will be wrong if there are designated 161 // initializations. Good thing they don't exist in C++! 162 llvm::APInt NumElements(Context.getTypeSize(Context.getSizeType()), 163 ILE->getNumInits()); 164 llvm::APInt Zero(Context.getTypeSize(Context.getSizeType()), 0); 165 if (NumElements == Zero) { 166 // Sizing an array implicitly to zero is not allowed by ISO C, 167 // but is supported by GNU. 168 Diag(ILE->getLocStart(), diag::ext_typecheck_zero_array_size); 169 } 170 171 DeclType = Context.getConstantArrayType(ArrayT->getElementType(), 172 NumElements, 173 ArrayT->getSizeModifier(), 174 ArrayT->getIndexTypeCVRQualifiers()); 175 return false; 176 } 177 } 178 179 // Make the array type-dependent by making it dependently-sized. 180 DeclType = Context.getDependentSizedArrayType(ArrayT->getElementType(), 181 /*NumElts=*/0, 182 ArrayT->getSizeModifier(), 183 ArrayT->getIndexTypeCVRQualifiers(), 184 SourceRange()); 185 } 186 } 187 188 return false; 189 } 190 191 // C++ [dcl.init.ref]p1: 192 // A variable declared to be a T& or T&&, that is "reference to type T" 193 // (8.3.2), shall be initialized by an object, or function, of 194 // type T or by an object that can be converted into a T. 195 if (DeclType->isReferenceType()) { 196 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1); 197 OwningExprResult CurInit = InitSeq.Perform(*this, Entity, Kind, 198 MultiExprArg(*this, (void**)&Init, 1), 199 &DeclType); 200 if (CurInit.isInvalid()) 201 return true; 202 203 Init = CurInit.takeAs<Expr>(); 204 return false; 205 } 206 207 // C99 6.7.8p3: The type of the entity to be initialized shall be an array 208 // of unknown size ("[]") or an object type that is not a variable array type. 209 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType)) 210 return Diag(InitLoc, diag::err_variable_object_no_init) 211 << VAT->getSizeExpr()->getSourceRange(); 212 213 InitListExpr *InitList = dyn_cast<InitListExpr>(Init); 214 if (!InitList) { 215 // FIXME: Handle wide strings 216 if (Expr *Str = IsStringInit(Init, DeclType, Context)) { 217 CheckStringInit(Str, DeclType, *this); 218 return false; 219 } 220 221 // C++ [dcl.init]p14: 222 // -- If the destination type is a (possibly cv-qualified) class 223 // type: 224 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) { 225 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1); 226 OwningExprResult CurInit = InitSeq.Perform(*this, Entity, Kind, 227 MultiExprArg(*this, (void**)&Init, 1), 228 &DeclType); 229 if (CurInit.isInvalid()) 230 return true; 231 232 Init = CurInit.takeAs<Expr>(); 233 return false; 234 } 235 236 // C99 6.7.8p16. 237 if (DeclType->isArrayType()) 238 return Diag(Init->getLocStart(), diag::err_array_init_list_required) 239 << Init->getSourceRange(); 240 241 return CheckSingleInitializer(Init, DeclType, DirectInit, *this); 242 } 243 244 bool hadError = CheckInitList(Entity, InitList, DeclType); 245 Init = InitList; 246 return hadError; 247} 248 249//===----------------------------------------------------------------------===// 250// Semantic checking for initializer lists. 251//===----------------------------------------------------------------------===// 252 253/// @brief Semantic checking for initializer lists. 254/// 255/// The InitListChecker class contains a set of routines that each 256/// handle the initialization of a certain kind of entity, e.g., 257/// arrays, vectors, struct/union types, scalars, etc. The 258/// InitListChecker itself performs a recursive walk of the subobject 259/// structure of the type to be initialized, while stepping through 260/// the initializer list one element at a time. The IList and Index 261/// parameters to each of the Check* routines contain the active 262/// (syntactic) initializer list and the index into that initializer 263/// list that represents the current initializer. Each routine is 264/// responsible for moving that Index forward as it consumes elements. 265/// 266/// Each Check* routine also has a StructuredList/StructuredIndex 267/// arguments, which contains the current the "structured" (semantic) 268/// initializer list and the index into that initializer list where we 269/// are copying initializers as we map them over to the semantic 270/// list. Once we have completed our recursive walk of the subobject 271/// structure, we will have constructed a full semantic initializer 272/// list. 273/// 274/// C99 designators cause changes in the initializer list traversal, 275/// because they make the initialization "jump" into a specific 276/// subobject and then continue the initialization from that 277/// point. CheckDesignatedInitializer() recursively steps into the 278/// designated subobject and manages backing out the recursion to 279/// initialize the subobjects after the one designated. 280namespace { 281class InitListChecker { 282 Sema &SemaRef; 283 bool hadError; 284 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic; 285 InitListExpr *FullyStructuredList; 286 287 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T, 288 unsigned &Index, InitListExpr *StructuredList, 289 unsigned &StructuredIndex, 290 bool TopLevelObject = false); 291 void CheckExplicitInitList(InitListExpr *IList, QualType &T, 292 unsigned &Index, InitListExpr *StructuredList, 293 unsigned &StructuredIndex, 294 bool TopLevelObject = false); 295 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType, 296 bool SubobjectIsDesignatorContext, 297 unsigned &Index, 298 InitListExpr *StructuredList, 299 unsigned &StructuredIndex, 300 bool TopLevelObject = false); 301 void CheckSubElementType(InitListExpr *IList, QualType ElemType, 302 unsigned &Index, 303 InitListExpr *StructuredList, 304 unsigned &StructuredIndex); 305 void CheckScalarType(InitListExpr *IList, QualType DeclType, 306 unsigned &Index, 307 InitListExpr *StructuredList, 308 unsigned &StructuredIndex); 309 void CheckReferenceType(InitListExpr *IList, QualType DeclType, 310 unsigned &Index, 311 InitListExpr *StructuredList, 312 unsigned &StructuredIndex); 313 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index, 314 InitListExpr *StructuredList, 315 unsigned &StructuredIndex); 316 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType, 317 RecordDecl::field_iterator Field, 318 bool SubobjectIsDesignatorContext, unsigned &Index, 319 InitListExpr *StructuredList, 320 unsigned &StructuredIndex, 321 bool TopLevelObject = false); 322 void CheckArrayType(InitListExpr *IList, QualType &DeclType, 323 llvm::APSInt elementIndex, 324 bool SubobjectIsDesignatorContext, unsigned &Index, 325 InitListExpr *StructuredList, 326 unsigned &StructuredIndex); 327 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE, 328 unsigned DesigIdx, 329 QualType &CurrentObjectType, 330 RecordDecl::field_iterator *NextField, 331 llvm::APSInt *NextElementIndex, 332 unsigned &Index, 333 InitListExpr *StructuredList, 334 unsigned &StructuredIndex, 335 bool FinishSubobjectInit, 336 bool TopLevelObject); 337 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, 338 QualType CurrentObjectType, 339 InitListExpr *StructuredList, 340 unsigned StructuredIndex, 341 SourceRange InitRange); 342 void UpdateStructuredListElement(InitListExpr *StructuredList, 343 unsigned &StructuredIndex, 344 Expr *expr); 345 int numArrayElements(QualType DeclType); 346 int numStructUnionElements(QualType DeclType); 347 348 void FillInValueInitializations(const InitializedEntity &Entity, 349 InitListExpr *ILE, bool &RequiresSecondPass); 350public: 351 InitListChecker(Sema &S, const InitializedEntity &Entity, 352 InitListExpr *IL, QualType &T); 353 bool HadError() { return hadError; } 354 355 // @brief Retrieves the fully-structured initializer list used for 356 // semantic analysis and code generation. 357 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; } 358}; 359} // end anonymous namespace 360 361/// Recursively replaces NULL values within the given initializer list 362/// with expressions that perform value-initialization of the 363/// appropriate type. 364void 365InitListChecker::FillInValueInitializations(const InitializedEntity &Entity, 366 InitListExpr *ILE, 367 bool &RequiresSecondPass) { 368 assert((ILE->getType() != SemaRef.Context.VoidTy) && 369 "Should not have void type"); 370 SourceLocation Loc = ILE->getSourceRange().getBegin(); 371 if (ILE->getSyntacticForm()) 372 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin(); 373 374 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) { 375 unsigned Init = 0, NumInits = ILE->getNumInits(); 376 for (RecordDecl::field_iterator 377 Field = RType->getDecl()->field_begin(), 378 FieldEnd = RType->getDecl()->field_end(); 379 Field != FieldEnd; ++Field) { 380 if (Field->isUnnamedBitfield()) 381 continue; 382 383 if (hadError) 384 return; 385 386 InitializedEntity MemberEntity 387 = InitializedEntity::InitializeMember(*Field, &Entity); 388 if (Init >= NumInits || !ILE->getInit(Init)) { 389 // FIXME: We probably don't need to handle references 390 // specially here, since value-initialization of references is 391 // handled in InitializationSequence. 392 if (Field->getType()->isReferenceType()) { 393 // C++ [dcl.init.aggr]p9: 394 // If an incomplete or empty initializer-list leaves a 395 // member of reference type uninitialized, the program is 396 // ill-formed. 397 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized) 398 << Field->getType() 399 << ILE->getSyntacticForm()->getSourceRange(); 400 SemaRef.Diag(Field->getLocation(), 401 diag::note_uninit_reference_member); 402 hadError = true; 403 return; 404 } 405 406 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc, 407 true); 408 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0); 409 if (!InitSeq) { 410 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0); 411 hadError = true; 412 return; 413 } 414 415 Sema::OwningExprResult MemberInit 416 = InitSeq.Perform(SemaRef, MemberEntity, Kind, 417 Sema::MultiExprArg(SemaRef, 0, 0)); 418 if (MemberInit.isInvalid()) { 419 hadError = true; 420 return; 421 } 422 423 if (hadError) { 424 // Do nothing 425 } else if (Init < NumInits) { 426 ILE->setInit(Init, MemberInit.takeAs<Expr>()); 427 } else if (InitSeq.getKind() 428 == InitializationSequence::ConstructorInitialization) { 429 // Value-initialization requires a constructor call, so 430 // extend the initializer list to include the constructor 431 // call and make a note that we'll need to take another pass 432 // through the initializer list. 433 ILE->updateInit(Init, MemberInit.takeAs<Expr>()); 434 RequiresSecondPass = true; 435 } 436 } else if (InitListExpr *InnerILE 437 = dyn_cast<InitListExpr>(ILE->getInit(Init))) 438 FillInValueInitializations(MemberEntity, InnerILE, 439 RequiresSecondPass); 440 ++Init; 441 442 // Only look at the first initialization of a union. 443 if (RType->getDecl()->isUnion()) 444 break; 445 } 446 447 return; 448 } 449 450 QualType ElementType; 451 452 InitializedEntity ElementEntity = Entity; 453 unsigned NumInits = ILE->getNumInits(); 454 unsigned NumElements = NumInits; 455 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) { 456 ElementType = AType->getElementType(); 457 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) 458 NumElements = CAType->getSize().getZExtValue(); 459 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context, 460 0, Entity); 461 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) { 462 ElementType = VType->getElementType(); 463 NumElements = VType->getNumElements(); 464 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context, 465 0, Entity); 466 } else 467 ElementType = ILE->getType(); 468 469 470 for (unsigned Init = 0; Init != NumElements; ++Init) { 471 if (hadError) 472 return; 473 474 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayOrVectorElement) 475 ElementEntity.setElementIndex(Init); 476 477 if (Init >= NumInits || !ILE->getInit(Init)) { 478 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc, 479 true); 480 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0); 481 if (!InitSeq) { 482 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0); 483 hadError = true; 484 return; 485 } 486 487 Sema::OwningExprResult ElementInit 488 = InitSeq.Perform(SemaRef, ElementEntity, Kind, 489 Sema::MultiExprArg(SemaRef, 0, 0)); 490 if (ElementInit.isInvalid()) { 491 hadError = true; 492 return; 493 } 494 495 if (hadError) { 496 // Do nothing 497 } else if (Init < NumInits) { 498 ILE->setInit(Init, ElementInit.takeAs<Expr>()); 499 } else if (InitSeq.getKind() 500 == InitializationSequence::ConstructorInitialization) { 501 // Value-initialization requires a constructor call, so 502 // extend the initializer list to include the constructor 503 // call and make a note that we'll need to take another pass 504 // through the initializer list. 505 ILE->updateInit(Init, ElementInit.takeAs<Expr>()); 506 RequiresSecondPass = true; 507 } 508 } else if (InitListExpr *InnerILE 509 = dyn_cast<InitListExpr>(ILE->getInit(Init))) 510 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass); 511 } 512} 513 514 515InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity, 516 InitListExpr *IL, QualType &T) 517 : SemaRef(S) { 518 hadError = false; 519 520 unsigned newIndex = 0; 521 unsigned newStructuredIndex = 0; 522 FullyStructuredList 523 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange()); 524 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex, 525 /*TopLevelObject=*/true); 526 527 if (!hadError) { 528 bool RequiresSecondPass = false; 529 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass); 530 if (RequiresSecondPass && !hadError) 531 FillInValueInitializations(Entity, FullyStructuredList, 532 RequiresSecondPass); 533 } 534} 535 536int InitListChecker::numArrayElements(QualType DeclType) { 537 // FIXME: use a proper constant 538 int maxElements = 0x7FFFFFFF; 539 if (const ConstantArrayType *CAT = 540 SemaRef.Context.getAsConstantArrayType(DeclType)) { 541 maxElements = static_cast<int>(CAT->getSize().getZExtValue()); 542 } 543 return maxElements; 544} 545 546int InitListChecker::numStructUnionElements(QualType DeclType) { 547 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl(); 548 int InitializableMembers = 0; 549 for (RecordDecl::field_iterator 550 Field = structDecl->field_begin(), 551 FieldEnd = structDecl->field_end(); 552 Field != FieldEnd; ++Field) { 553 if ((*Field)->getIdentifier() || !(*Field)->isBitField()) 554 ++InitializableMembers; 555 } 556 if (structDecl->isUnion()) 557 return std::min(InitializableMembers, 1); 558 return InitializableMembers - structDecl->hasFlexibleArrayMember(); 559} 560 561void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList, 562 QualType T, unsigned &Index, 563 InitListExpr *StructuredList, 564 unsigned &StructuredIndex, 565 bool TopLevelObject) { 566 int maxElements = 0; 567 568 if (T->isArrayType()) 569 maxElements = numArrayElements(T); 570 else if (T->isStructureType() || T->isUnionType()) 571 maxElements = numStructUnionElements(T); 572 else if (T->isVectorType()) 573 maxElements = T->getAs<VectorType>()->getNumElements(); 574 else 575 assert(0 && "CheckImplicitInitList(): Illegal type"); 576 577 if (maxElements == 0) { 578 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(), 579 diag::err_implicit_empty_initializer); 580 ++Index; 581 hadError = true; 582 return; 583 } 584 585 // Build a structured initializer list corresponding to this subobject. 586 InitListExpr *StructuredSubobjectInitList 587 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList, 588 StructuredIndex, 589 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(), 590 ParentIList->getSourceRange().getEnd())); 591 unsigned StructuredSubobjectInitIndex = 0; 592 593 // Check the element types and build the structural subobject. 594 unsigned StartIndex = Index; 595 CheckListElementTypes(ParentIList, T, false, Index, 596 StructuredSubobjectInitList, 597 StructuredSubobjectInitIndex, 598 TopLevelObject); 599 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1); 600 StructuredSubobjectInitList->setType(T); 601 602 // Update the structured sub-object initializer so that it's ending 603 // range corresponds with the end of the last initializer it used. 604 if (EndIndex < ParentIList->getNumInits()) { 605 SourceLocation EndLoc 606 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd(); 607 StructuredSubobjectInitList->setRBraceLoc(EndLoc); 608 } 609} 610 611void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T, 612 unsigned &Index, 613 InitListExpr *StructuredList, 614 unsigned &StructuredIndex, 615 bool TopLevelObject) { 616 assert(IList->isExplicit() && "Illegal Implicit InitListExpr"); 617 SyntacticToSemantic[IList] = StructuredList; 618 StructuredList->setSyntacticForm(IList); 619 CheckListElementTypes(IList, T, true, Index, StructuredList, 620 StructuredIndex, TopLevelObject); 621 IList->setType(T); 622 StructuredList->setType(T); 623 if (hadError) 624 return; 625 626 if (Index < IList->getNumInits()) { 627 // We have leftover initializers 628 if (StructuredIndex == 1 && 629 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) { 630 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer; 631 if (SemaRef.getLangOptions().CPlusPlus) { 632 DK = diag::err_excess_initializers_in_char_array_initializer; 633 hadError = true; 634 } 635 // Special-case 636 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK) 637 << IList->getInit(Index)->getSourceRange(); 638 } else if (!T->isIncompleteType()) { 639 // Don't complain for incomplete types, since we'll get an error 640 // elsewhere 641 QualType CurrentObjectType = StructuredList->getType(); 642 int initKind = 643 CurrentObjectType->isArrayType()? 0 : 644 CurrentObjectType->isVectorType()? 1 : 645 CurrentObjectType->isScalarType()? 2 : 646 CurrentObjectType->isUnionType()? 3 : 647 4; 648 649 unsigned DK = diag::warn_excess_initializers; 650 if (SemaRef.getLangOptions().CPlusPlus) { 651 DK = diag::err_excess_initializers; 652 hadError = true; 653 } 654 if (SemaRef.getLangOptions().OpenCL && initKind == 1) { 655 DK = diag::err_excess_initializers; 656 hadError = true; 657 } 658 659 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK) 660 << initKind << IList->getInit(Index)->getSourceRange(); 661 } 662 } 663 664 if (T->isScalarType() && !TopLevelObject) 665 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init) 666 << IList->getSourceRange() 667 << CodeModificationHint::CreateRemoval(IList->getLocStart()) 668 << CodeModificationHint::CreateRemoval(IList->getLocEnd()); 669} 670 671void InitListChecker::CheckListElementTypes(InitListExpr *IList, 672 QualType &DeclType, 673 bool SubobjectIsDesignatorContext, 674 unsigned &Index, 675 InitListExpr *StructuredList, 676 unsigned &StructuredIndex, 677 bool TopLevelObject) { 678 if (DeclType->isScalarType()) { 679 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex); 680 } else if (DeclType->isVectorType()) { 681 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex); 682 } else if (DeclType->isAggregateType()) { 683 if (DeclType->isRecordType()) { 684 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl(); 685 CheckStructUnionTypes(IList, DeclType, RD->field_begin(), 686 SubobjectIsDesignatorContext, Index, 687 StructuredList, StructuredIndex, 688 TopLevelObject); 689 } else if (DeclType->isArrayType()) { 690 llvm::APSInt Zero( 691 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()), 692 false); 693 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index, 694 StructuredList, StructuredIndex); 695 } else 696 assert(0 && "Aggregate that isn't a structure or array?!"); 697 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) { 698 // This type is invalid, issue a diagnostic. 699 ++Index; 700 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type) 701 << DeclType; 702 hadError = true; 703 } else if (DeclType->isRecordType()) { 704 // C++ [dcl.init]p14: 705 // [...] If the class is an aggregate (8.5.1), and the initializer 706 // is a brace-enclosed list, see 8.5.1. 707 // 708 // Note: 8.5.1 is handled below; here, we diagnose the case where 709 // we have an initializer list and a destination type that is not 710 // an aggregate. 711 // FIXME: In C++0x, this is yet another form of initialization. 712 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list) 713 << DeclType << IList->getSourceRange(); 714 hadError = true; 715 } else if (DeclType->isReferenceType()) { 716 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex); 717 } else { 718 // In C, all types are either scalars or aggregates, but 719 // additional handling is needed here for C++ (and possibly others?). 720 assert(0 && "Unsupported initializer type"); 721 } 722} 723 724void InitListChecker::CheckSubElementType(InitListExpr *IList, 725 QualType ElemType, 726 unsigned &Index, 727 InitListExpr *StructuredList, 728 unsigned &StructuredIndex) { 729 Expr *expr = IList->getInit(Index); 730 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) { 731 unsigned newIndex = 0; 732 unsigned newStructuredIndex = 0; 733 InitListExpr *newStructuredList 734 = getStructuredSubobjectInit(IList, Index, ElemType, 735 StructuredList, StructuredIndex, 736 SubInitList->getSourceRange()); 737 CheckExplicitInitList(SubInitList, ElemType, newIndex, 738 newStructuredList, newStructuredIndex); 739 ++StructuredIndex; 740 ++Index; 741 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) { 742 CheckStringInit(Str, ElemType, SemaRef); 743 UpdateStructuredListElement(StructuredList, StructuredIndex, Str); 744 ++Index; 745 } else if (ElemType->isScalarType()) { 746 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex); 747 } else if (ElemType->isReferenceType()) { 748 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex); 749 } else { 750 if (SemaRef.getLangOptions().CPlusPlus) { 751 // C++ [dcl.init.aggr]p12: 752 // All implicit type conversions (clause 4) are considered when 753 // initializing the aggregate member with an ini- tializer from 754 // an initializer-list. If the initializer can initialize a 755 // member, the member is initialized. [...] 756 ImplicitConversionSequence ICS 757 = SemaRef.TryCopyInitialization(expr, ElemType, 758 /*SuppressUserConversions=*/false, 759 /*ForceRValue=*/false, 760 /*InOverloadResolution=*/false); 761 762 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) { 763 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS, 764 Sema::AA_Initializing)) 765 hadError = true; 766 UpdateStructuredListElement(StructuredList, StructuredIndex, expr); 767 ++Index; 768 return; 769 } 770 771 // Fall through for subaggregate initialization 772 } else { 773 // C99 6.7.8p13: 774 // 775 // The initializer for a structure or union object that has 776 // automatic storage duration shall be either an initializer 777 // list as described below, or a single expression that has 778 // compatible structure or union type. In the latter case, the 779 // initial value of the object, including unnamed members, is 780 // that of the expression. 781 if ((ElemType->isRecordType() || ElemType->isVectorType()) && 782 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) { 783 UpdateStructuredListElement(StructuredList, StructuredIndex, expr); 784 ++Index; 785 return; 786 } 787 788 // Fall through for subaggregate initialization 789 } 790 791 // C++ [dcl.init.aggr]p12: 792 // 793 // [...] Otherwise, if the member is itself a non-empty 794 // subaggregate, brace elision is assumed and the initializer is 795 // considered for the initialization of the first member of 796 // the subaggregate. 797 if (ElemType->isAggregateType() || ElemType->isVectorType()) { 798 CheckImplicitInitList(IList, ElemType, Index, StructuredList, 799 StructuredIndex); 800 ++StructuredIndex; 801 } else { 802 // We cannot initialize this element, so let 803 // PerformCopyInitialization produce the appropriate diagnostic. 804 SemaRef.PerformCopyInitialization(expr, ElemType, Sema::AA_Initializing); 805 hadError = true; 806 ++Index; 807 ++StructuredIndex; 808 } 809 } 810} 811 812void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType, 813 unsigned &Index, 814 InitListExpr *StructuredList, 815 unsigned &StructuredIndex) { 816 if (Index < IList->getNumInits()) { 817 Expr *expr = IList->getInit(Index); 818 if (isa<InitListExpr>(expr)) { 819 SemaRef.Diag(IList->getLocStart(), 820 diag::err_many_braces_around_scalar_init) 821 << IList->getSourceRange(); 822 hadError = true; 823 ++Index; 824 ++StructuredIndex; 825 return; 826 } else if (isa<DesignatedInitExpr>(expr)) { 827 SemaRef.Diag(expr->getSourceRange().getBegin(), 828 diag::err_designator_for_scalar_init) 829 << DeclType << expr->getSourceRange(); 830 hadError = true; 831 ++Index; 832 ++StructuredIndex; 833 return; 834 } 835 836 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer. 837 if (CheckSingleInitializer(expr, DeclType, false, SemaRef)) 838 hadError = true; // types weren't compatible. 839 else if (savExpr != expr) { 840 // The type was promoted, update initializer list. 841 IList->setInit(Index, expr); 842 } 843 if (hadError) 844 ++StructuredIndex; 845 else 846 UpdateStructuredListElement(StructuredList, StructuredIndex, expr); 847 ++Index; 848 } else { 849 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer) 850 << IList->getSourceRange(); 851 hadError = true; 852 ++Index; 853 ++StructuredIndex; 854 return; 855 } 856} 857 858void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType, 859 unsigned &Index, 860 InitListExpr *StructuredList, 861 unsigned &StructuredIndex) { 862 if (Index < IList->getNumInits()) { 863 Expr *expr = IList->getInit(Index); 864 if (isa<InitListExpr>(expr)) { 865 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list) 866 << DeclType << IList->getSourceRange(); 867 hadError = true; 868 ++Index; 869 ++StructuredIndex; 870 return; 871 } 872 873 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer. 874 if (SemaRef.CheckReferenceInit(expr, DeclType, 875 /*FIXME:*/expr->getLocStart(), 876 /*SuppressUserConversions=*/false, 877 /*AllowExplicit=*/false, 878 /*ForceRValue=*/false)) 879 hadError = true; 880 else if (savExpr != expr) { 881 // The type was promoted, update initializer list. 882 IList->setInit(Index, expr); 883 } 884 if (hadError) 885 ++StructuredIndex; 886 else 887 UpdateStructuredListElement(StructuredList, StructuredIndex, expr); 888 ++Index; 889 } else { 890 // FIXME: It would be wonderful if we could point at the actual member. In 891 // general, it would be useful to pass location information down the stack, 892 // so that we know the location (or decl) of the "current object" being 893 // initialized. 894 SemaRef.Diag(IList->getLocStart(), 895 diag::err_init_reference_member_uninitialized) 896 << DeclType 897 << IList->getSourceRange(); 898 hadError = true; 899 ++Index; 900 ++StructuredIndex; 901 return; 902 } 903} 904 905void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType, 906 unsigned &Index, 907 InitListExpr *StructuredList, 908 unsigned &StructuredIndex) { 909 if (Index < IList->getNumInits()) { 910 const VectorType *VT = DeclType->getAs<VectorType>(); 911 unsigned maxElements = VT->getNumElements(); 912 unsigned numEltsInit = 0; 913 QualType elementType = VT->getElementType(); 914 915 if (!SemaRef.getLangOptions().OpenCL) { 916 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) { 917 // Don't attempt to go past the end of the init list 918 if (Index >= IList->getNumInits()) 919 break; 920 CheckSubElementType(IList, elementType, Index, 921 StructuredList, StructuredIndex); 922 } 923 } else { 924 // OpenCL initializers allows vectors to be constructed from vectors. 925 for (unsigned i = 0; i < maxElements; ++i) { 926 // Don't attempt to go past the end of the init list 927 if (Index >= IList->getNumInits()) 928 break; 929 QualType IType = IList->getInit(Index)->getType(); 930 if (!IType->isVectorType()) { 931 CheckSubElementType(IList, elementType, Index, 932 StructuredList, StructuredIndex); 933 ++numEltsInit; 934 } else { 935 const VectorType *IVT = IType->getAs<VectorType>(); 936 unsigned numIElts = IVT->getNumElements(); 937 QualType VecType = SemaRef.Context.getExtVectorType(elementType, 938 numIElts); 939 CheckSubElementType(IList, VecType, Index, 940 StructuredList, StructuredIndex); 941 numEltsInit += numIElts; 942 } 943 } 944 } 945 946 // OpenCL & AltiVec require all elements to be initialized. 947 if (numEltsInit != maxElements) 948 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec) 949 SemaRef.Diag(IList->getSourceRange().getBegin(), 950 diag::err_vector_incorrect_num_initializers) 951 << (numEltsInit < maxElements) << maxElements << numEltsInit; 952 } 953} 954 955void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType, 956 llvm::APSInt elementIndex, 957 bool SubobjectIsDesignatorContext, 958 unsigned &Index, 959 InitListExpr *StructuredList, 960 unsigned &StructuredIndex) { 961 // Check for the special-case of initializing an array with a string. 962 if (Index < IList->getNumInits()) { 963 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType, 964 SemaRef.Context)) { 965 CheckStringInit(Str, DeclType, SemaRef); 966 // We place the string literal directly into the resulting 967 // initializer list. This is the only place where the structure 968 // of the structured initializer list doesn't match exactly, 969 // because doing so would involve allocating one character 970 // constant for each string. 971 UpdateStructuredListElement(StructuredList, StructuredIndex, Str); 972 StructuredList->resizeInits(SemaRef.Context, StructuredIndex); 973 ++Index; 974 return; 975 } 976 } 977 if (const VariableArrayType *VAT = 978 SemaRef.Context.getAsVariableArrayType(DeclType)) { 979 // Check for VLAs; in standard C it would be possible to check this 980 // earlier, but I don't know where clang accepts VLAs (gcc accepts 981 // them in all sorts of strange places). 982 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(), 983 diag::err_variable_object_no_init) 984 << VAT->getSizeExpr()->getSourceRange(); 985 hadError = true; 986 ++Index; 987 ++StructuredIndex; 988 return; 989 } 990 991 // We might know the maximum number of elements in advance. 992 llvm::APSInt maxElements(elementIndex.getBitWidth(), 993 elementIndex.isUnsigned()); 994 bool maxElementsKnown = false; 995 if (const ConstantArrayType *CAT = 996 SemaRef.Context.getAsConstantArrayType(DeclType)) { 997 maxElements = CAT->getSize(); 998 elementIndex.extOrTrunc(maxElements.getBitWidth()); 999 elementIndex.setIsUnsigned(maxElements.isUnsigned()); 1000 maxElementsKnown = true; 1001 } 1002 1003 QualType elementType = SemaRef.Context.getAsArrayType(DeclType) 1004 ->getElementType(); 1005 while (Index < IList->getNumInits()) { 1006 Expr *Init = IList->getInit(Index); 1007 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) { 1008 // If we're not the subobject that matches up with the '{' for 1009 // the designator, we shouldn't be handling the 1010 // designator. Return immediately. 1011 if (!SubobjectIsDesignatorContext) 1012 return; 1013 1014 // Handle this designated initializer. elementIndex will be 1015 // updated to be the next array element we'll initialize. 1016 if (CheckDesignatedInitializer(IList, DIE, 0, 1017 DeclType, 0, &elementIndex, Index, 1018 StructuredList, StructuredIndex, true, 1019 false)) { 1020 hadError = true; 1021 continue; 1022 } 1023 1024 if (elementIndex.getBitWidth() > maxElements.getBitWidth()) 1025 maxElements.extend(elementIndex.getBitWidth()); 1026 else if (elementIndex.getBitWidth() < maxElements.getBitWidth()) 1027 elementIndex.extend(maxElements.getBitWidth()); 1028 elementIndex.setIsUnsigned(maxElements.isUnsigned()); 1029 1030 // If the array is of incomplete type, keep track of the number of 1031 // elements in the initializer. 1032 if (!maxElementsKnown && elementIndex > maxElements) 1033 maxElements = elementIndex; 1034 1035 continue; 1036 } 1037 1038 // If we know the maximum number of elements, and we've already 1039 // hit it, stop consuming elements in the initializer list. 1040 if (maxElementsKnown && elementIndex == maxElements) 1041 break; 1042 1043 // Check this element. 1044 CheckSubElementType(IList, elementType, Index, 1045 StructuredList, StructuredIndex); 1046 ++elementIndex; 1047 1048 // If the array is of incomplete type, keep track of the number of 1049 // elements in the initializer. 1050 if (!maxElementsKnown && elementIndex > maxElements) 1051 maxElements = elementIndex; 1052 } 1053 if (!hadError && DeclType->isIncompleteArrayType()) { 1054 // If this is an incomplete array type, the actual type needs to 1055 // be calculated here. 1056 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned()); 1057 if (maxElements == Zero) { 1058 // Sizing an array implicitly to zero is not allowed by ISO C, 1059 // but is supported by GNU. 1060 SemaRef.Diag(IList->getLocStart(), 1061 diag::ext_typecheck_zero_array_size); 1062 } 1063 1064 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements, 1065 ArrayType::Normal, 0); 1066 } 1067} 1068 1069void InitListChecker::CheckStructUnionTypes(InitListExpr *IList, 1070 QualType DeclType, 1071 RecordDecl::field_iterator Field, 1072 bool SubobjectIsDesignatorContext, 1073 unsigned &Index, 1074 InitListExpr *StructuredList, 1075 unsigned &StructuredIndex, 1076 bool TopLevelObject) { 1077 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl(); 1078 1079 // If the record is invalid, some of it's members are invalid. To avoid 1080 // confusion, we forgo checking the intializer for the entire record. 1081 if (structDecl->isInvalidDecl()) { 1082 hadError = true; 1083 return; 1084 } 1085 1086 if (DeclType->isUnionType() && IList->getNumInits() == 0) { 1087 // Value-initialize the first named member of the union. 1088 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl(); 1089 for (RecordDecl::field_iterator FieldEnd = RD->field_end(); 1090 Field != FieldEnd; ++Field) { 1091 if (Field->getDeclName()) { 1092 StructuredList->setInitializedFieldInUnion(*Field); 1093 break; 1094 } 1095 } 1096 return; 1097 } 1098 1099 // If structDecl is a forward declaration, this loop won't do 1100 // anything except look at designated initializers; That's okay, 1101 // because an error should get printed out elsewhere. It might be 1102 // worthwhile to skip over the rest of the initializer, though. 1103 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl(); 1104 RecordDecl::field_iterator FieldEnd = RD->field_end(); 1105 bool InitializedSomething = false; 1106 while (Index < IList->getNumInits()) { 1107 Expr *Init = IList->getInit(Index); 1108 1109 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) { 1110 // If we're not the subobject that matches up with the '{' for 1111 // the designator, we shouldn't be handling the 1112 // designator. Return immediately. 1113 if (!SubobjectIsDesignatorContext) 1114 return; 1115 1116 // Handle this designated initializer. Field will be updated to 1117 // the next field that we'll be initializing. 1118 if (CheckDesignatedInitializer(IList, DIE, 0, 1119 DeclType, &Field, 0, Index, 1120 StructuredList, StructuredIndex, 1121 true, TopLevelObject)) 1122 hadError = true; 1123 1124 InitializedSomething = true; 1125 continue; 1126 } 1127 1128 if (Field == FieldEnd) { 1129 // We've run out of fields. We're done. 1130 break; 1131 } 1132 1133 // We've already initialized a member of a union. We're done. 1134 if (InitializedSomething && DeclType->isUnionType()) 1135 break; 1136 1137 // If we've hit the flexible array member at the end, we're done. 1138 if (Field->getType()->isIncompleteArrayType()) 1139 break; 1140 1141 if (Field->isUnnamedBitfield()) { 1142 // Don't initialize unnamed bitfields, e.g. "int : 20;" 1143 ++Field; 1144 continue; 1145 } 1146 1147 CheckSubElementType(IList, Field->getType(), Index, 1148 StructuredList, StructuredIndex); 1149 InitializedSomething = true; 1150 1151 if (DeclType->isUnionType()) { 1152 // Initialize the first field within the union. 1153 StructuredList->setInitializedFieldInUnion(*Field); 1154 } 1155 1156 ++Field; 1157 } 1158 1159 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() || 1160 Index >= IList->getNumInits()) 1161 return; 1162 1163 // Handle GNU flexible array initializers. 1164 if (!TopLevelObject && 1165 (!isa<InitListExpr>(IList->getInit(Index)) || 1166 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) { 1167 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(), 1168 diag::err_flexible_array_init_nonempty) 1169 << IList->getInit(Index)->getSourceRange().getBegin(); 1170 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1171 << *Field; 1172 hadError = true; 1173 ++Index; 1174 return; 1175 } else { 1176 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(), 1177 diag::ext_flexible_array_init) 1178 << IList->getInit(Index)->getSourceRange().getBegin(); 1179 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1180 << *Field; 1181 } 1182 1183 if (isa<InitListExpr>(IList->getInit(Index))) 1184 CheckSubElementType(IList, Field->getType(), Index, StructuredList, 1185 StructuredIndex); 1186 else 1187 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList, 1188 StructuredIndex); 1189} 1190 1191/// \brief Expand a field designator that refers to a member of an 1192/// anonymous struct or union into a series of field designators that 1193/// refers to the field within the appropriate subobject. 1194/// 1195/// Field/FieldIndex will be updated to point to the (new) 1196/// currently-designated field. 1197static void ExpandAnonymousFieldDesignator(Sema &SemaRef, 1198 DesignatedInitExpr *DIE, 1199 unsigned DesigIdx, 1200 FieldDecl *Field, 1201 RecordDecl::field_iterator &FieldIter, 1202 unsigned &FieldIndex) { 1203 typedef DesignatedInitExpr::Designator Designator; 1204 1205 // Build the path from the current object to the member of the 1206 // anonymous struct/union (backwards). 1207 llvm::SmallVector<FieldDecl *, 4> Path; 1208 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path); 1209 1210 // Build the replacement designators. 1211 llvm::SmallVector<Designator, 4> Replacements; 1212 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator 1213 FI = Path.rbegin(), FIEnd = Path.rend(); 1214 FI != FIEnd; ++FI) { 1215 if (FI + 1 == FIEnd) 1216 Replacements.push_back(Designator((IdentifierInfo *)0, 1217 DIE->getDesignator(DesigIdx)->getDotLoc(), 1218 DIE->getDesignator(DesigIdx)->getFieldLoc())); 1219 else 1220 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(), 1221 SourceLocation())); 1222 Replacements.back().setField(*FI); 1223 } 1224 1225 // Expand the current designator into the set of replacement 1226 // designators, so we have a full subobject path down to where the 1227 // member of the anonymous struct/union is actually stored. 1228 DIE->ExpandDesignator(DesigIdx, &Replacements[0], 1229 &Replacements[0] + Replacements.size()); 1230 1231 // Update FieldIter/FieldIndex; 1232 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext()); 1233 FieldIter = Record->field_begin(); 1234 FieldIndex = 0; 1235 for (RecordDecl::field_iterator FEnd = Record->field_end(); 1236 FieldIter != FEnd; ++FieldIter) { 1237 if (FieldIter->isUnnamedBitfield()) 1238 continue; 1239 1240 if (*FieldIter == Path.back()) 1241 return; 1242 1243 ++FieldIndex; 1244 } 1245 1246 assert(false && "Unable to find anonymous struct/union field"); 1247} 1248 1249/// @brief Check the well-formedness of a C99 designated initializer. 1250/// 1251/// Determines whether the designated initializer @p DIE, which 1252/// resides at the given @p Index within the initializer list @p 1253/// IList, is well-formed for a current object of type @p DeclType 1254/// (C99 6.7.8). The actual subobject that this designator refers to 1255/// within the current subobject is returned in either 1256/// @p NextField or @p NextElementIndex (whichever is appropriate). 1257/// 1258/// @param IList The initializer list in which this designated 1259/// initializer occurs. 1260/// 1261/// @param DIE The designated initializer expression. 1262/// 1263/// @param DesigIdx The index of the current designator. 1264/// 1265/// @param DeclType The type of the "current object" (C99 6.7.8p17), 1266/// into which the designation in @p DIE should refer. 1267/// 1268/// @param NextField If non-NULL and the first designator in @p DIE is 1269/// a field, this will be set to the field declaration corresponding 1270/// to the field named by the designator. 1271/// 1272/// @param NextElementIndex If non-NULL and the first designator in @p 1273/// DIE is an array designator or GNU array-range designator, this 1274/// will be set to the last index initialized by this designator. 1275/// 1276/// @param Index Index into @p IList where the designated initializer 1277/// @p DIE occurs. 1278/// 1279/// @param StructuredList The initializer list expression that 1280/// describes all of the subobject initializers in the order they'll 1281/// actually be initialized. 1282/// 1283/// @returns true if there was an error, false otherwise. 1284bool 1285InitListChecker::CheckDesignatedInitializer(InitListExpr *IList, 1286 DesignatedInitExpr *DIE, 1287 unsigned DesigIdx, 1288 QualType &CurrentObjectType, 1289 RecordDecl::field_iterator *NextField, 1290 llvm::APSInt *NextElementIndex, 1291 unsigned &Index, 1292 InitListExpr *StructuredList, 1293 unsigned &StructuredIndex, 1294 bool FinishSubobjectInit, 1295 bool TopLevelObject) { 1296 if (DesigIdx == DIE->size()) { 1297 // Check the actual initialization for the designated object type. 1298 bool prevHadError = hadError; 1299 1300 // Temporarily remove the designator expression from the 1301 // initializer list that the child calls see, so that we don't try 1302 // to re-process the designator. 1303 unsigned OldIndex = Index; 1304 IList->setInit(OldIndex, DIE->getInit()); 1305 1306 CheckSubElementType(IList, CurrentObjectType, Index, 1307 StructuredList, StructuredIndex); 1308 1309 // Restore the designated initializer expression in the syntactic 1310 // form of the initializer list. 1311 if (IList->getInit(OldIndex) != DIE->getInit()) 1312 DIE->setInit(IList->getInit(OldIndex)); 1313 IList->setInit(OldIndex, DIE); 1314 1315 return hadError && !prevHadError; 1316 } 1317 1318 bool IsFirstDesignator = (DesigIdx == 0); 1319 assert((IsFirstDesignator || StructuredList) && 1320 "Need a non-designated initializer list to start from"); 1321 1322 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx); 1323 // Determine the structural initializer list that corresponds to the 1324 // current subobject. 1325 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList] 1326 : getStructuredSubobjectInit(IList, Index, CurrentObjectType, 1327 StructuredList, StructuredIndex, 1328 SourceRange(D->getStartLocation(), 1329 DIE->getSourceRange().getEnd())); 1330 assert(StructuredList && "Expected a structured initializer list"); 1331 1332 if (D->isFieldDesignator()) { 1333 // C99 6.7.8p7: 1334 // 1335 // If a designator has the form 1336 // 1337 // . identifier 1338 // 1339 // then the current object (defined below) shall have 1340 // structure or union type and the identifier shall be the 1341 // name of a member of that type. 1342 const RecordType *RT = CurrentObjectType->getAs<RecordType>(); 1343 if (!RT) { 1344 SourceLocation Loc = D->getDotLoc(); 1345 if (Loc.isInvalid()) 1346 Loc = D->getFieldLoc(); 1347 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr) 1348 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType; 1349 ++Index; 1350 return true; 1351 } 1352 1353 // Note: we perform a linear search of the fields here, despite 1354 // the fact that we have a faster lookup method, because we always 1355 // need to compute the field's index. 1356 FieldDecl *KnownField = D->getField(); 1357 IdentifierInfo *FieldName = D->getFieldName(); 1358 unsigned FieldIndex = 0; 1359 RecordDecl::field_iterator 1360 Field = RT->getDecl()->field_begin(), 1361 FieldEnd = RT->getDecl()->field_end(); 1362 for (; Field != FieldEnd; ++Field) { 1363 if (Field->isUnnamedBitfield()) 1364 continue; 1365 1366 if (KnownField == *Field || Field->getIdentifier() == FieldName) 1367 break; 1368 1369 ++FieldIndex; 1370 } 1371 1372 if (Field == FieldEnd) { 1373 // There was no normal field in the struct with the designated 1374 // name. Perform another lookup for this name, which may find 1375 // something that we can't designate (e.g., a member function), 1376 // may find nothing, or may find a member of an anonymous 1377 // struct/union. 1378 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName); 1379 if (Lookup.first == Lookup.second) { 1380 // Name lookup didn't find anything. 1381 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown) 1382 << FieldName << CurrentObjectType; 1383 ++Index; 1384 return true; 1385 } else if (!KnownField && isa<FieldDecl>(*Lookup.first) && 1386 cast<RecordDecl>((*Lookup.first)->getDeclContext()) 1387 ->isAnonymousStructOrUnion()) { 1388 // Handle an field designator that refers to a member of an 1389 // anonymous struct or union. 1390 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, 1391 cast<FieldDecl>(*Lookup.first), 1392 Field, FieldIndex); 1393 D = DIE->getDesignator(DesigIdx); 1394 } else { 1395 // Name lookup found something, but it wasn't a field. 1396 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield) 1397 << FieldName; 1398 SemaRef.Diag((*Lookup.first)->getLocation(), 1399 diag::note_field_designator_found); 1400 ++Index; 1401 return true; 1402 } 1403 } else if (!KnownField && 1404 cast<RecordDecl>((*Field)->getDeclContext()) 1405 ->isAnonymousStructOrUnion()) { 1406 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field, 1407 Field, FieldIndex); 1408 D = DIE->getDesignator(DesigIdx); 1409 } 1410 1411 // All of the fields of a union are located at the same place in 1412 // the initializer list. 1413 if (RT->getDecl()->isUnion()) { 1414 FieldIndex = 0; 1415 StructuredList->setInitializedFieldInUnion(*Field); 1416 } 1417 1418 // Update the designator with the field declaration. 1419 D->setField(*Field); 1420 1421 // Make sure that our non-designated initializer list has space 1422 // for a subobject corresponding to this field. 1423 if (FieldIndex >= StructuredList->getNumInits()) 1424 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1); 1425 1426 // This designator names a flexible array member. 1427 if (Field->getType()->isIncompleteArrayType()) { 1428 bool Invalid = false; 1429 if ((DesigIdx + 1) != DIE->size()) { 1430 // We can't designate an object within the flexible array 1431 // member (because GCC doesn't allow it). 1432 DesignatedInitExpr::Designator *NextD 1433 = DIE->getDesignator(DesigIdx + 1); 1434 SemaRef.Diag(NextD->getStartLocation(), 1435 diag::err_designator_into_flexible_array_member) 1436 << SourceRange(NextD->getStartLocation(), 1437 DIE->getSourceRange().getEnd()); 1438 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1439 << *Field; 1440 Invalid = true; 1441 } 1442 1443 if (!hadError && !isa<InitListExpr>(DIE->getInit())) { 1444 // The initializer is not an initializer list. 1445 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(), 1446 diag::err_flexible_array_init_needs_braces) 1447 << DIE->getInit()->getSourceRange(); 1448 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1449 << *Field; 1450 Invalid = true; 1451 } 1452 1453 // Handle GNU flexible array initializers. 1454 if (!Invalid && !TopLevelObject && 1455 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) { 1456 SemaRef.Diag(DIE->getSourceRange().getBegin(), 1457 diag::err_flexible_array_init_nonempty) 1458 << DIE->getSourceRange().getBegin(); 1459 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1460 << *Field; 1461 Invalid = true; 1462 } 1463 1464 if (Invalid) { 1465 ++Index; 1466 return true; 1467 } 1468 1469 // Initialize the array. 1470 bool prevHadError = hadError; 1471 unsigned newStructuredIndex = FieldIndex; 1472 unsigned OldIndex = Index; 1473 IList->setInit(Index, DIE->getInit()); 1474 CheckSubElementType(IList, Field->getType(), Index, 1475 StructuredList, newStructuredIndex); 1476 IList->setInit(OldIndex, DIE); 1477 if (hadError && !prevHadError) { 1478 ++Field; 1479 ++FieldIndex; 1480 if (NextField) 1481 *NextField = Field; 1482 StructuredIndex = FieldIndex; 1483 return true; 1484 } 1485 } else { 1486 // Recurse to check later designated subobjects. 1487 QualType FieldType = (*Field)->getType(); 1488 unsigned newStructuredIndex = FieldIndex; 1489 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0, 1490 Index, StructuredList, newStructuredIndex, 1491 true, false)) 1492 return true; 1493 } 1494 1495 // Find the position of the next field to be initialized in this 1496 // subobject. 1497 ++Field; 1498 ++FieldIndex; 1499 1500 // If this the first designator, our caller will continue checking 1501 // the rest of this struct/class/union subobject. 1502 if (IsFirstDesignator) { 1503 if (NextField) 1504 *NextField = Field; 1505 StructuredIndex = FieldIndex; 1506 return false; 1507 } 1508 1509 if (!FinishSubobjectInit) 1510 return false; 1511 1512 // We've already initialized something in the union; we're done. 1513 if (RT->getDecl()->isUnion()) 1514 return hadError; 1515 1516 // Check the remaining fields within this class/struct/union subobject. 1517 bool prevHadError = hadError; 1518 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index, 1519 StructuredList, FieldIndex); 1520 return hadError && !prevHadError; 1521 } 1522 1523 // C99 6.7.8p6: 1524 // 1525 // If a designator has the form 1526 // 1527 // [ constant-expression ] 1528 // 1529 // then the current object (defined below) shall have array 1530 // type and the expression shall be an integer constant 1531 // expression. If the array is of unknown size, any 1532 // nonnegative value is valid. 1533 // 1534 // Additionally, cope with the GNU extension that permits 1535 // designators of the form 1536 // 1537 // [ constant-expression ... constant-expression ] 1538 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType); 1539 if (!AT) { 1540 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array) 1541 << CurrentObjectType; 1542 ++Index; 1543 return true; 1544 } 1545 1546 Expr *IndexExpr = 0; 1547 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex; 1548 if (D->isArrayDesignator()) { 1549 IndexExpr = DIE->getArrayIndex(*D); 1550 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context); 1551 DesignatedEndIndex = DesignatedStartIndex; 1552 } else { 1553 assert(D->isArrayRangeDesignator() && "Need array-range designator"); 1554 1555 1556 DesignatedStartIndex = 1557 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context); 1558 DesignatedEndIndex = 1559 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context); 1560 IndexExpr = DIE->getArrayRangeEnd(*D); 1561 1562 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue()) 1563 FullyStructuredList->sawArrayRangeDesignator(); 1564 } 1565 1566 if (isa<ConstantArrayType>(AT)) { 1567 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false); 1568 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth()); 1569 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned()); 1570 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth()); 1571 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned()); 1572 if (DesignatedEndIndex >= MaxElements) { 1573 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(), 1574 diag::err_array_designator_too_large) 1575 << DesignatedEndIndex.toString(10) << MaxElements.toString(10) 1576 << IndexExpr->getSourceRange(); 1577 ++Index; 1578 return true; 1579 } 1580 } else { 1581 // Make sure the bit-widths and signedness match. 1582 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth()) 1583 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth()); 1584 else if (DesignatedStartIndex.getBitWidth() < 1585 DesignatedEndIndex.getBitWidth()) 1586 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth()); 1587 DesignatedStartIndex.setIsUnsigned(true); 1588 DesignatedEndIndex.setIsUnsigned(true); 1589 } 1590 1591 // Make sure that our non-designated initializer list has space 1592 // for a subobject corresponding to this array element. 1593 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits()) 1594 StructuredList->resizeInits(SemaRef.Context, 1595 DesignatedEndIndex.getZExtValue() + 1); 1596 1597 // Repeatedly perform subobject initializations in the range 1598 // [DesignatedStartIndex, DesignatedEndIndex]. 1599 1600 // Move to the next designator 1601 unsigned ElementIndex = DesignatedStartIndex.getZExtValue(); 1602 unsigned OldIndex = Index; 1603 while (DesignatedStartIndex <= DesignatedEndIndex) { 1604 // Recurse to check later designated subobjects. 1605 QualType ElementType = AT->getElementType(); 1606 Index = OldIndex; 1607 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0, 1608 Index, StructuredList, ElementIndex, 1609 (DesignatedStartIndex == DesignatedEndIndex), 1610 false)) 1611 return true; 1612 1613 // Move to the next index in the array that we'll be initializing. 1614 ++DesignatedStartIndex; 1615 ElementIndex = DesignatedStartIndex.getZExtValue(); 1616 } 1617 1618 // If this the first designator, our caller will continue checking 1619 // the rest of this array subobject. 1620 if (IsFirstDesignator) { 1621 if (NextElementIndex) 1622 *NextElementIndex = DesignatedStartIndex; 1623 StructuredIndex = ElementIndex; 1624 return false; 1625 } 1626 1627 if (!FinishSubobjectInit) 1628 return false; 1629 1630 // Check the remaining elements within this array subobject. 1631 bool prevHadError = hadError; 1632 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index, 1633 StructuredList, ElementIndex); 1634 return hadError && !prevHadError; 1635} 1636 1637// Get the structured initializer list for a subobject of type 1638// @p CurrentObjectType. 1639InitListExpr * 1640InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, 1641 QualType CurrentObjectType, 1642 InitListExpr *StructuredList, 1643 unsigned StructuredIndex, 1644 SourceRange InitRange) { 1645 Expr *ExistingInit = 0; 1646 if (!StructuredList) 1647 ExistingInit = SyntacticToSemantic[IList]; 1648 else if (StructuredIndex < StructuredList->getNumInits()) 1649 ExistingInit = StructuredList->getInit(StructuredIndex); 1650 1651 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit)) 1652 return Result; 1653 1654 if (ExistingInit) { 1655 // We are creating an initializer list that initializes the 1656 // subobjects of the current object, but there was already an 1657 // initialization that completely initialized the current 1658 // subobject, e.g., by a compound literal: 1659 // 1660 // struct X { int a, b; }; 1661 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 }; 1662 // 1663 // Here, xs[0].a == 0 and xs[0].b == 3, since the second, 1664 // designated initializer re-initializes the whole 1665 // subobject [0], overwriting previous initializers. 1666 SemaRef.Diag(InitRange.getBegin(), 1667 diag::warn_subobject_initializer_overrides) 1668 << InitRange; 1669 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(), 1670 diag::note_previous_initializer) 1671 << /*FIXME:has side effects=*/0 1672 << ExistingInit->getSourceRange(); 1673 } 1674 1675 InitListExpr *Result 1676 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0, 1677 InitRange.getEnd()); 1678 1679 Result->setType(CurrentObjectType); 1680 1681 // Pre-allocate storage for the structured initializer list. 1682 unsigned NumElements = 0; 1683 unsigned NumInits = 0; 1684 if (!StructuredList) 1685 NumInits = IList->getNumInits(); 1686 else if (Index < IList->getNumInits()) { 1687 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) 1688 NumInits = SubList->getNumInits(); 1689 } 1690 1691 if (const ArrayType *AType 1692 = SemaRef.Context.getAsArrayType(CurrentObjectType)) { 1693 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) { 1694 NumElements = CAType->getSize().getZExtValue(); 1695 // Simple heuristic so that we don't allocate a very large 1696 // initializer with many empty entries at the end. 1697 if (NumInits && NumElements > NumInits) 1698 NumElements = 0; 1699 } 1700 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) 1701 NumElements = VType->getNumElements(); 1702 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) { 1703 RecordDecl *RDecl = RType->getDecl(); 1704 if (RDecl->isUnion()) 1705 NumElements = 1; 1706 else 1707 NumElements = std::distance(RDecl->field_begin(), 1708 RDecl->field_end()); 1709 } 1710 1711 if (NumElements < NumInits) 1712 NumElements = IList->getNumInits(); 1713 1714 Result->reserveInits(NumElements); 1715 1716 // Link this new initializer list into the structured initializer 1717 // lists. 1718 if (StructuredList) 1719 StructuredList->updateInit(StructuredIndex, Result); 1720 else { 1721 Result->setSyntacticForm(IList); 1722 SyntacticToSemantic[IList] = Result; 1723 } 1724 1725 return Result; 1726} 1727 1728/// Update the initializer at index @p StructuredIndex within the 1729/// structured initializer list to the value @p expr. 1730void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList, 1731 unsigned &StructuredIndex, 1732 Expr *expr) { 1733 // No structured initializer list to update 1734 if (!StructuredList) 1735 return; 1736 1737 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) { 1738 // This initializer overwrites a previous initializer. Warn. 1739 SemaRef.Diag(expr->getSourceRange().getBegin(), 1740 diag::warn_initializer_overrides) 1741 << expr->getSourceRange(); 1742 SemaRef.Diag(PrevInit->getSourceRange().getBegin(), 1743 diag::note_previous_initializer) 1744 << /*FIXME:has side effects=*/0 1745 << PrevInit->getSourceRange(); 1746 } 1747 1748 ++StructuredIndex; 1749} 1750 1751/// Check that the given Index expression is a valid array designator 1752/// value. This is essentailly just a wrapper around 1753/// VerifyIntegerConstantExpression that also checks for negative values 1754/// and produces a reasonable diagnostic if there is a 1755/// failure. Returns true if there was an error, false otherwise. If 1756/// everything went okay, Value will receive the value of the constant 1757/// expression. 1758static bool 1759CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) { 1760 SourceLocation Loc = Index->getSourceRange().getBegin(); 1761 1762 // Make sure this is an integer constant expression. 1763 if (S.VerifyIntegerConstantExpression(Index, &Value)) 1764 return true; 1765 1766 if (Value.isSigned() && Value.isNegative()) 1767 return S.Diag(Loc, diag::err_array_designator_negative) 1768 << Value.toString(10) << Index->getSourceRange(); 1769 1770 Value.setIsUnsigned(true); 1771 return false; 1772} 1773 1774Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig, 1775 SourceLocation Loc, 1776 bool GNUSyntax, 1777 OwningExprResult Init) { 1778 typedef DesignatedInitExpr::Designator ASTDesignator; 1779 1780 bool Invalid = false; 1781 llvm::SmallVector<ASTDesignator, 32> Designators; 1782 llvm::SmallVector<Expr *, 32> InitExpressions; 1783 1784 // Build designators and check array designator expressions. 1785 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) { 1786 const Designator &D = Desig.getDesignator(Idx); 1787 switch (D.getKind()) { 1788 case Designator::FieldDesignator: 1789 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(), 1790 D.getFieldLoc())); 1791 break; 1792 1793 case Designator::ArrayDesignator: { 1794 Expr *Index = static_cast<Expr *>(D.getArrayIndex()); 1795 llvm::APSInt IndexValue; 1796 if (!Index->isTypeDependent() && 1797 !Index->isValueDependent() && 1798 CheckArrayDesignatorExpr(*this, Index, IndexValue)) 1799 Invalid = true; 1800 else { 1801 Designators.push_back(ASTDesignator(InitExpressions.size(), 1802 D.getLBracketLoc(), 1803 D.getRBracketLoc())); 1804 InitExpressions.push_back(Index); 1805 } 1806 break; 1807 } 1808 1809 case Designator::ArrayRangeDesignator: { 1810 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart()); 1811 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd()); 1812 llvm::APSInt StartValue; 1813 llvm::APSInt EndValue; 1814 bool StartDependent = StartIndex->isTypeDependent() || 1815 StartIndex->isValueDependent(); 1816 bool EndDependent = EndIndex->isTypeDependent() || 1817 EndIndex->isValueDependent(); 1818 if ((!StartDependent && 1819 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) || 1820 (!EndDependent && 1821 CheckArrayDesignatorExpr(*this, EndIndex, EndValue))) 1822 Invalid = true; 1823 else { 1824 // Make sure we're comparing values with the same bit width. 1825 if (StartDependent || EndDependent) { 1826 // Nothing to compute. 1827 } else if (StartValue.getBitWidth() > EndValue.getBitWidth()) 1828 EndValue.extend(StartValue.getBitWidth()); 1829 else if (StartValue.getBitWidth() < EndValue.getBitWidth()) 1830 StartValue.extend(EndValue.getBitWidth()); 1831 1832 if (!StartDependent && !EndDependent && EndValue < StartValue) { 1833 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range) 1834 << StartValue.toString(10) << EndValue.toString(10) 1835 << StartIndex->getSourceRange() << EndIndex->getSourceRange(); 1836 Invalid = true; 1837 } else { 1838 Designators.push_back(ASTDesignator(InitExpressions.size(), 1839 D.getLBracketLoc(), 1840 D.getEllipsisLoc(), 1841 D.getRBracketLoc())); 1842 InitExpressions.push_back(StartIndex); 1843 InitExpressions.push_back(EndIndex); 1844 } 1845 } 1846 break; 1847 } 1848 } 1849 } 1850 1851 if (Invalid || Init.isInvalid()) 1852 return ExprError(); 1853 1854 // Clear out the expressions within the designation. 1855 Desig.ClearExprs(*this); 1856 1857 DesignatedInitExpr *DIE 1858 = DesignatedInitExpr::Create(Context, 1859 Designators.data(), Designators.size(), 1860 InitExpressions.data(), InitExpressions.size(), 1861 Loc, GNUSyntax, Init.takeAs<Expr>()); 1862 return Owned(DIE); 1863} 1864 1865bool Sema::CheckInitList(const InitializedEntity &Entity, 1866 InitListExpr *&InitList, QualType &DeclType) { 1867 InitListChecker CheckInitList(*this, Entity, InitList, DeclType); 1868 if (!CheckInitList.HadError()) 1869 InitList = CheckInitList.getFullyStructuredList(); 1870 1871 return CheckInitList.HadError(); 1872} 1873 1874//===----------------------------------------------------------------------===// 1875// Initialization entity 1876//===----------------------------------------------------------------------===// 1877 1878InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index, 1879 const InitializedEntity &Parent) 1880 : Kind(EK_ArrayOrVectorElement), Parent(&Parent), Index(Index) 1881{ 1882 if (isa<ArrayType>(Parent.TL.getType())) { 1883 TL = cast<ArrayTypeLoc>(Parent.TL).getElementLoc(); 1884 return; 1885 } 1886 1887 // FIXME: should be able to get type location information for vectors, too. 1888 1889 QualType T; 1890 if (const ArrayType *AT = Context.getAsArrayType(Parent.TL.getType())) 1891 T = AT->getElementType(); 1892 else 1893 T = Parent.TL.getType()->getAs<VectorType>()->getElementType(); 1894 1895 // FIXME: Once we've gone through the effort to create the fake 1896 // TypeSourceInfo, should we cache it somewhere? (If not, we "leak" it). 1897 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(T); 1898 DI->getTypeLoc().initialize(Parent.TL.getSourceRange().getBegin()); 1899 TL = DI->getTypeLoc(); 1900} 1901 1902void InitializedEntity::InitDeclLoc() { 1903 assert((Kind == EK_Variable || Kind == EK_Parameter || Kind == EK_Member) && 1904 "InitDeclLoc cannot be used with non-declaration entities."); 1905 1906 if (TypeSourceInfo *DI = VariableOrMember->getTypeSourceInfo()) { 1907 TL = DI->getTypeLoc(); 1908 return; 1909 } 1910 1911 // FIXME: Once we've gone through the effort to create the fake 1912 // TypeSourceInfo, should we cache it in the declaration? 1913 // (If not, we "leak" it). 1914 TypeSourceInfo *DI = VariableOrMember->getASTContext() 1915 .CreateTypeSourceInfo(VariableOrMember->getType()); 1916 DI->getTypeLoc().initialize(VariableOrMember->getLocation()); 1917 TL = DI->getTypeLoc(); 1918} 1919 1920InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context, 1921 CXXBaseSpecifier *Base) 1922{ 1923 InitializedEntity Result; 1924 Result.Kind = EK_Base; 1925 Result.Base = Base; 1926 // FIXME: CXXBaseSpecifier should store a TypeLoc. 1927 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Base->getType()); 1928 DI->getTypeLoc().initialize(Base->getSourceRange().getBegin()); 1929 Result.TL = DI->getTypeLoc(); 1930 return Result; 1931} 1932 1933DeclarationName InitializedEntity::getName() const { 1934 switch (getKind()) { 1935 case EK_Variable: 1936 case EK_Parameter: 1937 case EK_Member: 1938 return VariableOrMember->getDeclName(); 1939 1940 case EK_Result: 1941 case EK_Exception: 1942 case EK_New: 1943 case EK_Temporary: 1944 case EK_Base: 1945 case EK_ArrayOrVectorElement: 1946 return DeclarationName(); 1947 } 1948 1949 // Silence GCC warning 1950 return DeclarationName(); 1951} 1952 1953DeclaratorDecl *InitializedEntity::getDecl() const { 1954 switch (getKind()) { 1955 case EK_Variable: 1956 case EK_Parameter: 1957 case EK_Member: 1958 return VariableOrMember; 1959 1960 case EK_Result: 1961 case EK_Exception: 1962 case EK_New: 1963 case EK_Temporary: 1964 case EK_Base: 1965 case EK_ArrayOrVectorElement: 1966 return 0; 1967 } 1968 1969 // Silence GCC warning 1970 return 0; 1971} 1972 1973//===----------------------------------------------------------------------===// 1974// Initialization sequence 1975//===----------------------------------------------------------------------===// 1976 1977void InitializationSequence::Step::Destroy() { 1978 switch (Kind) { 1979 case SK_ResolveAddressOfOverloadedFunction: 1980 case SK_CastDerivedToBaseRValue: 1981 case SK_CastDerivedToBaseLValue: 1982 case SK_BindReference: 1983 case SK_BindReferenceToTemporary: 1984 case SK_UserConversion: 1985 case SK_QualificationConversionRValue: 1986 case SK_QualificationConversionLValue: 1987 case SK_ListInitialization: 1988 case SK_ConstructorInitialization: 1989 case SK_ZeroInitialization: 1990 case SK_CAssignment: 1991 case SK_StringInit: 1992 break; 1993 1994 case SK_ConversionSequence: 1995 delete ICS; 1996 } 1997} 1998 1999void InitializationSequence::AddAddressOverloadResolutionStep( 2000 FunctionDecl *Function) { 2001 Step S; 2002 S.Kind = SK_ResolveAddressOfOverloadedFunction; 2003 S.Type = Function->getType(); 2004 S.Function = Function; 2005 Steps.push_back(S); 2006} 2007 2008void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType, 2009 bool IsLValue) { 2010 Step S; 2011 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue; 2012 S.Type = BaseType; 2013 Steps.push_back(S); 2014} 2015 2016void InitializationSequence::AddReferenceBindingStep(QualType T, 2017 bool BindingTemporary) { 2018 Step S; 2019 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference; 2020 S.Type = T; 2021 Steps.push_back(S); 2022} 2023 2024void InitializationSequence::AddUserConversionStep(FunctionDecl *Function, 2025 QualType T) { 2026 Step S; 2027 S.Kind = SK_UserConversion; 2028 S.Type = T; 2029 S.Function = Function; 2030 Steps.push_back(S); 2031} 2032 2033void InitializationSequence::AddQualificationConversionStep(QualType Ty, 2034 bool IsLValue) { 2035 Step S; 2036 S.Kind = IsLValue? SK_QualificationConversionLValue 2037 : SK_QualificationConversionRValue; 2038 S.Type = Ty; 2039 Steps.push_back(S); 2040} 2041 2042void InitializationSequence::AddConversionSequenceStep( 2043 const ImplicitConversionSequence &ICS, 2044 QualType T) { 2045 Step S; 2046 S.Kind = SK_ConversionSequence; 2047 S.Type = T; 2048 S.ICS = new ImplicitConversionSequence(ICS); 2049 Steps.push_back(S); 2050} 2051 2052void InitializationSequence::AddListInitializationStep(QualType T) { 2053 Step S; 2054 S.Kind = SK_ListInitialization; 2055 S.Type = T; 2056 Steps.push_back(S); 2057} 2058 2059void 2060InitializationSequence::AddConstructorInitializationStep( 2061 CXXConstructorDecl *Constructor, 2062 QualType T) { 2063 Step S; 2064 S.Kind = SK_ConstructorInitialization; 2065 S.Type = T; 2066 S.Function = Constructor; 2067 Steps.push_back(S); 2068} 2069 2070void InitializationSequence::AddZeroInitializationStep(QualType T) { 2071 Step S; 2072 S.Kind = SK_ZeroInitialization; 2073 S.Type = T; 2074 Steps.push_back(S); 2075} 2076 2077void InitializationSequence::AddCAssignmentStep(QualType T) { 2078 Step S; 2079 S.Kind = SK_CAssignment; 2080 S.Type = T; 2081 Steps.push_back(S); 2082} 2083 2084void InitializationSequence::AddStringInitStep(QualType T) { 2085 Step S; 2086 S.Kind = SK_StringInit; 2087 S.Type = T; 2088 Steps.push_back(S); 2089} 2090 2091void InitializationSequence::SetOverloadFailure(FailureKind Failure, 2092 OverloadingResult Result) { 2093 SequenceKind = FailedSequence; 2094 this->Failure = Failure; 2095 this->FailedOverloadResult = Result; 2096} 2097 2098//===----------------------------------------------------------------------===// 2099// Attempt initialization 2100//===----------------------------------------------------------------------===// 2101 2102/// \brief Attempt list initialization (C++0x [dcl.init.list]) 2103static void TryListInitialization(Sema &S, 2104 const InitializedEntity &Entity, 2105 const InitializationKind &Kind, 2106 InitListExpr *InitList, 2107 InitializationSequence &Sequence) { 2108 // FIXME: We only perform rudimentary checking of list 2109 // initializations at this point, then assume that any list 2110 // initialization of an array, aggregate, or scalar will be 2111 // well-formed. We we actually "perform" list initialization, we'll 2112 // do all of the necessary checking. C++0x initializer lists will 2113 // force us to perform more checking here. 2114 Sequence.setSequenceKind(InitializationSequence::ListInitialization); 2115 2116 QualType DestType = Entity.getType().getType(); 2117 2118 // C++ [dcl.init]p13: 2119 // If T is a scalar type, then a declaration of the form 2120 // 2121 // T x = { a }; 2122 // 2123 // is equivalent to 2124 // 2125 // T x = a; 2126 if (DestType->isScalarType()) { 2127 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) { 2128 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar); 2129 return; 2130 } 2131 2132 // Assume scalar initialization from a single value works. 2133 } else if (DestType->isAggregateType()) { 2134 // Assume aggregate initialization works. 2135 } else if (DestType->isVectorType()) { 2136 // Assume vector initialization works. 2137 } else if (DestType->isReferenceType()) { 2138 // FIXME: C++0x defines behavior for this. 2139 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList); 2140 return; 2141 } else if (DestType->isRecordType()) { 2142 // FIXME: C++0x defines behavior for this 2143 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType); 2144 } 2145 2146 // Add a general "list initialization" step. 2147 Sequence.AddListInitializationStep(DestType); 2148} 2149 2150/// \brief Try a reference initialization that involves calling a conversion 2151/// function. 2152/// 2153/// FIXME: look intos DRs 656, 896 2154static OverloadingResult TryRefInitWithConversionFunction(Sema &S, 2155 const InitializedEntity &Entity, 2156 const InitializationKind &Kind, 2157 Expr *Initializer, 2158 bool AllowRValues, 2159 InitializationSequence &Sequence) { 2160 QualType DestType = Entity.getType().getType(); 2161 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType(); 2162 QualType T1 = cv1T1.getUnqualifiedType(); 2163 QualType cv2T2 = Initializer->getType(); 2164 QualType T2 = cv2T2.getUnqualifiedType(); 2165 2166 bool DerivedToBase; 2167 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(), 2168 T1, T2, DerivedToBase) && 2169 "Must have incompatible references when binding via conversion"); 2170 (void)DerivedToBase; 2171 2172 // Build the candidate set directly in the initialization sequence 2173 // structure, so that it will persist if we fail. 2174 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 2175 CandidateSet.clear(); 2176 2177 // Determine whether we are allowed to call explicit constructors or 2178 // explicit conversion operators. 2179 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct; 2180 2181 const RecordType *T1RecordType = 0; 2182 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) { 2183 // The type we're converting to is a class type. Enumerate its constructors 2184 // to see if there is a suitable conversion. 2185 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl()); 2186 2187 DeclarationName ConstructorName 2188 = S.Context.DeclarationNames.getCXXConstructorName( 2189 S.Context.getCanonicalType(T1).getUnqualifiedType()); 2190 DeclContext::lookup_iterator Con, ConEnd; 2191 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName); 2192 Con != ConEnd; ++Con) { 2193 // Find the constructor (which may be a template). 2194 CXXConstructorDecl *Constructor = 0; 2195 FunctionTemplateDecl *ConstructorTmpl 2196 = dyn_cast<FunctionTemplateDecl>(*Con); 2197 if (ConstructorTmpl) 2198 Constructor = cast<CXXConstructorDecl>( 2199 ConstructorTmpl->getTemplatedDecl()); 2200 else 2201 Constructor = cast<CXXConstructorDecl>(*Con); 2202 2203 if (!Constructor->isInvalidDecl() && 2204 Constructor->isConvertingConstructor(AllowExplicit)) { 2205 if (ConstructorTmpl) 2206 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0, 2207 &Initializer, 1, CandidateSet); 2208 else 2209 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet); 2210 } 2211 } 2212 } 2213 2214 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) { 2215 // The type we're converting from is a class type, enumerate its conversion 2216 // functions. 2217 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl()); 2218 2219 // Determine the type we are converting to. If we are allowed to 2220 // convert to an rvalue, take the type that the destination type 2221 // refers to. 2222 QualType ToType = AllowRValues? cv1T1 : DestType; 2223 2224 const UnresolvedSet *Conversions 2225 = T2RecordDecl->getVisibleConversionFunctions(); 2226 for (UnresolvedSet::iterator I = Conversions->begin(), 2227 E = Conversions->end(); 2228 I != E; ++I) { 2229 NamedDecl *D = *I; 2230 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 2231 if (isa<UsingShadowDecl>(D)) 2232 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2233 2234 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 2235 CXXConversionDecl *Conv; 2236 if (ConvTemplate) 2237 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 2238 else 2239 Conv = cast<CXXConversionDecl>(*I); 2240 2241 // If the conversion function doesn't return a reference type, 2242 // it can't be considered for this conversion unless we're allowed to 2243 // consider rvalues. 2244 // FIXME: Do we need to make sure that we only consider conversion 2245 // candidates with reference-compatible results? That might be needed to 2246 // break recursion. 2247 if ((AllowExplicit || !Conv->isExplicit()) && 2248 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){ 2249 if (ConvTemplate) 2250 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer, 2251 ToType, CandidateSet); 2252 else 2253 S.AddConversionCandidate(Conv, ActingDC, Initializer, cv1T1, 2254 CandidateSet); 2255 } 2256 } 2257 } 2258 2259 SourceLocation DeclLoc = Initializer->getLocStart(); 2260 2261 // Perform overload resolution. If it fails, return the failed result. 2262 OverloadCandidateSet::iterator Best; 2263 if (OverloadingResult Result 2264 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) 2265 return Result; 2266 2267 FunctionDecl *Function = Best->Function; 2268 2269 // Compute the returned type of the conversion. 2270 if (isa<CXXConversionDecl>(Function)) 2271 T2 = Function->getResultType(); 2272 else 2273 T2 = cv1T1; 2274 2275 // Add the user-defined conversion step. 2276 Sequence.AddUserConversionStep(Function, T2.getNonReferenceType()); 2277 2278 // Determine whether we need to perform derived-to-base or 2279 // cv-qualification adjustments. 2280 bool NewDerivedToBase = false; 2281 Sema::ReferenceCompareResult NewRefRelationship 2282 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(), 2283 NewDerivedToBase); 2284 assert(NewRefRelationship != Sema::Ref_Incompatible && 2285 "Overload resolution picked a bad conversion function"); 2286 (void)NewRefRelationship; 2287 if (NewDerivedToBase) 2288 Sequence.AddDerivedToBaseCastStep( 2289 S.Context.getQualifiedType(T1, 2290 T2.getNonReferenceType().getQualifiers()), 2291 /*isLValue=*/true); 2292 2293 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers()) 2294 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType()); 2295 2296 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType()); 2297 return OR_Success; 2298} 2299 2300/// \brief Attempt reference initialization (C++0x [dcl.init.list]) 2301static void TryReferenceInitialization(Sema &S, 2302 const InitializedEntity &Entity, 2303 const InitializationKind &Kind, 2304 Expr *Initializer, 2305 InitializationSequence &Sequence) { 2306 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding); 2307 2308 QualType DestType = Entity.getType().getType(); 2309 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType(); 2310 QualType T1 = cv1T1.getUnqualifiedType(); 2311 QualType cv2T2 = Initializer->getType(); 2312 QualType T2 = cv2T2.getUnqualifiedType(); 2313 SourceLocation DeclLoc = Initializer->getLocStart(); 2314 2315 // If the initializer is the address of an overloaded function, try 2316 // to resolve the overloaded function. If all goes well, T2 is the 2317 // type of the resulting function. 2318 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 2319 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer, 2320 T1, 2321 false); 2322 if (!Fn) { 2323 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 2324 return; 2325 } 2326 2327 Sequence.AddAddressOverloadResolutionStep(Fn); 2328 cv2T2 = Fn->getType(); 2329 T2 = cv2T2.getUnqualifiedType(); 2330 } 2331 2332 // FIXME: Rvalue references 2333 bool ForceRValue = false; 2334 2335 // Compute some basic properties of the types and the initializer. 2336 bool isLValueRef = DestType->isLValueReferenceType(); 2337 bool isRValueRef = !isLValueRef; 2338 bool DerivedToBase = false; 2339 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression : 2340 Initializer->isLvalue(S.Context); 2341 Sema::ReferenceCompareResult RefRelationship 2342 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase); 2343 2344 // C++0x [dcl.init.ref]p5: 2345 // A reference to type "cv1 T1" is initialized by an expression of type 2346 // "cv2 T2" as follows: 2347 // 2348 // - If the reference is an lvalue reference and the initializer 2349 // expression 2350 OverloadingResult ConvOvlResult = OR_Success; 2351 if (isLValueRef) { 2352 if (InitLvalue == Expr::LV_Valid && 2353 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 2354 // - is an lvalue (but is not a bit-field), and "cv1 T1" is 2355 // reference-compatible with "cv2 T2," or 2356 // 2357 // Per C++ [over.best.ics]p2, we ignore whether the lvalue is a 2358 // bit-field when we're determining whether the reference initialization 2359 // can occur. This property will be checked by PerformInitialization. 2360 if (DerivedToBase) 2361 Sequence.AddDerivedToBaseCastStep( 2362 S.Context.getQualifiedType(T1, cv2T2.getQualifiers()), 2363 /*isLValue=*/true); 2364 if (cv1T1.getQualifiers() != cv2T2.getQualifiers()) 2365 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true); 2366 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/false); 2367 return; 2368 } 2369 2370 // - has a class type (i.e., T2 is a class type), where T1 is not 2371 // reference-related to T2, and can be implicitly converted to an 2372 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible 2373 // with "cv3 T3" (this conversion is selected by enumerating the 2374 // applicable conversion functions (13.3.1.6) and choosing the best 2375 // one through overload resolution (13.3)), 2376 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) { 2377 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind, 2378 Initializer, 2379 /*AllowRValues=*/false, 2380 Sequence); 2381 if (ConvOvlResult == OR_Success) 2382 return; 2383 } 2384 } 2385 2386 // - Otherwise, the reference shall be an lvalue reference to a 2387 // non-volatile const type (i.e., cv1 shall be const), or the reference 2388 // shall be an rvalue reference and the initializer expression shall 2389 // be an rvalue. 2390 if (!((isLValueRef && cv1T1.getCVRQualifiers() == Qualifiers::Const) || 2391 (isRValueRef && InitLvalue != Expr::LV_Valid))) { 2392 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) 2393 Sequence.SetOverloadFailure( 2394 InitializationSequence::FK_ReferenceInitOverloadFailed, 2395 ConvOvlResult); 2396 else if (isLValueRef) 2397 Sequence.SetFailed(InitLvalue == Expr::LV_Valid 2398 ? (RefRelationship == Sema::Ref_Related 2399 ? InitializationSequence::FK_ReferenceInitDropsQualifiers 2400 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated) 2401 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary); 2402 else 2403 Sequence.SetFailed( 2404 InitializationSequence::FK_RValueReferenceBindingToLValue); 2405 2406 return; 2407 } 2408 2409 // - If T1 and T2 are class types and 2410 if (T1->isRecordType() && T2->isRecordType()) { 2411 // - the initializer expression is an rvalue and "cv1 T1" is 2412 // reference-compatible with "cv2 T2", or 2413 if (InitLvalue != Expr::LV_Valid && 2414 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 2415 if (DerivedToBase) 2416 Sequence.AddDerivedToBaseCastStep( 2417 S.Context.getQualifiedType(T1, cv2T2.getQualifiers()), 2418 /*isLValue=*/false); 2419 if (cv1T1.getQualifiers() != cv2T2.getQualifiers()) 2420 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false); 2421 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true); 2422 return; 2423 } 2424 2425 // - T1 is not reference-related to T2 and the initializer expression 2426 // can be implicitly converted to an rvalue of type "cv3 T3" (this 2427 // conversion is selected by enumerating the applicable conversion 2428 // functions (13.3.1.6) and choosing the best one through overload 2429 // resolution (13.3)), 2430 if (RefRelationship == Sema::Ref_Incompatible) { 2431 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, 2432 Kind, Initializer, 2433 /*AllowRValues=*/true, 2434 Sequence); 2435 if (ConvOvlResult) 2436 Sequence.SetOverloadFailure( 2437 InitializationSequence::FK_ReferenceInitOverloadFailed, 2438 ConvOvlResult); 2439 2440 return; 2441 } 2442 2443 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); 2444 return; 2445 } 2446 2447 // - If the initializer expression is an rvalue, with T2 an array type, 2448 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference 2449 // is bound to the object represented by the rvalue (see 3.10). 2450 // FIXME: How can an array type be reference-compatible with anything? 2451 // Don't we mean the element types of T1 and T2? 2452 2453 // - Otherwise, a temporary of type “cv1 T1” is created and initialized 2454 // from the initializer expression using the rules for a non-reference 2455 // copy initialization (8.5). The reference is then bound to the 2456 // temporary. [...] 2457 // Determine whether we are allowed to call explicit constructors or 2458 // explicit conversion operators. 2459 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct); 2460 ImplicitConversionSequence ICS 2461 = S.TryImplicitConversion(Initializer, cv1T1, 2462 /*SuppressUserConversions=*/false, AllowExplicit, 2463 /*ForceRValue=*/false, 2464 /*FIXME:InOverloadResolution=*/false, 2465 /*UserCast=*/Kind.isExplicitCast()); 2466 2467 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) { 2468 // FIXME: Use the conversion function set stored in ICS to turn 2469 // this into an overloading ambiguity diagnostic. However, we need 2470 // to keep that set as an OverloadCandidateSet rather than as some 2471 // other kind of set. 2472 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) 2473 Sequence.SetOverloadFailure( 2474 InitializationSequence::FK_ReferenceInitOverloadFailed, 2475 ConvOvlResult); 2476 else 2477 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed); 2478 return; 2479 } 2480 2481 // [...] If T1 is reference-related to T2, cv1 must be the 2482 // same cv-qualification as, or greater cv-qualification 2483 // than, cv2; otherwise, the program is ill-formed. 2484 if (RefRelationship == Sema::Ref_Related && 2485 !cv1T1.isAtLeastAsQualifiedAs(cv2T2)) { 2486 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); 2487 return; 2488 } 2489 2490 // Perform the actual conversion. 2491 Sequence.AddConversionSequenceStep(ICS, cv1T1); 2492 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true); 2493 return; 2494} 2495 2496/// \brief Attempt character array initialization from a string literal 2497/// (C++ [dcl.init.string], C99 6.7.8). 2498static void TryStringLiteralInitialization(Sema &S, 2499 const InitializedEntity &Entity, 2500 const InitializationKind &Kind, 2501 Expr *Initializer, 2502 InitializationSequence &Sequence) { 2503 Sequence.setSequenceKind(InitializationSequence::StringInit); 2504 Sequence.AddStringInitStep(Entity.getType().getType()); 2505} 2506 2507/// \brief Attempt initialization by constructor (C++ [dcl.init]), which 2508/// enumerates the constructors of the initialized entity and performs overload 2509/// resolution to select the best. 2510static void TryConstructorInitialization(Sema &S, 2511 const InitializedEntity &Entity, 2512 const InitializationKind &Kind, 2513 Expr **Args, unsigned NumArgs, 2514 QualType DestType, 2515 InitializationSequence &Sequence) { 2516 if (Kind.getKind() == InitializationKind::IK_Copy) 2517 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion); 2518 else 2519 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization); 2520 2521 // Build the candidate set directly in the initialization sequence 2522 // structure, so that it will persist if we fail. 2523 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 2524 CandidateSet.clear(); 2525 2526 // Determine whether we are allowed to call explicit constructors or 2527 // explicit conversion operators. 2528 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct || 2529 Kind.getKind() == InitializationKind::IK_Value || 2530 Kind.getKind() == InitializationKind::IK_Default); 2531 2532 // The type we're converting to is a class type. Enumerate its constructors 2533 // to see if one is suitable. 2534 const RecordType *DestRecordType = DestType->getAs<RecordType>(); 2535 assert(DestRecordType && "Constructor initialization requires record type"); 2536 CXXRecordDecl *DestRecordDecl 2537 = cast<CXXRecordDecl>(DestRecordType->getDecl()); 2538 2539 DeclarationName ConstructorName 2540 = S.Context.DeclarationNames.getCXXConstructorName( 2541 S.Context.getCanonicalType(DestType).getUnqualifiedType()); 2542 DeclContext::lookup_iterator Con, ConEnd; 2543 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName); 2544 Con != ConEnd; ++Con) { 2545 // Find the constructor (which may be a template). 2546 CXXConstructorDecl *Constructor = 0; 2547 FunctionTemplateDecl *ConstructorTmpl 2548 = dyn_cast<FunctionTemplateDecl>(*Con); 2549 if (ConstructorTmpl) 2550 Constructor = cast<CXXConstructorDecl>( 2551 ConstructorTmpl->getTemplatedDecl()); 2552 else 2553 Constructor = cast<CXXConstructorDecl>(*Con); 2554 2555 if (!Constructor->isInvalidDecl() && 2556 (AllowExplicit || !Constructor->isExplicit())) { 2557 if (ConstructorTmpl) 2558 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0, 2559 Args, NumArgs, CandidateSet); 2560 else 2561 S.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet); 2562 } 2563 } 2564 2565 SourceLocation DeclLoc = Kind.getLocation(); 2566 2567 // Perform overload resolution. If it fails, return the failed result. 2568 OverloadCandidateSet::iterator Best; 2569 if (OverloadingResult Result 2570 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) { 2571 Sequence.SetOverloadFailure( 2572 InitializationSequence::FK_ConstructorOverloadFailed, 2573 Result); 2574 return; 2575 } 2576 2577 // Add the constructor initialization step. Any cv-qualification conversion is 2578 // subsumed by the initialization. 2579 if (Kind.getKind() == InitializationKind::IK_Copy) { 2580 Sequence.AddUserConversionStep(Best->Function, DestType); 2581 } else { 2582 Sequence.AddConstructorInitializationStep( 2583 cast<CXXConstructorDecl>(Best->Function), 2584 DestType); 2585 } 2586} 2587 2588/// \brief Attempt value initialization (C++ [dcl.init]p7). 2589static void TryValueInitialization(Sema &S, 2590 const InitializedEntity &Entity, 2591 const InitializationKind &Kind, 2592 InitializationSequence &Sequence) { 2593 // C++ [dcl.init]p5: 2594 // 2595 // To value-initialize an object of type T means: 2596 QualType T = Entity.getType().getType(); 2597 2598 // -- if T is an array type, then each element is value-initialized; 2599 while (const ArrayType *AT = S.Context.getAsArrayType(T)) 2600 T = AT->getElementType(); 2601 2602 if (const RecordType *RT = T->getAs<RecordType>()) { 2603 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 2604 // -- if T is a class type (clause 9) with a user-declared 2605 // constructor (12.1), then the default constructor for T is 2606 // called (and the initialization is ill-formed if T has no 2607 // accessible default constructor); 2608 // 2609 // FIXME: we really want to refer to a single subobject of the array, 2610 // but Entity doesn't have a way to capture that (yet). 2611 if (ClassDecl->hasUserDeclaredConstructor()) 2612 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence); 2613 2614 // -- if T is a (possibly cv-qualified) non-union class type 2615 // without a user-provided constructor, then the object is 2616 // zero-initialized and, if T’s implicitly-declared default 2617 // constructor is non-trivial, that constructor is called. 2618 if ((ClassDecl->getTagKind() == TagDecl::TK_class || 2619 ClassDecl->getTagKind() == TagDecl::TK_struct) && 2620 !ClassDecl->hasTrivialConstructor()) { 2621 Sequence.AddZeroInitializationStep(Entity.getType().getType()); 2622 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence); 2623 } 2624 } 2625 } 2626 2627 Sequence.AddZeroInitializationStep(Entity.getType().getType()); 2628 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization); 2629} 2630 2631/// \brief Attempt default initialization (C++ [dcl.init]p6). 2632static void TryDefaultInitialization(Sema &S, 2633 const InitializedEntity &Entity, 2634 const InitializationKind &Kind, 2635 InitializationSequence &Sequence) { 2636 assert(Kind.getKind() == InitializationKind::IK_Default); 2637 2638 // C++ [dcl.init]p6: 2639 // To default-initialize an object of type T means: 2640 // - if T is an array type, each element is default-initialized; 2641 QualType DestType = Entity.getType().getType(); 2642 while (const ArrayType *Array = S.Context.getAsArrayType(DestType)) 2643 DestType = Array->getElementType(); 2644 2645 // - if T is a (possibly cv-qualified) class type (Clause 9), the default 2646 // constructor for T is called (and the initialization is ill-formed if 2647 // T has no accessible default constructor); 2648 if (DestType->isRecordType()) { 2649 // FIXME: If a program calls for the default initialization of an object of 2650 // a const-qualified type T, T shall be a class type with a user-provided 2651 // default constructor. 2652 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, 2653 Sequence); 2654 } 2655 2656 // - otherwise, no initialization is performed. 2657 Sequence.setSequenceKind(InitializationSequence::NoInitialization); 2658 2659 // If a program calls for the default initialization of an object of 2660 // a const-qualified type T, T shall be a class type with a user-provided 2661 // default constructor. 2662 if (DestType.isConstQualified()) 2663 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); 2664} 2665 2666/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]), 2667/// which enumerates all conversion functions and performs overload resolution 2668/// to select the best. 2669static void TryUserDefinedConversion(Sema &S, 2670 const InitializedEntity &Entity, 2671 const InitializationKind &Kind, 2672 Expr *Initializer, 2673 InitializationSequence &Sequence) { 2674 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion); 2675 2676 QualType DestType = Entity.getType().getType(); 2677 assert(!DestType->isReferenceType() && "References are handled elsewhere"); 2678 QualType SourceType = Initializer->getType(); 2679 assert((DestType->isRecordType() || SourceType->isRecordType()) && 2680 "Must have a class type to perform a user-defined conversion"); 2681 2682 // Build the candidate set directly in the initialization sequence 2683 // structure, so that it will persist if we fail. 2684 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 2685 CandidateSet.clear(); 2686 2687 // Determine whether we are allowed to call explicit constructors or 2688 // explicit conversion operators. 2689 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct; 2690 2691 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) { 2692 // The type we're converting to is a class type. Enumerate its constructors 2693 // to see if there is a suitable conversion. 2694 CXXRecordDecl *DestRecordDecl 2695 = cast<CXXRecordDecl>(DestRecordType->getDecl()); 2696 2697 DeclarationName ConstructorName 2698 = S.Context.DeclarationNames.getCXXConstructorName( 2699 S.Context.getCanonicalType(DestType).getUnqualifiedType()); 2700 DeclContext::lookup_iterator Con, ConEnd; 2701 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName); 2702 Con != ConEnd; ++Con) { 2703 // Find the constructor (which may be a template). 2704 CXXConstructorDecl *Constructor = 0; 2705 FunctionTemplateDecl *ConstructorTmpl 2706 = dyn_cast<FunctionTemplateDecl>(*Con); 2707 if (ConstructorTmpl) 2708 Constructor = cast<CXXConstructorDecl>( 2709 ConstructorTmpl->getTemplatedDecl()); 2710 else 2711 Constructor = cast<CXXConstructorDecl>(*Con); 2712 2713 if (!Constructor->isInvalidDecl() && 2714 Constructor->isConvertingConstructor(AllowExplicit)) { 2715 if (ConstructorTmpl) 2716 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0, 2717 &Initializer, 1, CandidateSet); 2718 else 2719 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet); 2720 } 2721 } 2722 } 2723 2724 SourceLocation DeclLoc = Initializer->getLocStart(); 2725 2726 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) { 2727 // The type we're converting from is a class type, enumerate its conversion 2728 // functions. 2729 2730 // Try to force the type to be complete before enumerating the conversion 2731 // functions; it's okay if this fails, though. 2732 S.RequireCompleteType(DeclLoc, SourceType, 0); 2733 2734 CXXRecordDecl *SourceRecordDecl 2735 = cast<CXXRecordDecl>(SourceRecordType->getDecl()); 2736 2737 const UnresolvedSet *Conversions 2738 = SourceRecordDecl->getVisibleConversionFunctions(); 2739 for (UnresolvedSet::iterator I = Conversions->begin(), 2740 E = Conversions->end(); 2741 I != E; ++I) { 2742 NamedDecl *D = *I; 2743 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 2744 if (isa<UsingShadowDecl>(D)) 2745 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2746 2747 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 2748 CXXConversionDecl *Conv; 2749 if (ConvTemplate) 2750 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 2751 else 2752 Conv = cast<CXXConversionDecl>(*I); 2753 2754 if (AllowExplicit || !Conv->isExplicit()) { 2755 if (ConvTemplate) 2756 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer, 2757 DestType, CandidateSet); 2758 else 2759 S.AddConversionCandidate(Conv, ActingDC, Initializer, DestType, 2760 CandidateSet); 2761 } 2762 } 2763 } 2764 2765 // Perform overload resolution. If it fails, return the failed result. 2766 OverloadCandidateSet::iterator Best; 2767 if (OverloadingResult Result 2768 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) { 2769 Sequence.SetOverloadFailure( 2770 InitializationSequence::FK_UserConversionOverloadFailed, 2771 Result); 2772 return; 2773 } 2774 2775 FunctionDecl *Function = Best->Function; 2776 2777 if (isa<CXXConstructorDecl>(Function)) { 2778 // Add the user-defined conversion step. Any cv-qualification conversion is 2779 // subsumed by the initialization. 2780 Sequence.AddUserConversionStep(Function, DestType); 2781 return; 2782 } 2783 2784 // Add the user-defined conversion step that calls the conversion function. 2785 QualType ConvType = Function->getResultType().getNonReferenceType(); 2786 Sequence.AddUserConversionStep(Function, ConvType); 2787 2788 // If the conversion following the call to the conversion function is 2789 // interesting, add it as a separate step. 2790 if (Best->FinalConversion.First || Best->FinalConversion.Second || 2791 Best->FinalConversion.Third) { 2792 ImplicitConversionSequence ICS; 2793 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion; 2794 ICS.Standard = Best->FinalConversion; 2795 Sequence.AddConversionSequenceStep(ICS, DestType); 2796 } 2797} 2798 2799/// \brief Attempt an implicit conversion (C++ [conv]) converting from one 2800/// non-class type to another. 2801static void TryImplicitConversion(Sema &S, 2802 const InitializedEntity &Entity, 2803 const InitializationKind &Kind, 2804 Expr *Initializer, 2805 InitializationSequence &Sequence) { 2806 ImplicitConversionSequence ICS 2807 = S.TryImplicitConversion(Initializer, Entity.getType().getType(), 2808 /*SuppressUserConversions=*/true, 2809 /*AllowExplicit=*/false, 2810 /*ForceRValue=*/false, 2811 /*FIXME:InOverloadResolution=*/false, 2812 /*UserCast=*/Kind.isExplicitCast()); 2813 2814 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) { 2815 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed); 2816 return; 2817 } 2818 2819 Sequence.AddConversionSequenceStep(ICS, Entity.getType().getType()); 2820} 2821 2822InitializationSequence::InitializationSequence(Sema &S, 2823 const InitializedEntity &Entity, 2824 const InitializationKind &Kind, 2825 Expr **Args, 2826 unsigned NumArgs) { 2827 ASTContext &Context = S.Context; 2828 2829 // C++0x [dcl.init]p16: 2830 // The semantics of initializers are as follows. The destination type is 2831 // the type of the object or reference being initialized and the source 2832 // type is the type of the initializer expression. The source type is not 2833 // defined when the initializer is a braced-init-list or when it is a 2834 // parenthesized list of expressions. 2835 QualType DestType = Entity.getType().getType(); 2836 2837 if (DestType->isDependentType() || 2838 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) { 2839 SequenceKind = DependentSequence; 2840 return; 2841 } 2842 2843 QualType SourceType; 2844 Expr *Initializer = 0; 2845 if (NumArgs == 1) { 2846 Initializer = Args[0]; 2847 if (!isa<InitListExpr>(Initializer)) 2848 SourceType = Initializer->getType(); 2849 } 2850 2851 // - If the initializer is a braced-init-list, the object is 2852 // list-initialized (8.5.4). 2853 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) { 2854 TryListInitialization(S, Entity, Kind, InitList, *this); 2855 return; 2856 } 2857 2858 // - If the destination type is a reference type, see 8.5.3. 2859 if (DestType->isReferenceType()) { 2860 // C++0x [dcl.init.ref]p1: 2861 // A variable declared to be a T& or T&&, that is, "reference to type T" 2862 // (8.3.2), shall be initialized by an object, or function, of type T or 2863 // by an object that can be converted into a T. 2864 // (Therefore, multiple arguments are not permitted.) 2865 if (NumArgs != 1) 2866 SetFailed(FK_TooManyInitsForReference); 2867 else 2868 TryReferenceInitialization(S, Entity, Kind, Args[0], *this); 2869 return; 2870 } 2871 2872 // - If the destination type is an array of characters, an array of 2873 // char16_t, an array of char32_t, or an array of wchar_t, and the 2874 // initializer is a string literal, see 8.5.2. 2875 if (Initializer && IsStringInit(Initializer, DestType, Context)) { 2876 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this); 2877 return; 2878 } 2879 2880 // - If the initializer is (), the object is value-initialized. 2881 if (Kind.getKind() == InitializationKind::IK_Value || 2882 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) { 2883 TryValueInitialization(S, Entity, Kind, *this); 2884 return; 2885 } 2886 2887 // Handle default initialization. 2888 if (Kind.getKind() == InitializationKind::IK_Default){ 2889 TryDefaultInitialization(S, Entity, Kind, *this); 2890 return; 2891 } 2892 2893 // - Otherwise, if the destination type is an array, the program is 2894 // ill-formed. 2895 if (const ArrayType *AT = Context.getAsArrayType(DestType)) { 2896 if (AT->getElementType()->isAnyCharacterType()) 2897 SetFailed(FK_ArrayNeedsInitListOrStringLiteral); 2898 else 2899 SetFailed(FK_ArrayNeedsInitList); 2900 2901 return; 2902 } 2903 2904 // Handle initialization in C 2905 if (!S.getLangOptions().CPlusPlus) { 2906 setSequenceKind(CAssignment); 2907 AddCAssignmentStep(DestType); 2908 return; 2909 } 2910 2911 // - If the destination type is a (possibly cv-qualified) class type: 2912 if (DestType->isRecordType()) { 2913 // - If the initialization is direct-initialization, or if it is 2914 // copy-initialization where the cv-unqualified version of the 2915 // source type is the same class as, or a derived class of, the 2916 // class of the destination, constructors are considered. [...] 2917 if (Kind.getKind() == InitializationKind::IK_Direct || 2918 (Kind.getKind() == InitializationKind::IK_Copy && 2919 (Context.hasSameUnqualifiedType(SourceType, DestType) || 2920 S.IsDerivedFrom(SourceType, DestType)))) 2921 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs, 2922 Entity.getType().getType(), *this); 2923 // - Otherwise (i.e., for the remaining copy-initialization cases), 2924 // user-defined conversion sequences that can convert from the source 2925 // type to the destination type or (when a conversion function is 2926 // used) to a derived class thereof are enumerated as described in 2927 // 13.3.1.4, and the best one is chosen through overload resolution 2928 // (13.3). 2929 else 2930 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this); 2931 return; 2932 } 2933 2934 if (NumArgs > 1) { 2935 SetFailed(FK_TooManyInitsForScalar); 2936 return; 2937 } 2938 assert(NumArgs == 1 && "Zero-argument case handled above"); 2939 2940 // - Otherwise, if the source type is a (possibly cv-qualified) class 2941 // type, conversion functions are considered. 2942 if (!SourceType.isNull() && SourceType->isRecordType()) { 2943 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this); 2944 return; 2945 } 2946 2947 // - Otherwise, the initial value of the object being initialized is the 2948 // (possibly converted) value of the initializer expression. Standard 2949 // conversions (Clause 4) will be used, if necessary, to convert the 2950 // initializer expression to the cv-unqualified version of the 2951 // destination type; no user-defined conversions are considered. 2952 setSequenceKind(StandardConversion); 2953 TryImplicitConversion(S, Entity, Kind, Initializer, *this); 2954} 2955 2956InitializationSequence::~InitializationSequence() { 2957 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(), 2958 StepEnd = Steps.end(); 2959 Step != StepEnd; ++Step) 2960 Step->Destroy(); 2961} 2962 2963//===----------------------------------------------------------------------===// 2964// Perform initialization 2965//===----------------------------------------------------------------------===// 2966static Sema::AssignmentAction 2967getAssignmentAction(const InitializedEntity &Entity) { 2968 switch(Entity.getKind()) { 2969 case InitializedEntity::EK_Variable: 2970 case InitializedEntity::EK_New: 2971 return Sema::AA_Initializing; 2972 2973 case InitializedEntity::EK_Parameter: 2974 // FIXME: Can we tell when we're sending vs. passing? 2975 return Sema::AA_Passing; 2976 2977 case InitializedEntity::EK_Result: 2978 return Sema::AA_Returning; 2979 2980 case InitializedEntity::EK_Exception: 2981 case InitializedEntity::EK_Base: 2982 llvm_unreachable("No assignment action for C++-specific initialization"); 2983 break; 2984 2985 case InitializedEntity::EK_Temporary: 2986 // FIXME: Can we tell apart casting vs. converting? 2987 return Sema::AA_Casting; 2988 2989 case InitializedEntity::EK_Member: 2990 case InitializedEntity::EK_ArrayOrVectorElement: 2991 return Sema::AA_Initializing; 2992 } 2993 2994 return Sema::AA_Converting; 2995} 2996 2997static bool shouldBindAsTemporary(const InitializedEntity &Entity, 2998 bool IsCopy) { 2999 switch (Entity.getKind()) { 3000 case InitializedEntity::EK_Result: 3001 case InitializedEntity::EK_Exception: 3002 return !IsCopy; 3003 3004 case InitializedEntity::EK_New: 3005 case InitializedEntity::EK_Variable: 3006 case InitializedEntity::EK_Base: 3007 case InitializedEntity::EK_Member: 3008 case InitializedEntity::EK_ArrayOrVectorElement: 3009 return false; 3010 3011 case InitializedEntity::EK_Parameter: 3012 case InitializedEntity::EK_Temporary: 3013 return true; 3014 } 3015 3016 llvm_unreachable("missed an InitializedEntity kind?"); 3017} 3018 3019/// \brief If we need to perform an additional copy of the initialized object 3020/// for this kind of entity (e.g., the result of a function or an object being 3021/// thrown), make the copy. 3022static Sema::OwningExprResult CopyIfRequiredForEntity(Sema &S, 3023 const InitializedEntity &Entity, 3024 const InitializationKind &Kind, 3025 Sema::OwningExprResult CurInit) { 3026 SourceLocation Loc; 3027 3028 switch (Entity.getKind()) { 3029 case InitializedEntity::EK_Result: 3030 if (Entity.getType().getType()->isReferenceType()) 3031 return move(CurInit); 3032 Loc = Entity.getReturnLoc(); 3033 break; 3034 3035 case InitializedEntity::EK_Exception: 3036 Loc = Entity.getThrowLoc(); 3037 break; 3038 3039 case InitializedEntity::EK_Variable: 3040 if (Entity.getType().getType()->isReferenceType() || 3041 Kind.getKind() != InitializationKind::IK_Copy) 3042 return move(CurInit); 3043 Loc = Entity.getDecl()->getLocation(); 3044 break; 3045 3046 case InitializedEntity::EK_Parameter: 3047 // FIXME: Do we need this initialization for a parameter? 3048 return move(CurInit); 3049 3050 case InitializedEntity::EK_New: 3051 case InitializedEntity::EK_Temporary: 3052 case InitializedEntity::EK_Base: 3053 case InitializedEntity::EK_Member: 3054 case InitializedEntity::EK_ArrayOrVectorElement: 3055 // We don't need to copy for any of these initialized entities. 3056 return move(CurInit); 3057 } 3058 3059 Expr *CurInitExpr = (Expr *)CurInit.get(); 3060 CXXRecordDecl *Class = 0; 3061 if (const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>()) 3062 Class = cast<CXXRecordDecl>(Record->getDecl()); 3063 if (!Class) 3064 return move(CurInit); 3065 3066 // Perform overload resolution using the class's copy constructors. 3067 DeclarationName ConstructorName 3068 = S.Context.DeclarationNames.getCXXConstructorName( 3069 S.Context.getCanonicalType(S.Context.getTypeDeclType(Class))); 3070 DeclContext::lookup_iterator Con, ConEnd; 3071 OverloadCandidateSet CandidateSet; 3072 for (llvm::tie(Con, ConEnd) = Class->lookup(ConstructorName); 3073 Con != ConEnd; ++Con) { 3074 // Find the constructor (which may be a template). 3075 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con); 3076 if (!Constructor || Constructor->isInvalidDecl() || 3077 !Constructor->isCopyConstructor(S.Context)) 3078 continue; 3079 3080 S.AddOverloadCandidate(Constructor, &CurInitExpr, 1, CandidateSet); 3081 } 3082 3083 OverloadCandidateSet::iterator Best; 3084 switch (S.BestViableFunction(CandidateSet, Loc, Best)) { 3085 case OR_Success: 3086 break; 3087 3088 case OR_No_Viable_Function: 3089 S.Diag(Loc, diag::err_temp_copy_no_viable) 3090 << (int)Entity.getKind() << CurInitExpr->getType() 3091 << CurInitExpr->getSourceRange(); 3092 S.PrintOverloadCandidates(CandidateSet, false); 3093 return S.ExprError(); 3094 3095 case OR_Ambiguous: 3096 S.Diag(Loc, diag::err_temp_copy_ambiguous) 3097 << (int)Entity.getKind() << CurInitExpr->getType() 3098 << CurInitExpr->getSourceRange(); 3099 S.PrintOverloadCandidates(CandidateSet, true); 3100 return S.ExprError(); 3101 3102 case OR_Deleted: 3103 S.Diag(Loc, diag::err_temp_copy_deleted) 3104 << (int)Entity.getKind() << CurInitExpr->getType() 3105 << CurInitExpr->getSourceRange(); 3106 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here) 3107 << Best->Function->isDeleted(); 3108 return S.ExprError(); 3109 } 3110 3111 CurInit.release(); 3112 return S.BuildCXXConstructExpr(Loc, CurInitExpr->getType(), 3113 cast<CXXConstructorDecl>(Best->Function), 3114 /*Elidable=*/true, 3115 Sema::MultiExprArg(S, 3116 (void**)&CurInitExpr, 1)); 3117} 3118 3119Action::OwningExprResult 3120InitializationSequence::Perform(Sema &S, 3121 const InitializedEntity &Entity, 3122 const InitializationKind &Kind, 3123 Action::MultiExprArg Args, 3124 QualType *ResultType) { 3125 if (SequenceKind == FailedSequence) { 3126 unsigned NumArgs = Args.size(); 3127 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs); 3128 return S.ExprError(); 3129 } 3130 3131 if (SequenceKind == DependentSequence) { 3132 // If the declaration is a non-dependent, incomplete array type 3133 // that has an initializer, then its type will be completed once 3134 // the initializer is instantiated. 3135 if (ResultType && !Entity.getType().getType()->isDependentType() && 3136 Args.size() == 1) { 3137 QualType DeclType = Entity.getType().getType(); 3138 if (const IncompleteArrayType *ArrayT 3139 = S.Context.getAsIncompleteArrayType(DeclType)) { 3140 // FIXME: We don't currently have the ability to accurately 3141 // compute the length of an initializer list without 3142 // performing full type-checking of the initializer list 3143 // (since we have to determine where braces are implicitly 3144 // introduced and such). So, we fall back to making the array 3145 // type a dependently-sized array type with no specified 3146 // bound. 3147 if (isa<InitListExpr>((Expr *)Args.get()[0])) { 3148 SourceRange Brackets; 3149 // Scavange the location of the brackets from the entity, if we can. 3150 if (isa<IncompleteArrayTypeLoc>(Entity.getType())) { 3151 IncompleteArrayTypeLoc ArrayLoc 3152 = cast<IncompleteArrayTypeLoc>(Entity.getType()); 3153 Brackets = ArrayLoc.getBracketsRange(); 3154 } 3155 3156 *ResultType 3157 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(), 3158 /*NumElts=*/0, 3159 ArrayT->getSizeModifier(), 3160 ArrayT->getIndexTypeCVRQualifiers(), 3161 Brackets); 3162 } 3163 3164 } 3165 } 3166 3167 if (Kind.getKind() == InitializationKind::IK_Copy) 3168 return Sema::OwningExprResult(S, Args.release()[0]); 3169 3170 unsigned NumArgs = Args.size(); 3171 return S.Owned(new (S.Context) ParenListExpr(S.Context, 3172 SourceLocation(), 3173 (Expr **)Args.release(), 3174 NumArgs, 3175 SourceLocation())); 3176 } 3177 3178 if (SequenceKind == NoInitialization) 3179 return S.Owned((Expr *)0); 3180 3181 QualType DestType = Entity.getType().getType().getNonReferenceType(); 3182 if (ResultType) 3183 *ResultType = Entity.getType().getType(); 3184 3185 Sema::OwningExprResult CurInit = S.Owned((Expr *)0); 3186 3187 assert(!Steps.empty() && "Cannot have an empty initialization sequence"); 3188 3189 // For initialization steps that start with a single initializer, 3190 // grab the only argument out the Args and place it into the "current" 3191 // initializer. 3192 switch (Steps.front().Kind) { 3193 case SK_ResolveAddressOfOverloadedFunction: 3194 case SK_CastDerivedToBaseRValue: 3195 case SK_CastDerivedToBaseLValue: 3196 case SK_BindReference: 3197 case SK_BindReferenceToTemporary: 3198 case SK_UserConversion: 3199 case SK_QualificationConversionLValue: 3200 case SK_QualificationConversionRValue: 3201 case SK_ConversionSequence: 3202 case SK_ListInitialization: 3203 case SK_CAssignment: 3204 case SK_StringInit: 3205 assert(Args.size() == 1); 3206 CurInit = Sema::OwningExprResult(S, ((Expr **)(Args.get()))[0]->Retain()); 3207 if (CurInit.isInvalid()) 3208 return S.ExprError(); 3209 break; 3210 3211 case SK_ConstructorInitialization: 3212 case SK_ZeroInitialization: 3213 break; 3214 } 3215 3216 // Walk through the computed steps for the initialization sequence, 3217 // performing the specified conversions along the way. 3218 bool ConstructorInitRequiresZeroInit = false; 3219 for (step_iterator Step = step_begin(), StepEnd = step_end(); 3220 Step != StepEnd; ++Step) { 3221 if (CurInit.isInvalid()) 3222 return S.ExprError(); 3223 3224 Expr *CurInitExpr = (Expr *)CurInit.get(); 3225 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType(); 3226 3227 switch (Step->Kind) { 3228 case SK_ResolveAddressOfOverloadedFunction: 3229 // Overload resolution determined which function invoke; update the 3230 // initializer to reflect that choice. 3231 CurInit = S.FixOverloadedFunctionReference(move(CurInit), Step->Function); 3232 break; 3233 3234 case SK_CastDerivedToBaseRValue: 3235 case SK_CastDerivedToBaseLValue: { 3236 // We have a derived-to-base cast that produces either an rvalue or an 3237 // lvalue. Perform that cast. 3238 3239 // Casts to inaccessible base classes are allowed with C-style casts. 3240 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast(); 3241 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type, 3242 CurInitExpr->getLocStart(), 3243 CurInitExpr->getSourceRange(), 3244 IgnoreBaseAccess)) 3245 return S.ExprError(); 3246 3247 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type, 3248 CastExpr::CK_DerivedToBase, 3249 (Expr*)CurInit.release(), 3250 Step->Kind == SK_CastDerivedToBaseLValue)); 3251 break; 3252 } 3253 3254 case SK_BindReference: 3255 if (FieldDecl *BitField = CurInitExpr->getBitField()) { 3256 // References cannot bind to bit fields (C++ [dcl.init.ref]p5). 3257 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield) 3258 << Entity.getType().getType().isVolatileQualified() 3259 << BitField->getDeclName() 3260 << CurInitExpr->getSourceRange(); 3261 S.Diag(BitField->getLocation(), diag::note_bitfield_decl); 3262 return S.ExprError(); 3263 } 3264 3265 // Reference binding does not have any corresponding ASTs. 3266 3267 // Check exception specifications 3268 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType)) 3269 return S.ExprError(); 3270 break; 3271 3272 case SK_BindReferenceToTemporary: 3273 // Check exception specifications 3274 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType)) 3275 return S.ExprError(); 3276 3277 // FIXME: At present, we have no AST to describe when we need to make a 3278 // temporary to bind a reference to. We should. 3279 break; 3280 3281 case SK_UserConversion: { 3282 // We have a user-defined conversion that invokes either a constructor 3283 // or a conversion function. 3284 CastExpr::CastKind CastKind = CastExpr::CK_Unknown; 3285 bool IsCopy = false; 3286 if (CXXConstructorDecl *Constructor 3287 = dyn_cast<CXXConstructorDecl>(Step->Function)) { 3288 // Build a call to the selected constructor. 3289 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S); 3290 SourceLocation Loc = CurInitExpr->getLocStart(); 3291 CurInit.release(); // Ownership transferred into MultiExprArg, below. 3292 3293 // Determine the arguments required to actually perform the constructor 3294 // call. 3295 if (S.CompleteConstructorCall(Constructor, 3296 Sema::MultiExprArg(S, 3297 (void **)&CurInitExpr, 3298 1), 3299 Loc, ConstructorArgs)) 3300 return S.ExprError(); 3301 3302 // Build the an expression that constructs a temporary. 3303 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor, 3304 move_arg(ConstructorArgs)); 3305 if (CurInit.isInvalid()) 3306 return S.ExprError(); 3307 3308 CastKind = CastExpr::CK_ConstructorConversion; 3309 QualType Class = S.Context.getTypeDeclType(Constructor->getParent()); 3310 if (S.Context.hasSameUnqualifiedType(SourceType, Class) || 3311 S.IsDerivedFrom(SourceType, Class)) 3312 IsCopy = true; 3313 } else { 3314 // Build a call to the conversion function. 3315 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Step->Function); 3316 3317 // FIXME: Should we move this initialization into a separate 3318 // derived-to-base conversion? I believe the answer is "no", because 3319 // we don't want to turn off access control here for c-style casts. 3320 if (S.PerformObjectArgumentInitialization(CurInitExpr, Conversion)) 3321 return S.ExprError(); 3322 3323 // Do a little dance to make sure that CurInit has the proper 3324 // pointer. 3325 CurInit.release(); 3326 3327 // Build the actual call to the conversion function. 3328 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, Conversion)); 3329 if (CurInit.isInvalid() || !CurInit.get()) 3330 return S.ExprError(); 3331 3332 CastKind = CastExpr::CK_UserDefinedConversion; 3333 } 3334 3335 if (shouldBindAsTemporary(Entity, IsCopy)) 3336 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>()); 3337 3338 CurInitExpr = CurInit.takeAs<Expr>(); 3339 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(), 3340 CastKind, 3341 CurInitExpr, 3342 false)); 3343 3344 if (!IsCopy) 3345 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit)); 3346 break; 3347 } 3348 3349 case SK_QualificationConversionLValue: 3350 case SK_QualificationConversionRValue: 3351 // Perform a qualification conversion; these can never go wrong. 3352 S.ImpCastExprToType(CurInitExpr, Step->Type, 3353 CastExpr::CK_NoOp, 3354 Step->Kind == SK_QualificationConversionLValue); 3355 CurInit.release(); 3356 CurInit = S.Owned(CurInitExpr); 3357 break; 3358 3359 case SK_ConversionSequence: 3360 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, Sema::AA_Converting, 3361 false, false, *Step->ICS)) 3362 return S.ExprError(); 3363 3364 CurInit.release(); 3365 CurInit = S.Owned(CurInitExpr); 3366 break; 3367 3368 case SK_ListInitialization: { 3369 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr); 3370 QualType Ty = Step->Type; 3371 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty)) 3372 return S.ExprError(); 3373 3374 CurInit.release(); 3375 CurInit = S.Owned(InitList); 3376 break; 3377 } 3378 3379 case SK_ConstructorInitialization: { 3380 CXXConstructorDecl *Constructor 3381 = cast<CXXConstructorDecl>(Step->Function); 3382 3383 // Build a call to the selected constructor. 3384 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S); 3385 SourceLocation Loc = Kind.getLocation(); 3386 3387 // Determine the arguments required to actually perform the constructor 3388 // call. 3389 if (S.CompleteConstructorCall(Constructor, move(Args), 3390 Loc, ConstructorArgs)) 3391 return S.ExprError(); 3392 3393 // Build the an expression that constructs a temporary. 3394 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor, 3395 move_arg(ConstructorArgs), 3396 ConstructorInitRequiresZeroInit); 3397 if (CurInit.isInvalid()) 3398 return S.ExprError(); 3399 3400 bool Elidable 3401 = cast<CXXConstructExpr>((Expr *)CurInit.get())->isElidable(); 3402 if (shouldBindAsTemporary(Entity, Elidable)) 3403 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>()); 3404 3405 if (!Elidable) 3406 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit)); 3407 break; 3408 } 3409 3410 case SK_ZeroInitialization: { 3411 step_iterator NextStep = Step; 3412 ++NextStep; 3413 if (NextStep != StepEnd && 3414 NextStep->Kind == SK_ConstructorInitialization) { 3415 // The need for zero-initialization is recorded directly into 3416 // the call to the object's constructor within the next step. 3417 ConstructorInitRequiresZeroInit = true; 3418 } else if (Kind.getKind() == InitializationKind::IK_Value && 3419 S.getLangOptions().CPlusPlus && 3420 !Kind.isImplicitValueInit()) { 3421 CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type, 3422 Kind.getRange().getBegin(), 3423 Kind.getRange().getEnd())); 3424 } else { 3425 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type)); 3426 } 3427 break; 3428 } 3429 3430 case SK_CAssignment: { 3431 QualType SourceType = CurInitExpr->getType(); 3432 Sema::AssignConvertType ConvTy = 3433 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr); 3434 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(), 3435 Step->Type, SourceType, 3436 CurInitExpr, getAssignmentAction(Entity))) 3437 return S.ExprError(); 3438 3439 CurInit.release(); 3440 CurInit = S.Owned(CurInitExpr); 3441 break; 3442 } 3443 3444 case SK_StringInit: { 3445 QualType Ty = Step->Type; 3446 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S); 3447 break; 3448 } 3449 } 3450 } 3451 3452 return move(CurInit); 3453} 3454 3455//===----------------------------------------------------------------------===// 3456// Diagnose initialization failures 3457//===----------------------------------------------------------------------===// 3458bool InitializationSequence::Diagnose(Sema &S, 3459 const InitializedEntity &Entity, 3460 const InitializationKind &Kind, 3461 Expr **Args, unsigned NumArgs) { 3462 if (SequenceKind != FailedSequence) 3463 return false; 3464 3465 QualType DestType = Entity.getType().getType(); 3466 switch (Failure) { 3467 case FK_TooManyInitsForReference: 3468 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits) 3469 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd()); 3470 break; 3471 3472 case FK_ArrayNeedsInitList: 3473 case FK_ArrayNeedsInitListOrStringLiteral: 3474 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) 3475 << (Failure == FK_ArrayNeedsInitListOrStringLiteral); 3476 break; 3477 3478 case FK_AddressOfOverloadFailed: 3479 S.ResolveAddressOfOverloadedFunction(Args[0], 3480 DestType.getNonReferenceType(), 3481 true); 3482 break; 3483 3484 case FK_ReferenceInitOverloadFailed: 3485 case FK_UserConversionOverloadFailed: 3486 switch (FailedOverloadResult) { 3487 case OR_Ambiguous: 3488 if (Failure == FK_UserConversionOverloadFailed) 3489 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition) 3490 << Args[0]->getType() << DestType 3491 << Args[0]->getSourceRange(); 3492 else 3493 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous) 3494 << DestType << Args[0]->getType() 3495 << Args[0]->getSourceRange(); 3496 3497 S.PrintOverloadCandidates(FailedCandidateSet, true); 3498 break; 3499 3500 case OR_No_Viable_Function: 3501 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition) 3502 << Args[0]->getType() << DestType.getNonReferenceType() 3503 << Args[0]->getSourceRange(); 3504 S.PrintOverloadCandidates(FailedCandidateSet, false); 3505 break; 3506 3507 case OR_Deleted: { 3508 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function) 3509 << Args[0]->getType() << DestType.getNonReferenceType() 3510 << Args[0]->getSourceRange(); 3511 OverloadCandidateSet::iterator Best; 3512 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet, 3513 Kind.getLocation(), 3514 Best); 3515 if (Ovl == OR_Deleted) { 3516 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here) 3517 << Best->Function->isDeleted(); 3518 } else { 3519 llvm_unreachable("Inconsistent overload resolution?"); 3520 } 3521 break; 3522 } 3523 3524 case OR_Success: 3525 llvm_unreachable("Conversion did not fail!"); 3526 break; 3527 } 3528 break; 3529 3530 case FK_NonConstLValueReferenceBindingToTemporary: 3531 case FK_NonConstLValueReferenceBindingToUnrelated: 3532 S.Diag(Kind.getLocation(), 3533 Failure == FK_NonConstLValueReferenceBindingToTemporary 3534 ? diag::err_lvalue_reference_bind_to_temporary 3535 : diag::err_lvalue_reference_bind_to_unrelated) 3536 << DestType.getNonReferenceType() 3537 << Args[0]->getType() 3538 << Args[0]->getSourceRange(); 3539 break; 3540 3541 case FK_RValueReferenceBindingToLValue: 3542 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref) 3543 << Args[0]->getSourceRange(); 3544 break; 3545 3546 case FK_ReferenceInitDropsQualifiers: 3547 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals) 3548 << DestType.getNonReferenceType() 3549 << Args[0]->getType() 3550 << Args[0]->getSourceRange(); 3551 break; 3552 3553 case FK_ReferenceInitFailed: 3554 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed) 3555 << DestType.getNonReferenceType() 3556 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid) 3557 << Args[0]->getType() 3558 << Args[0]->getSourceRange(); 3559 break; 3560 3561 case FK_ConversionFailed: 3562 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed) 3563 << (int)Entity.getKind() 3564 << DestType 3565 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid) 3566 << Args[0]->getType() 3567 << Args[0]->getSourceRange(); 3568 break; 3569 3570 case FK_TooManyInitsForScalar: { 3571 SourceRange R; 3572 3573 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0])) 3574 R = SourceRange(InitList->getInit(1)->getLocStart(), 3575 InitList->getLocEnd()); 3576 else 3577 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd()); 3578 3579 S.Diag(Kind.getLocation(), diag::err_excess_initializers) 3580 << /*scalar=*/2 << R; 3581 break; 3582 } 3583 3584 case FK_ReferenceBindingToInitList: 3585 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list) 3586 << DestType.getNonReferenceType() << Args[0]->getSourceRange(); 3587 break; 3588 3589 case FK_InitListBadDestinationType: 3590 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type) 3591 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange(); 3592 break; 3593 3594 case FK_ConstructorOverloadFailed: { 3595 SourceRange ArgsRange; 3596 if (NumArgs) 3597 ArgsRange = SourceRange(Args[0]->getLocStart(), 3598 Args[NumArgs - 1]->getLocEnd()); 3599 3600 // FIXME: Using "DestType" for the entity we're printing is probably 3601 // bad. 3602 switch (FailedOverloadResult) { 3603 case OR_Ambiguous: 3604 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init) 3605 << DestType << ArgsRange; 3606 S.PrintOverloadCandidates(FailedCandidateSet, true); 3607 break; 3608 3609 case OR_No_Viable_Function: 3610 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init) 3611 << DestType << ArgsRange; 3612 S.PrintOverloadCandidates(FailedCandidateSet, false); 3613 break; 3614 3615 case OR_Deleted: { 3616 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init) 3617 << true << DestType << ArgsRange; 3618 OverloadCandidateSet::iterator Best; 3619 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet, 3620 Kind.getLocation(), 3621 Best); 3622 if (Ovl == OR_Deleted) { 3623 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here) 3624 << Best->Function->isDeleted(); 3625 } else { 3626 llvm_unreachable("Inconsistent overload resolution?"); 3627 } 3628 break; 3629 } 3630 3631 case OR_Success: 3632 llvm_unreachable("Conversion did not fail!"); 3633 break; 3634 } 3635 break; 3636 } 3637 3638 case FK_DefaultInitOfConst: 3639 S.Diag(Kind.getLocation(), diag::err_default_init_const) 3640 << DestType; 3641 break; 3642 } 3643 3644 return true; 3645} 3646 3647//===----------------------------------------------------------------------===// 3648// Initialization helper functions 3649//===----------------------------------------------------------------------===// 3650Sema::OwningExprResult 3651Sema::PerformCopyInitialization(const InitializedEntity &Entity, 3652 SourceLocation EqualLoc, 3653 OwningExprResult Init) { 3654 if (Init.isInvalid()) 3655 return ExprError(); 3656 3657 Expr *InitE = (Expr *)Init.get(); 3658 assert(InitE && "No initialization expression?"); 3659 3660 if (EqualLoc.isInvalid()) 3661 EqualLoc = InitE->getLocStart(); 3662 3663 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(), 3664 EqualLoc); 3665 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1); 3666 Init.release(); 3667 return Seq.Perform(*this, Entity, Kind, 3668 MultiExprArg(*this, (void**)&InitE, 1)); 3669} 3670