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