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