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