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