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