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