SemaInit.cpp revision 61b4bc80e943578ae855810918a1dc9697dbd15b
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//===----------------------------------------------------------------------===// 15 16#include "clang/Sema/Designator.h" 17#include "clang/Sema/Initialization.h" 18#include "clang/Sema/Lookup.h" 19#include "clang/Sema/SemaInternal.h" 20#include "clang/Lex/Preprocessor.h" 21#include "clang/AST/ASTContext.h" 22#include "clang/AST/DeclObjC.h" 23#include "clang/AST/ExprCXX.h" 24#include "clang/AST/ExprObjC.h" 25#include "clang/AST/TypeLoc.h" 26#include "llvm/Support/ErrorHandling.h" 27#include <map> 28using namespace clang; 29 30//===----------------------------------------------------------------------===// 31// Sema Initialization Checking 32//===----------------------------------------------------------------------===// 33 34static Expr *IsStringInit(Expr *Init, const ArrayType *AT, 35 ASTContext &Context) { 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 Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) { 68 const ArrayType *arrayType = Context.getAsArrayType(declType); 69 if (!arrayType) return 0; 70 71 return IsStringInit(init, arrayType, Context); 72} 73 74static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT, 75 Sema &S) { 76 // Get the length of the string as parsed. 77 uint64_t StrLength = 78 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue(); 79 80 81 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) { 82 // C99 6.7.8p14. We have an array of character type with unknown size 83 // being initialized to a string literal. 84 llvm::APSInt ConstVal(32); 85 ConstVal = StrLength; 86 // Return a new array type (C99 6.7.8p22). 87 DeclT = S.Context.getConstantArrayType(IAT->getElementType(), 88 ConstVal, 89 ArrayType::Normal, 0); 90 return; 91 } 92 93 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT); 94 95 // We have an array of character type with known size. However, 96 // the size may be smaller or larger than the string we are initializing. 97 // FIXME: Avoid truncation for 64-bit length strings. 98 if (S.getLangOptions().CPlusPlus) { 99 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) { 100 // For Pascal strings it's OK to strip off the terminating null character, 101 // so the example below is valid: 102 // 103 // unsigned char a[2] = "\pa"; 104 if (SL->isPascal()) 105 StrLength--; 106 } 107 108 // [dcl.init.string]p2 109 if (StrLength > CAT->getSize().getZExtValue()) 110 S.Diag(Str->getSourceRange().getBegin(), 111 diag::err_initializer_string_for_char_array_too_long) 112 << Str->getSourceRange(); 113 } else { 114 // C99 6.7.8p14. 115 if (StrLength-1 > CAT->getSize().getZExtValue()) 116 S.Diag(Str->getSourceRange().getBegin(), 117 diag::warn_initializer_string_for_char_array_too_long) 118 << Str->getSourceRange(); 119 } 120 121 // Set the type to the actual size that we are initializing. If we have 122 // something like: 123 // char x[1] = "foo"; 124 // then this will set the string literal's type to char[1]. 125 Str->setType(DeclT); 126} 127 128//===----------------------------------------------------------------------===// 129// Semantic checking for initializer lists. 130//===----------------------------------------------------------------------===// 131 132/// @brief Semantic checking for initializer lists. 133/// 134/// The InitListChecker class contains a set of routines that each 135/// handle the initialization of a certain kind of entity, e.g., 136/// arrays, vectors, struct/union types, scalars, etc. The 137/// InitListChecker itself performs a recursive walk of the subobject 138/// structure of the type to be initialized, while stepping through 139/// the initializer list one element at a time. The IList and Index 140/// parameters to each of the Check* routines contain the active 141/// (syntactic) initializer list and the index into that initializer 142/// list that represents the current initializer. Each routine is 143/// responsible for moving that Index forward as it consumes elements. 144/// 145/// Each Check* routine also has a StructuredList/StructuredIndex 146/// arguments, which contains the current "structured" (semantic) 147/// initializer list and the index into that initializer list where we 148/// are copying initializers as we map them over to the semantic 149/// list. Once we have completed our recursive walk of the subobject 150/// structure, we will have constructed a full semantic initializer 151/// list. 152/// 153/// C99 designators cause changes in the initializer list traversal, 154/// because they make the initialization "jump" into a specific 155/// subobject and then continue the initialization from that 156/// point. CheckDesignatedInitializer() recursively steps into the 157/// designated subobject and manages backing out the recursion to 158/// initialize the subobjects after the one designated. 159namespace { 160class InitListChecker { 161 Sema &SemaRef; 162 bool hadError; 163 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic; 164 InitListExpr *FullyStructuredList; 165 166 void CheckImplicitInitList(const InitializedEntity &Entity, 167 InitListExpr *ParentIList, QualType T, 168 unsigned &Index, InitListExpr *StructuredList, 169 unsigned &StructuredIndex, 170 bool TopLevelObject = false); 171 void CheckExplicitInitList(const InitializedEntity &Entity, 172 InitListExpr *IList, QualType &T, 173 unsigned &Index, InitListExpr *StructuredList, 174 unsigned &StructuredIndex, 175 bool TopLevelObject = false); 176 void CheckListElementTypes(const InitializedEntity &Entity, 177 InitListExpr *IList, QualType &DeclType, 178 bool SubobjectIsDesignatorContext, 179 unsigned &Index, 180 InitListExpr *StructuredList, 181 unsigned &StructuredIndex, 182 bool TopLevelObject = false); 183 void CheckSubElementType(const InitializedEntity &Entity, 184 InitListExpr *IList, QualType ElemType, 185 unsigned &Index, 186 InitListExpr *StructuredList, 187 unsigned &StructuredIndex); 188 void CheckScalarType(const InitializedEntity &Entity, 189 InitListExpr *IList, QualType DeclType, 190 unsigned &Index, 191 InitListExpr *StructuredList, 192 unsigned &StructuredIndex); 193 void CheckReferenceType(const InitializedEntity &Entity, 194 InitListExpr *IList, QualType DeclType, 195 unsigned &Index, 196 InitListExpr *StructuredList, 197 unsigned &StructuredIndex); 198 void CheckVectorType(const InitializedEntity &Entity, 199 InitListExpr *IList, QualType DeclType, unsigned &Index, 200 InitListExpr *StructuredList, 201 unsigned &StructuredIndex); 202 void CheckStructUnionTypes(const InitializedEntity &Entity, 203 InitListExpr *IList, QualType DeclType, 204 RecordDecl::field_iterator Field, 205 bool SubobjectIsDesignatorContext, unsigned &Index, 206 InitListExpr *StructuredList, 207 unsigned &StructuredIndex, 208 bool TopLevelObject = false); 209 void CheckArrayType(const InitializedEntity &Entity, 210 InitListExpr *IList, QualType &DeclType, 211 llvm::APSInt elementIndex, 212 bool SubobjectIsDesignatorContext, unsigned &Index, 213 InitListExpr *StructuredList, 214 unsigned &StructuredIndex); 215 bool CheckDesignatedInitializer(const InitializedEntity &Entity, 216 InitListExpr *IList, DesignatedInitExpr *DIE, 217 unsigned DesigIdx, 218 QualType &CurrentObjectType, 219 RecordDecl::field_iterator *NextField, 220 llvm::APSInt *NextElementIndex, 221 unsigned &Index, 222 InitListExpr *StructuredList, 223 unsigned &StructuredIndex, 224 bool FinishSubobjectInit, 225 bool TopLevelObject); 226 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, 227 QualType CurrentObjectType, 228 InitListExpr *StructuredList, 229 unsigned StructuredIndex, 230 SourceRange InitRange); 231 void UpdateStructuredListElement(InitListExpr *StructuredList, 232 unsigned &StructuredIndex, 233 Expr *expr); 234 int numArrayElements(QualType DeclType); 235 int numStructUnionElements(QualType DeclType); 236 237 void FillInValueInitForField(unsigned Init, FieldDecl *Field, 238 const InitializedEntity &ParentEntity, 239 InitListExpr *ILE, bool &RequiresSecondPass); 240 void FillInValueInitializations(const InitializedEntity &Entity, 241 InitListExpr *ILE, bool &RequiresSecondPass); 242public: 243 InitListChecker(Sema &S, const InitializedEntity &Entity, 244 InitListExpr *IL, QualType &T); 245 bool HadError() { return hadError; } 246 247 // @brief Retrieves the fully-structured initializer list used for 248 // semantic analysis and code generation. 249 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; } 250}; 251} // end anonymous namespace 252 253void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field, 254 const InitializedEntity &ParentEntity, 255 InitListExpr *ILE, 256 bool &RequiresSecondPass) { 257 SourceLocation Loc = ILE->getSourceRange().getBegin(); 258 unsigned NumInits = ILE->getNumInits(); 259 InitializedEntity MemberEntity 260 = InitializedEntity::InitializeMember(Field, &ParentEntity); 261 if (Init >= NumInits || !ILE->getInit(Init)) { 262 // FIXME: We probably don't need to handle references 263 // specially here, since value-initialization of references is 264 // handled in InitializationSequence. 265 if (Field->getType()->isReferenceType()) { 266 // C++ [dcl.init.aggr]p9: 267 // If an incomplete or empty initializer-list leaves a 268 // member of reference type uninitialized, the program is 269 // ill-formed. 270 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized) 271 << Field->getType() 272 << ILE->getSyntacticForm()->getSourceRange(); 273 SemaRef.Diag(Field->getLocation(), 274 diag::note_uninit_reference_member); 275 hadError = true; 276 return; 277 } 278 279 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc, 280 true); 281 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0); 282 if (!InitSeq) { 283 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0); 284 hadError = true; 285 return; 286 } 287 288 ExprResult MemberInit 289 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg()); 290 if (MemberInit.isInvalid()) { 291 hadError = true; 292 return; 293 } 294 295 if (hadError) { 296 // Do nothing 297 } else if (Init < NumInits) { 298 ILE->setInit(Init, MemberInit.takeAs<Expr>()); 299 } else if (InitSeq.isConstructorInitialization()) { 300 // Value-initialization requires a constructor call, so 301 // extend the initializer list to include the constructor 302 // call and make a note that we'll need to take another pass 303 // through the initializer list. 304 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>()); 305 RequiresSecondPass = true; 306 } 307 } else if (InitListExpr *InnerILE 308 = dyn_cast<InitListExpr>(ILE->getInit(Init))) 309 FillInValueInitializations(MemberEntity, InnerILE, 310 RequiresSecondPass); 311} 312 313/// Recursively replaces NULL values within the given initializer list 314/// with expressions that perform value-initialization of the 315/// appropriate type. 316void 317InitListChecker::FillInValueInitializations(const InitializedEntity &Entity, 318 InitListExpr *ILE, 319 bool &RequiresSecondPass) { 320 assert((ILE->getType() != SemaRef.Context.VoidTy) && 321 "Should not have void type"); 322 SourceLocation Loc = ILE->getSourceRange().getBegin(); 323 if (ILE->getSyntacticForm()) 324 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin(); 325 326 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) { 327 if (RType->getDecl()->isUnion() && 328 ILE->getInitializedFieldInUnion()) 329 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(), 330 Entity, ILE, RequiresSecondPass); 331 else { 332 unsigned Init = 0; 333 for (RecordDecl::field_iterator 334 Field = RType->getDecl()->field_begin(), 335 FieldEnd = RType->getDecl()->field_end(); 336 Field != FieldEnd; ++Field) { 337 if (Field->isUnnamedBitfield()) 338 continue; 339 340 if (hadError) 341 return; 342 343 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass); 344 if (hadError) 345 return; 346 347 ++Init; 348 349 // Only look at the first initialization of a union. 350 if (RType->getDecl()->isUnion()) 351 break; 352 } 353 } 354 355 return; 356 } 357 358 QualType ElementType; 359 360 InitializedEntity ElementEntity = Entity; 361 unsigned NumInits = ILE->getNumInits(); 362 unsigned NumElements = NumInits; 363 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) { 364 ElementType = AType->getElementType(); 365 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) 366 NumElements = CAType->getSize().getZExtValue(); 367 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context, 368 0, Entity); 369 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) { 370 ElementType = VType->getElementType(); 371 NumElements = VType->getNumElements(); 372 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context, 373 0, Entity); 374 } else 375 ElementType = ILE->getType(); 376 377 378 for (unsigned Init = 0; Init != NumElements; ++Init) { 379 if (hadError) 380 return; 381 382 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement || 383 ElementEntity.getKind() == InitializedEntity::EK_VectorElement) 384 ElementEntity.setElementIndex(Init); 385 386 if (Init >= NumInits || !ILE->getInit(Init)) { 387 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc, 388 true); 389 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0); 390 if (!InitSeq) { 391 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0); 392 hadError = true; 393 return; 394 } 395 396 ExprResult ElementInit 397 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg()); 398 if (ElementInit.isInvalid()) { 399 hadError = true; 400 return; 401 } 402 403 if (hadError) { 404 // Do nothing 405 } else if (Init < NumInits) { 406 // For arrays, just set the expression used for value-initialization 407 // of the "holes" in the array. 408 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) 409 ILE->setArrayFiller(ElementInit.takeAs<Expr>()); 410 else 411 ILE->setInit(Init, ElementInit.takeAs<Expr>()); 412 } else { 413 // For arrays, just set the expression used for value-initialization 414 // of the rest of elements and exit. 415 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) { 416 ILE->setArrayFiller(ElementInit.takeAs<Expr>()); 417 return; 418 } 419 420 if (InitSeq.isConstructorInitialization()) { 421 // Value-initialization requires a constructor call, so 422 // extend the initializer list to include the constructor 423 // call and make a note that we'll need to take another pass 424 // through the initializer list. 425 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>()); 426 RequiresSecondPass = true; 427 } 428 } 429 } else if (InitListExpr *InnerILE 430 = dyn_cast<InitListExpr>(ILE->getInit(Init))) 431 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass); 432 } 433} 434 435 436InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity, 437 InitListExpr *IL, QualType &T) 438 : SemaRef(S) { 439 hadError = false; 440 441 unsigned newIndex = 0; 442 unsigned newStructuredIndex = 0; 443 FullyStructuredList 444 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange()); 445 CheckExplicitInitList(Entity, IL, T, newIndex, 446 FullyStructuredList, newStructuredIndex, 447 /*TopLevelObject=*/true); 448 449 if (!hadError) { 450 bool RequiresSecondPass = false; 451 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass); 452 if (RequiresSecondPass && !hadError) 453 FillInValueInitializations(Entity, FullyStructuredList, 454 RequiresSecondPass); 455 } 456} 457 458int InitListChecker::numArrayElements(QualType DeclType) { 459 // FIXME: use a proper constant 460 int maxElements = 0x7FFFFFFF; 461 if (const ConstantArrayType *CAT = 462 SemaRef.Context.getAsConstantArrayType(DeclType)) { 463 maxElements = static_cast<int>(CAT->getSize().getZExtValue()); 464 } 465 return maxElements; 466} 467 468int InitListChecker::numStructUnionElements(QualType DeclType) { 469 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl(); 470 int InitializableMembers = 0; 471 for (RecordDecl::field_iterator 472 Field = structDecl->field_begin(), 473 FieldEnd = structDecl->field_end(); 474 Field != FieldEnd; ++Field) { 475 if ((*Field)->getIdentifier() || !(*Field)->isBitField()) 476 ++InitializableMembers; 477 } 478 if (structDecl->isUnion()) 479 return std::min(InitializableMembers, 1); 480 return InitializableMembers - structDecl->hasFlexibleArrayMember(); 481} 482 483void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity, 484 InitListExpr *ParentIList, 485 QualType T, unsigned &Index, 486 InitListExpr *StructuredList, 487 unsigned &StructuredIndex, 488 bool TopLevelObject) { 489 int maxElements = 0; 490 491 if (T->isArrayType()) 492 maxElements = numArrayElements(T); 493 else if (T->isRecordType()) 494 maxElements = numStructUnionElements(T); 495 else if (T->isVectorType()) 496 maxElements = T->getAs<VectorType>()->getNumElements(); 497 else 498 assert(0 && "CheckImplicitInitList(): Illegal type"); 499 500 if (maxElements == 0) { 501 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(), 502 diag::err_implicit_empty_initializer); 503 ++Index; 504 hadError = true; 505 return; 506 } 507 508 // Build a structured initializer list corresponding to this subobject. 509 InitListExpr *StructuredSubobjectInitList 510 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList, 511 StructuredIndex, 512 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(), 513 ParentIList->getSourceRange().getEnd())); 514 unsigned StructuredSubobjectInitIndex = 0; 515 516 // Check the element types and build the structural subobject. 517 unsigned StartIndex = Index; 518 CheckListElementTypes(Entity, ParentIList, T, 519 /*SubobjectIsDesignatorContext=*/false, Index, 520 StructuredSubobjectInitList, 521 StructuredSubobjectInitIndex, 522 TopLevelObject); 523 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1); 524 StructuredSubobjectInitList->setType(T); 525 526 // Update the structured sub-object initializer so that it's ending 527 // range corresponds with the end of the last initializer it used. 528 if (EndIndex < ParentIList->getNumInits()) { 529 SourceLocation EndLoc 530 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd(); 531 StructuredSubobjectInitList->setRBraceLoc(EndLoc); 532 } 533 534 // Warn about missing braces. 535 if (T->isArrayType() || T->isRecordType()) { 536 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(), 537 diag::warn_missing_braces) 538 << StructuredSubobjectInitList->getSourceRange() 539 << FixItHint::CreateInsertion(StructuredSubobjectInitList->getLocStart(), 540 "{") 541 << FixItHint::CreateInsertion(SemaRef.PP.getLocForEndOfToken( 542 StructuredSubobjectInitList->getLocEnd()), 543 "}"); 544 } 545} 546 547void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity, 548 InitListExpr *IList, QualType &T, 549 unsigned &Index, 550 InitListExpr *StructuredList, 551 unsigned &StructuredIndex, 552 bool TopLevelObject) { 553 assert(IList->isExplicit() && "Illegal Implicit InitListExpr"); 554 SyntacticToSemantic[IList] = StructuredList; 555 StructuredList->setSyntacticForm(IList); 556 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true, 557 Index, StructuredList, StructuredIndex, TopLevelObject); 558 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context); 559 IList->setType(ExprTy); 560 StructuredList->setType(ExprTy); 561 if (hadError) 562 return; 563 564 if (Index < IList->getNumInits()) { 565 // We have leftover initializers 566 if (StructuredIndex == 1 && 567 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) { 568 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer; 569 if (SemaRef.getLangOptions().CPlusPlus) { 570 DK = diag::err_excess_initializers_in_char_array_initializer; 571 hadError = true; 572 } 573 // Special-case 574 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK) 575 << IList->getInit(Index)->getSourceRange(); 576 } else if (!T->isIncompleteType()) { 577 // Don't complain for incomplete types, since we'll get an error 578 // elsewhere 579 QualType CurrentObjectType = StructuredList->getType(); 580 int initKind = 581 CurrentObjectType->isArrayType()? 0 : 582 CurrentObjectType->isVectorType()? 1 : 583 CurrentObjectType->isScalarType()? 2 : 584 CurrentObjectType->isUnionType()? 3 : 585 4; 586 587 unsigned DK = diag::warn_excess_initializers; 588 if (SemaRef.getLangOptions().CPlusPlus) { 589 DK = diag::err_excess_initializers; 590 hadError = true; 591 } 592 if (SemaRef.getLangOptions().OpenCL && initKind == 1) { 593 DK = diag::err_excess_initializers; 594 hadError = true; 595 } 596 597 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK) 598 << initKind << IList->getInit(Index)->getSourceRange(); 599 } 600 } 601 602 if (T->isScalarType() && !TopLevelObject) 603 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init) 604 << IList->getSourceRange() 605 << FixItHint::CreateRemoval(IList->getLocStart()) 606 << FixItHint::CreateRemoval(IList->getLocEnd()); 607} 608 609void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity, 610 InitListExpr *IList, 611 QualType &DeclType, 612 bool SubobjectIsDesignatorContext, 613 unsigned &Index, 614 InitListExpr *StructuredList, 615 unsigned &StructuredIndex, 616 bool TopLevelObject) { 617 if (DeclType->isScalarType()) { 618 CheckScalarType(Entity, IList, DeclType, Index, 619 StructuredList, StructuredIndex); 620 } else if (DeclType->isVectorType()) { 621 CheckVectorType(Entity, IList, DeclType, Index, 622 StructuredList, StructuredIndex); 623 } else if (DeclType->isAggregateType()) { 624 if (DeclType->isRecordType()) { 625 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl(); 626 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(), 627 SubobjectIsDesignatorContext, Index, 628 StructuredList, StructuredIndex, 629 TopLevelObject); 630 } else if (DeclType->isArrayType()) { 631 llvm::APSInt Zero( 632 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()), 633 false); 634 CheckArrayType(Entity, IList, DeclType, Zero, 635 SubobjectIsDesignatorContext, Index, 636 StructuredList, StructuredIndex); 637 } else 638 assert(0 && "Aggregate that isn't a structure or array?!"); 639 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) { 640 // This type is invalid, issue a diagnostic. 641 ++Index; 642 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type) 643 << DeclType; 644 hadError = true; 645 } else if (DeclType->isRecordType()) { 646 // C++ [dcl.init]p14: 647 // [...] If the class is an aggregate (8.5.1), and the initializer 648 // is a brace-enclosed list, see 8.5.1. 649 // 650 // Note: 8.5.1 is handled below; here, we diagnose the case where 651 // we have an initializer list and a destination type that is not 652 // an aggregate. 653 // FIXME: In C++0x, this is yet another form of initialization. 654 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list) 655 << DeclType << IList->getSourceRange(); 656 hadError = true; 657 } else if (DeclType->isReferenceType()) { 658 CheckReferenceType(Entity, IList, DeclType, Index, 659 StructuredList, StructuredIndex); 660 } else if (DeclType->isObjCObjectType()) { 661 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class) 662 << DeclType; 663 hadError = true; 664 } else { 665 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type) 666 << DeclType; 667 hadError = true; 668 } 669} 670 671void InitListChecker::CheckSubElementType(const InitializedEntity &Entity, 672 InitListExpr *IList, 673 QualType ElemType, 674 unsigned &Index, 675 InitListExpr *StructuredList, 676 unsigned &StructuredIndex) { 677 Expr *expr = IList->getInit(Index); 678 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) { 679 unsigned newIndex = 0; 680 unsigned newStructuredIndex = 0; 681 InitListExpr *newStructuredList 682 = getStructuredSubobjectInit(IList, Index, ElemType, 683 StructuredList, StructuredIndex, 684 SubInitList->getSourceRange()); 685 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex, 686 newStructuredList, newStructuredIndex); 687 ++StructuredIndex; 688 ++Index; 689 return; 690 } else if (ElemType->isScalarType()) { 691 return CheckScalarType(Entity, IList, ElemType, Index, 692 StructuredList, StructuredIndex); 693 } else if (ElemType->isReferenceType()) { 694 return CheckReferenceType(Entity, IList, ElemType, Index, 695 StructuredList, StructuredIndex); 696 } 697 698 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) { 699 // arrayType can be incomplete if we're initializing a flexible 700 // array member. There's nothing we can do with the completed 701 // type here, though. 702 703 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) { 704 CheckStringInit(Str, ElemType, arrayType, SemaRef); 705 UpdateStructuredListElement(StructuredList, StructuredIndex, Str); 706 ++Index; 707 return; 708 } 709 710 // Fall through for subaggregate initialization. 711 712 } else if (SemaRef.getLangOptions().CPlusPlus) { 713 // C++ [dcl.init.aggr]p12: 714 // All implicit type conversions (clause 4) are considered when 715 // initializing the aggregate member with an ini- tializer from 716 // an initializer-list. If the initializer can initialize a 717 // member, the member is initialized. [...] 718 719 // FIXME: Better EqualLoc? 720 InitializationKind Kind = 721 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation()); 722 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1); 723 724 if (Seq) { 725 ExprResult Result = 726 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1)); 727 if (Result.isInvalid()) 728 hadError = true; 729 730 UpdateStructuredListElement(StructuredList, StructuredIndex, 731 Result.takeAs<Expr>()); 732 ++Index; 733 return; 734 } 735 736 // Fall through for subaggregate initialization 737 } else { 738 // C99 6.7.8p13: 739 // 740 // The initializer for a structure or union object that has 741 // automatic storage duration shall be either an initializer 742 // list as described below, or a single expression that has 743 // compatible structure or union type. In the latter case, the 744 // initial value of the object, including unnamed members, is 745 // that of the expression. 746 ExprResult ExprRes = SemaRef.Owned(expr); 747 if ((ElemType->isRecordType() || ElemType->isVectorType()) && 748 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes) 749 == Sema::Compatible) { 750 if (ExprRes.isInvalid()) 751 hadError = true; 752 else { 753 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take()); 754 if (ExprRes.isInvalid()) 755 hadError = true; 756 } 757 UpdateStructuredListElement(StructuredList, StructuredIndex, 758 ExprRes.takeAs<Expr>()); 759 ++Index; 760 return; 761 } 762 ExprRes.release(); 763 // Fall through for subaggregate initialization 764 } 765 766 // C++ [dcl.init.aggr]p12: 767 // 768 // [...] Otherwise, if the member is itself a non-empty 769 // subaggregate, brace elision is assumed and the initializer is 770 // considered for the initialization of the first member of 771 // the subaggregate. 772 if (!SemaRef.getLangOptions().OpenCL && 773 (ElemType->isAggregateType() || ElemType->isVectorType())) { 774 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList, 775 StructuredIndex); 776 ++StructuredIndex; 777 } else { 778 // We cannot initialize this element, so let 779 // PerformCopyInitialization produce the appropriate diagnostic. 780 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), 781 SemaRef.Owned(expr)); 782 hadError = true; 783 ++Index; 784 ++StructuredIndex; 785 } 786} 787 788void InitListChecker::CheckScalarType(const InitializedEntity &Entity, 789 InitListExpr *IList, QualType DeclType, 790 unsigned &Index, 791 InitListExpr *StructuredList, 792 unsigned &StructuredIndex) { 793 if (Index >= IList->getNumInits()) { 794 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer) 795 << IList->getSourceRange(); 796 hadError = true; 797 ++Index; 798 ++StructuredIndex; 799 return; 800 } 801 802 Expr *expr = IList->getInit(Index); 803 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) { 804 SemaRef.Diag(SubIList->getLocStart(), 805 diag::warn_many_braces_around_scalar_init) 806 << SubIList->getSourceRange(); 807 808 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList, 809 StructuredIndex); 810 return; 811 } else if (isa<DesignatedInitExpr>(expr)) { 812 SemaRef.Diag(expr->getSourceRange().getBegin(), 813 diag::err_designator_for_scalar_init) 814 << DeclType << expr->getSourceRange(); 815 hadError = true; 816 ++Index; 817 ++StructuredIndex; 818 return; 819 } 820 821 ExprResult Result = 822 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), 823 SemaRef.Owned(expr)); 824 825 Expr *ResultExpr = 0; 826 827 if (Result.isInvalid()) 828 hadError = true; // types weren't compatible. 829 else { 830 ResultExpr = Result.takeAs<Expr>(); 831 832 if (ResultExpr != expr) { 833 // The type was promoted, update initializer list. 834 IList->setInit(Index, ResultExpr); 835 } 836 } 837 if (hadError) 838 ++StructuredIndex; 839 else 840 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr); 841 ++Index; 842} 843 844void InitListChecker::CheckReferenceType(const InitializedEntity &Entity, 845 InitListExpr *IList, QualType DeclType, 846 unsigned &Index, 847 InitListExpr *StructuredList, 848 unsigned &StructuredIndex) { 849 if (Index < IList->getNumInits()) { 850 Expr *expr = IList->getInit(Index); 851 if (isa<InitListExpr>(expr)) { 852 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list) 853 << DeclType << IList->getSourceRange(); 854 hadError = true; 855 ++Index; 856 ++StructuredIndex; 857 return; 858 } 859 860 ExprResult Result = 861 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), 862 SemaRef.Owned(expr)); 863 864 if (Result.isInvalid()) 865 hadError = true; 866 867 expr = Result.takeAs<Expr>(); 868 IList->setInit(Index, expr); 869 870 if (hadError) 871 ++StructuredIndex; 872 else 873 UpdateStructuredListElement(StructuredList, StructuredIndex, expr); 874 ++Index; 875 } else { 876 // FIXME: It would be wonderful if we could point at the actual member. In 877 // general, it would be useful to pass location information down the stack, 878 // so that we know the location (or decl) of the "current object" being 879 // initialized. 880 SemaRef.Diag(IList->getLocStart(), 881 diag::err_init_reference_member_uninitialized) 882 << DeclType 883 << IList->getSourceRange(); 884 hadError = true; 885 ++Index; 886 ++StructuredIndex; 887 return; 888 } 889} 890 891void InitListChecker::CheckVectorType(const InitializedEntity &Entity, 892 InitListExpr *IList, QualType DeclType, 893 unsigned &Index, 894 InitListExpr *StructuredList, 895 unsigned &StructuredIndex) { 896 if (Index >= IList->getNumInits()) 897 return; 898 899 const VectorType *VT = DeclType->getAs<VectorType>(); 900 unsigned maxElements = VT->getNumElements(); 901 unsigned numEltsInit = 0; 902 QualType elementType = VT->getElementType(); 903 904 if (!SemaRef.getLangOptions().OpenCL) { 905 // If the initializing element is a vector, try to copy-initialize 906 // instead of breaking it apart (which is doomed to failure anyway). 907 Expr *Init = IList->getInit(Index); 908 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) { 909 ExprResult Result = 910 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), 911 SemaRef.Owned(Init)); 912 913 Expr *ResultExpr = 0; 914 if (Result.isInvalid()) 915 hadError = true; // types weren't compatible. 916 else { 917 ResultExpr = Result.takeAs<Expr>(); 918 919 if (ResultExpr != Init) { 920 // The type was promoted, update initializer list. 921 IList->setInit(Index, ResultExpr); 922 } 923 } 924 if (hadError) 925 ++StructuredIndex; 926 else 927 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr); 928 ++Index; 929 return; 930 } 931 932 InitializedEntity ElementEntity = 933 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); 934 935 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) { 936 // Don't attempt to go past the end of the init list 937 if (Index >= IList->getNumInits()) 938 break; 939 940 ElementEntity.setElementIndex(Index); 941 CheckSubElementType(ElementEntity, IList, elementType, Index, 942 StructuredList, StructuredIndex); 943 } 944 return; 945 } 946 947 InitializedEntity ElementEntity = 948 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); 949 950 // OpenCL initializers allows vectors to be constructed from vectors. 951 for (unsigned i = 0; i < maxElements; ++i) { 952 // Don't attempt to go past the end of the init list 953 if (Index >= IList->getNumInits()) 954 break; 955 956 ElementEntity.setElementIndex(Index); 957 958 QualType IType = IList->getInit(Index)->getType(); 959 if (!IType->isVectorType()) { 960 CheckSubElementType(ElementEntity, IList, elementType, Index, 961 StructuredList, StructuredIndex); 962 ++numEltsInit; 963 } else { 964 QualType VecType; 965 const VectorType *IVT = IType->getAs<VectorType>(); 966 unsigned numIElts = IVT->getNumElements(); 967 968 if (IType->isExtVectorType()) 969 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts); 970 else 971 VecType = SemaRef.Context.getVectorType(elementType, numIElts, 972 IVT->getVectorKind()); 973 CheckSubElementType(ElementEntity, IList, VecType, Index, 974 StructuredList, StructuredIndex); 975 numEltsInit += numIElts; 976 } 977 } 978 979 // OpenCL requires all elements to be initialized. 980 if (numEltsInit != maxElements) 981 if (SemaRef.getLangOptions().OpenCL) 982 SemaRef.Diag(IList->getSourceRange().getBegin(), 983 diag::err_vector_incorrect_num_initializers) 984 << (numEltsInit < maxElements) << maxElements << numEltsInit; 985} 986 987void InitListChecker::CheckArrayType(const InitializedEntity &Entity, 988 InitListExpr *IList, QualType &DeclType, 989 llvm::APSInt elementIndex, 990 bool SubobjectIsDesignatorContext, 991 unsigned &Index, 992 InitListExpr *StructuredList, 993 unsigned &StructuredIndex) { 994 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType); 995 996 // Check for the special-case of initializing an array with a string. 997 if (Index < IList->getNumInits()) { 998 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType, 999 SemaRef.Context)) { 1000 CheckStringInit(Str, DeclType, arrayType, SemaRef); 1001 // We place the string literal directly into the resulting 1002 // initializer list. This is the only place where the structure 1003 // of the structured initializer list doesn't match exactly, 1004 // because doing so would involve allocating one character 1005 // constant for each string. 1006 UpdateStructuredListElement(StructuredList, StructuredIndex, Str); 1007 StructuredList->resizeInits(SemaRef.Context, StructuredIndex); 1008 ++Index; 1009 return; 1010 } 1011 } 1012 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) { 1013 // Check for VLAs; in standard C it would be possible to check this 1014 // earlier, but I don't know where clang accepts VLAs (gcc accepts 1015 // them in all sorts of strange places). 1016 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(), 1017 diag::err_variable_object_no_init) 1018 << VAT->getSizeExpr()->getSourceRange(); 1019 hadError = true; 1020 ++Index; 1021 ++StructuredIndex; 1022 return; 1023 } 1024 1025 // We might know the maximum number of elements in advance. 1026 llvm::APSInt maxElements(elementIndex.getBitWidth(), 1027 elementIndex.isUnsigned()); 1028 bool maxElementsKnown = false; 1029 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) { 1030 maxElements = CAT->getSize(); 1031 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth()); 1032 elementIndex.setIsUnsigned(maxElements.isUnsigned()); 1033 maxElementsKnown = true; 1034 } 1035 1036 QualType elementType = arrayType->getElementType(); 1037 while (Index < IList->getNumInits()) { 1038 Expr *Init = IList->getInit(Index); 1039 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) { 1040 // If we're not the subobject that matches up with the '{' for 1041 // the designator, we shouldn't be handling the 1042 // designator. Return immediately. 1043 if (!SubobjectIsDesignatorContext) 1044 return; 1045 1046 // Handle this designated initializer. elementIndex will be 1047 // updated to be the next array element we'll initialize. 1048 if (CheckDesignatedInitializer(Entity, IList, DIE, 0, 1049 DeclType, 0, &elementIndex, Index, 1050 StructuredList, StructuredIndex, true, 1051 false)) { 1052 hadError = true; 1053 continue; 1054 } 1055 1056 if (elementIndex.getBitWidth() > maxElements.getBitWidth()) 1057 maxElements = maxElements.extend(elementIndex.getBitWidth()); 1058 else if (elementIndex.getBitWidth() < maxElements.getBitWidth()) 1059 elementIndex = elementIndex.extend(maxElements.getBitWidth()); 1060 elementIndex.setIsUnsigned(maxElements.isUnsigned()); 1061 1062 // If the array is of incomplete type, keep track of the number of 1063 // elements in the initializer. 1064 if (!maxElementsKnown && elementIndex > maxElements) 1065 maxElements = elementIndex; 1066 1067 continue; 1068 } 1069 1070 // If we know the maximum number of elements, and we've already 1071 // hit it, stop consuming elements in the initializer list. 1072 if (maxElementsKnown && elementIndex == maxElements) 1073 break; 1074 1075 InitializedEntity ElementEntity = 1076 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex, 1077 Entity); 1078 // Check this element. 1079 CheckSubElementType(ElementEntity, IList, elementType, Index, 1080 StructuredList, StructuredIndex); 1081 ++elementIndex; 1082 1083 // If the array is of incomplete type, keep track of the number of 1084 // elements in the initializer. 1085 if (!maxElementsKnown && elementIndex > maxElements) 1086 maxElements = elementIndex; 1087 } 1088 if (!hadError && DeclType->isIncompleteArrayType()) { 1089 // If this is an incomplete array type, the actual type needs to 1090 // be calculated here. 1091 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned()); 1092 if (maxElements == Zero) { 1093 // Sizing an array implicitly to zero is not allowed by ISO C, 1094 // but is supported by GNU. 1095 SemaRef.Diag(IList->getLocStart(), 1096 diag::ext_typecheck_zero_array_size); 1097 } 1098 1099 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements, 1100 ArrayType::Normal, 0); 1101 } 1102} 1103 1104void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity, 1105 InitListExpr *IList, 1106 QualType DeclType, 1107 RecordDecl::field_iterator Field, 1108 bool SubobjectIsDesignatorContext, 1109 unsigned &Index, 1110 InitListExpr *StructuredList, 1111 unsigned &StructuredIndex, 1112 bool TopLevelObject) { 1113 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl(); 1114 1115 // If the record is invalid, some of it's members are invalid. To avoid 1116 // confusion, we forgo checking the intializer for the entire record. 1117 if (structDecl->isInvalidDecl()) { 1118 hadError = true; 1119 return; 1120 } 1121 1122 if (DeclType->isUnionType() && IList->getNumInits() == 0) { 1123 // Value-initialize the first named member of the union. 1124 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl(); 1125 for (RecordDecl::field_iterator FieldEnd = RD->field_end(); 1126 Field != FieldEnd; ++Field) { 1127 if (Field->getDeclName()) { 1128 StructuredList->setInitializedFieldInUnion(*Field); 1129 break; 1130 } 1131 } 1132 return; 1133 } 1134 1135 // If structDecl is a forward declaration, this loop won't do 1136 // anything except look at designated initializers; That's okay, 1137 // because an error should get printed out elsewhere. It might be 1138 // worthwhile to skip over the rest of the initializer, though. 1139 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl(); 1140 RecordDecl::field_iterator FieldEnd = RD->field_end(); 1141 bool InitializedSomething = false; 1142 bool CheckForMissingFields = true; 1143 while (Index < IList->getNumInits()) { 1144 Expr *Init = IList->getInit(Index); 1145 1146 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) { 1147 // If we're not the subobject that matches up with the '{' for 1148 // the designator, we shouldn't be handling the 1149 // designator. Return immediately. 1150 if (!SubobjectIsDesignatorContext) 1151 return; 1152 1153 // Handle this designated initializer. Field will be updated to 1154 // the next field that we'll be initializing. 1155 if (CheckDesignatedInitializer(Entity, IList, DIE, 0, 1156 DeclType, &Field, 0, Index, 1157 StructuredList, StructuredIndex, 1158 true, TopLevelObject)) 1159 hadError = true; 1160 1161 InitializedSomething = true; 1162 1163 // Disable check for missing fields when designators are used. 1164 // This matches gcc behaviour. 1165 CheckForMissingFields = false; 1166 continue; 1167 } 1168 1169 if (Field == FieldEnd) { 1170 // We've run out of fields. We're done. 1171 break; 1172 } 1173 1174 // We've already initialized a member of a union. We're done. 1175 if (InitializedSomething && DeclType->isUnionType()) 1176 break; 1177 1178 // If we've hit the flexible array member at the end, we're done. 1179 if (Field->getType()->isIncompleteArrayType()) 1180 break; 1181 1182 if (Field->isUnnamedBitfield()) { 1183 // Don't initialize unnamed bitfields, e.g. "int : 20;" 1184 ++Field; 1185 continue; 1186 } 1187 1188 // Make sure we can use this declaration. 1189 if (SemaRef.DiagnoseUseOfDecl(*Field, 1190 IList->getInit(Index)->getLocStart())) { 1191 ++Index; 1192 ++Field; 1193 hadError = true; 1194 continue; 1195 } 1196 1197 InitializedEntity MemberEntity = 1198 InitializedEntity::InitializeMember(*Field, &Entity); 1199 CheckSubElementType(MemberEntity, IList, Field->getType(), Index, 1200 StructuredList, StructuredIndex); 1201 InitializedSomething = true; 1202 1203 if (DeclType->isUnionType()) { 1204 // Initialize the first field within the union. 1205 StructuredList->setInitializedFieldInUnion(*Field); 1206 } 1207 1208 ++Field; 1209 } 1210 1211 // Emit warnings for missing struct field initializers. 1212 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd && 1213 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) { 1214 // It is possible we have one or more unnamed bitfields remaining. 1215 // Find first (if any) named field and emit warning. 1216 for (RecordDecl::field_iterator it = Field, end = RD->field_end(); 1217 it != end; ++it) { 1218 if (!it->isUnnamedBitfield()) { 1219 SemaRef.Diag(IList->getSourceRange().getEnd(), 1220 diag::warn_missing_field_initializers) << it->getName(); 1221 break; 1222 } 1223 } 1224 } 1225 1226 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() || 1227 Index >= IList->getNumInits()) 1228 return; 1229 1230 // Handle GNU flexible array initializers. 1231 if (!TopLevelObject && 1232 (!isa<InitListExpr>(IList->getInit(Index)) || 1233 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) { 1234 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(), 1235 diag::err_flexible_array_init_nonempty) 1236 << IList->getInit(Index)->getSourceRange().getBegin(); 1237 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1238 << *Field; 1239 hadError = true; 1240 ++Index; 1241 return; 1242 } else { 1243 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(), 1244 diag::ext_flexible_array_init) 1245 << IList->getInit(Index)->getSourceRange().getBegin(); 1246 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1247 << *Field; 1248 } 1249 1250 InitializedEntity MemberEntity = 1251 InitializedEntity::InitializeMember(*Field, &Entity); 1252 1253 if (isa<InitListExpr>(IList->getInit(Index))) 1254 CheckSubElementType(MemberEntity, IList, Field->getType(), Index, 1255 StructuredList, StructuredIndex); 1256 else 1257 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index, 1258 StructuredList, StructuredIndex); 1259} 1260 1261/// \brief Expand a field designator that refers to a member of an 1262/// anonymous struct or union into a series of field designators that 1263/// refers to the field within the appropriate subobject. 1264/// 1265static void ExpandAnonymousFieldDesignator(Sema &SemaRef, 1266 DesignatedInitExpr *DIE, 1267 unsigned DesigIdx, 1268 IndirectFieldDecl *IndirectField) { 1269 typedef DesignatedInitExpr::Designator Designator; 1270 1271 // Build the replacement designators. 1272 llvm::SmallVector<Designator, 4> Replacements; 1273 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(), 1274 PE = IndirectField->chain_end(); PI != PE; ++PI) { 1275 if (PI + 1 == PE) 1276 Replacements.push_back(Designator((IdentifierInfo *)0, 1277 DIE->getDesignator(DesigIdx)->getDotLoc(), 1278 DIE->getDesignator(DesigIdx)->getFieldLoc())); 1279 else 1280 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(), 1281 SourceLocation())); 1282 assert(isa<FieldDecl>(*PI)); 1283 Replacements.back().setField(cast<FieldDecl>(*PI)); 1284 } 1285 1286 // Expand the current designator into the set of replacement 1287 // designators, so we have a full subobject path down to where the 1288 // member of the anonymous struct/union is actually stored. 1289 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0], 1290 &Replacements[0] + Replacements.size()); 1291} 1292 1293/// \brief Given an implicit anonymous field, search the IndirectField that 1294/// corresponds to FieldName. 1295static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField, 1296 IdentifierInfo *FieldName) { 1297 assert(AnonField->isAnonymousStructOrUnion()); 1298 Decl *NextDecl = AnonField->getNextDeclInContext(); 1299 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) { 1300 if (FieldName && FieldName == IF->getAnonField()->getIdentifier()) 1301 return IF; 1302 NextDecl = NextDecl->getNextDeclInContext(); 1303 } 1304 return 0; 1305} 1306 1307/// @brief Check the well-formedness of a C99 designated initializer. 1308/// 1309/// Determines whether the designated initializer @p DIE, which 1310/// resides at the given @p Index within the initializer list @p 1311/// IList, is well-formed for a current object of type @p DeclType 1312/// (C99 6.7.8). The actual subobject that this designator refers to 1313/// within the current subobject is returned in either 1314/// @p NextField or @p NextElementIndex (whichever is appropriate). 1315/// 1316/// @param IList The initializer list in which this designated 1317/// initializer occurs. 1318/// 1319/// @param DIE The designated initializer expression. 1320/// 1321/// @param DesigIdx The index of the current designator. 1322/// 1323/// @param DeclType The type of the "current object" (C99 6.7.8p17), 1324/// into which the designation in @p DIE should refer. 1325/// 1326/// @param NextField If non-NULL and the first designator in @p DIE is 1327/// a field, this will be set to the field declaration corresponding 1328/// to the field named by the designator. 1329/// 1330/// @param NextElementIndex If non-NULL and the first designator in @p 1331/// DIE is an array designator or GNU array-range designator, this 1332/// will be set to the last index initialized by this designator. 1333/// 1334/// @param Index Index into @p IList where the designated initializer 1335/// @p DIE occurs. 1336/// 1337/// @param StructuredList The initializer list expression that 1338/// describes all of the subobject initializers in the order they'll 1339/// actually be initialized. 1340/// 1341/// @returns true if there was an error, false otherwise. 1342bool 1343InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity, 1344 InitListExpr *IList, 1345 DesignatedInitExpr *DIE, 1346 unsigned DesigIdx, 1347 QualType &CurrentObjectType, 1348 RecordDecl::field_iterator *NextField, 1349 llvm::APSInt *NextElementIndex, 1350 unsigned &Index, 1351 InitListExpr *StructuredList, 1352 unsigned &StructuredIndex, 1353 bool FinishSubobjectInit, 1354 bool TopLevelObject) { 1355 if (DesigIdx == DIE->size()) { 1356 // Check the actual initialization for the designated object type. 1357 bool prevHadError = hadError; 1358 1359 // Temporarily remove the designator expression from the 1360 // initializer list that the child calls see, so that we don't try 1361 // to re-process the designator. 1362 unsigned OldIndex = Index; 1363 IList->setInit(OldIndex, DIE->getInit()); 1364 1365 CheckSubElementType(Entity, IList, CurrentObjectType, Index, 1366 StructuredList, StructuredIndex); 1367 1368 // Restore the designated initializer expression in the syntactic 1369 // form of the initializer list. 1370 if (IList->getInit(OldIndex) != DIE->getInit()) 1371 DIE->setInit(IList->getInit(OldIndex)); 1372 IList->setInit(OldIndex, DIE); 1373 1374 return hadError && !prevHadError; 1375 } 1376 1377 bool IsFirstDesignator = (DesigIdx == 0); 1378 assert((IsFirstDesignator || StructuredList) && 1379 "Need a non-designated initializer list to start from"); 1380 1381 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx); 1382 // Determine the structural initializer list that corresponds to the 1383 // current subobject. 1384 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList] 1385 : getStructuredSubobjectInit(IList, Index, CurrentObjectType, 1386 StructuredList, StructuredIndex, 1387 SourceRange(D->getStartLocation(), 1388 DIE->getSourceRange().getEnd())); 1389 assert(StructuredList && "Expected a structured initializer list"); 1390 1391 if (D->isFieldDesignator()) { 1392 // C99 6.7.8p7: 1393 // 1394 // If a designator has the form 1395 // 1396 // . identifier 1397 // 1398 // then the current object (defined below) shall have 1399 // structure or union type and the identifier shall be the 1400 // name of a member of that type. 1401 const RecordType *RT = CurrentObjectType->getAs<RecordType>(); 1402 if (!RT) { 1403 SourceLocation Loc = D->getDotLoc(); 1404 if (Loc.isInvalid()) 1405 Loc = D->getFieldLoc(); 1406 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr) 1407 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType; 1408 ++Index; 1409 return true; 1410 } 1411 1412 // Note: we perform a linear search of the fields here, despite 1413 // the fact that we have a faster lookup method, because we always 1414 // need to compute the field's index. 1415 FieldDecl *KnownField = D->getField(); 1416 IdentifierInfo *FieldName = D->getFieldName(); 1417 unsigned FieldIndex = 0; 1418 RecordDecl::field_iterator 1419 Field = RT->getDecl()->field_begin(), 1420 FieldEnd = RT->getDecl()->field_end(); 1421 for (; Field != FieldEnd; ++Field) { 1422 if (Field->isUnnamedBitfield()) 1423 continue; 1424 1425 // If we find a field representing an anonymous field, look in the 1426 // IndirectFieldDecl that follow for the designated initializer. 1427 if (!KnownField && Field->isAnonymousStructOrUnion()) { 1428 if (IndirectFieldDecl *IF = 1429 FindIndirectFieldDesignator(*Field, FieldName)) { 1430 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF); 1431 D = DIE->getDesignator(DesigIdx); 1432 break; 1433 } 1434 } 1435 if (KnownField && KnownField == *Field) 1436 break; 1437 if (FieldName && FieldName == Field->getIdentifier()) 1438 break; 1439 1440 ++FieldIndex; 1441 } 1442 1443 if (Field == FieldEnd) { 1444 // There was no normal field in the struct with the designated 1445 // name. Perform another lookup for this name, which may find 1446 // something that we can't designate (e.g., a member function), 1447 // may find nothing, or may find a member of an anonymous 1448 // struct/union. 1449 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName); 1450 FieldDecl *ReplacementField = 0; 1451 if (Lookup.first == Lookup.second) { 1452 // Name lookup didn't find anything. Determine whether this 1453 // was a typo for another field name. 1454 LookupResult R(SemaRef, FieldName, D->getFieldLoc(), 1455 Sema::LookupMemberName); 1456 TypoCorrection Corrected = SemaRef.CorrectTypo( 1457 DeclarationNameInfo(FieldName, D->getFieldLoc()), 1458 Sema::LookupMemberName, /*Scope=*/NULL, /*SS=*/NULL, 1459 RT->getDecl(), false, Sema::CTC_NoKeywords); 1460 if ((ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>()) && 1461 ReplacementField->getDeclContext()->getRedeclContext() 1462 ->Equals(RT->getDecl())) { 1463 std::string CorrectedStr( 1464 Corrected.getAsString(SemaRef.getLangOptions())); 1465 std::string CorrectedQuotedStr( 1466 Corrected.getQuoted(SemaRef.getLangOptions())); 1467 SemaRef.Diag(D->getFieldLoc(), 1468 diag::err_field_designator_unknown_suggest) 1469 << FieldName << CurrentObjectType << CorrectedQuotedStr 1470 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr); 1471 SemaRef.Diag(ReplacementField->getLocation(), 1472 diag::note_previous_decl) << CorrectedQuotedStr; 1473 } else { 1474 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown) 1475 << FieldName << CurrentObjectType; 1476 ++Index; 1477 return true; 1478 } 1479 } 1480 1481 if (!ReplacementField) { 1482 // Name lookup found something, but it wasn't a field. 1483 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield) 1484 << FieldName; 1485 SemaRef.Diag((*Lookup.first)->getLocation(), 1486 diag::note_field_designator_found); 1487 ++Index; 1488 return true; 1489 } 1490 1491 if (!KnownField) { 1492 // The replacement field comes from typo correction; find it 1493 // in the list of fields. 1494 FieldIndex = 0; 1495 Field = RT->getDecl()->field_begin(); 1496 for (; Field != FieldEnd; ++Field) { 1497 if (Field->isUnnamedBitfield()) 1498 continue; 1499 1500 if (ReplacementField == *Field || 1501 Field->getIdentifier() == ReplacementField->getIdentifier()) 1502 break; 1503 1504 ++FieldIndex; 1505 } 1506 } 1507 } 1508 1509 // All of the fields of a union are located at the same place in 1510 // the initializer list. 1511 if (RT->getDecl()->isUnion()) { 1512 FieldIndex = 0; 1513 StructuredList->setInitializedFieldInUnion(*Field); 1514 } 1515 1516 // Make sure we can use this declaration. 1517 if (SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc())) { 1518 ++Index; 1519 return true; 1520 } 1521 1522 // Update the designator with the field declaration. 1523 D->setField(*Field); 1524 1525 // Make sure that our non-designated initializer list has space 1526 // for a subobject corresponding to this field. 1527 if (FieldIndex >= StructuredList->getNumInits()) 1528 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1); 1529 1530 // This designator names a flexible array member. 1531 if (Field->getType()->isIncompleteArrayType()) { 1532 bool Invalid = false; 1533 if ((DesigIdx + 1) != DIE->size()) { 1534 // We can't designate an object within the flexible array 1535 // member (because GCC doesn't allow it). 1536 DesignatedInitExpr::Designator *NextD 1537 = DIE->getDesignator(DesigIdx + 1); 1538 SemaRef.Diag(NextD->getStartLocation(), 1539 diag::err_designator_into_flexible_array_member) 1540 << SourceRange(NextD->getStartLocation(), 1541 DIE->getSourceRange().getEnd()); 1542 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1543 << *Field; 1544 Invalid = true; 1545 } 1546 1547 if (!hadError && !isa<InitListExpr>(DIE->getInit()) && 1548 !isa<StringLiteral>(DIE->getInit())) { 1549 // The initializer is not an initializer list. 1550 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(), 1551 diag::err_flexible_array_init_needs_braces) 1552 << DIE->getInit()->getSourceRange(); 1553 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1554 << *Field; 1555 Invalid = true; 1556 } 1557 1558 // Handle GNU flexible array initializers. 1559 if (!Invalid && !TopLevelObject && 1560 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) { 1561 SemaRef.Diag(DIE->getSourceRange().getBegin(), 1562 diag::err_flexible_array_init_nonempty) 1563 << DIE->getSourceRange().getBegin(); 1564 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) 1565 << *Field; 1566 Invalid = true; 1567 } 1568 1569 if (Invalid) { 1570 ++Index; 1571 return true; 1572 } 1573 1574 // Initialize the array. 1575 bool prevHadError = hadError; 1576 unsigned newStructuredIndex = FieldIndex; 1577 unsigned OldIndex = Index; 1578 IList->setInit(Index, DIE->getInit()); 1579 1580 InitializedEntity MemberEntity = 1581 InitializedEntity::InitializeMember(*Field, &Entity); 1582 CheckSubElementType(MemberEntity, IList, Field->getType(), Index, 1583 StructuredList, newStructuredIndex); 1584 1585 IList->setInit(OldIndex, DIE); 1586 if (hadError && !prevHadError) { 1587 ++Field; 1588 ++FieldIndex; 1589 if (NextField) 1590 *NextField = Field; 1591 StructuredIndex = FieldIndex; 1592 return true; 1593 } 1594 } else { 1595 // Recurse to check later designated subobjects. 1596 QualType FieldType = (*Field)->getType(); 1597 unsigned newStructuredIndex = FieldIndex; 1598 1599 InitializedEntity MemberEntity = 1600 InitializedEntity::InitializeMember(*Field, &Entity); 1601 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1, 1602 FieldType, 0, 0, Index, 1603 StructuredList, newStructuredIndex, 1604 true, false)) 1605 return true; 1606 } 1607 1608 // Find the position of the next field to be initialized in this 1609 // subobject. 1610 ++Field; 1611 ++FieldIndex; 1612 1613 // If this the first designator, our caller will continue checking 1614 // the rest of this struct/class/union subobject. 1615 if (IsFirstDesignator) { 1616 if (NextField) 1617 *NextField = Field; 1618 StructuredIndex = FieldIndex; 1619 return false; 1620 } 1621 1622 if (!FinishSubobjectInit) 1623 return false; 1624 1625 // We've already initialized something in the union; we're done. 1626 if (RT->getDecl()->isUnion()) 1627 return hadError; 1628 1629 // Check the remaining fields within this class/struct/union subobject. 1630 bool prevHadError = hadError; 1631 1632 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index, 1633 StructuredList, FieldIndex); 1634 return hadError && !prevHadError; 1635 } 1636 1637 // C99 6.7.8p6: 1638 // 1639 // If a designator has the form 1640 // 1641 // [ constant-expression ] 1642 // 1643 // then the current object (defined below) shall have array 1644 // type and the expression shall be an integer constant 1645 // expression. If the array is of unknown size, any 1646 // nonnegative value is valid. 1647 // 1648 // Additionally, cope with the GNU extension that permits 1649 // designators of the form 1650 // 1651 // [ constant-expression ... constant-expression ] 1652 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType); 1653 if (!AT) { 1654 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array) 1655 << CurrentObjectType; 1656 ++Index; 1657 return true; 1658 } 1659 1660 Expr *IndexExpr = 0; 1661 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex; 1662 if (D->isArrayDesignator()) { 1663 IndexExpr = DIE->getArrayIndex(*D); 1664 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context); 1665 DesignatedEndIndex = DesignatedStartIndex; 1666 } else { 1667 assert(D->isArrayRangeDesignator() && "Need array-range designator"); 1668 1669 DesignatedStartIndex = 1670 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context); 1671 DesignatedEndIndex = 1672 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context); 1673 IndexExpr = DIE->getArrayRangeEnd(*D); 1674 1675 // Codegen can't handle evaluating array range designators that have side 1676 // effects, because we replicate the AST value for each initialized element. 1677 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple 1678 // elements with something that has a side effect, so codegen can emit an 1679 // "error unsupported" error instead of miscompiling the app. 1680 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&& 1681 DIE->getInit()->HasSideEffects(SemaRef.Context)) 1682 FullyStructuredList->sawArrayRangeDesignator(); 1683 } 1684 1685 if (isa<ConstantArrayType>(AT)) { 1686 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false); 1687 DesignatedStartIndex 1688 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth()); 1689 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned()); 1690 DesignatedEndIndex 1691 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth()); 1692 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned()); 1693 if (DesignatedEndIndex >= MaxElements) { 1694 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(), 1695 diag::err_array_designator_too_large) 1696 << DesignatedEndIndex.toString(10) << MaxElements.toString(10) 1697 << IndexExpr->getSourceRange(); 1698 ++Index; 1699 return true; 1700 } 1701 } else { 1702 // Make sure the bit-widths and signedness match. 1703 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth()) 1704 DesignatedEndIndex 1705 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth()); 1706 else if (DesignatedStartIndex.getBitWidth() < 1707 DesignatedEndIndex.getBitWidth()) 1708 DesignatedStartIndex 1709 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth()); 1710 DesignatedStartIndex.setIsUnsigned(true); 1711 DesignatedEndIndex.setIsUnsigned(true); 1712 } 1713 1714 // Make sure that our non-designated initializer list has space 1715 // for a subobject corresponding to this array element. 1716 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits()) 1717 StructuredList->resizeInits(SemaRef.Context, 1718 DesignatedEndIndex.getZExtValue() + 1); 1719 1720 // Repeatedly perform subobject initializations in the range 1721 // [DesignatedStartIndex, DesignatedEndIndex]. 1722 1723 // Move to the next designator 1724 unsigned ElementIndex = DesignatedStartIndex.getZExtValue(); 1725 unsigned OldIndex = Index; 1726 1727 InitializedEntity ElementEntity = 1728 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); 1729 1730 while (DesignatedStartIndex <= DesignatedEndIndex) { 1731 // Recurse to check later designated subobjects. 1732 QualType ElementType = AT->getElementType(); 1733 Index = OldIndex; 1734 1735 ElementEntity.setElementIndex(ElementIndex); 1736 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1, 1737 ElementType, 0, 0, Index, 1738 StructuredList, ElementIndex, 1739 (DesignatedStartIndex == DesignatedEndIndex), 1740 false)) 1741 return true; 1742 1743 // Move to the next index in the array that we'll be initializing. 1744 ++DesignatedStartIndex; 1745 ElementIndex = DesignatedStartIndex.getZExtValue(); 1746 } 1747 1748 // If this the first designator, our caller will continue checking 1749 // the rest of this array subobject. 1750 if (IsFirstDesignator) { 1751 if (NextElementIndex) 1752 *NextElementIndex = DesignatedStartIndex; 1753 StructuredIndex = ElementIndex; 1754 return false; 1755 } 1756 1757 if (!FinishSubobjectInit) 1758 return false; 1759 1760 // Check the remaining elements within this array subobject. 1761 bool prevHadError = hadError; 1762 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex, 1763 /*SubobjectIsDesignatorContext=*/false, Index, 1764 StructuredList, ElementIndex); 1765 return hadError && !prevHadError; 1766} 1767 1768// Get the structured initializer list for a subobject of type 1769// @p CurrentObjectType. 1770InitListExpr * 1771InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, 1772 QualType CurrentObjectType, 1773 InitListExpr *StructuredList, 1774 unsigned StructuredIndex, 1775 SourceRange InitRange) { 1776 Expr *ExistingInit = 0; 1777 if (!StructuredList) 1778 ExistingInit = SyntacticToSemantic[IList]; 1779 else if (StructuredIndex < StructuredList->getNumInits()) 1780 ExistingInit = StructuredList->getInit(StructuredIndex); 1781 1782 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit)) 1783 return Result; 1784 1785 if (ExistingInit) { 1786 // We are creating an initializer list that initializes the 1787 // subobjects of the current object, but there was already an 1788 // initialization that completely initialized the current 1789 // subobject, e.g., by a compound literal: 1790 // 1791 // struct X { int a, b; }; 1792 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 }; 1793 // 1794 // Here, xs[0].a == 0 and xs[0].b == 3, since the second, 1795 // designated initializer re-initializes the whole 1796 // subobject [0], overwriting previous initializers. 1797 SemaRef.Diag(InitRange.getBegin(), 1798 diag::warn_subobject_initializer_overrides) 1799 << InitRange; 1800 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(), 1801 diag::note_previous_initializer) 1802 << /*FIXME:has side effects=*/0 1803 << ExistingInit->getSourceRange(); 1804 } 1805 1806 InitListExpr *Result 1807 = new (SemaRef.Context) InitListExpr(SemaRef.Context, 1808 InitRange.getBegin(), 0, 0, 1809 InitRange.getEnd()); 1810 1811 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context)); 1812 1813 // Pre-allocate storage for the structured initializer list. 1814 unsigned NumElements = 0; 1815 unsigned NumInits = 0; 1816 bool GotNumInits = false; 1817 if (!StructuredList) { 1818 NumInits = IList->getNumInits(); 1819 GotNumInits = true; 1820 } else if (Index < IList->getNumInits()) { 1821 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) { 1822 NumInits = SubList->getNumInits(); 1823 GotNumInits = true; 1824 } 1825 } 1826 1827 if (const ArrayType *AType 1828 = SemaRef.Context.getAsArrayType(CurrentObjectType)) { 1829 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) { 1830 NumElements = CAType->getSize().getZExtValue(); 1831 // Simple heuristic so that we don't allocate a very large 1832 // initializer with many empty entries at the end. 1833 if (GotNumInits && NumElements > NumInits) 1834 NumElements = 0; 1835 } 1836 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) 1837 NumElements = VType->getNumElements(); 1838 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) { 1839 RecordDecl *RDecl = RType->getDecl(); 1840 if (RDecl->isUnion()) 1841 NumElements = 1; 1842 else 1843 NumElements = std::distance(RDecl->field_begin(), 1844 RDecl->field_end()); 1845 } 1846 1847 if (NumElements < NumInits) 1848 NumElements = IList->getNumInits(); 1849 1850 Result->reserveInits(SemaRef.Context, NumElements); 1851 1852 // Link this new initializer list into the structured initializer 1853 // lists. 1854 if (StructuredList) 1855 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result); 1856 else { 1857 Result->setSyntacticForm(IList); 1858 SyntacticToSemantic[IList] = Result; 1859 } 1860 1861 return Result; 1862} 1863 1864/// Update the initializer at index @p StructuredIndex within the 1865/// structured initializer list to the value @p expr. 1866void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList, 1867 unsigned &StructuredIndex, 1868 Expr *expr) { 1869 // No structured initializer list to update 1870 if (!StructuredList) 1871 return; 1872 1873 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context, 1874 StructuredIndex, expr)) { 1875 // This initializer overwrites a previous initializer. Warn. 1876 SemaRef.Diag(expr->getSourceRange().getBegin(), 1877 diag::warn_initializer_overrides) 1878 << expr->getSourceRange(); 1879 SemaRef.Diag(PrevInit->getSourceRange().getBegin(), 1880 diag::note_previous_initializer) 1881 << /*FIXME:has side effects=*/0 1882 << PrevInit->getSourceRange(); 1883 } 1884 1885 ++StructuredIndex; 1886} 1887 1888/// Check that the given Index expression is a valid array designator 1889/// value. This is essentailly just a wrapper around 1890/// VerifyIntegerConstantExpression that also checks for negative values 1891/// and produces a reasonable diagnostic if there is a 1892/// failure. Returns true if there was an error, false otherwise. If 1893/// everything went okay, Value will receive the value of the constant 1894/// expression. 1895static bool 1896CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) { 1897 SourceLocation Loc = Index->getSourceRange().getBegin(); 1898 1899 // Make sure this is an integer constant expression. 1900 if (S.VerifyIntegerConstantExpression(Index, &Value)) 1901 return true; 1902 1903 if (Value.isSigned() && Value.isNegative()) 1904 return S.Diag(Loc, diag::err_array_designator_negative) 1905 << Value.toString(10) << Index->getSourceRange(); 1906 1907 Value.setIsUnsigned(true); 1908 return false; 1909} 1910 1911ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig, 1912 SourceLocation Loc, 1913 bool GNUSyntax, 1914 ExprResult Init) { 1915 typedef DesignatedInitExpr::Designator ASTDesignator; 1916 1917 bool Invalid = false; 1918 llvm::SmallVector<ASTDesignator, 32> Designators; 1919 llvm::SmallVector<Expr *, 32> InitExpressions; 1920 1921 // Build designators and check array designator expressions. 1922 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) { 1923 const Designator &D = Desig.getDesignator(Idx); 1924 switch (D.getKind()) { 1925 case Designator::FieldDesignator: 1926 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(), 1927 D.getFieldLoc())); 1928 break; 1929 1930 case Designator::ArrayDesignator: { 1931 Expr *Index = static_cast<Expr *>(D.getArrayIndex()); 1932 llvm::APSInt IndexValue; 1933 if (!Index->isTypeDependent() && 1934 !Index->isValueDependent() && 1935 CheckArrayDesignatorExpr(*this, Index, IndexValue)) 1936 Invalid = true; 1937 else { 1938 Designators.push_back(ASTDesignator(InitExpressions.size(), 1939 D.getLBracketLoc(), 1940 D.getRBracketLoc())); 1941 InitExpressions.push_back(Index); 1942 } 1943 break; 1944 } 1945 1946 case Designator::ArrayRangeDesignator: { 1947 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart()); 1948 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd()); 1949 llvm::APSInt StartValue; 1950 llvm::APSInt EndValue; 1951 bool StartDependent = StartIndex->isTypeDependent() || 1952 StartIndex->isValueDependent(); 1953 bool EndDependent = EndIndex->isTypeDependent() || 1954 EndIndex->isValueDependent(); 1955 if ((!StartDependent && 1956 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) || 1957 (!EndDependent && 1958 CheckArrayDesignatorExpr(*this, EndIndex, EndValue))) 1959 Invalid = true; 1960 else { 1961 // Make sure we're comparing values with the same bit width. 1962 if (StartDependent || EndDependent) { 1963 // Nothing to compute. 1964 } else if (StartValue.getBitWidth() > EndValue.getBitWidth()) 1965 EndValue = EndValue.extend(StartValue.getBitWidth()); 1966 else if (StartValue.getBitWidth() < EndValue.getBitWidth()) 1967 StartValue = StartValue.extend(EndValue.getBitWidth()); 1968 1969 if (!StartDependent && !EndDependent && EndValue < StartValue) { 1970 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range) 1971 << StartValue.toString(10) << EndValue.toString(10) 1972 << StartIndex->getSourceRange() << EndIndex->getSourceRange(); 1973 Invalid = true; 1974 } else { 1975 Designators.push_back(ASTDesignator(InitExpressions.size(), 1976 D.getLBracketLoc(), 1977 D.getEllipsisLoc(), 1978 D.getRBracketLoc())); 1979 InitExpressions.push_back(StartIndex); 1980 InitExpressions.push_back(EndIndex); 1981 } 1982 } 1983 break; 1984 } 1985 } 1986 } 1987 1988 if (Invalid || Init.isInvalid()) 1989 return ExprError(); 1990 1991 // Clear out the expressions within the designation. 1992 Desig.ClearExprs(*this); 1993 1994 DesignatedInitExpr *DIE 1995 = DesignatedInitExpr::Create(Context, 1996 Designators.data(), Designators.size(), 1997 InitExpressions.data(), InitExpressions.size(), 1998 Loc, GNUSyntax, Init.takeAs<Expr>()); 1999 2000 if (getLangOptions().CPlusPlus) 2001 Diag(DIE->getLocStart(), diag::ext_designated_init_cxx) 2002 << DIE->getSourceRange(); 2003 else if (!getLangOptions().C99) 2004 Diag(DIE->getLocStart(), diag::ext_designated_init) 2005 << DIE->getSourceRange(); 2006 2007 return Owned(DIE); 2008} 2009 2010bool Sema::CheckInitList(const InitializedEntity &Entity, 2011 InitListExpr *&InitList, QualType &DeclType) { 2012 InitListChecker CheckInitList(*this, Entity, InitList, DeclType); 2013 if (!CheckInitList.HadError()) 2014 InitList = CheckInitList.getFullyStructuredList(); 2015 2016 return CheckInitList.HadError(); 2017} 2018 2019//===----------------------------------------------------------------------===// 2020// Initialization entity 2021//===----------------------------------------------------------------------===// 2022 2023InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index, 2024 const InitializedEntity &Parent) 2025 : Parent(&Parent), Index(Index) 2026{ 2027 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) { 2028 Kind = EK_ArrayElement; 2029 Type = AT->getElementType(); 2030 } else { 2031 Kind = EK_VectorElement; 2032 Type = Parent.getType()->getAs<VectorType>()->getElementType(); 2033 } 2034} 2035 2036InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context, 2037 CXXBaseSpecifier *Base, 2038 bool IsInheritedVirtualBase) 2039{ 2040 InitializedEntity Result; 2041 Result.Kind = EK_Base; 2042 Result.Base = reinterpret_cast<uintptr_t>(Base); 2043 if (IsInheritedVirtualBase) 2044 Result.Base |= 0x01; 2045 2046 Result.Type = Base->getType(); 2047 return Result; 2048} 2049 2050DeclarationName InitializedEntity::getName() const { 2051 switch (getKind()) { 2052 case EK_Parameter: { 2053 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1); 2054 return (D ? D->getDeclName() : DeclarationName()); 2055 } 2056 2057 case EK_Variable: 2058 case EK_Member: 2059 return VariableOrMember->getDeclName(); 2060 2061 case EK_Result: 2062 case EK_Exception: 2063 case EK_New: 2064 case EK_Temporary: 2065 case EK_Base: 2066 case EK_Delegating: 2067 case EK_ArrayElement: 2068 case EK_VectorElement: 2069 case EK_BlockElement: 2070 return DeclarationName(); 2071 } 2072 2073 // Silence GCC warning 2074 return DeclarationName(); 2075} 2076 2077DeclaratorDecl *InitializedEntity::getDecl() const { 2078 switch (getKind()) { 2079 case EK_Variable: 2080 case EK_Member: 2081 return VariableOrMember; 2082 2083 case EK_Parameter: 2084 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1); 2085 2086 case EK_Result: 2087 case EK_Exception: 2088 case EK_New: 2089 case EK_Temporary: 2090 case EK_Base: 2091 case EK_Delegating: 2092 case EK_ArrayElement: 2093 case EK_VectorElement: 2094 case EK_BlockElement: 2095 return 0; 2096 } 2097 2098 // Silence GCC warning 2099 return 0; 2100} 2101 2102bool InitializedEntity::allowsNRVO() const { 2103 switch (getKind()) { 2104 case EK_Result: 2105 case EK_Exception: 2106 return LocAndNRVO.NRVO; 2107 2108 case EK_Variable: 2109 case EK_Parameter: 2110 case EK_Member: 2111 case EK_New: 2112 case EK_Temporary: 2113 case EK_Base: 2114 case EK_Delegating: 2115 case EK_ArrayElement: 2116 case EK_VectorElement: 2117 case EK_BlockElement: 2118 break; 2119 } 2120 2121 return false; 2122} 2123 2124//===----------------------------------------------------------------------===// 2125// Initialization sequence 2126//===----------------------------------------------------------------------===// 2127 2128void InitializationSequence::Step::Destroy() { 2129 switch (Kind) { 2130 case SK_ResolveAddressOfOverloadedFunction: 2131 case SK_CastDerivedToBaseRValue: 2132 case SK_CastDerivedToBaseXValue: 2133 case SK_CastDerivedToBaseLValue: 2134 case SK_BindReference: 2135 case SK_BindReferenceToTemporary: 2136 case SK_ExtraneousCopyToTemporary: 2137 case SK_UserConversion: 2138 case SK_QualificationConversionRValue: 2139 case SK_QualificationConversionXValue: 2140 case SK_QualificationConversionLValue: 2141 case SK_ListInitialization: 2142 case SK_ConstructorInitialization: 2143 case SK_ZeroInitialization: 2144 case SK_CAssignment: 2145 case SK_StringInit: 2146 case SK_ObjCObjectConversion: 2147 case SK_ArrayInit: 2148 case SK_PassByIndirectCopyRestore: 2149 case SK_PassByIndirectRestore: 2150 case SK_ProduceObjCObject: 2151 break; 2152 2153 case SK_ConversionSequence: 2154 delete ICS; 2155 } 2156} 2157 2158bool InitializationSequence::isDirectReferenceBinding() const { 2159 return !Steps.empty() && Steps.back().Kind == SK_BindReference; 2160} 2161 2162bool InitializationSequence::isAmbiguous() const { 2163 if (!Failed()) 2164 return false; 2165 2166 switch (getFailureKind()) { 2167 case FK_TooManyInitsForReference: 2168 case FK_ArrayNeedsInitList: 2169 case FK_ArrayNeedsInitListOrStringLiteral: 2170 case FK_AddressOfOverloadFailed: // FIXME: Could do better 2171 case FK_NonConstLValueReferenceBindingToTemporary: 2172 case FK_NonConstLValueReferenceBindingToUnrelated: 2173 case FK_RValueReferenceBindingToLValue: 2174 case FK_ReferenceInitDropsQualifiers: 2175 case FK_ReferenceInitFailed: 2176 case FK_ConversionFailed: 2177 case FK_ConversionFromPropertyFailed: 2178 case FK_TooManyInitsForScalar: 2179 case FK_ReferenceBindingToInitList: 2180 case FK_InitListBadDestinationType: 2181 case FK_DefaultInitOfConst: 2182 case FK_Incomplete: 2183 case FK_ArrayTypeMismatch: 2184 case FK_NonConstantArrayInit: 2185 return false; 2186 2187 case FK_ReferenceInitOverloadFailed: 2188 case FK_UserConversionOverloadFailed: 2189 case FK_ConstructorOverloadFailed: 2190 return FailedOverloadResult == OR_Ambiguous; 2191 } 2192 2193 return false; 2194} 2195 2196bool InitializationSequence::isConstructorInitialization() const { 2197 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization; 2198} 2199 2200void InitializationSequence::AddAddressOverloadResolutionStep( 2201 FunctionDecl *Function, 2202 DeclAccessPair Found) { 2203 Step S; 2204 S.Kind = SK_ResolveAddressOfOverloadedFunction; 2205 S.Type = Function->getType(); 2206 S.Function.Function = Function; 2207 S.Function.FoundDecl = Found; 2208 Steps.push_back(S); 2209} 2210 2211void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType, 2212 ExprValueKind VK) { 2213 Step S; 2214 switch (VK) { 2215 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break; 2216 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break; 2217 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break; 2218 default: llvm_unreachable("No such category"); 2219 } 2220 S.Type = BaseType; 2221 Steps.push_back(S); 2222} 2223 2224void InitializationSequence::AddReferenceBindingStep(QualType T, 2225 bool BindingTemporary) { 2226 Step S; 2227 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference; 2228 S.Type = T; 2229 Steps.push_back(S); 2230} 2231 2232void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) { 2233 Step S; 2234 S.Kind = SK_ExtraneousCopyToTemporary; 2235 S.Type = T; 2236 Steps.push_back(S); 2237} 2238 2239void InitializationSequence::AddUserConversionStep(FunctionDecl *Function, 2240 DeclAccessPair FoundDecl, 2241 QualType T) { 2242 Step S; 2243 S.Kind = SK_UserConversion; 2244 S.Type = T; 2245 S.Function.Function = Function; 2246 S.Function.FoundDecl = FoundDecl; 2247 Steps.push_back(S); 2248} 2249 2250void InitializationSequence::AddQualificationConversionStep(QualType Ty, 2251 ExprValueKind VK) { 2252 Step S; 2253 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning 2254 switch (VK) { 2255 case VK_RValue: 2256 S.Kind = SK_QualificationConversionRValue; 2257 break; 2258 case VK_XValue: 2259 S.Kind = SK_QualificationConversionXValue; 2260 break; 2261 case VK_LValue: 2262 S.Kind = SK_QualificationConversionLValue; 2263 break; 2264 } 2265 S.Type = Ty; 2266 Steps.push_back(S); 2267} 2268 2269void InitializationSequence::AddConversionSequenceStep( 2270 const ImplicitConversionSequence &ICS, 2271 QualType T) { 2272 Step S; 2273 S.Kind = SK_ConversionSequence; 2274 S.Type = T; 2275 S.ICS = new ImplicitConversionSequence(ICS); 2276 Steps.push_back(S); 2277} 2278 2279void InitializationSequence::AddListInitializationStep(QualType T) { 2280 Step S; 2281 S.Kind = SK_ListInitialization; 2282 S.Type = T; 2283 Steps.push_back(S); 2284} 2285 2286void 2287InitializationSequence::AddConstructorInitializationStep( 2288 CXXConstructorDecl *Constructor, 2289 AccessSpecifier Access, 2290 QualType T) { 2291 Step S; 2292 S.Kind = SK_ConstructorInitialization; 2293 S.Type = T; 2294 S.Function.Function = Constructor; 2295 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access); 2296 Steps.push_back(S); 2297} 2298 2299void InitializationSequence::AddZeroInitializationStep(QualType T) { 2300 Step S; 2301 S.Kind = SK_ZeroInitialization; 2302 S.Type = T; 2303 Steps.push_back(S); 2304} 2305 2306void InitializationSequence::AddCAssignmentStep(QualType T) { 2307 Step S; 2308 S.Kind = SK_CAssignment; 2309 S.Type = T; 2310 Steps.push_back(S); 2311} 2312 2313void InitializationSequence::AddStringInitStep(QualType T) { 2314 Step S; 2315 S.Kind = SK_StringInit; 2316 S.Type = T; 2317 Steps.push_back(S); 2318} 2319 2320void InitializationSequence::AddObjCObjectConversionStep(QualType T) { 2321 Step S; 2322 S.Kind = SK_ObjCObjectConversion; 2323 S.Type = T; 2324 Steps.push_back(S); 2325} 2326 2327void InitializationSequence::AddArrayInitStep(QualType T) { 2328 Step S; 2329 S.Kind = SK_ArrayInit; 2330 S.Type = T; 2331 Steps.push_back(S); 2332} 2333 2334void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type, 2335 bool shouldCopy) { 2336 Step s; 2337 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore 2338 : SK_PassByIndirectRestore); 2339 s.Type = type; 2340 Steps.push_back(s); 2341} 2342 2343void InitializationSequence::AddProduceObjCObjectStep(QualType T) { 2344 Step S; 2345 S.Kind = SK_ProduceObjCObject; 2346 S.Type = T; 2347 Steps.push_back(S); 2348} 2349 2350void InitializationSequence::SetOverloadFailure(FailureKind Failure, 2351 OverloadingResult Result) { 2352 setSequenceKind(FailedSequence); 2353 this->Failure = Failure; 2354 this->FailedOverloadResult = Result; 2355} 2356 2357//===----------------------------------------------------------------------===// 2358// Attempt initialization 2359//===----------------------------------------------------------------------===// 2360 2361static void MaybeProduceObjCObject(Sema &S, 2362 InitializationSequence &Sequence, 2363 const InitializedEntity &Entity) { 2364 if (!S.getLangOptions().ObjCAutoRefCount) return; 2365 2366 /// When initializing a parameter, produce the value if it's marked 2367 /// __attribute__((ns_consumed)). 2368 if (Entity.getKind() == InitializedEntity::EK_Parameter) { 2369 if (!Entity.isParameterConsumed()) 2370 return; 2371 2372 assert(Entity.getType()->isObjCRetainableType() && 2373 "consuming an object of unretainable type?"); 2374 Sequence.AddProduceObjCObjectStep(Entity.getType()); 2375 2376 /// When initializing a return value, if the return type is a 2377 /// retainable type, then returns need to immediately retain the 2378 /// object. If an autorelease is required, it will be done at the 2379 /// last instant. 2380 } else if (Entity.getKind() == InitializedEntity::EK_Result) { 2381 if (!Entity.getType()->isObjCRetainableType()) 2382 return; 2383 2384 Sequence.AddProduceObjCObjectStep(Entity.getType()); 2385 } 2386} 2387 2388/// \brief Attempt list initialization (C++0x [dcl.init.list]) 2389static void TryListInitialization(Sema &S, 2390 const InitializedEntity &Entity, 2391 const InitializationKind &Kind, 2392 InitListExpr *InitList, 2393 InitializationSequence &Sequence) { 2394 // FIXME: We only perform rudimentary checking of list 2395 // initializations at this point, then assume that any list 2396 // initialization of an array, aggregate, or scalar will be 2397 // well-formed. When we actually "perform" list initialization, we'll 2398 // do all of the necessary checking. C++0x initializer lists will 2399 // force us to perform more checking here. 2400 2401 QualType DestType = Entity.getType(); 2402 2403 // C++ [dcl.init]p13: 2404 // If T is a scalar type, then a declaration of the form 2405 // 2406 // T x = { a }; 2407 // 2408 // is equivalent to 2409 // 2410 // T x = a; 2411 if (DestType->isScalarType()) { 2412 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) { 2413 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar); 2414 return; 2415 } 2416 2417 // Assume scalar initialization from a single value works. 2418 } else if (DestType->isAggregateType()) { 2419 // Assume aggregate initialization works. 2420 } else if (DestType->isVectorType()) { 2421 // Assume vector initialization works. 2422 } else if (DestType->isReferenceType()) { 2423 // FIXME: C++0x defines behavior for this. 2424 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList); 2425 return; 2426 } else if (DestType->isRecordType()) { 2427 // FIXME: C++0x defines behavior for this 2428 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType); 2429 } 2430 2431 // Add a general "list initialization" step. 2432 Sequence.AddListInitializationStep(DestType); 2433} 2434 2435/// \brief Try a reference initialization that involves calling a conversion 2436/// function. 2437static OverloadingResult TryRefInitWithConversionFunction(Sema &S, 2438 const InitializedEntity &Entity, 2439 const InitializationKind &Kind, 2440 Expr *Initializer, 2441 bool AllowRValues, 2442 InitializationSequence &Sequence) { 2443 QualType DestType = Entity.getType(); 2444 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType(); 2445 QualType T1 = cv1T1.getUnqualifiedType(); 2446 QualType cv2T2 = Initializer->getType(); 2447 QualType T2 = cv2T2.getUnqualifiedType(); 2448 2449 bool DerivedToBase; 2450 bool ObjCConversion; 2451 bool ObjCLifetimeConversion; 2452 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(), 2453 T1, T2, DerivedToBase, 2454 ObjCConversion, 2455 ObjCLifetimeConversion) && 2456 "Must have incompatible references when binding via conversion"); 2457 (void)DerivedToBase; 2458 (void)ObjCConversion; 2459 (void)ObjCLifetimeConversion; 2460 2461 // Build the candidate set directly in the initialization sequence 2462 // structure, so that it will persist if we fail. 2463 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 2464 CandidateSet.clear(); 2465 2466 // Determine whether we are allowed to call explicit constructors or 2467 // explicit conversion operators. 2468 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct; 2469 2470 const RecordType *T1RecordType = 0; 2471 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) && 2472 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) { 2473 // The type we're converting to is a class type. Enumerate its constructors 2474 // to see if there is a suitable conversion. 2475 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl()); 2476 2477 DeclContext::lookup_iterator Con, ConEnd; 2478 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl); 2479 Con != ConEnd; ++Con) { 2480 NamedDecl *D = *Con; 2481 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2482 2483 // Find the constructor (which may be a template). 2484 CXXConstructorDecl *Constructor = 0; 2485 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D); 2486 if (ConstructorTmpl) 2487 Constructor = cast<CXXConstructorDecl>( 2488 ConstructorTmpl->getTemplatedDecl()); 2489 else 2490 Constructor = cast<CXXConstructorDecl>(D); 2491 2492 if (!Constructor->isInvalidDecl() && 2493 Constructor->isConvertingConstructor(AllowExplicit)) { 2494 if (ConstructorTmpl) 2495 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2496 /*ExplicitArgs*/ 0, 2497 &Initializer, 1, CandidateSet, 2498 /*SuppressUserConversions=*/true); 2499 else 2500 S.AddOverloadCandidate(Constructor, FoundDecl, 2501 &Initializer, 1, CandidateSet, 2502 /*SuppressUserConversions=*/true); 2503 } 2504 } 2505 } 2506 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl()) 2507 return OR_No_Viable_Function; 2508 2509 const RecordType *T2RecordType = 0; 2510 if ((T2RecordType = T2->getAs<RecordType>()) && 2511 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) { 2512 // The type we're converting from is a class type, enumerate its conversion 2513 // functions. 2514 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl()); 2515 2516 const UnresolvedSetImpl *Conversions 2517 = T2RecordDecl->getVisibleConversionFunctions(); 2518 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(), 2519 E = Conversions->end(); I != E; ++I) { 2520 NamedDecl *D = *I; 2521 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 2522 if (isa<UsingShadowDecl>(D)) 2523 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2524 2525 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 2526 CXXConversionDecl *Conv; 2527 if (ConvTemplate) 2528 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 2529 else 2530 Conv = cast<CXXConversionDecl>(D); 2531 2532 // If the conversion function doesn't return a reference type, 2533 // it can't be considered for this conversion unless we're allowed to 2534 // consider rvalues. 2535 // FIXME: Do we need to make sure that we only consider conversion 2536 // candidates with reference-compatible results? That might be needed to 2537 // break recursion. 2538 if ((AllowExplicit || !Conv->isExplicit()) && 2539 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){ 2540 if (ConvTemplate) 2541 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), 2542 ActingDC, Initializer, 2543 DestType, CandidateSet); 2544 else 2545 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, 2546 Initializer, DestType, CandidateSet); 2547 } 2548 } 2549 } 2550 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl()) 2551 return OR_No_Viable_Function; 2552 2553 SourceLocation DeclLoc = Initializer->getLocStart(); 2554 2555 // Perform overload resolution. If it fails, return the failed result. 2556 OverloadCandidateSet::iterator Best; 2557 if (OverloadingResult Result 2558 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) 2559 return Result; 2560 2561 FunctionDecl *Function = Best->Function; 2562 2563 // This is the overload that will actually be used for the initialization, so 2564 // mark it as used. 2565 S.MarkDeclarationReferenced(DeclLoc, Function); 2566 2567 // Compute the returned type of the conversion. 2568 if (isa<CXXConversionDecl>(Function)) 2569 T2 = Function->getResultType(); 2570 else 2571 T2 = cv1T1; 2572 2573 // Add the user-defined conversion step. 2574 Sequence.AddUserConversionStep(Function, Best->FoundDecl, 2575 T2.getNonLValueExprType(S.Context)); 2576 2577 // Determine whether we need to perform derived-to-base or 2578 // cv-qualification adjustments. 2579 ExprValueKind VK = VK_RValue; 2580 if (T2->isLValueReferenceType()) 2581 VK = VK_LValue; 2582 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>()) 2583 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue; 2584 2585 bool NewDerivedToBase = false; 2586 bool NewObjCConversion = false; 2587 bool NewObjCLifetimeConversion = false; 2588 Sema::ReferenceCompareResult NewRefRelationship 2589 = S.CompareReferenceRelationship(DeclLoc, T1, 2590 T2.getNonLValueExprType(S.Context), 2591 NewDerivedToBase, NewObjCConversion, 2592 NewObjCLifetimeConversion); 2593 if (NewRefRelationship == Sema::Ref_Incompatible) { 2594 // If the type we've converted to is not reference-related to the 2595 // type we're looking for, then there is another conversion step 2596 // we need to perform to produce a temporary of the right type 2597 // that we'll be binding to. 2598 ImplicitConversionSequence ICS; 2599 ICS.setStandard(); 2600 ICS.Standard = Best->FinalConversion; 2601 T2 = ICS.Standard.getToType(2); 2602 Sequence.AddConversionSequenceStep(ICS, T2); 2603 } else if (NewDerivedToBase) 2604 Sequence.AddDerivedToBaseCastStep( 2605 S.Context.getQualifiedType(T1, 2606 T2.getNonReferenceType().getQualifiers()), 2607 VK); 2608 else if (NewObjCConversion) 2609 Sequence.AddObjCObjectConversionStep( 2610 S.Context.getQualifiedType(T1, 2611 T2.getNonReferenceType().getQualifiers())); 2612 2613 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers()) 2614 Sequence.AddQualificationConversionStep(cv1T1, VK); 2615 2616 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType()); 2617 return OR_Success; 2618} 2619 2620/// \brief Attempt reference initialization (C++0x [dcl.init.ref]) 2621static void TryReferenceInitialization(Sema &S, 2622 const InitializedEntity &Entity, 2623 const InitializationKind &Kind, 2624 Expr *Initializer, 2625 InitializationSequence &Sequence) { 2626 QualType DestType = Entity.getType(); 2627 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType(); 2628 Qualifiers T1Quals; 2629 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals); 2630 QualType cv2T2 = Initializer->getType(); 2631 Qualifiers T2Quals; 2632 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals); 2633 SourceLocation DeclLoc = Initializer->getLocStart(); 2634 2635 // If the initializer is the address of an overloaded function, try 2636 // to resolve the overloaded function. If all goes well, T2 is the 2637 // type of the resulting function. 2638 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 2639 DeclAccessPair Found; 2640 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer, 2641 T1, 2642 false, 2643 Found)) { 2644 Sequence.AddAddressOverloadResolutionStep(Fn, Found); 2645 cv2T2 = Fn->getType(); 2646 T2 = cv2T2.getUnqualifiedType(); 2647 } else if (!T1->isRecordType()) { 2648 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 2649 return; 2650 } 2651 } 2652 2653 // Compute some basic properties of the types and the initializer. 2654 bool isLValueRef = DestType->isLValueReferenceType(); 2655 bool isRValueRef = !isLValueRef; 2656 bool DerivedToBase = false; 2657 bool ObjCConversion = false; 2658 bool ObjCLifetimeConversion = false; 2659 Expr::Classification InitCategory = Initializer->Classify(S.Context); 2660 Sema::ReferenceCompareResult RefRelationship 2661 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase, 2662 ObjCConversion, ObjCLifetimeConversion); 2663 2664 // C++0x [dcl.init.ref]p5: 2665 // A reference to type "cv1 T1" is initialized by an expression of type 2666 // "cv2 T2" as follows: 2667 // 2668 // - If the reference is an lvalue reference and the initializer 2669 // expression 2670 // Note the analogous bullet points for rvlaue refs to functions. Because 2671 // there are no function rvalues in C++, rvalue refs to functions are treated 2672 // like lvalue refs. 2673 OverloadingResult ConvOvlResult = OR_Success; 2674 bool T1Function = T1->isFunctionType(); 2675 if (isLValueRef || T1Function) { 2676 if (InitCategory.isLValue() && 2677 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification || 2678 (Kind.isCStyleOrFunctionalCast() && 2679 RefRelationship == Sema::Ref_Related))) { 2680 // - is an lvalue (but is not a bit-field), and "cv1 T1" is 2681 // reference-compatible with "cv2 T2," or 2682 // 2683 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a 2684 // bit-field when we're determining whether the reference initialization 2685 // can occur. However, we do pay attention to whether it is a bit-field 2686 // to decide whether we're actually binding to a temporary created from 2687 // the bit-field. 2688 if (DerivedToBase) 2689 Sequence.AddDerivedToBaseCastStep( 2690 S.Context.getQualifiedType(T1, T2Quals), 2691 VK_LValue); 2692 else if (ObjCConversion) 2693 Sequence.AddObjCObjectConversionStep( 2694 S.Context.getQualifiedType(T1, T2Quals)); 2695 2696 if (T1Quals != T2Quals) 2697 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue); 2698 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() && 2699 (Initializer->getBitField() || Initializer->refersToVectorElement()); 2700 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary); 2701 return; 2702 } 2703 2704 // - has a class type (i.e., T2 is a class type), where T1 is not 2705 // reference-related to T2, and can be implicitly converted to an 2706 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible 2707 // with "cv3 T3" (this conversion is selected by enumerating the 2708 // applicable conversion functions (13.3.1.6) and choosing the best 2709 // one through overload resolution (13.3)), 2710 // If we have an rvalue ref to function type here, the rhs must be 2711 // an rvalue. 2712 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() && 2713 (isLValueRef || InitCategory.isRValue())) { 2714 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind, 2715 Initializer, 2716 /*AllowRValues=*/isRValueRef, 2717 Sequence); 2718 if (ConvOvlResult == OR_Success) 2719 return; 2720 if (ConvOvlResult != OR_No_Viable_Function) { 2721 Sequence.SetOverloadFailure( 2722 InitializationSequence::FK_ReferenceInitOverloadFailed, 2723 ConvOvlResult); 2724 } 2725 } 2726 } 2727 2728 // - Otherwise, the reference shall be an lvalue reference to a 2729 // non-volatile const type (i.e., cv1 shall be const), or the reference 2730 // shall be an rvalue reference. 2731 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) { 2732 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) 2733 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 2734 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) 2735 Sequence.SetOverloadFailure( 2736 InitializationSequence::FK_ReferenceInitOverloadFailed, 2737 ConvOvlResult); 2738 else 2739 Sequence.SetFailed(InitCategory.isLValue() 2740 ? (RefRelationship == Sema::Ref_Related 2741 ? InitializationSequence::FK_ReferenceInitDropsQualifiers 2742 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated) 2743 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary); 2744 2745 return; 2746 } 2747 2748 // - If the initializer expression 2749 // - is an xvalue, class prvalue, array prvalue, or function lvalue and 2750 // "cv1 T1" is reference-compatible with "cv2 T2" 2751 // Note: functions are handled below. 2752 if (!T1Function && 2753 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification || 2754 (Kind.isCStyleOrFunctionalCast() && 2755 RefRelationship == Sema::Ref_Related)) && 2756 (InitCategory.isXValue() || 2757 (InitCategory.isPRValue() && T2->isRecordType()) || 2758 (InitCategory.isPRValue() && T2->isArrayType()))) { 2759 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue; 2760 if (InitCategory.isPRValue() && T2->isRecordType()) { 2761 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the 2762 // compiler the freedom to perform a copy here or bind to the 2763 // object, while C++0x requires that we bind directly to the 2764 // object. Hence, we always bind to the object without making an 2765 // extra copy. However, in C++03 requires that we check for the 2766 // presence of a suitable copy constructor: 2767 // 2768 // The constructor that would be used to make the copy shall 2769 // be callable whether or not the copy is actually done. 2770 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().Microsoft) 2771 Sequence.AddExtraneousCopyToTemporary(cv2T2); 2772 } 2773 2774 if (DerivedToBase) 2775 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals), 2776 ValueKind); 2777 else if (ObjCConversion) 2778 Sequence.AddObjCObjectConversionStep( 2779 S.Context.getQualifiedType(T1, T2Quals)); 2780 2781 if (T1Quals != T2Quals) 2782 Sequence.AddQualificationConversionStep(cv1T1, ValueKind); 2783 Sequence.AddReferenceBindingStep(cv1T1, 2784 /*bindingTemporary=*/(InitCategory.isPRValue() && !T2->isArrayType())); 2785 return; 2786 } 2787 2788 // - has a class type (i.e., T2 is a class type), where T1 is not 2789 // reference-related to T2, and can be implicitly converted to an 2790 // xvalue, class prvalue, or function lvalue of type "cv3 T3", 2791 // where "cv1 T1" is reference-compatible with "cv3 T3", 2792 if (T2->isRecordType()) { 2793 if (RefRelationship == Sema::Ref_Incompatible) { 2794 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, 2795 Kind, Initializer, 2796 /*AllowRValues=*/true, 2797 Sequence); 2798 if (ConvOvlResult) 2799 Sequence.SetOverloadFailure( 2800 InitializationSequence::FK_ReferenceInitOverloadFailed, 2801 ConvOvlResult); 2802 2803 return; 2804 } 2805 2806 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); 2807 return; 2808 } 2809 2810 // - Otherwise, a temporary of type "cv1 T1" is created and initialized 2811 // from the initializer expression using the rules for a non-reference 2812 // copy initialization (8.5). The reference is then bound to the 2813 // temporary. [...] 2814 2815 // Determine whether we are allowed to call explicit constructors or 2816 // explicit conversion operators. 2817 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct); 2818 2819 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1); 2820 2821 ImplicitConversionSequence ICS 2822 = S.TryImplicitConversion(Initializer, TempEntity.getType(), 2823 /*SuppressUserConversions*/ false, 2824 AllowExplicit, 2825 /*FIXME:InOverloadResolution=*/false, 2826 /*CStyle=*/Kind.isCStyleOrFunctionalCast(), 2827 /*AllowObjCWritebackConversion=*/false); 2828 2829 if (ICS.isBad()) { 2830 // FIXME: Use the conversion function set stored in ICS to turn 2831 // this into an overloading ambiguity diagnostic. However, we need 2832 // to keep that set as an OverloadCandidateSet rather than as some 2833 // other kind of set. 2834 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) 2835 Sequence.SetOverloadFailure( 2836 InitializationSequence::FK_ReferenceInitOverloadFailed, 2837 ConvOvlResult); 2838 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) 2839 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 2840 else 2841 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed); 2842 return; 2843 } else { 2844 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType()); 2845 } 2846 2847 // [...] If T1 is reference-related to T2, cv1 must be the 2848 // same cv-qualification as, or greater cv-qualification 2849 // than, cv2; otherwise, the program is ill-formed. 2850 unsigned T1CVRQuals = T1Quals.getCVRQualifiers(); 2851 unsigned T2CVRQuals = T2Quals.getCVRQualifiers(); 2852 if (RefRelationship == Sema::Ref_Related && 2853 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) { 2854 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); 2855 return; 2856 } 2857 2858 // [...] If T1 is reference-related to T2 and the reference is an rvalue 2859 // reference, the initializer expression shall not be an lvalue. 2860 if (RefRelationship >= Sema::Ref_Related && !isLValueRef && 2861 InitCategory.isLValue()) { 2862 Sequence.SetFailed( 2863 InitializationSequence::FK_RValueReferenceBindingToLValue); 2864 return; 2865 } 2866 2867 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true); 2868 return; 2869} 2870 2871/// \brief Attempt character array initialization from a string literal 2872/// (C++ [dcl.init.string], C99 6.7.8). 2873static void TryStringLiteralInitialization(Sema &S, 2874 const InitializedEntity &Entity, 2875 const InitializationKind &Kind, 2876 Expr *Initializer, 2877 InitializationSequence &Sequence) { 2878 Sequence.AddStringInitStep(Entity.getType()); 2879} 2880 2881/// \brief Attempt initialization by constructor (C++ [dcl.init]), which 2882/// enumerates the constructors of the initialized entity and performs overload 2883/// resolution to select the best. 2884static void TryConstructorInitialization(Sema &S, 2885 const InitializedEntity &Entity, 2886 const InitializationKind &Kind, 2887 Expr **Args, unsigned NumArgs, 2888 QualType DestType, 2889 InitializationSequence &Sequence) { 2890 // Build the candidate set directly in the initialization sequence 2891 // structure, so that it will persist if we fail. 2892 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 2893 CandidateSet.clear(); 2894 2895 // Determine whether we are allowed to call explicit constructors or 2896 // explicit conversion operators. 2897 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct || 2898 Kind.getKind() == InitializationKind::IK_Value || 2899 Kind.getKind() == InitializationKind::IK_Default); 2900 2901 // The type we're constructing needs to be complete. 2902 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) { 2903 Sequence.SetFailed(InitializationSequence::FK_Incomplete); 2904 return; 2905 } 2906 2907 // The type we're converting to is a class type. Enumerate its constructors 2908 // to see if one is suitable. 2909 const RecordType *DestRecordType = DestType->getAs<RecordType>(); 2910 assert(DestRecordType && "Constructor initialization requires record type"); 2911 CXXRecordDecl *DestRecordDecl 2912 = cast<CXXRecordDecl>(DestRecordType->getDecl()); 2913 2914 DeclContext::lookup_iterator Con, ConEnd; 2915 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl); 2916 Con != ConEnd; ++Con) { 2917 NamedDecl *D = *Con; 2918 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2919 bool SuppressUserConversions = false; 2920 2921 // Find the constructor (which may be a template). 2922 CXXConstructorDecl *Constructor = 0; 2923 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D); 2924 if (ConstructorTmpl) 2925 Constructor = cast<CXXConstructorDecl>( 2926 ConstructorTmpl->getTemplatedDecl()); 2927 else { 2928 Constructor = cast<CXXConstructorDecl>(D); 2929 2930 // If we're performing copy initialization using a copy constructor, we 2931 // suppress user-defined conversions on the arguments. 2932 // FIXME: Move constructors? 2933 if (Kind.getKind() == InitializationKind::IK_Copy && 2934 Constructor->isCopyConstructor()) 2935 SuppressUserConversions = true; 2936 } 2937 2938 if (!Constructor->isInvalidDecl() && 2939 (AllowExplicit || !Constructor->isExplicit())) { 2940 if (ConstructorTmpl) 2941 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2942 /*ExplicitArgs*/ 0, 2943 Args, NumArgs, CandidateSet, 2944 SuppressUserConversions); 2945 else 2946 S.AddOverloadCandidate(Constructor, FoundDecl, 2947 Args, NumArgs, CandidateSet, 2948 SuppressUserConversions); 2949 } 2950 } 2951 2952 SourceLocation DeclLoc = Kind.getLocation(); 2953 2954 // Perform overload resolution. If it fails, return the failed result. 2955 OverloadCandidateSet::iterator Best; 2956 if (OverloadingResult Result 2957 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 2958 Sequence.SetOverloadFailure( 2959 InitializationSequence::FK_ConstructorOverloadFailed, 2960 Result); 2961 return; 2962 } 2963 2964 // C++0x [dcl.init]p6: 2965 // If a program calls for the default initialization of an object 2966 // of a const-qualified type T, T shall be a class type with a 2967 // user-provided default constructor. 2968 if (Kind.getKind() == InitializationKind::IK_Default && 2969 Entity.getType().isConstQualified() && 2970 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) { 2971 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); 2972 return; 2973 } 2974 2975 // Add the constructor initialization step. Any cv-qualification conversion is 2976 // subsumed by the initialization. 2977 Sequence.AddConstructorInitializationStep( 2978 cast<CXXConstructorDecl>(Best->Function), 2979 Best->FoundDecl.getAccess(), 2980 DestType); 2981} 2982 2983/// \brief Attempt value initialization (C++ [dcl.init]p7). 2984static void TryValueInitialization(Sema &S, 2985 const InitializedEntity &Entity, 2986 const InitializationKind &Kind, 2987 InitializationSequence &Sequence) { 2988 // C++ [dcl.init]p5: 2989 // 2990 // To value-initialize an object of type T means: 2991 QualType T = Entity.getType(); 2992 2993 // -- if T is an array type, then each element is value-initialized; 2994 while (const ArrayType *AT = S.Context.getAsArrayType(T)) 2995 T = AT->getElementType(); 2996 2997 if (const RecordType *RT = T->getAs<RecordType>()) { 2998 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 2999 // -- if T is a class type (clause 9) with a user-declared 3000 // constructor (12.1), then the default constructor for T is 3001 // called (and the initialization is ill-formed if T has no 3002 // accessible default constructor); 3003 // 3004 // FIXME: we really want to refer to a single subobject of the array, 3005 // but Entity doesn't have a way to capture that (yet). 3006 if (ClassDecl->hasUserDeclaredConstructor()) 3007 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence); 3008 3009 // -- if T is a (possibly cv-qualified) non-union class type 3010 // without a user-provided constructor, then the object is 3011 // zero-initialized and, if T's implicitly-declared default 3012 // constructor is non-trivial, that constructor is called. 3013 if ((ClassDecl->getTagKind() == TTK_Class || 3014 ClassDecl->getTagKind() == TTK_Struct)) { 3015 Sequence.AddZeroInitializationStep(Entity.getType()); 3016 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence); 3017 } 3018 } 3019 } 3020 3021 Sequence.AddZeroInitializationStep(Entity.getType()); 3022} 3023 3024/// \brief Attempt default initialization (C++ [dcl.init]p6). 3025static void TryDefaultInitialization(Sema &S, 3026 const InitializedEntity &Entity, 3027 const InitializationKind &Kind, 3028 InitializationSequence &Sequence) { 3029 assert(Kind.getKind() == InitializationKind::IK_Default); 3030 3031 // C++ [dcl.init]p6: 3032 // To default-initialize an object of type T means: 3033 // - if T is an array type, each element is default-initialized; 3034 QualType DestType = S.Context.getBaseElementType(Entity.getType()); 3035 3036 // - if T is a (possibly cv-qualified) class type (Clause 9), the default 3037 // constructor for T is called (and the initialization is ill-formed if 3038 // T has no accessible default constructor); 3039 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) { 3040 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence); 3041 return; 3042 } 3043 3044 // - otherwise, no initialization is performed. 3045 3046 // If a program calls for the default initialization of an object of 3047 // a const-qualified type T, T shall be a class type with a user-provided 3048 // default constructor. 3049 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) { 3050 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); 3051 return; 3052 } 3053 3054 // If the destination type has a lifetime property, zero-initialize it. 3055 if (DestType.getQualifiers().hasObjCLifetime()) { 3056 Sequence.AddZeroInitializationStep(Entity.getType()); 3057 return; 3058 } 3059} 3060 3061/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]), 3062/// which enumerates all conversion functions and performs overload resolution 3063/// to select the best. 3064static void TryUserDefinedConversion(Sema &S, 3065 const InitializedEntity &Entity, 3066 const InitializationKind &Kind, 3067 Expr *Initializer, 3068 InitializationSequence &Sequence) { 3069 QualType DestType = Entity.getType(); 3070 assert(!DestType->isReferenceType() && "References are handled elsewhere"); 3071 QualType SourceType = Initializer->getType(); 3072 assert((DestType->isRecordType() || SourceType->isRecordType()) && 3073 "Must have a class type to perform a user-defined conversion"); 3074 3075 // Build the candidate set directly in the initialization sequence 3076 // structure, so that it will persist if we fail. 3077 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); 3078 CandidateSet.clear(); 3079 3080 // Determine whether we are allowed to call explicit constructors or 3081 // explicit conversion operators. 3082 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct; 3083 3084 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) { 3085 // The type we're converting to is a class type. Enumerate its constructors 3086 // to see if there is a suitable conversion. 3087 CXXRecordDecl *DestRecordDecl 3088 = cast<CXXRecordDecl>(DestRecordType->getDecl()); 3089 3090 // Try to complete the type we're converting to. 3091 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) { 3092 DeclContext::lookup_iterator Con, ConEnd; 3093 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl); 3094 Con != ConEnd; ++Con) { 3095 NamedDecl *D = *Con; 3096 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3097 3098 // Find the constructor (which may be a template). 3099 CXXConstructorDecl *Constructor = 0; 3100 FunctionTemplateDecl *ConstructorTmpl 3101 = dyn_cast<FunctionTemplateDecl>(D); 3102 if (ConstructorTmpl) 3103 Constructor = cast<CXXConstructorDecl>( 3104 ConstructorTmpl->getTemplatedDecl()); 3105 else 3106 Constructor = cast<CXXConstructorDecl>(D); 3107 3108 if (!Constructor->isInvalidDecl() && 3109 Constructor->isConvertingConstructor(AllowExplicit)) { 3110 if (ConstructorTmpl) 3111 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3112 /*ExplicitArgs*/ 0, 3113 &Initializer, 1, CandidateSet, 3114 /*SuppressUserConversions=*/true); 3115 else 3116 S.AddOverloadCandidate(Constructor, FoundDecl, 3117 &Initializer, 1, CandidateSet, 3118 /*SuppressUserConversions=*/true); 3119 } 3120 } 3121 } 3122 } 3123 3124 SourceLocation DeclLoc = Initializer->getLocStart(); 3125 3126 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) { 3127 // The type we're converting from is a class type, enumerate its conversion 3128 // functions. 3129 3130 // We can only enumerate the conversion functions for a complete type; if 3131 // the type isn't complete, simply skip this step. 3132 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) { 3133 CXXRecordDecl *SourceRecordDecl 3134 = cast<CXXRecordDecl>(SourceRecordType->getDecl()); 3135 3136 const UnresolvedSetImpl *Conversions 3137 = SourceRecordDecl->getVisibleConversionFunctions(); 3138 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(), 3139 E = Conversions->end(); 3140 I != E; ++I) { 3141 NamedDecl *D = *I; 3142 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 3143 if (isa<UsingShadowDecl>(D)) 3144 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3145 3146 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 3147 CXXConversionDecl *Conv; 3148 if (ConvTemplate) 3149 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3150 else 3151 Conv = cast<CXXConversionDecl>(D); 3152 3153 if (AllowExplicit || !Conv->isExplicit()) { 3154 if (ConvTemplate) 3155 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), 3156 ActingDC, Initializer, DestType, 3157 CandidateSet); 3158 else 3159 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, 3160 Initializer, DestType, CandidateSet); 3161 } 3162 } 3163 } 3164 } 3165 3166 // Perform overload resolution. If it fails, return the failed result. 3167 OverloadCandidateSet::iterator Best; 3168 if (OverloadingResult Result 3169 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 3170 Sequence.SetOverloadFailure( 3171 InitializationSequence::FK_UserConversionOverloadFailed, 3172 Result); 3173 return; 3174 } 3175 3176 FunctionDecl *Function = Best->Function; 3177 S.MarkDeclarationReferenced(DeclLoc, Function); 3178 3179 if (isa<CXXConstructorDecl>(Function)) { 3180 // Add the user-defined conversion step. Any cv-qualification conversion is 3181 // subsumed by the initialization. 3182 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType); 3183 return; 3184 } 3185 3186 // Add the user-defined conversion step that calls the conversion function. 3187 QualType ConvType = Function->getCallResultType(); 3188 if (ConvType->getAs<RecordType>()) { 3189 // If we're converting to a class type, there may be an copy if 3190 // the resulting temporary object (possible to create an object of 3191 // a base class type). That copy is not a separate conversion, so 3192 // we just make a note of the actual destination type (possibly a 3193 // base class of the type returned by the conversion function) and 3194 // let the user-defined conversion step handle the conversion. 3195 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType); 3196 return; 3197 } 3198 3199 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType); 3200 3201 // If the conversion following the call to the conversion function 3202 // is interesting, add it as a separate step. 3203 if (Best->FinalConversion.First || Best->FinalConversion.Second || 3204 Best->FinalConversion.Third) { 3205 ImplicitConversionSequence ICS; 3206 ICS.setStandard(); 3207 ICS.Standard = Best->FinalConversion; 3208 Sequence.AddConversionSequenceStep(ICS, DestType); 3209 } 3210} 3211 3212/// The non-zero enum values here are indexes into diagnostic alternatives. 3213enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar }; 3214 3215/// Determines whether this expression is an acceptable ICR source. 3216static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e, 3217 bool isAddressOf) { 3218 // Skip parens. 3219 e = e->IgnoreParens(); 3220 3221 // Skip address-of nodes. 3222 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) { 3223 if (op->getOpcode() == UO_AddrOf) 3224 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true); 3225 3226 // Skip certain casts. 3227 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) { 3228 switch (ce->getCastKind()) { 3229 case CK_Dependent: 3230 case CK_BitCast: 3231 case CK_LValueBitCast: 3232 case CK_NoOp: 3233 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf); 3234 3235 case CK_ArrayToPointerDecay: 3236 return IIK_nonscalar; 3237 3238 case CK_NullToPointer: 3239 return IIK_okay; 3240 3241 default: 3242 break; 3243 } 3244 3245 // If we have a declaration reference, it had better be a local variable. 3246 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) { 3247 if (!isAddressOf) return IIK_nonlocal; 3248 3249 VarDecl *var; 3250 if (isa<DeclRefExpr>(e)) { 3251 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl()); 3252 if (!var) return IIK_nonlocal; 3253 } else { 3254 var = cast<BlockDeclRefExpr>(e)->getDecl(); 3255 } 3256 3257 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal); 3258 3259 // If we have a conditional operator, check both sides. 3260 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) { 3261 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf)) 3262 return iik; 3263 3264 return isInvalidICRSource(C, cond->getRHS(), isAddressOf); 3265 3266 // These are never scalar. 3267 } else if (isa<ArraySubscriptExpr>(e)) { 3268 return IIK_nonscalar; 3269 3270 // Otherwise, it needs to be a null pointer constant. 3271 } else { 3272 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull) 3273 ? IIK_okay : IIK_nonlocal); 3274 } 3275 3276 return IIK_nonlocal; 3277} 3278 3279/// Check whether the given expression is a valid operand for an 3280/// indirect copy/restore. 3281static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) { 3282 assert(src->isRValue()); 3283 3284 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false); 3285 if (iik == IIK_okay) return; 3286 3287 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback) 3288 << ((unsigned) iik - 1) // shift index into diagnostic explanations 3289 << src->getSourceRange(); 3290} 3291 3292/// \brief Determine whether we have compatible array types for the 3293/// purposes of GNU by-copy array initialization. 3294static bool hasCompatibleArrayTypes(ASTContext &Context, 3295 const ArrayType *Dest, 3296 const ArrayType *Source) { 3297 // If the source and destination array types are equivalent, we're 3298 // done. 3299 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0))) 3300 return true; 3301 3302 // Make sure that the element types are the same. 3303 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType())) 3304 return false; 3305 3306 // The only mismatch we allow is when the destination is an 3307 // incomplete array type and the source is a constant array type. 3308 return Source->isConstantArrayType() && Dest->isIncompleteArrayType(); 3309} 3310 3311static bool tryObjCWritebackConversion(Sema &S, 3312 InitializationSequence &Sequence, 3313 const InitializedEntity &Entity, 3314 Expr *Initializer) { 3315 bool ArrayDecay = false; 3316 QualType ArgType = Initializer->getType(); 3317 QualType ArgPointee; 3318 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) { 3319 ArrayDecay = true; 3320 ArgPointee = ArgArrayType->getElementType(); 3321 ArgType = S.Context.getPointerType(ArgPointee); 3322 } 3323 3324 // Handle write-back conversion. 3325 QualType ConvertedArgType; 3326 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(), 3327 ConvertedArgType)) 3328 return false; 3329 3330 // We should copy unless we're passing to an argument explicitly 3331 // marked 'out'. 3332 bool ShouldCopy = true; 3333 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl())) 3334 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); 3335 3336 // Do we need an lvalue conversion? 3337 if (ArrayDecay || Initializer->isGLValue()) { 3338 ImplicitConversionSequence ICS; 3339 ICS.setStandard(); 3340 ICS.Standard.setAsIdentityConversion(); 3341 3342 QualType ResultType; 3343 if (ArrayDecay) { 3344 ICS.Standard.First = ICK_Array_To_Pointer; 3345 ResultType = S.Context.getPointerType(ArgPointee); 3346 } else { 3347 ICS.Standard.First = ICK_Lvalue_To_Rvalue; 3348 ResultType = Initializer->getType().getNonLValueExprType(S.Context); 3349 } 3350 3351 Sequence.AddConversionSequenceStep(ICS, ResultType); 3352 } 3353 3354 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy); 3355 return true; 3356} 3357 3358InitializationSequence::InitializationSequence(Sema &S, 3359 const InitializedEntity &Entity, 3360 const InitializationKind &Kind, 3361 Expr **Args, 3362 unsigned NumArgs) 3363 : FailedCandidateSet(Kind.getLocation()) { 3364 ASTContext &Context = S.Context; 3365 3366 // C++0x [dcl.init]p16: 3367 // The semantics of initializers are as follows. The destination type is 3368 // the type of the object or reference being initialized and the source 3369 // type is the type of the initializer expression. The source type is not 3370 // defined when the initializer is a braced-init-list or when it is a 3371 // parenthesized list of expressions. 3372 QualType DestType = Entity.getType(); 3373 3374 if (DestType->isDependentType() || 3375 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) { 3376 SequenceKind = DependentSequence; 3377 return; 3378 } 3379 3380 // Almost everything is a normal sequence. 3381 setSequenceKind(NormalSequence); 3382 3383 for (unsigned I = 0; I != NumArgs; ++I) 3384 if (Args[I]->getObjectKind() == OK_ObjCProperty) { 3385 ExprResult Result = S.ConvertPropertyForRValue(Args[I]); 3386 if (Result.isInvalid()) { 3387 SetFailed(FK_ConversionFromPropertyFailed); 3388 return; 3389 } 3390 Args[I] = Result.take(); 3391 } 3392 3393 QualType SourceType; 3394 Expr *Initializer = 0; 3395 if (NumArgs == 1) { 3396 Initializer = Args[0]; 3397 if (!isa<InitListExpr>(Initializer)) 3398 SourceType = Initializer->getType(); 3399 } 3400 3401 // - If the initializer is a braced-init-list, the object is 3402 // list-initialized (8.5.4). 3403 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) { 3404 TryListInitialization(S, Entity, Kind, InitList, *this); 3405 return; 3406 } 3407 3408 // - If the destination type is a reference type, see 8.5.3. 3409 if (DestType->isReferenceType()) { 3410 // C++0x [dcl.init.ref]p1: 3411 // A variable declared to be a T& or T&&, that is, "reference to type T" 3412 // (8.3.2), shall be initialized by an object, or function, of type T or 3413 // by an object that can be converted into a T. 3414 // (Therefore, multiple arguments are not permitted.) 3415 if (NumArgs != 1) 3416 SetFailed(FK_TooManyInitsForReference); 3417 else 3418 TryReferenceInitialization(S, Entity, Kind, Args[0], *this); 3419 return; 3420 } 3421 3422 // - If the initializer is (), the object is value-initialized. 3423 if (Kind.getKind() == InitializationKind::IK_Value || 3424 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) { 3425 TryValueInitialization(S, Entity, Kind, *this); 3426 return; 3427 } 3428 3429 // Handle default initialization. 3430 if (Kind.getKind() == InitializationKind::IK_Default) { 3431 TryDefaultInitialization(S, Entity, Kind, *this); 3432 return; 3433 } 3434 3435 // - If the destination type is an array of characters, an array of 3436 // char16_t, an array of char32_t, or an array of wchar_t, and the 3437 // initializer is a string literal, see 8.5.2. 3438 // - Otherwise, if the destination type is an array, the program is 3439 // ill-formed. 3440 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) { 3441 if (Initializer && IsStringInit(Initializer, DestAT, Context)) { 3442 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this); 3443 return; 3444 } 3445 3446 // Note: as an GNU C extension, we allow initialization of an 3447 // array from a compound literal that creates an array of the same 3448 // type, so long as the initializer has no side effects. 3449 if (!S.getLangOptions().CPlusPlus && Initializer && 3450 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) && 3451 Initializer->getType()->isArrayType()) { 3452 const ArrayType *SourceAT 3453 = Context.getAsArrayType(Initializer->getType()); 3454 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT)) 3455 SetFailed(FK_ArrayTypeMismatch); 3456 else if (Initializer->HasSideEffects(S.Context)) 3457 SetFailed(FK_NonConstantArrayInit); 3458 else { 3459 AddArrayInitStep(DestType); 3460 } 3461 } else if (DestAT->getElementType()->isAnyCharacterType()) 3462 SetFailed(FK_ArrayNeedsInitListOrStringLiteral); 3463 else 3464 SetFailed(FK_ArrayNeedsInitList); 3465 3466 return; 3467 } 3468 3469 // Determine whether we should consider writeback conversions for 3470 // Objective-C ARC. 3471 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount && 3472 Entity.getKind() == InitializedEntity::EK_Parameter; 3473 3474 // We're at the end of the line for C: it's either a write-back conversion 3475 // or it's a C assignment. There's no need to check anything else. 3476 if (!S.getLangOptions().CPlusPlus) { 3477 // If allowed, check whether this is an Objective-C writeback conversion. 3478 if (allowObjCWritebackConversion && 3479 tryObjCWritebackConversion(S, *this, Entity, Initializer)) { 3480 return; 3481 } 3482 3483 // Handle initialization in C 3484 AddCAssignmentStep(DestType); 3485 MaybeProduceObjCObject(S, *this, Entity); 3486 return; 3487 } 3488 3489 assert(S.getLangOptions().CPlusPlus); 3490 3491 // - If the destination type is a (possibly cv-qualified) class type: 3492 if (DestType->isRecordType()) { 3493 // - If the initialization is direct-initialization, or if it is 3494 // copy-initialization where the cv-unqualified version of the 3495 // source type is the same class as, or a derived class of, the 3496 // class of the destination, constructors are considered. [...] 3497 if (Kind.getKind() == InitializationKind::IK_Direct || 3498 (Kind.getKind() == InitializationKind::IK_Copy && 3499 (Context.hasSameUnqualifiedType(SourceType, DestType) || 3500 S.IsDerivedFrom(SourceType, DestType)))) 3501 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs, 3502 Entity.getType(), *this); 3503 // - Otherwise (i.e., for the remaining copy-initialization cases), 3504 // user-defined conversion sequences that can convert from the source 3505 // type to the destination type or (when a conversion function is 3506 // used) to a derived class thereof are enumerated as described in 3507 // 13.3.1.4, and the best one is chosen through overload resolution 3508 // (13.3). 3509 else 3510 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this); 3511 return; 3512 } 3513 3514 if (NumArgs > 1) { 3515 SetFailed(FK_TooManyInitsForScalar); 3516 return; 3517 } 3518 assert(NumArgs == 1 && "Zero-argument case handled above"); 3519 3520 // - Otherwise, if the source type is a (possibly cv-qualified) class 3521 // type, conversion functions are considered. 3522 if (!SourceType.isNull() && SourceType->isRecordType()) { 3523 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this); 3524 MaybeProduceObjCObject(S, *this, Entity); 3525 return; 3526 } 3527 3528 // - Otherwise, the initial value of the object being initialized is the 3529 // (possibly converted) value of the initializer expression. Standard 3530 // conversions (Clause 4) will be used, if necessary, to convert the 3531 // initializer expression to the cv-unqualified version of the 3532 // destination type; no user-defined conversions are considered. 3533 3534 ImplicitConversionSequence ICS 3535 = S.TryImplicitConversion(Initializer, Entity.getType(), 3536 /*SuppressUserConversions*/true, 3537 /*AllowExplicitConversions*/ false, 3538 /*InOverloadResolution*/ false, 3539 /*CStyle=*/Kind.isCStyleOrFunctionalCast(), 3540 allowObjCWritebackConversion); 3541 3542 if (ICS.isStandard() && 3543 ICS.Standard.Second == ICK_Writeback_Conversion) { 3544 // Objective-C ARC writeback conversion. 3545 3546 // We should copy unless we're passing to an argument explicitly 3547 // marked 'out'. 3548 bool ShouldCopy = true; 3549 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl())) 3550 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); 3551 3552 // If there was an lvalue adjustment, add it as a separate conversion. 3553 if (ICS.Standard.First == ICK_Array_To_Pointer || 3554 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 3555 ImplicitConversionSequence LvalueICS; 3556 LvalueICS.setStandard(); 3557 LvalueICS.Standard.setAsIdentityConversion(); 3558 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0)); 3559 LvalueICS.Standard.First = ICS.Standard.First; 3560 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0)); 3561 } 3562 3563 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy); 3564 } else if (ICS.isBad()) { 3565 DeclAccessPair dap; 3566 if (Initializer->getType() == Context.OverloadTy && 3567 !S.ResolveAddressOfOverloadedFunction(Initializer 3568 , DestType, false, dap)) 3569 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); 3570 else 3571 SetFailed(InitializationSequence::FK_ConversionFailed); 3572 } else { 3573 AddConversionSequenceStep(ICS, Entity.getType()); 3574 3575 MaybeProduceObjCObject(S, *this, Entity); 3576 } 3577} 3578 3579InitializationSequence::~InitializationSequence() { 3580 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(), 3581 StepEnd = Steps.end(); 3582 Step != StepEnd; ++Step) 3583 Step->Destroy(); 3584} 3585 3586//===----------------------------------------------------------------------===// 3587// Perform initialization 3588//===----------------------------------------------------------------------===// 3589static Sema::AssignmentAction 3590getAssignmentAction(const InitializedEntity &Entity) { 3591 switch(Entity.getKind()) { 3592 case InitializedEntity::EK_Variable: 3593 case InitializedEntity::EK_New: 3594 case InitializedEntity::EK_Exception: 3595 case InitializedEntity::EK_Base: 3596 case InitializedEntity::EK_Delegating: 3597 return Sema::AA_Initializing; 3598 3599 case InitializedEntity::EK_Parameter: 3600 if (Entity.getDecl() && 3601 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext())) 3602 return Sema::AA_Sending; 3603 3604 return Sema::AA_Passing; 3605 3606 case InitializedEntity::EK_Result: 3607 return Sema::AA_Returning; 3608 3609 case InitializedEntity::EK_Temporary: 3610 // FIXME: Can we tell apart casting vs. converting? 3611 return Sema::AA_Casting; 3612 3613 case InitializedEntity::EK_Member: 3614 case InitializedEntity::EK_ArrayElement: 3615 case InitializedEntity::EK_VectorElement: 3616 case InitializedEntity::EK_BlockElement: 3617 return Sema::AA_Initializing; 3618 } 3619 3620 return Sema::AA_Converting; 3621} 3622 3623/// \brief Whether we should binding a created object as a temporary when 3624/// initializing the given entity. 3625static bool shouldBindAsTemporary(const InitializedEntity &Entity) { 3626 switch (Entity.getKind()) { 3627 case InitializedEntity::EK_ArrayElement: 3628 case InitializedEntity::EK_Member: 3629 case InitializedEntity::EK_Result: 3630 case InitializedEntity::EK_New: 3631 case InitializedEntity::EK_Variable: 3632 case InitializedEntity::EK_Base: 3633 case InitializedEntity::EK_Delegating: 3634 case InitializedEntity::EK_VectorElement: 3635 case InitializedEntity::EK_Exception: 3636 case InitializedEntity::EK_BlockElement: 3637 return false; 3638 3639 case InitializedEntity::EK_Parameter: 3640 case InitializedEntity::EK_Temporary: 3641 return true; 3642 } 3643 3644 llvm_unreachable("missed an InitializedEntity kind?"); 3645} 3646 3647/// \brief Whether the given entity, when initialized with an object 3648/// created for that initialization, requires destruction. 3649static bool shouldDestroyTemporary(const InitializedEntity &Entity) { 3650 switch (Entity.getKind()) { 3651 case InitializedEntity::EK_Member: 3652 case InitializedEntity::EK_Result: 3653 case InitializedEntity::EK_New: 3654 case InitializedEntity::EK_Base: 3655 case InitializedEntity::EK_Delegating: 3656 case InitializedEntity::EK_VectorElement: 3657 case InitializedEntity::EK_BlockElement: 3658 return false; 3659 3660 case InitializedEntity::EK_Variable: 3661 case InitializedEntity::EK_Parameter: 3662 case InitializedEntity::EK_Temporary: 3663 case InitializedEntity::EK_ArrayElement: 3664 case InitializedEntity::EK_Exception: 3665 return true; 3666 } 3667 3668 llvm_unreachable("missed an InitializedEntity kind?"); 3669} 3670 3671/// \brief Make a (potentially elidable) temporary copy of the object 3672/// provided by the given initializer by calling the appropriate copy 3673/// constructor. 3674/// 3675/// \param S The Sema object used for type-checking. 3676/// 3677/// \param T The type of the temporary object, which must either be 3678/// the type of the initializer expression or a superclass thereof. 3679/// 3680/// \param Enter The entity being initialized. 3681/// 3682/// \param CurInit The initializer expression. 3683/// 3684/// \param IsExtraneousCopy Whether this is an "extraneous" copy that 3685/// is permitted in C++03 (but not C++0x) when binding a reference to 3686/// an rvalue. 3687/// 3688/// \returns An expression that copies the initializer expression into 3689/// a temporary object, or an error expression if a copy could not be 3690/// created. 3691static ExprResult CopyObject(Sema &S, 3692 QualType T, 3693 const InitializedEntity &Entity, 3694 ExprResult CurInit, 3695 bool IsExtraneousCopy) { 3696 // Determine which class type we're copying to. 3697 Expr *CurInitExpr = (Expr *)CurInit.get(); 3698 CXXRecordDecl *Class = 0; 3699 if (const RecordType *Record = T->getAs<RecordType>()) 3700 Class = cast<CXXRecordDecl>(Record->getDecl()); 3701 if (!Class) 3702 return move(CurInit); 3703 3704 // C++0x [class.copy]p32: 3705 // When certain criteria are met, an implementation is allowed to 3706 // omit the copy/move construction of a class object, even if the 3707 // copy/move constructor and/or destructor for the object have 3708 // side effects. [...] 3709 // - when a temporary class object that has not been bound to a 3710 // reference (12.2) would be copied/moved to a class object 3711 // with the same cv-unqualified type, the copy/move operation 3712 // can be omitted by constructing the temporary object 3713 // directly into the target of the omitted copy/move 3714 // 3715 // Note that the other three bullets are handled elsewhere. Copy 3716 // elision for return statements and throw expressions are handled as part 3717 // of constructor initialization, while copy elision for exception handlers 3718 // is handled by the run-time. 3719 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class); 3720 SourceLocation Loc; 3721 switch (Entity.getKind()) { 3722 case InitializedEntity::EK_Result: 3723 Loc = Entity.getReturnLoc(); 3724 break; 3725 3726 case InitializedEntity::EK_Exception: 3727 Loc = Entity.getThrowLoc(); 3728 break; 3729 3730 case InitializedEntity::EK_Variable: 3731 Loc = Entity.getDecl()->getLocation(); 3732 break; 3733 3734 case InitializedEntity::EK_ArrayElement: 3735 case InitializedEntity::EK_Member: 3736 case InitializedEntity::EK_Parameter: 3737 case InitializedEntity::EK_Temporary: 3738 case InitializedEntity::EK_New: 3739 case InitializedEntity::EK_Base: 3740 case InitializedEntity::EK_Delegating: 3741 case InitializedEntity::EK_VectorElement: 3742 case InitializedEntity::EK_BlockElement: 3743 Loc = CurInitExpr->getLocStart(); 3744 break; 3745 } 3746 3747 // Make sure that the type we are copying is complete. 3748 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete))) 3749 return move(CurInit); 3750 3751 // Perform overload resolution using the class's copy/move constructors. 3752 DeclContext::lookup_iterator Con, ConEnd; 3753 OverloadCandidateSet CandidateSet(Loc); 3754 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class); 3755 Con != ConEnd; ++Con) { 3756 // Only consider copy/move constructors and constructor templates. Per 3757 // C++0x [dcl.init]p16, second bullet to class types, this 3758 // initialization is direct-initialization. 3759 CXXConstructorDecl *Constructor = 0; 3760 3761 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) { 3762 // Handle copy/moveconstructors, only. 3763 if (!Constructor || Constructor->isInvalidDecl() || 3764 !Constructor->isCopyOrMoveConstructor() || 3765 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true)) 3766 continue; 3767 3768 DeclAccessPair FoundDecl 3769 = DeclAccessPair::make(Constructor, Constructor->getAccess()); 3770 S.AddOverloadCandidate(Constructor, FoundDecl, 3771 &CurInitExpr, 1, CandidateSet); 3772 continue; 3773 } 3774 3775 // Handle constructor templates. 3776 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con); 3777 if (ConstructorTmpl->isInvalidDecl()) 3778 continue; 3779 3780 Constructor = cast<CXXConstructorDecl>( 3781 ConstructorTmpl->getTemplatedDecl()); 3782 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true)) 3783 continue; 3784 3785 // FIXME: Do we need to limit this to copy-constructor-like 3786 // candidates? 3787 DeclAccessPair FoundDecl 3788 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess()); 3789 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0, 3790 &CurInitExpr, 1, CandidateSet, true); 3791 } 3792 3793 OverloadCandidateSet::iterator Best; 3794 switch (CandidateSet.BestViableFunction(S, Loc, Best)) { 3795 case OR_Success: 3796 break; 3797 3798 case OR_No_Viable_Function: 3799 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext() 3800 ? diag::ext_rvalue_to_reference_temp_copy_no_viable 3801 : diag::err_temp_copy_no_viable) 3802 << (int)Entity.getKind() << CurInitExpr->getType() 3803 << CurInitExpr->getSourceRange(); 3804 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1); 3805 if (!IsExtraneousCopy || S.isSFINAEContext()) 3806 return ExprError(); 3807 return move(CurInit); 3808 3809 case OR_Ambiguous: 3810 S.Diag(Loc, diag::err_temp_copy_ambiguous) 3811 << (int)Entity.getKind() << CurInitExpr->getType() 3812 << CurInitExpr->getSourceRange(); 3813 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1); 3814 return ExprError(); 3815 3816 case OR_Deleted: 3817 S.Diag(Loc, diag::err_temp_copy_deleted) 3818 << (int)Entity.getKind() << CurInitExpr->getType() 3819 << CurInitExpr->getSourceRange(); 3820 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here) 3821 << 1 << Best->Function->isDeleted(); 3822 return ExprError(); 3823 } 3824 3825 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3826 ASTOwningVector<Expr*> ConstructorArgs(S); 3827 CurInit.release(); // Ownership transferred into MultiExprArg, below. 3828 3829 S.CheckConstructorAccess(Loc, Constructor, Entity, 3830 Best->FoundDecl.getAccess(), IsExtraneousCopy); 3831 3832 if (IsExtraneousCopy) { 3833 // If this is a totally extraneous copy for C++03 reference 3834 // binding purposes, just return the original initialization 3835 // expression. We don't generate an (elided) copy operation here 3836 // because doing so would require us to pass down a flag to avoid 3837 // infinite recursion, where each step adds another extraneous, 3838 // elidable copy. 3839 3840 // Instantiate the default arguments of any extra parameters in 3841 // the selected copy constructor, as if we were going to create a 3842 // proper call to the copy constructor. 3843 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) { 3844 ParmVarDecl *Parm = Constructor->getParamDecl(I); 3845 if (S.RequireCompleteType(Loc, Parm->getType(), 3846 S.PDiag(diag::err_call_incomplete_argument))) 3847 break; 3848 3849 // Build the default argument expression; we don't actually care 3850 // if this succeeds or not, because this routine will complain 3851 // if there was a problem. 3852 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm); 3853 } 3854 3855 return S.Owned(CurInitExpr); 3856 } 3857 3858 S.MarkDeclarationReferenced(Loc, Constructor); 3859 3860 // Determine the arguments required to actually perform the 3861 // constructor call (we might have derived-to-base conversions, or 3862 // the copy constructor may have default arguments). 3863 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1), 3864 Loc, ConstructorArgs)) 3865 return ExprError(); 3866 3867 // Actually perform the constructor call. 3868 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable, 3869 move_arg(ConstructorArgs), 3870 /*ZeroInit*/ false, 3871 CXXConstructExpr::CK_Complete, 3872 SourceRange()); 3873 3874 // If we're supposed to bind temporaries, do so. 3875 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity)) 3876 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>()); 3877 return move(CurInit); 3878} 3879 3880void InitializationSequence::PrintInitLocationNote(Sema &S, 3881 const InitializedEntity &Entity) { 3882 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) { 3883 if (Entity.getDecl()->getLocation().isInvalid()) 3884 return; 3885 3886 if (Entity.getDecl()->getDeclName()) 3887 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here) 3888 << Entity.getDecl()->getDeclName(); 3889 else 3890 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here); 3891 } 3892} 3893 3894static bool isReferenceBinding(const InitializationSequence::Step &s) { 3895 return s.Kind == InitializationSequence::SK_BindReference || 3896 s.Kind == InitializationSequence::SK_BindReferenceToTemporary; 3897} 3898 3899ExprResult 3900InitializationSequence::Perform(Sema &S, 3901 const InitializedEntity &Entity, 3902 const InitializationKind &Kind, 3903 MultiExprArg Args, 3904 QualType *ResultType) { 3905 if (Failed()) { 3906 unsigned NumArgs = Args.size(); 3907 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs); 3908 return ExprError(); 3909 } 3910 3911 if (getKind() == DependentSequence) { 3912 // If the declaration is a non-dependent, incomplete array type 3913 // that has an initializer, then its type will be completed once 3914 // the initializer is instantiated. 3915 if (ResultType && !Entity.getType()->isDependentType() && 3916 Args.size() == 1) { 3917 QualType DeclType = Entity.getType(); 3918 if (const IncompleteArrayType *ArrayT 3919 = S.Context.getAsIncompleteArrayType(DeclType)) { 3920 // FIXME: We don't currently have the ability to accurately 3921 // compute the length of an initializer list without 3922 // performing full type-checking of the initializer list 3923 // (since we have to determine where braces are implicitly 3924 // introduced and such). So, we fall back to making the array 3925 // type a dependently-sized array type with no specified 3926 // bound. 3927 if (isa<InitListExpr>((Expr *)Args.get()[0])) { 3928 SourceRange Brackets; 3929 3930 // Scavange the location of the brackets from the entity, if we can. 3931 if (DeclaratorDecl *DD = Entity.getDecl()) { 3932 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) { 3933 TypeLoc TL = TInfo->getTypeLoc(); 3934 if (IncompleteArrayTypeLoc *ArrayLoc 3935 = dyn_cast<IncompleteArrayTypeLoc>(&TL)) 3936 Brackets = ArrayLoc->getBracketsRange(); 3937 } 3938 } 3939 3940 *ResultType 3941 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(), 3942 /*NumElts=*/0, 3943 ArrayT->getSizeModifier(), 3944 ArrayT->getIndexTypeCVRQualifiers(), 3945 Brackets); 3946 } 3947 3948 } 3949 } 3950 assert(Kind.getKind() == InitializationKind::IK_Copy || 3951 Kind.isExplicitCast()); 3952 return ExprResult(Args.release()[0]); 3953 } 3954 3955 // No steps means no initialization. 3956 if (Steps.empty()) 3957 return S.Owned((Expr *)0); 3958 3959 QualType DestType = Entity.getType().getNonReferenceType(); 3960 // FIXME: Ugly hack around the fact that Entity.getType() is not 3961 // the same as Entity.getDecl()->getType() in cases involving type merging, 3962 // and we want latter when it makes sense. 3963 if (ResultType) 3964 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() : 3965 Entity.getType(); 3966 3967 ExprResult CurInit = S.Owned((Expr *)0); 3968 3969 // For initialization steps that start with a single initializer, 3970 // grab the only argument out the Args and place it into the "current" 3971 // initializer. 3972 switch (Steps.front().Kind) { 3973 case SK_ResolveAddressOfOverloadedFunction: 3974 case SK_CastDerivedToBaseRValue: 3975 case SK_CastDerivedToBaseXValue: 3976 case SK_CastDerivedToBaseLValue: 3977 case SK_BindReference: 3978 case SK_BindReferenceToTemporary: 3979 case SK_ExtraneousCopyToTemporary: 3980 case SK_UserConversion: 3981 case SK_QualificationConversionLValue: 3982 case SK_QualificationConversionXValue: 3983 case SK_QualificationConversionRValue: 3984 case SK_ConversionSequence: 3985 case SK_ListInitialization: 3986 case SK_CAssignment: 3987 case SK_StringInit: 3988 case SK_ObjCObjectConversion: 3989 case SK_ArrayInit: 3990 case SK_PassByIndirectCopyRestore: 3991 case SK_PassByIndirectRestore: 3992 case SK_ProduceObjCObject: { 3993 assert(Args.size() == 1); 3994 CurInit = Args.get()[0]; 3995 if (!CurInit.get()) return ExprError(); 3996 3997 // Read from a property when initializing something with it. 3998 if (CurInit.get()->getObjectKind() == OK_ObjCProperty) { 3999 CurInit = S.ConvertPropertyForRValue(CurInit.take()); 4000 if (CurInit.isInvalid()) 4001 return ExprError(); 4002 } 4003 break; 4004 } 4005 4006 case SK_ConstructorInitialization: 4007 case SK_ZeroInitialization: 4008 break; 4009 } 4010 4011 // Walk through the computed steps for the initialization sequence, 4012 // performing the specified conversions along the way. 4013 bool ConstructorInitRequiresZeroInit = false; 4014 for (step_iterator Step = step_begin(), StepEnd = step_end(); 4015 Step != StepEnd; ++Step) { 4016 if (CurInit.isInvalid()) 4017 return ExprError(); 4018 4019 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType(); 4020 4021 switch (Step->Kind) { 4022 case SK_ResolveAddressOfOverloadedFunction: 4023 // Overload resolution determined which function invoke; update the 4024 // initializer to reflect that choice. 4025 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl); 4026 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()); 4027 CurInit = S.FixOverloadedFunctionReference(move(CurInit), 4028 Step->Function.FoundDecl, 4029 Step->Function.Function); 4030 break; 4031 4032 case SK_CastDerivedToBaseRValue: 4033 case SK_CastDerivedToBaseXValue: 4034 case SK_CastDerivedToBaseLValue: { 4035 // We have a derived-to-base cast that produces either an rvalue or an 4036 // lvalue. Perform that cast. 4037 4038 CXXCastPath BasePath; 4039 4040 // Casts to inaccessible base classes are allowed with C-style casts. 4041 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast(); 4042 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type, 4043 CurInit.get()->getLocStart(), 4044 CurInit.get()->getSourceRange(), 4045 &BasePath, IgnoreBaseAccess)) 4046 return ExprError(); 4047 4048 if (S.BasePathInvolvesVirtualBase(BasePath)) { 4049 QualType T = SourceType; 4050 if (const PointerType *Pointer = T->getAs<PointerType>()) 4051 T = Pointer->getPointeeType(); 4052 if (const RecordType *RecordTy = T->getAs<RecordType>()) 4053 S.MarkVTableUsed(CurInit.get()->getLocStart(), 4054 cast<CXXRecordDecl>(RecordTy->getDecl())); 4055 } 4056 4057 ExprValueKind VK = 4058 Step->Kind == SK_CastDerivedToBaseLValue ? 4059 VK_LValue : 4060 (Step->Kind == SK_CastDerivedToBaseXValue ? 4061 VK_XValue : 4062 VK_RValue); 4063 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, 4064 Step->Type, 4065 CK_DerivedToBase, 4066 CurInit.get(), 4067 &BasePath, VK)); 4068 break; 4069 } 4070 4071 case SK_BindReference: 4072 if (FieldDecl *BitField = CurInit.get()->getBitField()) { 4073 // References cannot bind to bit fields (C++ [dcl.init.ref]p5). 4074 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield) 4075 << Entity.getType().isVolatileQualified() 4076 << BitField->getDeclName() 4077 << CurInit.get()->getSourceRange(); 4078 S.Diag(BitField->getLocation(), diag::note_bitfield_decl); 4079 return ExprError(); 4080 } 4081 4082 if (CurInit.get()->refersToVectorElement()) { 4083 // References cannot bind to vector elements. 4084 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element) 4085 << Entity.getType().isVolatileQualified() 4086 << CurInit.get()->getSourceRange(); 4087 PrintInitLocationNote(S, Entity); 4088 return ExprError(); 4089 } 4090 4091 // Reference binding does not have any corresponding ASTs. 4092 4093 // Check exception specifications 4094 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType)) 4095 return ExprError(); 4096 4097 break; 4098 4099 case SK_BindReferenceToTemporary: 4100 // Check exception specifications 4101 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType)) 4102 return ExprError(); 4103 4104 // Materialize the temporary into memory. 4105 CurInit = new (S.Context) MaterializeTemporaryExpr( 4106 Entity.getType().getNonReferenceType(), 4107 CurInit.get(), 4108 Entity.getType()->isLValueReferenceType()); 4109 4110 // If we're binding to an Objective-C object that has lifetime, we 4111 // need cleanups. 4112 if (S.getLangOptions().ObjCAutoRefCount && 4113 CurInit.get()->getType()->isObjCLifetimeType()) 4114 S.ExprNeedsCleanups = true; 4115 4116 break; 4117 4118 case SK_ExtraneousCopyToTemporary: 4119 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit), 4120 /*IsExtraneousCopy=*/true); 4121 break; 4122 4123 case SK_UserConversion: { 4124 // We have a user-defined conversion that invokes either a constructor 4125 // or a conversion function. 4126 CastKind CastKind; 4127 bool IsCopy = false; 4128 FunctionDecl *Fn = Step->Function.Function; 4129 DeclAccessPair FoundFn = Step->Function.FoundDecl; 4130 bool CreatedObject = false; 4131 bool IsLvalue = false; 4132 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) { 4133 // Build a call to the selected constructor. 4134 ASTOwningVector<Expr*> ConstructorArgs(S); 4135 SourceLocation Loc = CurInit.get()->getLocStart(); 4136 CurInit.release(); // Ownership transferred into MultiExprArg, below. 4137 4138 // Determine the arguments required to actually perform the constructor 4139 // call. 4140 Expr *Arg = CurInit.get(); 4141 if (S.CompleteConstructorCall(Constructor, 4142 MultiExprArg(&Arg, 1), 4143 Loc, ConstructorArgs)) 4144 return ExprError(); 4145 4146 // Build the an expression that constructs a temporary. 4147 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor, 4148 move_arg(ConstructorArgs), 4149 /*ZeroInit*/ false, 4150 CXXConstructExpr::CK_Complete, 4151 SourceRange()); 4152 if (CurInit.isInvalid()) 4153 return ExprError(); 4154 4155 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity, 4156 FoundFn.getAccess()); 4157 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()); 4158 4159 CastKind = CK_ConstructorConversion; 4160 QualType Class = S.Context.getTypeDeclType(Constructor->getParent()); 4161 if (S.Context.hasSameUnqualifiedType(SourceType, Class) || 4162 S.IsDerivedFrom(SourceType, Class)) 4163 IsCopy = true; 4164 4165 CreatedObject = true; 4166 } else { 4167 // Build a call to the conversion function. 4168 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn); 4169 IsLvalue = Conversion->getResultType()->isLValueReferenceType(); 4170 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0, 4171 FoundFn); 4172 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()); 4173 4174 // FIXME: Should we move this initialization into a separate 4175 // derived-to-base conversion? I believe the answer is "no", because 4176 // we don't want to turn off access control here for c-style casts. 4177 ExprResult CurInitExprRes = 4178 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0, 4179 FoundFn, Conversion); 4180 if(CurInitExprRes.isInvalid()) 4181 return ExprError(); 4182 CurInit = move(CurInitExprRes); 4183 4184 // Build the actual call to the conversion function. 4185 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion); 4186 if (CurInit.isInvalid() || !CurInit.get()) 4187 return ExprError(); 4188 4189 CastKind = CK_UserDefinedConversion; 4190 4191 CreatedObject = Conversion->getResultType()->isRecordType(); 4192 } 4193 4194 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back()); 4195 if (RequiresCopy || shouldBindAsTemporary(Entity)) 4196 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>()); 4197 else if (CreatedObject && shouldDestroyTemporary(Entity)) { 4198 QualType T = CurInit.get()->getType(); 4199 if (const RecordType *Record = T->getAs<RecordType>()) { 4200 CXXDestructorDecl *Destructor 4201 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl())); 4202 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor, 4203 S.PDiag(diag::err_access_dtor_temp) << T); 4204 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor); 4205 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()); 4206 } 4207 } 4208 4209 // FIXME: xvalues 4210 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, 4211 CurInit.get()->getType(), 4212 CastKind, CurInit.get(), 0, 4213 IsLvalue ? VK_LValue : VK_RValue)); 4214 4215 if (RequiresCopy) 4216 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity, 4217 move(CurInit), /*IsExtraneousCopy=*/false); 4218 4219 break; 4220 } 4221 4222 case SK_QualificationConversionLValue: 4223 case SK_QualificationConversionXValue: 4224 case SK_QualificationConversionRValue: { 4225 // Perform a qualification conversion; these can never go wrong. 4226 ExprValueKind VK = 4227 Step->Kind == SK_QualificationConversionLValue ? 4228 VK_LValue : 4229 (Step->Kind == SK_QualificationConversionXValue ? 4230 VK_XValue : 4231 VK_RValue); 4232 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK); 4233 break; 4234 } 4235 4236 case SK_ConversionSequence: { 4237 Sema::CheckedConversionKind CCK 4238 = Kind.isCStyleCast()? Sema::CCK_CStyleCast 4239 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast 4240 : Kind.isExplicitCast()? Sema::CCK_OtherCast 4241 : Sema::CCK_ImplicitConversion; 4242 ExprResult CurInitExprRes = 4243 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS, 4244 getAssignmentAction(Entity), CCK); 4245 if (CurInitExprRes.isInvalid()) 4246 return ExprError(); 4247 CurInit = move(CurInitExprRes); 4248 break; 4249 } 4250 4251 case SK_ListInitialization: { 4252 InitListExpr *InitList = cast<InitListExpr>(CurInit.get()); 4253 QualType Ty = Step->Type; 4254 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty)) 4255 return ExprError(); 4256 4257 CurInit.release(); 4258 CurInit = S.Owned(InitList); 4259 break; 4260 } 4261 4262 case SK_ConstructorInitialization: { 4263 unsigned NumArgs = Args.size(); 4264 CXXConstructorDecl *Constructor 4265 = cast<CXXConstructorDecl>(Step->Function.Function); 4266 4267 // Build a call to the selected constructor. 4268 ASTOwningVector<Expr*> ConstructorArgs(S); 4269 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid()) 4270 ? Kind.getEqualLoc() 4271 : Kind.getLocation(); 4272 4273 if (Kind.getKind() == InitializationKind::IK_Default) { 4274 // Force even a trivial, implicit default constructor to be 4275 // semantically checked. We do this explicitly because we don't build 4276 // the definition for completely trivial constructors. 4277 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4278 assert(ClassDecl && "No parent class for constructor."); 4279 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 4280 ClassDecl->hasTrivialDefaultConstructor() && 4281 !Constructor->isUsed(false)) 4282 S.DefineImplicitDefaultConstructor(Loc, Constructor); 4283 } 4284 4285 // Determine the arguments required to actually perform the constructor 4286 // call. 4287 if (S.CompleteConstructorCall(Constructor, move(Args), 4288 Loc, ConstructorArgs)) 4289 return ExprError(); 4290 4291 4292 if (Entity.getKind() == InitializedEntity::EK_Temporary && 4293 NumArgs != 1 && // FIXME: Hack to work around cast weirdness 4294 (Kind.getKind() == InitializationKind::IK_Direct || 4295 Kind.getKind() == InitializationKind::IK_Value)) { 4296 // An explicitly-constructed temporary, e.g., X(1, 2). 4297 unsigned NumExprs = ConstructorArgs.size(); 4298 Expr **Exprs = (Expr **)ConstructorArgs.take(); 4299 S.MarkDeclarationReferenced(Loc, Constructor); 4300 S.DiagnoseUseOfDecl(Constructor, Loc); 4301 4302 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo(); 4303 if (!TSInfo) 4304 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc); 4305 4306 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context, 4307 Constructor, 4308 TSInfo, 4309 Exprs, 4310 NumExprs, 4311 Kind.getParenRange(), 4312 ConstructorInitRequiresZeroInit)); 4313 } else { 4314 CXXConstructExpr::ConstructionKind ConstructKind = 4315 CXXConstructExpr::CK_Complete; 4316 4317 if (Entity.getKind() == InitializedEntity::EK_Base) { 4318 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ? 4319 CXXConstructExpr::CK_VirtualBase : 4320 CXXConstructExpr::CK_NonVirtualBase; 4321 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) { 4322 ConstructKind = CXXConstructExpr::CK_Delegating; 4323 } 4324 4325 // Only get the parenthesis range if it is a direct construction. 4326 SourceRange parenRange = 4327 Kind.getKind() == InitializationKind::IK_Direct ? 4328 Kind.getParenRange() : SourceRange(); 4329 4330 // If the entity allows NRVO, mark the construction as elidable 4331 // unconditionally. 4332 if (Entity.allowsNRVO()) 4333 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(), 4334 Constructor, /*Elidable=*/true, 4335 move_arg(ConstructorArgs), 4336 ConstructorInitRequiresZeroInit, 4337 ConstructKind, 4338 parenRange); 4339 else 4340 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(), 4341 Constructor, 4342 move_arg(ConstructorArgs), 4343 ConstructorInitRequiresZeroInit, 4344 ConstructKind, 4345 parenRange); 4346 } 4347 if (CurInit.isInvalid()) 4348 return ExprError(); 4349 4350 // Only check access if all of that succeeded. 4351 S.CheckConstructorAccess(Loc, Constructor, Entity, 4352 Step->Function.FoundDecl.getAccess()); 4353 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc); 4354 4355 if (shouldBindAsTemporary(Entity)) 4356 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>()); 4357 4358 break; 4359 } 4360 4361 case SK_ZeroInitialization: { 4362 step_iterator NextStep = Step; 4363 ++NextStep; 4364 if (NextStep != StepEnd && 4365 NextStep->Kind == SK_ConstructorInitialization) { 4366 // The need for zero-initialization is recorded directly into 4367 // the call to the object's constructor within the next step. 4368 ConstructorInitRequiresZeroInit = true; 4369 } else if (Kind.getKind() == InitializationKind::IK_Value && 4370 S.getLangOptions().CPlusPlus && 4371 !Kind.isImplicitValueInit()) { 4372 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo(); 4373 if (!TSInfo) 4374 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type, 4375 Kind.getRange().getBegin()); 4376 4377 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr( 4378 TSInfo->getType().getNonLValueExprType(S.Context), 4379 TSInfo, 4380 Kind.getRange().getEnd())); 4381 } else { 4382 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type)); 4383 } 4384 break; 4385 } 4386 4387 case SK_CAssignment: { 4388 QualType SourceType = CurInit.get()->getType(); 4389 ExprResult Result = move(CurInit); 4390 Sema::AssignConvertType ConvTy = 4391 S.CheckSingleAssignmentConstraints(Step->Type, Result); 4392 if (Result.isInvalid()) 4393 return ExprError(); 4394 CurInit = move(Result); 4395 4396 // If this is a call, allow conversion to a transparent union. 4397 ExprResult CurInitExprRes = move(CurInit); 4398 if (ConvTy != Sema::Compatible && 4399 Entity.getKind() == InitializedEntity::EK_Parameter && 4400 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes) 4401 == Sema::Compatible) 4402 ConvTy = Sema::Compatible; 4403 if (CurInitExprRes.isInvalid()) 4404 return ExprError(); 4405 CurInit = move(CurInitExprRes); 4406 4407 bool Complained; 4408 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(), 4409 Step->Type, SourceType, 4410 CurInit.get(), 4411 getAssignmentAction(Entity), 4412 &Complained)) { 4413 PrintInitLocationNote(S, Entity); 4414 return ExprError(); 4415 } else if (Complained) 4416 PrintInitLocationNote(S, Entity); 4417 break; 4418 } 4419 4420 case SK_StringInit: { 4421 QualType Ty = Step->Type; 4422 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty, 4423 S.Context.getAsArrayType(Ty), S); 4424 break; 4425 } 4426 4427 case SK_ObjCObjectConversion: 4428 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, 4429 CK_ObjCObjectLValueCast, 4430 S.CastCategory(CurInit.get())); 4431 break; 4432 4433 case SK_ArrayInit: 4434 // Okay: we checked everything before creating this step. Note that 4435 // this is a GNU extension. 4436 S.Diag(Kind.getLocation(), diag::ext_array_init_copy) 4437 << Step->Type << CurInit.get()->getType() 4438 << CurInit.get()->getSourceRange(); 4439 4440 // If the destination type is an incomplete array type, update the 4441 // type accordingly. 4442 if (ResultType) { 4443 if (const IncompleteArrayType *IncompleteDest 4444 = S.Context.getAsIncompleteArrayType(Step->Type)) { 4445 if (const ConstantArrayType *ConstantSource 4446 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) { 4447 *ResultType = S.Context.getConstantArrayType( 4448 IncompleteDest->getElementType(), 4449 ConstantSource->getSize(), 4450 ArrayType::Normal, 0); 4451 } 4452 } 4453 } 4454 break; 4455 4456 case SK_PassByIndirectCopyRestore: 4457 case SK_PassByIndirectRestore: 4458 checkIndirectCopyRestoreSource(S, CurInit.get()); 4459 CurInit = S.Owned(new (S.Context) 4460 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type, 4461 Step->Kind == SK_PassByIndirectCopyRestore)); 4462 break; 4463 4464 case SK_ProduceObjCObject: 4465 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type, 4466 CK_ObjCProduceObject, 4467 CurInit.take(), 0, VK_RValue)); 4468 break; 4469 } 4470 } 4471 4472 // Diagnose non-fatal problems with the completed initialization. 4473 if (Entity.getKind() == InitializedEntity::EK_Member && 4474 cast<FieldDecl>(Entity.getDecl())->isBitField()) 4475 S.CheckBitFieldInitialization(Kind.getLocation(), 4476 cast<FieldDecl>(Entity.getDecl()), 4477 CurInit.get()); 4478 4479 return move(CurInit); 4480} 4481 4482//===----------------------------------------------------------------------===// 4483// Diagnose initialization failures 4484//===----------------------------------------------------------------------===// 4485bool InitializationSequence::Diagnose(Sema &S, 4486 const InitializedEntity &Entity, 4487 const InitializationKind &Kind, 4488 Expr **Args, unsigned NumArgs) { 4489 if (!Failed()) 4490 return false; 4491 4492 QualType DestType = Entity.getType(); 4493 switch (Failure) { 4494 case FK_TooManyInitsForReference: 4495 // FIXME: Customize for the initialized entity? 4496 if (NumArgs == 0) 4497 S.Diag(Kind.getLocation(), diag::err_reference_without_init) 4498 << DestType.getNonReferenceType(); 4499 else // FIXME: diagnostic below could be better! 4500 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits) 4501 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd()); 4502 break; 4503 4504 case FK_ArrayNeedsInitList: 4505 case FK_ArrayNeedsInitListOrStringLiteral: 4506 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) 4507 << (Failure == FK_ArrayNeedsInitListOrStringLiteral); 4508 break; 4509 4510 case FK_ArrayTypeMismatch: 4511 case FK_NonConstantArrayInit: 4512 S.Diag(Kind.getLocation(), 4513 (Failure == FK_ArrayTypeMismatch 4514 ? diag::err_array_init_different_type 4515 : diag::err_array_init_non_constant_array)) 4516 << DestType.getNonReferenceType() 4517 << Args[0]->getType() 4518 << Args[0]->getSourceRange(); 4519 break; 4520 4521 case FK_AddressOfOverloadFailed: { 4522 DeclAccessPair Found; 4523 S.ResolveAddressOfOverloadedFunction(Args[0], 4524 DestType.getNonReferenceType(), 4525 true, 4526 Found); 4527 break; 4528 } 4529 4530 case FK_ReferenceInitOverloadFailed: 4531 case FK_UserConversionOverloadFailed: 4532 switch (FailedOverloadResult) { 4533 case OR_Ambiguous: 4534 if (Failure == FK_UserConversionOverloadFailed) 4535 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition) 4536 << Args[0]->getType() << DestType 4537 << Args[0]->getSourceRange(); 4538 else 4539 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous) 4540 << DestType << Args[0]->getType() 4541 << Args[0]->getSourceRange(); 4542 4543 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs); 4544 break; 4545 4546 case OR_No_Viable_Function: 4547 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition) 4548 << Args[0]->getType() << DestType.getNonReferenceType() 4549 << Args[0]->getSourceRange(); 4550 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs); 4551 break; 4552 4553 case OR_Deleted: { 4554 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function) 4555 << Args[0]->getType() << DestType.getNonReferenceType() 4556 << Args[0]->getSourceRange(); 4557 OverloadCandidateSet::iterator Best; 4558 OverloadingResult Ovl 4559 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best, 4560 true); 4561 if (Ovl == OR_Deleted) { 4562 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here) 4563 << 1 << Best->Function->isDeleted(); 4564 } else { 4565 llvm_unreachable("Inconsistent overload resolution?"); 4566 } 4567 break; 4568 } 4569 4570 case OR_Success: 4571 llvm_unreachable("Conversion did not fail!"); 4572 break; 4573 } 4574 break; 4575 4576 case FK_NonConstLValueReferenceBindingToTemporary: 4577 case FK_NonConstLValueReferenceBindingToUnrelated: 4578 S.Diag(Kind.getLocation(), 4579 Failure == FK_NonConstLValueReferenceBindingToTemporary 4580 ? diag::err_lvalue_reference_bind_to_temporary 4581 : diag::err_lvalue_reference_bind_to_unrelated) 4582 << DestType.getNonReferenceType().isVolatileQualified() 4583 << DestType.getNonReferenceType() 4584 << Args[0]->getType() 4585 << Args[0]->getSourceRange(); 4586 break; 4587 4588 case FK_RValueReferenceBindingToLValue: 4589 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref) 4590 << DestType.getNonReferenceType() << Args[0]->getType() 4591 << Args[0]->getSourceRange(); 4592 break; 4593 4594 case FK_ReferenceInitDropsQualifiers: 4595 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals) 4596 << DestType.getNonReferenceType() 4597 << Args[0]->getType() 4598 << Args[0]->getSourceRange(); 4599 break; 4600 4601 case FK_ReferenceInitFailed: 4602 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed) 4603 << DestType.getNonReferenceType() 4604 << Args[0]->isLValue() 4605 << Args[0]->getType() 4606 << Args[0]->getSourceRange(); 4607 if (DestType.getNonReferenceType()->isObjCObjectPointerType() && 4608 Args[0]->getType()->isObjCObjectPointerType()) 4609 S.EmitRelatedResultTypeNote(Args[0]); 4610 break; 4611 4612 case FK_ConversionFailed: { 4613 QualType FromType = Args[0]->getType(); 4614 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed) 4615 << (int)Entity.getKind() 4616 << DestType 4617 << Args[0]->isLValue() 4618 << FromType 4619 << Args[0]->getSourceRange(); 4620 if (DestType.getNonReferenceType()->isObjCObjectPointerType() && 4621 Args[0]->getType()->isObjCObjectPointerType()) 4622 S.EmitRelatedResultTypeNote(Args[0]); 4623 break; 4624 } 4625 4626 case FK_ConversionFromPropertyFailed: 4627 // No-op. This error has already been reported. 4628 break; 4629 4630 case FK_TooManyInitsForScalar: { 4631 SourceRange R; 4632 4633 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0])) 4634 R = SourceRange(InitList->getInit(0)->getLocEnd(), 4635 InitList->getLocEnd()); 4636 else 4637 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd()); 4638 4639 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin())); 4640 if (Kind.isCStyleOrFunctionalCast()) 4641 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg) 4642 << R; 4643 else 4644 S.Diag(Kind.getLocation(), diag::err_excess_initializers) 4645 << /*scalar=*/2 << R; 4646 break; 4647 } 4648 4649 case FK_ReferenceBindingToInitList: 4650 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list) 4651 << DestType.getNonReferenceType() << Args[0]->getSourceRange(); 4652 break; 4653 4654 case FK_InitListBadDestinationType: 4655 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type) 4656 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange(); 4657 break; 4658 4659 case FK_ConstructorOverloadFailed: { 4660 SourceRange ArgsRange; 4661 if (NumArgs) 4662 ArgsRange = SourceRange(Args[0]->getLocStart(), 4663 Args[NumArgs - 1]->getLocEnd()); 4664 4665 // FIXME: Using "DestType" for the entity we're printing is probably 4666 // bad. 4667 switch (FailedOverloadResult) { 4668 case OR_Ambiguous: 4669 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init) 4670 << DestType << ArgsRange; 4671 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, 4672 Args, NumArgs); 4673 break; 4674 4675 case OR_No_Viable_Function: 4676 if (Kind.getKind() == InitializationKind::IK_Default && 4677 (Entity.getKind() == InitializedEntity::EK_Base || 4678 Entity.getKind() == InitializedEntity::EK_Member) && 4679 isa<CXXConstructorDecl>(S.CurContext)) { 4680 // This is implicit default initialization of a member or 4681 // base within a constructor. If no viable function was 4682 // found, notify the user that she needs to explicitly 4683 // initialize this base/member. 4684 CXXConstructorDecl *Constructor 4685 = cast<CXXConstructorDecl>(S.CurContext); 4686 if (Entity.getKind() == InitializedEntity::EK_Base) { 4687 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor) 4688 << Constructor->isImplicit() 4689 << S.Context.getTypeDeclType(Constructor->getParent()) 4690 << /*base=*/0 4691 << Entity.getType(); 4692 4693 RecordDecl *BaseDecl 4694 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>() 4695 ->getDecl(); 4696 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl) 4697 << S.Context.getTagDeclType(BaseDecl); 4698 } else { 4699 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor) 4700 << Constructor->isImplicit() 4701 << S.Context.getTypeDeclType(Constructor->getParent()) 4702 << /*member=*/1 4703 << Entity.getName(); 4704 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl); 4705 4706 if (const RecordType *Record 4707 = Entity.getType()->getAs<RecordType>()) 4708 S.Diag(Record->getDecl()->getLocation(), 4709 diag::note_previous_decl) 4710 << S.Context.getTagDeclType(Record->getDecl()); 4711 } 4712 break; 4713 } 4714 4715 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init) 4716 << DestType << ArgsRange; 4717 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs); 4718 break; 4719 4720 case OR_Deleted: { 4721 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init) 4722 << true << DestType << ArgsRange; 4723 OverloadCandidateSet::iterator Best; 4724 OverloadingResult Ovl 4725 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best); 4726 if (Ovl == OR_Deleted) { 4727 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here) 4728 << 1 << Best->Function->isDeleted(); 4729 } else { 4730 llvm_unreachable("Inconsistent overload resolution?"); 4731 } 4732 break; 4733 } 4734 4735 case OR_Success: 4736 llvm_unreachable("Conversion did not fail!"); 4737 break; 4738 } 4739 break; 4740 } 4741 4742 case FK_DefaultInitOfConst: 4743 if (Entity.getKind() == InitializedEntity::EK_Member && 4744 isa<CXXConstructorDecl>(S.CurContext)) { 4745 // This is implicit default-initialization of a const member in 4746 // a constructor. Complain that it needs to be explicitly 4747 // initialized. 4748 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext); 4749 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor) 4750 << Constructor->isImplicit() 4751 << S.Context.getTypeDeclType(Constructor->getParent()) 4752 << /*const=*/1 4753 << Entity.getName(); 4754 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl) 4755 << Entity.getName(); 4756 } else { 4757 S.Diag(Kind.getLocation(), diag::err_default_init_const) 4758 << DestType << (bool)DestType->getAs<RecordType>(); 4759 } 4760 break; 4761 4762 case FK_Incomplete: 4763 S.RequireCompleteType(Kind.getLocation(), DestType, 4764 diag::err_init_incomplete_type); 4765 break; 4766 } 4767 4768 PrintInitLocationNote(S, Entity); 4769 return true; 4770} 4771 4772void InitializationSequence::dump(llvm::raw_ostream &OS) const { 4773 switch (SequenceKind) { 4774 case FailedSequence: { 4775 OS << "Failed sequence: "; 4776 switch (Failure) { 4777 case FK_TooManyInitsForReference: 4778 OS << "too many initializers for reference"; 4779 break; 4780 4781 case FK_ArrayNeedsInitList: 4782 OS << "array requires initializer list"; 4783 break; 4784 4785 case FK_ArrayNeedsInitListOrStringLiteral: 4786 OS << "array requires initializer list or string literal"; 4787 break; 4788 4789 case FK_ArrayTypeMismatch: 4790 OS << "array type mismatch"; 4791 break; 4792 4793 case FK_NonConstantArrayInit: 4794 OS << "non-constant array initializer"; 4795 break; 4796 4797 case FK_AddressOfOverloadFailed: 4798 OS << "address of overloaded function failed"; 4799 break; 4800 4801 case FK_ReferenceInitOverloadFailed: 4802 OS << "overload resolution for reference initialization failed"; 4803 break; 4804 4805 case FK_NonConstLValueReferenceBindingToTemporary: 4806 OS << "non-const lvalue reference bound to temporary"; 4807 break; 4808 4809 case FK_NonConstLValueReferenceBindingToUnrelated: 4810 OS << "non-const lvalue reference bound to unrelated type"; 4811 break; 4812 4813 case FK_RValueReferenceBindingToLValue: 4814 OS << "rvalue reference bound to an lvalue"; 4815 break; 4816 4817 case FK_ReferenceInitDropsQualifiers: 4818 OS << "reference initialization drops qualifiers"; 4819 break; 4820 4821 case FK_ReferenceInitFailed: 4822 OS << "reference initialization failed"; 4823 break; 4824 4825 case FK_ConversionFailed: 4826 OS << "conversion failed"; 4827 break; 4828 4829 case FK_ConversionFromPropertyFailed: 4830 OS << "conversion from property failed"; 4831 break; 4832 4833 case FK_TooManyInitsForScalar: 4834 OS << "too many initializers for scalar"; 4835 break; 4836 4837 case FK_ReferenceBindingToInitList: 4838 OS << "referencing binding to initializer list"; 4839 break; 4840 4841 case FK_InitListBadDestinationType: 4842 OS << "initializer list for non-aggregate, non-scalar type"; 4843 break; 4844 4845 case FK_UserConversionOverloadFailed: 4846 OS << "overloading failed for user-defined conversion"; 4847 break; 4848 4849 case FK_ConstructorOverloadFailed: 4850 OS << "constructor overloading failed"; 4851 break; 4852 4853 case FK_DefaultInitOfConst: 4854 OS << "default initialization of a const variable"; 4855 break; 4856 4857 case FK_Incomplete: 4858 OS << "initialization of incomplete type"; 4859 break; 4860 } 4861 OS << '\n'; 4862 return; 4863 } 4864 4865 case DependentSequence: 4866 OS << "Dependent sequence\n"; 4867 return; 4868 4869 case NormalSequence: 4870 OS << "Normal sequence: "; 4871 break; 4872 } 4873 4874 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) { 4875 if (S != step_begin()) { 4876 OS << " -> "; 4877 } 4878 4879 switch (S->Kind) { 4880 case SK_ResolveAddressOfOverloadedFunction: 4881 OS << "resolve address of overloaded function"; 4882 break; 4883 4884 case SK_CastDerivedToBaseRValue: 4885 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")"; 4886 break; 4887 4888 case SK_CastDerivedToBaseXValue: 4889 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")"; 4890 break; 4891 4892 case SK_CastDerivedToBaseLValue: 4893 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")"; 4894 break; 4895 4896 case SK_BindReference: 4897 OS << "bind reference to lvalue"; 4898 break; 4899 4900 case SK_BindReferenceToTemporary: 4901 OS << "bind reference to a temporary"; 4902 break; 4903 4904 case SK_ExtraneousCopyToTemporary: 4905 OS << "extraneous C++03 copy to temporary"; 4906 break; 4907 4908 case SK_UserConversion: 4909 OS << "user-defined conversion via " << S->Function.Function; 4910 break; 4911 4912 case SK_QualificationConversionRValue: 4913 OS << "qualification conversion (rvalue)"; 4914 4915 case SK_QualificationConversionXValue: 4916 OS << "qualification conversion (xvalue)"; 4917 4918 case SK_QualificationConversionLValue: 4919 OS << "qualification conversion (lvalue)"; 4920 break; 4921 4922 case SK_ConversionSequence: 4923 OS << "implicit conversion sequence ("; 4924 S->ICS->DebugPrint(); // FIXME: use OS 4925 OS << ")"; 4926 break; 4927 4928 case SK_ListInitialization: 4929 OS << "list initialization"; 4930 break; 4931 4932 case SK_ConstructorInitialization: 4933 OS << "constructor initialization"; 4934 break; 4935 4936 case SK_ZeroInitialization: 4937 OS << "zero initialization"; 4938 break; 4939 4940 case SK_CAssignment: 4941 OS << "C assignment"; 4942 break; 4943 4944 case SK_StringInit: 4945 OS << "string initialization"; 4946 break; 4947 4948 case SK_ObjCObjectConversion: 4949 OS << "Objective-C object conversion"; 4950 break; 4951 4952 case SK_ArrayInit: 4953 OS << "array initialization"; 4954 break; 4955 4956 case SK_PassByIndirectCopyRestore: 4957 OS << "pass by indirect copy and restore"; 4958 break; 4959 4960 case SK_PassByIndirectRestore: 4961 OS << "pass by indirect restore"; 4962 break; 4963 4964 case SK_ProduceObjCObject: 4965 OS << "Objective-C object retension"; 4966 break; 4967 } 4968 } 4969} 4970 4971void InitializationSequence::dump() const { 4972 dump(llvm::errs()); 4973} 4974 4975//===----------------------------------------------------------------------===// 4976// Initialization helper functions 4977//===----------------------------------------------------------------------===// 4978bool 4979Sema::CanPerformCopyInitialization(const InitializedEntity &Entity, 4980 ExprResult Init) { 4981 if (Init.isInvalid()) 4982 return false; 4983 4984 Expr *InitE = Init.get(); 4985 assert(InitE && "No initialization expression"); 4986 4987 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(), 4988 SourceLocation()); 4989 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1); 4990 return !Seq.Failed(); 4991} 4992 4993ExprResult 4994Sema::PerformCopyInitialization(const InitializedEntity &Entity, 4995 SourceLocation EqualLoc, 4996 ExprResult Init) { 4997 if (Init.isInvalid()) 4998 return ExprError(); 4999 5000 Expr *InitE = Init.get(); 5001 assert(InitE && "No initialization expression?"); 5002 5003 if (EqualLoc.isInvalid()) 5004 EqualLoc = InitE->getLocStart(); 5005 5006 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(), 5007 EqualLoc); 5008 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1); 5009 Init.release(); 5010 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1)); 5011} 5012