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