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