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