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