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