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