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