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