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