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