1 //===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for initializers.
12 //===----------------------------------------------------------------------===//
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"
29 using namespace clang;
31 //===----------------------------------------------------------------------===//
32 // Sema Initialization Checking
33 //===----------------------------------------------------------------------===//
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))
40 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
41 return Context.typesAreCompatible(Context.Char16Ty, T) ||
42 Context.typesAreCompatible(Context.Char32Ty, T);
47 enum StringInitFailureKind {
49 SIF_NarrowStringIntoWideChar,
50 SIF_WideStringIntoChar,
51 SIF_IncompatWideStringIntoWideChar,
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))
64 // See if this is a string literal or @encode.
65 Init = Init->IgnoreParens();
67 // Handle @encode, which is a narrow string.
68 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
71 // Otherwise we can only handle string literals.
72 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
76 const QualType ElemTy =
77 Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
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())
86 if (IsWideCharCompatible(ElemTy, Context))
87 return SIF_NarrowStringIntoWideChar;
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))
97 if (ElemTy->isCharType())
98 return SIF_WideStringIntoChar;
99 if (IsWideCharCompatible(ElemTy, Context))
100 return SIF_IncompatWideStringIntoWideChar;
102 case StringLiteral::UTF32:
103 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
105 if (ElemTy->isCharType())
106 return SIF_WideStringIntoChar;
107 if (IsWideCharCompatible(ElemTy, Context))
108 return SIF_IncompatWideStringIntoWideChar;
110 case StringLiteral::Wide:
111 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
113 if (ElemTy->isCharType())
114 return SIF_WideStringIntoChar;
115 if (IsWideCharCompatible(ElemTy, Context))
116 return SIF_IncompatWideStringIntoWideChar;
120 llvm_unreachable("missed a StringLiteral kind?");
123 static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
124 ASTContext &Context) {
125 const ArrayType *arrayType = Context.getAsArrayType(declType);
128 return IsStringInit(init, arrayType, Context);
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) {
136 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
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();
145 llvm_unreachable("unexpected expr in string literal init");
149 static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
151 // Get the length of the string as parsed.
153 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
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(),
163 ArrayType::Normal, 0);
164 updateStringLiteralType(Str, DeclT);
168 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
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:
178 // unsigned char a[2] = "\pa";
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();
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();
196 // Set the type to the actual size that we are initializing. If we have
198 // char x[1] = "foo";
199 // then this will set the string literal's type to char[1].
200 updateStringLiteralType(Str, DeclT);
203 //===----------------------------------------------------------------------===//
204 // Semantic checking for initializer lists.
205 //===----------------------------------------------------------------------===//
207 /// @brief Semantic checking for initializer lists.
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.
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
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.
235 class InitListChecker {
238 bool VerifyOnly; // no diagnostics, no structure building
239 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
240 InitListExpr *FullyStructuredList;
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,
254 InitListExpr *StructuredList,
255 unsigned &StructuredIndex,
256 bool TopLevelObject = false);
257 void CheckSubElementType(const InitializedEntity &Entity,
258 InitListExpr *IList, QualType ElemType,
260 InitListExpr *StructuredList,
261 unsigned &StructuredIndex);
262 void CheckComplexType(const InitializedEntity &Entity,
263 InitListExpr *IList, QualType DeclType,
265 InitListExpr *StructuredList,
266 unsigned &StructuredIndex);
267 void CheckScalarType(const InitializedEntity &Entity,
268 InitListExpr *IList, QualType DeclType,
270 InitListExpr *StructuredList,
271 unsigned &StructuredIndex);
272 void CheckReferenceType(const InitializedEntity &Entity,
273 InitListExpr *IList, QualType DeclType,
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,
297 QualType &CurrentObjectType,
298 RecordDecl::field_iterator *NextField,
299 llvm::APSInt *NextElementIndex,
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,
313 int numArrayElements(QualType DeclType);
314 int numStructUnionElements(QualType DeclType);
316 static ExprResult PerformEmptyInit(Sema &SemaRef,
318 const InitializedEntity &Entity,
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,
332 InitListChecker(Sema &S, const InitializedEntity &Entity,
333 InitListExpr *IL, QualType &T, bool VerifyOnly);
334 bool HadError() { return hadError; }
336 // @brief Retrieves the fully-structured initializer list used for
337 // semantic analysis and code generation.
338 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
340 } // end anonymous namespace
342 ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef,
344 const InitializedEntity &Entity,
346 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
348 MultiExprArg SubInit;
350 InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
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
356 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
357 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
360 // shall be initialized [...] from an empty initializer list.
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.
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);
373 Kind = InitializationKind::CreateCopy(Loc, Loc);
376 // shall be value-initialized.
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
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);
392 assert(O == OR_Success && "Inconsistent overload resolution");
393 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
394 CXXRecordDecl *R = CtorDecl->getParent();
396 if (CtorDecl->getMinRequiredArguments() == 0 &&
397 CtorDecl->isExplicit() && R->getDeclName() &&
398 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
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))
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)
414 InitSeq.InitializeFrom(
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.
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);
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();
443 return VerifyOnly ? ExprResult(static_cast<Expr *>(nullptr))
444 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
447 void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
448 SourceLocation Loc) {
450 "CheckEmptyInitializable is only inteded for verification mode.");
451 if (PerformEmptyInit(SemaRef, Loc, Entity, /*VerifyOnly*/true).isInvalid())
455 void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
456 const InitializedEntity &ParentEntity,
458 bool &RequiresSecondPass) {
459 SourceLocation Loc = ILE->getLocEnd();
460 unsigned NumInits = ILE->getNumInits();
461 InitializedEntity MemberEntity
462 = InitializedEntity::InitializeMember(Field, &ParentEntity);
463 if (Init >= NumInits || !ILE->getInit(Init)) {
464 // C++1y [dcl.init.aggr]p7:
465 // If there are fewer initializer-clauses in the list than there are
466 // members in the aggregate, then each member not explicitly initialized
467 // shall be initialized from its brace-or-equal-initializer [...]
468 if (Field->hasInClassInitializer()) {
469 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context, Loc, Field);
471 ILE->setInit(Init, DIE);
473 ILE->updateInit(SemaRef.Context, Init, DIE);
474 RequiresSecondPass = true;
479 if (Field->getType()->isReferenceType()) {
480 // C++ [dcl.init.aggr]p9:
481 // If an incomplete or empty initializer-list leaves a
482 // member of reference type uninitialized, the program is
484 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
486 << ILE->getSyntacticForm()->getSourceRange();
487 SemaRef.Diag(Field->getLocation(),
488 diag::note_uninit_reference_member);
493 ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
494 /*VerifyOnly*/false);
495 if (MemberInit.isInvalid()) {
502 } else if (Init < NumInits) {
503 ILE->setInit(Init, MemberInit.getAs<Expr>());
504 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
505 // Empty initialization requires a constructor call, so
506 // extend the initializer list to include the constructor
507 // call and make a note that we'll need to take another pass
508 // through the initializer list.
509 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
510 RequiresSecondPass = true;
512 } else if (InitListExpr *InnerILE
513 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
514 FillInEmptyInitializations(MemberEntity, InnerILE,
518 /// Recursively replaces NULL values within the given initializer list
519 /// with expressions that perform value-initialization of the
520 /// appropriate type.
522 InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
524 bool &RequiresSecondPass) {
525 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
526 "Should not have void type");
528 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
529 const RecordDecl *RDecl = RType->getDecl();
530 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
531 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
532 Entity, ILE, RequiresSecondPass);
533 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
534 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
535 for (auto *Field : RDecl->fields()) {
536 if (Field->hasInClassInitializer()) {
537 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass);
543 for (auto *Field : RDecl->fields()) {
544 if (Field->isUnnamedBitfield())
550 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass);
556 // Only look at the first initialization of a union.
557 if (RDecl->isUnion())
565 QualType ElementType;
567 InitializedEntity ElementEntity = Entity;
568 unsigned NumInits = ILE->getNumInits();
569 unsigned NumElements = NumInits;
570 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
571 ElementType = AType->getElementType();
572 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
573 NumElements = CAType->getSize().getZExtValue();
574 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
576 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
577 ElementType = VType->getElementType();
578 NumElements = VType->getNumElements();
579 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
582 ElementType = ILE->getType();
584 for (unsigned Init = 0; Init != NumElements; ++Init) {
588 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
589 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
590 ElementEntity.setElementIndex(Init);
592 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
593 if (!InitExpr && !ILE->hasArrayFiller()) {
594 ExprResult ElementInit = PerformEmptyInit(SemaRef, ILE->getLocEnd(),
596 /*VerifyOnly*/false);
597 if (ElementInit.isInvalid()) {
604 } else if (Init < NumInits) {
605 // For arrays, just set the expression used for value-initialization
606 // of the "holes" in the array.
607 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
608 ILE->setArrayFiller(ElementInit.getAs<Expr>());
610 ILE->setInit(Init, ElementInit.getAs<Expr>());
612 // For arrays, just set the expression used for value-initialization
613 // of the rest of elements and exit.
614 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
615 ILE->setArrayFiller(ElementInit.getAs<Expr>());
619 if (!isa<ImplicitValueInitExpr>(ElementInit.get())) {
620 // Empty initialization requires a constructor call, so
621 // extend the initializer list to include the constructor
622 // call and make a note that we'll need to take another pass
623 // through the initializer list.
624 ILE->updateInit(SemaRef.Context, Init, ElementInit.getAs<Expr>());
625 RequiresSecondPass = true;
628 } else if (InitListExpr *InnerILE
629 = dyn_cast_or_null<InitListExpr>(InitExpr))
630 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass);
635 InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
636 InitListExpr *IL, QualType &T,
638 : SemaRef(S), VerifyOnly(VerifyOnly) {
641 FullyStructuredList =
642 getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
643 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
644 /*TopLevelObject=*/true);
646 if (!hadError && !VerifyOnly) {
647 bool RequiresSecondPass = false;
648 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass);
649 if (RequiresSecondPass && !hadError)
650 FillInEmptyInitializations(Entity, FullyStructuredList,
655 int InitListChecker::numArrayElements(QualType DeclType) {
656 // FIXME: use a proper constant
657 int maxElements = 0x7FFFFFFF;
658 if (const ConstantArrayType *CAT =
659 SemaRef.Context.getAsConstantArrayType(DeclType)) {
660 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
665 int InitListChecker::numStructUnionElements(QualType DeclType) {
666 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
667 int InitializableMembers = 0;
668 for (const auto *Field : structDecl->fields())
669 if (!Field->isUnnamedBitfield())
670 ++InitializableMembers;
672 if (structDecl->isUnion())
673 return std::min(InitializableMembers, 1);
674 return InitializableMembers - structDecl->hasFlexibleArrayMember();
677 /// Check whether the range of the initializer \p ParentIList from element
678 /// \p Index onwards can be used to initialize an object of type \p T. Update
679 /// \p Index to indicate how many elements of the list were consumed.
681 /// This also fills in \p StructuredList, from element \p StructuredIndex
682 /// onwards, with the fully-braced, desugared form of the initialization.
683 void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
684 InitListExpr *ParentIList,
685 QualType T, unsigned &Index,
686 InitListExpr *StructuredList,
687 unsigned &StructuredIndex) {
690 if (T->isArrayType())
691 maxElements = numArrayElements(T);
692 else if (T->isRecordType())
693 maxElements = numStructUnionElements(T);
694 else if (T->isVectorType())
695 maxElements = T->getAs<VectorType>()->getNumElements();
697 llvm_unreachable("CheckImplicitInitList(): Illegal type");
699 if (maxElements == 0) {
701 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
702 diag::err_implicit_empty_initializer);
708 // Build a structured initializer list corresponding to this subobject.
709 InitListExpr *StructuredSubobjectInitList
710 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
712 SourceRange(ParentIList->getInit(Index)->getLocStart(),
713 ParentIList->getSourceRange().getEnd()));
714 unsigned StructuredSubobjectInitIndex = 0;
716 // Check the element types and build the structural subobject.
717 unsigned StartIndex = Index;
718 CheckListElementTypes(Entity, ParentIList, T,
719 /*SubobjectIsDesignatorContext=*/false, Index,
720 StructuredSubobjectInitList,
721 StructuredSubobjectInitIndex);
724 StructuredSubobjectInitList->setType(T);
726 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
727 // Update the structured sub-object initializer so that it's ending
728 // range corresponds with the end of the last initializer it used.
729 if (EndIndex < ParentIList->getNumInits()) {
730 SourceLocation EndLoc
731 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
732 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
735 // Complain about missing braces.
736 if (T->isArrayType() || T->isRecordType()) {
737 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
738 diag::warn_missing_braces)
739 << StructuredSubobjectInitList->getSourceRange()
740 << FixItHint::CreateInsertion(
741 StructuredSubobjectInitList->getLocStart(), "{")
742 << FixItHint::CreateInsertion(
743 SemaRef.getLocForEndOfToken(
744 StructuredSubobjectInitList->getLocEnd()),
750 /// Check whether the initializer \p IList (that was written with explicit
751 /// braces) can be used to initialize an object of type \p T.
753 /// This also fills in \p StructuredList with the fully-braced, desugared
754 /// form of the initialization.
755 void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
756 InitListExpr *IList, QualType &T,
757 InitListExpr *StructuredList,
758 bool TopLevelObject) {
760 SyntacticToSemantic[IList] = StructuredList;
761 StructuredList->setSyntacticForm(IList);
764 unsigned Index = 0, StructuredIndex = 0;
765 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
766 Index, StructuredList, StructuredIndex, TopLevelObject);
769 if (!ExprTy->isArrayType())
770 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
771 IList->setType(ExprTy);
772 StructuredList->setType(ExprTy);
777 if (Index < IList->getNumInits()) {
778 // We have leftover initializers
780 if (SemaRef.getLangOpts().CPlusPlus ||
781 (SemaRef.getLangOpts().OpenCL &&
782 IList->getType()->isVectorType())) {
788 if (StructuredIndex == 1 &&
789 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
791 unsigned DK = diag::ext_excess_initializers_in_char_array_initializer;
792 if (SemaRef.getLangOpts().CPlusPlus) {
793 DK = diag::err_excess_initializers_in_char_array_initializer;
797 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
798 << IList->getInit(Index)->getSourceRange();
799 } else if (!T->isIncompleteType()) {
800 // Don't complain for incomplete types, since we'll get an error
802 QualType CurrentObjectType = StructuredList->getType();
804 CurrentObjectType->isArrayType()? 0 :
805 CurrentObjectType->isVectorType()? 1 :
806 CurrentObjectType->isScalarType()? 2 :
807 CurrentObjectType->isUnionType()? 3 :
810 unsigned DK = diag::ext_excess_initializers;
811 if (SemaRef.getLangOpts().CPlusPlus) {
812 DK = diag::err_excess_initializers;
815 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
816 DK = diag::err_excess_initializers;
820 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
821 << initKind << IList->getInit(Index)->getSourceRange();
825 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
827 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
828 << IList->getSourceRange()
829 << FixItHint::CreateRemoval(IList->getLocStart())
830 << FixItHint::CreateRemoval(IList->getLocEnd());
833 void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
836 bool SubobjectIsDesignatorContext,
838 InitListExpr *StructuredList,
839 unsigned &StructuredIndex,
840 bool TopLevelObject) {
841 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
842 // Explicitly braced initializer for complex type can be real+imaginary
844 CheckComplexType(Entity, IList, DeclType, Index,
845 StructuredList, StructuredIndex);
846 } else if (DeclType->isScalarType()) {
847 CheckScalarType(Entity, IList, DeclType, Index,
848 StructuredList, StructuredIndex);
849 } else if (DeclType->isVectorType()) {
850 CheckVectorType(Entity, IList, DeclType, Index,
851 StructuredList, StructuredIndex);
852 } else if (DeclType->isRecordType()) {
853 assert(DeclType->isAggregateType() &&
854 "non-aggregate records should be handed in CheckSubElementType");
855 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
856 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
857 SubobjectIsDesignatorContext, Index,
858 StructuredList, StructuredIndex,
860 } else if (DeclType->isArrayType()) {
862 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
864 CheckArrayType(Entity, IList, DeclType, Zero,
865 SubobjectIsDesignatorContext, Index,
866 StructuredList, StructuredIndex);
867 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
868 // This type is invalid, issue a diagnostic.
871 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
874 } else if (DeclType->isReferenceType()) {
875 CheckReferenceType(Entity, IList, DeclType, Index,
876 StructuredList, StructuredIndex);
877 } else if (DeclType->isObjCObjectType()) {
879 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
884 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
890 void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
894 InitListExpr *StructuredList,
895 unsigned &StructuredIndex) {
896 Expr *expr = IList->getInit(Index);
898 if (ElemType->isReferenceType())
899 return CheckReferenceType(Entity, IList, ElemType, Index,
900 StructuredList, StructuredIndex);
902 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
903 if (!ElemType->isRecordType() || ElemType->isAggregateType()) {
904 InitListExpr *InnerStructuredList
905 = getStructuredSubobjectInit(IList, Index, ElemType,
906 StructuredList, StructuredIndex,
907 SubInitList->getSourceRange());
908 CheckExplicitInitList(Entity, SubInitList, ElemType,
909 InnerStructuredList);
914 assert(SemaRef.getLangOpts().CPlusPlus &&
915 "non-aggregate records are only possible in C++");
916 // C++ initialization is handled later.
917 } else if (isa<ImplicitValueInitExpr>(expr)) {
918 // This happens during template instantiation when we see an InitListExpr
919 // that we've already checked once.
920 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
921 "found implicit initialization for the wrong type");
923 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
928 // FIXME: Need to handle atomic aggregate types with implicit init lists.
929 if (ElemType->isScalarType() || ElemType->isAtomicType())
930 return CheckScalarType(Entity, IList, ElemType, Index,
931 StructuredList, StructuredIndex);
933 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
934 ElemType->isArrayType()) && "Unexpected type");
936 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
937 // arrayType can be incomplete if we're initializing a flexible
938 // array member. There's nothing we can do with the completed
939 // type here, though.
941 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
943 CheckStringInit(expr, ElemType, arrayType, SemaRef);
944 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
950 // Fall through for subaggregate initialization.
952 } else if (SemaRef.getLangOpts().CPlusPlus) {
953 // C++ [dcl.init.aggr]p12:
954 // All implicit type conversions (clause 4) are considered when
955 // initializing the aggregate member with an initializer from
956 // an initializer-list. If the initializer can initialize a
957 // member, the member is initialized. [...]
959 // FIXME: Better EqualLoc?
960 InitializationKind Kind =
961 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
962 InitializationSequence Seq(SemaRef, Entity, Kind, expr);
967 Seq.Perform(SemaRef, Entity, Kind, expr);
968 if (Result.isInvalid())
971 UpdateStructuredListElement(StructuredList, StructuredIndex,
972 Result.getAs<Expr>());
978 // Fall through for subaggregate initialization
982 // The initializer for a structure or union object that has
983 // automatic storage duration shall be either an initializer
984 // list as described below, or a single expression that has
985 // compatible structure or union type. In the latter case, the
986 // initial value of the object, including unnamed members, is
987 // that of the expression.
988 ExprResult ExprRes = expr;
989 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
990 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
992 != Sema::Incompatible) {
993 if (ExprRes.isInvalid())
996 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
997 if (ExprRes.isInvalid())
1000 UpdateStructuredListElement(StructuredList, StructuredIndex,
1001 ExprRes.getAs<Expr>());
1006 // Fall through for subaggregate initialization
1009 // C++ [dcl.init.aggr]p12:
1011 // [...] Otherwise, if the member is itself a non-empty
1012 // subaggregate, brace elision is assumed and the initializer is
1013 // considered for the initialization of the first member of
1014 // the subaggregate.
1015 if (!SemaRef.getLangOpts().OpenCL &&
1016 (ElemType->isAggregateType() || ElemType->isVectorType())) {
1017 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1022 // We cannot initialize this element, so let
1023 // PerformCopyInitialization produce the appropriate diagnostic.
1024 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
1025 /*TopLevelOfInitList=*/true);
1033 void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1034 InitListExpr *IList, QualType DeclType,
1036 InitListExpr *StructuredList,
1037 unsigned &StructuredIndex) {
1038 assert(Index == 0 && "Index in explicit init list must be zero");
1040 // As an extension, clang supports complex initializers, which initialize
1041 // a complex number component-wise. When an explicit initializer list for
1042 // a complex number contains two two initializers, this extension kicks in:
1043 // it exepcts the initializer list to contain two elements convertible to
1044 // the element type of the complex type. The first element initializes
1045 // the real part, and the second element intitializes the imaginary part.
1047 if (IList->getNumInits() != 2)
1048 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1051 // This is an extension in C. (The builtin _Complex type does not exist
1052 // in the C++ standard.)
1053 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
1054 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
1055 << IList->getSourceRange();
1057 // Initialize the complex number.
1058 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
1059 InitializedEntity ElementEntity =
1060 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1062 for (unsigned i = 0; i < 2; ++i) {
1063 ElementEntity.setElementIndex(Index);
1064 CheckSubElementType(ElementEntity, IList, elementType, Index,
1065 StructuredList, StructuredIndex);
1070 void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
1071 InitListExpr *IList, QualType DeclType,
1073 InitListExpr *StructuredList,
1074 unsigned &StructuredIndex) {
1075 if (Index >= IList->getNumInits()) {
1077 SemaRef.Diag(IList->getLocStart(),
1078 SemaRef.getLangOpts().CPlusPlus11 ?
1079 diag::warn_cxx98_compat_empty_scalar_initializer :
1080 diag::err_empty_scalar_initializer)
1081 << IList->getSourceRange();
1082 hadError = !SemaRef.getLangOpts().CPlusPlus11;
1088 Expr *expr = IList->getInit(Index);
1089 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
1090 // FIXME: This is invalid, and accepting it causes overload resolution
1091 // to pick the wrong overload in some corner cases.
1093 SemaRef.Diag(SubIList->getLocStart(),
1094 diag::ext_many_braces_around_scalar_init)
1095 << SubIList->getSourceRange();
1097 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1100 } else if (isa<DesignatedInitExpr>(expr)) {
1102 SemaRef.Diag(expr->getLocStart(),
1103 diag::err_designator_for_scalar_init)
1104 << DeclType << expr->getSourceRange();
1112 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
1119 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1120 /*TopLevelOfInitList=*/true);
1122 Expr *ResultExpr = nullptr;
1124 if (Result.isInvalid())
1125 hadError = true; // types weren't compatible.
1127 ResultExpr = Result.getAs<Expr>();
1129 if (ResultExpr != expr) {
1130 // The type was promoted, update initializer list.
1131 IList->setInit(Index, ResultExpr);
1137 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1141 void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1142 InitListExpr *IList, QualType DeclType,
1144 InitListExpr *StructuredList,
1145 unsigned &StructuredIndex) {
1146 if (Index >= IList->getNumInits()) {
1147 // FIXME: It would be wonderful if we could point at the actual member. In
1148 // general, it would be useful to pass location information down the stack,
1149 // so that we know the location (or decl) of the "current object" being
1152 SemaRef.Diag(IList->getLocStart(),
1153 diag::err_init_reference_member_uninitialized)
1155 << IList->getSourceRange();
1162 Expr *expr = IList->getInit(Index);
1163 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1165 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1166 << DeclType << IList->getSourceRange();
1174 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
1181 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1182 /*TopLevelOfInitList=*/true);
1184 if (Result.isInvalid())
1187 expr = Result.getAs<Expr>();
1188 IList->setInit(Index, expr);
1193 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1197 void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1198 InitListExpr *IList, QualType DeclType,
1200 InitListExpr *StructuredList,
1201 unsigned &StructuredIndex) {
1202 const VectorType *VT = DeclType->getAs<VectorType>();
1203 unsigned maxElements = VT->getNumElements();
1204 unsigned numEltsInit = 0;
1205 QualType elementType = VT->getElementType();
1207 if (Index >= IList->getNumInits()) {
1208 // Make sure the element type can be value-initialized.
1210 CheckEmptyInitializable(
1211 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1212 IList->getLocEnd());
1216 if (!SemaRef.getLangOpts().OpenCL) {
1217 // If the initializing element is a vector, try to copy-initialize
1218 // instead of breaking it apart (which is doomed to failure anyway).
1219 Expr *Init = IList->getInit(Index);
1220 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1222 if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
1229 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), Init,
1230 /*TopLevelOfInitList=*/true);
1232 Expr *ResultExpr = nullptr;
1233 if (Result.isInvalid())
1234 hadError = true; // types weren't compatible.
1236 ResultExpr = Result.getAs<Expr>();
1238 if (ResultExpr != Init) {
1239 // The type was promoted, update initializer list.
1240 IList->setInit(Index, ResultExpr);
1246 UpdateStructuredListElement(StructuredList, StructuredIndex,
1252 InitializedEntity ElementEntity =
1253 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1255 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1256 // Don't attempt to go past the end of the init list
1257 if (Index >= IList->getNumInits()) {
1259 CheckEmptyInitializable(ElementEntity, IList->getLocEnd());
1263 ElementEntity.setElementIndex(Index);
1264 CheckSubElementType(ElementEntity, IList, elementType, Index,
1265 StructuredList, StructuredIndex);
1271 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1272 const VectorType *T = Entity.getType()->getAs<VectorType>();
1273 if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1274 T->getVectorKind() == VectorType::NeonPolyVector)) {
1275 // The ability to use vector initializer lists is a GNU vector extension
1276 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1277 // endian machines it works fine, however on big endian machines it
1278 // exhibits surprising behaviour:
1280 // uint32x2_t x = {42, 64};
1281 // return vget_lane_u32(x, 0); // Will return 64.
1283 // Because of this, explicitly call out that it is non-portable.
1285 SemaRef.Diag(IList->getLocStart(),
1286 diag::warn_neon_vector_initializer_non_portable);
1288 const char *typeCode;
1289 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1291 if (elementType->isFloatingType())
1293 else if (elementType->isSignedIntegerType())
1295 else if (elementType->isUnsignedIntegerType())
1298 llvm_unreachable("Invalid element type!");
1300 SemaRef.Diag(IList->getLocStart(),
1301 SemaRef.Context.getTypeSize(VT) > 64 ?
1302 diag::note_neon_vector_initializer_non_portable_q :
1303 diag::note_neon_vector_initializer_non_portable)
1304 << typeCode << typeSize;
1310 InitializedEntity ElementEntity =
1311 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1313 // OpenCL initializers allows vectors to be constructed from vectors.
1314 for (unsigned i = 0; i < maxElements; ++i) {
1315 // Don't attempt to go past the end of the init list
1316 if (Index >= IList->getNumInits())
1319 ElementEntity.setElementIndex(Index);
1321 QualType IType = IList->getInit(Index)->getType();
1322 if (!IType->isVectorType()) {
1323 CheckSubElementType(ElementEntity, IList, elementType, Index,
1324 StructuredList, StructuredIndex);
1328 const VectorType *IVT = IType->getAs<VectorType>();
1329 unsigned numIElts = IVT->getNumElements();
1331 if (IType->isExtVectorType())
1332 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1334 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
1335 IVT->getVectorKind());
1336 CheckSubElementType(ElementEntity, IList, VecType, Index,
1337 StructuredList, StructuredIndex);
1338 numEltsInit += numIElts;
1342 // OpenCL requires all elements to be initialized.
1343 if (numEltsInit != maxElements) {
1345 SemaRef.Diag(IList->getLocStart(),
1346 diag::err_vector_incorrect_num_initializers)
1347 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1352 void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
1353 InitListExpr *IList, QualType &DeclType,
1354 llvm::APSInt elementIndex,
1355 bool SubobjectIsDesignatorContext,
1357 InitListExpr *StructuredList,
1358 unsigned &StructuredIndex) {
1359 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1361 // Check for the special-case of initializing an array with a string.
1362 if (Index < IList->getNumInits()) {
1363 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1365 // We place the string literal directly into the resulting
1366 // initializer list. This is the only place where the structure
1367 // of the structured initializer list doesn't match exactly,
1368 // because doing so would involve allocating one character
1369 // constant for each string.
1371 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1372 UpdateStructuredListElement(StructuredList, StructuredIndex,
1373 IList->getInit(Index));
1374 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1380 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
1381 // Check for VLAs; in standard C it would be possible to check this
1382 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1383 // them in all sorts of strange places).
1385 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1386 diag::err_variable_object_no_init)
1387 << VAT->getSizeExpr()->getSourceRange();
1394 // We might know the maximum number of elements in advance.
1395 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1396 elementIndex.isUnsigned());
1397 bool maxElementsKnown = false;
1398 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
1399 maxElements = CAT->getSize();
1400 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
1401 elementIndex.setIsUnsigned(maxElements.isUnsigned());
1402 maxElementsKnown = true;
1405 QualType elementType = arrayType->getElementType();
1406 while (Index < IList->getNumInits()) {
1407 Expr *Init = IList->getInit(Index);
1408 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1409 // If we're not the subobject that matches up with the '{' for
1410 // the designator, we shouldn't be handling the
1411 // designator. Return immediately.
1412 if (!SubobjectIsDesignatorContext)
1415 // Handle this designated initializer. elementIndex will be
1416 // updated to be the next array element we'll initialize.
1417 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1418 DeclType, nullptr, &elementIndex, Index,
1419 StructuredList, StructuredIndex, true,
1425 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1426 maxElements = maxElements.extend(elementIndex.getBitWidth());
1427 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1428 elementIndex = elementIndex.extend(maxElements.getBitWidth());
1429 elementIndex.setIsUnsigned(maxElements.isUnsigned());
1431 // If the array is of incomplete type, keep track of the number of
1432 // elements in the initializer.
1433 if (!maxElementsKnown && elementIndex > maxElements)
1434 maxElements = elementIndex;
1439 // If we know the maximum number of elements, and we've already
1440 // hit it, stop consuming elements in the initializer list.
1441 if (maxElementsKnown && elementIndex == maxElements)
1444 InitializedEntity ElementEntity =
1445 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
1447 // Check this element.
1448 CheckSubElementType(ElementEntity, IList, elementType, Index,
1449 StructuredList, StructuredIndex);
1452 // If the array is of incomplete type, keep track of the number of
1453 // elements in the initializer.
1454 if (!maxElementsKnown && elementIndex > maxElements)
1455 maxElements = elementIndex;
1457 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
1458 // If this is an incomplete array type, the actual type needs to
1459 // be calculated here.
1460 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
1461 if (maxElements == Zero) {
1462 // Sizing an array implicitly to zero is not allowed by ISO C,
1463 // but is supported by GNU.
1464 SemaRef.Diag(IList->getLocStart(),
1465 diag::ext_typecheck_zero_array_size);
1468 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
1469 ArrayType::Normal, 0);
1471 if (!hadError && VerifyOnly) {
1472 // Check if there are any members of the array that get value-initialized.
1473 // If so, check if doing that is possible.
1474 // FIXME: This needs to detect holes left by designated initializers too.
1475 if (maxElementsKnown && elementIndex < maxElements)
1476 CheckEmptyInitializable(InitializedEntity::InitializeElement(
1477 SemaRef.Context, 0, Entity),
1478 IList->getLocEnd());
1482 bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1485 bool TopLevelObject) {
1486 // Handle GNU flexible array initializers.
1487 unsigned FlexArrayDiag;
1488 if (isa<InitListExpr>(InitExpr) &&
1489 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1490 // Empty flexible array init always allowed as an extension
1491 FlexArrayDiag = diag::ext_flexible_array_init;
1492 } else if (SemaRef.getLangOpts().CPlusPlus) {
1493 // Disallow flexible array init in C++; it is not required for gcc
1494 // compatibility, and it needs work to IRGen correctly in general.
1495 FlexArrayDiag = diag::err_flexible_array_init;
1496 } else if (!TopLevelObject) {
1497 // Disallow flexible array init on non-top-level object
1498 FlexArrayDiag = diag::err_flexible_array_init;
1499 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1500 // Disallow flexible array init on anything which is not a variable.
1501 FlexArrayDiag = diag::err_flexible_array_init;
1502 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1503 // Disallow flexible array init on local variables.
1504 FlexArrayDiag = diag::err_flexible_array_init;
1506 // Allow other cases.
1507 FlexArrayDiag = diag::ext_flexible_array_init;
1511 SemaRef.Diag(InitExpr->getLocStart(),
1513 << InitExpr->getLocStart();
1514 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1518 return FlexArrayDiag != diag::ext_flexible_array_init;
1521 void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
1522 InitListExpr *IList,
1524 RecordDecl::field_iterator Field,
1525 bool SubobjectIsDesignatorContext,
1527 InitListExpr *StructuredList,
1528 unsigned &StructuredIndex,
1529 bool TopLevelObject) {
1530 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
1532 // If the record is invalid, some of it's members are invalid. To avoid
1533 // confusion, we forgo checking the intializer for the entire record.
1534 if (structDecl->isInvalidDecl()) {
1535 // Assume it was supposed to consume a single initializer.
1541 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1542 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1544 // If there's a default initializer, use it.
1545 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1548 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1549 Field != FieldEnd; ++Field) {
1550 if (Field->hasInClassInitializer()) {
1551 StructuredList->setInitializedFieldInUnion(*Field);
1552 // FIXME: Actually build a CXXDefaultInitExpr?
1558 // Value-initialize the first named member of the union.
1559 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1560 Field != FieldEnd; ++Field) {
1561 if (Field->getDeclName()) {
1563 CheckEmptyInitializable(
1564 InitializedEntity::InitializeMember(*Field, &Entity),
1565 IList->getLocEnd());
1567 StructuredList->setInitializedFieldInUnion(*Field);
1574 // If structDecl is a forward declaration, this loop won't do
1575 // anything except look at designated initializers; That's okay,
1576 // because an error should get printed out elsewhere. It might be
1577 // worthwhile to skip over the rest of the initializer, though.
1578 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1579 RecordDecl::field_iterator FieldEnd = RD->field_end();
1580 bool InitializedSomething = false;
1581 bool CheckForMissingFields = true;
1582 while (Index < IList->getNumInits()) {
1583 Expr *Init = IList->getInit(Index);
1585 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1586 // If we're not the subobject that matches up with the '{' for
1587 // the designator, we shouldn't be handling the
1588 // designator. Return immediately.
1589 if (!SubobjectIsDesignatorContext)
1592 // Handle this designated initializer. Field will be updated to
1593 // the next field that we'll be initializing.
1594 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1595 DeclType, &Field, nullptr, Index,
1596 StructuredList, StructuredIndex,
1597 true, TopLevelObject))
1600 InitializedSomething = true;
1602 // Disable check for missing fields when designators are used.
1603 // This matches gcc behaviour.
1604 CheckForMissingFields = false;
1608 if (Field == FieldEnd) {
1609 // We've run out of fields. We're done.
1613 // We've already initialized a member of a union. We're done.
1614 if (InitializedSomething && DeclType->isUnionType())
1617 // If we've hit the flexible array member at the end, we're done.
1618 if (Field->getType()->isIncompleteArrayType())
1621 if (Field->isUnnamedBitfield()) {
1622 // Don't initialize unnamed bitfields, e.g. "int : 20;"
1627 // Make sure we can use this declaration.
1630 InvalidUse = !SemaRef.CanUseDecl(*Field);
1632 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1633 IList->getInit(Index)->getLocStart());
1641 InitializedEntity MemberEntity =
1642 InitializedEntity::InitializeMember(*Field, &Entity);
1643 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1644 StructuredList, StructuredIndex);
1645 InitializedSomething = true;
1647 if (DeclType->isUnionType() && !VerifyOnly) {
1648 // Initialize the first field within the union.
1649 StructuredList->setInitializedFieldInUnion(*Field);
1655 // Emit warnings for missing struct field initializers.
1656 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1657 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1658 !DeclType->isUnionType()) {
1659 // It is possible we have one or more unnamed bitfields remaining.
1660 // Find first (if any) named field and emit warning.
1661 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1663 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
1664 SemaRef.Diag(IList->getSourceRange().getEnd(),
1665 diag::warn_missing_field_initializers) << *it;
1671 // Check that any remaining fields can be value-initialized.
1672 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1673 !Field->getType()->isIncompleteArrayType()) {
1674 // FIXME: Should check for holes left by designated initializers too.
1675 for (; Field != FieldEnd && !hadError; ++Field) {
1676 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
1677 CheckEmptyInitializable(
1678 InitializedEntity::InitializeMember(*Field, &Entity),
1679 IList->getLocEnd());
1683 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
1684 Index >= IList->getNumInits())
1687 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1694 InitializedEntity MemberEntity =
1695 InitializedEntity::InitializeMember(*Field, &Entity);
1697 if (isa<InitListExpr>(IList->getInit(Index)))
1698 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1699 StructuredList, StructuredIndex);
1701 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
1702 StructuredList, StructuredIndex);
1705 /// \brief Expand a field designator that refers to a member of an
1706 /// anonymous struct or union into a series of field designators that
1707 /// refers to the field within the appropriate subobject.
1709 static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
1710 DesignatedInitExpr *DIE,
1712 IndirectFieldDecl *IndirectField) {
1713 typedef DesignatedInitExpr::Designator Designator;
1715 // Build the replacement designators.
1716 SmallVector<Designator, 4> Replacements;
1717 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1718 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1720 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
1721 DIE->getDesignator(DesigIdx)->getDotLoc(),
1722 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1724 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
1725 SourceLocation(), SourceLocation()));
1726 assert(isa<FieldDecl>(*PI));
1727 Replacements.back().setField(cast<FieldDecl>(*PI));
1730 // Expand the current designator into the set of replacement
1731 // designators, so we have a full subobject path down to where the
1732 // member of the anonymous struct/union is actually stored.
1733 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
1734 &Replacements[0] + Replacements.size());
1737 /// \brief Given an implicit anonymous field, search the IndirectField that
1738 /// corresponds to FieldName.
1739 static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1740 IdentifierInfo *FieldName) {
1744 assert(AnonField->isAnonymousStructOrUnion());
1745 Decl *NextDecl = AnonField->getNextDeclInContext();
1746 while (IndirectFieldDecl *IF =
1747 dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
1748 if (FieldName == IF->getAnonField()->getIdentifier())
1750 NextDecl = NextDecl->getNextDeclInContext();
1755 static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1756 DesignatedInitExpr *DIE) {
1757 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1758 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1759 for (unsigned I = 0; I < NumIndexExprs; ++I)
1760 IndexExprs[I] = DIE->getSubExpr(I + 1);
1761 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
1762 DIE->size(), IndexExprs,
1763 DIE->getEqualOrColonLoc(),
1764 DIE->usesGNUSyntax(), DIE->getInit());
1769 // Callback to only accept typo corrections that are for field members of
1770 // the given struct or union.
1771 class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1773 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1776 bool ValidateCandidate(const TypoCorrection &candidate) override {
1777 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1778 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1787 /// @brief Check the well-formedness of a C99 designated initializer.
1789 /// Determines whether the designated initializer @p DIE, which
1790 /// resides at the given @p Index within the initializer list @p
1791 /// IList, is well-formed for a current object of type @p DeclType
1792 /// (C99 6.7.8). The actual subobject that this designator refers to
1793 /// within the current subobject is returned in either
1794 /// @p NextField or @p NextElementIndex (whichever is appropriate).
1796 /// @param IList The initializer list in which this designated
1797 /// initializer occurs.
1799 /// @param DIE The designated initializer expression.
1801 /// @param DesigIdx The index of the current designator.
1803 /// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
1804 /// into which the designation in @p DIE should refer.
1806 /// @param NextField If non-NULL and the first designator in @p DIE is
1807 /// a field, this will be set to the field declaration corresponding
1808 /// to the field named by the designator.
1810 /// @param NextElementIndex If non-NULL and the first designator in @p
1811 /// DIE is an array designator or GNU array-range designator, this
1812 /// will be set to the last index initialized by this designator.
1814 /// @param Index Index into @p IList where the designated initializer
1817 /// @param StructuredList The initializer list expression that
1818 /// describes all of the subobject initializers in the order they'll
1819 /// actually be initialized.
1821 /// @returns true if there was an error, false otherwise.
1823 InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
1824 InitListExpr *IList,
1825 DesignatedInitExpr *DIE,
1827 QualType &CurrentObjectType,
1828 RecordDecl::field_iterator *NextField,
1829 llvm::APSInt *NextElementIndex,
1831 InitListExpr *StructuredList,
1832 unsigned &StructuredIndex,
1833 bool FinishSubobjectInit,
1834 bool TopLevelObject) {
1835 if (DesigIdx == DIE->size()) {
1836 // Check the actual initialization for the designated object type.
1837 bool prevHadError = hadError;
1839 // Temporarily remove the designator expression from the
1840 // initializer list that the child calls see, so that we don't try
1841 // to re-process the designator.
1842 unsigned OldIndex = Index;
1843 IList->setInit(OldIndex, DIE->getInit());
1845 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
1846 StructuredList, StructuredIndex);
1848 // Restore the designated initializer expression in the syntactic
1849 // form of the initializer list.
1850 if (IList->getInit(OldIndex) != DIE->getInit())
1851 DIE->setInit(IList->getInit(OldIndex));
1852 IList->setInit(OldIndex, DIE);
1854 return hadError && !prevHadError;
1857 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
1858 bool IsFirstDesignator = (DesigIdx == 0);
1860 assert((IsFirstDesignator || StructuredList) &&
1861 "Need a non-designated initializer list to start from");
1863 // Determine the structural initializer list that corresponds to the
1864 // current subobject.
1865 StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
1866 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1867 StructuredList, StructuredIndex,
1868 SourceRange(D->getLocStart(),
1870 assert(StructuredList && "Expected a structured initializer list");
1873 if (D->isFieldDesignator()) {
1876 // If a designator has the form
1880 // then the current object (defined below) shall have
1881 // structure or union type and the identifier shall be the
1882 // name of a member of that type.
1883 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
1885 SourceLocation Loc = D->getDotLoc();
1886 if (Loc.isInvalid())
1887 Loc = D->getFieldLoc();
1889 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1890 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
1895 // Note: we perform a linear search of the fields here, despite
1896 // the fact that we have a faster lookup method, because we always
1897 // need to compute the field's index.
1898 FieldDecl *KnownField = D->getField();
1899 IdentifierInfo *FieldName = D->getFieldName();
1900 unsigned FieldIndex = 0;
1901 RecordDecl::field_iterator
1902 Field = RT->getDecl()->field_begin(),
1903 FieldEnd = RT->getDecl()->field_end();
1904 for (; Field != FieldEnd; ++Field) {
1905 if (Field->isUnnamedBitfield())
1908 // If we find a field representing an anonymous field, look in the
1909 // IndirectFieldDecl that follow for the designated initializer.
1910 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1911 if (IndirectFieldDecl *IF =
1912 FindIndirectFieldDesignator(*Field, FieldName)) {
1913 // In verify mode, don't modify the original.
1915 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
1916 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1917 D = DIE->getDesignator(DesigIdx);
1921 if (KnownField && KnownField == *Field)
1923 if (FieldName && FieldName == Field->getIdentifier())
1929 if (Field == FieldEnd) {
1932 return true; // No typo correction when just trying this out.
1935 // There was no normal field in the struct with the designated
1936 // name. Perform another lookup for this name, which may find
1937 // something that we can't designate (e.g., a member function),
1938 // may find nothing, or may find a member of an anonymous
1940 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
1941 FieldDecl *ReplacementField = nullptr;
1942 if (Lookup.empty()) {
1943 // Name lookup didn't find anything. Determine whether this
1944 // was a typo for another field name.
1945 FieldInitializerValidatorCCC Validator(RT->getDecl());
1946 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
1947 DeclarationNameInfo(FieldName, D->getFieldLoc()),
1948 Sema::LookupMemberName, /*Scope=*/ nullptr, /*SS=*/ nullptr,
1949 Validator, Sema::CTK_ErrorRecovery, RT->getDecl())) {
1950 SemaRef.diagnoseTypo(
1952 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
1953 << FieldName << CurrentObjectType);
1954 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
1957 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1958 << FieldName << CurrentObjectType;
1964 if (!ReplacementField) {
1965 // Name lookup found something, but it wasn't a field.
1966 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
1968 SemaRef.Diag(Lookup.front()->getLocation(),
1969 diag::note_field_designator_found);
1975 // The replacement field comes from typo correction; find it
1976 // in the list of fields.
1978 Field = RT->getDecl()->field_begin();
1979 for (; Field != FieldEnd; ++Field) {
1980 if (Field->isUnnamedBitfield())
1983 if (ReplacementField == *Field ||
1984 Field->getIdentifier() == ReplacementField->getIdentifier())
1992 // All of the fields of a union are located at the same place in
1993 // the initializer list.
1994 if (RT->getDecl()->isUnion()) {
1997 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
1998 if (CurrentField && CurrentField != *Field) {
1999 assert(StructuredList->getNumInits() == 1
2000 && "A union should never have more than one initializer!");
2002 // we're about to throw away an initializer, emit warning
2003 SemaRef.Diag(D->getFieldLoc(),
2004 diag::warn_initializer_overrides)
2005 << D->getSourceRange();
2006 Expr *ExistingInit = StructuredList->getInit(0);
2007 SemaRef.Diag(ExistingInit->getLocStart(),
2008 diag::note_previous_initializer)
2009 << /*FIXME:has side effects=*/0
2010 << ExistingInit->getSourceRange();
2012 // remove existing initializer
2013 StructuredList->resizeInits(SemaRef.Context, 0);
2014 StructuredList->setInitializedFieldInUnion(nullptr);
2017 StructuredList->setInitializedFieldInUnion(*Field);
2021 // Make sure we can use this declaration.
2024 InvalidUse = !SemaRef.CanUseDecl(*Field);
2026 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
2033 // Update the designator with the field declaration.
2034 D->setField(*Field);
2036 // Make sure that our non-designated initializer list has space
2037 // for a subobject corresponding to this field.
2038 if (FieldIndex >= StructuredList->getNumInits())
2039 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2042 // This designator names a flexible array member.
2043 if (Field->getType()->isIncompleteArrayType()) {
2044 bool Invalid = false;
2045 if ((DesigIdx + 1) != DIE->size()) {
2046 // We can't designate an object within the flexible array
2047 // member (because GCC doesn't allow it).
2049 DesignatedInitExpr::Designator *NextD
2050 = DIE->getDesignator(DesigIdx + 1);
2051 SemaRef.Diag(NextD->getLocStart(),
2052 diag::err_designator_into_flexible_array_member)
2053 << SourceRange(NextD->getLocStart(),
2055 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2061 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2062 !isa<StringLiteral>(DIE->getInit())) {
2063 // The initializer is not an initializer list.
2065 SemaRef.Diag(DIE->getInit()->getLocStart(),
2066 diag::err_flexible_array_init_needs_braces)
2067 << DIE->getInit()->getSourceRange();
2068 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2074 // Check GNU flexible array initializer.
2075 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
2084 // Initialize the array.
2085 bool prevHadError = hadError;
2086 unsigned newStructuredIndex = FieldIndex;
2087 unsigned OldIndex = Index;
2088 IList->setInit(Index, DIE->getInit());
2090 InitializedEntity MemberEntity =
2091 InitializedEntity::InitializeMember(*Field, &Entity);
2092 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2093 StructuredList, newStructuredIndex);
2095 IList->setInit(OldIndex, DIE);
2096 if (hadError && !prevHadError) {
2101 StructuredIndex = FieldIndex;
2105 // Recurse to check later designated subobjects.
2106 QualType FieldType = Field->getType();
2107 unsigned newStructuredIndex = FieldIndex;
2109 InitializedEntity MemberEntity =
2110 InitializedEntity::InitializeMember(*Field, &Entity);
2111 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
2112 FieldType, nullptr, nullptr, Index,
2113 StructuredList, newStructuredIndex,
2118 // Find the position of the next field to be initialized in this
2123 // If this the first designator, our caller will continue checking
2124 // the rest of this struct/class/union subobject.
2125 if (IsFirstDesignator) {
2128 StructuredIndex = FieldIndex;
2132 if (!FinishSubobjectInit)
2135 // We've already initialized something in the union; we're done.
2136 if (RT->getDecl()->isUnion())
2139 // Check the remaining fields within this class/struct/union subobject.
2140 bool prevHadError = hadError;
2142 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
2143 StructuredList, FieldIndex);
2144 return hadError && !prevHadError;
2149 // If a designator has the form
2151 // [ constant-expression ]
2153 // then the current object (defined below) shall have array
2154 // type and the expression shall be an integer constant
2155 // expression. If the array is of unknown size, any
2156 // nonnegative value is valid.
2158 // Additionally, cope with the GNU extension that permits
2159 // designators of the form
2161 // [ constant-expression ... constant-expression ]
2162 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
2165 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2166 << CurrentObjectType;
2171 Expr *IndexExpr = nullptr;
2172 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2173 if (D->isArrayDesignator()) {
2174 IndexExpr = DIE->getArrayIndex(*D);
2175 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
2176 DesignatedEndIndex = DesignatedStartIndex;
2178 assert(D->isArrayRangeDesignator() && "Need array-range designator");
2180 DesignatedStartIndex =
2181 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
2182 DesignatedEndIndex =
2183 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
2184 IndexExpr = DIE->getArrayRangeEnd(*D);
2186 // Codegen can't handle evaluating array range designators that have side
2187 // effects, because we replicate the AST value for each initialized element.
2188 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2189 // elements with something that has a side effect, so codegen can emit an
2190 // "error unsupported" error instead of miscompiling the app.
2191 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
2192 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
2193 FullyStructuredList->sawArrayRangeDesignator();
2196 if (isa<ConstantArrayType>(AT)) {
2197 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
2198 DesignatedStartIndex
2199 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
2200 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
2202 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
2203 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2204 if (DesignatedEndIndex >= MaxElements) {
2206 SemaRef.Diag(IndexExpr->getLocStart(),
2207 diag::err_array_designator_too_large)
2208 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2209 << IndexExpr->getSourceRange();
2214 // Make sure the bit-widths and signedness match.
2215 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
2217 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
2218 else if (DesignatedStartIndex.getBitWidth() <
2219 DesignatedEndIndex.getBitWidth())
2220 DesignatedStartIndex
2221 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
2222 DesignatedStartIndex.setIsUnsigned(true);
2223 DesignatedEndIndex.setIsUnsigned(true);
2226 if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2227 // We're modifying a string literal init; we have to decompose the string
2228 // so we can modify the individual characters.
2229 ASTContext &Context = SemaRef.Context;
2230 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2232 // Compute the character type
2233 QualType CharTy = AT->getElementType();
2235 // Compute the type of the integer literals.
2236 QualType PromotedCharTy = CharTy;
2237 if (CharTy->isPromotableIntegerType())
2238 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2239 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2241 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2242 // Get the length of the string.
2243 uint64_t StrLen = SL->getLength();
2244 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2245 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2246 StructuredList->resizeInits(Context, StrLen);
2248 // Build a literal for each character in the string, and put them into
2250 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2251 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2252 Expr *Init = new (Context) IntegerLiteral(
2253 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2254 if (CharTy != PromotedCharTy)
2255 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2256 Init, nullptr, VK_RValue);
2257 StructuredList->updateInit(Context, i, Init);
2260 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2262 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2264 // Get the length of the string.
2265 uint64_t StrLen = Str.size();
2266 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2267 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2268 StructuredList->resizeInits(Context, StrLen);
2270 // Build a literal for each character in the string, and put them into
2272 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2273 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2274 Expr *Init = new (Context) IntegerLiteral(
2275 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2276 if (CharTy != PromotedCharTy)
2277 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2278 Init, nullptr, VK_RValue);
2279 StructuredList->updateInit(Context, i, Init);
2284 // Make sure that our non-designated initializer list has space
2285 // for a subobject corresponding to this array element.
2287 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
2288 StructuredList->resizeInits(SemaRef.Context,
2289 DesignatedEndIndex.getZExtValue() + 1);
2291 // Repeatedly perform subobject initializations in the range
2292 // [DesignatedStartIndex, DesignatedEndIndex].
2294 // Move to the next designator
2295 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2296 unsigned OldIndex = Index;
2298 InitializedEntity ElementEntity =
2299 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
2301 while (DesignatedStartIndex <= DesignatedEndIndex) {
2302 // Recurse to check later designated subobjects.
2303 QualType ElementType = AT->getElementType();
2306 ElementEntity.setElementIndex(ElementIndex);
2307 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2308 ElementType, nullptr, nullptr, Index,
2309 StructuredList, ElementIndex,
2310 (DesignatedStartIndex == DesignatedEndIndex),
2314 // Move to the next index in the array that we'll be initializing.
2315 ++DesignatedStartIndex;
2316 ElementIndex = DesignatedStartIndex.getZExtValue();
2319 // If this the first designator, our caller will continue checking
2320 // the rest of this array subobject.
2321 if (IsFirstDesignator) {
2322 if (NextElementIndex)
2323 *NextElementIndex = DesignatedStartIndex;
2324 StructuredIndex = ElementIndex;
2328 if (!FinishSubobjectInit)
2331 // Check the remaining elements within this array subobject.
2332 bool prevHadError = hadError;
2333 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
2334 /*SubobjectIsDesignatorContext=*/false, Index,
2335 StructuredList, ElementIndex);
2336 return hadError && !prevHadError;
2339 // Get the structured initializer list for a subobject of type
2340 // @p CurrentObjectType.
2342 InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2343 QualType CurrentObjectType,
2344 InitListExpr *StructuredList,
2345 unsigned StructuredIndex,
2346 SourceRange InitRange) {
2348 return nullptr; // No structured list in verification-only mode.
2349 Expr *ExistingInit = nullptr;
2350 if (!StructuredList)
2351 ExistingInit = SyntacticToSemantic.lookup(IList);
2352 else if (StructuredIndex < StructuredList->getNumInits())
2353 ExistingInit = StructuredList->getInit(StructuredIndex);
2355 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2359 // We are creating an initializer list that initializes the
2360 // subobjects of the current object, but there was already an
2361 // initialization that completely initialized the current
2362 // subobject, e.g., by a compound literal:
2364 // struct X { int a, b; };
2365 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2367 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2368 // designated initializer re-initializes the whole
2369 // subobject [0], overwriting previous initializers.
2370 SemaRef.Diag(InitRange.getBegin(),
2371 diag::warn_subobject_initializer_overrides)
2373 SemaRef.Diag(ExistingInit->getLocStart(),
2374 diag::note_previous_initializer)
2375 << /*FIXME:has side effects=*/0
2376 << ExistingInit->getSourceRange();
2379 InitListExpr *Result
2380 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2381 InitRange.getBegin(), None,
2382 InitRange.getEnd());
2384 QualType ResultType = CurrentObjectType;
2385 if (!ResultType->isArrayType())
2386 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2387 Result->setType(ResultType);
2389 // Pre-allocate storage for the structured initializer list.
2390 unsigned NumElements = 0;
2391 unsigned NumInits = 0;
2392 bool GotNumInits = false;
2393 if (!StructuredList) {
2394 NumInits = IList->getNumInits();
2396 } else if (Index < IList->getNumInits()) {
2397 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
2398 NumInits = SubList->getNumInits();
2403 if (const ArrayType *AType
2404 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2405 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2406 NumElements = CAType->getSize().getZExtValue();
2407 // Simple heuristic so that we don't allocate a very large
2408 // initializer with many empty entries at the end.
2409 if (GotNumInits && NumElements > NumInits)
2412 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
2413 NumElements = VType->getNumElements();
2414 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
2415 RecordDecl *RDecl = RType->getDecl();
2416 if (RDecl->isUnion())
2419 NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
2422 Result->reserveInits(SemaRef.Context, NumElements);
2424 // Link this new initializer list into the structured initializer
2427 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
2429 Result->setSyntacticForm(IList);
2430 SyntacticToSemantic[IList] = Result;
2436 /// Update the initializer at index @p StructuredIndex within the
2437 /// structured initializer list to the value @p expr.
2438 void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2439 unsigned &StructuredIndex,
2441 // No structured initializer list to update
2442 if (!StructuredList)
2445 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2446 StructuredIndex, expr)) {
2447 // This initializer overwrites a previous initializer. Warn.
2448 SemaRef.Diag(expr->getLocStart(),
2449 diag::warn_initializer_overrides)
2450 << expr->getSourceRange();
2451 SemaRef.Diag(PrevInit->getLocStart(),
2452 diag::note_previous_initializer)
2453 << /*FIXME:has side effects=*/0
2454 << PrevInit->getSourceRange();
2460 /// Check that the given Index expression is a valid array designator
2461 /// value. This is essentially just a wrapper around
2462 /// VerifyIntegerConstantExpression that also checks for negative values
2463 /// and produces a reasonable diagnostic if there is a
2464 /// failure. Returns the index expression, possibly with an implicit cast
2465 /// added, on success. If everything went okay, Value will receive the
2466 /// value of the constant expression.
2468 CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
2469 SourceLocation Loc = Index->getLocStart();
2471 // Make sure this is an integer constant expression.
2472 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2473 if (Result.isInvalid())
2476 if (Value.isSigned() && Value.isNegative())
2477 return S.Diag(Loc, diag::err_array_designator_negative)
2478 << Value.toString(10) << Index->getSourceRange();
2480 Value.setIsUnsigned(true);
2484 ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
2488 typedef DesignatedInitExpr::Designator ASTDesignator;
2490 bool Invalid = false;
2491 SmallVector<ASTDesignator, 32> Designators;
2492 SmallVector<Expr *, 32> InitExpressions;
2494 // Build designators and check array designator expressions.
2495 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2496 const Designator &D = Desig.getDesignator(Idx);
2497 switch (D.getKind()) {
2498 case Designator::FieldDesignator:
2499 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
2503 case Designator::ArrayDesignator: {
2504 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2505 llvm::APSInt IndexValue;
2506 if (!Index->isTypeDependent() && !Index->isValueDependent())
2507 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
2511 Designators.push_back(ASTDesignator(InitExpressions.size(),
2513 D.getRBracketLoc()));
2514 InitExpressions.push_back(Index);
2519 case Designator::ArrayRangeDesignator: {
2520 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2521 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2522 llvm::APSInt StartValue;
2523 llvm::APSInt EndValue;
2524 bool StartDependent = StartIndex->isTypeDependent() ||
2525 StartIndex->isValueDependent();
2526 bool EndDependent = EndIndex->isTypeDependent() ||
2527 EndIndex->isValueDependent();
2528 if (!StartDependent)
2530 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
2532 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
2534 if (!StartIndex || !EndIndex)
2537 // Make sure we're comparing values with the same bit width.
2538 if (StartDependent || EndDependent) {
2539 // Nothing to compute.
2540 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
2541 EndValue = EndValue.extend(StartValue.getBitWidth());
2542 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
2543 StartValue = StartValue.extend(EndValue.getBitWidth());
2545 if (!StartDependent && !EndDependent && EndValue < StartValue) {
2546 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
2547 << StartValue.toString(10) << EndValue.toString(10)
2548 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2551 Designators.push_back(ASTDesignator(InitExpressions.size(),
2554 D.getRBracketLoc()));
2555 InitExpressions.push_back(StartIndex);
2556 InitExpressions.push_back(EndIndex);
2564 if (Invalid || Init.isInvalid())
2567 // Clear out the expressions within the designation.
2568 Desig.ClearExprs(*this);
2570 DesignatedInitExpr *DIE
2571 = DesignatedInitExpr::Create(Context,
2572 Designators.data(), Designators.size(),
2573 InitExpressions, Loc, GNUSyntax,
2574 Init.getAs<Expr>());
2576 if (!getLangOpts().C99)
2577 Diag(DIE->getLocStart(), diag::ext_designated_init)
2578 << DIE->getSourceRange();
2583 //===----------------------------------------------------------------------===//
2584 // Initialization entity
2585 //===----------------------------------------------------------------------===//
2587 InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
2588 const InitializedEntity &Parent)
2589 : Parent(&Parent), Index(Index)
2591 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2592 Kind = EK_ArrayElement;
2593 Type = AT->getElementType();
2594 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
2595 Kind = EK_VectorElement;
2596 Type = VT->getElementType();
2598 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2599 assert(CT && "Unexpected type");
2600 Kind = EK_ComplexElement;
2601 Type = CT->getElementType();
2606 InitializedEntity::InitializeBase(ASTContext &Context,
2607 const CXXBaseSpecifier *Base,
2608 bool IsInheritedVirtualBase) {
2609 InitializedEntity Result;
2610 Result.Kind = EK_Base;
2611 Result.Parent = nullptr;
2612 Result.Base = reinterpret_cast<uintptr_t>(Base);
2613 if (IsInheritedVirtualBase)
2614 Result.Base |= 0x01;
2616 Result.Type = Base->getType();
2620 DeclarationName InitializedEntity::getName() const {
2621 switch (getKind()) {
2623 case EK_Parameter_CF_Audited: {
2624 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2625 return (D ? D->getDeclName() : DeclarationName());
2630 return VariableOrMember->getDeclName();
2632 case EK_LambdaCapture:
2633 return DeclarationName(Capture.VarID);
2641 case EK_ArrayElement:
2642 case EK_VectorElement:
2643 case EK_ComplexElement:
2644 case EK_BlockElement:
2645 case EK_CompoundLiteralInit:
2646 case EK_RelatedResult:
2647 return DeclarationName();
2650 llvm_unreachable("Invalid EntityKind!");
2653 DeclaratorDecl *InitializedEntity::getDecl() const {
2654 switch (getKind()) {
2657 return VariableOrMember;
2660 case EK_Parameter_CF_Audited:
2661 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2669 case EK_ArrayElement:
2670 case EK_VectorElement:
2671 case EK_ComplexElement:
2672 case EK_BlockElement:
2673 case EK_LambdaCapture:
2674 case EK_CompoundLiteralInit:
2675 case EK_RelatedResult:
2679 llvm_unreachable("Invalid EntityKind!");
2682 bool InitializedEntity::allowsNRVO() const {
2683 switch (getKind()) {
2686 return LocAndNRVO.NRVO;
2690 case EK_Parameter_CF_Audited:
2694 case EK_CompoundLiteralInit:
2697 case EK_ArrayElement:
2698 case EK_VectorElement:
2699 case EK_ComplexElement:
2700 case EK_BlockElement:
2701 case EK_LambdaCapture:
2702 case EK_RelatedResult:
2709 unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
2710 assert(getParent() != this);
2711 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
2712 for (unsigned I = 0; I != Depth; ++I)
2715 switch (getKind()) {
2716 case EK_Variable: OS << "Variable"; break;
2717 case EK_Parameter: OS << "Parameter"; break;
2718 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
2720 case EK_Result: OS << "Result"; break;
2721 case EK_Exception: OS << "Exception"; break;
2722 case EK_Member: OS << "Member"; break;
2723 case EK_New: OS << "New"; break;
2724 case EK_Temporary: OS << "Temporary"; break;
2725 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
2726 case EK_RelatedResult: OS << "RelatedResult"; break;
2727 case EK_Base: OS << "Base"; break;
2728 case EK_Delegating: OS << "Delegating"; break;
2729 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
2730 case EK_VectorElement: OS << "VectorElement " << Index; break;
2731 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
2732 case EK_BlockElement: OS << "Block"; break;
2733 case EK_LambdaCapture:
2734 OS << "LambdaCapture ";
2735 OS << DeclarationName(Capture.VarID);
2739 if (Decl *D = getDecl()) {
2741 cast<NamedDecl>(D)->printQualifiedName(OS);
2744 OS << " '" << getType().getAsString() << "'\n";
2749 void InitializedEntity::dump() const {
2750 dumpImpl(llvm::errs());
2753 //===----------------------------------------------------------------------===//
2754 // Initialization sequence
2755 //===----------------------------------------------------------------------===//
2757 void InitializationSequence::Step::Destroy() {
2759 case SK_ResolveAddressOfOverloadedFunction:
2760 case SK_CastDerivedToBaseRValue:
2761 case SK_CastDerivedToBaseXValue:
2762 case SK_CastDerivedToBaseLValue:
2763 case SK_BindReference:
2764 case SK_BindReferenceToTemporary:
2765 case SK_ExtraneousCopyToTemporary:
2766 case SK_UserConversion:
2767 case SK_QualificationConversionRValue:
2768 case SK_QualificationConversionXValue:
2769 case SK_QualificationConversionLValue:
2770 case SK_AtomicConversion:
2771 case SK_LValueToRValue:
2772 case SK_ListInitialization:
2773 case SK_UnwrapInitList:
2774 case SK_RewrapInitList:
2775 case SK_ConstructorInitialization:
2776 case SK_ConstructorInitializationFromList:
2777 case SK_ZeroInitialization:
2778 case SK_CAssignment:
2780 case SK_ObjCObjectConversion:
2782 case SK_ParenthesizedArrayInit:
2783 case SK_PassByIndirectCopyRestore:
2784 case SK_PassByIndirectRestore:
2785 case SK_ProduceObjCObject:
2786 case SK_StdInitializerList:
2787 case SK_StdInitializerListConstructorCall:
2788 case SK_OCLSamplerInit:
2789 case SK_OCLZeroEvent:
2792 case SK_ConversionSequence:
2793 case SK_ConversionSequenceNoNarrowing:
2798 bool InitializationSequence::isDirectReferenceBinding() const {
2799 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
2802 bool InitializationSequence::isAmbiguous() const {
2806 switch (getFailureKind()) {
2807 case FK_TooManyInitsForReference:
2808 case FK_ArrayNeedsInitList:
2809 case FK_ArrayNeedsInitListOrStringLiteral:
2810 case FK_ArrayNeedsInitListOrWideStringLiteral:
2811 case FK_NarrowStringIntoWideCharArray:
2812 case FK_WideStringIntoCharArray:
2813 case FK_IncompatWideStringIntoWideChar:
2814 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2815 case FK_NonConstLValueReferenceBindingToTemporary:
2816 case FK_NonConstLValueReferenceBindingToUnrelated:
2817 case FK_RValueReferenceBindingToLValue:
2818 case FK_ReferenceInitDropsQualifiers:
2819 case FK_ReferenceInitFailed:
2820 case FK_ConversionFailed:
2821 case FK_ConversionFromPropertyFailed:
2822 case FK_TooManyInitsForScalar:
2823 case FK_ReferenceBindingToInitList:
2824 case FK_InitListBadDestinationType:
2825 case FK_DefaultInitOfConst:
2827 case FK_ArrayTypeMismatch:
2828 case FK_NonConstantArrayInit:
2829 case FK_ListInitializationFailed:
2830 case FK_VariableLengthArrayHasInitializer:
2831 case FK_PlaceholderType:
2832 case FK_ExplicitConstructor:
2835 case FK_ReferenceInitOverloadFailed:
2836 case FK_UserConversionOverloadFailed:
2837 case FK_ConstructorOverloadFailed:
2838 case FK_ListConstructorOverloadFailed:
2839 return FailedOverloadResult == OR_Ambiguous;
2842 llvm_unreachable("Invalid EntityKind!");
2845 bool InitializationSequence::isConstructorInitialization() const {
2846 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2850 InitializationSequence
2851 ::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2852 DeclAccessPair Found,
2853 bool HadMultipleCandidates) {
2855 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2856 S.Type = Function->getType();
2857 S.Function.HadMultipleCandidates = HadMultipleCandidates;
2858 S.Function.Function = Function;
2859 S.Function.FoundDecl = Found;
2863 void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
2867 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2868 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2869 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
2875 void InitializationSequence::AddReferenceBindingStep(QualType T,
2876 bool BindingTemporary) {
2878 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2883 void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2885 S.Kind = SK_ExtraneousCopyToTemporary;
2891 InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2892 DeclAccessPair FoundDecl,
2894 bool HadMultipleCandidates) {
2896 S.Kind = SK_UserConversion;
2898 S.Function.HadMultipleCandidates = HadMultipleCandidates;
2899 S.Function.Function = Function;
2900 S.Function.FoundDecl = FoundDecl;
2904 void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2907 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
2910 S.Kind = SK_QualificationConversionRValue;
2913 S.Kind = SK_QualificationConversionXValue;
2916 S.Kind = SK_QualificationConversionLValue;
2923 void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
2925 S.Kind = SK_AtomicConversion;
2930 void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
2931 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
2934 S.Kind = SK_LValueToRValue;
2939 void InitializationSequence::AddConversionSequenceStep(
2940 const ImplicitConversionSequence &ICS, QualType T,
2941 bool TopLevelOfInitList) {
2943 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
2944 : SK_ConversionSequence;
2946 S.ICS = new ImplicitConversionSequence(ICS);
2950 void InitializationSequence::AddListInitializationStep(QualType T) {
2952 S.Kind = SK_ListInitialization;
2958 InitializationSequence
2959 ::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2960 AccessSpecifier Access,
2962 bool HadMultipleCandidates,
2963 bool FromInitList, bool AsInitList) {
2965 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
2966 : SK_ConstructorInitializationFromList
2967 : SK_ConstructorInitialization;
2969 S.Function.HadMultipleCandidates = HadMultipleCandidates;
2970 S.Function.Function = Constructor;
2971 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
2975 void InitializationSequence::AddZeroInitializationStep(QualType T) {
2977 S.Kind = SK_ZeroInitialization;
2982 void InitializationSequence::AddCAssignmentStep(QualType T) {
2984 S.Kind = SK_CAssignment;
2989 void InitializationSequence::AddStringInitStep(QualType T) {
2991 S.Kind = SK_StringInit;
2996 void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2998 S.Kind = SK_ObjCObjectConversion;
3003 void InitializationSequence::AddArrayInitStep(QualType T) {
3005 S.Kind = SK_ArrayInit;
3010 void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
3012 S.Kind = SK_ParenthesizedArrayInit;
3017 void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
3020 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3021 : SK_PassByIndirectRestore);
3026 void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3028 S.Kind = SK_ProduceObjCObject;
3033 void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3035 S.Kind = SK_StdInitializerList;
3040 void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3042 S.Kind = SK_OCLSamplerInit;
3047 void InitializationSequence::AddOCLZeroEventStep(QualType T) {
3049 S.Kind = SK_OCLZeroEvent;
3054 void InitializationSequence::RewrapReferenceInitList(QualType T,
3055 InitListExpr *Syntactic) {
3056 assert(Syntactic->getNumInits() == 1 &&
3057 "Can only rewrap trivial init lists.");
3059 S.Kind = SK_UnwrapInitList;
3060 S.Type = Syntactic->getInit(0)->getType();
3061 Steps.insert(Steps.begin(), S);
3063 S.Kind = SK_RewrapInitList;
3065 S.WrappingSyntacticList = Syntactic;
3069 void InitializationSequence::SetOverloadFailure(FailureKind Failure,
3070 OverloadingResult Result) {
3071 setSequenceKind(FailedSequence);
3072 this->Failure = Failure;
3073 this->FailedOverloadResult = Result;
3076 //===----------------------------------------------------------------------===//
3077 // Attempt initialization
3078 //===----------------------------------------------------------------------===//
3080 static void MaybeProduceObjCObject(Sema &S,
3081 InitializationSequence &Sequence,
3082 const InitializedEntity &Entity) {
3083 if (!S.getLangOpts().ObjCAutoRefCount) return;
3085 /// When initializing a parameter, produce the value if it's marked
3086 /// __attribute__((ns_consumed)).
3087 if (Entity.isParameterKind()) {
3088 if (!Entity.isParameterConsumed())
3091 assert(Entity.getType()->isObjCRetainableType() &&
3092 "consuming an object of unretainable type?");
3093 Sequence.AddProduceObjCObjectStep(Entity.getType());
3095 /// When initializing a return value, if the return type is a
3096 /// retainable type, then returns need to immediately retain the
3097 /// object. If an autorelease is required, it will be done at the
3099 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
3100 if (!Entity.getType()->isObjCRetainableType())
3103 Sequence.AddProduceObjCObjectStep(Entity.getType());
3107 static void TryListInitialization(Sema &S,
3108 const InitializedEntity &Entity,
3109 const InitializationKind &Kind,
3110 InitListExpr *InitList,
3111 InitializationSequence &Sequence);
3113 /// \brief When initializing from init list via constructor, handle
3114 /// initialization of an object of type std::initializer_list<T>.
3116 /// \return true if we have handled initialization of an object of type
3117 /// std::initializer_list<T>, false otherwise.
3118 static bool TryInitializerListConstruction(Sema &S,
3121 InitializationSequence &Sequence) {
3123 if (!S.isStdInitializerList(DestType, &E))
3126 if (S.RequireCompleteType(List->getExprLoc(), E, 0)) {
3127 Sequence.setIncompleteTypeFailure(E);
3131 // Try initializing a temporary array from the init list.
3132 QualType ArrayType = S.Context.getConstantArrayType(
3133 E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3134 List->getNumInits()),
3135 clang::ArrayType::Normal, 0);
3136 InitializedEntity HiddenArray =
3137 InitializedEntity::InitializeTemporary(ArrayType);
3138 InitializationKind Kind =
3139 InitializationKind::CreateDirectList(List->getExprLoc());
3140 TryListInitialization(S, HiddenArray, Kind, List, Sequence);
3142 Sequence.AddStdInitializerListConstructionStep(DestType);
3146 static OverloadingResult
3147 ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
3149 OverloadCandidateSet &CandidateSet,
3150 ArrayRef<NamedDecl *> Ctors,
3151 OverloadCandidateSet::iterator &Best,
3152 bool CopyInitializing, bool AllowExplicit,
3153 bool OnlyListConstructors, bool InitListSyntax) {
3154 CandidateSet.clear();
3156 for (ArrayRef<NamedDecl *>::iterator
3157 Con = Ctors.begin(), ConEnd = Ctors.end(); Con != ConEnd; ++Con) {
3158 NamedDecl *D = *Con;
3159 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3160 bool SuppressUserConversions = false;
3162 // Find the constructor (which may be a template).
3163 CXXConstructorDecl *Constructor = nullptr;
3164 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
3165 if (ConstructorTmpl)
3166 Constructor = cast<CXXConstructorDecl>(
3167 ConstructorTmpl->getTemplatedDecl());
3169 Constructor = cast<CXXConstructorDecl>(D);
3171 // C++11 [over.best.ics]p4:
3172 // However, when considering the argument of a constructor or
3173 // user-defined conversion function that is a candidate:
3174 // -- by 13.3.1.3 when invoked for the copying/moving of a temporary
3175 // in the second step of a class copy-initialization,
3176 // -- by 13.3.1.7 when passing the initializer list as a single
3177 // argument or when the initializer list has exactly one elementand
3178 // a conversion to some class X or reference to (possibly
3179 // cv-qualified) X is considered for the first parameter of a
3180 // constructor of X, or
3181 // -- by 13.3.1.4, 13.3.1.5, or 13.3.1.6 in all cases,
3182 // only standard conversion sequences and ellipsis conversion sequences
3184 if ((CopyInitializing || (InitListSyntax && Args.size() == 1)) &&
3185 Constructor->isCopyOrMoveConstructor())
3186 SuppressUserConversions = true;
3189 if (!Constructor->isInvalidDecl() &&
3190 (AllowExplicit || !Constructor->isExplicit()) &&
3191 (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
3192 if (ConstructorTmpl)
3193 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3194 /*ExplicitArgs*/ nullptr, Args,
3195 CandidateSet, SuppressUserConversions);
3197 // C++ [over.match.copy]p1:
3198 // - When initializing a temporary to be bound to the first parameter
3199 // of a constructor that takes a reference to possibly cv-qualified
3200 // T as its first argument, called with a single argument in the
3201 // context of direct-initialization, explicit conversion functions
3202 // are also considered.
3203 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
3205 Constructor->isCopyOrMoveConstructor();
3206 S.AddOverloadCandidate(Constructor, FoundDecl, Args, CandidateSet,
3207 SuppressUserConversions,
3208 /*PartialOverloading=*/false,
3209 /*AllowExplicit=*/AllowExplicitConv);
3214 // Perform overload resolution and return the result.
3215 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3218 /// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3219 /// enumerates the constructors of the initialized entity and performs overload
3220 /// resolution to select the best.
3221 /// If InitListSyntax is true, this is list-initialization of a non-aggregate
3223 static void TryConstructorInitialization(Sema &S,
3224 const InitializedEntity &Entity,
3225 const InitializationKind &Kind,
3226 MultiExprArg Args, QualType DestType,
3227 InitializationSequence &Sequence,
3228 bool InitListSyntax = false) {
3229 assert((!InitListSyntax || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
3230 "InitListSyntax must come with a single initializer list argument.");
3232 // The type we're constructing needs to be complete.
3233 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
3234 Sequence.setIncompleteTypeFailure(DestType);
3238 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3239 assert(DestRecordType && "Constructor initialization requires record type");
3240 CXXRecordDecl *DestRecordDecl
3241 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3243 // Build the candidate set directly in the initialization sequence
3244 // structure, so that it will persist if we fail.
3245 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3247 // Determine whether we are allowed to call explicit constructors or
3248 // explicit conversion operators.
3249 bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
3250 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
3252 // - Otherwise, if T is a class type, constructors are considered. The
3253 // applicable constructors are enumerated, and the best one is chosen
3254 // through overload resolution.
3255 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
3256 // The container holding the constructors can under certain conditions
3257 // be changed while iterating (e.g. because of deserialization).
3258 // To be safe we copy the lookup results to a new container.
3259 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
3261 OverloadingResult Result = OR_No_Viable_Function;
3262 OverloadCandidateSet::iterator Best;
3263 bool AsInitializerList = false;
3265 // C++11 [over.match.list]p1:
3266 // When objects of non-aggregate type T are list-initialized, overload
3267 // resolution selects the constructor in two phases:
3268 // - Initially, the candidate functions are the initializer-list
3269 // constructors of the class T and the argument list consists of the
3270 // initializer list as a single argument.
3271 if (InitListSyntax) {
3272 InitListExpr *ILE = cast<InitListExpr>(Args[0]);
3273 AsInitializerList = true;
3275 // If the initializer list has no elements and T has a default constructor,
3276 // the first phase is omitted.
3277 if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
3278 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
3279 CandidateSet, Ctors, Best,
3280 CopyInitialization, AllowExplicit,
3281 /*OnlyListConstructor=*/true,
3284 // Time to unwrap the init list.
3285 Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
3288 // C++11 [over.match.list]p1:
3289 // - If no viable initializer-list constructor is found, overload resolution
3290 // is performed again, where the candidate functions are all the
3291 // constructors of the class T and the argument list consists of the
3292 // elements of the initializer list.
3293 if (Result == OR_No_Viable_Function) {
3294 AsInitializerList = false;
3295 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
3296 CandidateSet, Ctors, Best,
3297 CopyInitialization, AllowExplicit,
3298 /*OnlyListConstructors=*/false,
3302 Sequence.SetOverloadFailure(InitListSyntax ?
3303 InitializationSequence::FK_ListConstructorOverloadFailed :
3304 InitializationSequence::FK_ConstructorOverloadFailed,
3309 // C++11 [dcl.init]p6:
3310 // If a program calls for the default initialization of an object
3311 // of a const-qualified type T, T shall be a class type with a
3312 // user-provided default constructor.
3313 if (Kind.getKind() == InitializationKind::IK_Default &&
3314 Entity.getType().isConstQualified() &&
3315 !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
3316 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3320 // C++11 [over.match.list]p1:
3321 // In copy-list-initialization, if an explicit constructor is chosen, the
3322 // initializer is ill-formed.
3323 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3324 if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
3325 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3329 // Add the constructor initialization step. Any cv-qualification conversion is
3330 // subsumed by the initialization.
3331 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3332 Sequence.AddConstructorInitializationStep(CtorDecl,
3333 Best->FoundDecl.getAccess(),
3334 DestType, HadMultipleCandidates,
3335 InitListSyntax, AsInitializerList);
3339 ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3341 QualType &SourceType,
3342 QualType &UnqualifiedSourceType,
3343 QualType UnqualifiedTargetType,
3344 InitializationSequence &Sequence) {
3345 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3346 S.Context.OverloadTy) {
3347 DeclAccessPair Found;
3348 bool HadMultipleCandidates = false;
3349 if (FunctionDecl *Fn
3350 = S.ResolveAddressOfOverloadedFunction(Initializer,
3351 UnqualifiedTargetType,
3353 &HadMultipleCandidates)) {
3354 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3355 HadMultipleCandidates);
3356 SourceType = Fn->getType();
3357 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3358 } else if (!UnqualifiedTargetType->isRecordType()) {
3359 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3366 static void TryReferenceInitializationCore(Sema &S,
3367 const InitializedEntity &Entity,
3368 const InitializationKind &Kind,
3370 QualType cv1T1, QualType T1,
3372 QualType cv2T2, QualType T2,
3374 InitializationSequence &Sequence);
3376 static void TryValueInitialization(Sema &S,
3377 const InitializedEntity &Entity,
3378 const InitializationKind &Kind,
3379 InitializationSequence &Sequence,
3380 InitListExpr *InitList = nullptr);
3382 /// \brief Attempt list initialization of a reference.
3383 static void TryReferenceListInitialization(Sema &S,
3384 const InitializedEntity &Entity,
3385 const InitializationKind &Kind,
3386 InitListExpr *InitList,
3387 InitializationSequence &Sequence) {
3388 // First, catch C++03 where this isn't possible.
3389 if (!S.getLangOpts().CPlusPlus11) {
3390 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3394 QualType DestType = Entity.getType();
3395 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3397 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3399 // Reference initialization via an initializer list works thus:
3400 // If the initializer list consists of a single element that is
3401 // reference-related to the referenced type, bind directly to that element
3402 // (possibly creating temporaries).
3403 // Otherwise, initialize a temporary with the initializer list and
3405 if (InitList->getNumInits() == 1) {
3406 Expr *Initializer = InitList->getInit(0);
3407 QualType cv2T2 = Initializer->getType();
3409 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3411 // If this fails, creating a temporary wouldn't work either.
3412 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3416 SourceLocation DeclLoc = Initializer->getLocStart();
3417 bool dummy1, dummy2, dummy3;
3418 Sema::ReferenceCompareResult RefRelationship
3419 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3421 if (RefRelationship >= Sema::Ref_Related) {
3422 // Try to bind the reference here.
3423 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3424 T1Quals, cv2T2, T2, T2Quals, Sequence);
3426 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3430 // Update the initializer if we've resolved an overloaded function.
3431 if (Sequence.step_begin() != Sequence.step_end())
3432 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3435 // Not reference-related. Create a temporary and bind to that.
3436 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3438 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3440 if (DestType->isRValueReferenceType() ||
3441 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3442 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3445 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3449 /// \brief Attempt list initialization (C++0x [dcl.init.list])
3450 static void TryListInitialization(Sema &S,
3451 const InitializedEntity &Entity,
3452 const InitializationKind &Kind,
3453 InitListExpr *InitList,
3454 InitializationSequence &Sequence) {
3455 QualType DestType = Entity.getType();
3457 // C++ doesn't allow scalar initialization with more than one argument.
3458 // But C99 complex numbers are scalars and it makes sense there.
3459 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
3460 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3461 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3464 if (DestType->isReferenceType()) {
3465 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
3468 if (DestType->isRecordType()) {
3469 if (S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
3470 Sequence.setIncompleteTypeFailure(DestType);
3474 // C++11 [dcl.init.list]p3:
3475 // - If T is an aggregate, aggregate initialization is performed.
3476 if (!DestType->isAggregateType()) {
3477 if (S.getLangOpts().CPlusPlus11) {
3478 // - Otherwise, if the initializer list has no elements and T is a
3479 // class type with a default constructor, the object is
3480 // value-initialized.
3481 if (InitList->getNumInits() == 0) {
3482 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
3483 if (RD->hasDefaultConstructor()) {
3484 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3489 // - Otherwise, if T is a specialization of std::initializer_list<E>,
3490 // an initializer_list object constructed [...]
3491 if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3494 // - Otherwise, if T is a class type, constructors are considered.
3495 Expr *InitListAsExpr = InitList;
3496 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
3497 Sequence, /*InitListSyntax*/true);
3500 InitializationSequence::FK_InitListBadDestinationType);
3504 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
3505 InitList->getNumInits() == 1 &&
3506 InitList->getInit(0)->getType()->isRecordType()) {
3507 // - Otherwise, if the initializer list has a single element of type E
3508 // [...references are handled above...], the object or reference is
3509 // initialized from that element; if a narrowing conversion is required
3510 // to convert the element to T, the program is ill-formed.
3512 // Per core-24034, this is direct-initialization if we were performing
3513 // direct-list-initialization and copy-initialization otherwise.
3514 // We can't use InitListChecker for this, because it always performs
3515 // copy-initialization. This only matters if we might use an 'explicit'
3516 // conversion operator, so we only need to handle the cases where the source
3517 // is of record type.
3518 InitializationKind SubKind =
3519 Kind.getKind() == InitializationKind::IK_DirectList
3520 ? InitializationKind::CreateDirect(Kind.getLocation(),
3521 InitList->getLBraceLoc(),
3522 InitList->getRBraceLoc())
3524 Expr *SubInit[1] = { InitList->getInit(0) };
3525 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
3526 /*TopLevelOfInitList*/true);
3528 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
3532 InitListChecker CheckInitList(S, Entity, InitList,
3533 DestType, /*VerifyOnly=*/true);
3534 if (CheckInitList.HadError()) {
3535 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3539 // Add the list initialization step with the built init list.
3540 Sequence.AddListInitializationStep(DestType);
3543 /// \brief Try a reference initialization that involves calling a conversion
3545 static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3546 const InitializedEntity &Entity,
3547 const InitializationKind &Kind,
3550 InitializationSequence &Sequence) {
3551 QualType DestType = Entity.getType();
3552 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3553 QualType T1 = cv1T1.getUnqualifiedType();
3554 QualType cv2T2 = Initializer->getType();
3555 QualType T2 = cv2T2.getUnqualifiedType();
3558 bool ObjCConversion;
3559 bool ObjCLifetimeConversion;
3560 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
3561 T1, T2, DerivedToBase,
3563 ObjCLifetimeConversion) &&
3564 "Must have incompatible references when binding via conversion");
3565 (void)DerivedToBase;
3566 (void)ObjCConversion;
3567 (void)ObjCLifetimeConversion;
3569 // Build the candidate set directly in the initialization sequence
3570 // structure, so that it will persist if we fail.
3571 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3572 CandidateSet.clear();
3574 // Determine whether we are allowed to call explicit constructors or
3575 // explicit conversion operators.
3576 bool AllowExplicit = Kind.AllowExplicit();
3577 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
3579 const RecordType *T1RecordType = nullptr;
3580 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3581 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
3582 // The type we're converting to is a class type. Enumerate its constructors
3583 // to see if there is a suitable conversion.
3584 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
3586 DeclContext::lookup_result R = S.LookupConstructors(T1RecordDecl);
3587 // The container holding the constructors can under certain conditions
3588 // be changed while iterating (e.g. because of deserialization).
3589 // To be safe we copy the lookup results to a new container.
3590 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
3591 for (SmallVectorImpl<NamedDecl *>::iterator
3592 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
3594 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3596 // Find the constructor (which may be a template).
3597 CXXConstructorDecl *Constructor = nullptr;
3598 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
3599 if (ConstructorTmpl)
3600 Constructor = cast<CXXConstructorDecl>(
3601 ConstructorTmpl->getTemplatedDecl());
3603 Constructor = cast<CXXConstructorDecl>(D);
3605 if (!Constructor->isInvalidDecl() &&
3606 Constructor->isConvertingConstructor(AllowExplicit)) {
3607 if (ConstructorTmpl)
3608 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3609 /*ExplicitArgs*/ nullptr,
3610 Initializer, CandidateSet,
3611 /*SuppressUserConversions=*/true);
3613 S.AddOverloadCandidate(Constructor, FoundDecl,
3614 Initializer, CandidateSet,
3615 /*SuppressUserConversions=*/true);
3619 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3620 return OR_No_Viable_Function;
3622 const RecordType *T2RecordType = nullptr;
3623 if ((T2RecordType = T2->getAs<RecordType>()) &&
3624 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
3625 // The type we're converting from is a class type, enumerate its conversion
3627 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3629 std::pair<CXXRecordDecl::conversion_iterator,
3630 CXXRecordDecl::conversion_iterator>
3631 Conversions = T2RecordDecl->getVisibleConversionFunctions();
3632 for (CXXRecordDecl::conversion_iterator
3633 I = Conversions.first, E = Conversions.second; I != E; ++I) {
3635 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3636 if (isa<UsingShadowDecl>(D))
3637 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3639 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3640 CXXConversionDecl *Conv;
3642 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3644 Conv = cast<CXXConversionDecl>(D);
3646 // If the conversion function doesn't return a reference type,
3647 // it can't be considered for this conversion unless we're allowed to
3648 // consider rvalues.
3649 // FIXME: Do we need to make sure that we only consider conversion
3650 // candidates with reference-compatible results? That might be needed to
3652 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
3653 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3655 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
3656 ActingDC, Initializer,
3657 DestType, CandidateSet,
3658 /*AllowObjCConversionOnExplicit=*/
3661 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
3662 Initializer, DestType, CandidateSet,
3663 /*AllowObjCConversionOnExplicit=*/false);
3667 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3668 return OR_No_Viable_Function;
3670 SourceLocation DeclLoc = Initializer->getLocStart();
3672 // Perform overload resolution. If it fails, return the failed result.
3673 OverloadCandidateSet::iterator Best;
3674 if (OverloadingResult Result
3675 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
3678 FunctionDecl *Function = Best->Function;
3679 // This is the overload that will be used for this initialization step if we
3680 // use this initialization. Mark it as referenced.
3681 Function->setReferenced();
3683 // Compute the returned type of the conversion.
3684 if (isa<CXXConversionDecl>(Function))
3685 T2 = Function->getReturnType();
3689 // Add the user-defined conversion step.
3690 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3691 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
3692 T2.getNonLValueExprType(S.Context),
3693 HadMultipleCandidates);
3695 // Determine whether we need to perform derived-to-base or
3696 // cv-qualification adjustments.
3697 ExprValueKind VK = VK_RValue;
3698 if (T2->isLValueReferenceType())
3700 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
3701 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
3703 bool NewDerivedToBase = false;
3704 bool NewObjCConversion = false;
3705 bool NewObjCLifetimeConversion = false;
3706 Sema::ReferenceCompareResult NewRefRelationship
3707 = S.CompareReferenceRelationship(DeclLoc, T1,
3708 T2.getNonLValueExprType(S.Context),
3709 NewDerivedToBase, NewObjCConversion,
3710 NewObjCLifetimeConversion);
3711 if (NewRefRelationship == Sema::Ref_Incompatible) {
3712 // If the type we've converted to is not reference-related to the
3713 // type we're looking for, then there is another conversion step
3714 // we need to perform to produce a temporary of the right type
3715 // that we'll be binding to.
3716 ImplicitConversionSequence ICS;
3718 ICS.Standard = Best->FinalConversion;
3719 T2 = ICS.Standard.getToType(2);
3720 Sequence.AddConversionSequenceStep(ICS, T2);
3721 } else if (NewDerivedToBase)
3722 Sequence.AddDerivedToBaseCastStep(
3723 S.Context.getQualifiedType(T1,
3724 T2.getNonReferenceType().getQualifiers()),
3726 else if (NewObjCConversion)
3727 Sequence.AddObjCObjectConversionStep(
3728 S.Context.getQualifiedType(T1,
3729 T2.getNonReferenceType().getQualifiers()));
3731 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
3732 Sequence.AddQualificationConversionStep(cv1T1, VK);
3734 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3738 static void CheckCXX98CompatAccessibleCopy(Sema &S,
3739 const InitializedEntity &Entity,
3742 /// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3743 static void TryReferenceInitialization(Sema &S,
3744 const InitializedEntity &Entity,
3745 const InitializationKind &Kind,
3747 InitializationSequence &Sequence) {
3748 QualType DestType = Entity.getType();
3749 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3751 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3752 QualType cv2T2 = Initializer->getType();
3754 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3756 // If the initializer is the address of an overloaded function, try
3757 // to resolve the overloaded function. If all goes well, T2 is the
3758 // type of the resulting function.
3759 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3763 // Delegate everything else to a subfunction.
3764 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3765 T1Quals, cv2T2, T2, T2Quals, Sequence);
3768 /// Converts the target of reference initialization so that it has the
3769 /// appropriate qualifiers and value kind.
3771 /// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
3774 /// const int &r = x;
3777 /// In this case the reference is binding to a bitfield lvalue, which isn't
3778 /// valid. Perform a load to create a lifetime-extended temporary instead.
3780 /// const int &r = someStruct.bitfield;
3782 static ExprValueKind
3783 convertQualifiersAndValueKindIfNecessary(Sema &S,
3784 InitializationSequence &Sequence,
3790 bool IsNonAddressableType = Initializer->refersToBitField() ||
3791 Initializer->refersToVectorElement();
3793 if (IsNonAddressableType) {
3794 // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
3795 // lvalue reference to a non-volatile const type, or the reference shall be
3796 // an rvalue reference.
3798 // If not, we can't make a temporary and bind to that. Give up and allow the
3799 // error to be diagnosed later.
3800 if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
3801 assert(Initializer->isGLValue());
3802 return Initializer->getValueKind();
3805 // Force a load so we can materialize a temporary.
3806 Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
3810 if (T1Quals != T2Quals) {
3811 Sequence.AddQualificationConversionStep(cv1T1,
3812 Initializer->getValueKind());
3815 return Initializer->getValueKind();
3819 /// \brief Reference initialization without resolving overloaded functions.
3820 static void TryReferenceInitializationCore(Sema &S,
3821 const InitializedEntity &Entity,
3822 const InitializationKind &Kind,
3824 QualType cv1T1, QualType T1,
3826 QualType cv2T2, QualType T2,
3828 InitializationSequence &Sequence) {
3829 QualType DestType = Entity.getType();
3830 SourceLocation DeclLoc = Initializer->getLocStart();
3831 // Compute some basic properties of the types and the initializer.
3832 bool isLValueRef = DestType->isLValueReferenceType();
3833 bool isRValueRef = !isLValueRef;
3834 bool DerivedToBase = false;
3835 bool ObjCConversion = false;
3836 bool ObjCLifetimeConversion = false;
3837 Expr::Classification InitCategory = Initializer->Classify(S.Context);
3838 Sema::ReferenceCompareResult RefRelationship
3839 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
3840 ObjCConversion, ObjCLifetimeConversion);
3842 // C++0x [dcl.init.ref]p5:
3843 // A reference to type "cv1 T1" is initialized by an expression of type
3844 // "cv2 T2" as follows:
3846 // - If the reference is an lvalue reference and the initializer
3848 // Note the analogous bullet points for rvalue refs to functions. Because
3849 // there are no function rvalues in C++, rvalue refs to functions are treated
3850 // like lvalue refs.
3851 OverloadingResult ConvOvlResult = OR_Success;
3852 bool T1Function = T1->isFunctionType();
3853 if (isLValueRef || T1Function) {
3854 if (InitCategory.isLValue() &&
3855 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
3856 (Kind.isCStyleOrFunctionalCast() &&
3857 RefRelationship == Sema::Ref_Related))) {
3858 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
3859 // reference-compatible with "cv2 T2," or
3861 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
3862 // bit-field when we're determining whether the reference initialization
3863 // can occur. However, we do pay attention to whether it is a bit-field
3864 // to decide whether we're actually binding to a temporary created from
3867 Sequence.AddDerivedToBaseCastStep(
3868 S.Context.getQualifiedType(T1, T2Quals),
3870 else if (ObjCConversion)
3871 Sequence.AddObjCObjectConversionStep(
3872 S.Context.getQualifiedType(T1, T2Quals));
3874 ExprValueKind ValueKind =
3875 convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
3876 cv1T1, T1Quals, T2Quals,
3878 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
3882 // - has a class type (i.e., T2 is a class type), where T1 is not
3883 // reference-related to T2, and can be implicitly converted to an
3884 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3885 // with "cv3 T3" (this conversion is selected by enumerating the
3886 // applicable conversion functions (13.3.1.6) and choosing the best
3887 // one through overload resolution (13.3)),
3888 // If we have an rvalue ref to function type here, the rhs must be
3889 // an rvalue. DR1287 removed the "implicitly" here.
3890 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3891 (isLValueRef || InitCategory.isRValue())) {
3892 ConvOvlResult = TryRefInitWithConversionFunction(
3893 S, Entity, Kind, Initializer, /*AllowRValues*/isRValueRef, Sequence);
3894 if (ConvOvlResult == OR_Success)
3896 if (ConvOvlResult != OR_No_Viable_Function)
3897 Sequence.SetOverloadFailure(
3898 InitializationSequence::FK_ReferenceInitOverloadFailed,
3903 // - Otherwise, the reference shall be an lvalue reference to a
3904 // non-volatile const type (i.e., cv1 shall be const), or the reference
3905 // shall be an rvalue reference.
3906 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
3907 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3908 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3909 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3910 Sequence.SetOverloadFailure(
3911 InitializationSequence::FK_ReferenceInitOverloadFailed,
3914 Sequence.SetFailed(InitCategory.isLValue()
3915 ? (RefRelationship == Sema::Ref_Related
3916 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3917 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3918 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3923 // - If the initializer expression
3924 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3925 // "cv1 T1" is reference-compatible with "cv2 T2"
3926 // Note: functions are handled below.
3928 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
3929 (Kind.isCStyleOrFunctionalCast() &&
3930 RefRelationship == Sema::Ref_Related)) &&
3931 (InitCategory.isXValue() ||
3932 (InitCategory.isPRValue() && T2->isRecordType()) ||
3933 (InitCategory.isPRValue() && T2->isArrayType()))) {
3934 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3935 if (InitCategory.isPRValue() && T2->isRecordType()) {
3936 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3937 // compiler the freedom to perform a copy here or bind to the
3938 // object, while C++0x requires that we bind directly to the
3939 // object. Hence, we always bind to the object without making an
3940 // extra copy. However, in C++03 requires that we check for the
3941 // presence of a suitable copy constructor:
3943 // The constructor that would be used to make the copy shall
3944 // be callable whether or not the copy is actually done.
3945 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
3946 Sequence.AddExtraneousCopyToTemporary(cv2T2);
3947 else if (S.getLangOpts().CPlusPlus11)
3948 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
3952 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3954 else if (ObjCConversion)
3955 Sequence.AddObjCObjectConversionStep(
3956 S.Context.getQualifiedType(T1, T2Quals));
3958 ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
3963 Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
3967 // - has a class type (i.e., T2 is a class type), where T1 is not
3968 // reference-related to T2, and can be implicitly converted to an
3969 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3970 // where "cv1 T1" is reference-compatible with "cv3 T3",
3972 // DR1287 removes the "implicitly" here.
3973 if (T2->isRecordType()) {
3974 if (RefRelationship == Sema::Ref_Incompatible) {
3975 ConvOvlResult = TryRefInitWithConversionFunction(
3976 S, Entity, Kind, Initializer, /*AllowRValues*/true, Sequence);
3978 Sequence.SetOverloadFailure(
3979 InitializationSequence::FK_ReferenceInitOverloadFailed,
3985 if ((RefRelationship == Sema::Ref_Compatible ||
3986 RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
3987 isRValueRef && InitCategory.isLValue()) {
3989 InitializationSequence::FK_RValueReferenceBindingToLValue);
3993 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3997 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
3998 // from the initializer expression using the rules for a non-reference
3999 // copy-initialization (8.5). The reference is then bound to the
4002 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
4004 // FIXME: Why do we use an implicit conversion here rather than trying
4005 // copy-initialization?
4006 ImplicitConversionSequence ICS
4007 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
4008 /*SuppressUserConversions=*/false,
4009 /*AllowExplicit=*/false,
4010 /*FIXME:InOverloadResolution=*/false,
4011 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4012 /*AllowObjCWritebackConversion=*/false);
4015 // FIXME: Use the conversion function set stored in ICS to turn
4016 // this into an overloading ambiguity diagnostic. However, we need
4017 // to keep that set as an OverloadCandidateSet rather than as some
4018 // other kind of set.
4019 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4020 Sequence.SetOverloadFailure(
4021 InitializationSequence::FK_ReferenceInitOverloadFailed,
4023 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4024 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4026 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
4029 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
4032 // [...] If T1 is reference-related to T2, cv1 must be the
4033 // same cv-qualification as, or greater cv-qualification
4034 // than, cv2; otherwise, the program is ill-formed.
4035 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
4036 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
4037 if (RefRelationship == Sema::Ref_Related &&
4038 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
4039 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4043 // [...] If T1 is reference-related to T2 and the reference is an rvalue
4044 // reference, the initializer expression shall not be an lvalue.
4045 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
4046 InitCategory.isLValue()) {
4048 InitializationSequence::FK_RValueReferenceBindingToLValue);
4052 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
4056 /// \brief Attempt character array initialization from a string literal
4057 /// (C++ [dcl.init.string], C99 6.7.8).
4058 static void TryStringLiteralInitialization(Sema &S,
4059 const InitializedEntity &Entity,
4060 const InitializationKind &Kind,
4062 InitializationSequence &Sequence) {
4063 Sequence.AddStringInitStep(Entity.getType());
4066 /// \brief Attempt value initialization (C++ [dcl.init]p7).
4067 static void TryValueInitialization(Sema &S,
4068 const InitializedEntity &Entity,
4069 const InitializationKind &Kind,
4070 InitializationSequence &Sequence,
4071 InitListExpr *InitList) {
4072 assert((!InitList || InitList->getNumInits() == 0) &&
4073 "Shouldn't use value-init for non-empty init lists");
4075 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
4077 // To value-initialize an object of type T means:
4078 QualType T = Entity.getType();
4080 // -- if T is an array type, then each element is value-initialized;
4081 T = S.Context.getBaseElementType(T);
4083 if (const RecordType *RT = T->getAs<RecordType>()) {
4084 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
4085 bool NeedZeroInitialization = true;
4086 if (!S.getLangOpts().CPlusPlus11) {
4088 // -- if T is a class type (clause 9) with a user-declared constructor
4089 // (12.1), then the default constructor for T is called (and the
4090 // initialization is ill-formed if T has no accessible default
4092 if (ClassDecl->hasUserDeclaredConstructor())
4093 NeedZeroInitialization = false;
4096 // -- if T is a class type (clause 9) with either no default constructor
4097 // (12.1 [class.ctor]) or a default constructor that is user-provided
4098 // or deleted, then the object is default-initialized;
4099 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
4100 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
4101 NeedZeroInitialization = false;
4104 // -- if T is a (possibly cv-qualified) non-union class type without a
4105 // user-provided or deleted default constructor, then the object is
4106 // zero-initialized and, if T has a non-trivial default constructor,
4107 // default-initialized;
4108 // The 'non-union' here was removed by DR1502. The 'non-trivial default
4109 // constructor' part was removed by DR1507.
4110 if (NeedZeroInitialization)
4111 Sequence.AddZeroInitializationStep(Entity.getType());
4114 // -- if T is a non-union class type without a user-declared constructor,
4115 // then every non-static data member and base class component of T is
4116 // value-initialized;
4117 // [...] A program that calls for [...] value-initialization of an
4118 // entity of reference type is ill-formed.
4120 // C++11 doesn't need this handling, because value-initialization does not
4121 // occur recursively there, and the implicit default constructor is
4122 // defined as deleted in the problematic cases.
4123 if (!S.getLangOpts().CPlusPlus11 &&
4124 ClassDecl->hasUninitializedReferenceMember()) {
4125 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
4129 // If this is list-value-initialization, pass the empty init list on when
4130 // building the constructor call. This affects the semantics of a few
4131 // things (such as whether an explicit default constructor can be called).
4132 Expr *InitListAsExpr = InitList;
4133 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
4134 bool InitListSyntax = InitList;
4136 return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
4141 Sequence.AddZeroInitializationStep(Entity.getType());
4144 /// \brief Attempt default initialization (C++ [dcl.init]p6).
4145 static void TryDefaultInitialization(Sema &S,
4146 const InitializedEntity &Entity,
4147 const InitializationKind &Kind,
4148 InitializationSequence &Sequence) {
4149 assert(Kind.getKind() == InitializationKind::IK_Default);
4151 // C++ [dcl.init]p6:
4152 // To default-initialize an object of type T means:
4153 // - if T is an array type, each element is default-initialized;
4154 QualType DestType = S.Context.getBaseElementType(Entity.getType());
4156 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4157 // constructor for T is called (and the initialization is ill-formed if
4158 // T has no accessible default constructor);
4159 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
4160 TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
4164 // - otherwise, no initialization is performed.
4166 // If a program calls for the default initialization of an object of
4167 // a const-qualified type T, T shall be a class type with a user-provided
4168 // default constructor.
4169 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
4170 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
4174 // If the destination type has a lifetime property, zero-initialize it.
4175 if (DestType.getQualifiers().hasObjCLifetime()) {
4176 Sequence.AddZeroInitializationStep(Entity.getType());
4181 /// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
4182 /// which enumerates all conversion functions and performs overload resolution
4183 /// to select the best.
4184 static void TryUserDefinedConversion(Sema &S,
4186 const InitializationKind &Kind,
4188 InitializationSequence &Sequence,
4189 bool TopLevelOfInitList) {
4190 assert(!DestType->isReferenceType() && "References are handled elsewhere");
4191 QualType SourceType = Initializer->getType();
4192 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4193 "Must have a class type to perform a user-defined conversion");
4195 // Build the candidate set directly in the initialization sequence
4196 // structure, so that it will persist if we fail.
4197 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4198 CandidateSet.clear();
4200 // Determine whether we are allowed to call explicit constructors or
4201 // explicit conversion operators.
4202 bool AllowExplicit = Kind.AllowExplicit();
4204 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4205 // The type we're converting to is a class type. Enumerate its constructors
4206 // to see if there is a suitable conversion.
4207 CXXRecordDecl *DestRecordDecl
4208 = cast<CXXRecordDecl>(DestRecordType->getDecl());
4210 // Try to complete the type we're converting to.
4211 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
4212 DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
4213 // The container holding the constructors can under certain conditions
4214 // be changed while iterating. To be safe we copy the lookup results
4215 // to a new container.
4216 SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
4217 for (SmallVectorImpl<NamedDecl *>::iterator
4218 Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
4219 Con != ConEnd; ++Con) {
4220 NamedDecl *D = *Con;
4221 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
4223 // Find the constructor (which may be a template).
4224 CXXConstructorDecl *Constructor = nullptr;
4225 FunctionTemplateDecl *ConstructorTmpl
4226 = dyn_cast<FunctionTemplateDecl>(D);
4227 if (ConstructorTmpl)
4228 Constructor = cast<CXXConstructorDecl>(
4229 ConstructorTmpl->getTemplatedDecl());
4231 Constructor = cast<CXXConstructorDecl>(D);
4233 if (!Constructor->isInvalidDecl() &&
4234 Constructor->isConvertingConstructor(AllowExplicit)) {
4235 if (ConstructorTmpl)
4236 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
4237 /*ExplicitArgs*/ nullptr,
4238 Initializer, CandidateSet,
4239 /*SuppressUserConversions=*/true);
4241 S.AddOverloadCandidate(Constructor, FoundDecl,
4242 Initializer, CandidateSet,
4243 /*SuppressUserConversions=*/true);
4249 SourceLocation DeclLoc = Initializer->getLocStart();
4251 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4252 // The type we're converting from is a class type, enumerate its conversion
4255 // We can only enumerate the conversion functions for a complete type; if
4256 // the type isn't complete, simply skip this step.
4257 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
4258 CXXRecordDecl *SourceRecordDecl
4259 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
4261 std::pair<CXXRecordDecl::conversion_iterator,
4262 CXXRecordDecl::conversion_iterator>
4263 Conversions = SourceRecordDecl->getVisibleConversionFunctions();
4264 for (CXXRecordDecl::conversion_iterator
4265 I = Conversions.first, E = Conversions.second; I != E; ++I) {
4267 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4268 if (isa<UsingShadowDecl>(D))
4269 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4271 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4272 CXXConversionDecl *Conv;
4274 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4276 Conv = cast<CXXConversionDecl>(D);
4278 if (AllowExplicit || !Conv->isExplicit()) {
4280 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
4281 ActingDC, Initializer, DestType,
4282 CandidateSet, AllowExplicit);
4284 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
4285 Initializer, DestType, CandidateSet,
4292 // Perform overload resolution. If it fails, return the failed result.
4293 OverloadCandidateSet::iterator Best;
4294 if (OverloadingResult Result
4295 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4296 Sequence.SetOverloadFailure(
4297 InitializationSequence::FK_UserConversionOverloadFailed,
4302 FunctionDecl *Function = Best->Function;
4303 Function->setReferenced();
4304 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4306 if (isa<CXXConstructorDecl>(Function)) {
4307 // Add the user-defined conversion step. Any cv-qualification conversion is
4308 // subsumed by the initialization. Per DR5, the created temporary is of the
4309 // cv-unqualified type of the destination.
4310 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4311 DestType.getUnqualifiedType(),
4312 HadMultipleCandidates);
4316 // Add the user-defined conversion step that calls the conversion function.
4317 QualType ConvType = Function->getCallResultType();
4318 if (ConvType->getAs<RecordType>()) {
4319 // If we're converting to a class type, there may be an copy of
4320 // the resulting temporary object (possible to create an object of
4321 // a base class type). That copy is not a separate conversion, so
4322 // we just make a note of the actual destination type (possibly a
4323 // base class of the type returned by the conversion function) and
4324 // let the user-defined conversion step handle the conversion.
4325 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
4326 HadMultipleCandidates);
4330 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4331 HadMultipleCandidates);
4333 // If the conversion following the call to the conversion function
4334 // is interesting, add it as a separate step.
4335 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4336 Best->FinalConversion.Third) {
4337 ImplicitConversionSequence ICS;
4339 ICS.Standard = Best->FinalConversion;
4340 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
4344 /// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4345 /// a function with a pointer return type contains a 'return false;' statement.
4346 /// In C++11, 'false' is not a null pointer, so this breaks the build of any
4347 /// code using that header.
4349 /// Work around this by treating 'return false;' as zero-initializing the result
4350 /// if it's used in a pointer-returning function in a system header.
4351 static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
4352 const InitializedEntity &Entity,
4354 return S.getLangOpts().CPlusPlus11 &&
4355 Entity.getKind() == InitializedEntity::EK_Result &&
4356 Entity.getType()->isPointerType() &&
4357 isa<CXXBoolLiteralExpr>(Init) &&
4358 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
4359 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
4362 /// The non-zero enum values here are indexes into diagnostic alternatives.
4363 enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4365 /// Determines whether this expression is an acceptable ICR source.
4366 static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
4367 bool isAddressOf, bool &isWeakAccess) {
4369 e = e->IgnoreParens();
4371 // Skip address-of nodes.
4372 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4373 if (op->getOpcode() == UO_AddrOf)
4374 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4377 // Skip certain casts.
4378 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4379 switch (ce->getCastKind()) {
4382 case CK_LValueBitCast:
4384 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
4386 case CK_ArrayToPointerDecay:
4387 return IIK_nonscalar;
4389 case CK_NullToPointer:
4396 // If we have a declaration reference, it had better be a local variable.
4397 } else if (isa<DeclRefExpr>(e)) {
4398 // set isWeakAccess to true, to mean that there will be an implicit
4399 // load which requires a cleanup.
4400 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4401 isWeakAccess = true;
4403 if (!isAddressOf) return IIK_nonlocal;
4405 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4406 if (!var) return IIK_nonlocal;
4408 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
4410 // If we have a conditional operator, check both sides.
4411 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
4412 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4416 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
4418 // These are never scalar.
4419 } else if (isa<ArraySubscriptExpr>(e)) {
4420 return IIK_nonscalar;
4422 // Otherwise, it needs to be a null pointer constant.
4424 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4425 ? IIK_okay : IIK_nonlocal);
4428 return IIK_nonlocal;
4431 /// Check whether the given expression is a valid operand for an
4432 /// indirect copy/restore.
4433 static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4434 assert(src->isRValue());
4435 bool isWeakAccess = false;
4436 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4437 // If isWeakAccess to true, there will be an implicit
4438 // load which requires a cleanup.
4439 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4440 S.ExprNeedsCleanups = true;
4442 if (iik == IIK_okay) return;
4444 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4445 << ((unsigned) iik - 1) // shift index into diagnostic explanations
4446 << src->getSourceRange();
4449 /// \brief Determine whether we have compatible array types for the
4450 /// purposes of GNU by-copy array initialization.
4451 static bool hasCompatibleArrayTypes(ASTContext &Context,
4452 const ArrayType *Dest,
4453 const ArrayType *Source) {
4454 // If the source and destination array types are equivalent, we're
4456 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4459 // Make sure that the element types are the same.
4460 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4463 // The only mismatch we allow is when the destination is an
4464 // incomplete array type and the source is a constant array type.
4465 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4468 static bool tryObjCWritebackConversion(Sema &S,
4469 InitializationSequence &Sequence,
4470 const InitializedEntity &Entity,
4471 Expr *Initializer) {
4472 bool ArrayDecay = false;
4473 QualType ArgType = Initializer->getType();
4474 QualType ArgPointee;
4475 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4477 ArgPointee = ArgArrayType->getElementType();
4478 ArgType = S.Context.getPointerType(ArgPointee);
4481 // Handle write-back conversion.
4482 QualType ConvertedArgType;
4483 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4487 // We should copy unless we're passing to an argument explicitly
4489 bool ShouldCopy = true;
4490 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4491 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4493 // Do we need an lvalue conversion?
4494 if (ArrayDecay || Initializer->isGLValue()) {
4495 ImplicitConversionSequence ICS;
4497 ICS.Standard.setAsIdentityConversion();
4499 QualType ResultType;
4501 ICS.Standard.First = ICK_Array_To_Pointer;
4502 ResultType = S.Context.getPointerType(ArgPointee);
4504 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4505 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4508 Sequence.AddConversionSequenceStep(ICS, ResultType);
4511 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4515 static bool TryOCLSamplerInitialization(Sema &S,
4516 InitializationSequence &Sequence,
4518 Expr *Initializer) {
4519 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4520 !Initializer->isIntegerConstantExpr(S.getASTContext()))
4523 Sequence.AddOCLSamplerInitStep(DestType);
4528 // OpenCL 1.2 spec, s6.12.10
4530 // The event argument can also be used to associate the
4531 // async_work_group_copy with a previous async copy allowing
4532 // an event to be shared by multiple async copies; otherwise
4533 // event should be zero.
4535 static bool TryOCLZeroEventInitialization(Sema &S,
4536 InitializationSequence &Sequence,
4538 Expr *Initializer) {
4539 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4540 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4541 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4544 Sequence.AddOCLZeroEventStep(DestType);
4548 InitializationSequence::InitializationSequence(Sema &S,
4549 const InitializedEntity &Entity,
4550 const InitializationKind &Kind,
4552 bool TopLevelOfInitList)
4553 : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
4554 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList);
4557 void InitializationSequence::InitializeFrom(Sema &S,
4558 const InitializedEntity &Entity,
4559 const InitializationKind &Kind,
4561 bool TopLevelOfInitList) {
4562 ASTContext &Context = S.Context;
4564 // Eliminate non-overload placeholder types in the arguments. We
4565 // need to do this before checking whether types are dependent
4566 // because lowering a pseudo-object expression might well give us
4567 // something of dependent type.
4568 for (unsigned I = 0, E = Args.size(); I != E; ++I)
4569 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4570 // FIXME: should we be doing this here?
4571 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4572 if (result.isInvalid()) {
4573 SetFailed(FK_PlaceholderType);
4576 Args[I] = result.get();
4579 // C++0x [dcl.init]p16:
4580 // The semantics of initializers are as follows. The destination type is
4581 // the type of the object or reference being initialized and the source
4582 // type is the type of the initializer expression. The source type is not
4583 // defined when the initializer is a braced-init-list or when it is a
4584 // parenthesized list of expressions.
4585 QualType DestType = Entity.getType();
4587 if (DestType->isDependentType() ||
4588 Expr::hasAnyTypeDependentArguments(Args)) {
4589 SequenceKind = DependentSequence;
4593 // Almost everything is a normal sequence.
4594 setSequenceKind(NormalSequence);
4596 QualType SourceType;
4597 Expr *Initializer = nullptr;
4598 if (Args.size() == 1) {
4599 Initializer = Args[0];
4600 if (S.getLangOpts().ObjC1) {
4601 if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(),
4602 DestType, Initializer->getType(),
4604 S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
4605 Args[0] = Initializer;
4607 if (!isa<InitListExpr>(Initializer))
4608 SourceType = Initializer->getType();
4611 // - If the initializer is a (non-parenthesized) braced-init-list, the
4612 // object is list-initialized (8.5.4).
4613 if (Kind.getKind() != InitializationKind::IK_Direct) {
4614 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4615 TryListInitialization(S, Entity, Kind, InitList, *this);
4620 // - If the destination type is a reference type, see 8.5.3.
4621 if (DestType->isReferenceType()) {
4622 // C++0x [dcl.init.ref]p1:
4623 // A variable declared to be a T& or T&&, that is, "reference to type T"
4624 // (8.3.2), shall be initialized by an object, or function, of type T or
4625 // by an object that can be converted into a T.
4626 // (Therefore, multiple arguments are not permitted.)
4627 if (Args.size() != 1)
4628 SetFailed(FK_TooManyInitsForReference);
4630 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
4634 // - If the initializer is (), the object is value-initialized.
4635 if (Kind.getKind() == InitializationKind::IK_Value ||
4636 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
4637 TryValueInitialization(S, Entity, Kind, *this);
4641 // Handle default initialization.
4642 if (Kind.getKind() == InitializationKind::IK_Default) {
4643 TryDefaultInitialization(S, Entity, Kind, *this);
4647 // - If the destination type is an array of characters, an array of
4648 // char16_t, an array of char32_t, or an array of wchar_t, and the
4649 // initializer is a string literal, see 8.5.2.
4650 // - Otherwise, if the destination type is an array, the program is
4652 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
4653 if (Initializer && isa<VariableArrayType>(DestAT)) {
4654 SetFailed(FK_VariableLengthArrayHasInitializer);
4659 switch (IsStringInit(Initializer, DestAT, Context)) {
4661 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
4663 case SIF_NarrowStringIntoWideChar:
4664 SetFailed(FK_NarrowStringIntoWideCharArray);
4666 case SIF_WideStringIntoChar:
4667 SetFailed(FK_WideStringIntoCharArray);
4669 case SIF_IncompatWideStringIntoWideChar:
4670 SetFailed(FK_IncompatWideStringIntoWideChar);
4677 // Note: as an GNU C extension, we allow initialization of an
4678 // array from a compound literal that creates an array of the same
4679 // type, so long as the initializer has no side effects.
4680 if (!S.getLangOpts().CPlusPlus && Initializer &&
4681 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4682 Initializer->getType()->isArrayType()) {
4683 const ArrayType *SourceAT
4684 = Context.getAsArrayType(Initializer->getType());
4685 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
4686 SetFailed(FK_ArrayTypeMismatch);
4687 else if (Initializer->HasSideEffects(S.Context))
4688 SetFailed(FK_NonConstantArrayInit);
4690 AddArrayInitStep(DestType);
4693 // Note: as a GNU C++ extension, we allow list-initialization of a
4694 // class member of array type from a parenthesized initializer list.
4695 else if (S.getLangOpts().CPlusPlus &&
4696 Entity.getKind() == InitializedEntity::EK_Member &&
4697 Initializer && isa<InitListExpr>(Initializer)) {
4698 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4700 AddParenthesizedArrayInitStep(DestType);
4701 } else if (DestAT->getElementType()->isCharType())
4702 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
4703 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
4704 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
4706 SetFailed(FK_ArrayNeedsInitList);
4711 // Determine whether we should consider writeback conversions for
4713 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
4714 Entity.isParameterKind();
4716 // We're at the end of the line for C: it's either a write-back conversion
4717 // or it's a C assignment. There's no need to check anything else.
4718 if (!S.getLangOpts().CPlusPlus) {
4719 // If allowed, check whether this is an Objective-C writeback conversion.
4720 if (allowObjCWritebackConversion &&
4721 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
4725 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4728 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4731 // Handle initialization in C
4732 AddCAssignmentStep(DestType);
4733 MaybeProduceObjCObject(S, *this, Entity);
4737 assert(S.getLangOpts().CPlusPlus);
4739 // - If the destination type is a (possibly cv-qualified) class type:
4740 if (DestType->isRecordType()) {
4741 // - If the initialization is direct-initialization, or if it is
4742 // copy-initialization where the cv-unqualified version of the
4743 // source type is the same class as, or a derived class of, the
4744 // class of the destination, constructors are considered. [...]
4745 if (Kind.getKind() == InitializationKind::IK_Direct ||
4746 (Kind.getKind() == InitializationKind::IK_Copy &&
4747 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4748 S.IsDerivedFrom(SourceType, DestType))))
4749 TryConstructorInitialization(S, Entity, Kind, Args,
4751 // - Otherwise (i.e., for the remaining copy-initialization cases),
4752 // user-defined conversion sequences that can convert from the source
4753 // type to the destination type or (when a conversion function is
4754 // used) to a derived class thereof are enumerated as described in
4755 // 13.3.1.4, and the best one is chosen through overload resolution
4758 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
4759 TopLevelOfInitList);
4763 if (Args.size() > 1) {
4764 SetFailed(FK_TooManyInitsForScalar);
4767 assert(Args.size() == 1 && "Zero-argument case handled above");
4769 // - Otherwise, if the source type is a (possibly cv-qualified) class
4770 // type, conversion functions are considered.
4771 if (!SourceType.isNull() && SourceType->isRecordType()) {
4772 // For a conversion to _Atomic(T) from either T or a class type derived
4773 // from T, initialize the T object then convert to _Atomic type.
4774 bool NeedAtomicConversion = false;
4775 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
4776 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
4777 S.IsDerivedFrom(SourceType, Atomic->getValueType())) {
4778 DestType = Atomic->getValueType();
4779 NeedAtomicConversion = true;
4783 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
4784 TopLevelOfInitList);
4785 MaybeProduceObjCObject(S, *this, Entity);
4786 if (!Failed() && NeedAtomicConversion)
4787 AddAtomicConversionStep(Entity.getType());
4791 // - Otherwise, the initial value of the object being initialized is the
4792 // (possibly converted) value of the initializer expression. Standard
4793 // conversions (Clause 4) will be used, if necessary, to convert the
4794 // initializer expression to the cv-unqualified version of the
4795 // destination type; no user-defined conversions are considered.
4797 ImplicitConversionSequence ICS
4798 = S.TryImplicitConversion(Initializer, DestType,
4799 /*SuppressUserConversions*/true,
4800 /*AllowExplicitConversions*/ false,
4801 /*InOverloadResolution*/ false,
4802 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4803 allowObjCWritebackConversion);
4805 if (ICS.isStandard() &&
4806 ICS.Standard.Second == ICK_Writeback_Conversion) {
4807 // Objective-C ARC writeback conversion.
4809 // We should copy unless we're passing to an argument explicitly
4811 bool ShouldCopy = true;
4812 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4813 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4815 // If there was an lvalue adjustment, add it as a separate conversion.
4816 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4817 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4818 ImplicitConversionSequence LvalueICS;
4819 LvalueICS.setStandard();
4820 LvalueICS.Standard.setAsIdentityConversion();
4821 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4822 LvalueICS.Standard.First = ICS.Standard.First;
4823 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
4826 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
4827 } else if (ICS.isBad()) {
4829 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
4830 AddZeroInitializationStep(Entity.getType());
4831 } else if (Initializer->getType() == Context.OverloadTy &&
4832 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
4834 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4836 SetFailed(InitializationSequence::FK_ConversionFailed);
4838 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
4840 MaybeProduceObjCObject(S, *this, Entity);
4844 InitializationSequence::~InitializationSequence() {
4845 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
4846 StepEnd = Steps.end();
4847 Step != StepEnd; ++Step)
4851 //===----------------------------------------------------------------------===//
4852 // Perform initialization
4853 //===----------------------------------------------------------------------===//
4854 static Sema::AssignmentAction
4855 getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
4856 switch(Entity.getKind()) {
4857 case InitializedEntity::EK_Variable:
4858 case InitializedEntity::EK_New:
4859 case InitializedEntity::EK_Exception:
4860 case InitializedEntity::EK_Base:
4861 case InitializedEntity::EK_Delegating:
4862 return Sema::AA_Initializing;
4864 case InitializedEntity::EK_Parameter:
4865 if (Entity.getDecl() &&
4866 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4867 return Sema::AA_Sending;
4869 return Sema::AA_Passing;
4871 case InitializedEntity::EK_Parameter_CF_Audited:
4872 if (Entity.getDecl() &&
4873 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4874 return Sema::AA_Sending;
4876 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
4878 case InitializedEntity::EK_Result:
4879 return Sema::AA_Returning;
4881 case InitializedEntity::EK_Temporary:
4882 case InitializedEntity::EK_RelatedResult:
4883 // FIXME: Can we tell apart casting vs. converting?
4884 return Sema::AA_Casting;
4886 case InitializedEntity::EK_Member:
4887 case InitializedEntity::EK_ArrayElement:
4888 case InitializedEntity::EK_VectorElement:
4889 case InitializedEntity::EK_ComplexElement:
4890 case InitializedEntity::EK_BlockElement:
4891 case InitializedEntity::EK_LambdaCapture:
4892 case InitializedEntity::EK_CompoundLiteralInit:
4893 return Sema::AA_Initializing;
4896 llvm_unreachable("Invalid EntityKind!");
4899 /// \brief Whether we should bind a created object as a temporary when
4900 /// initializing the given entity.
4901 static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
4902 switch (Entity.getKind()) {
4903 case InitializedEntity::EK_ArrayElement:
4904 case InitializedEntity::EK_Member:
4905 case InitializedEntity::EK_Result:
4906 case InitializedEntity::EK_New:
4907 case InitializedEntity::EK_Variable:
4908 case InitializedEntity::EK_Base:
4909 case InitializedEntity::EK_Delegating:
4910 case InitializedEntity::EK_VectorElement:
4911 case InitializedEntity::EK_ComplexElement:
4912 case InitializedEntity::EK_Exception:
4913 case InitializedEntity::EK_BlockElement:
4914 case InitializedEntity::EK_LambdaCapture:
4915 case InitializedEntity::EK_CompoundLiteralInit:
4918 case InitializedEntity::EK_Parameter:
4919 case InitializedEntity::EK_Parameter_CF_Audited:
4920 case InitializedEntity::EK_Temporary:
4921 case InitializedEntity::EK_RelatedResult:
4925 llvm_unreachable("missed an InitializedEntity kind?");
4928 /// \brief Whether the given entity, when initialized with an object
4929 /// created for that initialization, requires destruction.
4930 static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4931 switch (Entity.getKind()) {
4932 case InitializedEntity::EK_Result:
4933 case InitializedEntity::EK_New:
4934 case InitializedEntity::EK_Base:
4935 case InitializedEntity::EK_Delegating:
4936 case InitializedEntity::EK_VectorElement:
4937 case InitializedEntity::EK_ComplexElement:
4938 case InitializedEntity::EK_BlockElement:
4939 case InitializedEntity::EK_LambdaCapture:
4942 case InitializedEntity::EK_Member:
4943 case InitializedEntity::EK_Variable:
4944 case InitializedEntity::EK_Parameter:
4945 case InitializedEntity::EK_Parameter_CF_Audited:
4946 case InitializedEntity::EK_Temporary:
4947 case InitializedEntity::EK_ArrayElement:
4948 case InitializedEntity::EK_Exception:
4949 case InitializedEntity::EK_CompoundLiteralInit:
4950 case InitializedEntity::EK_RelatedResult:
4954 llvm_unreachable("missed an InitializedEntity kind?");
4957 /// \brief Look for copy and move constructors and constructor templates, for
4958 /// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4959 static void LookupCopyAndMoveConstructors(Sema &S,
4960 OverloadCandidateSet &CandidateSet,
4961 CXXRecordDecl *Class,
4962 Expr *CurInitExpr) {
4963 DeclContext::lookup_result R = S.LookupConstructors(Class);
4964 // The container holding the constructors can under certain conditions
4965 // be changed while iterating (e.g. because of deserialization).
4966 // To be safe we copy the lookup results to a new container.
4967 SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
4968 for (SmallVectorImpl<NamedDecl *>::iterator
4969 CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
4971 CXXConstructorDecl *Constructor = nullptr;
4973 if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
4974 // Handle copy/moveconstructors, only.
4975 if (!Constructor || Constructor->isInvalidDecl() ||
4976 !Constructor->isCopyOrMoveConstructor() ||
4977 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4980 DeclAccessPair FoundDecl
4981 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4982 S.AddOverloadCandidate(Constructor, FoundDecl,
4983 CurInitExpr, CandidateSet);
4987 // Handle constructor templates.
4988 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
4989 if (ConstructorTmpl->isInvalidDecl())
4992 Constructor = cast<CXXConstructorDecl>(
4993 ConstructorTmpl->getTemplatedDecl());
4994 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4997 // FIXME: Do we need to limit this to copy-constructor-like
4999 DeclAccessPair FoundDecl
5000 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
5001 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, nullptr,
5002 CurInitExpr, CandidateSet, true);
5006 /// \brief Get the location at which initialization diagnostics should appear.
5007 static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
5008 Expr *Initializer) {
5009 switch (Entity.getKind()) {
5010 case InitializedEntity::EK_Result:
5011 return Entity.getReturnLoc();
5013 case InitializedEntity::EK_Exception:
5014 return Entity.getThrowLoc();
5016 case InitializedEntity::EK_Variable:
5017 return Entity.getDecl()->getLocation();
5019 case InitializedEntity::EK_LambdaCapture:
5020 return Entity.getCaptureLoc();
5022 case InitializedEntity::EK_ArrayElement:
5023 case InitializedEntity::EK_Member:
5024 case InitializedEntity::EK_Parameter:
5025 case InitializedEntity::EK_Parameter_CF_Audited:
5026 case InitializedEntity::EK_Temporary:
5027 case InitializedEntity::EK_New:
5028 case InitializedEntity::EK_Base:
5029 case InitializedEntity::EK_Delegating:
5030 case InitializedEntity::EK_VectorElement:
5031 case InitializedEntity::EK_ComplexElement:
5032 case InitializedEntity::EK_BlockElement:
5033 case InitializedEntity::EK_CompoundLiteralInit:
5034 case InitializedEntity::EK_RelatedResult:
5035 return Initializer->getLocStart();
5037 llvm_unreachable("missed an InitializedEntity kind?");
5040 /// \brief Make a (potentially elidable) temporary copy of the object
5041 /// provided by the given initializer by calling the appropriate copy
5044 /// \param S The Sema object used for type-checking.
5046 /// \param T The type of the temporary object, which must either be
5047 /// the type of the initializer expression or a superclass thereof.
5049 /// \param Entity The entity being initialized.
5051 /// \param CurInit The initializer expression.
5053 /// \param IsExtraneousCopy Whether this is an "extraneous" copy that
5054 /// is permitted in C++03 (but not C++0x) when binding a reference to
5057 /// \returns An expression that copies the initializer expression into
5058 /// a temporary object, or an error expression if a copy could not be
5060 static ExprResult CopyObject(Sema &S,
5062 const InitializedEntity &Entity,
5064 bool IsExtraneousCopy) {
5065 // Determine which class type we're copying to.
5066 Expr *CurInitExpr = (Expr *)CurInit.get();
5067 CXXRecordDecl *Class = nullptr;
5068 if (const RecordType *Record = T->getAs<RecordType>())
5069 Class = cast<CXXRecordDecl>(Record->getDecl());
5073 // C++0x [class.copy]p32:
5074 // When certain criteria are met, an implementation is allowed to
5075 // omit the copy/move construction of a class object, even if the
5076 // copy/move constructor and/or destructor for the object have
5077 // side effects. [...]
5078 // - when a temporary class object that has not been bound to a
5079 // reference (12.2) would be copied/moved to a class object
5080 // with the same cv-unqualified type, the copy/move operation
5081 // can be omitted by constructing the temporary object
5082 // directly into the target of the omitted copy/move
5084 // Note that the other three bullets are handled elsewhere. Copy
5085 // elision for return statements and throw expressions are handled as part
5086 // of constructor initialization, while copy elision for exception handlers
5087 // is handled by the run-time.
5088 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
5089 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
5091 // Make sure that the type we are copying is complete.
5092 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
5095 // Perform overload resolution using the class's copy/move constructors.
5096 // Only consider constructors and constructor templates. Per
5097 // C++0x [dcl.init]p16, second bullet to class types, this initialization
5098 // is direct-initialization.
5099 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5100 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
5102 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5104 OverloadCandidateSet::iterator Best;
5105 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
5109 case OR_No_Viable_Function:
5110 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
5111 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
5112 : diag::err_temp_copy_no_viable)
5113 << (int)Entity.getKind() << CurInitExpr->getType()
5114 << CurInitExpr->getSourceRange();
5115 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
5116 if (!IsExtraneousCopy || S.isSFINAEContext())
5121 S.Diag(Loc, diag::err_temp_copy_ambiguous)
5122 << (int)Entity.getKind() << CurInitExpr->getType()
5123 << CurInitExpr->getSourceRange();
5124 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
5128 S.Diag(Loc, diag::err_temp_copy_deleted)
5129 << (int)Entity.getKind() << CurInitExpr->getType()
5130 << CurInitExpr->getSourceRange();
5131 S.NoteDeletedFunction(Best->Function);
5135 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
5136 SmallVector<Expr*, 8> ConstructorArgs;
5137 CurInit.get(); // Ownership transferred into MultiExprArg, below.
5139 S.CheckConstructorAccess(Loc, Constructor, Entity,
5140 Best->FoundDecl.getAccess(), IsExtraneousCopy);
5142 if (IsExtraneousCopy) {
5143 // If this is a totally extraneous copy for C++03 reference
5144 // binding purposes, just return the original initialization
5145 // expression. We don't generate an (elided) copy operation here
5146 // because doing so would require us to pass down a flag to avoid
5147 // infinite recursion, where each step adds another extraneous,
5150 // Instantiate the default arguments of any extra parameters in
5151 // the selected copy constructor, as if we were going to create a
5152 // proper call to the copy constructor.
5153 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
5154 ParmVarDecl *Parm = Constructor->getParamDecl(I);
5155 if (S.RequireCompleteType(Loc, Parm->getType(),
5156 diag::err_call_incomplete_argument))
5159 // Build the default argument expression; we don't actually care
5160 // if this succeeds or not, because this routine will complain
5161 // if there was a problem.
5162 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5168 // Determine the arguments required to actually perform the
5169 // constructor call (we might have derived-to-base conversions, or
5170 // the copy constructor may have default arguments).
5171 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
5174 // Actually perform the constructor call.
5175 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
5177 HadMultipleCandidates,
5179 /*StdInitListInit*/ false,
5181 CXXConstructExpr::CK_Complete,
5184 // If we're supposed to bind temporaries, do so.
5185 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
5186 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
5190 /// \brief Check whether elidable copy construction for binding a reference to
5191 /// a temporary would have succeeded if we were building in C++98 mode, for
5193 static void CheckCXX98CompatAccessibleCopy(Sema &S,
5194 const InitializedEntity &Entity,
5195 Expr *CurInitExpr) {
5196 assert(S.getLangOpts().CPlusPlus11);
5198 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
5202 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
5203 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
5206 // Find constructors which would have been considered.
5207 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5208 LookupCopyAndMoveConstructors(
5209 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
5211 // Perform overload resolution.
5212 OverloadCandidateSet::iterator Best;
5213 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
5215 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
5216 << OR << (int)Entity.getKind() << CurInitExpr->getType()
5217 << CurInitExpr->getSourceRange();
5221 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
5222 Entity, Best->FoundDecl.getAccess(), Diag);
5223 // FIXME: Check default arguments as far as that's possible.
5226 case OR_No_Viable_Function:
5228 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
5233 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
5238 S.NoteDeletedFunction(Best->Function);
5243 void InitializationSequence::PrintInitLocationNote(Sema &S,
5244 const InitializedEntity &Entity) {
5245 if (Entity.isParameterKind() && Entity.getDecl()) {
5246 if (Entity.getDecl()->getLocation().isInvalid())
5249 if (Entity.getDecl()->getDeclName())
5250 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5251 << Entity.getDecl()->getDeclName();
5253 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5255 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
5256 Entity.getMethodDecl())
5257 S.Diag(Entity.getMethodDecl()->getLocation(),
5258 diag::note_method_return_type_change)
5259 << Entity.getMethodDecl()->getDeclName();
5262 static bool isReferenceBinding(const InitializationSequence::Step &s) {
5263 return s.Kind == InitializationSequence::SK_BindReference ||
5264 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
5267 /// Returns true if the parameters describe a constructor initialization of
5268 /// an explicit temporary object, e.g. "Point(x, y)".
5269 static bool isExplicitTemporary(const InitializedEntity &Entity,
5270 const InitializationKind &Kind,
5272 switch (Entity.getKind()) {
5273 case InitializedEntity::EK_Temporary:
5274 case InitializedEntity::EK_CompoundLiteralInit:
5275 case InitializedEntity::EK_RelatedResult:
5281 switch (Kind.getKind()) {
5282 case InitializationKind::IK_DirectList:
5284 // FIXME: Hack to work around cast weirdness.
5285 case InitializationKind::IK_Direct:
5286 case InitializationKind::IK_Value:
5287 return NumArgs != 1;
5294 PerformConstructorInitialization(Sema &S,
5295 const InitializedEntity &Entity,
5296 const InitializationKind &Kind,
5298 const InitializationSequence::Step& Step,
5299 bool &ConstructorInitRequiresZeroInit,
5300 bool IsListInitialization,
5301 bool IsStdInitListInitialization,
5302 SourceLocation LBraceLoc,
5303 SourceLocation RBraceLoc) {
5304 unsigned NumArgs = Args.size();
5305 CXXConstructorDecl *Constructor
5306 = cast<CXXConstructorDecl>(Step.Function.Function);
5307 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
5309 // Build a call to the selected constructor.
5310 SmallVector<Expr*, 8> ConstructorArgs;
5311 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
5312 ? Kind.getEqualLoc()
5313 : Kind.getLocation();
5315 if (Kind.getKind() == InitializationKind::IK_Default) {
5316 // Force even a trivial, implicit default constructor to be
5317 // semantically checked. We do this explicitly because we don't build
5318 // the definition for completely trivial constructors.
5319 assert(Constructor->getParent() && "No parent class for constructor.");
5320 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
5321 Constructor->isTrivial() && !Constructor->isUsed(false))
5322 S.DefineImplicitDefaultConstructor(Loc, Constructor);
5325 ExprResult CurInit((Expr *)nullptr);
5327 // C++ [over.match.copy]p1:
5328 // - When initializing a temporary to be bound to the first parameter
5329 // of a constructor that takes a reference to possibly cv-qualified
5330 // T as its first argument, called with a single argument in the
5331 // context of direct-initialization, explicit conversion functions
5332 // are also considered.
5333 bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
5335 Constructor->isCopyOrMoveConstructor();
5337 // Determine the arguments required to actually perform the constructor
5339 if (S.CompleteConstructorCall(Constructor, Args,
5340 Loc, ConstructorArgs,
5342 IsListInitialization))
5346 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
5347 // An explicitly-constructed temporary, e.g., X(1, 2).
5348 S.MarkFunctionReferenced(Loc, Constructor);
5349 if (S.DiagnoseUseOfDecl(Constructor, Loc))
5352 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5354 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
5355 SourceRange ParenOrBraceRange =
5356 (Kind.getKind() == InitializationKind::IK_DirectList)
5357 ? SourceRange(LBraceLoc, RBraceLoc)
5358 : Kind.getParenRange();
5360 CurInit = new (S.Context) CXXTemporaryObjectExpr(
5361 S.Context, Constructor, TSInfo, ConstructorArgs, ParenOrBraceRange,
5362 HadMultipleCandidates, IsListInitialization,
5363 IsStdInitListInitialization, ConstructorInitRequiresZeroInit);
5365 CXXConstructExpr::ConstructionKind ConstructKind =
5366 CXXConstructExpr::CK_Complete;
5368 if (Entity.getKind() == InitializedEntity::EK_Base) {
5369 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
5370 CXXConstructExpr::CK_VirtualBase :
5371 CXXConstructExpr::CK_NonVirtualBase;
5372 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
5373 ConstructKind = CXXConstructExpr::CK_Delegating;
5376 // Only get the parenthesis or brace range if it is a list initialization or
5377 // direct construction.
5378 SourceRange ParenOrBraceRange;
5379 if (IsListInitialization)
5380 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
5381 else if (Kind.getKind() == InitializationKind::IK_Direct)
5382 ParenOrBraceRange = Kind.getParenRange();
5384 // If the entity allows NRVO, mark the construction as elidable
5386 if (Entity.allowsNRVO())
5387 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5388 Constructor, /*Elidable=*/true,
5390 HadMultipleCandidates,
5391 IsListInitialization,
5392 IsStdInitListInitialization,
5393 ConstructorInitRequiresZeroInit,
5397 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5400 HadMultipleCandidates,
5401 IsListInitialization,
5402 IsStdInitListInitialization,
5403 ConstructorInitRequiresZeroInit,
5407 if (CurInit.isInvalid())
5410 // Only check access if all of that succeeded.
5411 S.CheckConstructorAccess(Loc, Constructor, Entity,
5412 Step.Function.FoundDecl.getAccess());
5413 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
5416 if (shouldBindAsTemporary(Entity))
5417 CurInit = S.MaybeBindToTemporary(CurInit.get());
5422 /// Determine whether the specified InitializedEntity definitely has a lifetime
5423 /// longer than the current full-expression. Conservatively returns false if
5426 InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
5427 const InitializedEntity *Top = &Entity;
5428 while (Top->getParent())
5429 Top = Top->getParent();
5431 switch (Top->getKind()) {
5432 case InitializedEntity::EK_Variable:
5433 case InitializedEntity::EK_Result:
5434 case InitializedEntity::EK_Exception:
5435 case InitializedEntity::EK_Member:
5436 case InitializedEntity::EK_New:
5437 case InitializedEntity::EK_Base:
5438 case InitializedEntity::EK_Delegating:
5441 case InitializedEntity::EK_ArrayElement:
5442 case InitializedEntity::EK_VectorElement:
5443 case InitializedEntity::EK_BlockElement:
5444 case InitializedEntity::EK_ComplexElement:
5445 // Could not determine what the full initialization is. Assume it might not
5446 // outlive the full-expression.
5449 case InitializedEntity::EK_Parameter:
5450 case InitializedEntity::EK_Parameter_CF_Audited:
5451 case InitializedEntity::EK_Temporary:
5452 case InitializedEntity::EK_LambdaCapture:
5453 case InitializedEntity::EK_CompoundLiteralInit:
5454 case InitializedEntity::EK_RelatedResult:
5455 // The entity being initialized might not outlive the full-expression.
5459 llvm_unreachable("unknown entity kind");
5462 /// Determine the declaration which an initialized entity ultimately refers to,
5463 /// for the purpose of lifetime-extending a temporary bound to a reference in
5464 /// the initialization of \p Entity.
5465 static const InitializedEntity *getEntityForTemporaryLifetimeExtension(
5466 const InitializedEntity *Entity,
5467 const InitializedEntity *FallbackDecl = nullptr) {
5468 // C++11 [class.temporary]p5:
5469 switch (Entity->getKind()) {
5470 case InitializedEntity::EK_Variable:
5471 // The temporary [...] persists for the lifetime of the reference
5474 case InitializedEntity::EK_Member:
5475 // For subobjects, we look at the complete object.
5476 if (Entity->getParent())
5477 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
5481 // -- A temporary bound to a reference member in a constructor's
5482 // ctor-initializer persists until the constructor exits.
5485 case InitializedEntity::EK_Parameter:
5486 case InitializedEntity::EK_Parameter_CF_Audited:
5487 // -- A temporary bound to a reference parameter in a function call
5488 // persists until the completion of the full-expression containing
5490 case InitializedEntity::EK_Result:
5491 // -- The lifetime of a temporary bound to the returned value in a
5492 // function return statement is not extended; the temporary is
5493 // destroyed at the end of the full-expression in the return statement.
5494 case InitializedEntity::EK_New:
5495 // -- A temporary bound to a reference in a new-initializer persists
5496 // until the completion of the full-expression containing the
5500 case InitializedEntity::EK_Temporary:
5501 case InitializedEntity::EK_CompoundLiteralInit:
5502 case InitializedEntity::EK_RelatedResult:
5503 // We don't yet know the storage duration of the surrounding temporary.
5504 // Assume it's got full-expression duration for now, it will patch up our
5505 // storage duration if that's not correct.
5508 case InitializedEntity::EK_ArrayElement:
5509 // For subobjects, we look at the complete object.
5510 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
5513 case InitializedEntity::EK_Base:
5514 case InitializedEntity::EK_Delegating:
5515 // We can reach this case for aggregate initialization in a constructor:
5516 // struct A { int &&r; };
5517 // struct B : A { B() : A{0} {} };
5518 // In this case, use the innermost field decl as the context.
5519 return FallbackDecl;
5521 case InitializedEntity::EK_BlockElement:
5522 case InitializedEntity::EK_LambdaCapture:
5523 case InitializedEntity::EK_Exception:
5524 case InitializedEntity::EK_VectorElement:
5525 case InitializedEntity::EK_ComplexElement:
5528 llvm_unreachable("unknown entity kind");
5531 static void performLifetimeExtension(Expr *Init,
5532 const InitializedEntity *ExtendingEntity);
5534 /// Update a glvalue expression that is used as the initializer of a reference
5535 /// to note that its lifetime is extended.
5536 /// \return \c true if any temporary had its lifetime extended.
5538 performReferenceExtension(Expr *Init,
5539 const InitializedEntity *ExtendingEntity) {
5540 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5541 if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
5542 // This is just redundant braces around an initializer. Step over it.
5543 Init = ILE->getInit(0);
5547 // Walk past any constructs which we can lifetime-extend across.
5552 // Step over any subobject adjustments; we may have a materialized
5553 // temporary inside them.
5554 SmallVector<const Expr *, 2> CommaLHSs;
5555 SmallVector<SubobjectAdjustment, 2> Adjustments;
5556 Init = const_cast<Expr *>(
5557 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5559 // Per current approach for DR1376, look through casts to reference type
5560 // when performing lifetime extension.
5561 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
5562 if (CE->getSubExpr()->isGLValue())
5563 Init = CE->getSubExpr();
5565 // FIXME: Per DR1213, subscripting on an array temporary produces an xvalue.
5566 // It's unclear if binding a reference to that xvalue extends the array
5568 } while (Init != Old);
5570 if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
5571 // Update the storage duration of the materialized temporary.
5572 // FIXME: Rebuild the expression instead of mutating it.
5573 ME->setExtendingDecl(ExtendingEntity->getDecl(),
5574 ExtendingEntity->allocateManglingNumber());
5575 performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingEntity);
5582 /// Update a prvalue expression that is going to be materialized as a
5583 /// lifetime-extended temporary.
5584 static void performLifetimeExtension(Expr *Init,
5585 const InitializedEntity *ExtendingEntity) {
5586 // Dig out the expression which constructs the extended temporary.
5587 SmallVector<const Expr *, 2> CommaLHSs;
5588 SmallVector<SubobjectAdjustment, 2> Adjustments;
5589 Init = const_cast<Expr *>(
5590 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5592 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
5593 Init = BTE->getSubExpr();
5595 if (CXXStdInitializerListExpr *ILE =
5596 dyn_cast<CXXStdInitializerListExpr>(Init)) {
5597 performReferenceExtension(ILE->getSubExpr(), ExtendingEntity);
5601 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5602 if (ILE->getType()->isArrayType()) {
5603 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
5604 performLifetimeExtension(ILE->getInit(I), ExtendingEntity);
5608 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
5609 assert(RD->isAggregate() && "aggregate init on non-aggregate");
5611 // If we lifetime-extend a braced initializer which is initializing an
5612 // aggregate, and that aggregate contains reference members which are
5613 // bound to temporaries, those temporaries are also lifetime-extended.
5614 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
5615 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
5616 performReferenceExtension(ILE->getInit(0), ExtendingEntity);
5619 for (const auto *I : RD->fields()) {
5620 if (Index >= ILE->getNumInits())
5622 if (I->isUnnamedBitfield())
5624 Expr *SubInit = ILE->getInit(Index);
5625 if (I->getType()->isReferenceType())
5626 performReferenceExtension(SubInit, ExtendingEntity);
5627 else if (isa<InitListExpr>(SubInit) ||
5628 isa<CXXStdInitializerListExpr>(SubInit))
5629 // This may be either aggregate-initialization of a member or
5630 // initialization of a std::initializer_list object. Either way,
5631 // we should recursively lifetime-extend that initializer.
5632 performLifetimeExtension(SubInit, ExtendingEntity);
5640 static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
5641 const Expr *Init, bool IsInitializerList,
5642 const ValueDecl *ExtendingDecl) {
5643 // Warn if a field lifetime-extends a temporary.
5644 if (isa<FieldDecl>(ExtendingDecl)) {
5645 if (IsInitializerList) {
5646 S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
5647 << /*at end of constructor*/true;
5651 bool IsSubobjectMember = false;
5652 for (const InitializedEntity *Ent = Entity.getParent(); Ent;
5653 Ent = Ent->getParent()) {
5654 if (Ent->getKind() != InitializedEntity::EK_Base) {
5655 IsSubobjectMember = true;
5659 S.Diag(Init->getExprLoc(),
5660 diag::warn_bind_ref_member_to_temporary)
5661 << ExtendingDecl << Init->getSourceRange()
5662 << IsSubobjectMember << IsInitializerList;
5663 if (IsSubobjectMember)
5664 S.Diag(ExtendingDecl->getLocation(),
5665 diag::note_ref_subobject_of_member_declared_here);
5667 S.Diag(ExtendingDecl->getLocation(),
5668 diag::note_ref_or_ptr_member_declared_here)
5669 << /*is pointer*/false;
5673 static void DiagnoseNarrowingInInitList(Sema &S,
5674 const ImplicitConversionSequence &ICS,
5675 QualType PreNarrowingType,
5676 QualType EntityType,
5677 const Expr *PostInit);
5680 InitializationSequence::Perform(Sema &S,
5681 const InitializedEntity &Entity,
5682 const InitializationKind &Kind,
5684 QualType *ResultType) {
5686 Diagnose(S, Entity, Kind, Args);
5690 if (getKind() == DependentSequence) {
5691 // If the declaration is a non-dependent, incomplete array type
5692 // that has an initializer, then its type will be completed once
5693 // the initializer is instantiated.
5694 if (ResultType && !Entity.getType()->isDependentType() &&
5696 QualType DeclType = Entity.getType();
5697 if (const IncompleteArrayType *ArrayT
5698 = S.Context.getAsIncompleteArrayType(DeclType)) {
5699 // FIXME: We don't currently have the ability to accurately
5700 // compute the length of an initializer list without
5701 // performing full type-checking of the initializer list
5702 // (since we have to determine where braces are implicitly
5703 // introduced and such). So, we fall back to making the array
5704 // type a dependently-sized array type with no specified
5706 if (isa<InitListExpr>((Expr *)Args[0])) {
5707 SourceRange Brackets;
5709 // Scavange the location of the brackets from the entity, if we can.
5710 if (DeclaratorDecl *DD = Entity.getDecl()) {
5711 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
5712 TypeLoc TL = TInfo->getTypeLoc();
5713 if (IncompleteArrayTypeLoc ArrayLoc =
5714 TL.getAs<IncompleteArrayTypeLoc>())
5715 Brackets = ArrayLoc.getBracketsRange();
5720 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
5721 /*NumElts=*/nullptr,
5722 ArrayT->getSizeModifier(),
5723 ArrayT->getIndexTypeCVRQualifiers(),
5729 if (Kind.getKind() == InitializationKind::IK_Direct &&
5730 !Kind.isExplicitCast()) {
5731 // Rebuild the ParenListExpr.
5732 SourceRange ParenRange = Kind.getParenRange();
5733 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
5736 assert(Kind.getKind() == InitializationKind::IK_Copy ||
5737 Kind.isExplicitCast() ||
5738 Kind.getKind() == InitializationKind::IK_DirectList);
5739 return ExprResult(Args[0]);
5742 // No steps means no initialization.
5744 return ExprResult((Expr *)nullptr);
5746 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
5747 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
5748 !Entity.isParameterKind()) {
5749 // Produce a C++98 compatibility warning if we are initializing a reference
5750 // from an initializer list. For parameters, we produce a better warning
5752 Expr *Init = Args[0];
5753 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
5754 << Init->getSourceRange();
5757 // Diagnose cases where we initialize a pointer to an array temporary, and the
5758 // pointer obviously outlives the temporary.
5759 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
5760 Entity.getType()->isPointerType() &&
5761 InitializedEntityOutlivesFullExpression(Entity)) {
5762 Expr *Init = Args[0];
5763 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
5764 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
5765 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
5766 << Init->getSourceRange();
5769 QualType DestType = Entity.getType().getNonReferenceType();
5770 // FIXME: Ugly hack around the fact that Entity.getType() is not
5771 // the same as Entity.getDecl()->getType() in cases involving type merging,
5772 // and we want latter when it makes sense.
5774 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
5777 ExprResult CurInit((Expr *)nullptr);
5779 // For initialization steps that start with a single initializer,
5780 // grab the only argument out the Args and place it into the "current"
5782 switch (Steps.front().Kind) {
5783 case SK_ResolveAddressOfOverloadedFunction:
5784 case SK_CastDerivedToBaseRValue:
5785 case SK_CastDerivedToBaseXValue:
5786 case SK_CastDerivedToBaseLValue:
5787 case SK_BindReference:
5788 case SK_BindReferenceToTemporary:
5789 case SK_ExtraneousCopyToTemporary:
5790 case SK_UserConversion:
5791 case SK_QualificationConversionLValue:
5792 case SK_QualificationConversionXValue:
5793 case SK_QualificationConversionRValue:
5794 case SK_AtomicConversion:
5795 case SK_LValueToRValue:
5796 case SK_ConversionSequence:
5797 case SK_ConversionSequenceNoNarrowing:
5798 case SK_ListInitialization:
5799 case SK_UnwrapInitList:
5800 case SK_RewrapInitList:
5801 case SK_CAssignment:
5803 case SK_ObjCObjectConversion:
5805 case SK_ParenthesizedArrayInit:
5806 case SK_PassByIndirectCopyRestore:
5807 case SK_PassByIndirectRestore:
5808 case SK_ProduceObjCObject:
5809 case SK_StdInitializerList:
5810 case SK_OCLSamplerInit:
5811 case SK_OCLZeroEvent: {
5812 assert(Args.size() == 1);
5814 if (!CurInit.get()) return ExprError();
5818 case SK_ConstructorInitialization:
5819 case SK_ConstructorInitializationFromList:
5820 case SK_StdInitializerListConstructorCall:
5821 case SK_ZeroInitialization:
5825 // Walk through the computed steps for the initialization sequence,
5826 // performing the specified conversions along the way.
5827 bool ConstructorInitRequiresZeroInit = false;
5828 for (step_iterator Step = step_begin(), StepEnd = step_end();
5829 Step != StepEnd; ++Step) {
5830 if (CurInit.isInvalid())
5833 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
5835 switch (Step->Kind) {
5836 case SK_ResolveAddressOfOverloadedFunction:
5837 // Overload resolution determined which function invoke; update the
5838 // initializer to reflect that choice.
5839 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
5840 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
5842 CurInit = S.FixOverloadedFunctionReference(CurInit,
5843 Step->Function.FoundDecl,
5844 Step->Function.Function);
5847 case SK_CastDerivedToBaseRValue:
5848 case SK_CastDerivedToBaseXValue:
5849 case SK_CastDerivedToBaseLValue: {
5850 // We have a derived-to-base cast that produces either an rvalue or an
5851 // lvalue. Perform that cast.
5853 CXXCastPath BasePath;
5855 // Casts to inaccessible base classes are allowed with C-style casts.
5856 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
5857 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
5858 CurInit.get()->getLocStart(),
5859 CurInit.get()->getSourceRange(),
5860 &BasePath, IgnoreBaseAccess))
5863 if (S.BasePathInvolvesVirtualBase(BasePath)) {
5864 QualType T = SourceType;
5865 if (const PointerType *Pointer = T->getAs<PointerType>())
5866 T = Pointer->getPointeeType();
5867 if (const RecordType *RecordTy = T->getAs<RecordType>())
5868 S.MarkVTableUsed(CurInit.get()->getLocStart(),
5869 cast<CXXRecordDecl>(RecordTy->getDecl()));
5873 Step->Kind == SK_CastDerivedToBaseLValue ?
5875 (Step->Kind == SK_CastDerivedToBaseXValue ?
5879 ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
5880 CurInit.get(), &BasePath, VK);
5884 case SK_BindReference:
5885 // References cannot bind to bit-fields (C++ [dcl.init.ref]p5).
5886 if (CurInit.get()->refersToBitField()) {
5887 // We don't necessarily have an unambiguous source bit-field.
5888 FieldDecl *BitField = CurInit.get()->getSourceBitField();
5889 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
5890 << Entity.getType().isVolatileQualified()
5891 << (BitField ? BitField->getDeclName() : DeclarationName())
5892 << (BitField != nullptr)
5893 << CurInit.get()->getSourceRange();
5895 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
5900 if (CurInit.get()->refersToVectorElement()) {
5901 // References cannot bind to vector elements.
5902 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5903 << Entity.getType().isVolatileQualified()
5904 << CurInit.get()->getSourceRange();
5905 PrintInitLocationNote(S, Entity);
5909 // Reference binding does not have any corresponding ASTs.
5911 // Check exception specifications
5912 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
5915 // Even though we didn't materialize a temporary, the binding may still
5916 // extend the lifetime of a temporary. This happens if we bind a reference
5917 // to the result of a cast to reference type.
5918 if (const InitializedEntity *ExtendingEntity =
5919 getEntityForTemporaryLifetimeExtension(&Entity))
5920 if (performReferenceExtension(CurInit.get(), ExtendingEntity))
5921 warnOnLifetimeExtension(S, Entity, CurInit.get(),
5922 /*IsInitializerList=*/false,
5923 ExtendingEntity->getDecl());
5927 case SK_BindReferenceToTemporary: {
5928 // Make sure the "temporary" is actually an rvalue.
5929 assert(CurInit.get()->isRValue() && "not a temporary");
5931 // Check exception specifications
5932 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
5935 // Materialize the temporary into memory.
5936 MaterializeTemporaryExpr *MTE = new (S.Context) MaterializeTemporaryExpr(
5937 Entity.getType().getNonReferenceType(), CurInit.get(),
5938 Entity.getType()->isLValueReferenceType());
5940 // Maybe lifetime-extend the temporary's subobjects to match the
5941 // entity's lifetime.
5942 if (const InitializedEntity *ExtendingEntity =
5943 getEntityForTemporaryLifetimeExtension(&Entity))
5944 if (performReferenceExtension(MTE, ExtendingEntity))
5945 warnOnLifetimeExtension(S, Entity, CurInit.get(), /*IsInitializerList=*/false,
5946 ExtendingEntity->getDecl());
5948 // If we're binding to an Objective-C object that has lifetime, we
5949 // need cleanups. Likewise if we're extending this temporary to automatic
5950 // storage duration -- we need to register its cleanup during the
5951 // full-expression's cleanups.
5952 if ((S.getLangOpts().ObjCAutoRefCount &&
5953 MTE->getType()->isObjCLifetimeType()) ||
5954 (MTE->getStorageDuration() == SD_Automatic &&
5955 MTE->getType().isDestructedType()))
5956 S.ExprNeedsCleanups = true;
5962 case SK_ExtraneousCopyToTemporary:
5963 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
5964 /*IsExtraneousCopy=*/true);
5967 case SK_UserConversion: {
5968 // We have a user-defined conversion that invokes either a constructor
5969 // or a conversion function.
5971 bool IsCopy = false;
5972 FunctionDecl *Fn = Step->Function.Function;
5973 DeclAccessPair FoundFn = Step->Function.FoundDecl;
5974 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
5975 bool CreatedObject = false;
5976 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
5977 // Build a call to the selected constructor.
5978 SmallVector<Expr*, 8> ConstructorArgs;
5979 SourceLocation Loc = CurInit.get()->getLocStart();
5980 CurInit.get(); // Ownership transferred into MultiExprArg, below.
5982 // Determine the arguments required to actually perform the constructor
5984 Expr *Arg = CurInit.get();
5985 if (S.CompleteConstructorCall(Constructor,
5986 MultiExprArg(&Arg, 1),
5987 Loc, ConstructorArgs))
5990 // Build an expression that constructs a temporary.
5991 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
5993 HadMultipleCandidates,
5995 /*StdInitListInit*/ false,
5997 CXXConstructExpr::CK_Complete,
5999 if (CurInit.isInvalid())
6002 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
6003 FoundFn.getAccess());
6004 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6007 CastKind = CK_ConstructorConversion;
6008 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
6009 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
6010 S.IsDerivedFrom(SourceType, Class))
6013 CreatedObject = true;
6015 // Build a call to the conversion function.
6016 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
6017 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
6019 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6022 // FIXME: Should we move this initialization into a separate
6023 // derived-to-base conversion? I believe the answer is "no", because
6024 // we don't want to turn off access control here for c-style casts.
6025 ExprResult CurInitExprRes =
6026 S.PerformObjectArgumentInitialization(CurInit.get(),
6027 /*Qualifier=*/nullptr,
6028 FoundFn, Conversion);
6029 if(CurInitExprRes.isInvalid())
6031 CurInit = CurInitExprRes;
6033 // Build the actual call to the conversion function.
6034 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
6035 HadMultipleCandidates);
6036 if (CurInit.isInvalid() || !CurInit.get())
6039 CastKind = CK_UserDefinedConversion;
6041 CreatedObject = Conversion->getReturnType()->isRecordType();
6044 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
6045 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
6047 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
6048 QualType T = CurInit.get()->getType();
6049 if (const RecordType *Record = T->getAs<RecordType>()) {
6050 CXXDestructorDecl *Destructor
6051 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
6052 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
6053 S.PDiag(diag::err_access_dtor_temp) << T);
6054 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
6055 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
6060 CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
6061 CastKind, CurInit.get(), nullptr,
6062 CurInit.get()->getValueKind());
6063 if (MaybeBindToTemp)
6064 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
6066 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
6067 CurInit, /*IsExtraneousCopy=*/false);
6071 case SK_QualificationConversionLValue:
6072 case SK_QualificationConversionXValue:
6073 case SK_QualificationConversionRValue: {
6074 // Perform a qualification conversion; these can never go wrong.
6076 Step->Kind == SK_QualificationConversionLValue ?
6078 (Step->Kind == SK_QualificationConversionXValue ?
6081 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK);
6085 case SK_AtomicConversion: {
6086 assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic");
6087 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
6088 CK_NonAtomicToAtomic, VK_RValue);
6092 case SK_LValueToRValue: {
6093 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
6094 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
6095 CK_LValueToRValue, CurInit.get(),
6096 /*BasePath=*/nullptr, VK_RValue);
6100 case SK_ConversionSequence:
6101 case SK_ConversionSequenceNoNarrowing: {
6102 Sema::CheckedConversionKind CCK
6103 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
6104 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
6105 : Kind.isExplicitCast()? Sema::CCK_OtherCast
6106 : Sema::CCK_ImplicitConversion;
6107 ExprResult CurInitExprRes =
6108 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
6109 getAssignmentAction(Entity), CCK);
6110 if (CurInitExprRes.isInvalid())
6112 CurInit = CurInitExprRes;
6114 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
6115 S.getLangOpts().CPlusPlus && !CurInit.get()->isValueDependent())
6116 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
6121 case SK_ListInitialization: {
6122 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
6123 // If we're not initializing the top-level entity, we need to create an
6124 // InitializeTemporary entity for our target type.
6125 QualType Ty = Step->Type;
6126 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
6127 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
6128 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
6129 InitListChecker PerformInitList(S, InitEntity,
6130 InitList, Ty, /*VerifyOnly=*/false);
6131 if (PerformInitList.HadError())
6134 // Hack: We must update *ResultType if available in order to set the
6135 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
6136 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
6138 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
6139 if ((*ResultType)->isRValueReferenceType())
6140 Ty = S.Context.getRValueReferenceType(Ty);
6141 else if ((*ResultType)->isLValueReferenceType())
6142 Ty = S.Context.getLValueReferenceType(Ty,
6143 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
6147 InitListExpr *StructuredInitList =
6148 PerformInitList.getFullyStructuredList();
6150 CurInit = shouldBindAsTemporary(InitEntity)
6151 ? S.MaybeBindToTemporary(StructuredInitList)
6152 : StructuredInitList;
6156 case SK_ConstructorInitializationFromList: {
6157 // When an initializer list is passed for a parameter of type "reference
6158 // to object", we don't get an EK_Temporary entity, but instead an
6159 // EK_Parameter entity with reference type.
6160 // FIXME: This is a hack. What we really should do is create a user
6161 // conversion step for this case, but this makes it considerably more
6162 // complicated. For now, this will do.
6163 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6164 Entity.getType().getNonReferenceType());
6165 bool UseTemporary = Entity.getType()->isReferenceType();
6166 assert(Args.size() == 1 && "expected a single argument for list init");
6167 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
6168 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
6169 << InitList->getSourceRange();
6170 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
6171 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
6174 ConstructorInitRequiresZeroInit,
6175 /*IsListInitialization*/true,
6176 /*IsStdInitListInit*/false,
6177 InitList->getLBraceLoc(),
6178 InitList->getRBraceLoc());
6182 case SK_UnwrapInitList:
6183 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
6186 case SK_RewrapInitList: {
6187 Expr *E = CurInit.get();
6188 InitListExpr *Syntactic = Step->WrappingSyntacticList;
6189 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
6190 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
6191 ILE->setSyntacticForm(Syntactic);
6192 ILE->setType(E->getType());
6193 ILE->setValueKind(E->getValueKind());
6198 case SK_ConstructorInitialization:
6199 case SK_StdInitializerListConstructorCall: {
6200 // When an initializer list is passed for a parameter of type "reference
6201 // to object", we don't get an EK_Temporary entity, but instead an
6202 // EK_Parameter entity with reference type.
6203 // FIXME: This is a hack. What we really should do is create a user
6204 // conversion step for this case, but this makes it considerably more
6205 // complicated. For now, this will do.
6206 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6207 Entity.getType().getNonReferenceType());
6208 bool UseTemporary = Entity.getType()->isReferenceType();
6209 bool IsStdInitListInit =
6210 Step->Kind == SK_StdInitializerListConstructorCall;
6211 CurInit = PerformConstructorInitialization(
6212 S, UseTemporary ? TempEntity : Entity, Kind, Args, *Step,
6213 ConstructorInitRequiresZeroInit,
6214 /*IsListInitialization*/IsStdInitListInit,
6215 /*IsStdInitListInitialization*/IsStdInitListInit,
6216 /*LBraceLoc*/SourceLocation(),
6217 /*RBraceLoc*/SourceLocation());
6221 case SK_ZeroInitialization: {
6222 step_iterator NextStep = Step;
6224 if (NextStep != StepEnd &&
6225 (NextStep->Kind == SK_ConstructorInitialization ||
6226 NextStep->Kind == SK_ConstructorInitializationFromList)) {
6227 // The need for zero-initialization is recorded directly into
6228 // the call to the object's constructor within the next step.
6229 ConstructorInitRequiresZeroInit = true;
6230 } else if (Kind.getKind() == InitializationKind::IK_Value &&
6231 S.getLangOpts().CPlusPlus &&
6232 !Kind.isImplicitValueInit()) {
6233 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6235 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
6236 Kind.getRange().getBegin());
6238 CurInit = new (S.Context) CXXScalarValueInitExpr(
6239 TSInfo->getType().getNonLValueExprType(S.Context), TSInfo,
6240 Kind.getRange().getEnd());
6242 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
6247 case SK_CAssignment: {
6248 QualType SourceType = CurInit.get()->getType();
6249 ExprResult Result = CurInit;
6250 Sema::AssignConvertType ConvTy =
6251 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
6252 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
6253 if (Result.isInvalid())
6257 // If this is a call, allow conversion to a transparent union.
6258 ExprResult CurInitExprRes = CurInit;
6259 if (ConvTy != Sema::Compatible &&
6260 Entity.isParameterKind() &&
6261 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
6262 == Sema::Compatible)
6263 ConvTy = Sema::Compatible;
6264 if (CurInitExprRes.isInvalid())
6266 CurInit = CurInitExprRes;
6269 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
6270 Step->Type, SourceType,
6272 getAssignmentAction(Entity, true),
6274 PrintInitLocationNote(S, Entity);
6276 } else if (Complained)
6277 PrintInitLocationNote(S, Entity);
6281 case SK_StringInit: {
6282 QualType Ty = Step->Type;
6283 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
6284 S.Context.getAsArrayType(Ty), S);
6288 case SK_ObjCObjectConversion:
6289 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
6290 CK_ObjCObjectLValueCast,
6291 CurInit.get()->getValueKind());
6295 // Okay: we checked everything before creating this step. Note that
6296 // this is a GNU extension.
6297 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
6298 << Step->Type << CurInit.get()->getType()
6299 << CurInit.get()->getSourceRange();
6301 // If the destination type is an incomplete array type, update the
6302 // type accordingly.
6304 if (const IncompleteArrayType *IncompleteDest
6305 = S.Context.getAsIncompleteArrayType(Step->Type)) {
6306 if (const ConstantArrayType *ConstantSource
6307 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
6308 *ResultType = S.Context.getConstantArrayType(
6309 IncompleteDest->getElementType(),
6310 ConstantSource->getSize(),
6311 ArrayType::Normal, 0);
6317 case SK_ParenthesizedArrayInit:
6318 // Okay: we checked everything before creating this step. Note that
6319 // this is a GNU extension.
6320 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
6321 << CurInit.get()->getSourceRange();
6324 case SK_PassByIndirectCopyRestore:
6325 case SK_PassByIndirectRestore:
6326 checkIndirectCopyRestoreSource(S, CurInit.get());
6327 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
6328 CurInit.get(), Step->Type,
6329 Step->Kind == SK_PassByIndirectCopyRestore);
6332 case SK_ProduceObjCObject:
6334 ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
6335 CurInit.get(), nullptr, VK_RValue);
6338 case SK_StdInitializerList: {
6339 S.Diag(CurInit.get()->getExprLoc(),
6340 diag::warn_cxx98_compat_initializer_list_init)
6341 << CurInit.get()->getSourceRange();
6343 // Materialize the temporary into memory.
6344 MaterializeTemporaryExpr *MTE = new (S.Context)
6345 MaterializeTemporaryExpr(CurInit.get()->getType(), CurInit.get(),
6346 /*BoundToLvalueReference=*/false);
6348 // Maybe lifetime-extend the array temporary's subobjects to match the
6349 // entity's lifetime.
6350 if (const InitializedEntity *ExtendingEntity =
6351 getEntityForTemporaryLifetimeExtension(&Entity))
6352 if (performReferenceExtension(MTE, ExtendingEntity))
6353 warnOnLifetimeExtension(S, Entity, CurInit.get(),
6354 /*IsInitializerList=*/true,
6355 ExtendingEntity->getDecl());
6357 // Wrap it in a construction of a std::initializer_list<T>.
6358 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
6360 // Bind the result, in case the library has given initializer_list a
6361 // non-trivial destructor.
6362 if (shouldBindAsTemporary(Entity))
6363 CurInit = S.MaybeBindToTemporary(CurInit.get());
6367 case SK_OCLSamplerInit: {
6368 assert(Step->Type->isSamplerT() &&
6369 "Sampler initialization on non-sampler type.");
6371 QualType SourceType = CurInit.get()->getType();
6373 if (Entity.isParameterKind()) {
6374 if (!SourceType->isSamplerT())
6375 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
6377 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
6378 llvm_unreachable("Invalid EntityKind!");
6383 case SK_OCLZeroEvent: {
6384 assert(Step->Type->isEventT() &&
6385 "Event initialization on non-event type.");
6387 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
6389 CurInit.get()->getValueKind());
6395 // Diagnose non-fatal problems with the completed initialization.
6396 if (Entity.getKind() == InitializedEntity::EK_Member &&
6397 cast<FieldDecl>(Entity.getDecl())->isBitField())
6398 S.CheckBitFieldInitialization(Kind.getLocation(),
6399 cast<FieldDecl>(Entity.getDecl()),
6405 /// Somewhere within T there is an uninitialized reference subobject.
6406 /// Dig it out and diagnose it.
6407 static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
6409 if (T->isReferenceType()) {
6410 S.Diag(Loc, diag::err_reference_without_init)
6411 << T.getNonReferenceType();
6415 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6416 if (!RD || !RD->hasUninitializedReferenceMember())
6419 for (const auto *FI : RD->fields()) {
6420 if (FI->isUnnamedBitfield())
6423 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
6424 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6429 for (const auto &BI : RD->bases()) {
6430 if (DiagnoseUninitializedReference(S, BI.getLocStart(), BI.getType())) {
6431 S.Diag(Loc, diag::note_value_initialization_here) << RD;
6440 //===----------------------------------------------------------------------===//
6441 // Diagnose initialization failures
6442 //===----------------------------------------------------------------------===//
6444 /// Emit notes associated with an initialization that failed due to a
6445 /// "simple" conversion failure.
6446 static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
6448 QualType destType = entity.getType();
6449 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
6450 op->getType()->isObjCObjectPointerType()) {
6452 // Emit a possible note about the conversion failing because the
6453 // operand is a message send with a related result type.
6454 S.EmitRelatedResultTypeNote(op);
6456 // Emit a possible note about a return failing because we're
6457 // expecting a related result type.
6458 if (entity.getKind() == InitializedEntity::EK_Result)
6459 S.EmitRelatedResultTypeNoteForReturn(destType);
6463 static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
6464 InitListExpr *InitList) {
6465 QualType DestType = Entity.getType();
6468 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
6469 QualType ArrayType = S.Context.getConstantArrayType(
6471 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
6472 InitList->getNumInits()),
6473 clang::ArrayType::Normal, 0);
6474 InitializedEntity HiddenArray =
6475 InitializedEntity::InitializeTemporary(ArrayType);
6476 return diagnoseListInit(S, HiddenArray, InitList);
6479 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
6480 /*VerifyOnly=*/false);
6481 assert(DiagnoseInitList.HadError() &&
6482 "Inconsistent init list check result.");
6485 bool InitializationSequence::Diagnose(Sema &S,
6486 const InitializedEntity &Entity,
6487 const InitializationKind &Kind,
6488 ArrayRef<Expr *> Args) {
6492 QualType DestType = Entity.getType();
6494 case FK_TooManyInitsForReference:
6495 // FIXME: Customize for the initialized entity?
6497 // Dig out the reference subobject which is uninitialized and diagnose it.
6498 // If this is value-initialization, this could be nested some way within
6500 assert(Kind.getKind() == InitializationKind::IK_Value ||
6501 DestType->isReferenceType());
6503 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
6504 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
6506 } else // FIXME: diagnostic below could be better!
6507 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
6508 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
6511 case FK_ArrayNeedsInitList:
6512 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
6514 case FK_ArrayNeedsInitListOrStringLiteral:
6515 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
6517 case FK_ArrayNeedsInitListOrWideStringLiteral:
6518 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
6520 case FK_NarrowStringIntoWideCharArray:
6521 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
6523 case FK_WideStringIntoCharArray:
6524 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
6526 case FK_IncompatWideStringIntoWideChar:
6527 S.Diag(Kind.getLocation(),
6528 diag::err_array_init_incompat_wide_string_into_wchar);
6530 case FK_ArrayTypeMismatch:
6531 case FK_NonConstantArrayInit:
6532 S.Diag(Kind.getLocation(),
6533 (Failure == FK_ArrayTypeMismatch
6534 ? diag::err_array_init_different_type
6535 : diag::err_array_init_non_constant_array))
6536 << DestType.getNonReferenceType()
6537 << Args[0]->getType()
6538 << Args[0]->getSourceRange();
6541 case FK_VariableLengthArrayHasInitializer:
6542 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
6543 << Args[0]->getSourceRange();
6546 case FK_AddressOfOverloadFailed: {
6547 DeclAccessPair Found;
6548 S.ResolveAddressOfOverloadedFunction(Args[0],
6549 DestType.getNonReferenceType(),
6555 case FK_ReferenceInitOverloadFailed:
6556 case FK_UserConversionOverloadFailed:
6557 switch (FailedOverloadResult) {
6559 if (Failure == FK_UserConversionOverloadFailed)
6560 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
6561 << Args[0]->getType() << DestType
6562 << Args[0]->getSourceRange();
6564 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
6565 << DestType << Args[0]->getType()
6566 << Args[0]->getSourceRange();
6568 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
6571 case OR_No_Viable_Function:
6572 if (!S.RequireCompleteType(Kind.getLocation(),
6573 DestType.getNonReferenceType(),
6574 diag::err_typecheck_nonviable_condition_incomplete,
6575 Args[0]->getType(), Args[0]->getSourceRange()))
6576 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
6577 << Args[0]->getType() << Args[0]->getSourceRange()
6578 << DestType.getNonReferenceType();
6580 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
6584 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
6585 << Args[0]->getType() << DestType.getNonReferenceType()
6586 << Args[0]->getSourceRange();
6587 OverloadCandidateSet::iterator Best;
6588 OverloadingResult Ovl
6589 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
6591 if (Ovl == OR_Deleted) {
6592 S.NoteDeletedFunction(Best->Function);
6594 llvm_unreachable("Inconsistent overload resolution?");
6600 llvm_unreachable("Conversion did not fail!");
6604 case FK_NonConstLValueReferenceBindingToTemporary:
6605 if (isa<InitListExpr>(Args[0])) {
6606 S.Diag(Kind.getLocation(),
6607 diag::err_lvalue_reference_bind_to_initlist)
6608 << DestType.getNonReferenceType().isVolatileQualified()
6609 << DestType.getNonReferenceType()
6610 << Args[0]->getSourceRange();
6613 // Intentional fallthrough
6615 case FK_NonConstLValueReferenceBindingToUnrelated:
6616 S.Diag(Kind.getLocation(),
6617 Failure == FK_NonConstLValueReferenceBindingToTemporary
6618 ? diag::err_lvalue_reference_bind_to_temporary
6619 : diag::err_lvalue_reference_bind_to_unrelated)
6620 << DestType.getNonReferenceType().isVolatileQualified()
6621 << DestType.getNonReferenceType()
6622 << Args[0]->getType()
6623 << Args[0]->getSourceRange();
6626 case FK_RValueReferenceBindingToLValue:
6627 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
6628 << DestType.getNonReferenceType() << Args[0]->getType()
6629 << Args[0]->getSourceRange();
6632 case FK_ReferenceInitDropsQualifiers:
6633 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
6634 << DestType.getNonReferenceType()
6635 << Args[0]->getType()
6636 << Args[0]->getSourceRange();
6639 case FK_ReferenceInitFailed:
6640 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
6641 << DestType.getNonReferenceType()
6642 << Args[0]->isLValue()
6643 << Args[0]->getType()
6644 << Args[0]->getSourceRange();
6645 emitBadConversionNotes(S, Entity, Args[0]);
6648 case FK_ConversionFailed: {
6649 QualType FromType = Args[0]->getType();
6650 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
6651 << (int)Entity.getKind()
6653 << Args[0]->isLValue()
6655 << Args[0]->getSourceRange();
6656 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
6657 S.Diag(Kind.getLocation(), PDiag);
6658 emitBadConversionNotes(S, Entity, Args[0]);
6662 case FK_ConversionFromPropertyFailed:
6663 // No-op. This error has already been reported.
6666 case FK_TooManyInitsForScalar: {
6669 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
6670 R = SourceRange(InitList->getInit(0)->getLocEnd(),
6671 InitList->getLocEnd());
6673 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
6675 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
6676 if (Kind.isCStyleOrFunctionalCast())
6677 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
6680 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6681 << /*scalar=*/2 << R;
6685 case FK_ReferenceBindingToInitList:
6686 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
6687 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
6690 case FK_InitListBadDestinationType:
6691 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
6692 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
6695 case FK_ListConstructorOverloadFailed:
6696 case FK_ConstructorOverloadFailed: {
6697 SourceRange ArgsRange;
6699 ArgsRange = SourceRange(Args.front()->getLocStart(),
6700 Args.back()->getLocEnd());
6702 if (Failure == FK_ListConstructorOverloadFailed) {
6703 assert(Args.size() == 1 &&
6704 "List construction from other than 1 argument.");
6705 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
6706 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
6709 // FIXME: Using "DestType" for the entity we're printing is probably
6711 switch (FailedOverloadResult) {
6713 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
6714 << DestType << ArgsRange;
6715 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
6718 case OR_No_Viable_Function:
6719 if (Kind.getKind() == InitializationKind::IK_Default &&
6720 (Entity.getKind() == InitializedEntity::EK_Base ||
6721 Entity.getKind() == InitializedEntity::EK_Member) &&
6722 isa<CXXConstructorDecl>(S.CurContext)) {
6723 // This is implicit default initialization of a member or
6724 // base within a constructor. If no viable function was
6725 // found, notify the user that she needs to explicitly
6726 // initialize this base/member.
6727 CXXConstructorDecl *Constructor
6728 = cast<CXXConstructorDecl>(S.CurContext);
6729 if (Entity.getKind() == InitializedEntity::EK_Base) {
6730 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
6731 << (Constructor->getInheritedConstructor() ? 2 :
6732 Constructor->isImplicit() ? 1 : 0)
6733 << S.Context.getTypeDeclType(Constructor->getParent())
6735 << Entity.getType();
6737 RecordDecl *BaseDecl
6738 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
6740 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
6741 << S.Context.getTagDeclType(BaseDecl);
6743 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
6744 << (Constructor->getInheritedConstructor() ? 2 :
6745 Constructor->isImplicit() ? 1 : 0)
6746 << S.Context.getTypeDeclType(Constructor->getParent())
6748 << Entity.getName();
6749 S.Diag(Entity.getDecl()->getLocation(),
6750 diag::note_member_declared_at);
6752 if (const RecordType *Record
6753 = Entity.getType()->getAs<RecordType>())
6754 S.Diag(Record->getDecl()->getLocation(),
6755 diag::note_previous_decl)
6756 << S.Context.getTagDeclType(Record->getDecl());
6761 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
6762 << DestType << ArgsRange;
6763 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
6767 OverloadCandidateSet::iterator Best;
6768 OverloadingResult Ovl
6769 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
6770 if (Ovl != OR_Deleted) {
6771 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6772 << true << DestType << ArgsRange;
6773 llvm_unreachable("Inconsistent overload resolution?");
6777 // If this is a defaulted or implicitly-declared function, then
6778 // it was implicitly deleted. Make it clear that the deletion was
6780 if (S.isImplicitlyDeleted(Best->Function))
6781 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
6782 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
6783 << DestType << ArgsRange;
6785 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6786 << true << DestType << ArgsRange;
6788 S.NoteDeletedFunction(Best->Function);
6793 llvm_unreachable("Conversion did not fail!");
6798 case FK_DefaultInitOfConst:
6799 if (Entity.getKind() == InitializedEntity::EK_Member &&
6800 isa<CXXConstructorDecl>(S.CurContext)) {
6801 // This is implicit default-initialization of a const member in
6802 // a constructor. Complain that it needs to be explicitly
6804 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
6805 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
6806 << (Constructor->getInheritedConstructor() ? 2 :
6807 Constructor->isImplicit() ? 1 : 0)
6808 << S.Context.getTypeDeclType(Constructor->getParent())
6810 << Entity.getName();
6811 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
6812 << Entity.getName();
6814 S.Diag(Kind.getLocation(), diag::err_default_init_const)
6815 << DestType << (bool)DestType->getAs<RecordType>();
6820 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
6821 diag::err_init_incomplete_type);
6824 case FK_ListInitializationFailed: {
6825 // Run the init list checker again to emit diagnostics.
6826 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
6827 diagnoseListInit(S, Entity, InitList);
6831 case FK_PlaceholderType: {
6832 // FIXME: Already diagnosed!
6836 case FK_ExplicitConstructor: {
6837 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
6838 << Args[0]->getSourceRange();
6839 OverloadCandidateSet::iterator Best;
6840 OverloadingResult Ovl
6841 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
6843 assert(Ovl == OR_Success && "Inconsistent overload resolution");
6844 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
6845 S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
6850 PrintInitLocationNote(S, Entity);
6854 void InitializationSequence::dump(raw_ostream &OS) const {
6855 switch (SequenceKind) {
6856 case FailedSequence: {
6857 OS << "Failed sequence: ";
6859 case FK_TooManyInitsForReference:
6860 OS << "too many initializers for reference";
6863 case FK_ArrayNeedsInitList:
6864 OS << "array requires initializer list";
6867 case FK_ArrayNeedsInitListOrStringLiteral:
6868 OS << "array requires initializer list or string literal";
6871 case FK_ArrayNeedsInitListOrWideStringLiteral:
6872 OS << "array requires initializer list or wide string literal";
6875 case FK_NarrowStringIntoWideCharArray:
6876 OS << "narrow string into wide char array";
6879 case FK_WideStringIntoCharArray:
6880 OS << "wide string into char array";
6883 case FK_IncompatWideStringIntoWideChar:
6884 OS << "incompatible wide string into wide char array";
6887 case FK_ArrayTypeMismatch:
6888 OS << "array type mismatch";
6891 case FK_NonConstantArrayInit:
6892 OS << "non-constant array initializer";
6895 case FK_AddressOfOverloadFailed:
6896 OS << "address of overloaded function failed";
6899 case FK_ReferenceInitOverloadFailed:
6900 OS << "overload resolution for reference initialization failed";
6903 case FK_NonConstLValueReferenceBindingToTemporary:
6904 OS << "non-const lvalue reference bound to temporary";
6907 case FK_NonConstLValueReferenceBindingToUnrelated:
6908 OS << "non-const lvalue reference bound to unrelated type";
6911 case FK_RValueReferenceBindingToLValue:
6912 OS << "rvalue reference bound to an lvalue";
6915 case FK_ReferenceInitDropsQualifiers:
6916 OS << "reference initialization drops qualifiers";
6919 case FK_ReferenceInitFailed:
6920 OS << "reference initialization failed";
6923 case FK_ConversionFailed:
6924 OS << "conversion failed";
6927 case FK_ConversionFromPropertyFailed:
6928 OS << "conversion from property failed";
6931 case FK_TooManyInitsForScalar:
6932 OS << "too many initializers for scalar";
6935 case FK_ReferenceBindingToInitList:
6936 OS << "referencing binding to initializer list";
6939 case FK_InitListBadDestinationType:
6940 OS << "initializer list for non-aggregate, non-scalar type";
6943 case FK_UserConversionOverloadFailed:
6944 OS << "overloading failed for user-defined conversion";
6947 case FK_ConstructorOverloadFailed:
6948 OS << "constructor overloading failed";
6951 case FK_DefaultInitOfConst:
6952 OS << "default initialization of a const variable";
6956 OS << "initialization of incomplete type";
6959 case FK_ListInitializationFailed:
6960 OS << "list initialization checker failure";
6963 case FK_VariableLengthArrayHasInitializer:
6964 OS << "variable length array has an initializer";
6967 case FK_PlaceholderType:
6968 OS << "initializer expression isn't contextually valid";
6971 case FK_ListConstructorOverloadFailed:
6972 OS << "list constructor overloading failed";
6975 case FK_ExplicitConstructor:
6976 OS << "list copy initialization chose explicit constructor";
6983 case DependentSequence:
6984 OS << "Dependent sequence\n";
6987 case NormalSequence:
6988 OS << "Normal sequence: ";
6992 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
6993 if (S != step_begin()) {
6998 case SK_ResolveAddressOfOverloadedFunction:
6999 OS << "resolve address of overloaded function";
7002 case SK_CastDerivedToBaseRValue:
7003 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
7006 case SK_CastDerivedToBaseXValue:
7007 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
7010 case SK_CastDerivedToBaseLValue:
7011 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
7014 case SK_BindReference:
7015 OS << "bind reference to lvalue";
7018 case SK_BindReferenceToTemporary:
7019 OS << "bind reference to a temporary";
7022 case SK_ExtraneousCopyToTemporary:
7023 OS << "extraneous C++03 copy to temporary";
7026 case SK_UserConversion:
7027 OS << "user-defined conversion via " << *S->Function.Function;
7030 case SK_QualificationConversionRValue:
7031 OS << "qualification conversion (rvalue)";
7034 case SK_QualificationConversionXValue:
7035 OS << "qualification conversion (xvalue)";
7038 case SK_QualificationConversionLValue:
7039 OS << "qualification conversion (lvalue)";
7042 case SK_AtomicConversion:
7043 OS << "non-atomic-to-atomic conversion";
7046 case SK_LValueToRValue:
7047 OS << "load (lvalue to rvalue)";
7050 case SK_ConversionSequence:
7051 OS << "implicit conversion sequence (";
7052 S->ICS->dump(); // FIXME: use OS
7056 case SK_ConversionSequenceNoNarrowing:
7057 OS << "implicit conversion sequence with narrowing prohibited (";
7058 S->ICS->dump(); // FIXME: use OS
7062 case SK_ListInitialization:
7063 OS << "list aggregate initialization";
7066 case SK_UnwrapInitList:
7067 OS << "unwrap reference initializer list";
7070 case SK_RewrapInitList:
7071 OS << "rewrap reference initializer list";
7074 case SK_ConstructorInitialization:
7075 OS << "constructor initialization";
7078 case SK_ConstructorInitializationFromList:
7079 OS << "list initialization via constructor";
7082 case SK_ZeroInitialization:
7083 OS << "zero initialization";
7086 case SK_CAssignment:
7087 OS << "C assignment";
7091 OS << "string initialization";
7094 case SK_ObjCObjectConversion:
7095 OS << "Objective-C object conversion";
7099 OS << "array initialization";
7102 case SK_ParenthesizedArrayInit:
7103 OS << "parenthesized array initialization";
7106 case SK_PassByIndirectCopyRestore:
7107 OS << "pass by indirect copy and restore";
7110 case SK_PassByIndirectRestore:
7111 OS << "pass by indirect restore";
7114 case SK_ProduceObjCObject:
7115 OS << "Objective-C object retension";
7118 case SK_StdInitializerList:
7119 OS << "std::initializer_list from initializer list";
7122 case SK_StdInitializerListConstructorCall:
7123 OS << "list initialization from std::initializer_list";
7126 case SK_OCLSamplerInit:
7127 OS << "OpenCL sampler_t from integer constant";
7130 case SK_OCLZeroEvent:
7131 OS << "OpenCL event_t from zero";
7135 OS << " [" << S->Type.getAsString() << ']';
7141 void InitializationSequence::dump() const {
7145 static void DiagnoseNarrowingInInitList(Sema &S,
7146 const ImplicitConversionSequence &ICS,
7147 QualType PreNarrowingType,
7148 QualType EntityType,
7149 const Expr *PostInit) {
7150 const StandardConversionSequence *SCS = nullptr;
7151 switch (ICS.getKind()) {
7152 case ImplicitConversionSequence::StandardConversion:
7153 SCS = &ICS.Standard;
7155 case ImplicitConversionSequence::UserDefinedConversion:
7156 SCS = &ICS.UserDefined.After;
7158 case ImplicitConversionSequence::AmbiguousConversion:
7159 case ImplicitConversionSequence::EllipsisConversion:
7160 case ImplicitConversionSequence::BadConversion:
7164 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
7165 APValue ConstantValue;
7166 QualType ConstantType;
7167 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
7169 case NK_Not_Narrowing:
7170 // No narrowing occurred.
7173 case NK_Type_Narrowing:
7174 // This was a floating-to-integer conversion, which is always considered a
7175 // narrowing conversion even if the value is a constant and can be
7176 // represented exactly as an integer.
7177 S.Diag(PostInit->getLocStart(),
7178 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7179 ? diag::warn_init_list_type_narrowing
7180 : diag::ext_init_list_type_narrowing)
7181 << PostInit->getSourceRange()
7182 << PreNarrowingType.getLocalUnqualifiedType()
7183 << EntityType.getLocalUnqualifiedType();
7186 case NK_Constant_Narrowing:
7187 // A constant value was narrowed.
7188 S.Diag(PostInit->getLocStart(),
7189 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7190 ? diag::warn_init_list_constant_narrowing
7191 : diag::ext_init_list_constant_narrowing)
7192 << PostInit->getSourceRange()
7193 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
7194 << EntityType.getLocalUnqualifiedType();
7197 case NK_Variable_Narrowing:
7198 // A variable's value may have been narrowed.
7199 S.Diag(PostInit->getLocStart(),
7200 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7201 ? diag::warn_init_list_variable_narrowing
7202 : diag::ext_init_list_variable_narrowing)
7203 << PostInit->getSourceRange()
7204 << PreNarrowingType.getLocalUnqualifiedType()
7205 << EntityType.getLocalUnqualifiedType();
7209 SmallString<128> StaticCast;
7210 llvm::raw_svector_ostream OS(StaticCast);
7211 OS << "static_cast<";
7212 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
7213 // It's important to use the typedef's name if there is one so that the
7214 // fixit doesn't break code using types like int64_t.
7216 // FIXME: This will break if the typedef requires qualification. But
7217 // getQualifiedNameAsString() includes non-machine-parsable components.
7218 OS << *TT->getDecl();
7219 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
7220 OS << BT->getName(S.getLangOpts());
7222 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
7223 // with a broken cast.
7227 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_silence)
7228 << PostInit->getSourceRange()
7229 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
7230 << FixItHint::CreateInsertion(
7231 S.getLocForEndOfToken(PostInit->getLocEnd()), ")");
7234 //===----------------------------------------------------------------------===//
7235 // Initialization helper functions
7236 //===----------------------------------------------------------------------===//
7238 Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
7240 if (Init.isInvalid())
7243 Expr *InitE = Init.get();
7244 assert(InitE && "No initialization expression");
7246 InitializationKind Kind
7247 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
7248 InitializationSequence Seq(*this, Entity, Kind, InitE);
7249 return !Seq.Failed();
7253 Sema::PerformCopyInitialization(const InitializedEntity &Entity,
7254 SourceLocation EqualLoc,
7256 bool TopLevelOfInitList,
7257 bool AllowExplicit) {
7258 if (Init.isInvalid())
7261 Expr *InitE = Init.get();
7262 assert(InitE && "No initialization expression?");
7264 if (EqualLoc.isInvalid())
7265 EqualLoc = InitE->getLocStart();
7267 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
7270 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
7273 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);