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