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/AST/ASTContext.h"
15 #include "clang/AST/DeclObjC.h"
16 #include "clang/AST/ExprCXX.h"
17 #include "clang/AST/ExprObjC.h"
18 #include "clang/AST/TypeLoc.h"
19 #include "clang/Basic/TargetInfo.h"
20 #include "clang/Sema/Designator.h"
21 #include "clang/Sema/Initialization.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.
152 auto *ConstantArrayTy =
153 cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
154 uint64_t StrLength = ConstantArrayTy->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 //===----------------------------------------------------------------------===//
209 /// @brief Semantic checking for initializer lists.
211 /// The InitListChecker class contains a set of routines that each
212 /// handle the initialization of a certain kind of entity, e.g.,
213 /// arrays, vectors, struct/union types, scalars, etc. The
214 /// InitListChecker itself performs a recursive walk of the subobject
215 /// structure of the type to be initialized, while stepping through
216 /// the initializer list one element at a time. The IList and Index
217 /// parameters to each of the Check* routines contain the active
218 /// (syntactic) initializer list and the index into that initializer
219 /// list that represents the current initializer. Each routine is
220 /// responsible for moving that Index forward as it consumes elements.
222 /// Each Check* routine also has a StructuredList/StructuredIndex
223 /// arguments, which contains the current "structured" (semantic)
224 /// initializer list and the index into that initializer list where we
225 /// are copying initializers as we map them over to the semantic
226 /// list. Once we have completed our recursive walk of the subobject
227 /// structure, we will have constructed a full semantic initializer
230 /// C99 designators cause changes in the initializer list traversal,
231 /// because they make the initialization "jump" into a specific
232 /// subobject and then continue the initialization from that
233 /// point. CheckDesignatedInitializer() recursively steps into the
234 /// designated subobject and manages backing out the recursion to
235 /// initialize the subobjects after the one designated.
236 class InitListChecker {
239 bool VerifyOnly; // no diagnostics, no structure building
240 bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
241 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
242 InitListExpr *FullyStructuredList;
244 void CheckImplicitInitList(const InitializedEntity &Entity,
245 InitListExpr *ParentIList, QualType T,
246 unsigned &Index, InitListExpr *StructuredList,
247 unsigned &StructuredIndex);
248 void CheckExplicitInitList(const InitializedEntity &Entity,
249 InitListExpr *IList, QualType &T,
250 InitListExpr *StructuredList,
251 bool TopLevelObject = false);
252 void CheckListElementTypes(const InitializedEntity &Entity,
253 InitListExpr *IList, QualType &DeclType,
254 bool SubobjectIsDesignatorContext,
256 InitListExpr *StructuredList,
257 unsigned &StructuredIndex,
258 bool TopLevelObject = false);
259 void CheckSubElementType(const InitializedEntity &Entity,
260 InitListExpr *IList, QualType ElemType,
262 InitListExpr *StructuredList,
263 unsigned &StructuredIndex);
264 void CheckComplexType(const InitializedEntity &Entity,
265 InitListExpr *IList, QualType DeclType,
267 InitListExpr *StructuredList,
268 unsigned &StructuredIndex);
269 void CheckScalarType(const InitializedEntity &Entity,
270 InitListExpr *IList, QualType DeclType,
272 InitListExpr *StructuredList,
273 unsigned &StructuredIndex);
274 void CheckReferenceType(const InitializedEntity &Entity,
275 InitListExpr *IList, QualType DeclType,
277 InitListExpr *StructuredList,
278 unsigned &StructuredIndex);
279 void CheckVectorType(const InitializedEntity &Entity,
280 InitListExpr *IList, QualType DeclType, unsigned &Index,
281 InitListExpr *StructuredList,
282 unsigned &StructuredIndex);
283 void CheckStructUnionTypes(const InitializedEntity &Entity,
284 InitListExpr *IList, QualType DeclType,
285 CXXRecordDecl::base_class_range Bases,
286 RecordDecl::field_iterator Field,
287 bool SubobjectIsDesignatorContext, unsigned &Index,
288 InitListExpr *StructuredList,
289 unsigned &StructuredIndex,
290 bool TopLevelObject = false);
291 void CheckArrayType(const InitializedEntity &Entity,
292 InitListExpr *IList, QualType &DeclType,
293 llvm::APSInt elementIndex,
294 bool SubobjectIsDesignatorContext, unsigned &Index,
295 InitListExpr *StructuredList,
296 unsigned &StructuredIndex);
297 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
298 InitListExpr *IList, DesignatedInitExpr *DIE,
300 QualType &CurrentObjectType,
301 RecordDecl::field_iterator *NextField,
302 llvm::APSInt *NextElementIndex,
304 InitListExpr *StructuredList,
305 unsigned &StructuredIndex,
306 bool FinishSubobjectInit,
307 bool TopLevelObject);
308 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
309 QualType CurrentObjectType,
310 InitListExpr *StructuredList,
311 unsigned StructuredIndex,
312 SourceRange InitRange,
313 bool IsFullyOverwritten = false);
314 void UpdateStructuredListElement(InitListExpr *StructuredList,
315 unsigned &StructuredIndex,
317 int numArrayElements(QualType DeclType);
318 int numStructUnionElements(QualType DeclType);
320 static ExprResult PerformEmptyInit(Sema &SemaRef,
322 const InitializedEntity &Entity,
324 bool TreatUnavailableAsInvalid);
326 // Explanation on the "FillWithNoInit" mode:
328 // Assume we have the following definitions (Case#1):
329 // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
330 // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
332 // l.lp.x[1][0..1] should not be filled with implicit initializers because the
333 // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
335 // But if we have (Case#2):
336 // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
338 // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
339 // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
341 // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
342 // in the InitListExpr, the "holes" in Case#1 are filled not with empty
343 // initializers but with special "NoInitExpr" place holders, which tells the
344 // CodeGen not to generate any initializers for these parts.
345 void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
346 const InitializedEntity &ParentEntity,
347 InitListExpr *ILE, bool &RequiresSecondPass,
348 bool FillWithNoInit);
349 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
350 const InitializedEntity &ParentEntity,
351 InitListExpr *ILE, bool &RequiresSecondPass,
352 bool FillWithNoInit = false);
353 void FillInEmptyInitializations(const InitializedEntity &Entity,
354 InitListExpr *ILE, bool &RequiresSecondPass,
355 bool FillWithNoInit = false);
356 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
357 Expr *InitExpr, FieldDecl *Field,
358 bool TopLevelObject);
359 void CheckEmptyInitializable(const InitializedEntity &Entity,
363 InitListChecker(Sema &S, const InitializedEntity &Entity,
364 InitListExpr *IL, QualType &T, bool VerifyOnly,
365 bool TreatUnavailableAsInvalid);
366 bool HadError() { return hadError; }
368 // @brief Retrieves the fully-structured initializer list used for
369 // semantic analysis and code generation.
370 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
373 } // end anonymous namespace
375 ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef,
377 const InitializedEntity &Entity,
379 bool TreatUnavailableAsInvalid) {
380 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
382 MultiExprArg SubInit;
384 InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
386 // C++ [dcl.init.aggr]p7:
387 // If there are fewer initializer-clauses in the list than there are
388 // members in the aggregate, then each member not explicitly initialized
390 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
391 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
394 // shall be initialized [...] from an empty initializer list.
396 // We apply the resolution of this DR to C++11 but not C++98, since C++98
397 // does not have useful semantics for initialization from an init list.
398 // We treat this as copy-initialization, because aggregate initialization
399 // always performs copy-initialization on its elements.
401 // Only do this if we're initializing a class type, to avoid filling in
402 // the initializer list where possible.
403 InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context)
404 InitListExpr(SemaRef.Context, Loc, None, Loc);
405 InitExpr->setType(SemaRef.Context.VoidTy);
407 Kind = InitializationKind::CreateCopy(Loc, Loc);
410 // shall be value-initialized.
413 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
414 // libstdc++4.6 marks the vector default constructor as explicit in
415 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
416 // stlport does so too. Look for std::__debug for libstdc++, and for
417 // std:: for stlport. This is effectively a compiler-side implementation of
419 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
420 InitializationSequence::FK_ExplicitConstructor) {
421 OverloadCandidateSet::iterator Best;
422 OverloadingResult O =
423 InitSeq.getFailedCandidateSet()
424 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
426 assert(O == OR_Success && "Inconsistent overload resolution");
427 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
428 CXXRecordDecl *R = CtorDecl->getParent();
430 if (CtorDecl->getMinRequiredArguments() == 0 &&
431 CtorDecl->isExplicit() && R->getDeclName() &&
432 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
433 bool IsInStd = false;
434 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
435 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
436 if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
440 if (IsInStd && llvm::StringSwitch<bool>(R->getName())
441 .Cases("basic_string", "deque", "forward_list", true)
442 .Cases("list", "map", "multimap", "multiset", true)
443 .Cases("priority_queue", "queue", "set", "stack", true)
444 .Cases("unordered_map", "unordered_set", "vector", true)
446 InitSeq.InitializeFrom(
448 InitializationKind::CreateValue(Loc, Loc, Loc, true),
449 MultiExprArg(), /*TopLevelOfInitList=*/false,
450 TreatUnavailableAsInvalid);
451 // Emit a warning for this. System header warnings aren't shown
452 // by default, but people working on system headers should see it.
454 SemaRef.Diag(CtorDecl->getLocation(),
455 diag::warn_invalid_initializer_from_system_header);
456 if (Entity.getKind() == InitializedEntity::EK_Member)
457 SemaRef.Diag(Entity.getDecl()->getLocation(),
458 diag::note_used_in_initialization_here);
459 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
460 SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
467 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
468 if (Entity.getKind() == InitializedEntity::EK_Member)
469 SemaRef.Diag(Entity.getDecl()->getLocation(),
470 diag::note_in_omitted_aggregate_initializer)
471 << /*field*/1 << Entity.getDecl();
472 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
473 bool IsTrailingArrayNewMember =
474 Entity.getParent() &&
475 Entity.getParent()->isVariableLengthArrayNew();
476 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
477 << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
478 << Entity.getElementIndex();
484 return VerifyOnly ? ExprResult(static_cast<Expr *>(nullptr))
485 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
488 void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
489 SourceLocation Loc) {
491 "CheckEmptyInitializable is only inteded for verification mode.");
492 if (PerformEmptyInit(SemaRef, Loc, Entity, /*VerifyOnly*/true,
493 TreatUnavailableAsInvalid).isInvalid())
497 void InitListChecker::FillInEmptyInitForBase(
498 unsigned Init, const CXXBaseSpecifier &Base,
499 const InitializedEntity &ParentEntity, InitListExpr *ILE,
500 bool &RequiresSecondPass, bool FillWithNoInit) {
501 assert(Init < ILE->getNumInits() && "should have been expanded");
503 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
504 SemaRef.Context, &Base, false, &ParentEntity);
506 if (!ILE->getInit(Init)) {
507 ExprResult BaseInit =
508 FillWithNoInit ? new (SemaRef.Context) NoInitExpr(Base.getType())
509 : PerformEmptyInit(SemaRef, ILE->getLocEnd(), BaseEntity,
510 /*VerifyOnly*/ false,
511 TreatUnavailableAsInvalid);
512 if (BaseInit.isInvalid()) {
517 ILE->setInit(Init, BaseInit.getAs<Expr>());
518 } else if (InitListExpr *InnerILE =
519 dyn_cast<InitListExpr>(ILE->getInit(Init))) {
520 FillInEmptyInitializations(BaseEntity, InnerILE,
521 RequiresSecondPass, FillWithNoInit);
522 } else if (DesignatedInitUpdateExpr *InnerDIUE =
523 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
524 FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
525 RequiresSecondPass, /*FillWithNoInit =*/true);
529 void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
530 const InitializedEntity &ParentEntity,
532 bool &RequiresSecondPass,
533 bool FillWithNoInit) {
534 SourceLocation Loc = ILE->getLocEnd();
535 unsigned NumInits = ILE->getNumInits();
536 InitializedEntity MemberEntity
537 = InitializedEntity::InitializeMember(Field, &ParentEntity);
539 if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
540 if (!RType->getDecl()->isUnion())
541 assert(Init < NumInits && "This ILE should have been expanded");
543 if (Init >= NumInits || !ILE->getInit(Init)) {
544 if (FillWithNoInit) {
545 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
547 ILE->setInit(Init, Filler);
549 ILE->updateInit(SemaRef.Context, Init, Filler);
552 // C++1y [dcl.init.aggr]p7:
553 // If there are fewer initializer-clauses in the list than there are
554 // members in the aggregate, then each member not explicitly initialized
555 // shall be initialized from its brace-or-equal-initializer [...]
556 if (Field->hasInClassInitializer()) {
557 ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
558 if (DIE.isInvalid()) {
563 ILE->setInit(Init, DIE.get());
565 ILE->updateInit(SemaRef.Context, Init, DIE.get());
566 RequiresSecondPass = true;
571 if (Field->getType()->isReferenceType()) {
572 // C++ [dcl.init.aggr]p9:
573 // If an incomplete or empty initializer-list leaves a
574 // member of reference type uninitialized, the program is
576 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
578 << ILE->getSyntacticForm()->getSourceRange();
579 SemaRef.Diag(Field->getLocation(),
580 diag::note_uninit_reference_member);
585 ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
587 TreatUnavailableAsInvalid);
588 if (MemberInit.isInvalid()) {
595 } else if (Init < NumInits) {
596 ILE->setInit(Init, MemberInit.getAs<Expr>());
597 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
598 // Empty initialization requires a constructor call, so
599 // extend the initializer list to include the constructor
600 // call and make a note that we'll need to take another pass
601 // through the initializer list.
602 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
603 RequiresSecondPass = true;
605 } else if (InitListExpr *InnerILE
606 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
607 FillInEmptyInitializations(MemberEntity, InnerILE,
608 RequiresSecondPass, FillWithNoInit);
609 else if (DesignatedInitUpdateExpr *InnerDIUE
610 = dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init)))
611 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
612 RequiresSecondPass, /*FillWithNoInit =*/ true);
615 /// Recursively replaces NULL values within the given initializer list
616 /// with expressions that perform value-initialization of the
617 /// appropriate type.
619 InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
621 bool &RequiresSecondPass,
622 bool FillWithNoInit) {
623 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
624 "Should not have void type");
626 // A transparent ILE is not performing aggregate initialization and should
628 if (ILE->isTransparent())
631 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
632 const RecordDecl *RDecl = RType->getDecl();
633 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
634 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
635 Entity, ILE, RequiresSecondPass, FillWithNoInit);
636 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
637 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
638 for (auto *Field : RDecl->fields()) {
639 if (Field->hasInClassInitializer()) {
640 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
646 // The fields beyond ILE->getNumInits() are default initialized, so in
647 // order to leave them uninitialized, the ILE is expanded and the extra
648 // fields are then filled with NoInitExpr.
649 unsigned NumElems = numStructUnionElements(ILE->getType());
650 if (RDecl->hasFlexibleArrayMember())
652 if (ILE->getNumInits() < NumElems)
653 ILE->resizeInits(SemaRef.Context, NumElems);
657 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
658 for (auto &Base : CXXRD->bases()) {
662 FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
668 for (auto *Field : RDecl->fields()) {
669 if (Field->isUnnamedBitfield())
675 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
682 // Only look at the first initialization of a union.
683 if (RDecl->isUnion())
691 QualType ElementType;
693 InitializedEntity ElementEntity = Entity;
694 unsigned NumInits = ILE->getNumInits();
695 unsigned NumElements = NumInits;
696 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
697 ElementType = AType->getElementType();
698 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
699 NumElements = CAType->getSize().getZExtValue();
700 // For an array new with an unknown bound, ask for one additional element
701 // in order to populate the array filler.
702 if (Entity.isVariableLengthArrayNew())
704 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
706 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
707 ElementType = VType->getElementType();
708 NumElements = VType->getNumElements();
709 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
712 ElementType = ILE->getType();
714 for (unsigned Init = 0; Init != NumElements; ++Init) {
718 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
719 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
720 ElementEntity.setElementIndex(Init);
722 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
723 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
724 ILE->setInit(Init, ILE->getArrayFiller());
725 else if (!InitExpr && !ILE->hasArrayFiller()) {
726 Expr *Filler = nullptr;
729 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
731 ExprResult ElementInit = PerformEmptyInit(SemaRef, ILE->getLocEnd(),
734 TreatUnavailableAsInvalid);
735 if (ElementInit.isInvalid()) {
740 Filler = ElementInit.getAs<Expr>();
745 } else if (Init < NumInits) {
746 // For arrays, just set the expression used for value-initialization
747 // of the "holes" in the array.
748 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
749 ILE->setArrayFiller(Filler);
751 ILE->setInit(Init, Filler);
753 // For arrays, just set the expression used for value-initialization
754 // of the rest of elements and exit.
755 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
756 ILE->setArrayFiller(Filler);
760 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
761 // Empty initialization requires a constructor call, so
762 // extend the initializer list to include the constructor
763 // call and make a note that we'll need to take another pass
764 // through the initializer list.
765 ILE->updateInit(SemaRef.Context, Init, Filler);
766 RequiresSecondPass = true;
769 } else if (InitListExpr *InnerILE
770 = dyn_cast_or_null<InitListExpr>(InitExpr))
771 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
773 else if (DesignatedInitUpdateExpr *InnerDIUE
774 = dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr))
775 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
776 RequiresSecondPass, /*FillWithNoInit =*/ true);
780 InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
781 InitListExpr *IL, QualType &T,
783 bool TreatUnavailableAsInvalid)
784 : SemaRef(S), VerifyOnly(VerifyOnly),
785 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid) {
786 // FIXME: Check that IL isn't already the semantic form of some other
787 // InitListExpr. If it is, we'd create a broken AST.
791 FullyStructuredList =
792 getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
793 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
794 /*TopLevelObject=*/true);
796 if (!hadError && !VerifyOnly) {
797 bool RequiresSecondPass = false;
798 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass);
799 if (RequiresSecondPass && !hadError)
800 FillInEmptyInitializations(Entity, FullyStructuredList,
805 int InitListChecker::numArrayElements(QualType DeclType) {
806 // FIXME: use a proper constant
807 int maxElements = 0x7FFFFFFF;
808 if (const ConstantArrayType *CAT =
809 SemaRef.Context.getAsConstantArrayType(DeclType)) {
810 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
815 int InitListChecker::numStructUnionElements(QualType DeclType) {
816 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
817 int InitializableMembers = 0;
818 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
819 InitializableMembers += CXXRD->getNumBases();
820 for (const auto *Field : structDecl->fields())
821 if (!Field->isUnnamedBitfield())
822 ++InitializableMembers;
824 if (structDecl->isUnion())
825 return std::min(InitializableMembers, 1);
826 return InitializableMembers - structDecl->hasFlexibleArrayMember();
829 /// Determine whether Entity is an entity for which it is idiomatic to elide
830 /// the braces in aggregate initialization.
831 static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) {
832 // Recursive initialization of the one and only field within an aggregate
833 // class is considered idiomatic. This case arises in particular for
834 // initialization of std::array, where the C++ standard suggests the idiom of
836 // std::array<T, N> arr = {1, 2, 3};
838 // (where std::array is an aggregate struct containing a single array field.
840 // FIXME: Should aggregate initialization of a struct with a single
841 // base class and no members also suppress the warning?
842 if (Entity.getKind() != InitializedEntity::EK_Member || !Entity.getParent())
846 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
847 if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD))
848 if (CXXRD->getNumBases())
851 auto FieldIt = ParentRD->field_begin();
852 assert(FieldIt != ParentRD->field_end() &&
853 "no fields but have initializer for member?");
854 return ++FieldIt == ParentRD->field_end();
857 /// Check whether the range of the initializer \p ParentIList from element
858 /// \p Index onwards can be used to initialize an object of type \p T. Update
859 /// \p Index to indicate how many elements of the list were consumed.
861 /// This also fills in \p StructuredList, from element \p StructuredIndex
862 /// onwards, with the fully-braced, desugared form of the initialization.
863 void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
864 InitListExpr *ParentIList,
865 QualType T, unsigned &Index,
866 InitListExpr *StructuredList,
867 unsigned &StructuredIndex) {
870 if (T->isArrayType())
871 maxElements = numArrayElements(T);
872 else if (T->isRecordType())
873 maxElements = numStructUnionElements(T);
874 else if (T->isVectorType())
875 maxElements = T->getAs<VectorType>()->getNumElements();
877 llvm_unreachable("CheckImplicitInitList(): Illegal type");
879 if (maxElements == 0) {
881 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
882 diag::err_implicit_empty_initializer);
888 // Build a structured initializer list corresponding to this subobject.
889 InitListExpr *StructuredSubobjectInitList
890 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
892 SourceRange(ParentIList->getInit(Index)->getLocStart(),
893 ParentIList->getSourceRange().getEnd()));
894 unsigned StructuredSubobjectInitIndex = 0;
896 // Check the element types and build the structural subobject.
897 unsigned StartIndex = Index;
898 CheckListElementTypes(Entity, ParentIList, T,
899 /*SubobjectIsDesignatorContext=*/false, Index,
900 StructuredSubobjectInitList,
901 StructuredSubobjectInitIndex);
904 StructuredSubobjectInitList->setType(T);
906 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
907 // Update the structured sub-object initializer so that it's ending
908 // range corresponds with the end of the last initializer it used.
909 if (EndIndex < ParentIList->getNumInits() &&
910 ParentIList->getInit(EndIndex)) {
911 SourceLocation EndLoc
912 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
913 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
916 // Complain about missing braces.
917 if ((T->isArrayType() || T->isRecordType()) &&
918 !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
919 !isIdiomaticBraceElisionEntity(Entity)) {
920 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
921 diag::warn_missing_braces)
922 << StructuredSubobjectInitList->getSourceRange()
923 << FixItHint::CreateInsertion(
924 StructuredSubobjectInitList->getLocStart(), "{")
925 << FixItHint::CreateInsertion(
926 SemaRef.getLocForEndOfToken(
927 StructuredSubobjectInitList->getLocEnd()),
933 /// Warn that \p Entity was of scalar type and was initialized by a
934 /// single-element braced initializer list.
935 static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
936 SourceRange Braces) {
937 // Don't warn during template instantiation. If the initialization was
938 // non-dependent, we warned during the initial parse; otherwise, the
939 // type might not be scalar in some uses of the template.
940 if (S.inTemplateInstantiation())
945 switch (Entity.getKind()) {
946 case InitializedEntity::EK_VectorElement:
947 case InitializedEntity::EK_ComplexElement:
948 case InitializedEntity::EK_ArrayElement:
949 case InitializedEntity::EK_Parameter:
950 case InitializedEntity::EK_Parameter_CF_Audited:
951 case InitializedEntity::EK_Result:
952 // Extra braces here are suspicious.
953 DiagID = diag::warn_braces_around_scalar_init;
956 case InitializedEntity::EK_Member:
957 // Warn on aggregate initialization but not on ctor init list or
958 // default member initializer.
959 if (Entity.getParent())
960 DiagID = diag::warn_braces_around_scalar_init;
963 case InitializedEntity::EK_Variable:
964 case InitializedEntity::EK_LambdaCapture:
965 // No warning, might be direct-list-initialization.
966 // FIXME: Should we warn for copy-list-initialization in these cases?
969 case InitializedEntity::EK_New:
970 case InitializedEntity::EK_Temporary:
971 case InitializedEntity::EK_CompoundLiteralInit:
972 // No warning, braces are part of the syntax of the underlying construct.
975 case InitializedEntity::EK_RelatedResult:
976 // No warning, we already warned when initializing the result.
979 case InitializedEntity::EK_Exception:
980 case InitializedEntity::EK_Base:
981 case InitializedEntity::EK_Delegating:
982 case InitializedEntity::EK_BlockElement:
983 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
984 case InitializedEntity::EK_Binding:
985 llvm_unreachable("unexpected braced scalar init");
989 S.Diag(Braces.getBegin(), DiagID)
991 << FixItHint::CreateRemoval(Braces.getBegin())
992 << FixItHint::CreateRemoval(Braces.getEnd());
996 /// Check whether the initializer \p IList (that was written with explicit
997 /// braces) can be used to initialize an object of type \p T.
999 /// This also fills in \p StructuredList with the fully-braced, desugared
1000 /// form of the initialization.
1001 void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
1002 InitListExpr *IList, QualType &T,
1003 InitListExpr *StructuredList,
1004 bool TopLevelObject) {
1006 SyntacticToSemantic[IList] = StructuredList;
1007 StructuredList->setSyntacticForm(IList);
1010 unsigned Index = 0, StructuredIndex = 0;
1011 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
1012 Index, StructuredList, StructuredIndex, TopLevelObject);
1014 QualType ExprTy = T;
1015 if (!ExprTy->isArrayType())
1016 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
1017 IList->setType(ExprTy);
1018 StructuredList->setType(ExprTy);
1023 if (Index < IList->getNumInits()) {
1024 // We have leftover initializers
1026 if (SemaRef.getLangOpts().CPlusPlus ||
1027 (SemaRef.getLangOpts().OpenCL &&
1028 IList->getType()->isVectorType())) {
1034 if (StructuredIndex == 1 &&
1035 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1037 unsigned DK = diag::ext_excess_initializers_in_char_array_initializer;
1038 if (SemaRef.getLangOpts().CPlusPlus) {
1039 DK = diag::err_excess_initializers_in_char_array_initializer;
1043 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
1044 << IList->getInit(Index)->getSourceRange();
1045 } else if (!T->isIncompleteType()) {
1046 // Don't complain for incomplete types, since we'll get an error
1048 QualType CurrentObjectType = StructuredList->getType();
1050 CurrentObjectType->isArrayType()? 0 :
1051 CurrentObjectType->isVectorType()? 1 :
1052 CurrentObjectType->isScalarType()? 2 :
1053 CurrentObjectType->isUnionType()? 3 :
1056 unsigned DK = diag::ext_excess_initializers;
1057 if (SemaRef.getLangOpts().CPlusPlus) {
1058 DK = diag::err_excess_initializers;
1061 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
1062 DK = diag::err_excess_initializers;
1066 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
1067 << initKind << IList->getInit(Index)->getSourceRange();
1071 if (!VerifyOnly && T->isScalarType() &&
1072 IList->getNumInits() == 1 && !isa<InitListExpr>(IList->getInit(0)))
1073 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
1076 void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
1077 InitListExpr *IList,
1079 bool SubobjectIsDesignatorContext,
1081 InitListExpr *StructuredList,
1082 unsigned &StructuredIndex,
1083 bool TopLevelObject) {
1084 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1085 // Explicitly braced initializer for complex type can be real+imaginary
1087 CheckComplexType(Entity, IList, DeclType, Index,
1088 StructuredList, StructuredIndex);
1089 } else if (DeclType->isScalarType()) {
1090 CheckScalarType(Entity, IList, DeclType, Index,
1091 StructuredList, StructuredIndex);
1092 } else if (DeclType->isVectorType()) {
1093 CheckVectorType(Entity, IList, DeclType, Index,
1094 StructuredList, StructuredIndex);
1095 } else if (DeclType->isRecordType()) {
1096 assert(DeclType->isAggregateType() &&
1097 "non-aggregate records should be handed in CheckSubElementType");
1098 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1100 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
1101 CXXRecordDecl::base_class_iterator());
1102 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1103 Bases = CXXRD->bases();
1104 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1105 SubobjectIsDesignatorContext, Index, StructuredList,
1106 StructuredIndex, TopLevelObject);
1107 } else if (DeclType->isArrayType()) {
1109 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1111 CheckArrayType(Entity, IList, DeclType, Zero,
1112 SubobjectIsDesignatorContext, Index,
1113 StructuredList, StructuredIndex);
1114 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1115 // This type is invalid, issue a diagnostic.
1118 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
1121 } else if (DeclType->isReferenceType()) {
1122 CheckReferenceType(Entity, IList, DeclType, Index,
1123 StructuredList, StructuredIndex);
1124 } else if (DeclType->isObjCObjectType()) {
1126 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
1131 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
1137 void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
1138 InitListExpr *IList,
1141 InitListExpr *StructuredList,
1142 unsigned &StructuredIndex) {
1143 Expr *expr = IList->getInit(Index);
1145 if (ElemType->isReferenceType())
1146 return CheckReferenceType(Entity, IList, ElemType, Index,
1147 StructuredList, StructuredIndex);
1149 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
1150 if (SubInitList->getNumInits() == 1 &&
1151 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1153 expr = SubInitList->getInit(0);
1154 } else if (!SemaRef.getLangOpts().CPlusPlus) {
1155 InitListExpr *InnerStructuredList
1156 = getStructuredSubobjectInit(IList, Index, ElemType,
1157 StructuredList, StructuredIndex,
1158 SubInitList->getSourceRange(), true);
1159 CheckExplicitInitList(Entity, SubInitList, ElemType,
1160 InnerStructuredList);
1162 if (!hadError && !VerifyOnly) {
1163 bool RequiresSecondPass = false;
1164 FillInEmptyInitializations(Entity, InnerStructuredList,
1165 RequiresSecondPass);
1166 if (RequiresSecondPass && !hadError)
1167 FillInEmptyInitializations(Entity, InnerStructuredList,
1168 RequiresSecondPass);
1174 // C++ initialization is handled later.
1175 } else if (isa<ImplicitValueInitExpr>(expr)) {
1176 // This happens during template instantiation when we see an InitListExpr
1177 // that we've already checked once.
1178 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
1179 "found implicit initialization for the wrong type");
1181 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1186 if (SemaRef.getLangOpts().CPlusPlus) {
1187 // C++ [dcl.init.aggr]p2:
1188 // Each member is copy-initialized from the corresponding
1189 // initializer-clause.
1191 // FIXME: Better EqualLoc?
1192 InitializationKind Kind =
1193 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
1194 InitializationSequence Seq(SemaRef, Entity, Kind, expr,
1195 /*TopLevelOfInitList*/ true);
1197 // C++14 [dcl.init.aggr]p13:
1198 // If the assignment-expression can initialize a member, the member is
1199 // initialized. Otherwise [...] brace elision is assumed
1201 // Brace elision is never performed if the element is not an
1202 // assignment-expression.
1203 if (Seq || isa<InitListExpr>(expr)) {
1206 Seq.Perform(SemaRef, Entity, Kind, expr);
1207 if (Result.isInvalid())
1210 UpdateStructuredListElement(StructuredList, StructuredIndex,
1211 Result.getAs<Expr>());
1218 // Fall through for subaggregate initialization
1219 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1220 // FIXME: Need to handle atomic aggregate types with implicit init lists.
1221 return CheckScalarType(Entity, IList, ElemType, Index,
1222 StructuredList, StructuredIndex);
1223 } else if (const ArrayType *arrayType =
1224 SemaRef.Context.getAsArrayType(ElemType)) {
1225 // arrayType can be incomplete if we're initializing a flexible
1226 // array member. There's nothing we can do with the completed
1227 // type here, though.
1229 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
1231 CheckStringInit(expr, ElemType, arrayType, SemaRef);
1232 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1238 // Fall through for subaggregate initialization.
1241 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
1242 ElemType->isOpenCLSpecificType()) && "Unexpected type");
1246 // The initializer for a structure or union object that has
1247 // automatic storage duration shall be either an initializer
1248 // list as described below, or a single expression that has
1249 // compatible structure or union type. In the latter case, the
1250 // initial value of the object, including unnamed members, is
1251 // that of the expression.
1252 ExprResult ExprRes = expr;
1253 if (SemaRef.CheckSingleAssignmentConstraints(
1254 ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
1255 if (ExprRes.isInvalid())
1258 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
1259 if (ExprRes.isInvalid())
1262 UpdateStructuredListElement(StructuredList, StructuredIndex,
1263 ExprRes.getAs<Expr>());
1268 // Fall through for subaggregate initialization
1271 // C++ [dcl.init.aggr]p12:
1273 // [...] Otherwise, if the member is itself a non-empty
1274 // subaggregate, brace elision is assumed and the initializer is
1275 // considered for the initialization of the first member of
1276 // the subaggregate.
1277 // OpenCL vector initializer is handled elsewhere.
1278 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1279 ElemType->isAggregateType()) {
1280 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1285 // We cannot initialize this element, so let
1286 // PerformCopyInitialization produce the appropriate diagnostic.
1287 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
1288 /*TopLevelOfInitList=*/true);
1296 void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1297 InitListExpr *IList, QualType DeclType,
1299 InitListExpr *StructuredList,
1300 unsigned &StructuredIndex) {
1301 assert(Index == 0 && "Index in explicit init list must be zero");
1303 // As an extension, clang supports complex initializers, which initialize
1304 // a complex number component-wise. When an explicit initializer list for
1305 // a complex number contains two two initializers, this extension kicks in:
1306 // it exepcts the initializer list to contain two elements convertible to
1307 // the element type of the complex type. The first element initializes
1308 // the real part, and the second element intitializes the imaginary part.
1310 if (IList->getNumInits() != 2)
1311 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1314 // This is an extension in C. (The builtin _Complex type does not exist
1315 // in the C++ standard.)
1316 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
1317 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
1318 << IList->getSourceRange();
1320 // Initialize the complex number.
1321 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
1322 InitializedEntity ElementEntity =
1323 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1325 for (unsigned i = 0; i < 2; ++i) {
1326 ElementEntity.setElementIndex(Index);
1327 CheckSubElementType(ElementEntity, IList, elementType, Index,
1328 StructuredList, StructuredIndex);
1332 void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
1333 InitListExpr *IList, QualType DeclType,
1335 InitListExpr *StructuredList,
1336 unsigned &StructuredIndex) {
1337 if (Index >= IList->getNumInits()) {
1339 SemaRef.Diag(IList->getLocStart(),
1340 SemaRef.getLangOpts().CPlusPlus11 ?
1341 diag::warn_cxx98_compat_empty_scalar_initializer :
1342 diag::err_empty_scalar_initializer)
1343 << IList->getSourceRange();
1344 hadError = !SemaRef.getLangOpts().CPlusPlus11;
1350 Expr *expr = IList->getInit(Index);
1351 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
1352 // FIXME: This is invalid, and accepting it causes overload resolution
1353 // to pick the wrong overload in some corner cases.
1355 SemaRef.Diag(SubIList->getLocStart(),
1356 diag::ext_many_braces_around_scalar_init)
1357 << SubIList->getSourceRange();
1359 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1362 } else if (isa<DesignatedInitExpr>(expr)) {
1364 SemaRef.Diag(expr->getLocStart(),
1365 diag::err_designator_for_scalar_init)
1366 << DeclType << expr->getSourceRange();
1374 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
1381 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1382 /*TopLevelOfInitList=*/true);
1384 Expr *ResultExpr = nullptr;
1386 if (Result.isInvalid())
1387 hadError = true; // types weren't compatible.
1389 ResultExpr = Result.getAs<Expr>();
1391 if (ResultExpr != expr) {
1392 // The type was promoted, update initializer list.
1393 IList->setInit(Index, ResultExpr);
1399 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1403 void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1404 InitListExpr *IList, QualType DeclType,
1406 InitListExpr *StructuredList,
1407 unsigned &StructuredIndex) {
1408 if (Index >= IList->getNumInits()) {
1409 // FIXME: It would be wonderful if we could point at the actual member. In
1410 // general, it would be useful to pass location information down the stack,
1411 // so that we know the location (or decl) of the "current object" being
1414 SemaRef.Diag(IList->getLocStart(),
1415 diag::err_init_reference_member_uninitialized)
1417 << IList->getSourceRange();
1424 Expr *expr = IList->getInit(Index);
1425 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1427 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1428 << DeclType << IList->getSourceRange();
1436 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
1443 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1444 /*TopLevelOfInitList=*/true);
1446 if (Result.isInvalid())
1449 expr = Result.getAs<Expr>();
1450 IList->setInit(Index, expr);
1455 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1459 void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1460 InitListExpr *IList, QualType DeclType,
1462 InitListExpr *StructuredList,
1463 unsigned &StructuredIndex) {
1464 const VectorType *VT = DeclType->getAs<VectorType>();
1465 unsigned maxElements = VT->getNumElements();
1466 unsigned numEltsInit = 0;
1467 QualType elementType = VT->getElementType();
1469 if (Index >= IList->getNumInits()) {
1470 // Make sure the element type can be value-initialized.
1472 CheckEmptyInitializable(
1473 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1474 IList->getLocEnd());
1478 if (!SemaRef.getLangOpts().OpenCL) {
1479 // If the initializing element is a vector, try to copy-initialize
1480 // instead of breaking it apart (which is doomed to failure anyway).
1481 Expr *Init = IList->getInit(Index);
1482 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1484 if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
1491 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), Init,
1492 /*TopLevelOfInitList=*/true);
1494 Expr *ResultExpr = nullptr;
1495 if (Result.isInvalid())
1496 hadError = true; // types weren't compatible.
1498 ResultExpr = Result.getAs<Expr>();
1500 if (ResultExpr != Init) {
1501 // The type was promoted, update initializer list.
1502 IList->setInit(Index, ResultExpr);
1508 UpdateStructuredListElement(StructuredList, StructuredIndex,
1514 InitializedEntity ElementEntity =
1515 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1517 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1518 // Don't attempt to go past the end of the init list
1519 if (Index >= IList->getNumInits()) {
1521 CheckEmptyInitializable(ElementEntity, IList->getLocEnd());
1525 ElementEntity.setElementIndex(Index);
1526 CheckSubElementType(ElementEntity, IList, elementType, Index,
1527 StructuredList, StructuredIndex);
1533 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1534 const VectorType *T = Entity.getType()->getAs<VectorType>();
1535 if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1536 T->getVectorKind() == VectorType::NeonPolyVector)) {
1537 // The ability to use vector initializer lists is a GNU vector extension
1538 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1539 // endian machines it works fine, however on big endian machines it
1540 // exhibits surprising behaviour:
1542 // uint32x2_t x = {42, 64};
1543 // return vget_lane_u32(x, 0); // Will return 64.
1545 // Because of this, explicitly call out that it is non-portable.
1547 SemaRef.Diag(IList->getLocStart(),
1548 diag::warn_neon_vector_initializer_non_portable);
1550 const char *typeCode;
1551 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1553 if (elementType->isFloatingType())
1555 else if (elementType->isSignedIntegerType())
1557 else if (elementType->isUnsignedIntegerType())
1560 llvm_unreachable("Invalid element type!");
1562 SemaRef.Diag(IList->getLocStart(),
1563 SemaRef.Context.getTypeSize(VT) > 64 ?
1564 diag::note_neon_vector_initializer_non_portable_q :
1565 diag::note_neon_vector_initializer_non_portable)
1566 << typeCode << typeSize;
1572 InitializedEntity ElementEntity =
1573 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1575 // OpenCL initializers allows vectors to be constructed from vectors.
1576 for (unsigned i = 0; i < maxElements; ++i) {
1577 // Don't attempt to go past the end of the init list
1578 if (Index >= IList->getNumInits())
1581 ElementEntity.setElementIndex(Index);
1583 QualType IType = IList->getInit(Index)->getType();
1584 if (!IType->isVectorType()) {
1585 CheckSubElementType(ElementEntity, IList, elementType, Index,
1586 StructuredList, StructuredIndex);
1590 const VectorType *IVT = IType->getAs<VectorType>();
1591 unsigned numIElts = IVT->getNumElements();
1593 if (IType->isExtVectorType())
1594 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1596 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
1597 IVT->getVectorKind());
1598 CheckSubElementType(ElementEntity, IList, VecType, Index,
1599 StructuredList, StructuredIndex);
1600 numEltsInit += numIElts;
1604 // OpenCL requires all elements to be initialized.
1605 if (numEltsInit != maxElements) {
1607 SemaRef.Diag(IList->getLocStart(),
1608 diag::err_vector_incorrect_num_initializers)
1609 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1614 void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
1615 InitListExpr *IList, QualType &DeclType,
1616 llvm::APSInt elementIndex,
1617 bool SubobjectIsDesignatorContext,
1619 InitListExpr *StructuredList,
1620 unsigned &StructuredIndex) {
1621 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1623 // Check for the special-case of initializing an array with a string.
1624 if (Index < IList->getNumInits()) {
1625 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1627 // We place the string literal directly into the resulting
1628 // initializer list. This is the only place where the structure
1629 // of the structured initializer list doesn't match exactly,
1630 // because doing so would involve allocating one character
1631 // constant for each string.
1633 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1634 UpdateStructuredListElement(StructuredList, StructuredIndex,
1635 IList->getInit(Index));
1636 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1642 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
1643 // Check for VLAs; in standard C it would be possible to check this
1644 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1645 // them in all sorts of strange places).
1647 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1648 diag::err_variable_object_no_init)
1649 << VAT->getSizeExpr()->getSourceRange();
1656 // We might know the maximum number of elements in advance.
1657 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1658 elementIndex.isUnsigned());
1659 bool maxElementsKnown = false;
1660 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
1661 maxElements = CAT->getSize();
1662 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
1663 elementIndex.setIsUnsigned(maxElements.isUnsigned());
1664 maxElementsKnown = true;
1667 QualType elementType = arrayType->getElementType();
1668 while (Index < IList->getNumInits()) {
1669 Expr *Init = IList->getInit(Index);
1670 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1671 // If we're not the subobject that matches up with the '{' for
1672 // the designator, we shouldn't be handling the
1673 // designator. Return immediately.
1674 if (!SubobjectIsDesignatorContext)
1677 // Handle this designated initializer. elementIndex will be
1678 // updated to be the next array element we'll initialize.
1679 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1680 DeclType, nullptr, &elementIndex, Index,
1681 StructuredList, StructuredIndex, true,
1687 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1688 maxElements = maxElements.extend(elementIndex.getBitWidth());
1689 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1690 elementIndex = elementIndex.extend(maxElements.getBitWidth());
1691 elementIndex.setIsUnsigned(maxElements.isUnsigned());
1693 // If the array is of incomplete type, keep track of the number of
1694 // elements in the initializer.
1695 if (!maxElementsKnown && elementIndex > maxElements)
1696 maxElements = elementIndex;
1701 // If we know the maximum number of elements, and we've already
1702 // hit it, stop consuming elements in the initializer list.
1703 if (maxElementsKnown && elementIndex == maxElements)
1706 InitializedEntity ElementEntity =
1707 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
1709 // Check this element.
1710 CheckSubElementType(ElementEntity, IList, elementType, Index,
1711 StructuredList, StructuredIndex);
1714 // If the array is of incomplete type, keep track of the number of
1715 // elements in the initializer.
1716 if (!maxElementsKnown && elementIndex > maxElements)
1717 maxElements = elementIndex;
1719 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
1720 // If this is an incomplete array type, the actual type needs to
1721 // be calculated here.
1722 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
1723 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
1724 // Sizing an array implicitly to zero is not allowed by ISO C,
1725 // but is supported by GNU.
1726 SemaRef.Diag(IList->getLocStart(),
1727 diag::ext_typecheck_zero_array_size);
1730 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
1731 ArrayType::Normal, 0);
1733 if (!hadError && VerifyOnly) {
1734 // If there are any members of the array that get value-initialized, check
1735 // that is possible. That happens if we know the bound and don't have
1736 // enough elements, or if we're performing an array new with an unknown
1738 // FIXME: This needs to detect holes left by designated initializers too.
1739 if ((maxElementsKnown && elementIndex < maxElements) ||
1740 Entity.isVariableLengthArrayNew())
1741 CheckEmptyInitializable(InitializedEntity::InitializeElement(
1742 SemaRef.Context, 0, Entity),
1743 IList->getLocEnd());
1747 bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1750 bool TopLevelObject) {
1751 // Handle GNU flexible array initializers.
1752 unsigned FlexArrayDiag;
1753 if (isa<InitListExpr>(InitExpr) &&
1754 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1755 // Empty flexible array init always allowed as an extension
1756 FlexArrayDiag = diag::ext_flexible_array_init;
1757 } else if (SemaRef.getLangOpts().CPlusPlus) {
1758 // Disallow flexible array init in C++; it is not required for gcc
1759 // compatibility, and it needs work to IRGen correctly in general.
1760 FlexArrayDiag = diag::err_flexible_array_init;
1761 } else if (!TopLevelObject) {
1762 // Disallow flexible array init on non-top-level object
1763 FlexArrayDiag = diag::err_flexible_array_init;
1764 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1765 // Disallow flexible array init on anything which is not a variable.
1766 FlexArrayDiag = diag::err_flexible_array_init;
1767 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1768 // Disallow flexible array init on local variables.
1769 FlexArrayDiag = diag::err_flexible_array_init;
1771 // Allow other cases.
1772 FlexArrayDiag = diag::ext_flexible_array_init;
1776 SemaRef.Diag(InitExpr->getLocStart(),
1778 << InitExpr->getLocStart();
1779 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1783 return FlexArrayDiag != diag::ext_flexible_array_init;
1786 void InitListChecker::CheckStructUnionTypes(
1787 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
1788 CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field,
1789 bool SubobjectIsDesignatorContext, unsigned &Index,
1790 InitListExpr *StructuredList, unsigned &StructuredIndex,
1791 bool TopLevelObject) {
1792 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
1794 // If the record is invalid, some of it's members are invalid. To avoid
1795 // confusion, we forgo checking the intializer for the entire record.
1796 if (structDecl->isInvalidDecl()) {
1797 // Assume it was supposed to consume a single initializer.
1803 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1804 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1806 // If there's a default initializer, use it.
1807 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1810 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1811 Field != FieldEnd; ++Field) {
1812 if (Field->hasInClassInitializer()) {
1813 StructuredList->setInitializedFieldInUnion(*Field);
1814 // FIXME: Actually build a CXXDefaultInitExpr?
1820 // Value-initialize the first member of the union that isn't an unnamed
1822 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1823 Field != FieldEnd; ++Field) {
1824 if (!Field->isUnnamedBitfield()) {
1826 CheckEmptyInitializable(
1827 InitializedEntity::InitializeMember(*Field, &Entity),
1828 IList->getLocEnd());
1830 StructuredList->setInitializedFieldInUnion(*Field);
1837 bool InitializedSomething = false;
1839 // If we have any base classes, they are initialized prior to the fields.
1840 for (auto &Base : Bases) {
1841 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
1842 SourceLocation InitLoc = Init ? Init->getLocStart() : IList->getLocEnd();
1844 // Designated inits always initialize fields, so if we see one, all
1845 // remaining base classes have no explicit initializer.
1846 if (Init && isa<DesignatedInitExpr>(Init))
1849 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
1850 SemaRef.Context, &Base, false, &Entity);
1852 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
1853 StructuredList, StructuredIndex);
1854 InitializedSomething = true;
1855 } else if (VerifyOnly) {
1856 CheckEmptyInitializable(BaseEntity, InitLoc);
1860 // If structDecl is a forward declaration, this loop won't do
1861 // anything except look at designated initializers; That's okay,
1862 // because an error should get printed out elsewhere. It might be
1863 // worthwhile to skip over the rest of the initializer, though.
1864 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1865 RecordDecl::field_iterator FieldEnd = RD->field_end();
1866 bool CheckForMissingFields =
1867 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
1869 while (Index < IList->getNumInits()) {
1870 Expr *Init = IList->getInit(Index);
1872 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1873 // If we're not the subobject that matches up with the '{' for
1874 // the designator, we shouldn't be handling the
1875 // designator. Return immediately.
1876 if (!SubobjectIsDesignatorContext)
1879 // Handle this designated initializer. Field will be updated to
1880 // the next field that we'll be initializing.
1881 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1882 DeclType, &Field, nullptr, Index,
1883 StructuredList, StructuredIndex,
1884 true, TopLevelObject))
1887 InitializedSomething = true;
1889 // Disable check for missing fields when designators are used.
1890 // This matches gcc behaviour.
1891 CheckForMissingFields = false;
1895 if (Field == FieldEnd) {
1896 // We've run out of fields. We're done.
1900 // We've already initialized a member of a union. We're done.
1901 if (InitializedSomething && DeclType->isUnionType())
1904 // If we've hit the flexible array member at the end, we're done.
1905 if (Field->getType()->isIncompleteArrayType())
1908 if (Field->isUnnamedBitfield()) {
1909 // Don't initialize unnamed bitfields, e.g. "int : 20;"
1914 // Make sure we can use this declaration.
1917 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
1919 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1920 IList->getInit(Index)->getLocStart());
1928 InitializedEntity MemberEntity =
1929 InitializedEntity::InitializeMember(*Field, &Entity);
1930 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1931 StructuredList, StructuredIndex);
1932 InitializedSomething = true;
1934 if (DeclType->isUnionType() && !VerifyOnly) {
1935 // Initialize the first field within the union.
1936 StructuredList->setInitializedFieldInUnion(*Field);
1942 // Emit warnings for missing struct field initializers.
1943 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1944 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1945 !DeclType->isUnionType()) {
1946 // It is possible we have one or more unnamed bitfields remaining.
1947 // Find first (if any) named field and emit warning.
1948 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1950 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
1951 SemaRef.Diag(IList->getSourceRange().getEnd(),
1952 diag::warn_missing_field_initializers) << *it;
1958 // Check that any remaining fields can be value-initialized.
1959 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1960 !Field->getType()->isIncompleteArrayType()) {
1961 // FIXME: Should check for holes left by designated initializers too.
1962 for (; Field != FieldEnd && !hadError; ++Field) {
1963 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
1964 CheckEmptyInitializable(
1965 InitializedEntity::InitializeMember(*Field, &Entity),
1966 IList->getLocEnd());
1970 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
1971 Index >= IList->getNumInits())
1974 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1981 InitializedEntity MemberEntity =
1982 InitializedEntity::InitializeMember(*Field, &Entity);
1984 if (isa<InitListExpr>(IList->getInit(Index)))
1985 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1986 StructuredList, StructuredIndex);
1988 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
1989 StructuredList, StructuredIndex);
1992 /// \brief Expand a field designator that refers to a member of an
1993 /// anonymous struct or union into a series of field designators that
1994 /// refers to the field within the appropriate subobject.
1996 static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
1997 DesignatedInitExpr *DIE,
1999 IndirectFieldDecl *IndirectField) {
2000 typedef DesignatedInitExpr::Designator Designator;
2002 // Build the replacement designators.
2003 SmallVector<Designator, 4> Replacements;
2004 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2005 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2007 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
2008 DIE->getDesignator(DesigIdx)->getDotLoc(),
2009 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2011 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
2012 SourceLocation(), SourceLocation()));
2013 assert(isa<FieldDecl>(*PI));
2014 Replacements.back().setField(cast<FieldDecl>(*PI));
2017 // Expand the current designator into the set of replacement
2018 // designators, so we have a full subobject path down to where the
2019 // member of the anonymous struct/union is actually stored.
2020 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
2021 &Replacements[0] + Replacements.size());
2024 static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
2025 DesignatedInitExpr *DIE) {
2026 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2027 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2028 for (unsigned I = 0; I < NumIndexExprs; ++I)
2029 IndexExprs[I] = DIE->getSubExpr(I + 1);
2030 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2032 DIE->getEqualOrColonLoc(),
2033 DIE->usesGNUSyntax(), DIE->getInit());
2038 // Callback to only accept typo corrections that are for field members of
2039 // the given struct or union.
2040 class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
2042 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
2045 bool ValidateCandidate(const TypoCorrection &candidate) override {
2046 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2047 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2054 } // end anonymous namespace
2056 /// @brief Check the well-formedness of a C99 designated initializer.
2058 /// Determines whether the designated initializer @p DIE, which
2059 /// resides at the given @p Index within the initializer list @p
2060 /// IList, is well-formed for a current object of type @p DeclType
2061 /// (C99 6.7.8). The actual subobject that this designator refers to
2062 /// within the current subobject is returned in either
2063 /// @p NextField or @p NextElementIndex (whichever is appropriate).
2065 /// @param IList The initializer list in which this designated
2066 /// initializer occurs.
2068 /// @param DIE The designated initializer expression.
2070 /// @param DesigIdx The index of the current designator.
2072 /// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2073 /// into which the designation in @p DIE should refer.
2075 /// @param NextField If non-NULL and the first designator in @p DIE is
2076 /// a field, this will be set to the field declaration corresponding
2077 /// to the field named by the designator.
2079 /// @param NextElementIndex If non-NULL and the first designator in @p
2080 /// DIE is an array designator or GNU array-range designator, this
2081 /// will be set to the last index initialized by this designator.
2083 /// @param Index Index into @p IList where the designated initializer
2086 /// @param StructuredList The initializer list expression that
2087 /// describes all of the subobject initializers in the order they'll
2088 /// actually be initialized.
2090 /// @returns true if there was an error, false otherwise.
2092 InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2093 InitListExpr *IList,
2094 DesignatedInitExpr *DIE,
2096 QualType &CurrentObjectType,
2097 RecordDecl::field_iterator *NextField,
2098 llvm::APSInt *NextElementIndex,
2100 InitListExpr *StructuredList,
2101 unsigned &StructuredIndex,
2102 bool FinishSubobjectInit,
2103 bool TopLevelObject) {
2104 if (DesigIdx == DIE->size()) {
2105 // Check the actual initialization for the designated object type.
2106 bool prevHadError = hadError;
2108 // Temporarily remove the designator expression from the
2109 // initializer list that the child calls see, so that we don't try
2110 // to re-process the designator.
2111 unsigned OldIndex = Index;
2112 IList->setInit(OldIndex, DIE->getInit());
2114 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
2115 StructuredList, StructuredIndex);
2117 // Restore the designated initializer expression in the syntactic
2118 // form of the initializer list.
2119 if (IList->getInit(OldIndex) != DIE->getInit())
2120 DIE->setInit(IList->getInit(OldIndex));
2121 IList->setInit(OldIndex, DIE);
2123 return hadError && !prevHadError;
2126 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
2127 bool IsFirstDesignator = (DesigIdx == 0);
2129 assert((IsFirstDesignator || StructuredList) &&
2130 "Need a non-designated initializer list to start from");
2132 // Determine the structural initializer list that corresponds to the
2133 // current subobject.
2134 if (IsFirstDesignator)
2135 StructuredList = SyntacticToSemantic.lookup(IList);
2137 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2138 StructuredList->getInit(StructuredIndex) : nullptr;
2139 if (!ExistingInit && StructuredList->hasArrayFiller())
2140 ExistingInit = StructuredList->getArrayFiller();
2144 getStructuredSubobjectInit(IList, Index, CurrentObjectType,
2145 StructuredList, StructuredIndex,
2146 SourceRange(D->getLocStart(),
2148 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2149 StructuredList = Result;
2151 if (DesignatedInitUpdateExpr *E =
2152 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2153 StructuredList = E->getUpdater();
2155 DesignatedInitUpdateExpr *DIUE =
2156 new (SemaRef.Context) DesignatedInitUpdateExpr(SemaRef.Context,
2157 D->getLocStart(), ExistingInit,
2159 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2160 StructuredList = DIUE->getUpdater();
2163 // We need to check on source range validity because the previous
2164 // initializer does not have to be an explicit initializer. e.g.,
2166 // struct P { int a, b; };
2167 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2169 // There is an overwrite taking place because the first braced initializer
2170 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
2171 if (ExistingInit->getSourceRange().isValid()) {
2172 // We are creating an initializer list that initializes the
2173 // subobjects of the current object, but there was already an
2174 // initialization that completely initialized the current
2175 // subobject, e.g., by a compound literal:
2177 // struct X { int a, b; };
2178 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2180 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2181 // designated initializer re-initializes the whole
2182 // subobject [0], overwriting previous initializers.
2183 SemaRef.Diag(D->getLocStart(),
2184 diag::warn_subobject_initializer_overrides)
2185 << SourceRange(D->getLocStart(), DIE->getLocEnd());
2187 SemaRef.Diag(ExistingInit->getLocStart(),
2188 diag::note_previous_initializer)
2189 << /*FIXME:has side effects=*/0
2190 << ExistingInit->getSourceRange();
2194 assert(StructuredList && "Expected a structured initializer list");
2197 if (D->isFieldDesignator()) {
2200 // If a designator has the form
2204 // then the current object (defined below) shall have
2205 // structure or union type and the identifier shall be the
2206 // name of a member of that type.
2207 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
2209 SourceLocation Loc = D->getDotLoc();
2210 if (Loc.isInvalid())
2211 Loc = D->getFieldLoc();
2213 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
2214 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2219 FieldDecl *KnownField = D->getField();
2221 IdentifierInfo *FieldName = D->getFieldName();
2222 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
2223 for (NamedDecl *ND : Lookup) {
2224 if (auto *FD = dyn_cast<FieldDecl>(ND)) {
2228 if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
2229 // In verify mode, don't modify the original.
2231 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2232 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
2233 D = DIE->getDesignator(DesigIdx);
2234 KnownField = cast<FieldDecl>(*IFD->chain_begin());
2241 return true; // No typo correction when just trying this out.
2244 // Name lookup found something, but it wasn't a field.
2245 if (!Lookup.empty()) {
2246 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2248 SemaRef.Diag(Lookup.front()->getLocation(),
2249 diag::note_field_designator_found);
2254 // Name lookup didn't find anything.
2255 // Determine whether this was a typo for another field name.
2256 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2257 DeclarationNameInfo(FieldName, D->getFieldLoc()),
2258 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr,
2259 llvm::make_unique<FieldInitializerValidatorCCC>(RT->getDecl()),
2260 Sema::CTK_ErrorRecovery, RT->getDecl())) {
2261 SemaRef.diagnoseTypo(
2263 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
2264 << FieldName << CurrentObjectType);
2265 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
2268 // Typo correction didn't find anything.
2269 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
2270 << FieldName << CurrentObjectType;
2277 unsigned FieldIndex = 0;
2279 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2280 FieldIndex = CXXRD->getNumBases();
2282 for (auto *FI : RT->getDecl()->fields()) {
2283 if (FI->isUnnamedBitfield())
2285 if (declaresSameEntity(KnownField, FI)) {
2292 RecordDecl::field_iterator Field =
2293 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
2295 // All of the fields of a union are located at the same place in
2296 // the initializer list.
2297 if (RT->getDecl()->isUnion()) {
2300 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
2301 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
2302 assert(StructuredList->getNumInits() == 1
2303 && "A union should never have more than one initializer!");
2305 Expr *ExistingInit = StructuredList->getInit(0);
2307 // We're about to throw away an initializer, emit warning.
2308 SemaRef.Diag(D->getFieldLoc(),
2309 diag::warn_initializer_overrides)
2310 << D->getSourceRange();
2311 SemaRef.Diag(ExistingInit->getLocStart(),
2312 diag::note_previous_initializer)
2313 << /*FIXME:has side effects=*/0
2314 << ExistingInit->getSourceRange();
2317 // remove existing initializer
2318 StructuredList->resizeInits(SemaRef.Context, 0);
2319 StructuredList->setInitializedFieldInUnion(nullptr);
2322 StructuredList->setInitializedFieldInUnion(*Field);
2326 // Make sure we can use this declaration.
2329 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2331 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
2338 // Update the designator with the field declaration.
2339 D->setField(*Field);
2341 // Make sure that our non-designated initializer list has space
2342 // for a subobject corresponding to this field.
2343 if (FieldIndex >= StructuredList->getNumInits())
2344 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2347 // This designator names a flexible array member.
2348 if (Field->getType()->isIncompleteArrayType()) {
2349 bool Invalid = false;
2350 if ((DesigIdx + 1) != DIE->size()) {
2351 // We can't designate an object within the flexible array
2352 // member (because GCC doesn't allow it).
2354 DesignatedInitExpr::Designator *NextD
2355 = DIE->getDesignator(DesigIdx + 1);
2356 SemaRef.Diag(NextD->getLocStart(),
2357 diag::err_designator_into_flexible_array_member)
2358 << SourceRange(NextD->getLocStart(),
2360 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2366 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2367 !isa<StringLiteral>(DIE->getInit())) {
2368 // The initializer is not an initializer list.
2370 SemaRef.Diag(DIE->getInit()->getLocStart(),
2371 diag::err_flexible_array_init_needs_braces)
2372 << DIE->getInit()->getSourceRange();
2373 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2379 // Check GNU flexible array initializer.
2380 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
2389 // Initialize the array.
2390 bool prevHadError = hadError;
2391 unsigned newStructuredIndex = FieldIndex;
2392 unsigned OldIndex = Index;
2393 IList->setInit(Index, DIE->getInit());
2395 InitializedEntity MemberEntity =
2396 InitializedEntity::InitializeMember(*Field, &Entity);
2397 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2398 StructuredList, newStructuredIndex);
2400 IList->setInit(OldIndex, DIE);
2401 if (hadError && !prevHadError) {
2406 StructuredIndex = FieldIndex;
2410 // Recurse to check later designated subobjects.
2411 QualType FieldType = Field->getType();
2412 unsigned newStructuredIndex = FieldIndex;
2414 InitializedEntity MemberEntity =
2415 InitializedEntity::InitializeMember(*Field, &Entity);
2416 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
2417 FieldType, nullptr, nullptr, Index,
2418 StructuredList, newStructuredIndex,
2419 FinishSubobjectInit, false))
2423 // Find the position of the next field to be initialized in this
2428 // If this the first designator, our caller will continue checking
2429 // the rest of this struct/class/union subobject.
2430 if (IsFirstDesignator) {
2433 StructuredIndex = FieldIndex;
2437 if (!FinishSubobjectInit)
2440 // We've already initialized something in the union; we're done.
2441 if (RT->getDecl()->isUnion())
2444 // Check the remaining fields within this class/struct/union subobject.
2445 bool prevHadError = hadError;
2448 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
2449 CXXRecordDecl::base_class_iterator());
2450 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
2451 false, Index, StructuredList, FieldIndex);
2452 return hadError && !prevHadError;
2457 // If a designator has the form
2459 // [ constant-expression ]
2461 // then the current object (defined below) shall have array
2462 // type and the expression shall be an integer constant
2463 // expression. If the array is of unknown size, any
2464 // nonnegative value is valid.
2466 // Additionally, cope with the GNU extension that permits
2467 // designators of the form
2469 // [ constant-expression ... constant-expression ]
2470 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
2473 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2474 << CurrentObjectType;
2479 Expr *IndexExpr = nullptr;
2480 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2481 if (D->isArrayDesignator()) {
2482 IndexExpr = DIE->getArrayIndex(*D);
2483 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
2484 DesignatedEndIndex = DesignatedStartIndex;
2486 assert(D->isArrayRangeDesignator() && "Need array-range designator");
2488 DesignatedStartIndex =
2489 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
2490 DesignatedEndIndex =
2491 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
2492 IndexExpr = DIE->getArrayRangeEnd(*D);
2494 // Codegen can't handle evaluating array range designators that have side
2495 // effects, because we replicate the AST value for each initialized element.
2496 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2497 // elements with something that has a side effect, so codegen can emit an
2498 // "error unsupported" error instead of miscompiling the app.
2499 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
2500 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
2501 FullyStructuredList->sawArrayRangeDesignator();
2504 if (isa<ConstantArrayType>(AT)) {
2505 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
2506 DesignatedStartIndex
2507 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
2508 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
2510 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
2511 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2512 if (DesignatedEndIndex >= MaxElements) {
2514 SemaRef.Diag(IndexExpr->getLocStart(),
2515 diag::err_array_designator_too_large)
2516 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2517 << IndexExpr->getSourceRange();
2522 unsigned DesignatedIndexBitWidth =
2523 ConstantArrayType::getMaxSizeBits(SemaRef.Context);
2524 DesignatedStartIndex =
2525 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
2526 DesignatedEndIndex =
2527 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
2528 DesignatedStartIndex.setIsUnsigned(true);
2529 DesignatedEndIndex.setIsUnsigned(true);
2532 if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2533 // We're modifying a string literal init; we have to decompose the string
2534 // so we can modify the individual characters.
2535 ASTContext &Context = SemaRef.Context;
2536 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2538 // Compute the character type
2539 QualType CharTy = AT->getElementType();
2541 // Compute the type of the integer literals.
2542 QualType PromotedCharTy = CharTy;
2543 if (CharTy->isPromotableIntegerType())
2544 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2545 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2547 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2548 // Get the length of the string.
2549 uint64_t StrLen = SL->getLength();
2550 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2551 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2552 StructuredList->resizeInits(Context, StrLen);
2554 // Build a literal for each character in the string, and put them into
2556 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2557 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2558 Expr *Init = new (Context) IntegerLiteral(
2559 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2560 if (CharTy != PromotedCharTy)
2561 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2562 Init, nullptr, VK_RValue);
2563 StructuredList->updateInit(Context, i, Init);
2566 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2568 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2570 // Get the length of the string.
2571 uint64_t StrLen = Str.size();
2572 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2573 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2574 StructuredList->resizeInits(Context, StrLen);
2576 // Build a literal for each character in the string, and put them into
2578 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2579 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2580 Expr *Init = new (Context) IntegerLiteral(
2581 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2582 if (CharTy != PromotedCharTy)
2583 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2584 Init, nullptr, VK_RValue);
2585 StructuredList->updateInit(Context, i, Init);
2590 // Make sure that our non-designated initializer list has space
2591 // for a subobject corresponding to this array element.
2593 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
2594 StructuredList->resizeInits(SemaRef.Context,
2595 DesignatedEndIndex.getZExtValue() + 1);
2597 // Repeatedly perform subobject initializations in the range
2598 // [DesignatedStartIndex, DesignatedEndIndex].
2600 // Move to the next designator
2601 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2602 unsigned OldIndex = Index;
2604 InitializedEntity ElementEntity =
2605 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
2607 while (DesignatedStartIndex <= DesignatedEndIndex) {
2608 // Recurse to check later designated subobjects.
2609 QualType ElementType = AT->getElementType();
2612 ElementEntity.setElementIndex(ElementIndex);
2613 if (CheckDesignatedInitializer(
2614 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
2615 nullptr, Index, StructuredList, ElementIndex,
2616 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
2620 // Move to the next index in the array that we'll be initializing.
2621 ++DesignatedStartIndex;
2622 ElementIndex = DesignatedStartIndex.getZExtValue();
2625 // If this the first designator, our caller will continue checking
2626 // the rest of this array subobject.
2627 if (IsFirstDesignator) {
2628 if (NextElementIndex)
2629 *NextElementIndex = DesignatedStartIndex;
2630 StructuredIndex = ElementIndex;
2634 if (!FinishSubobjectInit)
2637 // Check the remaining elements within this array subobject.
2638 bool prevHadError = hadError;
2639 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
2640 /*SubobjectIsDesignatorContext=*/false, Index,
2641 StructuredList, ElementIndex);
2642 return hadError && !prevHadError;
2645 // Get the structured initializer list for a subobject of type
2646 // @p CurrentObjectType.
2648 InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2649 QualType CurrentObjectType,
2650 InitListExpr *StructuredList,
2651 unsigned StructuredIndex,
2652 SourceRange InitRange,
2653 bool IsFullyOverwritten) {
2655 return nullptr; // No structured list in verification-only mode.
2656 Expr *ExistingInit = nullptr;
2657 if (!StructuredList)
2658 ExistingInit = SyntacticToSemantic.lookup(IList);
2659 else if (StructuredIndex < StructuredList->getNumInits())
2660 ExistingInit = StructuredList->getInit(StructuredIndex);
2662 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2663 // There might have already been initializers for subobjects of the current
2664 // object, but a subsequent initializer list will overwrite the entirety
2665 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
2667 // struct P { char x[6]; };
2668 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
2670 // The first designated initializer is ignored, and l.x is just "f".
2671 if (!IsFullyOverwritten)
2675 // We are creating an initializer list that initializes the
2676 // subobjects of the current object, but there was already an
2677 // initialization that completely initialized the current
2678 // subobject, e.g., by a compound literal:
2680 // struct X { int a, b; };
2681 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2683 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2684 // designated initializer re-initializes the whole
2685 // subobject [0], overwriting previous initializers.
2686 SemaRef.Diag(InitRange.getBegin(),
2687 diag::warn_subobject_initializer_overrides)
2689 SemaRef.Diag(ExistingInit->getLocStart(),
2690 diag::note_previous_initializer)
2691 << /*FIXME:has side effects=*/0
2692 << ExistingInit->getSourceRange();
2695 InitListExpr *Result
2696 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2697 InitRange.getBegin(), None,
2698 InitRange.getEnd());
2700 QualType ResultType = CurrentObjectType;
2701 if (!ResultType->isArrayType())
2702 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2703 Result->setType(ResultType);
2705 // Pre-allocate storage for the structured initializer list.
2706 unsigned NumElements = 0;
2707 unsigned NumInits = 0;
2708 bool GotNumInits = false;
2709 if (!StructuredList) {
2710 NumInits = IList->getNumInits();
2712 } else if (Index < IList->getNumInits()) {
2713 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
2714 NumInits = SubList->getNumInits();
2719 if (const ArrayType *AType
2720 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2721 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2722 NumElements = CAType->getSize().getZExtValue();
2723 // Simple heuristic so that we don't allocate a very large
2724 // initializer with many empty entries at the end.
2725 if (GotNumInits && NumElements > NumInits)
2728 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
2729 NumElements = VType->getNumElements();
2730 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
2731 RecordDecl *RDecl = RType->getDecl();
2732 if (RDecl->isUnion())
2735 NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
2738 Result->reserveInits(SemaRef.Context, NumElements);
2740 // Link this new initializer list into the structured initializer
2743 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
2745 Result->setSyntacticForm(IList);
2746 SyntacticToSemantic[IList] = Result;
2752 /// Update the initializer at index @p StructuredIndex within the
2753 /// structured initializer list to the value @p expr.
2754 void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2755 unsigned &StructuredIndex,
2757 // No structured initializer list to update
2758 if (!StructuredList)
2761 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2762 StructuredIndex, expr)) {
2763 // This initializer overwrites a previous initializer. Warn.
2764 // We need to check on source range validity because the previous
2765 // initializer does not have to be an explicit initializer.
2766 // struct P { int a, b; };
2767 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2768 // There is an overwrite taking place because the first braced initializer
2769 // list "{ .a = 2 }' already provides value for .p.b (which is zero).
2770 if (PrevInit->getSourceRange().isValid()) {
2771 SemaRef.Diag(expr->getLocStart(),
2772 diag::warn_initializer_overrides)
2773 << expr->getSourceRange();
2775 SemaRef.Diag(PrevInit->getLocStart(),
2776 diag::note_previous_initializer)
2777 << /*FIXME:has side effects=*/0
2778 << PrevInit->getSourceRange();
2785 /// Check that the given Index expression is a valid array designator
2786 /// value. This is essentially just a wrapper around
2787 /// VerifyIntegerConstantExpression that also checks for negative values
2788 /// and produces a reasonable diagnostic if there is a
2789 /// failure. Returns the index expression, possibly with an implicit cast
2790 /// added, on success. If everything went okay, Value will receive the
2791 /// value of the constant expression.
2793 CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
2794 SourceLocation Loc = Index->getLocStart();
2796 // Make sure this is an integer constant expression.
2797 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2798 if (Result.isInvalid())
2801 if (Value.isSigned() && Value.isNegative())
2802 return S.Diag(Loc, diag::err_array_designator_negative)
2803 << Value.toString(10) << Index->getSourceRange();
2805 Value.setIsUnsigned(true);
2809 ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
2813 typedef DesignatedInitExpr::Designator ASTDesignator;
2815 bool Invalid = false;
2816 SmallVector<ASTDesignator, 32> Designators;
2817 SmallVector<Expr *, 32> InitExpressions;
2819 // Build designators and check array designator expressions.
2820 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2821 const Designator &D = Desig.getDesignator(Idx);
2822 switch (D.getKind()) {
2823 case Designator::FieldDesignator:
2824 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
2828 case Designator::ArrayDesignator: {
2829 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2830 llvm::APSInt IndexValue;
2831 if (!Index->isTypeDependent() && !Index->isValueDependent())
2832 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
2836 Designators.push_back(ASTDesignator(InitExpressions.size(),
2838 D.getRBracketLoc()));
2839 InitExpressions.push_back(Index);
2844 case Designator::ArrayRangeDesignator: {
2845 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2846 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2847 llvm::APSInt StartValue;
2848 llvm::APSInt EndValue;
2849 bool StartDependent = StartIndex->isTypeDependent() ||
2850 StartIndex->isValueDependent();
2851 bool EndDependent = EndIndex->isTypeDependent() ||
2852 EndIndex->isValueDependent();
2853 if (!StartDependent)
2855 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
2857 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
2859 if (!StartIndex || !EndIndex)
2862 // Make sure we're comparing values with the same bit width.
2863 if (StartDependent || EndDependent) {
2864 // Nothing to compute.
2865 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
2866 EndValue = EndValue.extend(StartValue.getBitWidth());
2867 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
2868 StartValue = StartValue.extend(EndValue.getBitWidth());
2870 if (!StartDependent && !EndDependent && EndValue < StartValue) {
2871 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
2872 << StartValue.toString(10) << EndValue.toString(10)
2873 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2876 Designators.push_back(ASTDesignator(InitExpressions.size(),
2879 D.getRBracketLoc()));
2880 InitExpressions.push_back(StartIndex);
2881 InitExpressions.push_back(EndIndex);
2889 if (Invalid || Init.isInvalid())
2892 // Clear out the expressions within the designation.
2893 Desig.ClearExprs(*this);
2895 DesignatedInitExpr *DIE
2896 = DesignatedInitExpr::Create(Context,
2898 InitExpressions, Loc, GNUSyntax,
2899 Init.getAs<Expr>());
2901 if (!getLangOpts().C99)
2902 Diag(DIE->getLocStart(), diag::ext_designated_init)
2903 << DIE->getSourceRange();
2908 //===----------------------------------------------------------------------===//
2909 // Initialization entity
2910 //===----------------------------------------------------------------------===//
2912 InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
2913 const InitializedEntity &Parent)
2914 : Parent(&Parent), Index(Index)
2916 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2917 Kind = EK_ArrayElement;
2918 Type = AT->getElementType();
2919 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
2920 Kind = EK_VectorElement;
2921 Type = VT->getElementType();
2923 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2924 assert(CT && "Unexpected type");
2925 Kind = EK_ComplexElement;
2926 Type = CT->getElementType();
2931 InitializedEntity::InitializeBase(ASTContext &Context,
2932 const CXXBaseSpecifier *Base,
2933 bool IsInheritedVirtualBase,
2934 const InitializedEntity *Parent) {
2935 InitializedEntity Result;
2936 Result.Kind = EK_Base;
2937 Result.Parent = Parent;
2938 Result.Base = reinterpret_cast<uintptr_t>(Base);
2939 if (IsInheritedVirtualBase)
2940 Result.Base |= 0x01;
2942 Result.Type = Base->getType();
2946 DeclarationName InitializedEntity::getName() const {
2947 switch (getKind()) {
2949 case EK_Parameter_CF_Audited: {
2950 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2951 return (D ? D->getDeclName() : DeclarationName());
2957 return Variable.VariableOrMember->getDeclName();
2959 case EK_LambdaCapture:
2960 return DeclarationName(Capture.VarID);
2968 case EK_ArrayElement:
2969 case EK_VectorElement:
2970 case EK_ComplexElement:
2971 case EK_BlockElement:
2972 case EK_LambdaToBlockConversionBlockElement:
2973 case EK_CompoundLiteralInit:
2974 case EK_RelatedResult:
2975 return DeclarationName();
2978 llvm_unreachable("Invalid EntityKind!");
2981 ValueDecl *InitializedEntity::getDecl() const {
2982 switch (getKind()) {
2986 return Variable.VariableOrMember;
2989 case EK_Parameter_CF_Audited:
2990 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2998 case EK_ArrayElement:
2999 case EK_VectorElement:
3000 case EK_ComplexElement:
3001 case EK_BlockElement:
3002 case EK_LambdaToBlockConversionBlockElement:
3003 case EK_LambdaCapture:
3004 case EK_CompoundLiteralInit:
3005 case EK_RelatedResult:
3009 llvm_unreachable("Invalid EntityKind!");
3012 bool InitializedEntity::allowsNRVO() const {
3013 switch (getKind()) {
3016 return LocAndNRVO.NRVO;
3020 case EK_Parameter_CF_Audited:
3025 case EK_CompoundLiteralInit:
3028 case EK_ArrayElement:
3029 case EK_VectorElement:
3030 case EK_ComplexElement:
3031 case EK_BlockElement:
3032 case EK_LambdaToBlockConversionBlockElement:
3033 case EK_LambdaCapture:
3034 case EK_RelatedResult:
3041 unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
3042 assert(getParent() != this);
3043 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3044 for (unsigned I = 0; I != Depth; ++I)
3047 switch (getKind()) {
3048 case EK_Variable: OS << "Variable"; break;
3049 case EK_Parameter: OS << "Parameter"; break;
3050 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3052 case EK_Result: OS << "Result"; break;
3053 case EK_Exception: OS << "Exception"; break;
3054 case EK_Member: OS << "Member"; break;
3055 case EK_Binding: OS << "Binding"; break;
3056 case EK_New: OS << "New"; break;
3057 case EK_Temporary: OS << "Temporary"; break;
3058 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
3059 case EK_RelatedResult: OS << "RelatedResult"; break;
3060 case EK_Base: OS << "Base"; break;
3061 case EK_Delegating: OS << "Delegating"; break;
3062 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3063 case EK_VectorElement: OS << "VectorElement " << Index; break;
3064 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3065 case EK_BlockElement: OS << "Block"; break;
3066 case EK_LambdaToBlockConversionBlockElement:
3067 OS << "Block (lambda)";
3069 case EK_LambdaCapture:
3070 OS << "LambdaCapture ";
3071 OS << DeclarationName(Capture.VarID);
3075 if (auto *D = getDecl()) {
3077 D->printQualifiedName(OS);
3080 OS << " '" << getType().getAsString() << "'\n";
3085 LLVM_DUMP_METHOD void InitializedEntity::dump() const {
3086 dumpImpl(llvm::errs());
3089 //===----------------------------------------------------------------------===//
3090 // Initialization sequence
3091 //===----------------------------------------------------------------------===//
3093 void InitializationSequence::Step::Destroy() {
3095 case SK_ResolveAddressOfOverloadedFunction:
3096 case SK_CastDerivedToBaseRValue:
3097 case SK_CastDerivedToBaseXValue:
3098 case SK_CastDerivedToBaseLValue:
3099 case SK_BindReference:
3100 case SK_BindReferenceToTemporary:
3102 case SK_ExtraneousCopyToTemporary:
3103 case SK_UserConversion:
3104 case SK_QualificationConversionRValue:
3105 case SK_QualificationConversionXValue:
3106 case SK_QualificationConversionLValue:
3107 case SK_AtomicConversion:
3108 case SK_LValueToRValue:
3109 case SK_ListInitialization:
3110 case SK_UnwrapInitList:
3111 case SK_RewrapInitList:
3112 case SK_ConstructorInitialization:
3113 case SK_ConstructorInitializationFromList:
3114 case SK_ZeroInitialization:
3115 case SK_CAssignment:
3117 case SK_ObjCObjectConversion:
3118 case SK_ArrayLoopIndex:
3119 case SK_ArrayLoopInit:
3121 case SK_GNUArrayInit:
3122 case SK_ParenthesizedArrayInit:
3123 case SK_PassByIndirectCopyRestore:
3124 case SK_PassByIndirectRestore:
3125 case SK_ProduceObjCObject:
3126 case SK_StdInitializerList:
3127 case SK_StdInitializerListConstructorCall:
3128 case SK_OCLSamplerInit:
3129 case SK_OCLZeroEvent:
3130 case SK_OCLZeroQueue:
3133 case SK_ConversionSequence:
3134 case SK_ConversionSequenceNoNarrowing:
3139 bool InitializationSequence::isDirectReferenceBinding() const {
3140 // There can be some lvalue adjustments after the SK_BindReference step.
3141 for (auto I = Steps.rbegin(); I != Steps.rend(); ++I) {
3142 if (I->Kind == SK_BindReference)
3144 if (I->Kind == SK_BindReferenceToTemporary)
3150 bool InitializationSequence::isAmbiguous() const {
3154 switch (getFailureKind()) {
3155 case FK_TooManyInitsForReference:
3156 case FK_ParenthesizedListInitForReference:
3157 case FK_ArrayNeedsInitList:
3158 case FK_ArrayNeedsInitListOrStringLiteral:
3159 case FK_ArrayNeedsInitListOrWideStringLiteral:
3160 case FK_NarrowStringIntoWideCharArray:
3161 case FK_WideStringIntoCharArray:
3162 case FK_IncompatWideStringIntoWideChar:
3163 case FK_AddressOfOverloadFailed: // FIXME: Could do better
3164 case FK_NonConstLValueReferenceBindingToTemporary:
3165 case FK_NonConstLValueReferenceBindingToBitfield:
3166 case FK_NonConstLValueReferenceBindingToVectorElement:
3167 case FK_NonConstLValueReferenceBindingToUnrelated:
3168 case FK_RValueReferenceBindingToLValue:
3169 case FK_ReferenceInitDropsQualifiers:
3170 case FK_ReferenceInitFailed:
3171 case FK_ConversionFailed:
3172 case FK_ConversionFromPropertyFailed:
3173 case FK_TooManyInitsForScalar:
3174 case FK_ParenthesizedListInitForScalar:
3175 case FK_ReferenceBindingToInitList:
3176 case FK_InitListBadDestinationType:
3177 case FK_DefaultInitOfConst:
3179 case FK_ArrayTypeMismatch:
3180 case FK_NonConstantArrayInit:
3181 case FK_ListInitializationFailed:
3182 case FK_VariableLengthArrayHasInitializer:
3183 case FK_PlaceholderType:
3184 case FK_ExplicitConstructor:
3185 case FK_AddressOfUnaddressableFunction:
3188 case FK_ReferenceInitOverloadFailed:
3189 case FK_UserConversionOverloadFailed:
3190 case FK_ConstructorOverloadFailed:
3191 case FK_ListConstructorOverloadFailed:
3192 return FailedOverloadResult == OR_Ambiguous;
3195 llvm_unreachable("Invalid EntityKind!");
3198 bool InitializationSequence::isConstructorInitialization() const {
3199 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3203 InitializationSequence
3204 ::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3205 DeclAccessPair Found,
3206 bool HadMultipleCandidates) {
3208 S.Kind = SK_ResolveAddressOfOverloadedFunction;
3209 S.Type = Function->getType();
3210 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3211 S.Function.Function = Function;
3212 S.Function.FoundDecl = Found;
3216 void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
3220 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
3221 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3222 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
3228 void InitializationSequence::AddReferenceBindingStep(QualType T,
3229 bool BindingTemporary) {
3231 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3236 void InitializationSequence::AddFinalCopy(QualType T) {
3238 S.Kind = SK_FinalCopy;
3243 void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
3245 S.Kind = SK_ExtraneousCopyToTemporary;
3251 InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
3252 DeclAccessPair FoundDecl,
3254 bool HadMultipleCandidates) {
3256 S.Kind = SK_UserConversion;
3258 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3259 S.Function.Function = Function;
3260 S.Function.FoundDecl = FoundDecl;
3264 void InitializationSequence::AddQualificationConversionStep(QualType Ty,
3267 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
3270 S.Kind = SK_QualificationConversionRValue;
3273 S.Kind = SK_QualificationConversionXValue;
3276 S.Kind = SK_QualificationConversionLValue;
3283 void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
3285 S.Kind = SK_AtomicConversion;
3290 void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
3291 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
3294 S.Kind = SK_LValueToRValue;
3299 void InitializationSequence::AddConversionSequenceStep(
3300 const ImplicitConversionSequence &ICS, QualType T,
3301 bool TopLevelOfInitList) {
3303 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3304 : SK_ConversionSequence;
3306 S.ICS = new ImplicitConversionSequence(ICS);
3310 void InitializationSequence::AddListInitializationStep(QualType T) {
3312 S.Kind = SK_ListInitialization;
3317 void InitializationSequence::AddConstructorInitializationStep(
3318 DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3319 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
3321 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
3322 : SK_ConstructorInitializationFromList
3323 : SK_ConstructorInitialization;
3325 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3326 S.Function.Function = Constructor;
3327 S.Function.FoundDecl = FoundDecl;
3331 void InitializationSequence::AddZeroInitializationStep(QualType T) {
3333 S.Kind = SK_ZeroInitialization;
3338 void InitializationSequence::AddCAssignmentStep(QualType T) {
3340 S.Kind = SK_CAssignment;
3345 void InitializationSequence::AddStringInitStep(QualType T) {
3347 S.Kind = SK_StringInit;
3352 void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
3354 S.Kind = SK_ObjCObjectConversion;
3359 void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) {
3361 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
3366 void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) {
3368 S.Kind = SK_ArrayLoopIndex;
3370 Steps.insert(Steps.begin(), S);
3372 S.Kind = SK_ArrayLoopInit;
3377 void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
3379 S.Kind = SK_ParenthesizedArrayInit;
3384 void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
3387 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3388 : SK_PassByIndirectRestore);
3393 void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3395 S.Kind = SK_ProduceObjCObject;
3400 void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3402 S.Kind = SK_StdInitializerList;
3407 void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3409 S.Kind = SK_OCLSamplerInit;
3414 void InitializationSequence::AddOCLZeroEventStep(QualType T) {
3416 S.Kind = SK_OCLZeroEvent;
3421 void InitializationSequence::AddOCLZeroQueueStep(QualType T) {
3423 S.Kind = SK_OCLZeroQueue;
3428 void InitializationSequence::RewrapReferenceInitList(QualType T,
3429 InitListExpr *Syntactic) {
3430 assert(Syntactic->getNumInits() == 1 &&
3431 "Can only rewrap trivial init lists.");
3433 S.Kind = SK_UnwrapInitList;
3434 S.Type = Syntactic->getInit(0)->getType();
3435 Steps.insert(Steps.begin(), S);
3437 S.Kind = SK_RewrapInitList;
3439 S.WrappingSyntacticList = Syntactic;
3443 void InitializationSequence::SetOverloadFailure(FailureKind Failure,
3444 OverloadingResult Result) {
3445 setSequenceKind(FailedSequence);
3446 this->Failure = Failure;
3447 this->FailedOverloadResult = Result;
3450 //===----------------------------------------------------------------------===//
3451 // Attempt initialization
3452 //===----------------------------------------------------------------------===//
3454 /// Tries to add a zero initializer. Returns true if that worked.
3456 maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
3457 const InitializedEntity &Entity) {
3458 if (Entity.getKind() != InitializedEntity::EK_Variable)
3461 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
3462 if (VD->getInit() || VD->getLocEnd().isMacroID())
3465 QualType VariableTy = VD->getType().getCanonicalType();
3466 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
3467 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
3468 if (!Init.empty()) {
3469 Sequence.AddZeroInitializationStep(Entity.getType());
3470 Sequence.SetZeroInitializationFixit(Init, Loc);
3476 static void MaybeProduceObjCObject(Sema &S,
3477 InitializationSequence &Sequence,
3478 const InitializedEntity &Entity) {
3479 if (!S.getLangOpts().ObjCAutoRefCount) return;
3481 /// When initializing a parameter, produce the value if it's marked
3482 /// __attribute__((ns_consumed)).
3483 if (Entity.isParameterKind()) {
3484 if (!Entity.isParameterConsumed())
3487 assert(Entity.getType()->isObjCRetainableType() &&
3488 "consuming an object of unretainable type?");
3489 Sequence.AddProduceObjCObjectStep(Entity.getType());
3491 /// When initializing a return value, if the return type is a
3492 /// retainable type, then returns need to immediately retain the
3493 /// object. If an autorelease is required, it will be done at the
3495 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
3496 if (!Entity.getType()->isObjCRetainableType())
3499 Sequence.AddProduceObjCObjectStep(Entity.getType());
3503 static void TryListInitialization(Sema &S,
3504 const InitializedEntity &Entity,
3505 const InitializationKind &Kind,
3506 InitListExpr *InitList,
3507 InitializationSequence &Sequence,
3508 bool TreatUnavailableAsInvalid);
3510 /// \brief When initializing from init list via constructor, handle
3511 /// initialization of an object of type std::initializer_list<T>.
3513 /// \return true if we have handled initialization of an object of type
3514 /// std::initializer_list<T>, false otherwise.
3515 static bool TryInitializerListConstruction(Sema &S,
3518 InitializationSequence &Sequence,
3519 bool TreatUnavailableAsInvalid) {
3521 if (!S.isStdInitializerList(DestType, &E))
3524 if (!S.isCompleteType(List->getExprLoc(), E)) {
3525 Sequence.setIncompleteTypeFailure(E);
3529 // Try initializing a temporary array from the init list.
3530 QualType ArrayType = S.Context.getConstantArrayType(
3531 E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3532 List->getNumInits()),
3533 clang::ArrayType::Normal, 0);
3534 InitializedEntity HiddenArray =
3535 InitializedEntity::InitializeTemporary(ArrayType);
3536 InitializationKind Kind =
3537 InitializationKind::CreateDirectList(List->getExprLoc());
3538 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
3539 TreatUnavailableAsInvalid);
3541 Sequence.AddStdInitializerListConstructionStep(DestType);
3545 /// Determine if the constructor has the signature of a copy or move
3546 /// constructor for the type T of the class in which it was found. That is,
3547 /// determine if its first parameter is of type T or reference to (possibly
3548 /// cv-qualified) T.
3549 static bool hasCopyOrMoveCtorParam(ASTContext &Ctx,
3550 const ConstructorInfo &Info) {
3551 if (Info.Constructor->getNumParams() == 0)
3555 Info.Constructor->getParamDecl(0)->getType().getNonReferenceType();
3557 Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
3559 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
3562 static OverloadingResult
3563 ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
3565 OverloadCandidateSet &CandidateSet,
3567 DeclContext::lookup_result Ctors,
3568 OverloadCandidateSet::iterator &Best,
3569 bool CopyInitializing, bool AllowExplicit,
3570 bool OnlyListConstructors, bool IsListInit,
3571 bool SecondStepOfCopyInit = false) {
3572 CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor);
3574 for (NamedDecl *D : Ctors) {
3575 auto Info = getConstructorInfo(D);
3576 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
3579 if (!AllowExplicit && Info.Constructor->isExplicit())
3582 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
3585 // C++11 [over.best.ics]p4:
3586 // ... and the constructor or user-defined conversion function is a
3588 // - 13.3.1.3, when the argument is the temporary in the second step
3589 // of a class copy-initialization, or
3590 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
3591 // - the second phase of 13.3.1.7 when the initializer list has exactly
3592 // one element that is itself an initializer list, and the target is
3593 // the first parameter of a constructor of class X, and the conversion
3594 // is to X or reference to (possibly cv-qualified X),
3595 // user-defined conversion sequences are not considered.
3596 bool SuppressUserConversions =
3597 SecondStepOfCopyInit ||
3598 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
3599 hasCopyOrMoveCtorParam(S.Context, Info));
3601 if (Info.ConstructorTmpl)
3602 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3603 /*ExplicitArgs*/ nullptr, Args,
3604 CandidateSet, SuppressUserConversions);
3606 // C++ [over.match.copy]p1:
3607 // - When initializing a temporary to be bound to the first parameter
3608 // of a constructor [for type T] that takes a reference to possibly
3609 // cv-qualified T as its first argument, called with a single
3610 // argument in the context of direct-initialization, explicit
3611 // conversion functions are also considered.
3612 // FIXME: What if a constructor template instantiates to such a signature?
3613 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
3615 hasCopyOrMoveCtorParam(S.Context, Info);
3616 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
3617 CandidateSet, SuppressUserConversions,
3618 /*PartialOverloading=*/false,
3619 /*AllowExplicit=*/AllowExplicitConv);
3623 // FIXME: Work around a bug in C++17 guaranteed copy elision.
3625 // When initializing an object of class type T by constructor
3626 // ([over.match.ctor]) or by list-initialization ([over.match.list])
3627 // from a single expression of class type U, conversion functions of
3628 // U that convert to the non-reference type cv T are candidates.
3629 // Explicit conversion functions are only candidates during
3630 // direct-initialization.
3632 // Note: SecondStepOfCopyInit is only ever true in this case when
3633 // evaluating whether to produce a C++98 compatibility warning.
3634 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
3635 !SecondStepOfCopyInit) {
3636 Expr *Initializer = Args[0];
3637 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
3638 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
3639 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
3640 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3642 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3643 D = D->getUnderlyingDecl();
3645 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3646 CXXConversionDecl *Conv;
3648 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3650 Conv = cast<CXXConversionDecl>(D);
3652 if ((AllowExplicit && !CopyInitializing) || !Conv->isExplicit()) {
3654 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
3655 ActingDC, Initializer, DestType,
3656 CandidateSet, AllowExplicit,
3657 /*AllowResultConversion*/false);
3659 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
3660 DestType, CandidateSet, AllowExplicit,
3661 /*AllowResultConversion*/false);
3667 // Perform overload resolution and return the result.
3668 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3671 /// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3672 /// enumerates the constructors of the initialized entity and performs overload
3673 /// resolution to select the best.
3674 /// \param DestType The destination class type.
3675 /// \param DestArrayType The destination type, which is either DestType or
3676 /// a (possibly multidimensional) array of DestType.
3677 /// \param IsListInit Is this list-initialization?
3678 /// \param IsInitListCopy Is this non-list-initialization resulting from a
3679 /// list-initialization from {x} where x is the same
3680 /// type as the entity?
3681 static void TryConstructorInitialization(Sema &S,
3682 const InitializedEntity &Entity,
3683 const InitializationKind &Kind,
3684 MultiExprArg Args, QualType DestType,
3685 QualType DestArrayType,
3686 InitializationSequence &Sequence,
3687 bool IsListInit = false,
3688 bool IsInitListCopy = false) {
3689 assert(((!IsListInit && !IsInitListCopy) ||
3690 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
3691 "IsListInit/IsInitListCopy must come with a single initializer list "
3694 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
3695 MultiExprArg UnwrappedArgs =
3696 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
3698 // The type we're constructing needs to be complete.
3699 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
3700 Sequence.setIncompleteTypeFailure(DestType);
3704 // C++17 [dcl.init]p17:
3705 // - If the initializer expression is a prvalue and the cv-unqualified
3706 // version of the source type is the same class as the class of the
3707 // destination, the initializer expression is used to initialize the
3708 // destination object.
3709 // Per DR (no number yet), this does not apply when initializing a base
3710 // class or delegating to another constructor from a mem-initializer.
3711 // ObjC++: Lambda captured by the block in the lambda to block conversion
3712 // should avoid copy elision.
3713 if (S.getLangOpts().CPlusPlus17 &&
3714 Entity.getKind() != InitializedEntity::EK_Base &&
3715 Entity.getKind() != InitializedEntity::EK_Delegating &&
3717 InitializedEntity::EK_LambdaToBlockConversionBlockElement &&
3718 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isRValue() &&
3719 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
3720 // Convert qualifications if necessary.
3721 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
3723 Sequence.RewrapReferenceInitList(DestType, ILE);
3727 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3728 assert(DestRecordType && "Constructor initialization requires record type");
3729 CXXRecordDecl *DestRecordDecl
3730 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3732 // Build the candidate set directly in the initialization sequence
3733 // structure, so that it will persist if we fail.
3734 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3736 // Determine whether we are allowed to call explicit constructors or
3737 // explicit conversion operators.
3738 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
3739 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
3741 // - Otherwise, if T is a class type, constructors are considered. The
3742 // applicable constructors are enumerated, and the best one is chosen
3743 // through overload resolution.
3744 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
3746 OverloadingResult Result = OR_No_Viable_Function;
3747 OverloadCandidateSet::iterator Best;
3748 bool AsInitializerList = false;
3750 // C++11 [over.match.list]p1, per DR1467:
3751 // When objects of non-aggregate type T are list-initialized, such that
3752 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
3753 // according to the rules in this section, overload resolution selects
3754 // the constructor in two phases:
3756 // - Initially, the candidate functions are the initializer-list
3757 // constructors of the class T and the argument list consists of the
3758 // initializer list as a single argument.
3760 AsInitializerList = true;
3762 // If the initializer list has no elements and T has a default constructor,
3763 // the first phase is omitted.
3764 if (!(UnwrappedArgs.empty() && DestRecordDecl->hasDefaultConstructor()))
3765 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
3766 CandidateSet, DestType, Ctors, Best,
3767 CopyInitialization, AllowExplicit,
3768 /*OnlyListConstructor=*/true,
3772 // C++11 [over.match.list]p1:
3773 // - If no viable initializer-list constructor is found, overload resolution
3774 // is performed again, where the candidate functions are all the
3775 // constructors of the class T and the argument list consists of the
3776 // elements of the initializer list.
3777 if (Result == OR_No_Viable_Function) {
3778 AsInitializerList = false;
3779 Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs,
3780 CandidateSet, DestType, Ctors, Best,
3781 CopyInitialization, AllowExplicit,
3782 /*OnlyListConstructors=*/false,
3786 Sequence.SetOverloadFailure(IsListInit ?
3787 InitializationSequence::FK_ListConstructorOverloadFailed :
3788 InitializationSequence::FK_ConstructorOverloadFailed,
3793 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3795 // In C++17, ResolveConstructorOverload can select a conversion function
3796 // instead of a constructor.
3797 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
3798 // Add the user-defined conversion step that calls the conversion function.
3799 QualType ConvType = CD->getConversionType();
3800 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
3801 "should not have selected this conversion function");
3802 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
3803 HadMultipleCandidates);
3804 if (!S.Context.hasSameType(ConvType, DestType))
3805 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
3807 Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
3811 // C++11 [dcl.init]p6:
3812 // If a program calls for the default initialization of an object
3813 // of a const-qualified type T, T shall be a class type with a
3814 // user-provided default constructor.
3815 // C++ core issue 253 proposal:
3816 // If the implicit default constructor initializes all subobjects, no
3817 // initializer should be required.
3818 // The 253 proposal is for example needed to process libstdc++ headers in 5.x.
3819 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3820 if (Kind.getKind() == InitializationKind::IK_Default &&
3821 Entity.getType().isConstQualified()) {
3822 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
3823 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
3824 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3829 // C++11 [over.match.list]p1:
3830 // In copy-list-initialization, if an explicit constructor is chosen, the
3831 // initializer is ill-formed.
3832 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
3833 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3837 // Add the constructor initialization step. Any cv-qualification conversion is
3838 // subsumed by the initialization.
3839 Sequence.AddConstructorInitializationStep(
3840 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
3841 IsListInit | IsInitListCopy, AsInitializerList);
3845 ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3847 QualType &SourceType,
3848 QualType &UnqualifiedSourceType,
3849 QualType UnqualifiedTargetType,
3850 InitializationSequence &Sequence) {
3851 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3852 S.Context.OverloadTy) {
3853 DeclAccessPair Found;
3854 bool HadMultipleCandidates = false;
3855 if (FunctionDecl *Fn
3856 = S.ResolveAddressOfOverloadedFunction(Initializer,
3857 UnqualifiedTargetType,
3859 &HadMultipleCandidates)) {
3860 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3861 HadMultipleCandidates);
3862 SourceType = Fn->getType();
3863 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3864 } else if (!UnqualifiedTargetType->isRecordType()) {
3865 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3872 static void TryReferenceInitializationCore(Sema &S,
3873 const InitializedEntity &Entity,
3874 const InitializationKind &Kind,
3876 QualType cv1T1, QualType T1,
3878 QualType cv2T2, QualType T2,
3880 InitializationSequence &Sequence);
3882 static void TryValueInitialization(Sema &S,
3883 const InitializedEntity &Entity,
3884 const InitializationKind &Kind,
3885 InitializationSequence &Sequence,
3886 InitListExpr *InitList = nullptr);
3888 /// \brief Attempt list initialization of a reference.
3889 static void TryReferenceListInitialization(Sema &S,
3890 const InitializedEntity &Entity,
3891 const InitializationKind &Kind,
3892 InitListExpr *InitList,
3893 InitializationSequence &Sequence,
3894 bool TreatUnavailableAsInvalid) {
3895 // First, catch C++03 where this isn't possible.
3896 if (!S.getLangOpts().CPlusPlus11) {
3897 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3900 // Can't reference initialize a compound literal.
3901 if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
3902 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3906 QualType DestType = Entity.getType();
3907 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3909 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3911 // Reference initialization via an initializer list works thus:
3912 // If the initializer list consists of a single element that is
3913 // reference-related to the referenced type, bind directly to that element
3914 // (possibly creating temporaries).
3915 // Otherwise, initialize a temporary with the initializer list and
3917 if (InitList->getNumInits() == 1) {
3918 Expr *Initializer = InitList->getInit(0);
3919 QualType cv2T2 = Initializer->getType();
3921 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3923 // If this fails, creating a temporary wouldn't work either.
3924 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3928 SourceLocation DeclLoc = Initializer->getLocStart();
3929 bool dummy1, dummy2, dummy3;
3930 Sema::ReferenceCompareResult RefRelationship
3931 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3933 if (RefRelationship >= Sema::Ref_Related) {
3934 // Try to bind the reference here.
3935 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3936 T1Quals, cv2T2, T2, T2Quals, Sequence);
3938 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3942 // Update the initializer if we've resolved an overloaded function.
3943 if (Sequence.step_begin() != Sequence.step_end())
3944 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3947 // Not reference-related. Create a temporary and bind to that.
3948 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3950 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
3951 TreatUnavailableAsInvalid);
3953 if (DestType->isRValueReferenceType() ||
3954 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3955 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3958 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3962 /// \brief Attempt list initialization (C++0x [dcl.init.list])
3963 static void TryListInitialization(Sema &S,
3964 const InitializedEntity &Entity,
3965 const InitializationKind &Kind,
3966 InitListExpr *InitList,
3967 InitializationSequence &Sequence,
3968 bool TreatUnavailableAsInvalid) {
3969 QualType DestType = Entity.getType();
3971 // C++ doesn't allow scalar initialization with more than one argument.
3972 // But C99 complex numbers are scalars and it makes sense there.
3973 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
3974 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3975 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3978 if (DestType->isReferenceType()) {
3979 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
3980 TreatUnavailableAsInvalid);
3984 if (DestType->isRecordType() &&
3985 !S.isCompleteType(InitList->getLocStart(), DestType)) {
3986 Sequence.setIncompleteTypeFailure(DestType);
3990 // C++11 [dcl.init.list]p3, per DR1467:
3991 // - If T is a class type and the initializer list has a single element of
3992 // type cv U, where U is T or a class derived from T, the object is
3993 // initialized from that element (by copy-initialization for
3994 // copy-list-initialization, or by direct-initialization for
3995 // direct-list-initialization).
3996 // - Otherwise, if T is a character array and the initializer list has a
3997 // single element that is an appropriately-typed string literal
3998 // (8.5.2 [dcl.init.string]), initialization is performed as described
4000 // - Otherwise, if T is an aggregate, [...] (continue below).
4001 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
4002 if (DestType->isRecordType()) {
4003 QualType InitType = InitList->getInit(0)->getType();
4004 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
4005 S.IsDerivedFrom(InitList->getLocStart(), InitType, DestType)) {
4006 Expr *InitListAsExpr = InitList;
4007 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4009 /*InitListSyntax*/false,
4010 /*IsInitListCopy*/true);
4014 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
4015 Expr *SubInit[1] = {InitList->getInit(0)};
4016 if (!isa<VariableArrayType>(DestAT) &&
4017 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
4018 InitializationKind SubKind =
4019 Kind.getKind() == InitializationKind::IK_DirectList
4020 ? InitializationKind::CreateDirect(Kind.getLocation(),
4021 InitList->getLBraceLoc(),
4022 InitList->getRBraceLoc())
4024 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4025 /*TopLevelOfInitList*/ true,
4026 TreatUnavailableAsInvalid);
4028 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4029 // the element is not an appropriately-typed string literal, in which
4030 // case we should proceed as in C++11 (below).
4032 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4039 // C++11 [dcl.init.list]p3:
4040 // - If T is an aggregate, aggregate initialization is performed.
4041 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
4042 (S.getLangOpts().CPlusPlus11 &&
4043 S.isStdInitializerList(DestType, nullptr))) {
4044 if (S.getLangOpts().CPlusPlus11) {
4045 // - Otherwise, if the initializer list has no elements and T is a
4046 // class type with a default constructor, the object is
4047 // value-initialized.
4048 if (InitList->getNumInits() == 0) {
4049 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4050 if (RD->hasDefaultConstructor()) {
4051 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
4056 // - Otherwise, if T is a specialization of std::initializer_list<E>,
4057 // an initializer_list object constructed [...]
4058 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
4059 TreatUnavailableAsInvalid))
4062 // - Otherwise, if T is a class type, constructors are considered.
4063 Expr *InitListAsExpr = InitList;
4064 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4065 DestType, Sequence, /*InitListSyntax*/true);
4067 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
4071 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
4072 InitList->getNumInits() == 1) {
4073 Expr *E = InitList->getInit(0);
4075 // - Otherwise, if T is an enumeration with a fixed underlying type,
4076 // the initializer-list has a single element v, and the initialization
4077 // is direct-list-initialization, the object is initialized with the
4078 // value T(v); if a narrowing conversion is required to convert v to
4079 // the underlying type of T, the program is ill-formed.
4080 auto *ET = DestType->getAs<EnumType>();
4081 if (S.getLangOpts().CPlusPlus17 &&
4082 Kind.getKind() == InitializationKind::IK_DirectList &&
4083 ET && ET->getDecl()->isFixed() &&
4084 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
4085 (E->getType()->isIntegralOrEnumerationType() ||
4086 E->getType()->isFloatingType())) {
4087 // There are two ways that T(v) can work when T is an enumeration type.
4088 // If there is either an implicit conversion sequence from v to T or
4089 // a conversion function that can convert from v to T, then we use that.
4090 // Otherwise, if v is of integral, enumeration, or floating-point type,
4091 // it is converted to the enumeration type via its underlying type.
4092 // There is no overlap possible between these two cases (except when the
4093 // source value is already of the destination type), and the first
4094 // case is handled by the general case for single-element lists below.
4095 ImplicitConversionSequence ICS;
4097 ICS.Standard.setAsIdentityConversion();
4099 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4100 // If E is of a floating-point type, then the conversion is ill-formed
4101 // due to narrowing, but go through the motions in order to produce the
4102 // right diagnostic.
4103 ICS.Standard.Second = E->getType()->isFloatingType()
4104 ? ICK_Floating_Integral
4105 : ICK_Integral_Conversion;
4106 ICS.Standard.setFromType(E->getType());
4107 ICS.Standard.setToType(0, E->getType());
4108 ICS.Standard.setToType(1, DestType);
4109 ICS.Standard.setToType(2, DestType);
4110 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
4111 /*TopLevelOfInitList*/true);
4112 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4116 // - Otherwise, if the initializer list has a single element of type E
4117 // [...references are handled above...], the object or reference is
4118 // initialized from that element (by copy-initialization for
4119 // copy-list-initialization, or by direct-initialization for
4120 // direct-list-initialization); if a narrowing conversion is required
4121 // to convert the element to T, the program is ill-formed.
4123 // Per core-24034, this is direct-initialization if we were performing
4124 // direct-list-initialization and copy-initialization otherwise.
4125 // We can't use InitListChecker for this, because it always performs
4126 // copy-initialization. This only matters if we might use an 'explicit'
4127 // conversion operator, so we only need to handle the cases where the source
4128 // is of record type.
4129 if (InitList->getInit(0)->getType()->isRecordType()) {
4130 InitializationKind SubKind =
4131 Kind.getKind() == InitializationKind::IK_DirectList
4132 ? InitializationKind::CreateDirect(Kind.getLocation(),
4133 InitList->getLBraceLoc(),
4134 InitList->getRBraceLoc())
4136 Expr *SubInit[1] = { InitList->getInit(0) };
4137 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4138 /*TopLevelOfInitList*/true,
4139 TreatUnavailableAsInvalid);
4141 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4146 InitListChecker CheckInitList(S, Entity, InitList,
4147 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
4148 if (CheckInitList.HadError()) {
4149 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
4153 // Add the list initialization step with the built init list.
4154 Sequence.AddListInitializationStep(DestType);
4157 /// \brief Try a reference initialization that involves calling a conversion
4159 static OverloadingResult TryRefInitWithConversionFunction(
4160 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4161 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
4162 InitializationSequence &Sequence) {
4163 QualType DestType = Entity.getType();
4164 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4165 QualType T1 = cv1T1.getUnqualifiedType();
4166 QualType cv2T2 = Initializer->getType();
4167 QualType T2 = cv2T2.getUnqualifiedType();
4170 bool ObjCConversion;
4171 bool ObjCLifetimeConversion;
4172 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
4173 T1, T2, DerivedToBase,
4175 ObjCLifetimeConversion) &&
4176 "Must have incompatible references when binding via conversion");
4177 (void)DerivedToBase;
4178 (void)ObjCConversion;
4179 (void)ObjCLifetimeConversion;
4181 // Build the candidate set directly in the initialization sequence
4182 // structure, so that it will persist if we fail.
4183 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4184 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4186 // Determine whether we are allowed to call explicit constructors or
4187 // explicit conversion operators.
4188 bool AllowExplicit = Kind.AllowExplicit();
4189 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
4191 const RecordType *T1RecordType = nullptr;
4192 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
4193 S.isCompleteType(Kind.getLocation(), T1)) {
4194 // The type we're converting to is a class type. Enumerate its constructors
4195 // to see if there is a suitable conversion.
4196 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
4198 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
4199 auto Info = getConstructorInfo(D);
4200 if (!Info.Constructor)
4203 if (!Info.Constructor->isInvalidDecl() &&
4204 Info.Constructor->isConvertingConstructor(AllowExplicit)) {
4205 if (Info.ConstructorTmpl)
4206 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
4207 /*ExplicitArgs*/ nullptr,
4208 Initializer, CandidateSet,
4209 /*SuppressUserConversions=*/true);
4211 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4212 Initializer, CandidateSet,
4213 /*SuppressUserConversions=*/true);
4217 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
4218 return OR_No_Viable_Function;
4220 const RecordType *T2RecordType = nullptr;
4221 if ((T2RecordType = T2->getAs<RecordType>()) &&
4222 S.isCompleteType(Kind.getLocation(), T2)) {
4223 // The type we're converting from is a class type, enumerate its conversion
4225 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4227 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4228 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4230 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4231 if (isa<UsingShadowDecl>(D))
4232 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4234 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4235 CXXConversionDecl *Conv;
4237 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4239 Conv = cast<CXXConversionDecl>(D);
4241 // If the conversion function doesn't return a reference type,
4242 // it can't be considered for this conversion unless we're allowed to
4243 // consider rvalues.
4244 // FIXME: Do we need to make sure that we only consider conversion
4245 // candidates with reference-compatible results? That might be needed to
4247 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
4248 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
4250 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
4251 ActingDC, Initializer,
4252 DestType, CandidateSet,
4253 /*AllowObjCConversionOnExplicit=*/
4256 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
4257 Initializer, DestType, CandidateSet,
4258 /*AllowObjCConversionOnExplicit=*/false);
4262 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4263 return OR_No_Viable_Function;
4265 SourceLocation DeclLoc = Initializer->getLocStart();
4267 // Perform overload resolution. If it fails, return the failed result.
4268 OverloadCandidateSet::iterator Best;
4269 if (OverloadingResult Result
4270 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
4273 FunctionDecl *Function = Best->Function;
4274 // This is the overload that will be used for this initialization step if we
4275 // use this initialization. Mark it as referenced.
4276 Function->setReferenced();
4278 // Compute the returned type and value kind of the conversion.
4280 if (isa<CXXConversionDecl>(Function))
4281 cv3T3 = Function->getReturnType();
4285 ExprValueKind VK = VK_RValue;
4286 if (cv3T3->isLValueReferenceType())
4288 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
4289 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
4290 cv3T3 = cv3T3.getNonLValueExprType(S.Context);
4292 // Add the user-defined conversion step.
4293 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4294 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
4295 HadMultipleCandidates);
4297 // Determine whether we'll need to perform derived-to-base adjustments or
4298 // other conversions.
4299 bool NewDerivedToBase = false;
4300 bool NewObjCConversion = false;
4301 bool NewObjCLifetimeConversion = false;
4302 Sema::ReferenceCompareResult NewRefRelationship
4303 = S.CompareReferenceRelationship(DeclLoc, T1, cv3T3,
4304 NewDerivedToBase, NewObjCConversion,
4305 NewObjCLifetimeConversion);
4307 // Add the final conversion sequence, if necessary.
4308 if (NewRefRelationship == Sema::Ref_Incompatible) {
4309 assert(!isa<CXXConstructorDecl>(Function) &&
4310 "should not have conversion after constructor");
4312 ImplicitConversionSequence ICS;
4314 ICS.Standard = Best->FinalConversion;
4315 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
4317 // Every implicit conversion results in a prvalue, except for a glvalue
4318 // derived-to-base conversion, which we handle below.
4319 cv3T3 = ICS.Standard.getToType(2);
4323 // If the converted initializer is a prvalue, its type T4 is adjusted to
4324 // type "cv1 T4" and the temporary materialization conversion is applied.
4326 // We adjust the cv-qualifications to match the reference regardless of
4327 // whether we have a prvalue so that the AST records the change. In this
4328 // case, T4 is "cv3 T3".
4329 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
4330 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
4331 Sequence.AddQualificationConversionStep(cv1T4, VK);
4332 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_RValue);
4333 VK = IsLValueRef ? VK_LValue : VK_XValue;
4335 if (NewDerivedToBase)
4336 Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
4337 else if (NewObjCConversion)
4338 Sequence.AddObjCObjectConversionStep(cv1T1);
4343 static void CheckCXX98CompatAccessibleCopy(Sema &S,
4344 const InitializedEntity &Entity,
4347 /// \brief Attempt reference initialization (C++0x [dcl.init.ref])
4348 static void TryReferenceInitialization(Sema &S,
4349 const InitializedEntity &Entity,
4350 const InitializationKind &Kind,
4352 InitializationSequence &Sequence) {
4353 QualType DestType = Entity.getType();
4354 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4356 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4357 QualType cv2T2 = Initializer->getType();
4359 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4361 // If the initializer is the address of an overloaded function, try
4362 // to resolve the overloaded function. If all goes well, T2 is the
4363 // type of the resulting function.
4364 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4368 // Delegate everything else to a subfunction.
4369 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4370 T1Quals, cv2T2, T2, T2Quals, Sequence);
4373 /// Determine whether an expression is a non-referenceable glvalue (one to
4374 /// which a reference can never bind). Attemting to bind a reference to
4375 /// such a glvalue will always create a temporary.
4376 static bool isNonReferenceableGLValue(Expr *E) {
4377 return E->refersToBitField() || E->refersToVectorElement();
4380 /// \brief Reference initialization without resolving overloaded functions.
4381 static void TryReferenceInitializationCore(Sema &S,
4382 const InitializedEntity &Entity,
4383 const InitializationKind &Kind,
4385 QualType cv1T1, QualType T1,
4387 QualType cv2T2, QualType T2,
4389 InitializationSequence &Sequence) {
4390 QualType DestType = Entity.getType();
4391 SourceLocation DeclLoc = Initializer->getLocStart();
4392 // Compute some basic properties of the types and the initializer.
4393 bool isLValueRef = DestType->isLValueReferenceType();
4394 bool isRValueRef = !isLValueRef;
4395 bool DerivedToBase = false;
4396 bool ObjCConversion = false;
4397 bool ObjCLifetimeConversion = false;
4398 Expr::Classification InitCategory = Initializer->Classify(S.Context);
4399 Sema::ReferenceCompareResult RefRelationship
4400 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
4401 ObjCConversion, ObjCLifetimeConversion);
4403 // C++0x [dcl.init.ref]p5:
4404 // A reference to type "cv1 T1" is initialized by an expression of type
4405 // "cv2 T2" as follows:
4407 // - If the reference is an lvalue reference and the initializer
4409 // Note the analogous bullet points for rvalue refs to functions. Because
4410 // there are no function rvalues in C++, rvalue refs to functions are treated
4411 // like lvalue refs.
4412 OverloadingResult ConvOvlResult = OR_Success;
4413 bool T1Function = T1->isFunctionType();
4414 if (isLValueRef || T1Function) {
4415 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
4416 (RefRelationship == Sema::Ref_Compatible ||
4417 (Kind.isCStyleOrFunctionalCast() &&
4418 RefRelationship == Sema::Ref_Related))) {
4419 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
4420 // reference-compatible with "cv2 T2," or
4421 if (T1Quals != T2Quals)
4422 // Convert to cv1 T2. This should only add qualifiers unless this is a
4423 // c-style cast. The removal of qualifiers in that case notionally
4424 // happens after the reference binding, but that doesn't matter.
4425 Sequence.AddQualificationConversionStep(
4426 S.Context.getQualifiedType(T2, T1Quals),
4427 Initializer->getValueKind());
4429 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
4430 else if (ObjCConversion)
4431 Sequence.AddObjCObjectConversionStep(cv1T1);
4433 // We only create a temporary here when binding a reference to a
4434 // bit-field or vector element. Those cases are't supposed to be
4435 // handled by this bullet, but the outcome is the same either way.
4436 Sequence.AddReferenceBindingStep(cv1T1, false);
4440 // - has a class type (i.e., T2 is a class type), where T1 is not
4441 // reference-related to T2, and can be implicitly converted to an
4442 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
4443 // with "cv3 T3" (this conversion is selected by enumerating the
4444 // applicable conversion functions (13.3.1.6) and choosing the best
4445 // one through overload resolution (13.3)),
4446 // If we have an rvalue ref to function type here, the rhs must be
4447 // an rvalue. DR1287 removed the "implicitly" here.
4448 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
4449 (isLValueRef || InitCategory.isRValue())) {
4450 ConvOvlResult = TryRefInitWithConversionFunction(
4451 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
4452 /*IsLValueRef*/ isLValueRef, Sequence);
4453 if (ConvOvlResult == OR_Success)
4455 if (ConvOvlResult != OR_No_Viable_Function)
4456 Sequence.SetOverloadFailure(
4457 InitializationSequence::FK_ReferenceInitOverloadFailed,
4462 // - Otherwise, the reference shall be an lvalue reference to a
4463 // non-volatile const type (i.e., cv1 shall be const), or the reference
4464 // shall be an rvalue reference.
4465 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
4466 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4467 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4468 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4469 Sequence.SetOverloadFailure(
4470 InitializationSequence::FK_ReferenceInitOverloadFailed,
4472 else if (!InitCategory.isLValue())
4474 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
4476 InitializationSequence::FailureKind FK;
4477 switch (RefRelationship) {
4478 case Sema::Ref_Compatible:
4479 if (Initializer->refersToBitField())
4480 FK = InitializationSequence::
4481 FK_NonConstLValueReferenceBindingToBitfield;
4482 else if (Initializer->refersToVectorElement())
4483 FK = InitializationSequence::
4484 FK_NonConstLValueReferenceBindingToVectorElement;
4486 llvm_unreachable("unexpected kind of compatible initializer");
4488 case Sema::Ref_Related:
4489 FK = InitializationSequence::FK_ReferenceInitDropsQualifiers;
4491 case Sema::Ref_Incompatible:
4492 FK = InitializationSequence::
4493 FK_NonConstLValueReferenceBindingToUnrelated;
4496 Sequence.SetFailed(FK);
4501 // - If the initializer expression
4503 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
4504 // [1z] rvalue (but not a bit-field) or
4505 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
4507 // Note: functions are handled above and below rather than here...
4509 (RefRelationship == Sema::Ref_Compatible ||
4510 (Kind.isCStyleOrFunctionalCast() &&
4511 RefRelationship == Sema::Ref_Related)) &&
4512 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
4513 (InitCategory.isPRValue() &&
4514 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
4515 T2->isArrayType())))) {
4516 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_RValue;
4517 if (InitCategory.isPRValue() && T2->isRecordType()) {
4518 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
4519 // compiler the freedom to perform a copy here or bind to the
4520 // object, while C++0x requires that we bind directly to the
4521 // object. Hence, we always bind to the object without making an
4522 // extra copy. However, in C++03 requires that we check for the
4523 // presence of a suitable copy constructor:
4525 // The constructor that would be used to make the copy shall
4526 // be callable whether or not the copy is actually done.
4527 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
4528 Sequence.AddExtraneousCopyToTemporary(cv2T2);
4529 else if (S.getLangOpts().CPlusPlus11)
4530 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
4533 // C++1z [dcl.init.ref]/5.2.1.2:
4534 // If the converted initializer is a prvalue, its type T4 is adjusted
4535 // to type "cv1 T4" and the temporary materialization conversion is
4537 QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1Quals);
4538 if (T1Quals != T2Quals)
4539 Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
4540 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_RValue);
4541 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
4543 // In any case, the reference is bound to the resulting glvalue (or to
4544 // an appropriate base class subobject).
4546 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
4547 else if (ObjCConversion)
4548 Sequence.AddObjCObjectConversionStep(cv1T1);
4552 // - has a class type (i.e., T2 is a class type), where T1 is not
4553 // reference-related to T2, and can be implicitly converted to an
4554 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
4555 // where "cv1 T1" is reference-compatible with "cv3 T3",
4557 // DR1287 removes the "implicitly" here.
4558 if (T2->isRecordType()) {
4559 if (RefRelationship == Sema::Ref_Incompatible) {
4560 ConvOvlResult = TryRefInitWithConversionFunction(
4561 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
4562 /*IsLValueRef*/ isLValueRef, Sequence);
4564 Sequence.SetOverloadFailure(
4565 InitializationSequence::FK_ReferenceInitOverloadFailed,
4571 if (RefRelationship == Sema::Ref_Compatible &&
4572 isRValueRef && InitCategory.isLValue()) {
4574 InitializationSequence::FK_RValueReferenceBindingToLValue);
4578 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4582 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
4583 // from the initializer expression using the rules for a non-reference
4584 // copy-initialization (8.5). The reference is then bound to the
4587 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
4589 // FIXME: Why do we use an implicit conversion here rather than trying
4590 // copy-initialization?
4591 ImplicitConversionSequence ICS
4592 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
4593 /*SuppressUserConversions=*/false,
4594 /*AllowExplicit=*/false,
4595 /*FIXME:InOverloadResolution=*/false,
4596 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4597 /*AllowObjCWritebackConversion=*/false);
4600 // FIXME: Use the conversion function set stored in ICS to turn
4601 // this into an overloading ambiguity diagnostic. However, we need
4602 // to keep that set as an OverloadCandidateSet rather than as some
4603 // other kind of set.
4604 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4605 Sequence.SetOverloadFailure(
4606 InitializationSequence::FK_ReferenceInitOverloadFailed,
4608 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4609 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4611 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
4614 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
4617 // [...] If T1 is reference-related to T2, cv1 must be the
4618 // same cv-qualification as, or greater cv-qualification
4619 // than, cv2; otherwise, the program is ill-formed.
4620 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
4621 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
4622 if (RefRelationship == Sema::Ref_Related &&
4623 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
4624 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4628 // [...] If T1 is reference-related to T2 and the reference is an rvalue
4629 // reference, the initializer expression shall not be an lvalue.
4630 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
4631 InitCategory.isLValue()) {
4633 InitializationSequence::FK_RValueReferenceBindingToLValue);
4637 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
4640 /// \brief Attempt character array initialization from a string literal
4641 /// (C++ [dcl.init.string], C99 6.7.8).
4642 static void TryStringLiteralInitialization(Sema &S,
4643 const InitializedEntity &Entity,
4644 const InitializationKind &Kind,
4646 InitializationSequence &Sequence) {
4647 Sequence.AddStringInitStep(Entity.getType());
4650 /// \brief Attempt value initialization (C++ [dcl.init]p7).
4651 static void TryValueInitialization(Sema &S,
4652 const InitializedEntity &Entity,
4653 const InitializationKind &Kind,
4654 InitializationSequence &Sequence,
4655 InitListExpr *InitList) {
4656 assert((!InitList || InitList->getNumInits() == 0) &&
4657 "Shouldn't use value-init for non-empty init lists");
4659 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
4661 // To value-initialize an object of type T means:
4662 QualType T = Entity.getType();
4664 // -- if T is an array type, then each element is value-initialized;
4665 T = S.Context.getBaseElementType(T);
4667 if (const RecordType *RT = T->getAs<RecordType>()) {
4668 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
4669 bool NeedZeroInitialization = true;
4671 // -- if T is a class type (clause 9) with a user-declared constructor
4672 // (12.1), then the default constructor for T is called (and the
4673 // initialization is ill-formed if T has no accessible default
4676 // -- if T is a class type (clause 9) with either no default constructor
4677 // (12.1 [class.ctor]) or a default constructor that is user-provided
4678 // or deleted, then the object is default-initialized;
4680 // Note that the C++11 rule is the same as the C++98 rule if there are no
4681 // defaulted or deleted constructors, so we just use it unconditionally.
4682 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
4683 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
4684 NeedZeroInitialization = false;
4686 // -- if T is a (possibly cv-qualified) non-union class type without a
4687 // user-provided or deleted default constructor, then the object is
4688 // zero-initialized and, if T has a non-trivial default constructor,
4689 // default-initialized;
4690 // The 'non-union' here was removed by DR1502. The 'non-trivial default
4691 // constructor' part was removed by DR1507.
4692 if (NeedZeroInitialization)
4693 Sequence.AddZeroInitializationStep(Entity.getType());
4696 // -- if T is a non-union class type without a user-declared constructor,
4697 // then every non-static data member and base class component of T is
4698 // value-initialized;
4699 // [...] A program that calls for [...] value-initialization of an
4700 // entity of reference type is ill-formed.
4702 // C++11 doesn't need this handling, because value-initialization does not
4703 // occur recursively there, and the implicit default constructor is
4704 // defined as deleted in the problematic cases.
4705 if (!S.getLangOpts().CPlusPlus11 &&
4706 ClassDecl->hasUninitializedReferenceMember()) {
4707 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
4711 // If this is list-value-initialization, pass the empty init list on when
4712 // building the constructor call. This affects the semantics of a few
4713 // things (such as whether an explicit default constructor can be called).
4714 Expr *InitListAsExpr = InitList;
4715 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
4716 bool InitListSyntax = InitList;
4718 // FIXME: Instead of creating a CXXConstructExpr of array type here,
4719 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
4720 return TryConstructorInitialization(
4721 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
4725 Sequence.AddZeroInitializationStep(Entity.getType());
4728 /// \brief Attempt default initialization (C++ [dcl.init]p6).
4729 static void TryDefaultInitialization(Sema &S,
4730 const InitializedEntity &Entity,
4731 const InitializationKind &Kind,
4732 InitializationSequence &Sequence) {
4733 assert(Kind.getKind() == InitializationKind::IK_Default);
4735 // C++ [dcl.init]p6:
4736 // To default-initialize an object of type T means:
4737 // - if T is an array type, each element is default-initialized;
4738 QualType DestType = S.Context.getBaseElementType(Entity.getType());
4740 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4741 // constructor for T is called (and the initialization is ill-formed if
4742 // T has no accessible default constructor);
4743 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
4744 TryConstructorInitialization(S, Entity, Kind, None, DestType,
4745 Entity.getType(), Sequence);
4749 // - otherwise, no initialization is performed.
4751 // If a program calls for the default initialization of an object of
4752 // a const-qualified type T, T shall be a class type with a user-provided
4753 // default constructor.
4754 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
4755 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4756 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
4760 // If the destination type has a lifetime property, zero-initialize it.
4761 if (DestType.getQualifiers().hasObjCLifetime()) {
4762 Sequence.AddZeroInitializationStep(Entity.getType());
4767 /// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
4768 /// which enumerates all conversion functions and performs overload resolution
4769 /// to select the best.
4770 static void TryUserDefinedConversion(Sema &S,
4772 const InitializationKind &Kind,
4774 InitializationSequence &Sequence,
4775 bool TopLevelOfInitList) {
4776 assert(!DestType->isReferenceType() && "References are handled elsewhere");
4777 QualType SourceType = Initializer->getType();
4778 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4779 "Must have a class type to perform a user-defined conversion");
4781 // Build the candidate set directly in the initialization sequence
4782 // structure, so that it will persist if we fail.
4783 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4784 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4786 // Determine whether we are allowed to call explicit constructors or
4787 // explicit conversion operators.
4788 bool AllowExplicit = Kind.AllowExplicit();
4790 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4791 // The type we're converting to is a class type. Enumerate its constructors
4792 // to see if there is a suitable conversion.
4793 CXXRecordDecl *DestRecordDecl
4794 = cast<CXXRecordDecl>(DestRecordType->getDecl());
4796 // Try to complete the type we're converting to.
4797 if (S.isCompleteType(Kind.getLocation(), DestType)) {
4798 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
4799 auto Info = getConstructorInfo(D);
4800 if (!Info.Constructor)
4803 if (!Info.Constructor->isInvalidDecl() &&
4804 Info.Constructor->isConvertingConstructor(AllowExplicit)) {
4805 if (Info.ConstructorTmpl)
4806 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
4807 /*ExplicitArgs*/ nullptr,
4808 Initializer, CandidateSet,
4809 /*SuppressUserConversions=*/true);
4811 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4812 Initializer, CandidateSet,
4813 /*SuppressUserConversions=*/true);
4819 SourceLocation DeclLoc = Initializer->getLocStart();
4821 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4822 // The type we're converting from is a class type, enumerate its conversion
4825 // We can only enumerate the conversion functions for a complete type; if
4826 // the type isn't complete, simply skip this step.
4827 if (S.isCompleteType(DeclLoc, SourceType)) {
4828 CXXRecordDecl *SourceRecordDecl
4829 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
4831 const auto &Conversions =
4832 SourceRecordDecl->getVisibleConversionFunctions();
4833 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4835 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4836 if (isa<UsingShadowDecl>(D))
4837 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4839 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4840 CXXConversionDecl *Conv;
4842 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4844 Conv = cast<CXXConversionDecl>(D);
4846 if (AllowExplicit || !Conv->isExplicit()) {
4848 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
4849 ActingDC, Initializer, DestType,
4850 CandidateSet, AllowExplicit);
4852 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
4853 Initializer, DestType, CandidateSet,
4860 // Perform overload resolution. If it fails, return the failed result.
4861 OverloadCandidateSet::iterator Best;
4862 if (OverloadingResult Result
4863 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4864 Sequence.SetOverloadFailure(
4865 InitializationSequence::FK_UserConversionOverloadFailed,
4870 FunctionDecl *Function = Best->Function;
4871 Function->setReferenced();
4872 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4874 if (isa<CXXConstructorDecl>(Function)) {
4875 // Add the user-defined conversion step. Any cv-qualification conversion is
4876 // subsumed by the initialization. Per DR5, the created temporary is of the
4877 // cv-unqualified type of the destination.
4878 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4879 DestType.getUnqualifiedType(),
4880 HadMultipleCandidates);
4882 // C++14 and before:
4883 // - if the function is a constructor, the call initializes a temporary
4884 // of the cv-unqualified version of the destination type. The [...]
4885 // temporary [...] is then used to direct-initialize, according to the
4886 // rules above, the object that is the destination of the
4887 // copy-initialization.
4888 // Note that this just performs a simple object copy from the temporary.
4891 // - if the function is a constructor, the call is a prvalue of the
4892 // cv-unqualified version of the destination type whose return object
4893 // is initialized by the constructor. The call is used to
4894 // direct-initialize, according to the rules above, the object that
4895 // is the destination of the copy-initialization.
4896 // Therefore we need to do nothing further.
4898 // FIXME: Mark this copy as extraneous.
4899 if (!S.getLangOpts().CPlusPlus17)
4900 Sequence.AddFinalCopy(DestType);
4901 else if (DestType.hasQualifiers())
4902 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
4906 // Add the user-defined conversion step that calls the conversion function.
4907 QualType ConvType = Function->getCallResultType();
4908 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4909 HadMultipleCandidates);
4911 if (ConvType->getAs<RecordType>()) {
4912 // The call is used to direct-initialize [...] the object that is the
4913 // destination of the copy-initialization.
4915 // In C++17, this does not call a constructor if we enter /17.6.1:
4916 // - If the initializer expression is a prvalue and the cv-unqualified
4917 // version of the source type is the same as the class of the
4918 // destination [... do not make an extra copy]
4920 // FIXME: Mark this copy as extraneous.
4921 if (!S.getLangOpts().CPlusPlus17 ||
4922 Function->getReturnType()->isReferenceType() ||
4923 !S.Context.hasSameUnqualifiedType(ConvType, DestType))
4924 Sequence.AddFinalCopy(DestType);
4925 else if (!S.Context.hasSameType(ConvType, DestType))
4926 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
4930 // If the conversion following the call to the conversion function
4931 // is interesting, add it as a separate step.
4932 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4933 Best->FinalConversion.Third) {
4934 ImplicitConversionSequence ICS;
4936 ICS.Standard = Best->FinalConversion;
4937 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
4941 /// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4942 /// a function with a pointer return type contains a 'return false;' statement.
4943 /// In C++11, 'false' is not a null pointer, so this breaks the build of any
4944 /// code using that header.
4946 /// Work around this by treating 'return false;' as zero-initializing the result
4947 /// if it's used in a pointer-returning function in a system header.
4948 static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
4949 const InitializedEntity &Entity,
4951 return S.getLangOpts().CPlusPlus11 &&
4952 Entity.getKind() == InitializedEntity::EK_Result &&
4953 Entity.getType()->isPointerType() &&
4954 isa<CXXBoolLiteralExpr>(Init) &&
4955 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
4956 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
4959 /// The non-zero enum values here are indexes into diagnostic alternatives.
4960 enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4962 /// Determines whether this expression is an acceptable ICR source.
4963 static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
4964 bool isAddressOf, bool &isWeakAccess) {
4966 e = e->IgnoreParens();
4968 // Skip address-of nodes.
4969 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4970 if (op->getOpcode() == UO_AddrOf)
4971 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4974 // Skip certain casts.
4975 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4976 switch (ce->getCastKind()) {
4979 case CK_LValueBitCast:
4981 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
4983 case CK_ArrayToPointerDecay:
4984 return IIK_nonscalar;
4986 case CK_NullToPointer:
4993 // If we have a declaration reference, it had better be a local variable.
4994 } else if (isa<DeclRefExpr>(e)) {
4995 // set isWeakAccess to true, to mean that there will be an implicit
4996 // load which requires a cleanup.
4997 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4998 isWeakAccess = true;
5000 if (!isAddressOf) return IIK_nonlocal;
5002 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
5003 if (!var) return IIK_nonlocal;
5005 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
5007 // If we have a conditional operator, check both sides.
5008 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
5009 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
5013 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
5015 // These are never scalar.
5016 } else if (isa<ArraySubscriptExpr>(e)) {
5017 return IIK_nonscalar;
5019 // Otherwise, it needs to be a null pointer constant.
5021 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
5022 ? IIK_okay : IIK_nonlocal);
5025 return IIK_nonlocal;
5028 /// Check whether the given expression is a valid operand for an
5029 /// indirect copy/restore.
5030 static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
5031 assert(src->isRValue());
5032 bool isWeakAccess = false;
5033 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
5034 // If isWeakAccess to true, there will be an implicit
5035 // load which requires a cleanup.
5036 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
5037 S.Cleanup.setExprNeedsCleanups(true);
5039 if (iik == IIK_okay) return;
5041 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
5042 << ((unsigned) iik - 1) // shift index into diagnostic explanations
5043 << src->getSourceRange();
5046 /// \brief Determine whether we have compatible array types for the
5047 /// purposes of GNU by-copy array initialization.
5048 static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
5049 const ArrayType *Source) {
5050 // If the source and destination array types are equivalent, we're
5052 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
5055 // Make sure that the element types are the same.
5056 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
5059 // The only mismatch we allow is when the destination is an
5060 // incomplete array type and the source is a constant array type.
5061 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
5064 static bool tryObjCWritebackConversion(Sema &S,
5065 InitializationSequence &Sequence,
5066 const InitializedEntity &Entity,
5067 Expr *Initializer) {
5068 bool ArrayDecay = false;
5069 QualType ArgType = Initializer->getType();
5070 QualType ArgPointee;
5071 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
5073 ArgPointee = ArgArrayType->getElementType();
5074 ArgType = S.Context.getPointerType(ArgPointee);
5077 // Handle write-back conversion.
5078 QualType ConvertedArgType;
5079 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
5083 // We should copy unless we're passing to an argument explicitly
5085 bool ShouldCopy = true;
5086 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5087 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5089 // Do we need an lvalue conversion?
5090 if (ArrayDecay || Initializer->isGLValue()) {
5091 ImplicitConversionSequence ICS;
5093 ICS.Standard.setAsIdentityConversion();
5095 QualType ResultType;
5097 ICS.Standard.First = ICK_Array_To_Pointer;
5098 ResultType = S.Context.getPointerType(ArgPointee);
5100 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
5101 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
5104 Sequence.AddConversionSequenceStep(ICS, ResultType);
5107 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
5111 static bool TryOCLSamplerInitialization(Sema &S,
5112 InitializationSequence &Sequence,
5114 Expr *Initializer) {
5115 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
5116 (!Initializer->isIntegerConstantExpr(S.Context) &&
5117 !Initializer->getType()->isSamplerT()))
5120 Sequence.AddOCLSamplerInitStep(DestType);
5125 // OpenCL 1.2 spec, s6.12.10
5127 // The event argument can also be used to associate the
5128 // async_work_group_copy with a previous async copy allowing
5129 // an event to be shared by multiple async copies; otherwise
5130 // event should be zero.
5132 static bool TryOCLZeroEventInitialization(Sema &S,
5133 InitializationSequence &Sequence,
5135 Expr *Initializer) {
5136 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
5137 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
5138 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
5141 Sequence.AddOCLZeroEventStep(DestType);
5145 static bool TryOCLZeroQueueInitialization(Sema &S,
5146 InitializationSequence &Sequence,
5148 Expr *Initializer) {
5149 if (!S.getLangOpts().OpenCL || S.getLangOpts().OpenCLVersion < 200 ||
5150 !DestType->isQueueT() ||
5151 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
5152 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
5155 Sequence.AddOCLZeroQueueStep(DestType);
5159 InitializationSequence::InitializationSequence(Sema &S,
5160 const InitializedEntity &Entity,
5161 const InitializationKind &Kind,
5163 bool TopLevelOfInitList,
5164 bool TreatUnavailableAsInvalid)
5165 : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
5166 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
5167 TreatUnavailableAsInvalid);
5170 /// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
5171 /// address of that function, this returns true. Otherwise, it returns false.
5172 static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
5173 auto *DRE = dyn_cast<DeclRefExpr>(E);
5174 if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
5177 return !S.checkAddressOfFunctionIsAvailable(
5178 cast<FunctionDecl>(DRE->getDecl()));
5181 /// Determine whether we can perform an elementwise array copy for this kind
5183 static bool canPerformArrayCopy(const InitializedEntity &Entity) {
5184 switch (Entity.getKind()) {
5185 case InitializedEntity::EK_LambdaCapture:
5186 // C++ [expr.prim.lambda]p24:
5187 // For array members, the array elements are direct-initialized in
5188 // increasing subscript order.
5191 case InitializedEntity::EK_Variable:
5192 // C++ [dcl.decomp]p1:
5193 // [...] each element is copy-initialized or direct-initialized from the
5194 // corresponding element of the assignment-expression [...]
5195 return isa<DecompositionDecl>(Entity.getDecl());
5197 case InitializedEntity::EK_Member:
5198 // C++ [class.copy.ctor]p14:
5199 // - if the member is an array, each element is direct-initialized with
5200 // the corresponding subobject of x
5201 return Entity.isImplicitMemberInitializer();
5203 case InitializedEntity::EK_ArrayElement:
5204 // All the above cases are intended to apply recursively, even though none
5205 // of them actually say that.
5206 if (auto *E = Entity.getParent())
5207 return canPerformArrayCopy(*E);
5217 void InitializationSequence::InitializeFrom(Sema &S,
5218 const InitializedEntity &Entity,
5219 const InitializationKind &Kind,
5221 bool TopLevelOfInitList,
5222 bool TreatUnavailableAsInvalid) {
5223 ASTContext &Context = S.Context;
5225 // Eliminate non-overload placeholder types in the arguments. We
5226 // need to do this before checking whether types are dependent
5227 // because lowering a pseudo-object expression might well give us
5228 // something of dependent type.
5229 for (unsigned I = 0, E = Args.size(); I != E; ++I)
5230 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
5231 // FIXME: should we be doing this here?
5232 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
5233 if (result.isInvalid()) {
5234 SetFailed(FK_PlaceholderType);
5237 Args[I] = result.get();
5240 // C++0x [dcl.init]p16:
5241 // The semantics of initializers are as follows. The destination type is
5242 // the type of the object or reference being initialized and the source
5243 // type is the type of the initializer expression. The source type is not
5244 // defined when the initializer is a braced-init-list or when it is a
5245 // parenthesized list of expressions.
5246 QualType DestType = Entity.getType();
5248 if (DestType->isDependentType() ||
5249 Expr::hasAnyTypeDependentArguments(Args)) {
5250 SequenceKind = DependentSequence;
5254 // Almost everything is a normal sequence.
5255 setSequenceKind(NormalSequence);
5257 QualType SourceType;
5258 Expr *Initializer = nullptr;
5259 if (Args.size() == 1) {
5260 Initializer = Args[0];
5261 if (S.getLangOpts().ObjC1) {
5262 if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(),
5263 DestType, Initializer->getType(),
5265 S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
5266 Args[0] = Initializer;
5268 if (!isa<InitListExpr>(Initializer))
5269 SourceType = Initializer->getType();
5272 // - If the initializer is a (non-parenthesized) braced-init-list, the
5273 // object is list-initialized (8.5.4).
5274 if (Kind.getKind() != InitializationKind::IK_Direct) {
5275 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
5276 TryListInitialization(S, Entity, Kind, InitList, *this,
5277 TreatUnavailableAsInvalid);
5282 // - If the destination type is a reference type, see 8.5.3.
5283 if (DestType->isReferenceType()) {
5284 // C++0x [dcl.init.ref]p1:
5285 // A variable declared to be a T& or T&&, that is, "reference to type T"
5286 // (8.3.2), shall be initialized by an object, or function, of type T or
5287 // by an object that can be converted into a T.
5288 // (Therefore, multiple arguments are not permitted.)
5289 if (Args.size() != 1)
5290 SetFailed(FK_TooManyInitsForReference);
5291 // C++17 [dcl.init.ref]p5:
5292 // A reference [...] is initialized by an expression [...] as follows:
5293 // If the initializer is not an expression, presumably we should reject,
5294 // but the standard fails to actually say so.
5295 else if (isa<InitListExpr>(Args[0]))
5296 SetFailed(FK_ParenthesizedListInitForReference);
5298 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
5302 // - If the initializer is (), the object is value-initialized.
5303 if (Kind.getKind() == InitializationKind::IK_Value ||
5304 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
5305 TryValueInitialization(S, Entity, Kind, *this);
5309 // Handle default initialization.
5310 if (Kind.getKind() == InitializationKind::IK_Default) {
5311 TryDefaultInitialization(S, Entity, Kind, *this);
5315 // - If the destination type is an array of characters, an array of
5316 // char16_t, an array of char32_t, or an array of wchar_t, and the
5317 // initializer is a string literal, see 8.5.2.
5318 // - Otherwise, if the destination type is an array, the program is
5320 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
5321 if (Initializer && isa<VariableArrayType>(DestAT)) {
5322 SetFailed(FK_VariableLengthArrayHasInitializer);
5327 switch (IsStringInit(Initializer, DestAT, Context)) {
5329 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
5331 case SIF_NarrowStringIntoWideChar:
5332 SetFailed(FK_NarrowStringIntoWideCharArray);
5334 case SIF_WideStringIntoChar:
5335 SetFailed(FK_WideStringIntoCharArray);
5337 case SIF_IncompatWideStringIntoWideChar:
5338 SetFailed(FK_IncompatWideStringIntoWideChar);
5345 // Some kinds of initialization permit an array to be initialized from
5346 // another array of the same type, and perform elementwise initialization.
5347 if (Initializer && isa<ConstantArrayType>(DestAT) &&
5348 S.Context.hasSameUnqualifiedType(Initializer->getType(),
5349 Entity.getType()) &&
5350 canPerformArrayCopy(Entity)) {
5351 // If source is a prvalue, use it directly.
5352 if (Initializer->getValueKind() == VK_RValue) {
5353 AddArrayInitStep(DestType, /*IsGNUExtension*/false);
5357 // Emit element-at-a-time copy loop.
5358 InitializedEntity Element =
5359 InitializedEntity::InitializeElement(S.Context, 0, Entity);
5361 Context.getAsArrayType(Initializer->getType())->getElementType();
5362 OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
5363 Initializer->getValueKind(),
5364 Initializer->getObjectKind());
5365 Expr *OVEAsExpr = &OVE;
5366 InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList,
5367 TreatUnavailableAsInvalid);
5369 AddArrayInitLoopStep(Entity.getType(), InitEltT);
5373 // Note: as an GNU C extension, we allow initialization of an
5374 // array from a compound literal that creates an array of the same
5375 // type, so long as the initializer has no side effects.
5376 if (!S.getLangOpts().CPlusPlus && Initializer &&
5377 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
5378 Initializer->getType()->isArrayType()) {
5379 const ArrayType *SourceAT
5380 = Context.getAsArrayType(Initializer->getType());
5381 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
5382 SetFailed(FK_ArrayTypeMismatch);
5383 else if (Initializer->HasSideEffects(S.Context))
5384 SetFailed(FK_NonConstantArrayInit);
5386 AddArrayInitStep(DestType, /*IsGNUExtension*/true);
5389 // Note: as a GNU C++ extension, we allow list-initialization of a
5390 // class member of array type from a parenthesized initializer list.
5391 else if (S.getLangOpts().CPlusPlus &&
5392 Entity.getKind() == InitializedEntity::EK_Member &&
5393 Initializer && isa<InitListExpr>(Initializer)) {
5394 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
5395 *this, TreatUnavailableAsInvalid);
5396 AddParenthesizedArrayInitStep(DestType);
5397 } else if (DestAT->getElementType()->isCharType())
5398 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
5399 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
5400 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
5402 SetFailed(FK_ArrayNeedsInitList);
5407 // Determine whether we should consider writeback conversions for
5409 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
5410 Entity.isParameterKind();
5412 // We're at the end of the line for C: it's either a write-back conversion
5413 // or it's a C assignment. There's no need to check anything else.
5414 if (!S.getLangOpts().CPlusPlus) {
5415 // If allowed, check whether this is an Objective-C writeback conversion.
5416 if (allowObjCWritebackConversion &&
5417 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
5421 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
5424 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
5427 if (TryOCLZeroQueueInitialization(S, *this, DestType, Initializer))
5430 // Handle initialization in C
5431 AddCAssignmentStep(DestType);
5432 MaybeProduceObjCObject(S, *this, Entity);
5436 assert(S.getLangOpts().CPlusPlus);
5438 // - If the destination type is a (possibly cv-qualified) class type:
5439 if (DestType->isRecordType()) {
5440 // - If the initialization is direct-initialization, or if it is
5441 // copy-initialization where the cv-unqualified version of the
5442 // source type is the same class as, or a derived class of, the
5443 // class of the destination, constructors are considered. [...]
5444 if (Kind.getKind() == InitializationKind::IK_Direct ||
5445 (Kind.getKind() == InitializationKind::IK_Copy &&
5446 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
5447 S.IsDerivedFrom(Initializer->getLocStart(), SourceType, DestType))))
5448 TryConstructorInitialization(S, Entity, Kind, Args,
5449 DestType, DestType, *this);
5450 // - Otherwise (i.e., for the remaining copy-initialization cases),
5451 // user-defined conversion sequences that can convert from the source
5452 // type to the destination type or (when a conversion function is
5453 // used) to a derived class thereof are enumerated as described in
5454 // 13.3.1.4, and the best one is chosen through overload resolution
5457 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
5458 TopLevelOfInitList);
5462 assert(Args.size() >= 1 && "Zero-argument case handled above");
5464 // The remaining cases all need a source type.
5465 if (Args.size() > 1) {
5466 SetFailed(FK_TooManyInitsForScalar);
5468 } else if (isa<InitListExpr>(Args[0])) {
5469 SetFailed(FK_ParenthesizedListInitForScalar);
5473 // - Otherwise, if the source type is a (possibly cv-qualified) class
5474 // type, conversion functions are considered.
5475 if (!SourceType.isNull() && SourceType->isRecordType()) {
5476 // For a conversion to _Atomic(T) from either T or a class type derived
5477 // from T, initialize the T object then convert to _Atomic type.
5478 bool NeedAtomicConversion = false;
5479 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
5480 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
5481 S.IsDerivedFrom(Initializer->getLocStart(), SourceType,
5482 Atomic->getValueType())) {
5483 DestType = Atomic->getValueType();
5484 NeedAtomicConversion = true;
5488 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
5489 TopLevelOfInitList);
5490 MaybeProduceObjCObject(S, *this, Entity);
5491 if (!Failed() && NeedAtomicConversion)
5492 AddAtomicConversionStep(Entity.getType());
5496 // - Otherwise, the initial value of the object being initialized is the
5497 // (possibly converted) value of the initializer expression. Standard
5498 // conversions (Clause 4) will be used, if necessary, to convert the
5499 // initializer expression to the cv-unqualified version of the
5500 // destination type; no user-defined conversions are considered.
5502 ImplicitConversionSequence ICS
5503 = S.TryImplicitConversion(Initializer, DestType,
5504 /*SuppressUserConversions*/true,
5505 /*AllowExplicitConversions*/ false,
5506 /*InOverloadResolution*/ false,
5507 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5508 allowObjCWritebackConversion);
5510 if (ICS.isStandard() &&
5511 ICS.Standard.Second == ICK_Writeback_Conversion) {
5512 // Objective-C ARC writeback conversion.
5514 // We should copy unless we're passing to an argument explicitly
5516 bool ShouldCopy = true;
5517 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5518 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5520 // If there was an lvalue adjustment, add it as a separate conversion.
5521 if (ICS.Standard.First == ICK_Array_To_Pointer ||
5522 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5523 ImplicitConversionSequence LvalueICS;
5524 LvalueICS.setStandard();
5525 LvalueICS.Standard.setAsIdentityConversion();
5526 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
5527 LvalueICS.Standard.First = ICS.Standard.First;
5528 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
5531 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
5532 } else if (ICS.isBad()) {
5534 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
5535 AddZeroInitializationStep(Entity.getType());
5536 } else if (Initializer->getType() == Context.OverloadTy &&
5537 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
5539 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
5540 else if (Initializer->getType()->isFunctionType() &&
5541 isExprAnUnaddressableFunction(S, Initializer))
5542 SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction);
5544 SetFailed(InitializationSequence::FK_ConversionFailed);
5546 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
5548 MaybeProduceObjCObject(S, *this, Entity);
5552 InitializationSequence::~InitializationSequence() {
5553 for (auto &S : Steps)
5557 //===----------------------------------------------------------------------===//
5558 // Perform initialization
5559 //===----------------------------------------------------------------------===//
5560 static Sema::AssignmentAction
5561 getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
5562 switch(Entity.getKind()) {
5563 case InitializedEntity::EK_Variable:
5564 case InitializedEntity::EK_New:
5565 case InitializedEntity::EK_Exception:
5566 case InitializedEntity::EK_Base:
5567 case InitializedEntity::EK_Delegating:
5568 return Sema::AA_Initializing;
5570 case InitializedEntity::EK_Parameter:
5571 if (Entity.getDecl() &&
5572 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5573 return Sema::AA_Sending;
5575 return Sema::AA_Passing;
5577 case InitializedEntity::EK_Parameter_CF_Audited:
5578 if (Entity.getDecl() &&
5579 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5580 return Sema::AA_Sending;
5582 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
5584 case InitializedEntity::EK_Result:
5585 return Sema::AA_Returning;
5587 case InitializedEntity::EK_Temporary:
5588 case InitializedEntity::EK_RelatedResult:
5589 // FIXME: Can we tell apart casting vs. converting?
5590 return Sema::AA_Casting;
5592 case InitializedEntity::EK_Member:
5593 case InitializedEntity::EK_Binding:
5594 case InitializedEntity::EK_ArrayElement:
5595 case InitializedEntity::EK_VectorElement:
5596 case InitializedEntity::EK_ComplexElement:
5597 case InitializedEntity::EK_BlockElement:
5598 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
5599 case InitializedEntity::EK_LambdaCapture:
5600 case InitializedEntity::EK_CompoundLiteralInit:
5601 return Sema::AA_Initializing;
5604 llvm_unreachable("Invalid EntityKind!");
5607 /// \brief Whether we should bind a created object as a temporary when
5608 /// initializing the given entity.
5609 static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
5610 switch (Entity.getKind()) {
5611 case InitializedEntity::EK_ArrayElement:
5612 case InitializedEntity::EK_Member:
5613 case InitializedEntity::EK_Result:
5614 case InitializedEntity::EK_New:
5615 case InitializedEntity::EK_Variable:
5616 case InitializedEntity::EK_Base:
5617 case InitializedEntity::EK_Delegating:
5618 case InitializedEntity::EK_VectorElement:
5619 case InitializedEntity::EK_ComplexElement:
5620 case InitializedEntity::EK_Exception:
5621 case InitializedEntity::EK_BlockElement:
5622 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
5623 case InitializedEntity::EK_LambdaCapture:
5624 case InitializedEntity::EK_CompoundLiteralInit:
5627 case InitializedEntity::EK_Parameter:
5628 case InitializedEntity::EK_Parameter_CF_Audited:
5629 case InitializedEntity::EK_Temporary:
5630 case InitializedEntity::EK_RelatedResult:
5631 case InitializedEntity::EK_Binding:
5635 llvm_unreachable("missed an InitializedEntity kind?");
5638 /// \brief Whether the given entity, when initialized with an object
5639 /// created for that initialization, requires destruction.
5640 static bool shouldDestroyEntity(const InitializedEntity &Entity) {
5641 switch (Entity.getKind()) {
5642 case InitializedEntity::EK_Result:
5643 case InitializedEntity::EK_New:
5644 case InitializedEntity::EK_Base:
5645 case InitializedEntity::EK_Delegating:
5646 case InitializedEntity::EK_VectorElement:
5647 case InitializedEntity::EK_ComplexElement:
5648 case InitializedEntity::EK_BlockElement:
5649 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
5650 case InitializedEntity::EK_LambdaCapture:
5653 case InitializedEntity::EK_Member:
5654 case InitializedEntity::EK_Binding:
5655 case InitializedEntity::EK_Variable:
5656 case InitializedEntity::EK_Parameter:
5657 case InitializedEntity::EK_Parameter_CF_Audited:
5658 case InitializedEntity::EK_Temporary:
5659 case InitializedEntity::EK_ArrayElement:
5660 case InitializedEntity::EK_Exception:
5661 case InitializedEntity::EK_CompoundLiteralInit:
5662 case InitializedEntity::EK_RelatedResult:
5666 llvm_unreachable("missed an InitializedEntity kind?");
5669 /// \brief Get the location at which initialization diagnostics should appear.
5670 static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
5671 Expr *Initializer) {
5672 switch (Entity.getKind()) {
5673 case InitializedEntity::EK_Result:
5674 return Entity.getReturnLoc();
5676 case InitializedEntity::EK_Exception:
5677 return Entity.getThrowLoc();
5679 case InitializedEntity::EK_Variable:
5680 case InitializedEntity::EK_Binding:
5681 return Entity.getDecl()->getLocation();
5683 case InitializedEntity::EK_LambdaCapture:
5684 return Entity.getCaptureLoc();
5686 case InitializedEntity::EK_ArrayElement:
5687 case InitializedEntity::EK_Member:
5688 case InitializedEntity::EK_Parameter:
5689 case InitializedEntity::EK_Parameter_CF_Audited:
5690 case InitializedEntity::EK_Temporary:
5691 case InitializedEntity::EK_New:
5692 case InitializedEntity::EK_Base:
5693 case InitializedEntity::EK_Delegating:
5694 case InitializedEntity::EK_VectorElement:
5695 case InitializedEntity::EK_ComplexElement:
5696 case InitializedEntity::EK_BlockElement:
5697 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
5698 case InitializedEntity::EK_CompoundLiteralInit:
5699 case InitializedEntity::EK_RelatedResult:
5700 return Initializer->getLocStart();
5702 llvm_unreachable("missed an InitializedEntity kind?");
5705 /// \brief Make a (potentially elidable) temporary copy of the object
5706 /// provided by the given initializer by calling the appropriate copy
5709 /// \param S The Sema object used for type-checking.
5711 /// \param T The type of the temporary object, which must either be
5712 /// the type of the initializer expression or a superclass thereof.
5714 /// \param Entity The entity being initialized.
5716 /// \param CurInit The initializer expression.
5718 /// \param IsExtraneousCopy Whether this is an "extraneous" copy that
5719 /// is permitted in C++03 (but not C++0x) when binding a reference to
5722 /// \returns An expression that copies the initializer expression into
5723 /// a temporary object, or an error expression if a copy could not be
5725 static ExprResult CopyObject(Sema &S,
5727 const InitializedEntity &Entity,
5729 bool IsExtraneousCopy) {
5730 if (CurInit.isInvalid())
5732 // Determine which class type we're copying to.
5733 Expr *CurInitExpr = (Expr *)CurInit.get();
5734 CXXRecordDecl *Class = nullptr;
5735 if (const RecordType *Record = T->getAs<RecordType>())
5736 Class = cast<CXXRecordDecl>(Record->getDecl());
5740 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
5742 // Make sure that the type we are copying is complete.
5743 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
5746 // Perform overload resolution using the class's constructors. Per
5747 // C++11 [dcl.init]p16, second bullet for class types, this initialization
5748 // is direct-initialization.
5749 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5750 DeclContext::lookup_result Ctors = S.LookupConstructors(Class);
5752 OverloadCandidateSet::iterator Best;
5753 switch (ResolveConstructorOverload(
5754 S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
5755 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
5756 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
5757 /*SecondStepOfCopyInit=*/true)) {
5761 case OR_No_Viable_Function:
5762 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
5763 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
5764 : diag::err_temp_copy_no_viable)
5765 << (int)Entity.getKind() << CurInitExpr->getType()
5766 << CurInitExpr->getSourceRange();
5767 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
5768 if (!IsExtraneousCopy || S.isSFINAEContext())
5773 S.Diag(Loc, diag::err_temp_copy_ambiguous)
5774 << (int)Entity.getKind() << CurInitExpr->getType()
5775 << CurInitExpr->getSourceRange();
5776 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
5780 S.Diag(Loc, diag::err_temp_copy_deleted)
5781 << (int)Entity.getKind() << CurInitExpr->getType()
5782 << CurInitExpr->getSourceRange();
5783 S.NoteDeletedFunction(Best->Function);
5787 bool HadMultipleCandidates = CandidateSet.size() > 1;
5789 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
5790 SmallVector<Expr*, 8> ConstructorArgs;
5791 CurInit.get(); // Ownership transferred into MultiExprArg, below.
5793 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
5796 if (IsExtraneousCopy) {
5797 // If this is a totally extraneous copy for C++03 reference
5798 // binding purposes, just return the original initialization
5799 // expression. We don't generate an (elided) copy operation here
5800 // because doing so would require us to pass down a flag to avoid
5801 // infinite recursion, where each step adds another extraneous,
5804 // Instantiate the default arguments of any extra parameters in
5805 // the selected copy constructor, as if we were going to create a
5806 // proper call to the copy constructor.
5807 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
5808 ParmVarDecl *Parm = Constructor->getParamDecl(I);
5809 if (S.RequireCompleteType(Loc, Parm->getType(),
5810 diag::err_call_incomplete_argument))
5813 // Build the default argument expression; we don't actually care
5814 // if this succeeds or not, because this routine will complain
5815 // if there was a problem.
5816 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5822 // Determine the arguments required to actually perform the
5823 // constructor call (we might have derived-to-base conversions, or
5824 // the copy constructor may have default arguments).
5825 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
5828 // C++0x [class.copy]p32:
5829 // When certain criteria are met, an implementation is allowed to
5830 // omit the copy/move construction of a class object, even if the
5831 // copy/move constructor and/or destructor for the object have
5832 // side effects. [...]
5833 // - when a temporary class object that has not been bound to a
5834 // reference (12.2) would be copied/moved to a class object
5835 // with the same cv-unqualified type, the copy/move operation
5836 // can be omitted by constructing the temporary object
5837 // directly into the target of the omitted copy/move
5839 // Note that the other three bullets are handled elsewhere. Copy
5840 // elision for return statements and throw expressions are handled as part
5841 // of constructor initialization, while copy elision for exception handlers
5842 // is handled by the run-time.
5844 // FIXME: If the function parameter is not the same type as the temporary, we
5845 // should still be able to elide the copy, but we don't have a way to
5846 // represent in the AST how much should be elided in this case.
5848 CurInitExpr->isTemporaryObject(S.Context, Class) &&
5849 S.Context.hasSameUnqualifiedType(
5850 Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
5851 CurInitExpr->getType());
5853 // Actually perform the constructor call.
5854 CurInit = S.BuildCXXConstructExpr(Loc, T, Best->FoundDecl, Constructor,
5857 HadMultipleCandidates,
5859 /*StdInitListInit*/ false,
5861 CXXConstructExpr::CK_Complete,
5864 // If we're supposed to bind temporaries, do so.
5865 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
5866 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
5870 /// \brief Check whether elidable copy construction for binding a reference to
5871 /// a temporary would have succeeded if we were building in C++98 mode, for
5873 static void CheckCXX98CompatAccessibleCopy(Sema &S,
5874 const InitializedEntity &Entity,
5875 Expr *CurInitExpr) {
5876 assert(S.getLangOpts().CPlusPlus11);
5878 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
5882 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
5883 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
5886 // Find constructors which would have been considered.
5887 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5888 DeclContext::lookup_result Ctors =
5889 S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl()));
5891 // Perform overload resolution.
5892 OverloadCandidateSet::iterator Best;
5893 OverloadingResult OR = ResolveConstructorOverload(
5894 S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
5895 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
5896 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
5897 /*SecondStepOfCopyInit=*/true);
5899 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
5900 << OR << (int)Entity.getKind() << CurInitExpr->getType()
5901 << CurInitExpr->getSourceRange();
5905 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
5906 Best->FoundDecl, Entity, Diag);
5907 // FIXME: Check default arguments as far as that's possible.
5910 case OR_No_Viable_Function:
5912 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
5917 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
5922 S.NoteDeletedFunction(Best->Function);
5927 void InitializationSequence::PrintInitLocationNote(Sema &S,
5928 const InitializedEntity &Entity) {
5929 if (Entity.isParameterKind() && Entity.getDecl()) {
5930 if (Entity.getDecl()->getLocation().isInvalid())
5933 if (Entity.getDecl()->getDeclName())
5934 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5935 << Entity.getDecl()->getDeclName();
5937 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5939 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
5940 Entity.getMethodDecl())
5941 S.Diag(Entity.getMethodDecl()->getLocation(),
5942 diag::note_method_return_type_change)
5943 << Entity.getMethodDecl()->getDeclName();
5946 /// Returns true if the parameters describe a constructor initialization of
5947 /// an explicit temporary object, e.g. "Point(x, y)".
5948 static bool isExplicitTemporary(const InitializedEntity &Entity,
5949 const InitializationKind &Kind,
5951 switch (Entity.getKind()) {
5952 case InitializedEntity::EK_Temporary:
5953 case InitializedEntity::EK_CompoundLiteralInit:
5954 case InitializedEntity::EK_RelatedResult:
5960 switch (Kind.getKind()) {
5961 case InitializationKind::IK_DirectList:
5963 // FIXME: Hack to work around cast weirdness.
5964 case InitializationKind::IK_Direct:
5965 case InitializationKind::IK_Value:
5966 return NumArgs != 1;
5973 PerformConstructorInitialization(Sema &S,
5974 const InitializedEntity &Entity,
5975 const InitializationKind &Kind,
5977 const InitializationSequence::Step& Step,
5978 bool &ConstructorInitRequiresZeroInit,
5979 bool IsListInitialization,
5980 bool IsStdInitListInitialization,
5981 SourceLocation LBraceLoc,
5982 SourceLocation RBraceLoc) {
5983 unsigned NumArgs = Args.size();
5984 CXXConstructorDecl *Constructor
5985 = cast<CXXConstructorDecl>(Step.Function.Function);
5986 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
5988 // Build a call to the selected constructor.
5989 SmallVector<Expr*, 8> ConstructorArgs;
5990 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
5991 ? Kind.getEqualLoc()
5992 : Kind.getLocation();
5994 if (Kind.getKind() == InitializationKind::IK_Default) {
5995 // Force even a trivial, implicit default constructor to be
5996 // semantically checked. We do this explicitly because we don't build
5997 // the definition for completely trivial constructors.
5998 assert(Constructor->getParent() && "No parent class for constructor.");
5999 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
6000 Constructor->isTrivial() && !Constructor->isUsed(false))
6001 S.DefineImplicitDefaultConstructor(Loc, Constructor);
6004 ExprResult CurInit((Expr *)nullptr);
6006 // C++ [over.match.copy]p1:
6007 // - When initializing a temporary to be bound to the first parameter
6008 // of a constructor that takes a reference to possibly cv-qualified
6009 // T as its first argument, called with a single argument in the
6010 // context of direct-initialization, explicit conversion functions
6011 // are also considered.
6012 bool AllowExplicitConv =
6013 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
6014 hasCopyOrMoveCtorParam(S.Context,
6015 getConstructorInfo(Step.Function.FoundDecl));
6017 // Determine the arguments required to actually perform the constructor
6019 if (S.CompleteConstructorCall(Constructor, Args,
6020 Loc, ConstructorArgs,
6022 IsListInitialization))
6026 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
6027 // An explicitly-constructed temporary, e.g., X(1, 2).
6028 if (S.DiagnoseUseOfDecl(Constructor, Loc))
6031 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6033 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
6034 SourceRange ParenOrBraceRange =
6035 (Kind.getKind() == InitializationKind::IK_DirectList)
6036 ? SourceRange(LBraceLoc, RBraceLoc)
6037 : Kind.getParenRange();
6039 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
6040 Step.Function.FoundDecl.getDecl())) {
6041 Constructor = S.findInheritingConstructor(Loc, Constructor, Shadow);
6042 if (S.DiagnoseUseOfDecl(Constructor, Loc))
6045 S.MarkFunctionReferenced(Loc, Constructor);
6047 CurInit = new (S.Context) CXXTemporaryObjectExpr(
6048 S.Context, Constructor,
6049 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
6050 ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
6051 IsListInitialization, IsStdInitListInitialization,
6052 ConstructorInitRequiresZeroInit);
6054 CXXConstructExpr::ConstructionKind ConstructKind =
6055 CXXConstructExpr::CK_Complete;
6057 if (Entity.getKind() == InitializedEntity::EK_Base) {
6058 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
6059 CXXConstructExpr::CK_VirtualBase :
6060 CXXConstructExpr::CK_NonVirtualBase;
6061 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
6062 ConstructKind = CXXConstructExpr::CK_Delegating;
6065 // Only get the parenthesis or brace range if it is a list initialization or
6066 // direct construction.
6067 SourceRange ParenOrBraceRange;
6068 if (IsListInitialization)
6069 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
6070 else if (Kind.getKind() == InitializationKind::IK_Direct)
6071 ParenOrBraceRange = Kind.getParenRange();
6073 // If the entity allows NRVO, mark the construction as elidable
6075 if (Entity.allowsNRVO())
6076 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
6077 Step.Function.FoundDecl,
6078 Constructor, /*Elidable=*/true,
6080 HadMultipleCandidates,
6081 IsListInitialization,
6082 IsStdInitListInitialization,
6083 ConstructorInitRequiresZeroInit,
6087 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
6088 Step.Function.FoundDecl,
6091 HadMultipleCandidates,
6092 IsListInitialization,
6093 IsStdInitListInitialization,
6094 ConstructorInitRequiresZeroInit,
6098 if (CurInit.isInvalid())
6101 // Only check access if all of that succeeded.
6102 S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity);
6103 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
6106 if (shouldBindAsTemporary(Entity))
6107 CurInit = S.MaybeBindToTemporary(CurInit.get());
6112 /// Determine whether the specified InitializedEntity definitely has a lifetime
6113 /// longer than the current full-expression. Conservatively returns false if
6116 InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
6117 const InitializedEntity *Top = &Entity;
6118 while (Top->getParent())
6119 Top = Top->getParent();
6121 switch (Top->getKind()) {
6122 case InitializedEntity::EK_Variable:
6123 case InitializedEntity::EK_Result:
6124 case InitializedEntity::EK_Exception:
6125 case InitializedEntity::EK_Member:
6126 case InitializedEntity::EK_Binding:
6127 case InitializedEntity::EK_New:
6128 case InitializedEntity::EK_Base:
6129 case InitializedEntity::EK_Delegating:
6132 case InitializedEntity::EK_ArrayElement:
6133 case InitializedEntity::EK_VectorElement:
6134 case InitializedEntity::EK_BlockElement:
6135 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
6136 case InitializedEntity::EK_ComplexElement:
6137 // Could not determine what the full initialization is. Assume it might not
6138 // outlive the full-expression.
6141 case InitializedEntity::EK_Parameter:
6142 case InitializedEntity::EK_Parameter_CF_Audited:
6143 case InitializedEntity::EK_Temporary:
6144 case InitializedEntity::EK_LambdaCapture:
6145 case InitializedEntity::EK_CompoundLiteralInit:
6146 case InitializedEntity::EK_RelatedResult:
6147 // The entity being initialized might not outlive the full-expression.
6151 llvm_unreachable("unknown entity kind");
6154 /// Determine the declaration which an initialized entity ultimately refers to,
6155 /// for the purpose of lifetime-extending a temporary bound to a reference in
6156 /// the initialization of \p Entity.
6157 static const InitializedEntity *getEntityForTemporaryLifetimeExtension(
6158 const InitializedEntity *Entity,
6159 const InitializedEntity *FallbackDecl = nullptr) {
6160 // C++11 [class.temporary]p5:
6161 switch (Entity->getKind()) {
6162 case InitializedEntity::EK_Variable:
6163 // The temporary [...] persists for the lifetime of the reference
6166 case InitializedEntity::EK_Member:
6167 // For subobjects, we look at the complete object.
6168 if (Entity->getParent())
6169 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
6173 // -- A temporary bound to a reference member in a constructor's
6174 // ctor-initializer persists until the constructor exits.
6177 case InitializedEntity::EK_Binding:
6178 // Per [dcl.decomp]p3, the binding is treated as a variable of reference
6182 case InitializedEntity::EK_Parameter:
6183 case InitializedEntity::EK_Parameter_CF_Audited:
6184 // -- A temporary bound to a reference parameter in a function call
6185 // persists until the completion of the full-expression containing
6187 case InitializedEntity::EK_Result:
6188 // -- The lifetime of a temporary bound to the returned value in a
6189 // function return statement is not extended; the temporary is
6190 // destroyed at the end of the full-expression in the return statement.
6191 case InitializedEntity::EK_New:
6192 // -- A temporary bound to a reference in a new-initializer persists
6193 // until the completion of the full-expression containing the
6197 case InitializedEntity::EK_Temporary:
6198 case InitializedEntity::EK_CompoundLiteralInit:
6199 case InitializedEntity::EK_RelatedResult:
6200 // We don't yet know the storage duration of the surrounding temporary.
6201 // Assume it's got full-expression duration for now, it will patch up our
6202 // storage duration if that's not correct.
6205 case InitializedEntity::EK_ArrayElement:
6206 // For subobjects, we look at the complete object.
6207 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
6210 case InitializedEntity::EK_Base:
6211 // For subobjects, we look at the complete object.
6212 if (Entity->getParent())
6213 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
6216 case InitializedEntity::EK_Delegating:
6217 // We can reach this case for aggregate initialization in a constructor:
6218 // struct A { int &&r; };
6219 // struct B : A { B() : A{0} {} };
6220 // In this case, use the innermost field decl as the context.
6221 return FallbackDecl;
6223 case InitializedEntity::EK_BlockElement:
6224 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
6225 case InitializedEntity::EK_LambdaCapture:
6226 case InitializedEntity::EK_Exception:
6227 case InitializedEntity::EK_VectorElement:
6228 case InitializedEntity::EK_ComplexElement:
6231 llvm_unreachable("unknown entity kind");
6234 static void performLifetimeExtension(Expr *Init,
6235 const InitializedEntity *ExtendingEntity);
6237 /// Update a glvalue expression that is used as the initializer of a reference
6238 /// to note that its lifetime is extended.
6239 /// \return \c true if any temporary had its lifetime extended.
6241 performReferenceExtension(Expr *Init,
6242 const InitializedEntity *ExtendingEntity) {
6243 // Walk past any constructs which we can lifetime-extend across.
6248 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
6249 if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
6250 // This is just redundant braces around an initializer. Step over it.
6251 Init = ILE->getInit(0);
6255 // Step over any subobject adjustments; we may have a materialized
6256 // temporary inside them.
6257 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
6259 // Per current approach for DR1376, look through casts to reference type
6260 // when performing lifetime extension.
6261 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
6262 if (CE->getSubExpr()->isGLValue())
6263 Init = CE->getSubExpr();
6265 // Per the current approach for DR1299, look through array element access
6266 // when performing lifetime extension.
6267 if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init))
6268 Init = ASE->getBase();
6269 } while (Init != Old);
6271 if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
6272 // Update the storage duration of the materialized temporary.
6273 // FIXME: Rebuild the expression instead of mutating it.
6274 ME->setExtendingDecl(ExtendingEntity->getDecl(),
6275 ExtendingEntity->allocateManglingNumber());
6276 performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingEntity);
6283 /// Update a prvalue expression that is going to be materialized as a
6284 /// lifetime-extended temporary.
6285 static void performLifetimeExtension(Expr *Init,
6286 const InitializedEntity *ExtendingEntity) {
6287 // Dig out the expression which constructs the extended temporary.
6288 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
6290 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
6291 Init = BTE->getSubExpr();
6293 if (CXXStdInitializerListExpr *ILE =
6294 dyn_cast<CXXStdInitializerListExpr>(Init)) {
6295 performReferenceExtension(ILE->getSubExpr(), ExtendingEntity);
6299 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
6300 if (ILE->getType()->isArrayType()) {
6301 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
6302 performLifetimeExtension(ILE->getInit(I), ExtendingEntity);
6306 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
6307 assert(RD->isAggregate() && "aggregate init on non-aggregate");
6309 // If we lifetime-extend a braced initializer which is initializing an
6310 // aggregate, and that aggregate contains reference members which are
6311 // bound to temporaries, those temporaries are also lifetime-extended.
6312 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
6313 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
6314 performReferenceExtension(ILE->getInit(0), ExtendingEntity);
6317 for (const auto *I : RD->fields()) {
6318 if (Index >= ILE->getNumInits())
6320 if (I->isUnnamedBitfield())
6322 Expr *SubInit = ILE->getInit(Index);
6323 if (I->getType()->isReferenceType())
6324 performReferenceExtension(SubInit, ExtendingEntity);
6325 else if (isa<InitListExpr>(SubInit) ||
6326 isa<CXXStdInitializerListExpr>(SubInit))
6327 // This may be either aggregate-initialization of a member or
6328 // initialization of a std::initializer_list object. Either way,
6329 // we should recursively lifetime-extend that initializer.
6330 performLifetimeExtension(SubInit, ExtendingEntity);
6338 static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
6339 const Expr *Init, bool IsInitializerList,
6340 const ValueDecl *ExtendingDecl) {
6341 // Warn if a field lifetime-extends a temporary.
6342 if (isa<FieldDecl>(ExtendingDecl)) {
6343 if (IsInitializerList) {
6344 S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
6345 << /*at end of constructor*/true;
6349 bool IsSubobjectMember = false;
6350 for (const InitializedEntity *Ent = Entity.getParent(); Ent;
6351 Ent = Ent->getParent()) {
6352 if (Ent->getKind() != InitializedEntity::EK_Base) {
6353 IsSubobjectMember = true;
6357 S.Diag(Init->getExprLoc(),
6358 diag::warn_bind_ref_member_to_temporary)
6359 << ExtendingDecl << Init->getSourceRange()
6360 << IsSubobjectMember << IsInitializerList;
6361 if (IsSubobjectMember)
6362 S.Diag(ExtendingDecl->getLocation(),
6363 diag::note_ref_subobject_of_member_declared_here);
6365 S.Diag(ExtendingDecl->getLocation(),
6366 diag::note_ref_or_ptr_member_declared_here)
6367 << /*is pointer*/false;
6371 static void DiagnoseNarrowingInInitList(Sema &S,
6372 const ImplicitConversionSequence &ICS,
6373 QualType PreNarrowingType,
6374 QualType EntityType,
6375 const Expr *PostInit);
6377 /// Provide warnings when std::move is used on construction.
6378 static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
6379 bool IsReturnStmt) {
6383 if (S.inTemplateInstantiation())
6386 QualType DestType = InitExpr->getType();
6387 if (!DestType->isRecordType())
6390 unsigned DiagID = 0;
6392 const CXXConstructExpr *CCE =
6393 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
6394 if (!CCE || CCE->getNumArgs() != 1)
6397 if (!CCE->getConstructor()->isCopyOrMoveConstructor())
6400 InitExpr = CCE->getArg(0)->IgnoreImpCasts();
6403 // Find the std::move call and get the argument.
6404 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
6405 if (!CE || CE->getNumArgs() != 1)
6408 const FunctionDecl *MoveFunction = CE->getDirectCallee();
6409 if (!MoveFunction || !MoveFunction->isInStdNamespace() ||
6410 !MoveFunction->getIdentifier() ||
6411 !MoveFunction->getIdentifier()->isStr("move"))
6414 const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
6417 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
6418 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
6421 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
6422 if (!VD || !VD->hasLocalStorage())
6425 // __block variables are not moved implicitly.
6426 if (VD->hasAttr<BlocksAttr>())
6429 QualType SourceType = VD->getType();
6430 if (!SourceType->isRecordType())
6433 if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
6437 // If we're returning a function parameter, copy elision
6439 if (isa<ParmVarDecl>(VD))
6440 DiagID = diag::warn_redundant_move_on_return;
6442 DiagID = diag::warn_pessimizing_move_on_return;
6444 DiagID = diag::warn_pessimizing_move_on_initialization;
6445 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
6446 if (!ArgStripped->isRValue() || !ArgStripped->getType()->isRecordType())
6450 S.Diag(CE->getLocStart(), DiagID);
6452 // Get all the locations for a fix-it. Don't emit the fix-it if any location
6453 // is within a macro.
6454 SourceLocation CallBegin = CE->getCallee()->getLocStart();
6455 if (CallBegin.isMacroID())
6457 SourceLocation RParen = CE->getRParenLoc();
6458 if (RParen.isMacroID())
6460 SourceLocation LParen;
6461 SourceLocation ArgLoc = Arg->getLocStart();
6463 // Special testing for the argument location. Since the fix-it needs the
6464 // location right before the argument, the argument location can be in a
6465 // macro only if it is at the beginning of the macro.
6466 while (ArgLoc.isMacroID() &&
6467 S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) {
6468 ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).first;
6471 if (LParen.isMacroID())
6474 LParen = ArgLoc.getLocWithOffset(-1);
6476 S.Diag(CE->getLocStart(), diag::note_remove_move)
6477 << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
6478 << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
6481 static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
6482 // Check to see if we are dereferencing a null pointer. If so, this is
6483 // undefined behavior, so warn about it. This only handles the pattern
6484 // "*null", which is a very syntactic check.
6485 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
6486 if (UO->getOpcode() == UO_Deref &&
6487 UO->getSubExpr()->IgnoreParenCasts()->
6488 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
6489 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
6490 S.PDiag(diag::warn_binding_null_to_reference)
6491 << UO->getSubExpr()->getSourceRange());
6495 MaterializeTemporaryExpr *
6496 Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
6497 bool BoundToLvalueReference) {
6498 auto MTE = new (Context)
6499 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
6501 // Order an ExprWithCleanups for lifetime marks.
6503 // TODO: It'll be good to have a single place to check the access of the
6504 // destructor and generate ExprWithCleanups for various uses. Currently these
6505 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
6506 // but there may be a chance to merge them.
6507 Cleanup.setExprNeedsCleanups(false);
6511 ExprResult Sema::TemporaryMaterializationConversion(Expr *E) {
6512 // In C++98, we don't want to implicitly create an xvalue.
6513 // FIXME: This means that AST consumers need to deal with "prvalues" that
6514 // denote materialized temporaries. Maybe we should add another ValueKind
6515 // for "xvalue pretending to be a prvalue" for C++98 support.
6516 if (!E->isRValue() || !getLangOpts().CPlusPlus11)
6519 // C++1z [conv.rval]/1: T shall be a complete type.
6520 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
6521 // If so, we should check for a non-abstract class type here too.
6522 QualType T = E->getType();
6523 if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
6526 return CreateMaterializeTemporaryExpr(E->getType(), E, false);
6530 InitializationSequence::Perform(Sema &S,
6531 const InitializedEntity &Entity,
6532 const InitializationKind &Kind,
6534 QualType *ResultType) {
6536 Diagnose(S, Entity, Kind, Args);
6539 if (!ZeroInitializationFixit.empty()) {
6540 unsigned DiagID = diag::err_default_init_const;
6541 if (Decl *D = Entity.getDecl())
6542 if (S.getLangOpts().MSVCCompat && D->hasAttr<SelectAnyAttr>())
6543 DiagID = diag::ext_default_init_const;
6545 // The initialization would have succeeded with this fixit. Since the fixit
6546 // is on the error, we need to build a valid AST in this case, so this isn't
6547 // handled in the Failed() branch above.
6548 QualType DestType = Entity.getType();
6549 S.Diag(Kind.getLocation(), DiagID)
6550 << DestType << (bool)DestType->getAs<RecordType>()
6551 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
6552 ZeroInitializationFixit);
6555 if (getKind() == DependentSequence) {
6556 // If the declaration is a non-dependent, incomplete array type
6557 // that has an initializer, then its type will be completed once
6558 // the initializer is instantiated.
6559 if (ResultType && !Entity.getType()->isDependentType() &&
6561 QualType DeclType = Entity.getType();
6562 if (const IncompleteArrayType *ArrayT
6563 = S.Context.getAsIncompleteArrayType(DeclType)) {
6564 // FIXME: We don't currently have the ability to accurately
6565 // compute the length of an initializer list without
6566 // performing full type-checking of the initializer list
6567 // (since we have to determine where braces are implicitly
6568 // introduced and such). So, we fall back to making the array
6569 // type a dependently-sized array type with no specified
6571 if (isa<InitListExpr>((Expr *)Args[0])) {
6572 SourceRange Brackets;
6574 // Scavange the location of the brackets from the entity, if we can.
6575 if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) {
6576 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
6577 TypeLoc TL = TInfo->getTypeLoc();
6578 if (IncompleteArrayTypeLoc ArrayLoc =
6579 TL.getAs<IncompleteArrayTypeLoc>())
6580 Brackets = ArrayLoc.getBracketsRange();
6585 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
6586 /*NumElts=*/nullptr,
6587 ArrayT->getSizeModifier(),
6588 ArrayT->getIndexTypeCVRQualifiers(),
6594 if (Kind.getKind() == InitializationKind::IK_Direct &&
6595 !Kind.isExplicitCast()) {
6596 // Rebuild the ParenListExpr.
6597 SourceRange ParenRange = Kind.getParenRange();
6598 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
6601 assert(Kind.getKind() == InitializationKind::IK_Copy ||
6602 Kind.isExplicitCast() ||
6603 Kind.getKind() == InitializationKind::IK_DirectList);
6604 return ExprResult(Args[0]);
6607 // No steps means no initialization.
6609 return ExprResult((Expr *)nullptr);
6611 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
6612 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
6613 !Entity.isParameterKind()) {
6614 // Produce a C++98 compatibility warning if we are initializing a reference
6615 // from an initializer list. For parameters, we produce a better warning
6617 Expr *Init = Args[0];
6618 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
6619 << Init->getSourceRange();
6622 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
6623 QualType ETy = Entity.getType();
6624 Qualifiers TyQualifiers = ETy.getQualifiers();
6625 bool HasGlobalAS = TyQualifiers.hasAddressSpace() &&
6626 TyQualifiers.getAddressSpace() == LangAS::opencl_global;
6628 if (S.getLangOpts().OpenCLVersion >= 200 &&
6629 ETy->isAtomicType() && !HasGlobalAS &&
6630 Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
6631 S.Diag(Args[0]->getLocStart(), diag::err_opencl_atomic_init) << 1 <<
6632 SourceRange(Entity.getDecl()->getLocStart(), Args[0]->getLocEnd());
6636 // Diagnose cases where we initialize a pointer to an array temporary, and the
6637 // pointer obviously outlives the temporary.
6638 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
6639 Entity.getType()->isPointerType() &&
6640 InitializedEntityOutlivesFullExpression(Entity)) {
6641 const Expr *Init = Args[0]->skipRValueSubobjectAdjustments();
6642 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
6643 Init = MTE->GetTemporaryExpr();
6644 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
6645 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
6646 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
6647 << Init->getSourceRange();
6650 QualType DestType = Entity.getType().getNonReferenceType();
6651 // FIXME: Ugly hack around the fact that Entity.getType() is not
6652 // the same as Entity.getDecl()->getType() in cases involving type merging,
6653 // and we want latter when it makes sense.
6655 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
6658 ExprResult CurInit((Expr *)nullptr);
6659 SmallVector<Expr*, 4> ArrayLoopCommonExprs;
6661 // For initialization steps that start with a single initializer,
6662 // grab the only argument out the Args and place it into the "current"
6664 switch (Steps.front().Kind) {
6665 case SK_ResolveAddressOfOverloadedFunction:
6666 case SK_CastDerivedToBaseRValue:
6667 case SK_CastDerivedToBaseXValue:
6668 case SK_CastDerivedToBaseLValue:
6669 case SK_BindReference:
6670 case SK_BindReferenceToTemporary:
6672 case SK_ExtraneousCopyToTemporary:
6673 case SK_UserConversion:
6674 case SK_QualificationConversionLValue:
6675 case SK_QualificationConversionXValue:
6676 case SK_QualificationConversionRValue:
6677 case SK_AtomicConversion:
6678 case SK_LValueToRValue:
6679 case SK_ConversionSequence:
6680 case SK_ConversionSequenceNoNarrowing:
6681 case SK_ListInitialization:
6682 case SK_UnwrapInitList:
6683 case SK_RewrapInitList:
6684 case SK_CAssignment:
6686 case SK_ObjCObjectConversion:
6687 case SK_ArrayLoopIndex:
6688 case SK_ArrayLoopInit:
6690 case SK_GNUArrayInit:
6691 case SK_ParenthesizedArrayInit:
6692 case SK_PassByIndirectCopyRestore:
6693 case SK_PassByIndirectRestore:
6694 case SK_ProduceObjCObject:
6695 case SK_StdInitializerList:
6696 case SK_OCLSamplerInit:
6697 case SK_OCLZeroEvent:
6698 case SK_OCLZeroQueue: {
6699 assert(Args.size() == 1);
6701 if (!CurInit.get()) return ExprError();
6705 case SK_ConstructorInitialization:
6706 case SK_ConstructorInitializationFromList:
6707 case SK_StdInitializerListConstructorCall:
6708 case SK_ZeroInitialization:
6712 // Promote from an unevaluated context to an unevaluated list context in
6713 // C++11 list-initialization; we need to instantiate entities usable in
6714 // constant expressions here in order to perform narrowing checks =(
6715 EnterExpressionEvaluationContext Evaluated(
6716 S, EnterExpressionEvaluationContext::InitList,
6717 CurInit.get() && isa<InitListExpr>(CurInit.get()));
6719 // C++ [class.abstract]p2:
6720 // no objects of an abstract class can be created except as subobjects
6721 // of a class derived from it
6722 auto checkAbstractType = [&](QualType T) -> bool {
6723 if (Entity.getKind() == InitializedEntity::EK_Base ||
6724 Entity.getKind() == InitializedEntity::EK_Delegating)
6726 return S.RequireNonAbstractType(Kind.getLocation(), T,
6727 diag::err_allocation_of_abstract_type);
6730 // Walk through the computed steps for the initialization sequence,
6731 // performing the specified conversions along the way.
6732 bool ConstructorInitRequiresZeroInit = false;
6733 for (step_iterator Step = step_begin(), StepEnd = step_end();
6734 Step != StepEnd; ++Step) {
6735 if (CurInit.isInvalid())
6738 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
6740 switch (Step->Kind) {
6741 case SK_ResolveAddressOfOverloadedFunction:
6742 // Overload resolution determined which function invoke; update the
6743 // initializer to reflect that choice.
6744 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
6745 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
6747 CurInit = S.FixOverloadedFunctionReference(CurInit,
6748 Step->Function.FoundDecl,
6749 Step->Function.Function);
6752 case SK_CastDerivedToBaseRValue:
6753 case SK_CastDerivedToBaseXValue:
6754 case SK_CastDerivedToBaseLValue: {
6755 // We have a derived-to-base cast that produces either an rvalue or an
6756 // lvalue. Perform that cast.
6758 CXXCastPath BasePath;
6760 // Casts to inaccessible base classes are allowed with C-style casts.
6761 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
6762 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
6763 CurInit.get()->getLocStart(),
6764 CurInit.get()->getSourceRange(),
6765 &BasePath, IgnoreBaseAccess))
6769 Step->Kind == SK_CastDerivedToBaseLValue ?
6771 (Step->Kind == SK_CastDerivedToBaseXValue ?
6775 ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
6776 CurInit.get(), &BasePath, VK);
6780 case SK_BindReference:
6781 // Reference binding does not have any corresponding ASTs.
6783 // Check exception specifications
6784 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
6787 // We don't check for e.g. function pointers here, since address
6788 // availability checks should only occur when the function first decays
6789 // into a pointer or reference.
6790 if (CurInit.get()->getType()->isFunctionProtoType()) {
6791 if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
6792 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
6793 if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
6794 DRE->getLocStart()))
6800 // Even though we didn't materialize a temporary, the binding may still
6801 // extend the lifetime of a temporary. This happens if we bind a reference
6802 // to the result of a cast to reference type.
6803 if (const InitializedEntity *ExtendingEntity =
6804 getEntityForTemporaryLifetimeExtension(&Entity))
6805 if (performReferenceExtension(CurInit.get(), ExtendingEntity))
6806 warnOnLifetimeExtension(S, Entity, CurInit.get(),
6807 /*IsInitializerList=*/false,
6808 ExtendingEntity->getDecl());
6810 CheckForNullPointerDereference(S, CurInit.get());
6813 case SK_BindReferenceToTemporary: {
6814 // Make sure the "temporary" is actually an rvalue.
6815 assert(CurInit.get()->isRValue() && "not a temporary");
6817 // Check exception specifications
6818 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
6821 // Materialize the temporary into memory.
6822 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
6823 Step->Type, CurInit.get(), Entity.getType()->isLValueReferenceType());
6825 // Maybe lifetime-extend the temporary's subobjects to match the
6826 // entity's lifetime.
6827 if (const InitializedEntity *ExtendingEntity =
6828 getEntityForTemporaryLifetimeExtension(&Entity))
6829 if (performReferenceExtension(MTE, ExtendingEntity))
6830 warnOnLifetimeExtension(S, Entity, CurInit.get(),
6831 /*IsInitializerList=*/false,
6832 ExtendingEntity->getDecl());
6834 // If we're extending this temporary to automatic storage duration -- we
6835 // need to register its cleanup during the full-expression's cleanups.
6836 if (MTE->getStorageDuration() == SD_Automatic &&
6837 MTE->getType().isDestructedType())
6838 S.Cleanup.setExprNeedsCleanups(true);
6845 if (checkAbstractType(Step->Type))
6848 // If the overall initialization is initializing a temporary, we already
6849 // bound our argument if it was necessary to do so. If not (if we're
6850 // ultimately initializing a non-temporary), our argument needs to be
6851 // bound since it's initializing a function parameter.
6852 // FIXME: This is a mess. Rationalize temporary destruction.
6853 if (!shouldBindAsTemporary(Entity))
6854 CurInit = S.MaybeBindToTemporary(CurInit.get());
6855 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
6856 /*IsExtraneousCopy=*/false);
6859 case SK_ExtraneousCopyToTemporary:
6860 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
6861 /*IsExtraneousCopy=*/true);
6864 case SK_UserConversion: {
6865 // We have a user-defined conversion that invokes either a constructor
6866 // or a conversion function.
6868 FunctionDecl *Fn = Step->Function.Function;
6869 DeclAccessPair FoundFn = Step->Function.FoundDecl;
6870 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
6871 bool CreatedObject = false;
6872 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
6873 // Build a call to the selected constructor.
6874 SmallVector<Expr*, 8> ConstructorArgs;
6875 SourceLocation Loc = CurInit.get()->getLocStart();
6877 // Determine the arguments required to actually perform the constructor
6879 Expr *Arg = CurInit.get();
6880 if (S.CompleteConstructorCall(Constructor,
6881 MultiExprArg(&Arg, 1),
6882 Loc, ConstructorArgs))
6885 // Build an expression that constructs a temporary.
6886 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type,
6887 FoundFn, Constructor,
6889 HadMultipleCandidates,
6891 /*StdInitListInit*/ false,
6893 CXXConstructExpr::CK_Complete,
6895 if (CurInit.isInvalid())
6898 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
6900 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6903 CastKind = CK_ConstructorConversion;
6904 CreatedObject = true;
6906 // Build a call to the conversion function.
6907 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
6908 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
6910 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6913 // FIXME: Should we move this initialization into a separate
6914 // derived-to-base conversion? I believe the answer is "no", because
6915 // we don't want to turn off access control here for c-style casts.
6916 CurInit = S.PerformObjectArgumentInitialization(CurInit.get(),
6917 /*Qualifier=*/nullptr,
6918 FoundFn, Conversion);
6919 if (CurInit.isInvalid())
6922 // Build the actual call to the conversion function.
6923 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
6924 HadMultipleCandidates);
6925 if (CurInit.isInvalid())
6928 CastKind = CK_UserDefinedConversion;
6929 CreatedObject = Conversion->getReturnType()->isRecordType();
6932 if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
6935 CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
6936 CastKind, CurInit.get(), nullptr,
6937 CurInit.get()->getValueKind());
6939 if (shouldBindAsTemporary(Entity))
6940 // The overall entity is temporary, so this expression should be
6941 // destroyed at the end of its full-expression.
6942 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
6943 else if (CreatedObject && shouldDestroyEntity(Entity)) {
6944 // The object outlasts the full-expression, but we need to prepare for
6945 // a destructor being run on it.
6946 // FIXME: It makes no sense to do this here. This should happen
6947 // regardless of how we initialized the entity.
6948 QualType T = CurInit.get()->getType();
6949 if (const RecordType *Record = T->getAs<RecordType>()) {
6950 CXXDestructorDecl *Destructor
6951 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
6952 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
6953 S.PDiag(diag::err_access_dtor_temp) << T);
6954 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
6955 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
6962 case SK_QualificationConversionLValue:
6963 case SK_QualificationConversionXValue:
6964 case SK_QualificationConversionRValue: {
6965 // Perform a qualification conversion; these can never go wrong.
6967 Step->Kind == SK_QualificationConversionLValue ?
6969 (Step->Kind == SK_QualificationConversionXValue ?
6972 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK);
6976 case SK_AtomicConversion: {
6977 assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic");
6978 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
6979 CK_NonAtomicToAtomic, VK_RValue);
6983 case SK_LValueToRValue: {
6984 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
6985 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
6986 CK_LValueToRValue, CurInit.get(),
6987 /*BasePath=*/nullptr, VK_RValue);
6991 case SK_ConversionSequence:
6992 case SK_ConversionSequenceNoNarrowing: {
6993 Sema::CheckedConversionKind CCK
6994 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
6995 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
6996 : Kind.isExplicitCast()? Sema::CCK_OtherCast
6997 : Sema::CCK_ImplicitConversion;
6998 ExprResult CurInitExprRes =
6999 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
7000 getAssignmentAction(Entity), CCK);
7001 if (CurInitExprRes.isInvalid())
7004 S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), CurInit.get());
7006 CurInit = CurInitExprRes;
7008 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
7009 S.getLangOpts().CPlusPlus)
7010 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
7016 case SK_ListInitialization: {
7017 if (checkAbstractType(Step->Type))
7020 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
7021 // If we're not initializing the top-level entity, we need to create an
7022 // InitializeTemporary entity for our target type.
7023 QualType Ty = Step->Type;
7024 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
7025 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
7026 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
7027 InitListChecker PerformInitList(S, InitEntity,
7028 InitList, Ty, /*VerifyOnly=*/false,
7029 /*TreatUnavailableAsInvalid=*/false);
7030 if (PerformInitList.HadError())
7033 // Hack: We must update *ResultType if available in order to set the
7034 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
7035 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
7037 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
7038 if ((*ResultType)->isRValueReferenceType())
7039 Ty = S.Context.getRValueReferenceType(Ty);
7040 else if ((*ResultType)->isLValueReferenceType())
7041 Ty = S.Context.getLValueReferenceType(Ty,
7042 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
7046 InitListExpr *StructuredInitList =
7047 PerformInitList.getFullyStructuredList();
7049 CurInit = shouldBindAsTemporary(InitEntity)
7050 ? S.MaybeBindToTemporary(StructuredInitList)
7051 : StructuredInitList;
7055 case SK_ConstructorInitializationFromList: {
7056 if (checkAbstractType(Step->Type))
7059 // When an initializer list is passed for a parameter of type "reference
7060 // to object", we don't get an EK_Temporary entity, but instead an
7061 // EK_Parameter entity with reference type.
7062 // FIXME: This is a hack. What we really should do is create a user
7063 // conversion step for this case, but this makes it considerably more
7064 // complicated. For now, this will do.
7065 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
7066 Entity.getType().getNonReferenceType());
7067 bool UseTemporary = Entity.getType()->isReferenceType();
7068 assert(Args.size() == 1 && "expected a single argument for list init");
7069 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
7070 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
7071 << InitList->getSourceRange();
7072 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
7073 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
7076 ConstructorInitRequiresZeroInit,
7077 /*IsListInitialization*/true,
7078 /*IsStdInitListInit*/false,
7079 InitList->getLBraceLoc(),
7080 InitList->getRBraceLoc());
7084 case SK_UnwrapInitList:
7085 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
7088 case SK_RewrapInitList: {
7089 Expr *E = CurInit.get();
7090 InitListExpr *Syntactic = Step->WrappingSyntacticList;
7091 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
7092 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
7093 ILE->setSyntacticForm(Syntactic);
7094 ILE->setType(E->getType());
7095 ILE->setValueKind(E->getValueKind());
7100 case SK_ConstructorInitialization:
7101 case SK_StdInitializerListConstructorCall: {
7102 if (checkAbstractType(Step->Type))
7105 // When an initializer list is passed for a parameter of type "reference
7106 // to object", we don't get an EK_Temporary entity, but instead an
7107 // EK_Parameter entity with reference type.
7108 // FIXME: This is a hack. What we really should do is create a user
7109 // conversion step for this case, but this makes it considerably more
7110 // complicated. For now, this will do.
7111 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
7112 Entity.getType().getNonReferenceType());
7113 bool UseTemporary = Entity.getType()->isReferenceType();
7114 bool IsStdInitListInit =
7115 Step->Kind == SK_StdInitializerListConstructorCall;
7116 Expr *Source = CurInit.get();
7117 CurInit = PerformConstructorInitialization(
7118 S, UseTemporary ? TempEntity : Entity, Kind,
7119 Source ? MultiExprArg(Source) : Args, *Step,
7120 ConstructorInitRequiresZeroInit,
7121 /*IsListInitialization*/ IsStdInitListInit,
7122 /*IsStdInitListInitialization*/ IsStdInitListInit,
7123 /*LBraceLoc*/ SourceLocation(),
7124 /*RBraceLoc*/ SourceLocation());
7128 case SK_ZeroInitialization: {
7129 step_iterator NextStep = Step;
7131 if (NextStep != StepEnd &&
7132 (NextStep->Kind == SK_ConstructorInitialization ||
7133 NextStep->Kind == SK_ConstructorInitializationFromList)) {
7134 // The need for zero-initialization is recorded directly into
7135 // the call to the object's constructor within the next step.
7136 ConstructorInitRequiresZeroInit = true;
7137 } else if (Kind.getKind() == InitializationKind::IK_Value &&
7138 S.getLangOpts().CPlusPlus &&
7139 !Kind.isImplicitValueInit()) {
7140 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
7142 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
7143 Kind.getRange().getBegin());
7145 CurInit = new (S.Context) CXXScalarValueInitExpr(
7146 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
7147 Kind.getRange().getEnd());
7149 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
7154 case SK_CAssignment: {
7155 QualType SourceType = CurInit.get()->getType();
7156 // Save off the initial CurInit in case we need to emit a diagnostic
7157 ExprResult InitialCurInit = CurInit;
7158 ExprResult Result = CurInit;
7159 Sema::AssignConvertType ConvTy =
7160 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
7161 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
7162 if (Result.isInvalid())
7166 // If this is a call, allow conversion to a transparent union.
7167 ExprResult CurInitExprRes = CurInit;
7168 if (ConvTy != Sema::Compatible &&
7169 Entity.isParameterKind() &&
7170 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
7171 == Sema::Compatible)
7172 ConvTy = Sema::Compatible;
7173 if (CurInitExprRes.isInvalid())
7175 CurInit = CurInitExprRes;
7178 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
7179 Step->Type, SourceType,
7180 InitialCurInit.get(),
7181 getAssignmentAction(Entity, true),
7183 PrintInitLocationNote(S, Entity);
7185 } else if (Complained)
7186 PrintInitLocationNote(S, Entity);
7190 case SK_StringInit: {
7191 QualType Ty = Step->Type;
7192 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
7193 S.Context.getAsArrayType(Ty), S);
7197 case SK_ObjCObjectConversion:
7198 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
7199 CK_ObjCObjectLValueCast,
7200 CurInit.get()->getValueKind());
7203 case SK_ArrayLoopIndex: {
7204 Expr *Cur = CurInit.get();
7205 Expr *BaseExpr = new (S.Context)
7206 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
7207 Cur->getValueKind(), Cur->getObjectKind(), Cur);
7209 new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType());
7210 CurInit = S.CreateBuiltinArraySubscriptExpr(
7211 BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
7212 ArrayLoopCommonExprs.push_back(BaseExpr);
7216 case SK_ArrayLoopInit: {
7217 assert(!ArrayLoopCommonExprs.empty() &&
7218 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
7219 Expr *Common = ArrayLoopCommonExprs.pop_back_val();
7220 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
7225 case SK_GNUArrayInit:
7226 // Okay: we checked everything before creating this step. Note that
7227 // this is a GNU extension.
7228 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
7229 << Step->Type << CurInit.get()->getType()
7230 << CurInit.get()->getSourceRange();
7233 // If the destination type is an incomplete array type, update the
7234 // type accordingly.
7236 if (const IncompleteArrayType *IncompleteDest
7237 = S.Context.getAsIncompleteArrayType(Step->Type)) {
7238 if (const ConstantArrayType *ConstantSource
7239 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
7240 *ResultType = S.Context.getConstantArrayType(
7241 IncompleteDest->getElementType(),
7242 ConstantSource->getSize(),
7243 ArrayType::Normal, 0);
7249 case SK_ParenthesizedArrayInit:
7250 // Okay: we checked everything before creating this step. Note that
7251 // this is a GNU extension.
7252 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
7253 << CurInit.get()->getSourceRange();
7256 case SK_PassByIndirectCopyRestore:
7257 case SK_PassByIndirectRestore:
7258 checkIndirectCopyRestoreSource(S, CurInit.get());
7259 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
7260 CurInit.get(), Step->Type,
7261 Step->Kind == SK_PassByIndirectCopyRestore);
7264 case SK_ProduceObjCObject:
7266 ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
7267 CurInit.get(), nullptr, VK_RValue);
7270 case SK_StdInitializerList: {
7271 S.Diag(CurInit.get()->getExprLoc(),
7272 diag::warn_cxx98_compat_initializer_list_init)
7273 << CurInit.get()->getSourceRange();
7275 // Materialize the temporary into memory.
7276 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
7277 CurInit.get()->getType(), CurInit.get(),
7278 /*BoundToLvalueReference=*/false);
7280 // Maybe lifetime-extend the array temporary's subobjects to match the
7281 // entity's lifetime.
7282 if (const InitializedEntity *ExtendingEntity =
7283 getEntityForTemporaryLifetimeExtension(&Entity))
7284 if (performReferenceExtension(MTE, ExtendingEntity))
7285 warnOnLifetimeExtension(S, Entity, CurInit.get(),
7286 /*IsInitializerList=*/true,
7287 ExtendingEntity->getDecl());
7289 // Wrap it in a construction of a std::initializer_list<T>.
7290 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
7292 // Bind the result, in case the library has given initializer_list a
7293 // non-trivial destructor.
7294 if (shouldBindAsTemporary(Entity))
7295 CurInit = S.MaybeBindToTemporary(CurInit.get());
7299 case SK_OCLSamplerInit: {
7300 // Sampler initialzation have 5 cases:
7301 // 1. function argument passing
7302 // 1a. argument is a file-scope variable
7303 // 1b. argument is a function-scope variable
7304 // 1c. argument is one of caller function's parameters
7305 // 2. variable initialization
7306 // 2a. initializing a file-scope variable
7307 // 2b. initializing a function-scope variable
7309 // For file-scope variables, since they cannot be initialized by function
7310 // call of __translate_sampler_initializer in LLVM IR, their references
7311 // need to be replaced by a cast from their literal initializers to
7312 // sampler type. Since sampler variables can only be used in function
7313 // calls as arguments, we only need to replace them when handling the
7314 // argument passing.
7315 assert(Step->Type->isSamplerT() &&
7316 "Sampler initialization on non-sampler type.");
7317 Expr *Init = CurInit.get();
7318 QualType SourceType = Init->getType();
7320 if (Entity.isParameterKind()) {
7321 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
7322 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
7325 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
7326 auto Var = cast<VarDecl>(DRE->getDecl());
7328 // No cast from integer to sampler is needed.
7329 if (!Var->hasGlobalStorage()) {
7330 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
7331 CK_LValueToRValue, Init,
7332 /*BasePath=*/nullptr, VK_RValue);
7336 // For function call with a file-scope sampler variable as argument,
7337 // get the integer literal.
7338 // Do not diagnose if the file-scope variable does not have initializer
7339 // since this has already been diagnosed when parsing the variable
7341 if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
7343 Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
7344 Var->getInit()))->getSubExpr();
7345 SourceType = Init->getType();
7349 // Check initializer is 32 bit integer constant.
7350 // If the initializer is taken from global variable, do not diagnose since
7351 // this has already been done when parsing the variable declaration.
7352 if (!Init->isConstantInitializer(S.Context, false))
7355 if (!SourceType->isIntegerType() ||
7356 32 != S.Context.getIntWidth(SourceType)) {
7357 S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
7362 llvm::APSInt Result;
7363 Init->EvaluateAsInt(Result, S.Context);
7364 const uint64_t SamplerValue = Result.getLimitedValue();
7365 // 32-bit value of sampler's initializer is interpreted as
7366 // bit-field with the following structure:
7367 // |unspecified|Filter|Addressing Mode| Normalized Coords|
7368 // |31 6|5 4|3 1| 0|
7369 // This structure corresponds to enum values of sampler properties
7370 // defined in SPIR spec v1.2 and also opencl-c.h
7371 unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
7372 unsigned FilterMode = (0x30 & SamplerValue) >> 4;
7373 if (FilterMode != 1 && FilterMode != 2)
7374 S.Diag(Kind.getLocation(),
7375 diag::warn_sampler_initializer_invalid_bits)
7377 if (AddressingMode > 4)
7378 S.Diag(Kind.getLocation(),
7379 diag::warn_sampler_initializer_invalid_bits)
7380 << "Addressing Mode";
7383 // Cases 1a, 2a and 2b
7384 // Insert cast from integer to sampler.
7385 CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy,
7386 CK_IntToOCLSampler);
7389 case SK_OCLZeroEvent: {
7390 assert(Step->Type->isEventT() &&
7391 "Event initialization on non-event type.");
7393 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
7395 CurInit.get()->getValueKind());
7398 case SK_OCLZeroQueue: {
7399 assert(Step->Type->isQueueT() &&
7400 "Event initialization on non queue type.");
7402 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
7404 CurInit.get()->getValueKind());
7410 // Diagnose non-fatal problems with the completed initialization.
7411 if (Entity.getKind() == InitializedEntity::EK_Member &&
7412 cast<FieldDecl>(Entity.getDecl())->isBitField())
7413 S.CheckBitFieldInitialization(Kind.getLocation(),
7414 cast<FieldDecl>(Entity.getDecl()),
7417 // Check for std::move on construction.
7418 if (const Expr *E = CurInit.get()) {
7419 CheckMoveOnConstruction(S, E,
7420 Entity.getKind() == InitializedEntity::EK_Result);
7426 /// Somewhere within T there is an uninitialized reference subobject.
7427 /// Dig it out and diagnose it.
7428 static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
7430 if (T->isReferenceType()) {
7431 S.Diag(Loc, diag::err_reference_without_init)
7432 << T.getNonReferenceType();
7436 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7437 if (!RD || !RD->hasUninitializedReferenceMember())
7440 for (const auto *FI : RD->fields()) {
7441 if (FI->isUnnamedBitfield())
7444 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
7445 S.Diag(Loc, diag::note_value_initialization_here) << RD;
7450 for (const auto &BI : RD->bases()) {
7451 if (DiagnoseUninitializedReference(S, BI.getLocStart(), BI.getType())) {
7452 S.Diag(Loc, diag::note_value_initialization_here) << RD;
7461 //===----------------------------------------------------------------------===//
7462 // Diagnose initialization failures
7463 //===----------------------------------------------------------------------===//
7465 /// Emit notes associated with an initialization that failed due to a
7466 /// "simple" conversion failure.
7467 static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
7469 QualType destType = entity.getType();
7470 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
7471 op->getType()->isObjCObjectPointerType()) {
7473 // Emit a possible note about the conversion failing because the
7474 // operand is a message send with a related result type.
7475 S.EmitRelatedResultTypeNote(op);
7477 // Emit a possible note about a return failing because we're
7478 // expecting a related result type.
7479 if (entity.getKind() == InitializedEntity::EK_Result)
7480 S.EmitRelatedResultTypeNoteForReturn(destType);
7484 static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
7485 InitListExpr *InitList) {
7486 QualType DestType = Entity.getType();
7489 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
7490 QualType ArrayType = S.Context.getConstantArrayType(
7492 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
7493 InitList->getNumInits()),
7494 clang::ArrayType::Normal, 0);
7495 InitializedEntity HiddenArray =
7496 InitializedEntity::InitializeTemporary(ArrayType);
7497 return diagnoseListInit(S, HiddenArray, InitList);
7500 if (DestType->isReferenceType()) {
7501 // A list-initialization failure for a reference means that we tried to
7502 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
7503 // inner initialization failed.
7504 QualType T = DestType->getAs<ReferenceType>()->getPointeeType();
7505 diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
7506 SourceLocation Loc = InitList->getLocStart();
7507 if (auto *D = Entity.getDecl())
7508 Loc = D->getLocation();
7509 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
7513 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
7514 /*VerifyOnly=*/false,
7515 /*TreatUnavailableAsInvalid=*/false);
7516 assert(DiagnoseInitList.HadError() &&
7517 "Inconsistent init list check result.");
7520 bool InitializationSequence::Diagnose(Sema &S,
7521 const InitializedEntity &Entity,
7522 const InitializationKind &Kind,
7523 ArrayRef<Expr *> Args) {
7527 QualType DestType = Entity.getType();
7529 case FK_TooManyInitsForReference:
7530 // FIXME: Customize for the initialized entity?
7532 // Dig out the reference subobject which is uninitialized and diagnose it.
7533 // If this is value-initialization, this could be nested some way within
7535 assert(Kind.getKind() == InitializationKind::IK_Value ||
7536 DestType->isReferenceType());
7538 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
7539 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
7541 } else // FIXME: diagnostic below could be better!
7542 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
7543 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
7545 case FK_ParenthesizedListInitForReference:
7546 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
7547 << 1 << Entity.getType() << Args[0]->getSourceRange();
7550 case FK_ArrayNeedsInitList:
7551 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
7553 case FK_ArrayNeedsInitListOrStringLiteral:
7554 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
7556 case FK_ArrayNeedsInitListOrWideStringLiteral:
7557 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
7559 case FK_NarrowStringIntoWideCharArray:
7560 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
7562 case FK_WideStringIntoCharArray:
7563 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
7565 case FK_IncompatWideStringIntoWideChar:
7566 S.Diag(Kind.getLocation(),
7567 diag::err_array_init_incompat_wide_string_into_wchar);
7569 case FK_ArrayTypeMismatch:
7570 case FK_NonConstantArrayInit:
7571 S.Diag(Kind.getLocation(),
7572 (Failure == FK_ArrayTypeMismatch
7573 ? diag::err_array_init_different_type
7574 : diag::err_array_init_non_constant_array))
7575 << DestType.getNonReferenceType()
7576 << Args[0]->getType()
7577 << Args[0]->getSourceRange();
7580 case FK_VariableLengthArrayHasInitializer:
7581 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
7582 << Args[0]->getSourceRange();
7585 case FK_AddressOfOverloadFailed: {
7586 DeclAccessPair Found;
7587 S.ResolveAddressOfOverloadedFunction(Args[0],
7588 DestType.getNonReferenceType(),
7594 case FK_AddressOfUnaddressableFunction: {
7595 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(Args[0])->getDecl());
7596 S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
7597 Args[0]->getLocStart());
7601 case FK_ReferenceInitOverloadFailed:
7602 case FK_UserConversionOverloadFailed:
7603 switch (FailedOverloadResult) {
7605 if (Failure == FK_UserConversionOverloadFailed)
7606 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
7607 << Args[0]->getType() << DestType
7608 << Args[0]->getSourceRange();
7610 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
7611 << DestType << Args[0]->getType()
7612 << Args[0]->getSourceRange();
7614 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
7617 case OR_No_Viable_Function:
7618 if (!S.RequireCompleteType(Kind.getLocation(),
7619 DestType.getNonReferenceType(),
7620 diag::err_typecheck_nonviable_condition_incomplete,
7621 Args[0]->getType(), Args[0]->getSourceRange()))
7622 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
7623 << (Entity.getKind() == InitializedEntity::EK_Result)
7624 << Args[0]->getType() << Args[0]->getSourceRange()
7625 << DestType.getNonReferenceType();
7627 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
7631 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
7632 << Args[0]->getType() << DestType.getNonReferenceType()
7633 << Args[0]->getSourceRange();
7634 OverloadCandidateSet::iterator Best;
7635 OverloadingResult Ovl
7636 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
7637 if (Ovl == OR_Deleted) {
7638 S.NoteDeletedFunction(Best->Function);
7640 llvm_unreachable("Inconsistent overload resolution?");
7646 llvm_unreachable("Conversion did not fail!");
7650 case FK_NonConstLValueReferenceBindingToTemporary:
7651 if (isa<InitListExpr>(Args[0])) {
7652 S.Diag(Kind.getLocation(),
7653 diag::err_lvalue_reference_bind_to_initlist)
7654 << DestType.getNonReferenceType().isVolatileQualified()
7655 << DestType.getNonReferenceType()
7656 << Args[0]->getSourceRange();
7661 case FK_NonConstLValueReferenceBindingToUnrelated:
7662 S.Diag(Kind.getLocation(),
7663 Failure == FK_NonConstLValueReferenceBindingToTemporary
7664 ? diag::err_lvalue_reference_bind_to_temporary
7665 : diag::err_lvalue_reference_bind_to_unrelated)
7666 << DestType.getNonReferenceType().isVolatileQualified()
7667 << DestType.getNonReferenceType()
7668 << Args[0]->getType()
7669 << Args[0]->getSourceRange();
7672 case FK_NonConstLValueReferenceBindingToBitfield: {
7673 // We don't necessarily have an unambiguous source bit-field.
7674 FieldDecl *BitField = Args[0]->getSourceBitField();
7675 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
7676 << DestType.isVolatileQualified()
7677 << (BitField ? BitField->getDeclName() : DeclarationName())
7678 << (BitField != nullptr)
7679 << Args[0]->getSourceRange();
7681 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
7685 case FK_NonConstLValueReferenceBindingToVectorElement:
7686 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
7687 << DestType.isVolatileQualified()
7688 << Args[0]->getSourceRange();
7691 case FK_RValueReferenceBindingToLValue:
7692 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
7693 << DestType.getNonReferenceType() << Args[0]->getType()
7694 << Args[0]->getSourceRange();
7697 case FK_ReferenceInitDropsQualifiers: {
7698 QualType SourceType = Args[0]->getType();
7699 QualType NonRefType = DestType.getNonReferenceType();
7700 Qualifiers DroppedQualifiers =
7701 SourceType.getQualifiers() - NonRefType.getQualifiers();
7703 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
7706 << DroppedQualifiers.getCVRQualifiers()
7707 << Args[0]->getSourceRange();
7711 case FK_ReferenceInitFailed:
7712 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
7713 << DestType.getNonReferenceType()
7714 << Args[0]->isLValue()
7715 << Args[0]->getType()
7716 << Args[0]->getSourceRange();
7717 emitBadConversionNotes(S, Entity, Args[0]);
7720 case FK_ConversionFailed: {
7721 QualType FromType = Args[0]->getType();
7722 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
7723 << (int)Entity.getKind()
7725 << Args[0]->isLValue()
7727 << Args[0]->getSourceRange();
7728 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
7729 S.Diag(Kind.getLocation(), PDiag);
7730 emitBadConversionNotes(S, Entity, Args[0]);
7734 case FK_ConversionFromPropertyFailed:
7735 // No-op. This error has already been reported.
7738 case FK_TooManyInitsForScalar: {
7741 auto *InitList = dyn_cast<InitListExpr>(Args[0]);
7742 if (InitList && InitList->getNumInits() >= 1) {
7743 R = SourceRange(InitList->getInit(0)->getLocEnd(), InitList->getLocEnd());
7745 assert(Args.size() > 1 && "Expected multiple initializers!");
7746 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
7749 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
7750 if (Kind.isCStyleOrFunctionalCast())
7751 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
7754 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
7755 << /*scalar=*/2 << R;
7759 case FK_ParenthesizedListInitForScalar:
7760 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
7761 << 0 << Entity.getType() << Args[0]->getSourceRange();
7764 case FK_ReferenceBindingToInitList:
7765 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
7766 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
7769 case FK_InitListBadDestinationType:
7770 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
7771 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
7774 case FK_ListConstructorOverloadFailed:
7775 case FK_ConstructorOverloadFailed: {
7776 SourceRange ArgsRange;
7778 ArgsRange = SourceRange(Args.front()->getLocStart(),
7779 Args.back()->getLocEnd());
7781 if (Failure == FK_ListConstructorOverloadFailed) {
7782 assert(Args.size() == 1 &&
7783 "List construction from other than 1 argument.");
7784 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
7785 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
7788 // FIXME: Using "DestType" for the entity we're printing is probably
7790 switch (FailedOverloadResult) {
7792 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
7793 << DestType << ArgsRange;
7794 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
7797 case OR_No_Viable_Function:
7798 if (Kind.getKind() == InitializationKind::IK_Default &&
7799 (Entity.getKind() == InitializedEntity::EK_Base ||
7800 Entity.getKind() == InitializedEntity::EK_Member) &&
7801 isa<CXXConstructorDecl>(S.CurContext)) {
7802 // This is implicit default initialization of a member or
7803 // base within a constructor. If no viable function was
7804 // found, notify the user that they need to explicitly
7805 // initialize this base/member.
7806 CXXConstructorDecl *Constructor
7807 = cast<CXXConstructorDecl>(S.CurContext);
7808 const CXXRecordDecl *InheritedFrom = nullptr;
7809 if (auto Inherited = Constructor->getInheritedConstructor())
7810 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
7811 if (Entity.getKind() == InitializedEntity::EK_Base) {
7812 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
7813 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
7814 << S.Context.getTypeDeclType(Constructor->getParent())
7819 RecordDecl *BaseDecl
7820 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
7822 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
7823 << S.Context.getTagDeclType(BaseDecl);
7825 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
7826 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
7827 << S.Context.getTypeDeclType(Constructor->getParent())
7831 S.Diag(Entity.getDecl()->getLocation(),
7832 diag::note_member_declared_at);
7834 if (const RecordType *Record
7835 = Entity.getType()->getAs<RecordType>())
7836 S.Diag(Record->getDecl()->getLocation(),
7837 diag::note_previous_decl)
7838 << S.Context.getTagDeclType(Record->getDecl());
7843 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
7844 << DestType << ArgsRange;
7845 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
7849 OverloadCandidateSet::iterator Best;
7850 OverloadingResult Ovl
7851 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
7852 if (Ovl != OR_Deleted) {
7853 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
7854 << true << DestType << ArgsRange;
7855 llvm_unreachable("Inconsistent overload resolution?");
7859 // If this is a defaulted or implicitly-declared function, then
7860 // it was implicitly deleted. Make it clear that the deletion was
7862 if (S.isImplicitlyDeleted(Best->Function))
7863 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
7864 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
7865 << DestType << ArgsRange;
7867 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
7868 << true << DestType << ArgsRange;
7870 S.NoteDeletedFunction(Best->Function);
7875 llvm_unreachable("Conversion did not fail!");
7880 case FK_DefaultInitOfConst:
7881 if (Entity.getKind() == InitializedEntity::EK_Member &&
7882 isa<CXXConstructorDecl>(S.CurContext)) {
7883 // This is implicit default-initialization of a const member in
7884 // a constructor. Complain that it needs to be explicitly
7886 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
7887 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
7888 << (Constructor->getInheritedConstructor() ? 2 :
7889 Constructor->isImplicit() ? 1 : 0)
7890 << S.Context.getTypeDeclType(Constructor->getParent())
7892 << Entity.getName();
7893 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
7894 << Entity.getName();
7896 S.Diag(Kind.getLocation(), diag::err_default_init_const)
7897 << DestType << (bool)DestType->getAs<RecordType>();
7902 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
7903 diag::err_init_incomplete_type);
7906 case FK_ListInitializationFailed: {
7907 // Run the init list checker again to emit diagnostics.
7908 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
7909 diagnoseListInit(S, Entity, InitList);
7913 case FK_PlaceholderType: {
7914 // FIXME: Already diagnosed!
7918 case FK_ExplicitConstructor: {
7919 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
7920 << Args[0]->getSourceRange();
7921 OverloadCandidateSet::iterator Best;
7922 OverloadingResult Ovl
7923 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
7925 assert(Ovl == OR_Success && "Inconsistent overload resolution");
7926 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
7927 S.Diag(CtorDecl->getLocation(),
7928 diag::note_explicit_ctor_deduction_guide_here) << false;
7933 PrintInitLocationNote(S, Entity);
7937 void InitializationSequence::dump(raw_ostream &OS) const {
7938 switch (SequenceKind) {
7939 case FailedSequence: {
7940 OS << "Failed sequence: ";
7942 case FK_TooManyInitsForReference:
7943 OS << "too many initializers for reference";
7946 case FK_ParenthesizedListInitForReference:
7947 OS << "parenthesized list init for reference";
7950 case FK_ArrayNeedsInitList:
7951 OS << "array requires initializer list";
7954 case FK_AddressOfUnaddressableFunction:
7955 OS << "address of unaddressable function was taken";
7958 case FK_ArrayNeedsInitListOrStringLiteral:
7959 OS << "array requires initializer list or string literal";
7962 case FK_ArrayNeedsInitListOrWideStringLiteral:
7963 OS << "array requires initializer list or wide string literal";
7966 case FK_NarrowStringIntoWideCharArray:
7967 OS << "narrow string into wide char array";
7970 case FK_WideStringIntoCharArray:
7971 OS << "wide string into char array";
7974 case FK_IncompatWideStringIntoWideChar:
7975 OS << "incompatible wide string into wide char array";
7978 case FK_ArrayTypeMismatch:
7979 OS << "array type mismatch";
7982 case FK_NonConstantArrayInit:
7983 OS << "non-constant array initializer";
7986 case FK_AddressOfOverloadFailed:
7987 OS << "address of overloaded function failed";
7990 case FK_ReferenceInitOverloadFailed:
7991 OS << "overload resolution for reference initialization failed";
7994 case FK_NonConstLValueReferenceBindingToTemporary:
7995 OS << "non-const lvalue reference bound to temporary";
7998 case FK_NonConstLValueReferenceBindingToBitfield:
7999 OS << "non-const lvalue reference bound to bit-field";
8002 case FK_NonConstLValueReferenceBindingToVectorElement:
8003 OS << "non-const lvalue reference bound to vector element";
8006 case FK_NonConstLValueReferenceBindingToUnrelated:
8007 OS << "non-const lvalue reference bound to unrelated type";
8010 case FK_RValueReferenceBindingToLValue:
8011 OS << "rvalue reference bound to an lvalue";
8014 case FK_ReferenceInitDropsQualifiers:
8015 OS << "reference initialization drops qualifiers";
8018 case FK_ReferenceInitFailed:
8019 OS << "reference initialization failed";
8022 case FK_ConversionFailed:
8023 OS << "conversion failed";
8026 case FK_ConversionFromPropertyFailed:
8027 OS << "conversion from property failed";
8030 case FK_TooManyInitsForScalar:
8031 OS << "too many initializers for scalar";
8034 case FK_ParenthesizedListInitForScalar:
8035 OS << "parenthesized list init for reference";
8038 case FK_ReferenceBindingToInitList:
8039 OS << "referencing binding to initializer list";
8042 case FK_InitListBadDestinationType:
8043 OS << "initializer list for non-aggregate, non-scalar type";
8046 case FK_UserConversionOverloadFailed:
8047 OS << "overloading failed for user-defined conversion";
8050 case FK_ConstructorOverloadFailed:
8051 OS << "constructor overloading failed";
8054 case FK_DefaultInitOfConst:
8055 OS << "default initialization of a const variable";
8059 OS << "initialization of incomplete type";
8062 case FK_ListInitializationFailed:
8063 OS << "list initialization checker failure";
8066 case FK_VariableLengthArrayHasInitializer:
8067 OS << "variable length array has an initializer";
8070 case FK_PlaceholderType:
8071 OS << "initializer expression isn't contextually valid";
8074 case FK_ListConstructorOverloadFailed:
8075 OS << "list constructor overloading failed";
8078 case FK_ExplicitConstructor:
8079 OS << "list copy initialization chose explicit constructor";
8086 case DependentSequence:
8087 OS << "Dependent sequence\n";
8090 case NormalSequence:
8091 OS << "Normal sequence: ";
8095 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
8096 if (S != step_begin()) {
8101 case SK_ResolveAddressOfOverloadedFunction:
8102 OS << "resolve address of overloaded function";
8105 case SK_CastDerivedToBaseRValue:
8106 OS << "derived-to-base (rvalue)";
8109 case SK_CastDerivedToBaseXValue:
8110 OS << "derived-to-base (xvalue)";
8113 case SK_CastDerivedToBaseLValue:
8114 OS << "derived-to-base (lvalue)";
8117 case SK_BindReference:
8118 OS << "bind reference to lvalue";
8121 case SK_BindReferenceToTemporary:
8122 OS << "bind reference to a temporary";
8126 OS << "final copy in class direct-initialization";
8129 case SK_ExtraneousCopyToTemporary:
8130 OS << "extraneous C++03 copy to temporary";
8133 case SK_UserConversion:
8134 OS << "user-defined conversion via " << *S->Function.Function;
8137 case SK_QualificationConversionRValue:
8138 OS << "qualification conversion (rvalue)";
8141 case SK_QualificationConversionXValue:
8142 OS << "qualification conversion (xvalue)";
8145 case SK_QualificationConversionLValue:
8146 OS << "qualification conversion (lvalue)";
8149 case SK_AtomicConversion:
8150 OS << "non-atomic-to-atomic conversion";
8153 case SK_LValueToRValue:
8154 OS << "load (lvalue to rvalue)";
8157 case SK_ConversionSequence:
8158 OS << "implicit conversion sequence (";
8159 S->ICS->dump(); // FIXME: use OS
8163 case SK_ConversionSequenceNoNarrowing:
8164 OS << "implicit conversion sequence with narrowing prohibited (";
8165 S->ICS->dump(); // FIXME: use OS
8169 case SK_ListInitialization:
8170 OS << "list aggregate initialization";
8173 case SK_UnwrapInitList:
8174 OS << "unwrap reference initializer list";
8177 case SK_RewrapInitList:
8178 OS << "rewrap reference initializer list";
8181 case SK_ConstructorInitialization:
8182 OS << "constructor initialization";
8185 case SK_ConstructorInitializationFromList:
8186 OS << "list initialization via constructor";
8189 case SK_ZeroInitialization:
8190 OS << "zero initialization";
8193 case SK_CAssignment:
8194 OS << "C assignment";
8198 OS << "string initialization";
8201 case SK_ObjCObjectConversion:
8202 OS << "Objective-C object conversion";
8205 case SK_ArrayLoopIndex:
8206 OS << "indexing for array initialization loop";
8209 case SK_ArrayLoopInit:
8210 OS << "array initialization loop";
8214 OS << "array initialization";
8217 case SK_GNUArrayInit:
8218 OS << "array initialization (GNU extension)";
8221 case SK_ParenthesizedArrayInit:
8222 OS << "parenthesized array initialization";
8225 case SK_PassByIndirectCopyRestore:
8226 OS << "pass by indirect copy and restore";
8229 case SK_PassByIndirectRestore:
8230 OS << "pass by indirect restore";
8233 case SK_ProduceObjCObject:
8234 OS << "Objective-C object retension";
8237 case SK_StdInitializerList:
8238 OS << "std::initializer_list from initializer list";
8241 case SK_StdInitializerListConstructorCall:
8242 OS << "list initialization from std::initializer_list";
8245 case SK_OCLSamplerInit:
8246 OS << "OpenCL sampler_t from integer constant";
8249 case SK_OCLZeroEvent:
8250 OS << "OpenCL event_t from zero";
8253 case SK_OCLZeroQueue:
8254 OS << "OpenCL queue_t from zero";
8258 OS << " [" << S->Type.getAsString() << ']';
8264 void InitializationSequence::dump() const {
8268 static void DiagnoseNarrowingInInitList(Sema &S,
8269 const ImplicitConversionSequence &ICS,
8270 QualType PreNarrowingType,
8271 QualType EntityType,
8272 const Expr *PostInit) {
8273 const StandardConversionSequence *SCS = nullptr;
8274 switch (ICS.getKind()) {
8275 case ImplicitConversionSequence::StandardConversion:
8276 SCS = &ICS.Standard;
8278 case ImplicitConversionSequence::UserDefinedConversion:
8279 SCS = &ICS.UserDefined.After;
8281 case ImplicitConversionSequence::AmbiguousConversion:
8282 case ImplicitConversionSequence::EllipsisConversion:
8283 case ImplicitConversionSequence::BadConversion:
8287 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
8288 APValue ConstantValue;
8289 QualType ConstantType;
8290 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
8292 case NK_Not_Narrowing:
8293 case NK_Dependent_Narrowing:
8294 // No narrowing occurred.
8297 case NK_Type_Narrowing:
8298 // This was a floating-to-integer conversion, which is always considered a
8299 // narrowing conversion even if the value is a constant and can be
8300 // represented exactly as an integer.
8301 S.Diag(PostInit->getLocStart(),
8302 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
8303 ? diag::warn_init_list_type_narrowing
8304 : diag::ext_init_list_type_narrowing)
8305 << PostInit->getSourceRange()
8306 << PreNarrowingType.getLocalUnqualifiedType()
8307 << EntityType.getLocalUnqualifiedType();
8310 case NK_Constant_Narrowing:
8311 // A constant value was narrowed.
8312 S.Diag(PostInit->getLocStart(),
8313 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
8314 ? diag::warn_init_list_constant_narrowing
8315 : diag::ext_init_list_constant_narrowing)
8316 << PostInit->getSourceRange()
8317 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
8318 << EntityType.getLocalUnqualifiedType();
8321 case NK_Variable_Narrowing:
8322 // A variable's value may have been narrowed.
8323 S.Diag(PostInit->getLocStart(),
8324 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
8325 ? diag::warn_init_list_variable_narrowing
8326 : diag::ext_init_list_variable_narrowing)
8327 << PostInit->getSourceRange()
8328 << PreNarrowingType.getLocalUnqualifiedType()
8329 << EntityType.getLocalUnqualifiedType();
8333 SmallString<128> StaticCast;
8334 llvm::raw_svector_ostream OS(StaticCast);
8335 OS << "static_cast<";
8336 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
8337 // It's important to use the typedef's name if there is one so that the
8338 // fixit doesn't break code using types like int64_t.
8340 // FIXME: This will break if the typedef requires qualification. But
8341 // getQualifiedNameAsString() includes non-machine-parsable components.
8342 OS << *TT->getDecl();
8343 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
8344 OS << BT->getName(S.getLangOpts());
8346 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
8347 // with a broken cast.
8351 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_silence)
8352 << PostInit->getSourceRange()
8353 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
8354 << FixItHint::CreateInsertion(
8355 S.getLocForEndOfToken(PostInit->getLocEnd()), ")");
8358 //===----------------------------------------------------------------------===//
8359 // Initialization helper functions
8360 //===----------------------------------------------------------------------===//
8362 Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
8364 if (Init.isInvalid())
8367 Expr *InitE = Init.get();
8368 assert(InitE && "No initialization expression");
8370 InitializationKind Kind
8371 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
8372 InitializationSequence Seq(*this, Entity, Kind, InitE);
8373 return !Seq.Failed();
8377 Sema::PerformCopyInitialization(const InitializedEntity &Entity,
8378 SourceLocation EqualLoc,
8380 bool TopLevelOfInitList,
8381 bool AllowExplicit) {
8382 if (Init.isInvalid())
8385 Expr *InitE = Init.get();
8386 assert(InitE && "No initialization expression?");
8388 if (EqualLoc.isInvalid())
8389 EqualLoc = InitE->getLocStart();
8391 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
8394 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
8396 // Prevent infinite recursion when performing parameter copy-initialization.
8397 const bool ShouldTrackCopy =
8398 Entity.isParameterKind() && Seq.isConstructorInitialization();
8399 if (ShouldTrackCopy) {
8400 if (llvm::find(CurrentParameterCopyTypes, Entity.getType()) !=
8401 CurrentParameterCopyTypes.end()) {
8402 Seq.SetOverloadFailure(
8403 InitializationSequence::FK_ConstructorOverloadFailed,
8404 OR_No_Viable_Function);
8406 // Try to give a meaningful diagnostic note for the problematic
8408 const auto LastStep = Seq.step_end() - 1;
8409 assert(LastStep->Kind ==
8410 InitializationSequence::SK_ConstructorInitialization);
8411 const FunctionDecl *Function = LastStep->Function.Function;
8413 llvm::find_if(Seq.getFailedCandidateSet(),
8414 [Function](const OverloadCandidate &Candidate) -> bool {
8415 return Candidate.Viable &&
8416 Candidate.Function == Function &&
8417 Candidate.Conversions.size() > 0;
8419 if (Candidate != Seq.getFailedCandidateSet().end() &&
8420 Function->getNumParams() > 0) {
8421 Candidate->Viable = false;
8422 Candidate->FailureKind = ovl_fail_bad_conversion;
8423 Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion,
8425 Function->getParamDecl(0)->getType());
8428 CurrentParameterCopyTypes.push_back(Entity.getType());
8431 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
8433 if (ShouldTrackCopy)
8434 CurrentParameterCopyTypes.pop_back();
8439 /// Determine whether RD is, or is derived from, a specialization of CTD.
8440 static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD,
8441 ClassTemplateDecl *CTD) {
8442 auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
8443 auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
8444 return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
8446 return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
8449 QualType Sema::DeduceTemplateSpecializationFromInitializer(
8450 TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
8451 const InitializationKind &Kind, MultiExprArg Inits) {
8452 auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
8453 TSInfo->getType()->getContainedDeducedType());
8454 assert(DeducedTST && "not a deduced template specialization type");
8456 // We can only perform deduction for class templates.
8457 auto TemplateName = DeducedTST->getTemplateName();
8459 dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
8461 Diag(Kind.getLocation(),
8462 diag::err_deduced_non_class_template_specialization_type)
8463 << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName;
8464 if (auto *TD = TemplateName.getAsTemplateDecl())
8465 Diag(TD->getLocation(), diag::note_template_decl_here);
8469 // Can't deduce from dependent arguments.
8470 if (Expr::hasAnyTypeDependentArguments(Inits))
8471 return Context.DependentTy;
8473 // FIXME: Perform "exact type" matching first, per CWG discussion?
8474 // Or implement this via an implied 'T(T) -> T' deduction guide?
8476 // FIXME: Do we need/want a std::initializer_list<T> special case?
8478 // Look up deduction guides, including those synthesized from constructors.
8480 // C++1z [over.match.class.deduct]p1:
8481 // A set of functions and function templates is formed comprising:
8482 // - For each constructor of the class template designated by the
8483 // template-name, a function template [...]
8484 // - For each deduction-guide, a function or function template [...]
8485 DeclarationNameInfo NameInfo(
8486 Context.DeclarationNames.getCXXDeductionGuideName(Template),
8487 TSInfo->getTypeLoc().getEndLoc());
8488 LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
8489 LookupQualifiedName(Guides, Template->getDeclContext());
8491 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
8492 // clear on this, but they're not found by name so access does not apply.
8493 Guides.suppressDiagnostics();
8495 // Figure out if this is list-initialization.
8496 InitListExpr *ListInit =
8497 (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
8498 ? dyn_cast<InitListExpr>(Inits[0])
8501 // C++1z [over.match.class.deduct]p1:
8502 // Initialization and overload resolution are performed as described in
8503 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
8504 // (as appropriate for the type of initialization performed) for an object
8505 // of a hypothetical class type, where the selected functions and function
8506 // templates are considered to be the constructors of that class type
8508 // Since we know we're initializing a class type of a type unrelated to that
8509 // of the initializer, this reduces to something fairly reasonable.
8510 OverloadCandidateSet Candidates(Kind.getLocation(),
8511 OverloadCandidateSet::CSK_Normal);
8512 OverloadCandidateSet::iterator Best;
8513 auto tryToResolveOverload =
8514 [&](bool OnlyListConstructors) -> OverloadingResult {
8515 Candidates.clear(OverloadCandidateSet::CSK_Normal);
8516 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
8517 NamedDecl *D = (*I)->getUnderlyingDecl();
8518 if (D->isInvalidDecl())
8521 auto *TD = dyn_cast<FunctionTemplateDecl>(D);
8522 auto *GD = dyn_cast_or_null<CXXDeductionGuideDecl>(
8523 TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
8527 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
8528 // For copy-initialization, the candidate functions are all the
8529 // converting constructors (12.3.1) of that class.
8530 // C++ [over.match.copy]p1: (non-list copy-initialization from class)
8531 // The converting constructors of T are candidate functions.
8532 if (Kind.isCopyInit() && !ListInit) {
8533 // Only consider converting constructors.
8534 if (GD->isExplicit())
8537 // When looking for a converting constructor, deduction guides that
8538 // could never be called with one argument are not interesting to
8540 if (GD->getMinRequiredArguments() > 1 ||
8541 (GD->getNumParams() == 0 && !GD->isVariadic()))
8545 // C++ [over.match.list]p1.1: (first phase list initialization)
8546 // Initially, the candidate functions are the initializer-list
8547 // constructors of the class T
8548 if (OnlyListConstructors && !isInitListConstructor(GD))
8551 // C++ [over.match.list]p1.2: (second phase list initialization)
8552 // the candidate functions are all the constructors of the class T
8553 // C++ [over.match.ctor]p1: (all other cases)
8554 // the candidate functions are all the constructors of the class of
8555 // the object being initialized
8557 // C++ [over.best.ics]p4:
8558 // When [...] the constructor [...] is a candidate by
8559 // - [over.match.copy] (in all cases)
8560 // FIXME: The "second phase of [over.match.list] case can also
8561 // theoretically happen here, but it's not clear whether we can
8562 // ever have a parameter of the right type.
8563 bool SuppressUserConversions = Kind.isCopyInit();
8566 AddTemplateOverloadCandidate(TD, I.getPair(), /*ExplicitArgs*/ nullptr,
8568 SuppressUserConversions);
8570 AddOverloadCandidate(GD, I.getPair(), Inits, Candidates,
8571 SuppressUserConversions);
8573 return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
8576 OverloadingResult Result = OR_No_Viable_Function;
8578 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
8579 // try initializer-list constructors.
8581 bool TryListConstructors = true;
8583 // Try list constructors unless the list is empty and the class has one or
8584 // more default constructors, in which case those constructors win.
8585 if (!ListInit->getNumInits()) {
8586 for (NamedDecl *D : Guides) {
8587 auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
8588 if (FD && FD->getMinRequiredArguments() == 0) {
8589 TryListConstructors = false;
8593 } else if (ListInit->getNumInits() == 1) {
8594 // C++ [over.match.class.deduct]:
8595 // As an exception, the first phase in [over.match.list] (considering
8596 // initializer-list constructors) is omitted if the initializer list
8597 // consists of a single expression of type cv U, where U is a
8598 // specialization of C or a class derived from a specialization of C.
8599 Expr *E = ListInit->getInit(0);
8600 auto *RD = E->getType()->getAsCXXRecordDecl();
8601 if (!isa<InitListExpr>(E) && RD &&
8602 isOrIsDerivedFromSpecializationOf(RD, Template))
8603 TryListConstructors = false;
8606 if (TryListConstructors)
8607 Result = tryToResolveOverload(/*OnlyListConstructor*/true);
8608 // Then unwrap the initializer list and try again considering all
8610 Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
8613 // If list-initialization fails, or if we're doing any other kind of
8614 // initialization, we (eventually) consider constructors.
8615 if (Result == OR_No_Viable_Function)
8616 Result = tryToResolveOverload(/*OnlyListConstructor*/false);
8620 Diag(Kind.getLocation(), diag::err_deduced_class_template_ctor_ambiguous)
8622 // FIXME: For list-initialization candidates, it'd usually be better to
8623 // list why they were not viable when given the initializer list itself as
8625 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Inits);
8628 case OR_No_Viable_Function: {
8629 CXXRecordDecl *Primary =
8630 cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
8632 isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary));
8633 Diag(Kind.getLocation(),
8634 Complete ? diag::err_deduced_class_template_ctor_no_viable
8635 : diag::err_deduced_class_template_incomplete)
8636 << TemplateName << !Guides.empty();
8637 Candidates.NoteCandidates(*this, OCD_AllCandidates, Inits);
8642 Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
8644 NoteDeletedFunction(Best->Function);
8649 // C++ [over.match.list]p1:
8650 // In copy-list-initialization, if an explicit constructor is chosen, the
8651 // initialization is ill-formed.
8652 if (Kind.isCopyInit() && ListInit &&
8653 cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
8654 bool IsDeductionGuide = !Best->Function->isImplicit();
8655 Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
8656 << TemplateName << IsDeductionGuide;
8657 Diag(Best->Function->getLocation(),
8658 diag::note_explicit_ctor_deduction_guide_here)
8659 << IsDeductionGuide;
8663 // Make sure we didn't select an unusable deduction guide, and mark it
8665 DiagnoseUseOfDecl(Best->Function, Kind.getLocation());
8666 MarkFunctionReferenced(Kind.getLocation(), Best->Function);
8670 // C++ [dcl.type.class.deduct]p1:
8671 // The placeholder is replaced by the return type of the function selected
8672 // by overload resolution for class template deduction.
8673 return SubstAutoType(TSInfo->getType(), Best->Function->getReturnType());