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 InitListExpr *OuterILE, unsigned OuterIndex,
356 bool FillWithNoInit = false);
357 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
358 Expr *InitExpr, FieldDecl *Field,
359 bool TopLevelObject);
360 void CheckEmptyInitializable(const InitializedEntity &Entity,
364 InitListChecker(Sema &S, const InitializedEntity &Entity,
365 InitListExpr *IL, QualType &T, bool VerifyOnly,
366 bool TreatUnavailableAsInvalid);
367 bool HadError() { return hadError; }
369 // @brief Retrieves the fully-structured initializer list used for
370 // semantic analysis and code generation.
371 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
374 } // end anonymous namespace
376 ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef,
378 const InitializedEntity &Entity,
380 bool TreatUnavailableAsInvalid) {
381 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
383 MultiExprArg SubInit;
385 InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
387 // C++ [dcl.init.aggr]p7:
388 // If there are fewer initializer-clauses in the list than there are
389 // members in the aggregate, then each member not explicitly initialized
391 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
392 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
395 // shall be initialized [...] from an empty initializer list.
397 // We apply the resolution of this DR to C++11 but not C++98, since C++98
398 // does not have useful semantics for initialization from an init list.
399 // We treat this as copy-initialization, because aggregate initialization
400 // always performs copy-initialization on its elements.
402 // Only do this if we're initializing a class type, to avoid filling in
403 // the initializer list where possible.
404 InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context)
405 InitListExpr(SemaRef.Context, Loc, None, Loc);
406 InitExpr->setType(SemaRef.Context.VoidTy);
408 Kind = InitializationKind::CreateCopy(Loc, Loc);
411 // shall be value-initialized.
414 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
415 // libstdc++4.6 marks the vector default constructor as explicit in
416 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
417 // stlport does so too. Look for std::__debug for libstdc++, and for
418 // std:: for stlport. This is effectively a compiler-side implementation of
420 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
421 InitializationSequence::FK_ExplicitConstructor) {
422 OverloadCandidateSet::iterator Best;
423 OverloadingResult O =
424 InitSeq.getFailedCandidateSet()
425 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
427 assert(O == OR_Success && "Inconsistent overload resolution");
428 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
429 CXXRecordDecl *R = CtorDecl->getParent();
431 if (CtorDecl->getMinRequiredArguments() == 0 &&
432 CtorDecl->isExplicit() && R->getDeclName() &&
433 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
434 bool IsInStd = false;
435 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
436 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
437 if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
441 if (IsInStd && llvm::StringSwitch<bool>(R->getName())
442 .Cases("basic_string", "deque", "forward_list", true)
443 .Cases("list", "map", "multimap", "multiset", true)
444 .Cases("priority_queue", "queue", "set", "stack", true)
445 .Cases("unordered_map", "unordered_set", "vector", true)
447 InitSeq.InitializeFrom(
449 InitializationKind::CreateValue(Loc, Loc, Loc, true),
450 MultiExprArg(), /*TopLevelOfInitList=*/false,
451 TreatUnavailableAsInvalid);
452 // Emit a warning for this. System header warnings aren't shown
453 // by default, but people working on system headers should see it.
455 SemaRef.Diag(CtorDecl->getLocation(),
456 diag::warn_invalid_initializer_from_system_header);
457 if (Entity.getKind() == InitializedEntity::EK_Member)
458 SemaRef.Diag(Entity.getDecl()->getLocation(),
459 diag::note_used_in_initialization_here);
460 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
461 SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
468 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
469 if (Entity.getKind() == InitializedEntity::EK_Member)
470 SemaRef.Diag(Entity.getDecl()->getLocation(),
471 diag::note_in_omitted_aggregate_initializer)
472 << /*field*/1 << Entity.getDecl();
473 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
474 bool IsTrailingArrayNewMember =
475 Entity.getParent() &&
476 Entity.getParent()->isVariableLengthArrayNew();
477 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
478 << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
479 << Entity.getElementIndex();
485 return VerifyOnly ? ExprResult(static_cast<Expr *>(nullptr))
486 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
489 void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
490 SourceLocation Loc) {
492 "CheckEmptyInitializable is only inteded for verification mode.");
493 if (PerformEmptyInit(SemaRef, Loc, Entity, /*VerifyOnly*/true,
494 TreatUnavailableAsInvalid).isInvalid())
498 void InitListChecker::FillInEmptyInitForBase(
499 unsigned Init, const CXXBaseSpecifier &Base,
500 const InitializedEntity &ParentEntity, InitListExpr *ILE,
501 bool &RequiresSecondPass, bool FillWithNoInit) {
502 assert(Init < ILE->getNumInits() && "should have been expanded");
504 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
505 SemaRef.Context, &Base, false, &ParentEntity);
507 if (!ILE->getInit(Init)) {
508 ExprResult BaseInit =
509 FillWithNoInit ? new (SemaRef.Context) NoInitExpr(Base.getType())
510 : PerformEmptyInit(SemaRef, ILE->getLocEnd(), BaseEntity,
511 /*VerifyOnly*/ false,
512 TreatUnavailableAsInvalid);
513 if (BaseInit.isInvalid()) {
518 ILE->setInit(Init, BaseInit.getAs<Expr>());
519 } else if (InitListExpr *InnerILE =
520 dyn_cast<InitListExpr>(ILE->getInit(Init))) {
521 FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,
522 ILE, Init, FillWithNoInit);
523 } else if (DesignatedInitUpdateExpr *InnerDIUE =
524 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
525 FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
526 RequiresSecondPass, ILE, Init,
527 /*FillWithNoInit =*/true);
531 void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
532 const InitializedEntity &ParentEntity,
534 bool &RequiresSecondPass,
535 bool FillWithNoInit) {
536 SourceLocation Loc = ILE->getLocEnd();
537 unsigned NumInits = ILE->getNumInits();
538 InitializedEntity MemberEntity
539 = InitializedEntity::InitializeMember(Field, &ParentEntity);
541 if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
542 if (!RType->getDecl()->isUnion())
543 assert(Init < NumInits && "This ILE should have been expanded");
545 if (Init >= NumInits || !ILE->getInit(Init)) {
546 if (FillWithNoInit) {
547 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
549 ILE->setInit(Init, Filler);
551 ILE->updateInit(SemaRef.Context, Init, Filler);
554 // C++1y [dcl.init.aggr]p7:
555 // If there are fewer initializer-clauses in the list than there are
556 // members in the aggregate, then each member not explicitly initialized
557 // shall be initialized from its brace-or-equal-initializer [...]
558 if (Field->hasInClassInitializer()) {
559 ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
560 if (DIE.isInvalid()) {
565 ILE->setInit(Init, DIE.get());
567 ILE->updateInit(SemaRef.Context, Init, DIE.get());
568 RequiresSecondPass = true;
573 if (Field->getType()->isReferenceType()) {
574 // C++ [dcl.init.aggr]p9:
575 // If an incomplete or empty initializer-list leaves a
576 // member of reference type uninitialized, the program is
578 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
580 << ILE->getSyntacticForm()->getSourceRange();
581 SemaRef.Diag(Field->getLocation(),
582 diag::note_uninit_reference_member);
587 ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
589 TreatUnavailableAsInvalid);
590 if (MemberInit.isInvalid()) {
597 } else if (Init < NumInits) {
598 ILE->setInit(Init, MemberInit.getAs<Expr>());
599 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
600 // Empty initialization requires a constructor call, so
601 // extend the initializer list to include the constructor
602 // call and make a note that we'll need to take another pass
603 // through the initializer list.
604 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
605 RequiresSecondPass = true;
607 } else if (InitListExpr *InnerILE
608 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
609 FillInEmptyInitializations(MemberEntity, InnerILE,
610 RequiresSecondPass, ILE, Init, FillWithNoInit);
611 else if (DesignatedInitUpdateExpr *InnerDIUE
612 = dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init)))
613 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
614 RequiresSecondPass, ILE, Init,
615 /*FillWithNoInit =*/true);
618 /// Recursively replaces NULL values within the given initializer list
619 /// with expressions that perform value-initialization of the
620 /// appropriate type, and finish off the InitListExpr formation.
622 InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
624 bool &RequiresSecondPass,
625 InitListExpr *OuterILE,
627 bool FillWithNoInit) {
628 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
629 "Should not have void type");
631 // If this is a nested initializer list, we might have changed its contents
632 // (and therefore some of its properties, such as instantiation-dependence)
633 // while filling it in. Inform the outer initializer list so that its state
634 // can be updated to match.
635 // FIXME: We should fully build the inner initializers before constructing
636 // the outer InitListExpr instead of mutating AST nodes after they have
637 // been used as subexpressions of other nodes.
638 struct UpdateOuterILEWithUpdatedInit {
641 ~UpdateOuterILEWithUpdatedInit() {
643 Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
645 } UpdateOuterRAII = {OuterILE, OuterIndex};
647 // A transparent ILE is not performing aggregate initialization and should
649 if (ILE->isTransparent())
652 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
653 const RecordDecl *RDecl = RType->getDecl();
654 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
655 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
656 Entity, ILE, RequiresSecondPass, FillWithNoInit);
657 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
658 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
659 for (auto *Field : RDecl->fields()) {
660 if (Field->hasInClassInitializer()) {
661 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
667 // The fields beyond ILE->getNumInits() are default initialized, so in
668 // order to leave them uninitialized, the ILE is expanded and the extra
669 // fields are then filled with NoInitExpr.
670 unsigned NumElems = numStructUnionElements(ILE->getType());
671 if (RDecl->hasFlexibleArrayMember())
673 if (ILE->getNumInits() < NumElems)
674 ILE->resizeInits(SemaRef.Context, NumElems);
678 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
679 for (auto &Base : CXXRD->bases()) {
683 FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
689 for (auto *Field : RDecl->fields()) {
690 if (Field->isUnnamedBitfield())
696 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
703 // Only look at the first initialization of a union.
704 if (RDecl->isUnion())
712 QualType ElementType;
714 InitializedEntity ElementEntity = Entity;
715 unsigned NumInits = ILE->getNumInits();
716 unsigned NumElements = NumInits;
717 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
718 ElementType = AType->getElementType();
719 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
720 NumElements = CAType->getSize().getZExtValue();
721 // For an array new with an unknown bound, ask for one additional element
722 // in order to populate the array filler.
723 if (Entity.isVariableLengthArrayNew())
725 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
727 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
728 ElementType = VType->getElementType();
729 NumElements = VType->getNumElements();
730 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
733 ElementType = ILE->getType();
735 for (unsigned Init = 0; Init != NumElements; ++Init) {
739 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
740 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
741 ElementEntity.setElementIndex(Init);
743 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
744 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
745 ILE->setInit(Init, ILE->getArrayFiller());
746 else if (!InitExpr && !ILE->hasArrayFiller()) {
747 Expr *Filler = nullptr;
750 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
752 ExprResult ElementInit = PerformEmptyInit(SemaRef, ILE->getLocEnd(),
755 TreatUnavailableAsInvalid);
756 if (ElementInit.isInvalid()) {
761 Filler = ElementInit.getAs<Expr>();
766 } else if (Init < NumInits) {
767 // For arrays, just set the expression used for value-initialization
768 // of the "holes" in the array.
769 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
770 ILE->setArrayFiller(Filler);
772 ILE->setInit(Init, Filler);
774 // For arrays, just set the expression used for value-initialization
775 // of the rest of elements and exit.
776 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
777 ILE->setArrayFiller(Filler);
781 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
782 // Empty initialization requires a constructor call, so
783 // extend the initializer list to include the constructor
784 // call and make a note that we'll need to take another pass
785 // through the initializer list.
786 ILE->updateInit(SemaRef.Context, Init, Filler);
787 RequiresSecondPass = true;
790 } else if (InitListExpr *InnerILE
791 = dyn_cast_or_null<InitListExpr>(InitExpr))
792 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
793 ILE, Init, FillWithNoInit);
794 else if (DesignatedInitUpdateExpr *InnerDIUE
795 = dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr))
796 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
797 RequiresSecondPass, ILE, Init,
798 /*FillWithNoInit =*/true);
802 InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
803 InitListExpr *IL, QualType &T,
805 bool TreatUnavailableAsInvalid)
806 : SemaRef(S), VerifyOnly(VerifyOnly),
807 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid) {
808 // FIXME: Check that IL isn't already the semantic form of some other
809 // InitListExpr. If it is, we'd create a broken AST.
813 FullyStructuredList =
814 getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
815 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
816 /*TopLevelObject=*/true);
818 if (!hadError && !VerifyOnly) {
819 bool RequiresSecondPass = false;
820 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
821 /*OuterILE=*/nullptr, /*OuterIndex=*/0);
822 if (RequiresSecondPass && !hadError)
823 FillInEmptyInitializations(Entity, FullyStructuredList,
824 RequiresSecondPass, nullptr, 0);
828 int InitListChecker::numArrayElements(QualType DeclType) {
829 // FIXME: use a proper constant
830 int maxElements = 0x7FFFFFFF;
831 if (const ConstantArrayType *CAT =
832 SemaRef.Context.getAsConstantArrayType(DeclType)) {
833 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
838 int InitListChecker::numStructUnionElements(QualType DeclType) {
839 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
840 int InitializableMembers = 0;
841 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
842 InitializableMembers += CXXRD->getNumBases();
843 for (const auto *Field : structDecl->fields())
844 if (!Field->isUnnamedBitfield())
845 ++InitializableMembers;
847 if (structDecl->isUnion())
848 return std::min(InitializableMembers, 1);
849 return InitializableMembers - structDecl->hasFlexibleArrayMember();
852 /// Determine whether Entity is an entity for which it is idiomatic to elide
853 /// the braces in aggregate initialization.
854 static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) {
855 // Recursive initialization of the one and only field within an aggregate
856 // class is considered idiomatic. This case arises in particular for
857 // initialization of std::array, where the C++ standard suggests the idiom of
859 // std::array<T, N> arr = {1, 2, 3};
861 // (where std::array is an aggregate struct containing a single array field.
863 // FIXME: Should aggregate initialization of a struct with a single
864 // base class and no members also suppress the warning?
865 if (Entity.getKind() != InitializedEntity::EK_Member || !Entity.getParent())
869 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
870 if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD))
871 if (CXXRD->getNumBases())
874 auto FieldIt = ParentRD->field_begin();
875 assert(FieldIt != ParentRD->field_end() &&
876 "no fields but have initializer for member?");
877 return ++FieldIt == ParentRD->field_end();
880 /// Check whether the range of the initializer \p ParentIList from element
881 /// \p Index onwards can be used to initialize an object of type \p T. Update
882 /// \p Index to indicate how many elements of the list were consumed.
884 /// This also fills in \p StructuredList, from element \p StructuredIndex
885 /// onwards, with the fully-braced, desugared form of the initialization.
886 void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
887 InitListExpr *ParentIList,
888 QualType T, unsigned &Index,
889 InitListExpr *StructuredList,
890 unsigned &StructuredIndex) {
893 if (T->isArrayType())
894 maxElements = numArrayElements(T);
895 else if (T->isRecordType())
896 maxElements = numStructUnionElements(T);
897 else if (T->isVectorType())
898 maxElements = T->getAs<VectorType>()->getNumElements();
900 llvm_unreachable("CheckImplicitInitList(): Illegal type");
902 if (maxElements == 0) {
904 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
905 diag::err_implicit_empty_initializer);
911 // Build a structured initializer list corresponding to this subobject.
912 InitListExpr *StructuredSubobjectInitList
913 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
915 SourceRange(ParentIList->getInit(Index)->getLocStart(),
916 ParentIList->getSourceRange().getEnd()));
917 unsigned StructuredSubobjectInitIndex = 0;
919 // Check the element types and build the structural subobject.
920 unsigned StartIndex = Index;
921 CheckListElementTypes(Entity, ParentIList, T,
922 /*SubobjectIsDesignatorContext=*/false, Index,
923 StructuredSubobjectInitList,
924 StructuredSubobjectInitIndex);
927 StructuredSubobjectInitList->setType(T);
929 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
930 // Update the structured sub-object initializer so that it's ending
931 // range corresponds with the end of the last initializer it used.
932 if (EndIndex < ParentIList->getNumInits() &&
933 ParentIList->getInit(EndIndex)) {
934 SourceLocation EndLoc
935 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
936 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
939 // Complain about missing braces.
940 if ((T->isArrayType() || T->isRecordType()) &&
941 !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
942 !isIdiomaticBraceElisionEntity(Entity)) {
943 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
944 diag::warn_missing_braces)
945 << StructuredSubobjectInitList->getSourceRange()
946 << FixItHint::CreateInsertion(
947 StructuredSubobjectInitList->getLocStart(), "{")
948 << FixItHint::CreateInsertion(
949 SemaRef.getLocForEndOfToken(
950 StructuredSubobjectInitList->getLocEnd()),
956 /// Warn that \p Entity was of scalar type and was initialized by a
957 /// single-element braced initializer list.
958 static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
959 SourceRange Braces) {
960 // Don't warn during template instantiation. If the initialization was
961 // non-dependent, we warned during the initial parse; otherwise, the
962 // type might not be scalar in some uses of the template.
963 if (S.inTemplateInstantiation())
968 switch (Entity.getKind()) {
969 case InitializedEntity::EK_VectorElement:
970 case InitializedEntity::EK_ComplexElement:
971 case InitializedEntity::EK_ArrayElement:
972 case InitializedEntity::EK_Parameter:
973 case InitializedEntity::EK_Parameter_CF_Audited:
974 case InitializedEntity::EK_Result:
975 // Extra braces here are suspicious.
976 DiagID = diag::warn_braces_around_scalar_init;
979 case InitializedEntity::EK_Member:
980 // Warn on aggregate initialization but not on ctor init list or
981 // default member initializer.
982 if (Entity.getParent())
983 DiagID = diag::warn_braces_around_scalar_init;
986 case InitializedEntity::EK_Variable:
987 case InitializedEntity::EK_LambdaCapture:
988 // No warning, might be direct-list-initialization.
989 // FIXME: Should we warn for copy-list-initialization in these cases?
992 case InitializedEntity::EK_New:
993 case InitializedEntity::EK_Temporary:
994 case InitializedEntity::EK_CompoundLiteralInit:
995 // No warning, braces are part of the syntax of the underlying construct.
998 case InitializedEntity::EK_RelatedResult:
999 // No warning, we already warned when initializing the result.
1002 case InitializedEntity::EK_Exception:
1003 case InitializedEntity::EK_Base:
1004 case InitializedEntity::EK_Delegating:
1005 case InitializedEntity::EK_BlockElement:
1006 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
1007 case InitializedEntity::EK_Binding:
1008 llvm_unreachable("unexpected braced scalar init");
1012 S.Diag(Braces.getBegin(), DiagID)
1014 << FixItHint::CreateRemoval(Braces.getBegin())
1015 << FixItHint::CreateRemoval(Braces.getEnd());
1019 /// Check whether the initializer \p IList (that was written with explicit
1020 /// braces) can be used to initialize an object of type \p T.
1022 /// This also fills in \p StructuredList with the fully-braced, desugared
1023 /// form of the initialization.
1024 void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
1025 InitListExpr *IList, QualType &T,
1026 InitListExpr *StructuredList,
1027 bool TopLevelObject) {
1029 SyntacticToSemantic[IList] = StructuredList;
1030 StructuredList->setSyntacticForm(IList);
1033 unsigned Index = 0, StructuredIndex = 0;
1034 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
1035 Index, StructuredList, StructuredIndex, TopLevelObject);
1037 QualType ExprTy = T;
1038 if (!ExprTy->isArrayType())
1039 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
1040 IList->setType(ExprTy);
1041 StructuredList->setType(ExprTy);
1046 if (Index < IList->getNumInits()) {
1047 // We have leftover initializers
1049 if (SemaRef.getLangOpts().CPlusPlus ||
1050 (SemaRef.getLangOpts().OpenCL &&
1051 IList->getType()->isVectorType())) {
1057 if (StructuredIndex == 1 &&
1058 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1060 unsigned DK = diag::ext_excess_initializers_in_char_array_initializer;
1061 if (SemaRef.getLangOpts().CPlusPlus) {
1062 DK = diag::err_excess_initializers_in_char_array_initializer;
1066 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
1067 << IList->getInit(Index)->getSourceRange();
1068 } else if (!T->isIncompleteType()) {
1069 // Don't complain for incomplete types, since we'll get an error
1071 QualType CurrentObjectType = StructuredList->getType();
1073 CurrentObjectType->isArrayType()? 0 :
1074 CurrentObjectType->isVectorType()? 1 :
1075 CurrentObjectType->isScalarType()? 2 :
1076 CurrentObjectType->isUnionType()? 3 :
1079 unsigned DK = diag::ext_excess_initializers;
1080 if (SemaRef.getLangOpts().CPlusPlus) {
1081 DK = diag::err_excess_initializers;
1084 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
1085 DK = diag::err_excess_initializers;
1089 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
1090 << initKind << IList->getInit(Index)->getSourceRange();
1094 if (!VerifyOnly && T->isScalarType() &&
1095 IList->getNumInits() == 1 && !isa<InitListExpr>(IList->getInit(0)))
1096 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
1099 void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
1100 InitListExpr *IList,
1102 bool SubobjectIsDesignatorContext,
1104 InitListExpr *StructuredList,
1105 unsigned &StructuredIndex,
1106 bool TopLevelObject) {
1107 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1108 // Explicitly braced initializer for complex type can be real+imaginary
1110 CheckComplexType(Entity, IList, DeclType, Index,
1111 StructuredList, StructuredIndex);
1112 } else if (DeclType->isScalarType()) {
1113 CheckScalarType(Entity, IList, DeclType, Index,
1114 StructuredList, StructuredIndex);
1115 } else if (DeclType->isVectorType()) {
1116 CheckVectorType(Entity, IList, DeclType, Index,
1117 StructuredList, StructuredIndex);
1118 } else if (DeclType->isRecordType()) {
1119 assert(DeclType->isAggregateType() &&
1120 "non-aggregate records should be handed in CheckSubElementType");
1121 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1123 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
1124 CXXRecordDecl::base_class_iterator());
1125 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1126 Bases = CXXRD->bases();
1127 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1128 SubobjectIsDesignatorContext, Index, StructuredList,
1129 StructuredIndex, TopLevelObject);
1130 } else if (DeclType->isArrayType()) {
1132 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1134 CheckArrayType(Entity, IList, DeclType, Zero,
1135 SubobjectIsDesignatorContext, Index,
1136 StructuredList, StructuredIndex);
1137 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1138 // This type is invalid, issue a diagnostic.
1141 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
1144 } else if (DeclType->isReferenceType()) {
1145 CheckReferenceType(Entity, IList, DeclType, Index,
1146 StructuredList, StructuredIndex);
1147 } else if (DeclType->isObjCObjectType()) {
1149 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
1154 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
1160 void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
1161 InitListExpr *IList,
1164 InitListExpr *StructuredList,
1165 unsigned &StructuredIndex) {
1166 Expr *expr = IList->getInit(Index);
1168 if (ElemType->isReferenceType())
1169 return CheckReferenceType(Entity, IList, ElemType, Index,
1170 StructuredList, StructuredIndex);
1172 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
1173 if (SubInitList->getNumInits() == 1 &&
1174 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1176 expr = SubInitList->getInit(0);
1177 } else if (!SemaRef.getLangOpts().CPlusPlus) {
1178 InitListExpr *InnerStructuredList
1179 = getStructuredSubobjectInit(IList, Index, ElemType,
1180 StructuredList, StructuredIndex,
1181 SubInitList->getSourceRange(), true);
1182 CheckExplicitInitList(Entity, SubInitList, ElemType,
1183 InnerStructuredList);
1185 if (!hadError && !VerifyOnly) {
1186 bool RequiresSecondPass = false;
1187 FillInEmptyInitializations(Entity, InnerStructuredList,
1188 RequiresSecondPass, StructuredList,
1190 if (RequiresSecondPass && !hadError)
1191 FillInEmptyInitializations(Entity, InnerStructuredList,
1192 RequiresSecondPass, StructuredList,
1199 // C++ initialization is handled later.
1200 } else if (isa<ImplicitValueInitExpr>(expr)) {
1201 // This happens during template instantiation when we see an InitListExpr
1202 // that we've already checked once.
1203 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
1204 "found implicit initialization for the wrong type");
1206 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1211 if (SemaRef.getLangOpts().CPlusPlus) {
1212 // C++ [dcl.init.aggr]p2:
1213 // Each member is copy-initialized from the corresponding
1214 // initializer-clause.
1216 // FIXME: Better EqualLoc?
1217 InitializationKind Kind =
1218 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
1219 InitializationSequence Seq(SemaRef, Entity, Kind, expr,
1220 /*TopLevelOfInitList*/ true);
1222 // C++14 [dcl.init.aggr]p13:
1223 // If the assignment-expression can initialize a member, the member is
1224 // initialized. Otherwise [...] brace elision is assumed
1226 // Brace elision is never performed if the element is not an
1227 // assignment-expression.
1228 if (Seq || isa<InitListExpr>(expr)) {
1231 Seq.Perform(SemaRef, Entity, Kind, expr);
1232 if (Result.isInvalid())
1235 UpdateStructuredListElement(StructuredList, StructuredIndex,
1236 Result.getAs<Expr>());
1243 // Fall through for subaggregate initialization
1244 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1245 // FIXME: Need to handle atomic aggregate types with implicit init lists.
1246 return CheckScalarType(Entity, IList, ElemType, Index,
1247 StructuredList, StructuredIndex);
1248 } else if (const ArrayType *arrayType =
1249 SemaRef.Context.getAsArrayType(ElemType)) {
1250 // arrayType can be incomplete if we're initializing a flexible
1251 // array member. There's nothing we can do with the completed
1252 // type here, though.
1254 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
1256 CheckStringInit(expr, ElemType, arrayType, SemaRef);
1257 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1263 // Fall through for subaggregate initialization.
1266 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
1267 ElemType->isOpenCLSpecificType()) && "Unexpected type");
1271 // The initializer for a structure or union object that has
1272 // automatic storage duration shall be either an initializer
1273 // list as described below, or a single expression that has
1274 // compatible structure or union type. In the latter case, the
1275 // initial value of the object, including unnamed members, is
1276 // that of the expression.
1277 ExprResult ExprRes = expr;
1278 if (SemaRef.CheckSingleAssignmentConstraints(
1279 ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
1280 if (ExprRes.isInvalid())
1283 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
1284 if (ExprRes.isInvalid())
1287 UpdateStructuredListElement(StructuredList, StructuredIndex,
1288 ExprRes.getAs<Expr>());
1293 // Fall through for subaggregate initialization
1296 // C++ [dcl.init.aggr]p12:
1298 // [...] Otherwise, if the member is itself a non-empty
1299 // subaggregate, brace elision is assumed and the initializer is
1300 // considered for the initialization of the first member of
1301 // the subaggregate.
1302 // OpenCL vector initializer is handled elsewhere.
1303 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1304 ElemType->isAggregateType()) {
1305 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1310 // We cannot initialize this element, so let
1311 // PerformCopyInitialization produce the appropriate diagnostic.
1312 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
1313 /*TopLevelOfInitList=*/true);
1321 void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1322 InitListExpr *IList, QualType DeclType,
1324 InitListExpr *StructuredList,
1325 unsigned &StructuredIndex) {
1326 assert(Index == 0 && "Index in explicit init list must be zero");
1328 // As an extension, clang supports complex initializers, which initialize
1329 // a complex number component-wise. When an explicit initializer list for
1330 // a complex number contains two two initializers, this extension kicks in:
1331 // it exepcts the initializer list to contain two elements convertible to
1332 // the element type of the complex type. The first element initializes
1333 // the real part, and the second element intitializes the imaginary part.
1335 if (IList->getNumInits() != 2)
1336 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1339 // This is an extension in C. (The builtin _Complex type does not exist
1340 // in the C++ standard.)
1341 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
1342 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
1343 << IList->getSourceRange();
1345 // Initialize the complex number.
1346 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
1347 InitializedEntity ElementEntity =
1348 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1350 for (unsigned i = 0; i < 2; ++i) {
1351 ElementEntity.setElementIndex(Index);
1352 CheckSubElementType(ElementEntity, IList, elementType, Index,
1353 StructuredList, StructuredIndex);
1357 void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
1358 InitListExpr *IList, QualType DeclType,
1360 InitListExpr *StructuredList,
1361 unsigned &StructuredIndex) {
1362 if (Index >= IList->getNumInits()) {
1364 SemaRef.Diag(IList->getLocStart(),
1365 SemaRef.getLangOpts().CPlusPlus11 ?
1366 diag::warn_cxx98_compat_empty_scalar_initializer :
1367 diag::err_empty_scalar_initializer)
1368 << IList->getSourceRange();
1369 hadError = !SemaRef.getLangOpts().CPlusPlus11;
1375 Expr *expr = IList->getInit(Index);
1376 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
1377 // FIXME: This is invalid, and accepting it causes overload resolution
1378 // to pick the wrong overload in some corner cases.
1380 SemaRef.Diag(SubIList->getLocStart(),
1381 diag::ext_many_braces_around_scalar_init)
1382 << SubIList->getSourceRange();
1384 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1387 } else if (isa<DesignatedInitExpr>(expr)) {
1389 SemaRef.Diag(expr->getLocStart(),
1390 diag::err_designator_for_scalar_init)
1391 << DeclType << expr->getSourceRange();
1399 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
1406 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1407 /*TopLevelOfInitList=*/true);
1409 Expr *ResultExpr = nullptr;
1411 if (Result.isInvalid())
1412 hadError = true; // types weren't compatible.
1414 ResultExpr = Result.getAs<Expr>();
1416 if (ResultExpr != expr) {
1417 // The type was promoted, update initializer list.
1418 IList->setInit(Index, ResultExpr);
1424 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1428 void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1429 InitListExpr *IList, QualType DeclType,
1431 InitListExpr *StructuredList,
1432 unsigned &StructuredIndex) {
1433 if (Index >= IList->getNumInits()) {
1434 // FIXME: It would be wonderful if we could point at the actual member. In
1435 // general, it would be useful to pass location information down the stack,
1436 // so that we know the location (or decl) of the "current object" being
1439 SemaRef.Diag(IList->getLocStart(),
1440 diag::err_init_reference_member_uninitialized)
1442 << IList->getSourceRange();
1449 Expr *expr = IList->getInit(Index);
1450 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1452 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1453 << DeclType << IList->getSourceRange();
1461 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
1468 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(), expr,
1469 /*TopLevelOfInitList=*/true);
1471 if (Result.isInvalid())
1474 expr = Result.getAs<Expr>();
1475 IList->setInit(Index, expr);
1480 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1484 void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1485 InitListExpr *IList, QualType DeclType,
1487 InitListExpr *StructuredList,
1488 unsigned &StructuredIndex) {
1489 const VectorType *VT = DeclType->getAs<VectorType>();
1490 unsigned maxElements = VT->getNumElements();
1491 unsigned numEltsInit = 0;
1492 QualType elementType = VT->getElementType();
1494 if (Index >= IList->getNumInits()) {
1495 // Make sure the element type can be value-initialized.
1497 CheckEmptyInitializable(
1498 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1499 IList->getLocEnd());
1503 if (!SemaRef.getLangOpts().OpenCL) {
1504 // If the initializing element is a vector, try to copy-initialize
1505 // instead of breaking it apart (which is doomed to failure anyway).
1506 Expr *Init = IList->getInit(Index);
1507 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1509 if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
1516 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(), Init,
1517 /*TopLevelOfInitList=*/true);
1519 Expr *ResultExpr = nullptr;
1520 if (Result.isInvalid())
1521 hadError = true; // types weren't compatible.
1523 ResultExpr = Result.getAs<Expr>();
1525 if (ResultExpr != Init) {
1526 // The type was promoted, update initializer list.
1527 IList->setInit(Index, ResultExpr);
1533 UpdateStructuredListElement(StructuredList, StructuredIndex,
1539 InitializedEntity ElementEntity =
1540 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1542 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1543 // Don't attempt to go past the end of the init list
1544 if (Index >= IList->getNumInits()) {
1546 CheckEmptyInitializable(ElementEntity, IList->getLocEnd());
1550 ElementEntity.setElementIndex(Index);
1551 CheckSubElementType(ElementEntity, IList, elementType, Index,
1552 StructuredList, StructuredIndex);
1558 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1559 const VectorType *T = Entity.getType()->getAs<VectorType>();
1560 if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1561 T->getVectorKind() == VectorType::NeonPolyVector)) {
1562 // The ability to use vector initializer lists is a GNU vector extension
1563 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1564 // endian machines it works fine, however on big endian machines it
1565 // exhibits surprising behaviour:
1567 // uint32x2_t x = {42, 64};
1568 // return vget_lane_u32(x, 0); // Will return 64.
1570 // Because of this, explicitly call out that it is non-portable.
1572 SemaRef.Diag(IList->getLocStart(),
1573 diag::warn_neon_vector_initializer_non_portable);
1575 const char *typeCode;
1576 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1578 if (elementType->isFloatingType())
1580 else if (elementType->isSignedIntegerType())
1582 else if (elementType->isUnsignedIntegerType())
1585 llvm_unreachable("Invalid element type!");
1587 SemaRef.Diag(IList->getLocStart(),
1588 SemaRef.Context.getTypeSize(VT) > 64 ?
1589 diag::note_neon_vector_initializer_non_portable_q :
1590 diag::note_neon_vector_initializer_non_portable)
1591 << typeCode << typeSize;
1597 InitializedEntity ElementEntity =
1598 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1600 // OpenCL initializers allows vectors to be constructed from vectors.
1601 for (unsigned i = 0; i < maxElements; ++i) {
1602 // Don't attempt to go past the end of the init list
1603 if (Index >= IList->getNumInits())
1606 ElementEntity.setElementIndex(Index);
1608 QualType IType = IList->getInit(Index)->getType();
1609 if (!IType->isVectorType()) {
1610 CheckSubElementType(ElementEntity, IList, elementType, Index,
1611 StructuredList, StructuredIndex);
1615 const VectorType *IVT = IType->getAs<VectorType>();
1616 unsigned numIElts = IVT->getNumElements();
1618 if (IType->isExtVectorType())
1619 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1621 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
1622 IVT->getVectorKind());
1623 CheckSubElementType(ElementEntity, IList, VecType, Index,
1624 StructuredList, StructuredIndex);
1625 numEltsInit += numIElts;
1629 // OpenCL requires all elements to be initialized.
1630 if (numEltsInit != maxElements) {
1632 SemaRef.Diag(IList->getLocStart(),
1633 diag::err_vector_incorrect_num_initializers)
1634 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1639 void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
1640 InitListExpr *IList, QualType &DeclType,
1641 llvm::APSInt elementIndex,
1642 bool SubobjectIsDesignatorContext,
1644 InitListExpr *StructuredList,
1645 unsigned &StructuredIndex) {
1646 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1648 // Check for the special-case of initializing an array with a string.
1649 if (Index < IList->getNumInits()) {
1650 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1652 // We place the string literal directly into the resulting
1653 // initializer list. This is the only place where the structure
1654 // of the structured initializer list doesn't match exactly,
1655 // because doing so would involve allocating one character
1656 // constant for each string.
1658 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1659 UpdateStructuredListElement(StructuredList, StructuredIndex,
1660 IList->getInit(Index));
1661 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1667 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
1668 // Check for VLAs; in standard C it would be possible to check this
1669 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1670 // them in all sorts of strange places).
1672 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1673 diag::err_variable_object_no_init)
1674 << VAT->getSizeExpr()->getSourceRange();
1681 // We might know the maximum number of elements in advance.
1682 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1683 elementIndex.isUnsigned());
1684 bool maxElementsKnown = false;
1685 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
1686 maxElements = CAT->getSize();
1687 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
1688 elementIndex.setIsUnsigned(maxElements.isUnsigned());
1689 maxElementsKnown = true;
1692 QualType elementType = arrayType->getElementType();
1693 while (Index < IList->getNumInits()) {
1694 Expr *Init = IList->getInit(Index);
1695 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1696 // If we're not the subobject that matches up with the '{' for
1697 // the designator, we shouldn't be handling the
1698 // designator. Return immediately.
1699 if (!SubobjectIsDesignatorContext)
1702 // Handle this designated initializer. elementIndex will be
1703 // updated to be the next array element we'll initialize.
1704 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1705 DeclType, nullptr, &elementIndex, Index,
1706 StructuredList, StructuredIndex, true,
1712 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1713 maxElements = maxElements.extend(elementIndex.getBitWidth());
1714 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1715 elementIndex = elementIndex.extend(maxElements.getBitWidth());
1716 elementIndex.setIsUnsigned(maxElements.isUnsigned());
1718 // If the array is of incomplete type, keep track of the number of
1719 // elements in the initializer.
1720 if (!maxElementsKnown && elementIndex > maxElements)
1721 maxElements = elementIndex;
1726 // If we know the maximum number of elements, and we've already
1727 // hit it, stop consuming elements in the initializer list.
1728 if (maxElementsKnown && elementIndex == maxElements)
1731 InitializedEntity ElementEntity =
1732 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
1734 // Check this element.
1735 CheckSubElementType(ElementEntity, IList, elementType, Index,
1736 StructuredList, StructuredIndex);
1739 // If the array is of incomplete type, keep track of the number of
1740 // elements in the initializer.
1741 if (!maxElementsKnown && elementIndex > maxElements)
1742 maxElements = elementIndex;
1744 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
1745 // If this is an incomplete array type, the actual type needs to
1746 // be calculated here.
1747 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
1748 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
1749 // Sizing an array implicitly to zero is not allowed by ISO C,
1750 // but is supported by GNU.
1751 SemaRef.Diag(IList->getLocStart(),
1752 diag::ext_typecheck_zero_array_size);
1755 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
1756 ArrayType::Normal, 0);
1758 if (!hadError && VerifyOnly) {
1759 // If there are any members of the array that get value-initialized, check
1760 // that is possible. That happens if we know the bound and don't have
1761 // enough elements, or if we're performing an array new with an unknown
1763 // FIXME: This needs to detect holes left by designated initializers too.
1764 if ((maxElementsKnown && elementIndex < maxElements) ||
1765 Entity.isVariableLengthArrayNew())
1766 CheckEmptyInitializable(InitializedEntity::InitializeElement(
1767 SemaRef.Context, 0, Entity),
1768 IList->getLocEnd());
1772 bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1775 bool TopLevelObject) {
1776 // Handle GNU flexible array initializers.
1777 unsigned FlexArrayDiag;
1778 if (isa<InitListExpr>(InitExpr) &&
1779 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1780 // Empty flexible array init always allowed as an extension
1781 FlexArrayDiag = diag::ext_flexible_array_init;
1782 } else if (SemaRef.getLangOpts().CPlusPlus) {
1783 // Disallow flexible array init in C++; it is not required for gcc
1784 // compatibility, and it needs work to IRGen correctly in general.
1785 FlexArrayDiag = diag::err_flexible_array_init;
1786 } else if (!TopLevelObject) {
1787 // Disallow flexible array init on non-top-level object
1788 FlexArrayDiag = diag::err_flexible_array_init;
1789 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1790 // Disallow flexible array init on anything which is not a variable.
1791 FlexArrayDiag = diag::err_flexible_array_init;
1792 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1793 // Disallow flexible array init on local variables.
1794 FlexArrayDiag = diag::err_flexible_array_init;
1796 // Allow other cases.
1797 FlexArrayDiag = diag::ext_flexible_array_init;
1801 SemaRef.Diag(InitExpr->getLocStart(),
1803 << InitExpr->getLocStart();
1804 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1808 return FlexArrayDiag != diag::ext_flexible_array_init;
1811 void InitListChecker::CheckStructUnionTypes(
1812 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
1813 CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field,
1814 bool SubobjectIsDesignatorContext, unsigned &Index,
1815 InitListExpr *StructuredList, unsigned &StructuredIndex,
1816 bool TopLevelObject) {
1817 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
1819 // If the record is invalid, some of it's members are invalid. To avoid
1820 // confusion, we forgo checking the intializer for the entire record.
1821 if (structDecl->isInvalidDecl()) {
1822 // Assume it was supposed to consume a single initializer.
1828 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1829 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1831 // If there's a default initializer, use it.
1832 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1835 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1836 Field != FieldEnd; ++Field) {
1837 if (Field->hasInClassInitializer()) {
1838 StructuredList->setInitializedFieldInUnion(*Field);
1839 // FIXME: Actually build a CXXDefaultInitExpr?
1845 // Value-initialize the first member of the union that isn't an unnamed
1847 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1848 Field != FieldEnd; ++Field) {
1849 if (!Field->isUnnamedBitfield()) {
1851 CheckEmptyInitializable(
1852 InitializedEntity::InitializeMember(*Field, &Entity),
1853 IList->getLocEnd());
1855 StructuredList->setInitializedFieldInUnion(*Field);
1862 bool InitializedSomething = false;
1864 // If we have any base classes, they are initialized prior to the fields.
1865 for (auto &Base : Bases) {
1866 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
1867 SourceLocation InitLoc = Init ? Init->getLocStart() : IList->getLocEnd();
1869 // Designated inits always initialize fields, so if we see one, all
1870 // remaining base classes have no explicit initializer.
1871 if (Init && isa<DesignatedInitExpr>(Init))
1874 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
1875 SemaRef.Context, &Base, false, &Entity);
1877 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
1878 StructuredList, StructuredIndex);
1879 InitializedSomething = true;
1880 } else if (VerifyOnly) {
1881 CheckEmptyInitializable(BaseEntity, InitLoc);
1885 // If structDecl is a forward declaration, this loop won't do
1886 // anything except look at designated initializers; That's okay,
1887 // because an error should get printed out elsewhere. It might be
1888 // worthwhile to skip over the rest of the initializer, though.
1889 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1890 RecordDecl::field_iterator FieldEnd = RD->field_end();
1891 bool CheckForMissingFields =
1892 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
1894 while (Index < IList->getNumInits()) {
1895 Expr *Init = IList->getInit(Index);
1897 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1898 // If we're not the subobject that matches up with the '{' for
1899 // the designator, we shouldn't be handling the
1900 // designator. Return immediately.
1901 if (!SubobjectIsDesignatorContext)
1904 // Handle this designated initializer. Field will be updated to
1905 // the next field that we'll be initializing.
1906 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1907 DeclType, &Field, nullptr, Index,
1908 StructuredList, StructuredIndex,
1909 true, TopLevelObject))
1912 InitializedSomething = true;
1914 // Disable check for missing fields when designators are used.
1915 // This matches gcc behaviour.
1916 CheckForMissingFields = false;
1920 if (Field == FieldEnd) {
1921 // We've run out of fields. We're done.
1925 // We've already initialized a member of a union. We're done.
1926 if (InitializedSomething && DeclType->isUnionType())
1929 // If we've hit the flexible array member at the end, we're done.
1930 if (Field->getType()->isIncompleteArrayType())
1933 if (Field->isUnnamedBitfield()) {
1934 // Don't initialize unnamed bitfields, e.g. "int : 20;"
1939 // Make sure we can use this declaration.
1942 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
1944 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1945 IList->getInit(Index)->getLocStart());
1953 InitializedEntity MemberEntity =
1954 InitializedEntity::InitializeMember(*Field, &Entity);
1955 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1956 StructuredList, StructuredIndex);
1957 InitializedSomething = true;
1959 if (DeclType->isUnionType() && !VerifyOnly) {
1960 // Initialize the first field within the union.
1961 StructuredList->setInitializedFieldInUnion(*Field);
1967 // Emit warnings for missing struct field initializers.
1968 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1969 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1970 !DeclType->isUnionType()) {
1971 // It is possible we have one or more unnamed bitfields remaining.
1972 // Find first (if any) named field and emit warning.
1973 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1975 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
1976 SemaRef.Diag(IList->getSourceRange().getEnd(),
1977 diag::warn_missing_field_initializers) << *it;
1983 // Check that any remaining fields can be value-initialized.
1984 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1985 !Field->getType()->isIncompleteArrayType()) {
1986 // FIXME: Should check for holes left by designated initializers too.
1987 for (; Field != FieldEnd && !hadError; ++Field) {
1988 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
1989 CheckEmptyInitializable(
1990 InitializedEntity::InitializeMember(*Field, &Entity),
1991 IList->getLocEnd());
1995 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
1996 Index >= IList->getNumInits())
1999 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
2006 InitializedEntity MemberEntity =
2007 InitializedEntity::InitializeMember(*Field, &Entity);
2009 if (isa<InitListExpr>(IList->getInit(Index)))
2010 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2011 StructuredList, StructuredIndex);
2013 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
2014 StructuredList, StructuredIndex);
2017 /// \brief Expand a field designator that refers to a member of an
2018 /// anonymous struct or union into a series of field designators that
2019 /// refers to the field within the appropriate subobject.
2021 static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
2022 DesignatedInitExpr *DIE,
2024 IndirectFieldDecl *IndirectField) {
2025 typedef DesignatedInitExpr::Designator Designator;
2027 // Build the replacement designators.
2028 SmallVector<Designator, 4> Replacements;
2029 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2030 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2032 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
2033 DIE->getDesignator(DesigIdx)->getDotLoc(),
2034 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2036 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
2037 SourceLocation(), SourceLocation()));
2038 assert(isa<FieldDecl>(*PI));
2039 Replacements.back().setField(cast<FieldDecl>(*PI));
2042 // Expand the current designator into the set of replacement
2043 // designators, so we have a full subobject path down to where the
2044 // member of the anonymous struct/union is actually stored.
2045 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
2046 &Replacements[0] + Replacements.size());
2049 static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
2050 DesignatedInitExpr *DIE) {
2051 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2052 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2053 for (unsigned I = 0; I < NumIndexExprs; ++I)
2054 IndexExprs[I] = DIE->getSubExpr(I + 1);
2055 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2057 DIE->getEqualOrColonLoc(),
2058 DIE->usesGNUSyntax(), DIE->getInit());
2063 // Callback to only accept typo corrections that are for field members of
2064 // the given struct or union.
2065 class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
2067 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
2070 bool ValidateCandidate(const TypoCorrection &candidate) override {
2071 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2072 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2079 } // end anonymous namespace
2081 /// @brief Check the well-formedness of a C99 designated initializer.
2083 /// Determines whether the designated initializer @p DIE, which
2084 /// resides at the given @p Index within the initializer list @p
2085 /// IList, is well-formed for a current object of type @p DeclType
2086 /// (C99 6.7.8). The actual subobject that this designator refers to
2087 /// within the current subobject is returned in either
2088 /// @p NextField or @p NextElementIndex (whichever is appropriate).
2090 /// @param IList The initializer list in which this designated
2091 /// initializer occurs.
2093 /// @param DIE The designated initializer expression.
2095 /// @param DesigIdx The index of the current designator.
2097 /// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2098 /// into which the designation in @p DIE should refer.
2100 /// @param NextField If non-NULL and the first designator in @p DIE is
2101 /// a field, this will be set to the field declaration corresponding
2102 /// to the field named by the designator.
2104 /// @param NextElementIndex If non-NULL and the first designator in @p
2105 /// DIE is an array designator or GNU array-range designator, this
2106 /// will be set to the last index initialized by this designator.
2108 /// @param Index Index into @p IList where the designated initializer
2111 /// @param StructuredList The initializer list expression that
2112 /// describes all of the subobject initializers in the order they'll
2113 /// actually be initialized.
2115 /// @returns true if there was an error, false otherwise.
2117 InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2118 InitListExpr *IList,
2119 DesignatedInitExpr *DIE,
2121 QualType &CurrentObjectType,
2122 RecordDecl::field_iterator *NextField,
2123 llvm::APSInt *NextElementIndex,
2125 InitListExpr *StructuredList,
2126 unsigned &StructuredIndex,
2127 bool FinishSubobjectInit,
2128 bool TopLevelObject) {
2129 if (DesigIdx == DIE->size()) {
2130 // Check the actual initialization for the designated object type.
2131 bool prevHadError = hadError;
2133 // Temporarily remove the designator expression from the
2134 // initializer list that the child calls see, so that we don't try
2135 // to re-process the designator.
2136 unsigned OldIndex = Index;
2137 IList->setInit(OldIndex, DIE->getInit());
2139 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
2140 StructuredList, StructuredIndex);
2142 // Restore the designated initializer expression in the syntactic
2143 // form of the initializer list.
2144 if (IList->getInit(OldIndex) != DIE->getInit())
2145 DIE->setInit(IList->getInit(OldIndex));
2146 IList->setInit(OldIndex, DIE);
2148 return hadError && !prevHadError;
2151 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
2152 bool IsFirstDesignator = (DesigIdx == 0);
2154 assert((IsFirstDesignator || StructuredList) &&
2155 "Need a non-designated initializer list to start from");
2157 // Determine the structural initializer list that corresponds to the
2158 // current subobject.
2159 if (IsFirstDesignator)
2160 StructuredList = SyntacticToSemantic.lookup(IList);
2162 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2163 StructuredList->getInit(StructuredIndex) : nullptr;
2164 if (!ExistingInit && StructuredList->hasArrayFiller())
2165 ExistingInit = StructuredList->getArrayFiller();
2169 getStructuredSubobjectInit(IList, Index, CurrentObjectType,
2170 StructuredList, StructuredIndex,
2171 SourceRange(D->getLocStart(),
2173 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2174 StructuredList = Result;
2176 if (DesignatedInitUpdateExpr *E =
2177 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2178 StructuredList = E->getUpdater();
2180 DesignatedInitUpdateExpr *DIUE =
2181 new (SemaRef.Context) DesignatedInitUpdateExpr(SemaRef.Context,
2182 D->getLocStart(), ExistingInit,
2184 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2185 StructuredList = DIUE->getUpdater();
2188 // We need to check on source range validity because the previous
2189 // initializer does not have to be an explicit initializer. e.g.,
2191 // struct P { int a, b; };
2192 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2194 // There is an overwrite taking place because the first braced initializer
2195 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
2196 if (ExistingInit->getSourceRange().isValid()) {
2197 // We are creating an initializer list that initializes the
2198 // subobjects of the current object, but there was already an
2199 // initialization that completely initialized the current
2200 // subobject, e.g., by a compound literal:
2202 // struct X { int a, b; };
2203 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2205 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2206 // designated initializer re-initializes the whole
2207 // subobject [0], overwriting previous initializers.
2208 SemaRef.Diag(D->getLocStart(),
2209 diag::warn_subobject_initializer_overrides)
2210 << SourceRange(D->getLocStart(), DIE->getLocEnd());
2212 SemaRef.Diag(ExistingInit->getLocStart(),
2213 diag::note_previous_initializer)
2214 << /*FIXME:has side effects=*/0
2215 << ExistingInit->getSourceRange();
2219 assert(StructuredList && "Expected a structured initializer list");
2222 if (D->isFieldDesignator()) {
2225 // If a designator has the form
2229 // then the current object (defined below) shall have
2230 // structure or union type and the identifier shall be the
2231 // name of a member of that type.
2232 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
2234 SourceLocation Loc = D->getDotLoc();
2235 if (Loc.isInvalid())
2236 Loc = D->getFieldLoc();
2238 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
2239 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2244 FieldDecl *KnownField = D->getField();
2246 IdentifierInfo *FieldName = D->getFieldName();
2247 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
2248 for (NamedDecl *ND : Lookup) {
2249 if (auto *FD = dyn_cast<FieldDecl>(ND)) {
2253 if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
2254 // In verify mode, don't modify the original.
2256 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2257 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
2258 D = DIE->getDesignator(DesigIdx);
2259 KnownField = cast<FieldDecl>(*IFD->chain_begin());
2266 return true; // No typo correction when just trying this out.
2269 // Name lookup found something, but it wasn't a field.
2270 if (!Lookup.empty()) {
2271 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2273 SemaRef.Diag(Lookup.front()->getLocation(),
2274 diag::note_field_designator_found);
2279 // Name lookup didn't find anything.
2280 // Determine whether this was a typo for another field name.
2281 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2282 DeclarationNameInfo(FieldName, D->getFieldLoc()),
2283 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr,
2284 llvm::make_unique<FieldInitializerValidatorCCC>(RT->getDecl()),
2285 Sema::CTK_ErrorRecovery, RT->getDecl())) {
2286 SemaRef.diagnoseTypo(
2288 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
2289 << FieldName << CurrentObjectType);
2290 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
2293 // Typo correction didn't find anything.
2294 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
2295 << FieldName << CurrentObjectType;
2302 unsigned FieldIndex = 0;
2304 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2305 FieldIndex = CXXRD->getNumBases();
2307 for (auto *FI : RT->getDecl()->fields()) {
2308 if (FI->isUnnamedBitfield())
2310 if (declaresSameEntity(KnownField, FI)) {
2317 RecordDecl::field_iterator Field =
2318 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
2320 // All of the fields of a union are located at the same place in
2321 // the initializer list.
2322 if (RT->getDecl()->isUnion()) {
2325 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
2326 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
2327 assert(StructuredList->getNumInits() == 1
2328 && "A union should never have more than one initializer!");
2330 Expr *ExistingInit = StructuredList->getInit(0);
2332 // We're about to throw away an initializer, emit warning.
2333 SemaRef.Diag(D->getFieldLoc(),
2334 diag::warn_initializer_overrides)
2335 << D->getSourceRange();
2336 SemaRef.Diag(ExistingInit->getLocStart(),
2337 diag::note_previous_initializer)
2338 << /*FIXME:has side effects=*/0
2339 << ExistingInit->getSourceRange();
2342 // remove existing initializer
2343 StructuredList->resizeInits(SemaRef.Context, 0);
2344 StructuredList->setInitializedFieldInUnion(nullptr);
2347 StructuredList->setInitializedFieldInUnion(*Field);
2351 // Make sure we can use this declaration.
2354 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2356 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
2363 // Update the designator with the field declaration.
2364 D->setField(*Field);
2366 // Make sure that our non-designated initializer list has space
2367 // for a subobject corresponding to this field.
2368 if (FieldIndex >= StructuredList->getNumInits())
2369 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2372 // This designator names a flexible array member.
2373 if (Field->getType()->isIncompleteArrayType()) {
2374 bool Invalid = false;
2375 if ((DesigIdx + 1) != DIE->size()) {
2376 // We can't designate an object within the flexible array
2377 // member (because GCC doesn't allow it).
2379 DesignatedInitExpr::Designator *NextD
2380 = DIE->getDesignator(DesigIdx + 1);
2381 SemaRef.Diag(NextD->getLocStart(),
2382 diag::err_designator_into_flexible_array_member)
2383 << SourceRange(NextD->getLocStart(),
2385 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2391 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2392 !isa<StringLiteral>(DIE->getInit())) {
2393 // The initializer is not an initializer list.
2395 SemaRef.Diag(DIE->getInit()->getLocStart(),
2396 diag::err_flexible_array_init_needs_braces)
2397 << DIE->getInit()->getSourceRange();
2398 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2404 // Check GNU flexible array initializer.
2405 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
2414 // Initialize the array.
2415 bool prevHadError = hadError;
2416 unsigned newStructuredIndex = FieldIndex;
2417 unsigned OldIndex = Index;
2418 IList->setInit(Index, DIE->getInit());
2420 InitializedEntity MemberEntity =
2421 InitializedEntity::InitializeMember(*Field, &Entity);
2422 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2423 StructuredList, newStructuredIndex);
2425 IList->setInit(OldIndex, DIE);
2426 if (hadError && !prevHadError) {
2431 StructuredIndex = FieldIndex;
2435 // Recurse to check later designated subobjects.
2436 QualType FieldType = Field->getType();
2437 unsigned newStructuredIndex = FieldIndex;
2439 InitializedEntity MemberEntity =
2440 InitializedEntity::InitializeMember(*Field, &Entity);
2441 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
2442 FieldType, nullptr, nullptr, Index,
2443 StructuredList, newStructuredIndex,
2444 FinishSubobjectInit, false))
2448 // Find the position of the next field to be initialized in this
2453 // If this the first designator, our caller will continue checking
2454 // the rest of this struct/class/union subobject.
2455 if (IsFirstDesignator) {
2458 StructuredIndex = FieldIndex;
2462 if (!FinishSubobjectInit)
2465 // We've already initialized something in the union; we're done.
2466 if (RT->getDecl()->isUnion())
2469 // Check the remaining fields within this class/struct/union subobject.
2470 bool prevHadError = hadError;
2473 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
2474 CXXRecordDecl::base_class_iterator());
2475 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
2476 false, Index, StructuredList, FieldIndex);
2477 return hadError && !prevHadError;
2482 // If a designator has the form
2484 // [ constant-expression ]
2486 // then the current object (defined below) shall have array
2487 // type and the expression shall be an integer constant
2488 // expression. If the array is of unknown size, any
2489 // nonnegative value is valid.
2491 // Additionally, cope with the GNU extension that permits
2492 // designators of the form
2494 // [ constant-expression ... constant-expression ]
2495 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
2498 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2499 << CurrentObjectType;
2504 Expr *IndexExpr = nullptr;
2505 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2506 if (D->isArrayDesignator()) {
2507 IndexExpr = DIE->getArrayIndex(*D);
2508 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
2509 DesignatedEndIndex = DesignatedStartIndex;
2511 assert(D->isArrayRangeDesignator() && "Need array-range designator");
2513 DesignatedStartIndex =
2514 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
2515 DesignatedEndIndex =
2516 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
2517 IndexExpr = DIE->getArrayRangeEnd(*D);
2519 // Codegen can't handle evaluating array range designators that have side
2520 // effects, because we replicate the AST value for each initialized element.
2521 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2522 // elements with something that has a side effect, so codegen can emit an
2523 // "error unsupported" error instead of miscompiling the app.
2524 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
2525 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
2526 FullyStructuredList->sawArrayRangeDesignator();
2529 if (isa<ConstantArrayType>(AT)) {
2530 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
2531 DesignatedStartIndex
2532 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
2533 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
2535 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
2536 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2537 if (DesignatedEndIndex >= MaxElements) {
2539 SemaRef.Diag(IndexExpr->getLocStart(),
2540 diag::err_array_designator_too_large)
2541 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2542 << IndexExpr->getSourceRange();
2547 unsigned DesignatedIndexBitWidth =
2548 ConstantArrayType::getMaxSizeBits(SemaRef.Context);
2549 DesignatedStartIndex =
2550 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
2551 DesignatedEndIndex =
2552 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
2553 DesignatedStartIndex.setIsUnsigned(true);
2554 DesignatedEndIndex.setIsUnsigned(true);
2557 if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2558 // We're modifying a string literal init; we have to decompose the string
2559 // so we can modify the individual characters.
2560 ASTContext &Context = SemaRef.Context;
2561 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2563 // Compute the character type
2564 QualType CharTy = AT->getElementType();
2566 // Compute the type of the integer literals.
2567 QualType PromotedCharTy = CharTy;
2568 if (CharTy->isPromotableIntegerType())
2569 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2570 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2572 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2573 // Get the length of the string.
2574 uint64_t StrLen = SL->getLength();
2575 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2576 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2577 StructuredList->resizeInits(Context, StrLen);
2579 // Build a literal for each character in the string, and put them into
2581 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2582 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2583 Expr *Init = new (Context) IntegerLiteral(
2584 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2585 if (CharTy != PromotedCharTy)
2586 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2587 Init, nullptr, VK_RValue);
2588 StructuredList->updateInit(Context, i, Init);
2591 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2593 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2595 // Get the length of the string.
2596 uint64_t StrLen = Str.size();
2597 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2598 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2599 StructuredList->resizeInits(Context, StrLen);
2601 // Build a literal for each character in the string, and put them into
2603 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2604 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2605 Expr *Init = new (Context) IntegerLiteral(
2606 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2607 if (CharTy != PromotedCharTy)
2608 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2609 Init, nullptr, VK_RValue);
2610 StructuredList->updateInit(Context, i, Init);
2615 // Make sure that our non-designated initializer list has space
2616 // for a subobject corresponding to this array element.
2618 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
2619 StructuredList->resizeInits(SemaRef.Context,
2620 DesignatedEndIndex.getZExtValue() + 1);
2622 // Repeatedly perform subobject initializations in the range
2623 // [DesignatedStartIndex, DesignatedEndIndex].
2625 // Move to the next designator
2626 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2627 unsigned OldIndex = Index;
2629 InitializedEntity ElementEntity =
2630 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
2632 while (DesignatedStartIndex <= DesignatedEndIndex) {
2633 // Recurse to check later designated subobjects.
2634 QualType ElementType = AT->getElementType();
2637 ElementEntity.setElementIndex(ElementIndex);
2638 if (CheckDesignatedInitializer(
2639 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
2640 nullptr, Index, StructuredList, ElementIndex,
2641 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
2645 // Move to the next index in the array that we'll be initializing.
2646 ++DesignatedStartIndex;
2647 ElementIndex = DesignatedStartIndex.getZExtValue();
2650 // If this the first designator, our caller will continue checking
2651 // the rest of this array subobject.
2652 if (IsFirstDesignator) {
2653 if (NextElementIndex)
2654 *NextElementIndex = DesignatedStartIndex;
2655 StructuredIndex = ElementIndex;
2659 if (!FinishSubobjectInit)
2662 // Check the remaining elements within this array subobject.
2663 bool prevHadError = hadError;
2664 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
2665 /*SubobjectIsDesignatorContext=*/false, Index,
2666 StructuredList, ElementIndex);
2667 return hadError && !prevHadError;
2670 // Get the structured initializer list for a subobject of type
2671 // @p CurrentObjectType.
2673 InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2674 QualType CurrentObjectType,
2675 InitListExpr *StructuredList,
2676 unsigned StructuredIndex,
2677 SourceRange InitRange,
2678 bool IsFullyOverwritten) {
2680 return nullptr; // No structured list in verification-only mode.
2681 Expr *ExistingInit = nullptr;
2682 if (!StructuredList)
2683 ExistingInit = SyntacticToSemantic.lookup(IList);
2684 else if (StructuredIndex < StructuredList->getNumInits())
2685 ExistingInit = StructuredList->getInit(StructuredIndex);
2687 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2688 // There might have already been initializers for subobjects of the current
2689 // object, but a subsequent initializer list will overwrite the entirety
2690 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
2692 // struct P { char x[6]; };
2693 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
2695 // The first designated initializer is ignored, and l.x is just "f".
2696 if (!IsFullyOverwritten)
2700 // We are creating an initializer list that initializes the
2701 // subobjects of the current object, but there was already an
2702 // initialization that completely initialized the current
2703 // subobject, e.g., by a compound literal:
2705 // struct X { int a, b; };
2706 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2708 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2709 // designated initializer re-initializes the whole
2710 // subobject [0], overwriting previous initializers.
2711 SemaRef.Diag(InitRange.getBegin(),
2712 diag::warn_subobject_initializer_overrides)
2714 SemaRef.Diag(ExistingInit->getLocStart(),
2715 diag::note_previous_initializer)
2716 << /*FIXME:has side effects=*/0
2717 << ExistingInit->getSourceRange();
2720 InitListExpr *Result
2721 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2722 InitRange.getBegin(), None,
2723 InitRange.getEnd());
2725 QualType ResultType = CurrentObjectType;
2726 if (!ResultType->isArrayType())
2727 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2728 Result->setType(ResultType);
2730 // Pre-allocate storage for the structured initializer list.
2731 unsigned NumElements = 0;
2732 unsigned NumInits = 0;
2733 bool GotNumInits = false;
2734 if (!StructuredList) {
2735 NumInits = IList->getNumInits();
2737 } else if (Index < IList->getNumInits()) {
2738 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
2739 NumInits = SubList->getNumInits();
2744 if (const ArrayType *AType
2745 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2746 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2747 NumElements = CAType->getSize().getZExtValue();
2748 // Simple heuristic so that we don't allocate a very large
2749 // initializer with many empty entries at the end.
2750 if (GotNumInits && NumElements > NumInits)
2753 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
2754 NumElements = VType->getNumElements();
2755 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
2756 RecordDecl *RDecl = RType->getDecl();
2757 if (RDecl->isUnion())
2760 NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
2763 Result->reserveInits(SemaRef.Context, NumElements);
2765 // Link this new initializer list into the structured initializer
2768 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
2770 Result->setSyntacticForm(IList);
2771 SyntacticToSemantic[IList] = Result;
2777 /// Update the initializer at index @p StructuredIndex within the
2778 /// structured initializer list to the value @p expr.
2779 void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2780 unsigned &StructuredIndex,
2782 // No structured initializer list to update
2783 if (!StructuredList)
2786 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2787 StructuredIndex, expr)) {
2788 // This initializer overwrites a previous initializer. Warn.
2789 // We need to check on source range validity because the previous
2790 // initializer does not have to be an explicit initializer.
2791 // struct P { int a, b; };
2792 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2793 // There is an overwrite taking place because the first braced initializer
2794 // list "{ .a = 2 }' already provides value for .p.b (which is zero).
2795 if (PrevInit->getSourceRange().isValid()) {
2796 SemaRef.Diag(expr->getLocStart(),
2797 diag::warn_initializer_overrides)
2798 << expr->getSourceRange();
2800 SemaRef.Diag(PrevInit->getLocStart(),
2801 diag::note_previous_initializer)
2802 << /*FIXME:has side effects=*/0
2803 << PrevInit->getSourceRange();
2810 /// Check that the given Index expression is a valid array designator
2811 /// value. This is essentially just a wrapper around
2812 /// VerifyIntegerConstantExpression that also checks for negative values
2813 /// and produces a reasonable diagnostic if there is a
2814 /// failure. Returns the index expression, possibly with an implicit cast
2815 /// added, on success. If everything went okay, Value will receive the
2816 /// value of the constant expression.
2818 CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
2819 SourceLocation Loc = Index->getLocStart();
2821 // Make sure this is an integer constant expression.
2822 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2823 if (Result.isInvalid())
2826 if (Value.isSigned() && Value.isNegative())
2827 return S.Diag(Loc, diag::err_array_designator_negative)
2828 << Value.toString(10) << Index->getSourceRange();
2830 Value.setIsUnsigned(true);
2834 ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
2838 typedef DesignatedInitExpr::Designator ASTDesignator;
2840 bool Invalid = false;
2841 SmallVector<ASTDesignator, 32> Designators;
2842 SmallVector<Expr *, 32> InitExpressions;
2844 // Build designators and check array designator expressions.
2845 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2846 const Designator &D = Desig.getDesignator(Idx);
2847 switch (D.getKind()) {
2848 case Designator::FieldDesignator:
2849 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
2853 case Designator::ArrayDesignator: {
2854 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2855 llvm::APSInt IndexValue;
2856 if (!Index->isTypeDependent() && !Index->isValueDependent())
2857 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
2861 Designators.push_back(ASTDesignator(InitExpressions.size(),
2863 D.getRBracketLoc()));
2864 InitExpressions.push_back(Index);
2869 case Designator::ArrayRangeDesignator: {
2870 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2871 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2872 llvm::APSInt StartValue;
2873 llvm::APSInt EndValue;
2874 bool StartDependent = StartIndex->isTypeDependent() ||
2875 StartIndex->isValueDependent();
2876 bool EndDependent = EndIndex->isTypeDependent() ||
2877 EndIndex->isValueDependent();
2878 if (!StartDependent)
2880 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
2882 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
2884 if (!StartIndex || !EndIndex)
2887 // Make sure we're comparing values with the same bit width.
2888 if (StartDependent || EndDependent) {
2889 // Nothing to compute.
2890 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
2891 EndValue = EndValue.extend(StartValue.getBitWidth());
2892 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
2893 StartValue = StartValue.extend(EndValue.getBitWidth());
2895 if (!StartDependent && !EndDependent && EndValue < StartValue) {
2896 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
2897 << StartValue.toString(10) << EndValue.toString(10)
2898 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2901 Designators.push_back(ASTDesignator(InitExpressions.size(),
2904 D.getRBracketLoc()));
2905 InitExpressions.push_back(StartIndex);
2906 InitExpressions.push_back(EndIndex);
2914 if (Invalid || Init.isInvalid())
2917 // Clear out the expressions within the designation.
2918 Desig.ClearExprs(*this);
2920 DesignatedInitExpr *DIE
2921 = DesignatedInitExpr::Create(Context,
2923 InitExpressions, Loc, GNUSyntax,
2924 Init.getAs<Expr>());
2926 if (!getLangOpts().C99)
2927 Diag(DIE->getLocStart(), diag::ext_designated_init)
2928 << DIE->getSourceRange();
2933 //===----------------------------------------------------------------------===//
2934 // Initialization entity
2935 //===----------------------------------------------------------------------===//
2937 InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
2938 const InitializedEntity &Parent)
2939 : Parent(&Parent), Index(Index)
2941 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2942 Kind = EK_ArrayElement;
2943 Type = AT->getElementType();
2944 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
2945 Kind = EK_VectorElement;
2946 Type = VT->getElementType();
2948 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2949 assert(CT && "Unexpected type");
2950 Kind = EK_ComplexElement;
2951 Type = CT->getElementType();
2956 InitializedEntity::InitializeBase(ASTContext &Context,
2957 const CXXBaseSpecifier *Base,
2958 bool IsInheritedVirtualBase,
2959 const InitializedEntity *Parent) {
2960 InitializedEntity Result;
2961 Result.Kind = EK_Base;
2962 Result.Parent = Parent;
2963 Result.Base = reinterpret_cast<uintptr_t>(Base);
2964 if (IsInheritedVirtualBase)
2965 Result.Base |= 0x01;
2967 Result.Type = Base->getType();
2971 DeclarationName InitializedEntity::getName() const {
2972 switch (getKind()) {
2974 case EK_Parameter_CF_Audited: {
2975 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2976 return (D ? D->getDeclName() : DeclarationName());
2982 return Variable.VariableOrMember->getDeclName();
2984 case EK_LambdaCapture:
2985 return DeclarationName(Capture.VarID);
2993 case EK_ArrayElement:
2994 case EK_VectorElement:
2995 case EK_ComplexElement:
2996 case EK_BlockElement:
2997 case EK_LambdaToBlockConversionBlockElement:
2998 case EK_CompoundLiteralInit:
2999 case EK_RelatedResult:
3000 return DeclarationName();
3003 llvm_unreachable("Invalid EntityKind!");
3006 ValueDecl *InitializedEntity::getDecl() const {
3007 switch (getKind()) {
3011 return Variable.VariableOrMember;
3014 case EK_Parameter_CF_Audited:
3015 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
3023 case EK_ArrayElement:
3024 case EK_VectorElement:
3025 case EK_ComplexElement:
3026 case EK_BlockElement:
3027 case EK_LambdaToBlockConversionBlockElement:
3028 case EK_LambdaCapture:
3029 case EK_CompoundLiteralInit:
3030 case EK_RelatedResult:
3034 llvm_unreachable("Invalid EntityKind!");
3037 bool InitializedEntity::allowsNRVO() const {
3038 switch (getKind()) {
3041 return LocAndNRVO.NRVO;
3045 case EK_Parameter_CF_Audited:
3050 case EK_CompoundLiteralInit:
3053 case EK_ArrayElement:
3054 case EK_VectorElement:
3055 case EK_ComplexElement:
3056 case EK_BlockElement:
3057 case EK_LambdaToBlockConversionBlockElement:
3058 case EK_LambdaCapture:
3059 case EK_RelatedResult:
3066 unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
3067 assert(getParent() != this);
3068 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3069 for (unsigned I = 0; I != Depth; ++I)
3072 switch (getKind()) {
3073 case EK_Variable: OS << "Variable"; break;
3074 case EK_Parameter: OS << "Parameter"; break;
3075 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3077 case EK_Result: OS << "Result"; break;
3078 case EK_Exception: OS << "Exception"; break;
3079 case EK_Member: OS << "Member"; break;
3080 case EK_Binding: OS << "Binding"; break;
3081 case EK_New: OS << "New"; break;
3082 case EK_Temporary: OS << "Temporary"; break;
3083 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
3084 case EK_RelatedResult: OS << "RelatedResult"; break;
3085 case EK_Base: OS << "Base"; break;
3086 case EK_Delegating: OS << "Delegating"; break;
3087 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3088 case EK_VectorElement: OS << "VectorElement " << Index; break;
3089 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3090 case EK_BlockElement: OS << "Block"; break;
3091 case EK_LambdaToBlockConversionBlockElement:
3092 OS << "Block (lambda)";
3094 case EK_LambdaCapture:
3095 OS << "LambdaCapture ";
3096 OS << DeclarationName(Capture.VarID);
3100 if (auto *D = getDecl()) {
3102 D->printQualifiedName(OS);
3105 OS << " '" << getType().getAsString() << "'\n";
3110 LLVM_DUMP_METHOD void InitializedEntity::dump() const {
3111 dumpImpl(llvm::errs());
3114 //===----------------------------------------------------------------------===//
3115 // Initialization sequence
3116 //===----------------------------------------------------------------------===//
3118 void InitializationSequence::Step::Destroy() {
3120 case SK_ResolveAddressOfOverloadedFunction:
3121 case SK_CastDerivedToBaseRValue:
3122 case SK_CastDerivedToBaseXValue:
3123 case SK_CastDerivedToBaseLValue:
3124 case SK_BindReference:
3125 case SK_BindReferenceToTemporary:
3127 case SK_ExtraneousCopyToTemporary:
3128 case SK_UserConversion:
3129 case SK_QualificationConversionRValue:
3130 case SK_QualificationConversionXValue:
3131 case SK_QualificationConversionLValue:
3132 case SK_AtomicConversion:
3133 case SK_LValueToRValue:
3134 case SK_ListInitialization:
3135 case SK_UnwrapInitList:
3136 case SK_RewrapInitList:
3137 case SK_ConstructorInitialization:
3138 case SK_ConstructorInitializationFromList:
3139 case SK_ZeroInitialization:
3140 case SK_CAssignment:
3142 case SK_ObjCObjectConversion:
3143 case SK_ArrayLoopIndex:
3144 case SK_ArrayLoopInit:
3146 case SK_GNUArrayInit:
3147 case SK_ParenthesizedArrayInit:
3148 case SK_PassByIndirectCopyRestore:
3149 case SK_PassByIndirectRestore:
3150 case SK_ProduceObjCObject:
3151 case SK_StdInitializerList:
3152 case SK_StdInitializerListConstructorCall:
3153 case SK_OCLSamplerInit:
3154 case SK_OCLZeroEvent:
3155 case SK_OCLZeroQueue:
3158 case SK_ConversionSequence:
3159 case SK_ConversionSequenceNoNarrowing:
3164 bool InitializationSequence::isDirectReferenceBinding() const {
3165 // There can be some lvalue adjustments after the SK_BindReference step.
3166 for (auto I = Steps.rbegin(); I != Steps.rend(); ++I) {
3167 if (I->Kind == SK_BindReference)
3169 if (I->Kind == SK_BindReferenceToTemporary)
3175 bool InitializationSequence::isAmbiguous() const {
3179 switch (getFailureKind()) {
3180 case FK_TooManyInitsForReference:
3181 case FK_ParenthesizedListInitForReference:
3182 case FK_ArrayNeedsInitList:
3183 case FK_ArrayNeedsInitListOrStringLiteral:
3184 case FK_ArrayNeedsInitListOrWideStringLiteral:
3185 case FK_NarrowStringIntoWideCharArray:
3186 case FK_WideStringIntoCharArray:
3187 case FK_IncompatWideStringIntoWideChar:
3188 case FK_AddressOfOverloadFailed: // FIXME: Could do better
3189 case FK_NonConstLValueReferenceBindingToTemporary:
3190 case FK_NonConstLValueReferenceBindingToBitfield:
3191 case FK_NonConstLValueReferenceBindingToVectorElement:
3192 case FK_NonConstLValueReferenceBindingToUnrelated:
3193 case FK_RValueReferenceBindingToLValue:
3194 case FK_ReferenceInitDropsQualifiers:
3195 case FK_ReferenceInitFailed:
3196 case FK_ConversionFailed:
3197 case FK_ConversionFromPropertyFailed:
3198 case FK_TooManyInitsForScalar:
3199 case FK_ParenthesizedListInitForScalar:
3200 case FK_ReferenceBindingToInitList:
3201 case FK_InitListBadDestinationType:
3202 case FK_DefaultInitOfConst:
3204 case FK_ArrayTypeMismatch:
3205 case FK_NonConstantArrayInit:
3206 case FK_ListInitializationFailed:
3207 case FK_VariableLengthArrayHasInitializer:
3208 case FK_PlaceholderType:
3209 case FK_ExplicitConstructor:
3210 case FK_AddressOfUnaddressableFunction:
3213 case FK_ReferenceInitOverloadFailed:
3214 case FK_UserConversionOverloadFailed:
3215 case FK_ConstructorOverloadFailed:
3216 case FK_ListConstructorOverloadFailed:
3217 return FailedOverloadResult == OR_Ambiguous;
3220 llvm_unreachable("Invalid EntityKind!");
3223 bool InitializationSequence::isConstructorInitialization() const {
3224 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3228 InitializationSequence
3229 ::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3230 DeclAccessPair Found,
3231 bool HadMultipleCandidates) {
3233 S.Kind = SK_ResolveAddressOfOverloadedFunction;
3234 S.Type = Function->getType();
3235 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3236 S.Function.Function = Function;
3237 S.Function.FoundDecl = Found;
3241 void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
3245 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
3246 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3247 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
3253 void InitializationSequence::AddReferenceBindingStep(QualType T,
3254 bool BindingTemporary) {
3256 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3261 void InitializationSequence::AddFinalCopy(QualType T) {
3263 S.Kind = SK_FinalCopy;
3268 void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
3270 S.Kind = SK_ExtraneousCopyToTemporary;
3276 InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
3277 DeclAccessPair FoundDecl,
3279 bool HadMultipleCandidates) {
3281 S.Kind = SK_UserConversion;
3283 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3284 S.Function.Function = Function;
3285 S.Function.FoundDecl = FoundDecl;
3289 void InitializationSequence::AddQualificationConversionStep(QualType Ty,
3292 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
3295 S.Kind = SK_QualificationConversionRValue;
3298 S.Kind = SK_QualificationConversionXValue;
3301 S.Kind = SK_QualificationConversionLValue;
3308 void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
3310 S.Kind = SK_AtomicConversion;
3315 void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
3316 assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
3319 S.Kind = SK_LValueToRValue;
3324 void InitializationSequence::AddConversionSequenceStep(
3325 const ImplicitConversionSequence &ICS, QualType T,
3326 bool TopLevelOfInitList) {
3328 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3329 : SK_ConversionSequence;
3331 S.ICS = new ImplicitConversionSequence(ICS);
3335 void InitializationSequence::AddListInitializationStep(QualType T) {
3337 S.Kind = SK_ListInitialization;
3342 void InitializationSequence::AddConstructorInitializationStep(
3343 DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3344 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
3346 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
3347 : SK_ConstructorInitializationFromList
3348 : SK_ConstructorInitialization;
3350 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3351 S.Function.Function = Constructor;
3352 S.Function.FoundDecl = FoundDecl;
3356 void InitializationSequence::AddZeroInitializationStep(QualType T) {
3358 S.Kind = SK_ZeroInitialization;
3363 void InitializationSequence::AddCAssignmentStep(QualType T) {
3365 S.Kind = SK_CAssignment;
3370 void InitializationSequence::AddStringInitStep(QualType T) {
3372 S.Kind = SK_StringInit;
3377 void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
3379 S.Kind = SK_ObjCObjectConversion;
3384 void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) {
3386 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
3391 void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) {
3393 S.Kind = SK_ArrayLoopIndex;
3395 Steps.insert(Steps.begin(), S);
3397 S.Kind = SK_ArrayLoopInit;
3402 void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
3404 S.Kind = SK_ParenthesizedArrayInit;
3409 void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
3412 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3413 : SK_PassByIndirectRestore);
3418 void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3420 S.Kind = SK_ProduceObjCObject;
3425 void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3427 S.Kind = SK_StdInitializerList;
3432 void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3434 S.Kind = SK_OCLSamplerInit;
3439 void InitializationSequence::AddOCLZeroEventStep(QualType T) {
3441 S.Kind = SK_OCLZeroEvent;
3446 void InitializationSequence::AddOCLZeroQueueStep(QualType T) {
3448 S.Kind = SK_OCLZeroQueue;
3453 void InitializationSequence::RewrapReferenceInitList(QualType T,
3454 InitListExpr *Syntactic) {
3455 assert(Syntactic->getNumInits() == 1 &&
3456 "Can only rewrap trivial init lists.");
3458 S.Kind = SK_UnwrapInitList;
3459 S.Type = Syntactic->getInit(0)->getType();
3460 Steps.insert(Steps.begin(), S);
3462 S.Kind = SK_RewrapInitList;
3464 S.WrappingSyntacticList = Syntactic;
3468 void InitializationSequence::SetOverloadFailure(FailureKind Failure,
3469 OverloadingResult Result) {
3470 setSequenceKind(FailedSequence);
3471 this->Failure = Failure;
3472 this->FailedOverloadResult = Result;
3475 //===----------------------------------------------------------------------===//
3476 // Attempt initialization
3477 //===----------------------------------------------------------------------===//
3479 /// Tries to add a zero initializer. Returns true if that worked.
3481 maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
3482 const InitializedEntity &Entity) {
3483 if (Entity.getKind() != InitializedEntity::EK_Variable)
3486 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
3487 if (VD->getInit() || VD->getLocEnd().isMacroID())
3490 QualType VariableTy = VD->getType().getCanonicalType();
3491 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
3492 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
3493 if (!Init.empty()) {
3494 Sequence.AddZeroInitializationStep(Entity.getType());
3495 Sequence.SetZeroInitializationFixit(Init, Loc);
3501 static void MaybeProduceObjCObject(Sema &S,
3502 InitializationSequence &Sequence,
3503 const InitializedEntity &Entity) {
3504 if (!S.getLangOpts().ObjCAutoRefCount) return;
3506 /// When initializing a parameter, produce the value if it's marked
3507 /// __attribute__((ns_consumed)).
3508 if (Entity.isParameterKind()) {
3509 if (!Entity.isParameterConsumed())
3512 assert(Entity.getType()->isObjCRetainableType() &&
3513 "consuming an object of unretainable type?");
3514 Sequence.AddProduceObjCObjectStep(Entity.getType());
3516 /// When initializing a return value, if the return type is a
3517 /// retainable type, then returns need to immediately retain the
3518 /// object. If an autorelease is required, it will be done at the
3520 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
3521 if (!Entity.getType()->isObjCRetainableType())
3524 Sequence.AddProduceObjCObjectStep(Entity.getType());
3528 static void TryListInitialization(Sema &S,
3529 const InitializedEntity &Entity,
3530 const InitializationKind &Kind,
3531 InitListExpr *InitList,
3532 InitializationSequence &Sequence,
3533 bool TreatUnavailableAsInvalid);
3535 /// \brief When initializing from init list via constructor, handle
3536 /// initialization of an object of type std::initializer_list<T>.
3538 /// \return true if we have handled initialization of an object of type
3539 /// std::initializer_list<T>, false otherwise.
3540 static bool TryInitializerListConstruction(Sema &S,
3543 InitializationSequence &Sequence,
3544 bool TreatUnavailableAsInvalid) {
3546 if (!S.isStdInitializerList(DestType, &E))
3549 if (!S.isCompleteType(List->getExprLoc(), E)) {
3550 Sequence.setIncompleteTypeFailure(E);
3554 // Try initializing a temporary array from the init list.
3555 QualType ArrayType = S.Context.getConstantArrayType(
3556 E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3557 List->getNumInits()),
3558 clang::ArrayType::Normal, 0);
3559 InitializedEntity HiddenArray =
3560 InitializedEntity::InitializeTemporary(ArrayType);
3561 InitializationKind Kind =
3562 InitializationKind::CreateDirectList(List->getExprLoc());
3563 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
3564 TreatUnavailableAsInvalid);
3566 Sequence.AddStdInitializerListConstructionStep(DestType);
3570 /// Determine if the constructor has the signature of a copy or move
3571 /// constructor for the type T of the class in which it was found. That is,
3572 /// determine if its first parameter is of type T or reference to (possibly
3573 /// cv-qualified) T.
3574 static bool hasCopyOrMoveCtorParam(ASTContext &Ctx,
3575 const ConstructorInfo &Info) {
3576 if (Info.Constructor->getNumParams() == 0)
3580 Info.Constructor->getParamDecl(0)->getType().getNonReferenceType();
3582 Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
3584 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
3587 static OverloadingResult
3588 ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
3590 OverloadCandidateSet &CandidateSet,
3592 DeclContext::lookup_result Ctors,
3593 OverloadCandidateSet::iterator &Best,
3594 bool CopyInitializing, bool AllowExplicit,
3595 bool OnlyListConstructors, bool IsListInit,
3596 bool SecondStepOfCopyInit = false) {
3597 CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor);
3599 for (NamedDecl *D : Ctors) {
3600 auto Info = getConstructorInfo(D);
3601 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
3604 if (!AllowExplicit && Info.Constructor->isExplicit())
3607 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
3610 // C++11 [over.best.ics]p4:
3611 // ... and the constructor or user-defined conversion function is a
3613 // - 13.3.1.3, when the argument is the temporary in the second step
3614 // of a class copy-initialization, or
3615 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
3616 // - the second phase of 13.3.1.7 when the initializer list has exactly
3617 // one element that is itself an initializer list, and the target is
3618 // the first parameter of a constructor of class X, and the conversion
3619 // is to X or reference to (possibly cv-qualified X),
3620 // user-defined conversion sequences are not considered.
3621 bool SuppressUserConversions =
3622 SecondStepOfCopyInit ||
3623 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
3624 hasCopyOrMoveCtorParam(S.Context, Info));
3626 if (Info.ConstructorTmpl)
3627 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3628 /*ExplicitArgs*/ nullptr, Args,
3629 CandidateSet, SuppressUserConversions);
3631 // C++ [over.match.copy]p1:
3632 // - When initializing a temporary to be bound to the first parameter
3633 // of a constructor [for type T] that takes a reference to possibly
3634 // cv-qualified T as its first argument, called with a single
3635 // argument in the context of direct-initialization, explicit
3636 // conversion functions are also considered.
3637 // FIXME: What if a constructor template instantiates to such a signature?
3638 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
3640 hasCopyOrMoveCtorParam(S.Context, Info);
3641 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
3642 CandidateSet, SuppressUserConversions,
3643 /*PartialOverloading=*/false,
3644 /*AllowExplicit=*/AllowExplicitConv);
3648 // FIXME: Work around a bug in C++17 guaranteed copy elision.
3650 // When initializing an object of class type T by constructor
3651 // ([over.match.ctor]) or by list-initialization ([over.match.list])
3652 // from a single expression of class type U, conversion functions of
3653 // U that convert to the non-reference type cv T are candidates.
3654 // Explicit conversion functions are only candidates during
3655 // direct-initialization.
3657 // Note: SecondStepOfCopyInit is only ever true in this case when
3658 // evaluating whether to produce a C++98 compatibility warning.
3659 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
3660 !SecondStepOfCopyInit) {
3661 Expr *Initializer = Args[0];
3662 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
3663 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
3664 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
3665 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3667 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3668 D = D->getUnderlyingDecl();
3670 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3671 CXXConversionDecl *Conv;
3673 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3675 Conv = cast<CXXConversionDecl>(D);
3677 if ((AllowExplicit && !CopyInitializing) || !Conv->isExplicit()) {
3679 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
3680 ActingDC, Initializer, DestType,
3681 CandidateSet, AllowExplicit,
3682 /*AllowResultConversion*/false);
3684 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
3685 DestType, CandidateSet, AllowExplicit,
3686 /*AllowResultConversion*/false);
3692 // Perform overload resolution and return the result.
3693 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3696 /// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3697 /// enumerates the constructors of the initialized entity and performs overload
3698 /// resolution to select the best.
3699 /// \param DestType The destination class type.
3700 /// \param DestArrayType The destination type, which is either DestType or
3701 /// a (possibly multidimensional) array of DestType.
3702 /// \param IsListInit Is this list-initialization?
3703 /// \param IsInitListCopy Is this non-list-initialization resulting from a
3704 /// list-initialization from {x} where x is the same
3705 /// type as the entity?
3706 static void TryConstructorInitialization(Sema &S,
3707 const InitializedEntity &Entity,
3708 const InitializationKind &Kind,
3709 MultiExprArg Args, QualType DestType,
3710 QualType DestArrayType,
3711 InitializationSequence &Sequence,
3712 bool IsListInit = false,
3713 bool IsInitListCopy = false) {
3714 assert(((!IsListInit && !IsInitListCopy) ||
3715 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
3716 "IsListInit/IsInitListCopy must come with a single initializer list "
3719 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
3720 MultiExprArg UnwrappedArgs =
3721 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
3723 // The type we're constructing needs to be complete.
3724 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
3725 Sequence.setIncompleteTypeFailure(DestType);
3729 // C++17 [dcl.init]p17:
3730 // - If the initializer expression is a prvalue and the cv-unqualified
3731 // version of the source type is the same class as the class of the
3732 // destination, the initializer expression is used to initialize the
3733 // destination object.
3734 // Per DR (no number yet), this does not apply when initializing a base
3735 // class or delegating to another constructor from a mem-initializer.
3736 // ObjC++: Lambda captured by the block in the lambda to block conversion
3737 // should avoid copy elision.
3738 if (S.getLangOpts().CPlusPlus17 &&
3739 Entity.getKind() != InitializedEntity::EK_Base &&
3740 Entity.getKind() != InitializedEntity::EK_Delegating &&
3742 InitializedEntity::EK_LambdaToBlockConversionBlockElement &&
3743 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isRValue() &&
3744 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
3745 // Convert qualifications if necessary.
3746 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
3748 Sequence.RewrapReferenceInitList(DestType, ILE);
3752 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3753 assert(DestRecordType && "Constructor initialization requires record type");
3754 CXXRecordDecl *DestRecordDecl
3755 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3757 // Build the candidate set directly in the initialization sequence
3758 // structure, so that it will persist if we fail.
3759 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3761 // Determine whether we are allowed to call explicit constructors or
3762 // explicit conversion operators.
3763 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
3764 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
3766 // - Otherwise, if T is a class type, constructors are considered. The
3767 // applicable constructors are enumerated, and the best one is chosen
3768 // through overload resolution.
3769 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
3771 OverloadingResult Result = OR_No_Viable_Function;
3772 OverloadCandidateSet::iterator Best;
3773 bool AsInitializerList = false;
3775 // C++11 [over.match.list]p1, per DR1467:
3776 // When objects of non-aggregate type T are list-initialized, such that
3777 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
3778 // according to the rules in this section, overload resolution selects
3779 // the constructor in two phases:
3781 // - Initially, the candidate functions are the initializer-list
3782 // constructors of the class T and the argument list consists of the
3783 // initializer list as a single argument.
3785 AsInitializerList = true;
3787 // If the initializer list has no elements and T has a default constructor,
3788 // the first phase is omitted.
3789 if (!(UnwrappedArgs.empty() && DestRecordDecl->hasDefaultConstructor()))
3790 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
3791 CandidateSet, DestType, Ctors, Best,
3792 CopyInitialization, AllowExplicit,
3793 /*OnlyListConstructor=*/true,
3797 // C++11 [over.match.list]p1:
3798 // - If no viable initializer-list constructor is found, overload resolution
3799 // is performed again, where the candidate functions are all the
3800 // constructors of the class T and the argument list consists of the
3801 // elements of the initializer list.
3802 if (Result == OR_No_Viable_Function) {
3803 AsInitializerList = false;
3804 Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs,
3805 CandidateSet, DestType, Ctors, Best,
3806 CopyInitialization, AllowExplicit,
3807 /*OnlyListConstructors=*/false,
3811 Sequence.SetOverloadFailure(IsListInit ?
3812 InitializationSequence::FK_ListConstructorOverloadFailed :
3813 InitializationSequence::FK_ConstructorOverloadFailed,
3818 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3820 // In C++17, ResolveConstructorOverload can select a conversion function
3821 // instead of a constructor.
3822 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
3823 // Add the user-defined conversion step that calls the conversion function.
3824 QualType ConvType = CD->getConversionType();
3825 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
3826 "should not have selected this conversion function");
3827 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
3828 HadMultipleCandidates);
3829 if (!S.Context.hasSameType(ConvType, DestType))
3830 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
3832 Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
3836 // C++11 [dcl.init]p6:
3837 // If a program calls for the default initialization of an object
3838 // of a const-qualified type T, T shall be a class type with a
3839 // user-provided default constructor.
3840 // C++ core issue 253 proposal:
3841 // If the implicit default constructor initializes all subobjects, no
3842 // initializer should be required.
3843 // The 253 proposal is for example needed to process libstdc++ headers in 5.x.
3844 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3845 if (Kind.getKind() == InitializationKind::IK_Default &&
3846 Entity.getType().isConstQualified()) {
3847 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
3848 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
3849 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3854 // C++11 [over.match.list]p1:
3855 // In copy-list-initialization, if an explicit constructor is chosen, the
3856 // initializer is ill-formed.
3857 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
3858 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3862 // Add the constructor initialization step. Any cv-qualification conversion is
3863 // subsumed by the initialization.
3864 Sequence.AddConstructorInitializationStep(
3865 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
3866 IsListInit | IsInitListCopy, AsInitializerList);
3870 ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3872 QualType &SourceType,
3873 QualType &UnqualifiedSourceType,
3874 QualType UnqualifiedTargetType,
3875 InitializationSequence &Sequence) {
3876 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3877 S.Context.OverloadTy) {
3878 DeclAccessPair Found;
3879 bool HadMultipleCandidates = false;
3880 if (FunctionDecl *Fn
3881 = S.ResolveAddressOfOverloadedFunction(Initializer,
3882 UnqualifiedTargetType,
3884 &HadMultipleCandidates)) {
3885 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3886 HadMultipleCandidates);
3887 SourceType = Fn->getType();
3888 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3889 } else if (!UnqualifiedTargetType->isRecordType()) {
3890 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3897 static void TryReferenceInitializationCore(Sema &S,
3898 const InitializedEntity &Entity,
3899 const InitializationKind &Kind,
3901 QualType cv1T1, QualType T1,
3903 QualType cv2T2, QualType T2,
3905 InitializationSequence &Sequence);
3907 static void TryValueInitialization(Sema &S,
3908 const InitializedEntity &Entity,
3909 const InitializationKind &Kind,
3910 InitializationSequence &Sequence,
3911 InitListExpr *InitList = nullptr);
3913 /// \brief Attempt list initialization of a reference.
3914 static void TryReferenceListInitialization(Sema &S,
3915 const InitializedEntity &Entity,
3916 const InitializationKind &Kind,
3917 InitListExpr *InitList,
3918 InitializationSequence &Sequence,
3919 bool TreatUnavailableAsInvalid) {
3920 // First, catch C++03 where this isn't possible.
3921 if (!S.getLangOpts().CPlusPlus11) {
3922 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3925 // Can't reference initialize a compound literal.
3926 if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
3927 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3931 QualType DestType = Entity.getType();
3932 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3934 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3936 // Reference initialization via an initializer list works thus:
3937 // If the initializer list consists of a single element that is
3938 // reference-related to the referenced type, bind directly to that element
3939 // (possibly creating temporaries).
3940 // Otherwise, initialize a temporary with the initializer list and
3942 if (InitList->getNumInits() == 1) {
3943 Expr *Initializer = InitList->getInit(0);
3944 QualType cv2T2 = Initializer->getType();
3946 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3948 // If this fails, creating a temporary wouldn't work either.
3949 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3953 SourceLocation DeclLoc = Initializer->getLocStart();
3954 bool dummy1, dummy2, dummy3;
3955 Sema::ReferenceCompareResult RefRelationship
3956 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3958 if (RefRelationship >= Sema::Ref_Related) {
3959 // Try to bind the reference here.
3960 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3961 T1Quals, cv2T2, T2, T2Quals, Sequence);
3963 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3967 // Update the initializer if we've resolved an overloaded function.
3968 if (Sequence.step_begin() != Sequence.step_end())
3969 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3972 // Not reference-related. Create a temporary and bind to that.
3973 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3975 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
3976 TreatUnavailableAsInvalid);
3978 if (DestType->isRValueReferenceType() ||
3979 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3980 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3983 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3987 /// \brief Attempt list initialization (C++0x [dcl.init.list])
3988 static void TryListInitialization(Sema &S,
3989 const InitializedEntity &Entity,
3990 const InitializationKind &Kind,
3991 InitListExpr *InitList,
3992 InitializationSequence &Sequence,
3993 bool TreatUnavailableAsInvalid) {
3994 QualType DestType = Entity.getType();
3996 // C++ doesn't allow scalar initialization with more than one argument.
3997 // But C99 complex numbers are scalars and it makes sense there.
3998 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
3999 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
4000 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
4003 if (DestType->isReferenceType()) {
4004 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
4005 TreatUnavailableAsInvalid);
4009 if (DestType->isRecordType() &&
4010 !S.isCompleteType(InitList->getLocStart(), DestType)) {
4011 Sequence.setIncompleteTypeFailure(DestType);
4015 // C++11 [dcl.init.list]p3, per DR1467:
4016 // - If T is a class type and the initializer list has a single element of
4017 // type cv U, where U is T or a class derived from T, the object is
4018 // initialized from that element (by copy-initialization for
4019 // copy-list-initialization, or by direct-initialization for
4020 // direct-list-initialization).
4021 // - Otherwise, if T is a character array and the initializer list has a
4022 // single element that is an appropriately-typed string literal
4023 // (8.5.2 [dcl.init.string]), initialization is performed as described
4025 // - Otherwise, if T is an aggregate, [...] (continue below).
4026 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
4027 if (DestType->isRecordType()) {
4028 QualType InitType = InitList->getInit(0)->getType();
4029 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
4030 S.IsDerivedFrom(InitList->getLocStart(), InitType, DestType)) {
4031 Expr *InitListAsExpr = InitList;
4032 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4034 /*InitListSyntax*/false,
4035 /*IsInitListCopy*/true);
4039 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
4040 Expr *SubInit[1] = {InitList->getInit(0)};
4041 if (!isa<VariableArrayType>(DestAT) &&
4042 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
4043 InitializationKind SubKind =
4044 Kind.getKind() == InitializationKind::IK_DirectList
4045 ? InitializationKind::CreateDirect(Kind.getLocation(),
4046 InitList->getLBraceLoc(),
4047 InitList->getRBraceLoc())
4049 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4050 /*TopLevelOfInitList*/ true,
4051 TreatUnavailableAsInvalid);
4053 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4054 // the element is not an appropriately-typed string literal, in which
4055 // case we should proceed as in C++11 (below).
4057 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4064 // C++11 [dcl.init.list]p3:
4065 // - If T is an aggregate, aggregate initialization is performed.
4066 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
4067 (S.getLangOpts().CPlusPlus11 &&
4068 S.isStdInitializerList(DestType, nullptr))) {
4069 if (S.getLangOpts().CPlusPlus11) {
4070 // - Otherwise, if the initializer list has no elements and T is a
4071 // class type with a default constructor, the object is
4072 // value-initialized.
4073 if (InitList->getNumInits() == 0) {
4074 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4075 if (RD->hasDefaultConstructor()) {
4076 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
4081 // - Otherwise, if T is a specialization of std::initializer_list<E>,
4082 // an initializer_list object constructed [...]
4083 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
4084 TreatUnavailableAsInvalid))
4087 // - Otherwise, if T is a class type, constructors are considered.
4088 Expr *InitListAsExpr = InitList;
4089 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4090 DestType, Sequence, /*InitListSyntax*/true);
4092 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
4096 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
4097 InitList->getNumInits() == 1) {
4098 Expr *E = InitList->getInit(0);
4100 // - Otherwise, if T is an enumeration with a fixed underlying type,
4101 // the initializer-list has a single element v, and the initialization
4102 // is direct-list-initialization, the object is initialized with the
4103 // value T(v); if a narrowing conversion is required to convert v to
4104 // the underlying type of T, the program is ill-formed.
4105 auto *ET = DestType->getAs<EnumType>();
4106 if (S.getLangOpts().CPlusPlus17 &&
4107 Kind.getKind() == InitializationKind::IK_DirectList &&
4108 ET && ET->getDecl()->isFixed() &&
4109 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
4110 (E->getType()->isIntegralOrEnumerationType() ||
4111 E->getType()->isFloatingType())) {
4112 // There are two ways that T(v) can work when T is an enumeration type.
4113 // If there is either an implicit conversion sequence from v to T or
4114 // a conversion function that can convert from v to T, then we use that.
4115 // Otherwise, if v is of integral, enumeration, or floating-point type,
4116 // it is converted to the enumeration type via its underlying type.
4117 // There is no overlap possible between these two cases (except when the
4118 // source value is already of the destination type), and the first
4119 // case is handled by the general case for single-element lists below.
4120 ImplicitConversionSequence ICS;
4122 ICS.Standard.setAsIdentityConversion();
4124 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4125 // If E is of a floating-point type, then the conversion is ill-formed
4126 // due to narrowing, but go through the motions in order to produce the
4127 // right diagnostic.
4128 ICS.Standard.Second = E->getType()->isFloatingType()
4129 ? ICK_Floating_Integral
4130 : ICK_Integral_Conversion;
4131 ICS.Standard.setFromType(E->getType());
4132 ICS.Standard.setToType(0, E->getType());
4133 ICS.Standard.setToType(1, DestType);
4134 ICS.Standard.setToType(2, DestType);
4135 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
4136 /*TopLevelOfInitList*/true);
4137 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4141 // - Otherwise, if the initializer list has a single element of type E
4142 // [...references are handled above...], the object or reference is
4143 // initialized from that element (by copy-initialization for
4144 // copy-list-initialization, or by direct-initialization for
4145 // direct-list-initialization); if a narrowing conversion is required
4146 // to convert the element to T, the program is ill-formed.
4148 // Per core-24034, this is direct-initialization if we were performing
4149 // direct-list-initialization and copy-initialization otherwise.
4150 // We can't use InitListChecker for this, because it always performs
4151 // copy-initialization. This only matters if we might use an 'explicit'
4152 // conversion operator, so we only need to handle the cases where the source
4153 // is of record type.
4154 if (InitList->getInit(0)->getType()->isRecordType()) {
4155 InitializationKind SubKind =
4156 Kind.getKind() == InitializationKind::IK_DirectList
4157 ? InitializationKind::CreateDirect(Kind.getLocation(),
4158 InitList->getLBraceLoc(),
4159 InitList->getRBraceLoc())
4161 Expr *SubInit[1] = { InitList->getInit(0) };
4162 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4163 /*TopLevelOfInitList*/true,
4164 TreatUnavailableAsInvalid);
4166 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4171 InitListChecker CheckInitList(S, Entity, InitList,
4172 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
4173 if (CheckInitList.HadError()) {
4174 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
4178 // Add the list initialization step with the built init list.
4179 Sequence.AddListInitializationStep(DestType);
4182 /// \brief Try a reference initialization that involves calling a conversion
4184 static OverloadingResult TryRefInitWithConversionFunction(
4185 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4186 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
4187 InitializationSequence &Sequence) {
4188 QualType DestType = Entity.getType();
4189 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4190 QualType T1 = cv1T1.getUnqualifiedType();
4191 QualType cv2T2 = Initializer->getType();
4192 QualType T2 = cv2T2.getUnqualifiedType();
4195 bool ObjCConversion;
4196 bool ObjCLifetimeConversion;
4197 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
4198 T1, T2, DerivedToBase,
4200 ObjCLifetimeConversion) &&
4201 "Must have incompatible references when binding via conversion");
4202 (void)DerivedToBase;
4203 (void)ObjCConversion;
4204 (void)ObjCLifetimeConversion;
4206 // Build the candidate set directly in the initialization sequence
4207 // structure, so that it will persist if we fail.
4208 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4209 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4211 // Determine whether we are allowed to call explicit constructors or
4212 // explicit conversion operators.
4213 bool AllowExplicit = Kind.AllowExplicit();
4214 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
4216 const RecordType *T1RecordType = nullptr;
4217 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
4218 S.isCompleteType(Kind.getLocation(), T1)) {
4219 // The type we're converting to is a class type. Enumerate its constructors
4220 // to see if there is a suitable conversion.
4221 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
4223 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
4224 auto Info = getConstructorInfo(D);
4225 if (!Info.Constructor)
4228 if (!Info.Constructor->isInvalidDecl() &&
4229 Info.Constructor->isConvertingConstructor(AllowExplicit)) {
4230 if (Info.ConstructorTmpl)
4231 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
4232 /*ExplicitArgs*/ nullptr,
4233 Initializer, CandidateSet,
4234 /*SuppressUserConversions=*/true);
4236 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4237 Initializer, CandidateSet,
4238 /*SuppressUserConversions=*/true);
4242 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
4243 return OR_No_Viable_Function;
4245 const RecordType *T2RecordType = nullptr;
4246 if ((T2RecordType = T2->getAs<RecordType>()) &&
4247 S.isCompleteType(Kind.getLocation(), T2)) {
4248 // The type we're converting from is a class type, enumerate its conversion
4250 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4252 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4253 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4255 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4256 if (isa<UsingShadowDecl>(D))
4257 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4259 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4260 CXXConversionDecl *Conv;
4262 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4264 Conv = cast<CXXConversionDecl>(D);
4266 // If the conversion function doesn't return a reference type,
4267 // it can't be considered for this conversion unless we're allowed to
4268 // consider rvalues.
4269 // FIXME: Do we need to make sure that we only consider conversion
4270 // candidates with reference-compatible results? That might be needed to
4272 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
4273 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
4275 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
4276 ActingDC, Initializer,
4277 DestType, CandidateSet,
4278 /*AllowObjCConversionOnExplicit=*/
4281 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
4282 Initializer, DestType, CandidateSet,
4283 /*AllowObjCConversionOnExplicit=*/false);
4287 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4288 return OR_No_Viable_Function;
4290 SourceLocation DeclLoc = Initializer->getLocStart();
4292 // Perform overload resolution. If it fails, return the failed result.
4293 OverloadCandidateSet::iterator Best;
4294 if (OverloadingResult Result
4295 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
4298 FunctionDecl *Function = Best->Function;
4299 // This is the overload that will be used for this initialization step if we
4300 // use this initialization. Mark it as referenced.
4301 Function->setReferenced();
4303 // Compute the returned type and value kind of the conversion.
4305 if (isa<CXXConversionDecl>(Function))
4306 cv3T3 = Function->getReturnType();
4310 ExprValueKind VK = VK_RValue;
4311 if (cv3T3->isLValueReferenceType())
4313 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
4314 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
4315 cv3T3 = cv3T3.getNonLValueExprType(S.Context);
4317 // Add the user-defined conversion step.
4318 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4319 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
4320 HadMultipleCandidates);
4322 // Determine whether we'll need to perform derived-to-base adjustments or
4323 // other conversions.
4324 bool NewDerivedToBase = false;
4325 bool NewObjCConversion = false;
4326 bool NewObjCLifetimeConversion = false;
4327 Sema::ReferenceCompareResult NewRefRelationship
4328 = S.CompareReferenceRelationship(DeclLoc, T1, cv3T3,
4329 NewDerivedToBase, NewObjCConversion,
4330 NewObjCLifetimeConversion);
4332 // Add the final conversion sequence, if necessary.
4333 if (NewRefRelationship == Sema::Ref_Incompatible) {
4334 assert(!isa<CXXConstructorDecl>(Function) &&
4335 "should not have conversion after constructor");
4337 ImplicitConversionSequence ICS;
4339 ICS.Standard = Best->FinalConversion;
4340 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
4342 // Every implicit conversion results in a prvalue, except for a glvalue
4343 // derived-to-base conversion, which we handle below.
4344 cv3T3 = ICS.Standard.getToType(2);
4348 // If the converted initializer is a prvalue, its type T4 is adjusted to
4349 // type "cv1 T4" and the temporary materialization conversion is applied.
4351 // We adjust the cv-qualifications to match the reference regardless of
4352 // whether we have a prvalue so that the AST records the change. In this
4353 // case, T4 is "cv3 T3".
4354 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
4355 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
4356 Sequence.AddQualificationConversionStep(cv1T4, VK);
4357 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_RValue);
4358 VK = IsLValueRef ? VK_LValue : VK_XValue;
4360 if (NewDerivedToBase)
4361 Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
4362 else if (NewObjCConversion)
4363 Sequence.AddObjCObjectConversionStep(cv1T1);
4368 static void CheckCXX98CompatAccessibleCopy(Sema &S,
4369 const InitializedEntity &Entity,
4372 /// \brief Attempt reference initialization (C++0x [dcl.init.ref])
4373 static void TryReferenceInitialization(Sema &S,
4374 const InitializedEntity &Entity,
4375 const InitializationKind &Kind,
4377 InitializationSequence &Sequence) {
4378 QualType DestType = Entity.getType();
4379 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4381 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4382 QualType cv2T2 = Initializer->getType();
4384 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4386 // If the initializer is the address of an overloaded function, try
4387 // to resolve the overloaded function. If all goes well, T2 is the
4388 // type of the resulting function.
4389 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4393 // Delegate everything else to a subfunction.
4394 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4395 T1Quals, cv2T2, T2, T2Quals, Sequence);
4398 /// Determine whether an expression is a non-referenceable glvalue (one to
4399 /// which a reference can never bind). Attemting to bind a reference to
4400 /// such a glvalue will always create a temporary.
4401 static bool isNonReferenceableGLValue(Expr *E) {
4402 return E->refersToBitField() || E->refersToVectorElement();
4405 /// \brief Reference initialization without resolving overloaded functions.
4406 static void TryReferenceInitializationCore(Sema &S,
4407 const InitializedEntity &Entity,
4408 const InitializationKind &Kind,
4410 QualType cv1T1, QualType T1,
4412 QualType cv2T2, QualType T2,
4414 InitializationSequence &Sequence) {
4415 QualType DestType = Entity.getType();
4416 SourceLocation DeclLoc = Initializer->getLocStart();
4417 // Compute some basic properties of the types and the initializer.
4418 bool isLValueRef = DestType->isLValueReferenceType();
4419 bool isRValueRef = !isLValueRef;
4420 bool DerivedToBase = false;
4421 bool ObjCConversion = false;
4422 bool ObjCLifetimeConversion = false;
4423 Expr::Classification InitCategory = Initializer->Classify(S.Context);
4424 Sema::ReferenceCompareResult RefRelationship
4425 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
4426 ObjCConversion, ObjCLifetimeConversion);
4428 // C++0x [dcl.init.ref]p5:
4429 // A reference to type "cv1 T1" is initialized by an expression of type
4430 // "cv2 T2" as follows:
4432 // - If the reference is an lvalue reference and the initializer
4434 // Note the analogous bullet points for rvalue refs to functions. Because
4435 // there are no function rvalues in C++, rvalue refs to functions are treated
4436 // like lvalue refs.
4437 OverloadingResult ConvOvlResult = OR_Success;
4438 bool T1Function = T1->isFunctionType();
4439 if (isLValueRef || T1Function) {
4440 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
4441 (RefRelationship == Sema::Ref_Compatible ||
4442 (Kind.isCStyleOrFunctionalCast() &&
4443 RefRelationship == Sema::Ref_Related))) {
4444 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
4445 // reference-compatible with "cv2 T2," or
4446 if (T1Quals != T2Quals)
4447 // Convert to cv1 T2. This should only add qualifiers unless this is a
4448 // c-style cast. The removal of qualifiers in that case notionally
4449 // happens after the reference binding, but that doesn't matter.
4450 Sequence.AddQualificationConversionStep(
4451 S.Context.getQualifiedType(T2, T1Quals),
4452 Initializer->getValueKind());
4454 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
4455 else if (ObjCConversion)
4456 Sequence.AddObjCObjectConversionStep(cv1T1);
4458 // We only create a temporary here when binding a reference to a
4459 // bit-field or vector element. Those cases are't supposed to be
4460 // handled by this bullet, but the outcome is the same either way.
4461 Sequence.AddReferenceBindingStep(cv1T1, false);
4465 // - has a class type (i.e., T2 is a class type), where T1 is not
4466 // reference-related to T2, and can be implicitly converted to an
4467 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
4468 // with "cv3 T3" (this conversion is selected by enumerating the
4469 // applicable conversion functions (13.3.1.6) and choosing the best
4470 // one through overload resolution (13.3)),
4471 // If we have an rvalue ref to function type here, the rhs must be
4472 // an rvalue. DR1287 removed the "implicitly" here.
4473 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
4474 (isLValueRef || InitCategory.isRValue())) {
4475 ConvOvlResult = TryRefInitWithConversionFunction(
4476 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
4477 /*IsLValueRef*/ isLValueRef, Sequence);
4478 if (ConvOvlResult == OR_Success)
4480 if (ConvOvlResult != OR_No_Viable_Function)
4481 Sequence.SetOverloadFailure(
4482 InitializationSequence::FK_ReferenceInitOverloadFailed,
4487 // - Otherwise, the reference shall be an lvalue reference to a
4488 // non-volatile const type (i.e., cv1 shall be const), or the reference
4489 // shall be an rvalue reference.
4490 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
4491 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4492 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4493 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4494 Sequence.SetOverloadFailure(
4495 InitializationSequence::FK_ReferenceInitOverloadFailed,
4497 else if (!InitCategory.isLValue())
4499 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
4501 InitializationSequence::FailureKind FK;
4502 switch (RefRelationship) {
4503 case Sema::Ref_Compatible:
4504 if (Initializer->refersToBitField())
4505 FK = InitializationSequence::
4506 FK_NonConstLValueReferenceBindingToBitfield;
4507 else if (Initializer->refersToVectorElement())
4508 FK = InitializationSequence::
4509 FK_NonConstLValueReferenceBindingToVectorElement;
4511 llvm_unreachable("unexpected kind of compatible initializer");
4513 case Sema::Ref_Related:
4514 FK = InitializationSequence::FK_ReferenceInitDropsQualifiers;
4516 case Sema::Ref_Incompatible:
4517 FK = InitializationSequence::
4518 FK_NonConstLValueReferenceBindingToUnrelated;
4521 Sequence.SetFailed(FK);
4526 // - If the initializer expression
4528 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
4529 // [1z] rvalue (but not a bit-field) or
4530 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
4532 // Note: functions are handled above and below rather than here...
4534 (RefRelationship == Sema::Ref_Compatible ||
4535 (Kind.isCStyleOrFunctionalCast() &&
4536 RefRelationship == Sema::Ref_Related)) &&
4537 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
4538 (InitCategory.isPRValue() &&
4539 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
4540 T2->isArrayType())))) {
4541 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_RValue;
4542 if (InitCategory.isPRValue() && T2->isRecordType()) {
4543 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
4544 // compiler the freedom to perform a copy here or bind to the
4545 // object, while C++0x requires that we bind directly to the
4546 // object. Hence, we always bind to the object without making an
4547 // extra copy. However, in C++03 requires that we check for the
4548 // presence of a suitable copy constructor:
4550 // The constructor that would be used to make the copy shall
4551 // be callable whether or not the copy is actually done.
4552 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
4553 Sequence.AddExtraneousCopyToTemporary(cv2T2);
4554 else if (S.getLangOpts().CPlusPlus11)
4555 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
4558 // C++1z [dcl.init.ref]/5.2.1.2:
4559 // If the converted initializer is a prvalue, its type T4 is adjusted
4560 // to type "cv1 T4" and the temporary materialization conversion is
4562 QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1Quals);
4563 if (T1Quals != T2Quals)
4564 Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
4565 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_RValue);
4566 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
4568 // In any case, the reference is bound to the resulting glvalue (or to
4569 // an appropriate base class subobject).
4571 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
4572 else if (ObjCConversion)
4573 Sequence.AddObjCObjectConversionStep(cv1T1);
4577 // - has a class type (i.e., T2 is a class type), where T1 is not
4578 // reference-related to T2, and can be implicitly converted to an
4579 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
4580 // where "cv1 T1" is reference-compatible with "cv3 T3",
4582 // DR1287 removes the "implicitly" here.
4583 if (T2->isRecordType()) {
4584 if (RefRelationship == Sema::Ref_Incompatible) {
4585 ConvOvlResult = TryRefInitWithConversionFunction(
4586 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
4587 /*IsLValueRef*/ isLValueRef, Sequence);
4589 Sequence.SetOverloadFailure(
4590 InitializationSequence::FK_ReferenceInitOverloadFailed,
4596 if (RefRelationship == Sema::Ref_Compatible &&
4597 isRValueRef && InitCategory.isLValue()) {
4599 InitializationSequence::FK_RValueReferenceBindingToLValue);
4603 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4607 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
4608 // from the initializer expression using the rules for a non-reference
4609 // copy-initialization (8.5). The reference is then bound to the
4612 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
4614 // FIXME: Why do we use an implicit conversion here rather than trying
4615 // copy-initialization?
4616 ImplicitConversionSequence ICS
4617 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
4618 /*SuppressUserConversions=*/false,
4619 /*AllowExplicit=*/false,
4620 /*FIXME:InOverloadResolution=*/false,
4621 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4622 /*AllowObjCWritebackConversion=*/false);
4625 // FIXME: Use the conversion function set stored in ICS to turn
4626 // this into an overloading ambiguity diagnostic. However, we need
4627 // to keep that set as an OverloadCandidateSet rather than as some
4628 // other kind of set.
4629 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4630 Sequence.SetOverloadFailure(
4631 InitializationSequence::FK_ReferenceInitOverloadFailed,
4633 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4634 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4636 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
4639 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
4642 // [...] If T1 is reference-related to T2, cv1 must be the
4643 // same cv-qualification as, or greater cv-qualification
4644 // than, cv2; otherwise, the program is ill-formed.
4645 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
4646 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
4647 if (RefRelationship == Sema::Ref_Related &&
4648 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
4649 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4653 // [...] If T1 is reference-related to T2 and the reference is an rvalue
4654 // reference, the initializer expression shall not be an lvalue.
4655 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
4656 InitCategory.isLValue()) {
4658 InitializationSequence::FK_RValueReferenceBindingToLValue);
4662 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
4665 /// \brief Attempt character array initialization from a string literal
4666 /// (C++ [dcl.init.string], C99 6.7.8).
4667 static void TryStringLiteralInitialization(Sema &S,
4668 const InitializedEntity &Entity,
4669 const InitializationKind &Kind,
4671 InitializationSequence &Sequence) {
4672 Sequence.AddStringInitStep(Entity.getType());
4675 /// \brief Attempt value initialization (C++ [dcl.init]p7).
4676 static void TryValueInitialization(Sema &S,
4677 const InitializedEntity &Entity,
4678 const InitializationKind &Kind,
4679 InitializationSequence &Sequence,
4680 InitListExpr *InitList) {
4681 assert((!InitList || InitList->getNumInits() == 0) &&
4682 "Shouldn't use value-init for non-empty init lists");
4684 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
4686 // To value-initialize an object of type T means:
4687 QualType T = Entity.getType();
4689 // -- if T is an array type, then each element is value-initialized;
4690 T = S.Context.getBaseElementType(T);
4692 if (const RecordType *RT = T->getAs<RecordType>()) {
4693 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
4694 bool NeedZeroInitialization = true;
4696 // -- if T is a class type (clause 9) with a user-declared constructor
4697 // (12.1), then the default constructor for T is called (and the
4698 // initialization is ill-formed if T has no accessible default
4701 // -- if T is a class type (clause 9) with either no default constructor
4702 // (12.1 [class.ctor]) or a default constructor that is user-provided
4703 // or deleted, then the object is default-initialized;
4705 // Note that the C++11 rule is the same as the C++98 rule if there are no
4706 // defaulted or deleted constructors, so we just use it unconditionally.
4707 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
4708 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
4709 NeedZeroInitialization = false;
4711 // -- if T is a (possibly cv-qualified) non-union class type without a
4712 // user-provided or deleted default constructor, then the object is
4713 // zero-initialized and, if T has a non-trivial default constructor,
4714 // default-initialized;
4715 // The 'non-union' here was removed by DR1502. The 'non-trivial default
4716 // constructor' part was removed by DR1507.
4717 if (NeedZeroInitialization)
4718 Sequence.AddZeroInitializationStep(Entity.getType());
4721 // -- if T is a non-union class type without a user-declared constructor,
4722 // then every non-static data member and base class component of T is
4723 // value-initialized;
4724 // [...] A program that calls for [...] value-initialization of an
4725 // entity of reference type is ill-formed.
4727 // C++11 doesn't need this handling, because value-initialization does not
4728 // occur recursively there, and the implicit default constructor is
4729 // defined as deleted in the problematic cases.
4730 if (!S.getLangOpts().CPlusPlus11 &&
4731 ClassDecl->hasUninitializedReferenceMember()) {
4732 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
4736 // If this is list-value-initialization, pass the empty init list on when
4737 // building the constructor call. This affects the semantics of a few
4738 // things (such as whether an explicit default constructor can be called).
4739 Expr *InitListAsExpr = InitList;
4740 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
4741 bool InitListSyntax = InitList;
4743 // FIXME: Instead of creating a CXXConstructExpr of array type here,
4744 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
4745 return TryConstructorInitialization(
4746 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
4750 Sequence.AddZeroInitializationStep(Entity.getType());
4753 /// \brief Attempt default initialization (C++ [dcl.init]p6).
4754 static void TryDefaultInitialization(Sema &S,
4755 const InitializedEntity &Entity,
4756 const InitializationKind &Kind,
4757 InitializationSequence &Sequence) {
4758 assert(Kind.getKind() == InitializationKind::IK_Default);
4760 // C++ [dcl.init]p6:
4761 // To default-initialize an object of type T means:
4762 // - if T is an array type, each element is default-initialized;
4763 QualType DestType = S.Context.getBaseElementType(Entity.getType());
4765 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4766 // constructor for T is called (and the initialization is ill-formed if
4767 // T has no accessible default constructor);
4768 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
4769 TryConstructorInitialization(S, Entity, Kind, None, DestType,
4770 Entity.getType(), Sequence);
4774 // - otherwise, no initialization is performed.
4776 // If a program calls for the default initialization of an object of
4777 // a const-qualified type T, T shall be a class type with a user-provided
4778 // default constructor.
4779 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
4780 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4781 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
4785 // If the destination type has a lifetime property, zero-initialize it.
4786 if (DestType.getQualifiers().hasObjCLifetime()) {
4787 Sequence.AddZeroInitializationStep(Entity.getType());
4792 /// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
4793 /// which enumerates all conversion functions and performs overload resolution
4794 /// to select the best.
4795 static void TryUserDefinedConversion(Sema &S,
4797 const InitializationKind &Kind,
4799 InitializationSequence &Sequence,
4800 bool TopLevelOfInitList) {
4801 assert(!DestType->isReferenceType() && "References are handled elsewhere");
4802 QualType SourceType = Initializer->getType();
4803 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4804 "Must have a class type to perform a user-defined conversion");
4806 // Build the candidate set directly in the initialization sequence
4807 // structure, so that it will persist if we fail.
4808 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4809 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4811 // Determine whether we are allowed to call explicit constructors or
4812 // explicit conversion operators.
4813 bool AllowExplicit = Kind.AllowExplicit();
4815 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4816 // The type we're converting to is a class type. Enumerate its constructors
4817 // to see if there is a suitable conversion.
4818 CXXRecordDecl *DestRecordDecl
4819 = cast<CXXRecordDecl>(DestRecordType->getDecl());
4821 // Try to complete the type we're converting to.
4822 if (S.isCompleteType(Kind.getLocation(), DestType)) {
4823 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
4824 auto Info = getConstructorInfo(D);
4825 if (!Info.Constructor)
4828 if (!Info.Constructor->isInvalidDecl() &&
4829 Info.Constructor->isConvertingConstructor(AllowExplicit)) {
4830 if (Info.ConstructorTmpl)
4831 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
4832 /*ExplicitArgs*/ nullptr,
4833 Initializer, CandidateSet,
4834 /*SuppressUserConversions=*/true);
4836 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4837 Initializer, CandidateSet,
4838 /*SuppressUserConversions=*/true);
4844 SourceLocation DeclLoc = Initializer->getLocStart();
4846 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4847 // The type we're converting from is a class type, enumerate its conversion
4850 // We can only enumerate the conversion functions for a complete type; if
4851 // the type isn't complete, simply skip this step.
4852 if (S.isCompleteType(DeclLoc, SourceType)) {
4853 CXXRecordDecl *SourceRecordDecl
4854 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
4856 const auto &Conversions =
4857 SourceRecordDecl->getVisibleConversionFunctions();
4858 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4860 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4861 if (isa<UsingShadowDecl>(D))
4862 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4864 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4865 CXXConversionDecl *Conv;
4867 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4869 Conv = cast<CXXConversionDecl>(D);
4871 if (AllowExplicit || !Conv->isExplicit()) {
4873 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
4874 ActingDC, Initializer, DestType,
4875 CandidateSet, AllowExplicit);
4877 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
4878 Initializer, DestType, CandidateSet,
4885 // Perform overload resolution. If it fails, return the failed result.
4886 OverloadCandidateSet::iterator Best;
4887 if (OverloadingResult Result
4888 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4889 Sequence.SetOverloadFailure(
4890 InitializationSequence::FK_UserConversionOverloadFailed,
4895 FunctionDecl *Function = Best->Function;
4896 Function->setReferenced();
4897 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4899 if (isa<CXXConstructorDecl>(Function)) {
4900 // Add the user-defined conversion step. Any cv-qualification conversion is
4901 // subsumed by the initialization. Per DR5, the created temporary is of the
4902 // cv-unqualified type of the destination.
4903 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4904 DestType.getUnqualifiedType(),
4905 HadMultipleCandidates);
4907 // C++14 and before:
4908 // - if the function is a constructor, the call initializes a temporary
4909 // of the cv-unqualified version of the destination type. The [...]
4910 // temporary [...] is then used to direct-initialize, according to the
4911 // rules above, the object that is the destination of the
4912 // copy-initialization.
4913 // Note that this just performs a simple object copy from the temporary.
4916 // - if the function is a constructor, the call is a prvalue of the
4917 // cv-unqualified version of the destination type whose return object
4918 // is initialized by the constructor. The call is used to
4919 // direct-initialize, according to the rules above, the object that
4920 // is the destination of the copy-initialization.
4921 // Therefore we need to do nothing further.
4923 // FIXME: Mark this copy as extraneous.
4924 if (!S.getLangOpts().CPlusPlus17)
4925 Sequence.AddFinalCopy(DestType);
4926 else if (DestType.hasQualifiers())
4927 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
4931 // Add the user-defined conversion step that calls the conversion function.
4932 QualType ConvType = Function->getCallResultType();
4933 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4934 HadMultipleCandidates);
4936 if (ConvType->getAs<RecordType>()) {
4937 // The call is used to direct-initialize [...] the object that is the
4938 // destination of the copy-initialization.
4940 // In C++17, this does not call a constructor if we enter /17.6.1:
4941 // - If the initializer expression is a prvalue and the cv-unqualified
4942 // version of the source type is the same as the class of the
4943 // destination [... do not make an extra copy]
4945 // FIXME: Mark this copy as extraneous.
4946 if (!S.getLangOpts().CPlusPlus17 ||
4947 Function->getReturnType()->isReferenceType() ||
4948 !S.Context.hasSameUnqualifiedType(ConvType, DestType))
4949 Sequence.AddFinalCopy(DestType);
4950 else if (!S.Context.hasSameType(ConvType, DestType))
4951 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
4955 // If the conversion following the call to the conversion function
4956 // is interesting, add it as a separate step.
4957 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4958 Best->FinalConversion.Third) {
4959 ImplicitConversionSequence ICS;
4961 ICS.Standard = Best->FinalConversion;
4962 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
4966 /// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4967 /// a function with a pointer return type contains a 'return false;' statement.
4968 /// In C++11, 'false' is not a null pointer, so this breaks the build of any
4969 /// code using that header.
4971 /// Work around this by treating 'return false;' as zero-initializing the result
4972 /// if it's used in a pointer-returning function in a system header.
4973 static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
4974 const InitializedEntity &Entity,
4976 return S.getLangOpts().CPlusPlus11 &&
4977 Entity.getKind() == InitializedEntity::EK_Result &&
4978 Entity.getType()->isPointerType() &&
4979 isa<CXXBoolLiteralExpr>(Init) &&
4980 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
4981 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
4984 /// The non-zero enum values here are indexes into diagnostic alternatives.
4985 enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4987 /// Determines whether this expression is an acceptable ICR source.
4988 static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
4989 bool isAddressOf, bool &isWeakAccess) {
4991 e = e->IgnoreParens();
4993 // Skip address-of nodes.
4994 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4995 if (op->getOpcode() == UO_AddrOf)
4996 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4999 // Skip certain casts.
5000 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
5001 switch (ce->getCastKind()) {
5004 case CK_LValueBitCast:
5006 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
5008 case CK_ArrayToPointerDecay:
5009 return IIK_nonscalar;
5011 case CK_NullToPointer:
5018 // If we have a declaration reference, it had better be a local variable.
5019 } else if (isa<DeclRefExpr>(e)) {
5020 // set isWeakAccess to true, to mean that there will be an implicit
5021 // load which requires a cleanup.
5022 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
5023 isWeakAccess = true;
5025 if (!isAddressOf) return IIK_nonlocal;
5027 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
5028 if (!var) return IIK_nonlocal;
5030 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
5032 // If we have a conditional operator, check both sides.
5033 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
5034 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
5038 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
5040 // These are never scalar.
5041 } else if (isa<ArraySubscriptExpr>(e)) {
5042 return IIK_nonscalar;
5044 // Otherwise, it needs to be a null pointer constant.
5046 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
5047 ? IIK_okay : IIK_nonlocal);
5050 return IIK_nonlocal;
5053 /// Check whether the given expression is a valid operand for an
5054 /// indirect copy/restore.
5055 static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
5056 assert(src->isRValue());
5057 bool isWeakAccess = false;
5058 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
5059 // If isWeakAccess to true, there will be an implicit
5060 // load which requires a cleanup.
5061 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
5062 S.Cleanup.setExprNeedsCleanups(true);
5064 if (iik == IIK_okay) return;
5066 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
5067 << ((unsigned) iik - 1) // shift index into diagnostic explanations
5068 << src->getSourceRange();
5071 /// \brief Determine whether we have compatible array types for the
5072 /// purposes of GNU by-copy array initialization.
5073 static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
5074 const ArrayType *Source) {
5075 // If the source and destination array types are equivalent, we're
5077 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
5080 // Make sure that the element types are the same.
5081 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
5084 // The only mismatch we allow is when the destination is an
5085 // incomplete array type and the source is a constant array type.
5086 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
5089 static bool tryObjCWritebackConversion(Sema &S,
5090 InitializationSequence &Sequence,
5091 const InitializedEntity &Entity,
5092 Expr *Initializer) {
5093 bool ArrayDecay = false;
5094 QualType ArgType = Initializer->getType();
5095 QualType ArgPointee;
5096 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
5098 ArgPointee = ArgArrayType->getElementType();
5099 ArgType = S.Context.getPointerType(ArgPointee);
5102 // Handle write-back conversion.
5103 QualType ConvertedArgType;
5104 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
5108 // We should copy unless we're passing to an argument explicitly
5110 bool ShouldCopy = true;
5111 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5112 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5114 // Do we need an lvalue conversion?
5115 if (ArrayDecay || Initializer->isGLValue()) {
5116 ImplicitConversionSequence ICS;
5118 ICS.Standard.setAsIdentityConversion();
5120 QualType ResultType;
5122 ICS.Standard.First = ICK_Array_To_Pointer;
5123 ResultType = S.Context.getPointerType(ArgPointee);
5125 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
5126 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
5129 Sequence.AddConversionSequenceStep(ICS, ResultType);
5132 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
5136 static bool TryOCLSamplerInitialization(Sema &S,
5137 InitializationSequence &Sequence,
5139 Expr *Initializer) {
5140 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
5141 (!Initializer->isIntegerConstantExpr(S.Context) &&
5142 !Initializer->getType()->isSamplerT()))
5145 Sequence.AddOCLSamplerInitStep(DestType);
5150 // OpenCL 1.2 spec, s6.12.10
5152 // The event argument can also be used to associate the
5153 // async_work_group_copy with a previous async copy allowing
5154 // an event to be shared by multiple async copies; otherwise
5155 // event should be zero.
5157 static bool TryOCLZeroEventInitialization(Sema &S,
5158 InitializationSequence &Sequence,
5160 Expr *Initializer) {
5161 if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
5162 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
5163 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
5166 Sequence.AddOCLZeroEventStep(DestType);
5170 static bool TryOCLZeroQueueInitialization(Sema &S,
5171 InitializationSequence &Sequence,
5173 Expr *Initializer) {
5174 if (!S.getLangOpts().OpenCL || S.getLangOpts().OpenCLVersion < 200 ||
5175 !DestType->isQueueT() ||
5176 !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
5177 (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
5180 Sequence.AddOCLZeroQueueStep(DestType);
5184 InitializationSequence::InitializationSequence(Sema &S,
5185 const InitializedEntity &Entity,
5186 const InitializationKind &Kind,
5188 bool TopLevelOfInitList,
5189 bool TreatUnavailableAsInvalid)
5190 : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
5191 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
5192 TreatUnavailableAsInvalid);
5195 /// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
5196 /// address of that function, this returns true. Otherwise, it returns false.
5197 static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
5198 auto *DRE = dyn_cast<DeclRefExpr>(E);
5199 if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
5202 return !S.checkAddressOfFunctionIsAvailable(
5203 cast<FunctionDecl>(DRE->getDecl()));
5206 /// Determine whether we can perform an elementwise array copy for this kind
5208 static bool canPerformArrayCopy(const InitializedEntity &Entity) {
5209 switch (Entity.getKind()) {
5210 case InitializedEntity::EK_LambdaCapture:
5211 // C++ [expr.prim.lambda]p24:
5212 // For array members, the array elements are direct-initialized in
5213 // increasing subscript order.
5216 case InitializedEntity::EK_Variable:
5217 // C++ [dcl.decomp]p1:
5218 // [...] each element is copy-initialized or direct-initialized from the
5219 // corresponding element of the assignment-expression [...]
5220 return isa<DecompositionDecl>(Entity.getDecl());
5222 case InitializedEntity::EK_Member:
5223 // C++ [class.copy.ctor]p14:
5224 // - if the member is an array, each element is direct-initialized with
5225 // the corresponding subobject of x
5226 return Entity.isImplicitMemberInitializer();
5228 case InitializedEntity::EK_ArrayElement:
5229 // All the above cases are intended to apply recursively, even though none
5230 // of them actually say that.
5231 if (auto *E = Entity.getParent())
5232 return canPerformArrayCopy(*E);
5242 void InitializationSequence::InitializeFrom(Sema &S,
5243 const InitializedEntity &Entity,
5244 const InitializationKind &Kind,
5246 bool TopLevelOfInitList,
5247 bool TreatUnavailableAsInvalid) {
5248 ASTContext &Context = S.Context;
5250 // Eliminate non-overload placeholder types in the arguments. We
5251 // need to do this before checking whether types are dependent
5252 // because lowering a pseudo-object expression might well give us
5253 // something of dependent type.
5254 for (unsigned I = 0, E = Args.size(); I != E; ++I)
5255 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
5256 // FIXME: should we be doing this here?
5257 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
5258 if (result.isInvalid()) {
5259 SetFailed(FK_PlaceholderType);
5262 Args[I] = result.get();
5265 // C++0x [dcl.init]p16:
5266 // The semantics of initializers are as follows. The destination type is
5267 // the type of the object or reference being initialized and the source
5268 // type is the type of the initializer expression. The source type is not
5269 // defined when the initializer is a braced-init-list or when it is a
5270 // parenthesized list of expressions.
5271 QualType DestType = Entity.getType();
5273 if (DestType->isDependentType() ||
5274 Expr::hasAnyTypeDependentArguments(Args)) {
5275 SequenceKind = DependentSequence;
5279 // Almost everything is a normal sequence.
5280 setSequenceKind(NormalSequence);
5282 QualType SourceType;
5283 Expr *Initializer = nullptr;
5284 if (Args.size() == 1) {
5285 Initializer = Args[0];
5286 if (S.getLangOpts().ObjC1) {
5287 if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(),
5288 DestType, Initializer->getType(),
5290 S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
5291 Args[0] = Initializer;
5293 if (!isa<InitListExpr>(Initializer))
5294 SourceType = Initializer->getType();
5297 // - If the initializer is a (non-parenthesized) braced-init-list, the
5298 // object is list-initialized (8.5.4).
5299 if (Kind.getKind() != InitializationKind::IK_Direct) {
5300 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
5301 TryListInitialization(S, Entity, Kind, InitList, *this,
5302 TreatUnavailableAsInvalid);
5307 // - If the destination type is a reference type, see 8.5.3.
5308 if (DestType->isReferenceType()) {
5309 // C++0x [dcl.init.ref]p1:
5310 // A variable declared to be a T& or T&&, that is, "reference to type T"
5311 // (8.3.2), shall be initialized by an object, or function, of type T or
5312 // by an object that can be converted into a T.
5313 // (Therefore, multiple arguments are not permitted.)
5314 if (Args.size() != 1)
5315 SetFailed(FK_TooManyInitsForReference);
5316 // C++17 [dcl.init.ref]p5:
5317 // A reference [...] is initialized by an expression [...] as follows:
5318 // If the initializer is not an expression, presumably we should reject,
5319 // but the standard fails to actually say so.
5320 else if (isa<InitListExpr>(Args[0]))
5321 SetFailed(FK_ParenthesizedListInitForReference);
5323 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
5327 // - If the initializer is (), the object is value-initialized.
5328 if (Kind.getKind() == InitializationKind::IK_Value ||
5329 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
5330 TryValueInitialization(S, Entity, Kind, *this);
5334 // Handle default initialization.
5335 if (Kind.getKind() == InitializationKind::IK_Default) {
5336 TryDefaultInitialization(S, Entity, Kind, *this);
5340 // - If the destination type is an array of characters, an array of
5341 // char16_t, an array of char32_t, or an array of wchar_t, and the
5342 // initializer is a string literal, see 8.5.2.
5343 // - Otherwise, if the destination type is an array, the program is
5345 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
5346 if (Initializer && isa<VariableArrayType>(DestAT)) {
5347 SetFailed(FK_VariableLengthArrayHasInitializer);
5352 switch (IsStringInit(Initializer, DestAT, Context)) {
5354 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
5356 case SIF_NarrowStringIntoWideChar:
5357 SetFailed(FK_NarrowStringIntoWideCharArray);
5359 case SIF_WideStringIntoChar:
5360 SetFailed(FK_WideStringIntoCharArray);
5362 case SIF_IncompatWideStringIntoWideChar:
5363 SetFailed(FK_IncompatWideStringIntoWideChar);
5370 // Some kinds of initialization permit an array to be initialized from
5371 // another array of the same type, and perform elementwise initialization.
5372 if (Initializer && isa<ConstantArrayType>(DestAT) &&
5373 S.Context.hasSameUnqualifiedType(Initializer->getType(),
5374 Entity.getType()) &&
5375 canPerformArrayCopy(Entity)) {
5376 // If source is a prvalue, use it directly.
5377 if (Initializer->getValueKind() == VK_RValue) {
5378 AddArrayInitStep(DestType, /*IsGNUExtension*/false);
5382 // Emit element-at-a-time copy loop.
5383 InitializedEntity Element =
5384 InitializedEntity::InitializeElement(S.Context, 0, Entity);
5386 Context.getAsArrayType(Initializer->getType())->getElementType();
5387 OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
5388 Initializer->getValueKind(),
5389 Initializer->getObjectKind());
5390 Expr *OVEAsExpr = &OVE;
5391 InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList,
5392 TreatUnavailableAsInvalid);
5394 AddArrayInitLoopStep(Entity.getType(), InitEltT);
5398 // Note: as an GNU C extension, we allow initialization of an
5399 // array from a compound literal that creates an array of the same
5400 // type, so long as the initializer has no side effects.
5401 if (!S.getLangOpts().CPlusPlus && Initializer &&
5402 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
5403 Initializer->getType()->isArrayType()) {
5404 const ArrayType *SourceAT
5405 = Context.getAsArrayType(Initializer->getType());
5406 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
5407 SetFailed(FK_ArrayTypeMismatch);
5408 else if (Initializer->HasSideEffects(S.Context))
5409 SetFailed(FK_NonConstantArrayInit);
5411 AddArrayInitStep(DestType, /*IsGNUExtension*/true);
5414 // Note: as a GNU C++ extension, we allow list-initialization of a
5415 // class member of array type from a parenthesized initializer list.
5416 else if (S.getLangOpts().CPlusPlus &&
5417 Entity.getKind() == InitializedEntity::EK_Member &&
5418 Initializer && isa<InitListExpr>(Initializer)) {
5419 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
5420 *this, TreatUnavailableAsInvalid);
5421 AddParenthesizedArrayInitStep(DestType);
5422 } else if (DestAT->getElementType()->isCharType())
5423 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
5424 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
5425 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
5427 SetFailed(FK_ArrayNeedsInitList);
5432 // Determine whether we should consider writeback conversions for
5434 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
5435 Entity.isParameterKind();
5437 // We're at the end of the line for C: it's either a write-back conversion
5438 // or it's a C assignment. There's no need to check anything else.
5439 if (!S.getLangOpts().CPlusPlus) {
5440 // If allowed, check whether this is an Objective-C writeback conversion.
5441 if (allowObjCWritebackConversion &&
5442 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
5446 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
5449 if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
5452 if (TryOCLZeroQueueInitialization(S, *this, DestType, Initializer))
5455 // Handle initialization in C
5456 AddCAssignmentStep(DestType);
5457 MaybeProduceObjCObject(S, *this, Entity);
5461 assert(S.getLangOpts().CPlusPlus);
5463 // - If the destination type is a (possibly cv-qualified) class type:
5464 if (DestType->isRecordType()) {
5465 // - If the initialization is direct-initialization, or if it is
5466 // copy-initialization where the cv-unqualified version of the
5467 // source type is the same class as, or a derived class of, the
5468 // class of the destination, constructors are considered. [...]
5469 if (Kind.getKind() == InitializationKind::IK_Direct ||
5470 (Kind.getKind() == InitializationKind::IK_Copy &&
5471 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
5472 S.IsDerivedFrom(Initializer->getLocStart(), SourceType, DestType))))
5473 TryConstructorInitialization(S, Entity, Kind, Args,
5474 DestType, DestType, *this);
5475 // - Otherwise (i.e., for the remaining copy-initialization cases),
5476 // user-defined conversion sequences that can convert from the source
5477 // type to the destination type or (when a conversion function is
5478 // used) to a derived class thereof are enumerated as described in
5479 // 13.3.1.4, and the best one is chosen through overload resolution
5482 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
5483 TopLevelOfInitList);
5487 assert(Args.size() >= 1 && "Zero-argument case handled above");
5489 // The remaining cases all need a source type.
5490 if (Args.size() > 1) {
5491 SetFailed(FK_TooManyInitsForScalar);
5493 } else if (isa<InitListExpr>(Args[0])) {
5494 SetFailed(FK_ParenthesizedListInitForScalar);
5498 // - Otherwise, if the source type is a (possibly cv-qualified) class
5499 // type, conversion functions are considered.
5500 if (!SourceType.isNull() && SourceType->isRecordType()) {
5501 // For a conversion to _Atomic(T) from either T or a class type derived
5502 // from T, initialize the T object then convert to _Atomic type.
5503 bool NeedAtomicConversion = false;
5504 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
5505 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
5506 S.IsDerivedFrom(Initializer->getLocStart(), SourceType,
5507 Atomic->getValueType())) {
5508 DestType = Atomic->getValueType();
5509 NeedAtomicConversion = true;
5513 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
5514 TopLevelOfInitList);
5515 MaybeProduceObjCObject(S, *this, Entity);
5516 if (!Failed() && NeedAtomicConversion)
5517 AddAtomicConversionStep(Entity.getType());
5521 // - Otherwise, the initial value of the object being initialized is the
5522 // (possibly converted) value of the initializer expression. Standard
5523 // conversions (Clause 4) will be used, if necessary, to convert the
5524 // initializer expression to the cv-unqualified version of the
5525 // destination type; no user-defined conversions are considered.
5527 ImplicitConversionSequence ICS
5528 = S.TryImplicitConversion(Initializer, DestType,
5529 /*SuppressUserConversions*/true,
5530 /*AllowExplicitConversions*/ false,
5531 /*InOverloadResolution*/ false,
5532 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5533 allowObjCWritebackConversion);
5535 if (ICS.isStandard() &&
5536 ICS.Standard.Second == ICK_Writeback_Conversion) {
5537 // Objective-C ARC writeback conversion.
5539 // We should copy unless we're passing to an argument explicitly
5541 bool ShouldCopy = true;
5542 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5543 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5545 // If there was an lvalue adjustment, add it as a separate conversion.
5546 if (ICS.Standard.First == ICK_Array_To_Pointer ||
5547 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5548 ImplicitConversionSequence LvalueICS;
5549 LvalueICS.setStandard();
5550 LvalueICS.Standard.setAsIdentityConversion();
5551 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
5552 LvalueICS.Standard.First = ICS.Standard.First;
5553 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
5556 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
5557 } else if (ICS.isBad()) {
5559 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
5560 AddZeroInitializationStep(Entity.getType());
5561 } else if (Initializer->getType() == Context.OverloadTy &&
5562 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
5564 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
5565 else if (Initializer->getType()->isFunctionType() &&
5566 isExprAnUnaddressableFunction(S, Initializer))
5567 SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction);
5569 SetFailed(InitializationSequence::FK_ConversionFailed);
5571 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
5573 MaybeProduceObjCObject(S, *this, Entity);
5577 InitializationSequence::~InitializationSequence() {
5578 for (auto &S : Steps)
5582 //===----------------------------------------------------------------------===//
5583 // Perform initialization
5584 //===----------------------------------------------------------------------===//
5585 static Sema::AssignmentAction
5586 getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
5587 switch(Entity.getKind()) {
5588 case InitializedEntity::EK_Variable:
5589 case InitializedEntity::EK_New:
5590 case InitializedEntity::EK_Exception:
5591 case InitializedEntity::EK_Base:
5592 case InitializedEntity::EK_Delegating:
5593 return Sema::AA_Initializing;
5595 case InitializedEntity::EK_Parameter:
5596 if (Entity.getDecl() &&
5597 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5598 return Sema::AA_Sending;
5600 return Sema::AA_Passing;
5602 case InitializedEntity::EK_Parameter_CF_Audited:
5603 if (Entity.getDecl() &&
5604 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5605 return Sema::AA_Sending;
5607 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
5609 case InitializedEntity::EK_Result:
5610 return Sema::AA_Returning;
5612 case InitializedEntity::EK_Temporary:
5613 case InitializedEntity::EK_RelatedResult:
5614 // FIXME: Can we tell apart casting vs. converting?
5615 return Sema::AA_Casting;
5617 case InitializedEntity::EK_Member:
5618 case InitializedEntity::EK_Binding:
5619 case InitializedEntity::EK_ArrayElement:
5620 case InitializedEntity::EK_VectorElement:
5621 case InitializedEntity::EK_ComplexElement:
5622 case InitializedEntity::EK_BlockElement:
5623 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
5624 case InitializedEntity::EK_LambdaCapture:
5625 case InitializedEntity::EK_CompoundLiteralInit:
5626 return Sema::AA_Initializing;
5629 llvm_unreachable("Invalid EntityKind!");
5632 /// \brief Whether we should bind a created object as a temporary when
5633 /// initializing the given entity.
5634 static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
5635 switch (Entity.getKind()) {
5636 case InitializedEntity::EK_ArrayElement:
5637 case InitializedEntity::EK_Member:
5638 case InitializedEntity::EK_Result:
5639 case InitializedEntity::EK_New:
5640 case InitializedEntity::EK_Variable:
5641 case InitializedEntity::EK_Base:
5642 case InitializedEntity::EK_Delegating:
5643 case InitializedEntity::EK_VectorElement:
5644 case InitializedEntity::EK_ComplexElement:
5645 case InitializedEntity::EK_Exception:
5646 case InitializedEntity::EK_BlockElement:
5647 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
5648 case InitializedEntity::EK_LambdaCapture:
5649 case InitializedEntity::EK_CompoundLiteralInit:
5652 case InitializedEntity::EK_Parameter:
5653 case InitializedEntity::EK_Parameter_CF_Audited:
5654 case InitializedEntity::EK_Temporary:
5655 case InitializedEntity::EK_RelatedResult:
5656 case InitializedEntity::EK_Binding:
5660 llvm_unreachable("missed an InitializedEntity kind?");
5663 /// \brief Whether the given entity, when initialized with an object
5664 /// created for that initialization, requires destruction.
5665 static bool shouldDestroyEntity(const InitializedEntity &Entity) {
5666 switch (Entity.getKind()) {
5667 case InitializedEntity::EK_Result:
5668 case InitializedEntity::EK_New:
5669 case InitializedEntity::EK_Base:
5670 case InitializedEntity::EK_Delegating:
5671 case InitializedEntity::EK_VectorElement:
5672 case InitializedEntity::EK_ComplexElement:
5673 case InitializedEntity::EK_BlockElement:
5674 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
5675 case InitializedEntity::EK_LambdaCapture:
5678 case InitializedEntity::EK_Member:
5679 case InitializedEntity::EK_Binding:
5680 case InitializedEntity::EK_Variable:
5681 case InitializedEntity::EK_Parameter:
5682 case InitializedEntity::EK_Parameter_CF_Audited:
5683 case InitializedEntity::EK_Temporary:
5684 case InitializedEntity::EK_ArrayElement:
5685 case InitializedEntity::EK_Exception:
5686 case InitializedEntity::EK_CompoundLiteralInit:
5687 case InitializedEntity::EK_RelatedResult:
5691 llvm_unreachable("missed an InitializedEntity kind?");
5694 /// \brief Get the location at which initialization diagnostics should appear.
5695 static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
5696 Expr *Initializer) {
5697 switch (Entity.getKind()) {
5698 case InitializedEntity::EK_Result:
5699 return Entity.getReturnLoc();
5701 case InitializedEntity::EK_Exception:
5702 return Entity.getThrowLoc();
5704 case InitializedEntity::EK_Variable:
5705 case InitializedEntity::EK_Binding:
5706 return Entity.getDecl()->getLocation();
5708 case InitializedEntity::EK_LambdaCapture:
5709 return Entity.getCaptureLoc();
5711 case InitializedEntity::EK_ArrayElement:
5712 case InitializedEntity::EK_Member:
5713 case InitializedEntity::EK_Parameter:
5714 case InitializedEntity::EK_Parameter_CF_Audited:
5715 case InitializedEntity::EK_Temporary:
5716 case InitializedEntity::EK_New:
5717 case InitializedEntity::EK_Base:
5718 case InitializedEntity::EK_Delegating:
5719 case InitializedEntity::EK_VectorElement:
5720 case InitializedEntity::EK_ComplexElement:
5721 case InitializedEntity::EK_BlockElement:
5722 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
5723 case InitializedEntity::EK_CompoundLiteralInit:
5724 case InitializedEntity::EK_RelatedResult:
5725 return Initializer->getLocStart();
5727 llvm_unreachable("missed an InitializedEntity kind?");
5730 /// \brief Make a (potentially elidable) temporary copy of the object
5731 /// provided by the given initializer by calling the appropriate copy
5734 /// \param S The Sema object used for type-checking.
5736 /// \param T The type of the temporary object, which must either be
5737 /// the type of the initializer expression or a superclass thereof.
5739 /// \param Entity The entity being initialized.
5741 /// \param CurInit The initializer expression.
5743 /// \param IsExtraneousCopy Whether this is an "extraneous" copy that
5744 /// is permitted in C++03 (but not C++0x) when binding a reference to
5747 /// \returns An expression that copies the initializer expression into
5748 /// a temporary object, or an error expression if a copy could not be
5750 static ExprResult CopyObject(Sema &S,
5752 const InitializedEntity &Entity,
5754 bool IsExtraneousCopy) {
5755 if (CurInit.isInvalid())
5757 // Determine which class type we're copying to.
5758 Expr *CurInitExpr = (Expr *)CurInit.get();
5759 CXXRecordDecl *Class = nullptr;
5760 if (const RecordType *Record = T->getAs<RecordType>())
5761 Class = cast<CXXRecordDecl>(Record->getDecl());
5765 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
5767 // Make sure that the type we are copying is complete.
5768 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
5771 // Perform overload resolution using the class's constructors. Per
5772 // C++11 [dcl.init]p16, second bullet for class types, this initialization
5773 // is direct-initialization.
5774 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5775 DeclContext::lookup_result Ctors = S.LookupConstructors(Class);
5777 OverloadCandidateSet::iterator Best;
5778 switch (ResolveConstructorOverload(
5779 S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
5780 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
5781 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
5782 /*SecondStepOfCopyInit=*/true)) {
5786 case OR_No_Viable_Function:
5787 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
5788 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
5789 : diag::err_temp_copy_no_viable)
5790 << (int)Entity.getKind() << CurInitExpr->getType()
5791 << CurInitExpr->getSourceRange();
5792 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
5793 if (!IsExtraneousCopy || S.isSFINAEContext())
5798 S.Diag(Loc, diag::err_temp_copy_ambiguous)
5799 << (int)Entity.getKind() << CurInitExpr->getType()
5800 << CurInitExpr->getSourceRange();
5801 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
5805 S.Diag(Loc, diag::err_temp_copy_deleted)
5806 << (int)Entity.getKind() << CurInitExpr->getType()
5807 << CurInitExpr->getSourceRange();
5808 S.NoteDeletedFunction(Best->Function);
5812 bool HadMultipleCandidates = CandidateSet.size() > 1;
5814 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
5815 SmallVector<Expr*, 8> ConstructorArgs;
5816 CurInit.get(); // Ownership transferred into MultiExprArg, below.
5818 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
5821 if (IsExtraneousCopy) {
5822 // If this is a totally extraneous copy for C++03 reference
5823 // binding purposes, just return the original initialization
5824 // expression. We don't generate an (elided) copy operation here
5825 // because doing so would require us to pass down a flag to avoid
5826 // infinite recursion, where each step adds another extraneous,
5829 // Instantiate the default arguments of any extra parameters in
5830 // the selected copy constructor, as if we were going to create a
5831 // proper call to the copy constructor.
5832 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
5833 ParmVarDecl *Parm = Constructor->getParamDecl(I);
5834 if (S.RequireCompleteType(Loc, Parm->getType(),
5835 diag::err_call_incomplete_argument))
5838 // Build the default argument expression; we don't actually care
5839 // if this succeeds or not, because this routine will complain
5840 // if there was a problem.
5841 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5847 // Determine the arguments required to actually perform the
5848 // constructor call (we might have derived-to-base conversions, or
5849 // the copy constructor may have default arguments).
5850 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
5853 // C++0x [class.copy]p32:
5854 // When certain criteria are met, an implementation is allowed to
5855 // omit the copy/move construction of a class object, even if the
5856 // copy/move constructor and/or destructor for the object have
5857 // side effects. [...]
5858 // - when a temporary class object that has not been bound to a
5859 // reference (12.2) would be copied/moved to a class object
5860 // with the same cv-unqualified type, the copy/move operation
5861 // can be omitted by constructing the temporary object
5862 // directly into the target of the omitted copy/move
5864 // Note that the other three bullets are handled elsewhere. Copy
5865 // elision for return statements and throw expressions are handled as part
5866 // of constructor initialization, while copy elision for exception handlers
5867 // is handled by the run-time.
5869 // FIXME: If the function parameter is not the same type as the temporary, we
5870 // should still be able to elide the copy, but we don't have a way to
5871 // represent in the AST how much should be elided in this case.
5873 CurInitExpr->isTemporaryObject(S.Context, Class) &&
5874 S.Context.hasSameUnqualifiedType(
5875 Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
5876 CurInitExpr->getType());
5878 // Actually perform the constructor call.
5879 CurInit = S.BuildCXXConstructExpr(Loc, T, Best->FoundDecl, Constructor,
5882 HadMultipleCandidates,
5884 /*StdInitListInit*/ false,
5886 CXXConstructExpr::CK_Complete,
5889 // If we're supposed to bind temporaries, do so.
5890 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
5891 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
5895 /// \brief Check whether elidable copy construction for binding a reference to
5896 /// a temporary would have succeeded if we were building in C++98 mode, for
5898 static void CheckCXX98CompatAccessibleCopy(Sema &S,
5899 const InitializedEntity &Entity,
5900 Expr *CurInitExpr) {
5901 assert(S.getLangOpts().CPlusPlus11);
5903 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
5907 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
5908 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
5911 // Find constructors which would have been considered.
5912 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5913 DeclContext::lookup_result Ctors =
5914 S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl()));
5916 // Perform overload resolution.
5917 OverloadCandidateSet::iterator Best;
5918 OverloadingResult OR = ResolveConstructorOverload(
5919 S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
5920 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
5921 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
5922 /*SecondStepOfCopyInit=*/true);
5924 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
5925 << OR << (int)Entity.getKind() << CurInitExpr->getType()
5926 << CurInitExpr->getSourceRange();
5930 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
5931 Best->FoundDecl, Entity, Diag);
5932 // FIXME: Check default arguments as far as that's possible.
5935 case OR_No_Viable_Function:
5937 CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
5942 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
5947 S.NoteDeletedFunction(Best->Function);
5952 void InitializationSequence::PrintInitLocationNote(Sema &S,
5953 const InitializedEntity &Entity) {
5954 if (Entity.isParameterKind() && Entity.getDecl()) {
5955 if (Entity.getDecl()->getLocation().isInvalid())
5958 if (Entity.getDecl()->getDeclName())
5959 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5960 << Entity.getDecl()->getDeclName();
5962 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5964 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
5965 Entity.getMethodDecl())
5966 S.Diag(Entity.getMethodDecl()->getLocation(),
5967 diag::note_method_return_type_change)
5968 << Entity.getMethodDecl()->getDeclName();
5971 /// Returns true if the parameters describe a constructor initialization of
5972 /// an explicit temporary object, e.g. "Point(x, y)".
5973 static bool isExplicitTemporary(const InitializedEntity &Entity,
5974 const InitializationKind &Kind,
5976 switch (Entity.getKind()) {
5977 case InitializedEntity::EK_Temporary:
5978 case InitializedEntity::EK_CompoundLiteralInit:
5979 case InitializedEntity::EK_RelatedResult:
5985 switch (Kind.getKind()) {
5986 case InitializationKind::IK_DirectList:
5988 // FIXME: Hack to work around cast weirdness.
5989 case InitializationKind::IK_Direct:
5990 case InitializationKind::IK_Value:
5991 return NumArgs != 1;
5998 PerformConstructorInitialization(Sema &S,
5999 const InitializedEntity &Entity,
6000 const InitializationKind &Kind,
6002 const InitializationSequence::Step& Step,
6003 bool &ConstructorInitRequiresZeroInit,
6004 bool IsListInitialization,
6005 bool IsStdInitListInitialization,
6006 SourceLocation LBraceLoc,
6007 SourceLocation RBraceLoc) {
6008 unsigned NumArgs = Args.size();
6009 CXXConstructorDecl *Constructor
6010 = cast<CXXConstructorDecl>(Step.Function.Function);
6011 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
6013 // Build a call to the selected constructor.
6014 SmallVector<Expr*, 8> ConstructorArgs;
6015 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
6016 ? Kind.getEqualLoc()
6017 : Kind.getLocation();
6019 if (Kind.getKind() == InitializationKind::IK_Default) {
6020 // Force even a trivial, implicit default constructor to be
6021 // semantically checked. We do this explicitly because we don't build
6022 // the definition for completely trivial constructors.
6023 assert(Constructor->getParent() && "No parent class for constructor.");
6024 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
6025 Constructor->isTrivial() && !Constructor->isUsed(false))
6026 S.DefineImplicitDefaultConstructor(Loc, Constructor);
6029 ExprResult CurInit((Expr *)nullptr);
6031 // C++ [over.match.copy]p1:
6032 // - When initializing a temporary to be bound to the first parameter
6033 // of a constructor that takes a reference to possibly cv-qualified
6034 // T as its first argument, called with a single argument in the
6035 // context of direct-initialization, explicit conversion functions
6036 // are also considered.
6037 bool AllowExplicitConv =
6038 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
6039 hasCopyOrMoveCtorParam(S.Context,
6040 getConstructorInfo(Step.Function.FoundDecl));
6042 // Determine the arguments required to actually perform the constructor
6044 if (S.CompleteConstructorCall(Constructor, Args,
6045 Loc, ConstructorArgs,
6047 IsListInitialization))
6051 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
6052 // An explicitly-constructed temporary, e.g., X(1, 2).
6053 if (S.DiagnoseUseOfDecl(Constructor, Loc))
6056 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6058 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
6059 SourceRange ParenOrBraceRange =
6060 (Kind.getKind() == InitializationKind::IK_DirectList)
6061 ? SourceRange(LBraceLoc, RBraceLoc)
6062 : Kind.getParenRange();
6064 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
6065 Step.Function.FoundDecl.getDecl())) {
6066 Constructor = S.findInheritingConstructor(Loc, Constructor, Shadow);
6067 if (S.DiagnoseUseOfDecl(Constructor, Loc))
6070 S.MarkFunctionReferenced(Loc, Constructor);
6072 CurInit = new (S.Context) CXXTemporaryObjectExpr(
6073 S.Context, Constructor,
6074 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
6075 ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
6076 IsListInitialization, IsStdInitListInitialization,
6077 ConstructorInitRequiresZeroInit);
6079 CXXConstructExpr::ConstructionKind ConstructKind =
6080 CXXConstructExpr::CK_Complete;
6082 if (Entity.getKind() == InitializedEntity::EK_Base) {
6083 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
6084 CXXConstructExpr::CK_VirtualBase :
6085 CXXConstructExpr::CK_NonVirtualBase;
6086 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
6087 ConstructKind = CXXConstructExpr::CK_Delegating;
6090 // Only get the parenthesis or brace range if it is a list initialization or
6091 // direct construction.
6092 SourceRange ParenOrBraceRange;
6093 if (IsListInitialization)
6094 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
6095 else if (Kind.getKind() == InitializationKind::IK_Direct)
6096 ParenOrBraceRange = Kind.getParenRange();
6098 // If the entity allows NRVO, mark the construction as elidable
6100 if (Entity.allowsNRVO())
6101 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
6102 Step.Function.FoundDecl,
6103 Constructor, /*Elidable=*/true,
6105 HadMultipleCandidates,
6106 IsListInitialization,
6107 IsStdInitListInitialization,
6108 ConstructorInitRequiresZeroInit,
6112 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
6113 Step.Function.FoundDecl,
6116 HadMultipleCandidates,
6117 IsListInitialization,
6118 IsStdInitListInitialization,
6119 ConstructorInitRequiresZeroInit,
6123 if (CurInit.isInvalid())
6126 // Only check access if all of that succeeded.
6127 S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity);
6128 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
6131 if (shouldBindAsTemporary(Entity))
6132 CurInit = S.MaybeBindToTemporary(CurInit.get());
6137 /// Determine whether the specified InitializedEntity definitely has a lifetime
6138 /// longer than the current full-expression. Conservatively returns false if
6141 InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
6142 const InitializedEntity *Top = &Entity;
6143 while (Top->getParent())
6144 Top = Top->getParent();
6146 switch (Top->getKind()) {
6147 case InitializedEntity::EK_Variable:
6148 case InitializedEntity::EK_Result:
6149 case InitializedEntity::EK_Exception:
6150 case InitializedEntity::EK_Member:
6151 case InitializedEntity::EK_Binding:
6152 case InitializedEntity::EK_New:
6153 case InitializedEntity::EK_Base:
6154 case InitializedEntity::EK_Delegating:
6157 case InitializedEntity::EK_ArrayElement:
6158 case InitializedEntity::EK_VectorElement:
6159 case InitializedEntity::EK_BlockElement:
6160 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
6161 case InitializedEntity::EK_ComplexElement:
6162 // Could not determine what the full initialization is. Assume it might not
6163 // outlive the full-expression.
6166 case InitializedEntity::EK_Parameter:
6167 case InitializedEntity::EK_Parameter_CF_Audited:
6168 case InitializedEntity::EK_Temporary:
6169 case InitializedEntity::EK_LambdaCapture:
6170 case InitializedEntity::EK_CompoundLiteralInit:
6171 case InitializedEntity::EK_RelatedResult:
6172 // The entity being initialized might not outlive the full-expression.
6176 llvm_unreachable("unknown entity kind");
6179 /// Determine the declaration which an initialized entity ultimately refers to,
6180 /// for the purpose of lifetime-extending a temporary bound to a reference in
6181 /// the initialization of \p Entity.
6182 static const InitializedEntity *getEntityForTemporaryLifetimeExtension(
6183 const InitializedEntity *Entity,
6184 const InitializedEntity *FallbackDecl = nullptr) {
6185 // C++11 [class.temporary]p5:
6186 switch (Entity->getKind()) {
6187 case InitializedEntity::EK_Variable:
6188 // The temporary [...] persists for the lifetime of the reference
6191 case InitializedEntity::EK_Member:
6192 // For subobjects, we look at the complete object.
6193 if (Entity->getParent())
6194 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
6198 // -- A temporary bound to a reference member in a constructor's
6199 // ctor-initializer persists until the constructor exits.
6202 case InitializedEntity::EK_Binding:
6203 // Per [dcl.decomp]p3, the binding is treated as a variable of reference
6207 case InitializedEntity::EK_Parameter:
6208 case InitializedEntity::EK_Parameter_CF_Audited:
6209 // -- A temporary bound to a reference parameter in a function call
6210 // persists until the completion of the full-expression containing
6212 case InitializedEntity::EK_Result:
6213 // -- The lifetime of a temporary bound to the returned value in a
6214 // function return statement is not extended; the temporary is
6215 // destroyed at the end of the full-expression in the return statement.
6216 case InitializedEntity::EK_New:
6217 // -- A temporary bound to a reference in a new-initializer persists
6218 // until the completion of the full-expression containing the
6222 case InitializedEntity::EK_Temporary:
6223 case InitializedEntity::EK_CompoundLiteralInit:
6224 case InitializedEntity::EK_RelatedResult:
6225 // We don't yet know the storage duration of the surrounding temporary.
6226 // Assume it's got full-expression duration for now, it will patch up our
6227 // storage duration if that's not correct.
6230 case InitializedEntity::EK_ArrayElement:
6231 // For subobjects, we look at the complete object.
6232 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
6235 case InitializedEntity::EK_Base:
6236 // For subobjects, we look at the complete object.
6237 if (Entity->getParent())
6238 return getEntityForTemporaryLifetimeExtension(Entity->getParent(),
6241 case InitializedEntity::EK_Delegating:
6242 // We can reach this case for aggregate initialization in a constructor:
6243 // struct A { int &&r; };
6244 // struct B : A { B() : A{0} {} };
6245 // In this case, use the innermost field decl as the context.
6246 return FallbackDecl;
6248 case InitializedEntity::EK_BlockElement:
6249 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
6250 case InitializedEntity::EK_LambdaCapture:
6251 case InitializedEntity::EK_Exception:
6252 case InitializedEntity::EK_VectorElement:
6253 case InitializedEntity::EK_ComplexElement:
6256 llvm_unreachable("unknown entity kind");
6259 static void performLifetimeExtension(Expr *Init,
6260 const InitializedEntity *ExtendingEntity);
6262 /// Update a glvalue expression that is used as the initializer of a reference
6263 /// to note that its lifetime is extended.
6264 /// \return \c true if any temporary had its lifetime extended.
6266 performReferenceExtension(Expr *Init,
6267 const InitializedEntity *ExtendingEntity) {
6268 // Walk past any constructs which we can lifetime-extend across.
6273 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
6274 if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
6275 // This is just redundant braces around an initializer. Step over it.
6276 Init = ILE->getInit(0);
6280 // Step over any subobject adjustments; we may have a materialized
6281 // temporary inside them.
6282 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
6284 // Per current approach for DR1376, look through casts to reference type
6285 // when performing lifetime extension.
6286 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
6287 if (CE->getSubExpr()->isGLValue())
6288 Init = CE->getSubExpr();
6290 // Per the current approach for DR1299, look through array element access
6291 // when performing lifetime extension.
6292 if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init))
6293 Init = ASE->getBase();
6294 } while (Init != Old);
6296 if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
6297 // Update the storage duration of the materialized temporary.
6298 // FIXME: Rebuild the expression instead of mutating it.
6299 ME->setExtendingDecl(ExtendingEntity->getDecl(),
6300 ExtendingEntity->allocateManglingNumber());
6301 performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingEntity);
6308 /// Update a prvalue expression that is going to be materialized as a
6309 /// lifetime-extended temporary.
6310 static void performLifetimeExtension(Expr *Init,
6311 const InitializedEntity *ExtendingEntity) {
6312 // Dig out the expression which constructs the extended temporary.
6313 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
6315 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
6316 Init = BTE->getSubExpr();
6318 if (CXXStdInitializerListExpr *ILE =
6319 dyn_cast<CXXStdInitializerListExpr>(Init)) {
6320 performReferenceExtension(ILE->getSubExpr(), ExtendingEntity);
6324 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
6325 if (ILE->getType()->isArrayType()) {
6326 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
6327 performLifetimeExtension(ILE->getInit(I), ExtendingEntity);
6331 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
6332 assert(RD->isAggregate() && "aggregate init on non-aggregate");
6334 // If we lifetime-extend a braced initializer which is initializing an
6335 // aggregate, and that aggregate contains reference members which are
6336 // bound to temporaries, those temporaries are also lifetime-extended.
6337 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
6338 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
6339 performReferenceExtension(ILE->getInit(0), ExtendingEntity);
6342 for (const auto *I : RD->fields()) {
6343 if (Index >= ILE->getNumInits())
6345 if (I->isUnnamedBitfield())
6347 Expr *SubInit = ILE->getInit(Index);
6348 if (I->getType()->isReferenceType())
6349 performReferenceExtension(SubInit, ExtendingEntity);
6350 else if (isa<InitListExpr>(SubInit) ||
6351 isa<CXXStdInitializerListExpr>(SubInit))
6352 // This may be either aggregate-initialization of a member or
6353 // initialization of a std::initializer_list object. Either way,
6354 // we should recursively lifetime-extend that initializer.
6355 performLifetimeExtension(SubInit, ExtendingEntity);
6363 static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
6364 const Expr *Init, bool IsInitializerList,
6365 const ValueDecl *ExtendingDecl) {
6366 // Warn if a field lifetime-extends a temporary.
6367 if (isa<FieldDecl>(ExtendingDecl)) {
6368 if (IsInitializerList) {
6369 S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
6370 << /*at end of constructor*/true;
6374 bool IsSubobjectMember = false;
6375 for (const InitializedEntity *Ent = Entity.getParent(); Ent;
6376 Ent = Ent->getParent()) {
6377 if (Ent->getKind() != InitializedEntity::EK_Base) {
6378 IsSubobjectMember = true;
6382 S.Diag(Init->getExprLoc(),
6383 diag::warn_bind_ref_member_to_temporary)
6384 << ExtendingDecl << Init->getSourceRange()
6385 << IsSubobjectMember << IsInitializerList;
6386 if (IsSubobjectMember)
6387 S.Diag(ExtendingDecl->getLocation(),
6388 diag::note_ref_subobject_of_member_declared_here);
6390 S.Diag(ExtendingDecl->getLocation(),
6391 diag::note_ref_or_ptr_member_declared_here)
6392 << /*is pointer*/false;
6396 static void DiagnoseNarrowingInInitList(Sema &S,
6397 const ImplicitConversionSequence &ICS,
6398 QualType PreNarrowingType,
6399 QualType EntityType,
6400 const Expr *PostInit);
6402 /// Provide warnings when std::move is used on construction.
6403 static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
6404 bool IsReturnStmt) {
6408 if (S.inTemplateInstantiation())
6411 QualType DestType = InitExpr->getType();
6412 if (!DestType->isRecordType())
6415 unsigned DiagID = 0;
6417 const CXXConstructExpr *CCE =
6418 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
6419 if (!CCE || CCE->getNumArgs() != 1)
6422 if (!CCE->getConstructor()->isCopyOrMoveConstructor())
6425 InitExpr = CCE->getArg(0)->IgnoreImpCasts();
6428 // Find the std::move call and get the argument.
6429 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
6430 if (!CE || CE->getNumArgs() != 1)
6433 const FunctionDecl *MoveFunction = CE->getDirectCallee();
6434 if (!MoveFunction || !MoveFunction->isInStdNamespace() ||
6435 !MoveFunction->getIdentifier() ||
6436 !MoveFunction->getIdentifier()->isStr("move"))
6439 const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
6442 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
6443 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
6446 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
6447 if (!VD || !VD->hasLocalStorage())
6450 // __block variables are not moved implicitly.
6451 if (VD->hasAttr<BlocksAttr>())
6454 QualType SourceType = VD->getType();
6455 if (!SourceType->isRecordType())
6458 if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
6462 // If we're returning a function parameter, copy elision
6464 if (isa<ParmVarDecl>(VD))
6465 DiagID = diag::warn_redundant_move_on_return;
6467 DiagID = diag::warn_pessimizing_move_on_return;
6469 DiagID = diag::warn_pessimizing_move_on_initialization;
6470 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
6471 if (!ArgStripped->isRValue() || !ArgStripped->getType()->isRecordType())
6475 S.Diag(CE->getLocStart(), DiagID);
6477 // Get all the locations for a fix-it. Don't emit the fix-it if any location
6478 // is within a macro.
6479 SourceLocation CallBegin = CE->getCallee()->getLocStart();
6480 if (CallBegin.isMacroID())
6482 SourceLocation RParen = CE->getRParenLoc();
6483 if (RParen.isMacroID())
6485 SourceLocation LParen;
6486 SourceLocation ArgLoc = Arg->getLocStart();
6488 // Special testing for the argument location. Since the fix-it needs the
6489 // location right before the argument, the argument location can be in a
6490 // macro only if it is at the beginning of the macro.
6491 while (ArgLoc.isMacroID() &&
6492 S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) {
6493 ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).first;
6496 if (LParen.isMacroID())
6499 LParen = ArgLoc.getLocWithOffset(-1);
6501 S.Diag(CE->getLocStart(), diag::note_remove_move)
6502 << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
6503 << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
6506 static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
6507 // Check to see if we are dereferencing a null pointer. If so, this is
6508 // undefined behavior, so warn about it. This only handles the pattern
6509 // "*null", which is a very syntactic check.
6510 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
6511 if (UO->getOpcode() == UO_Deref &&
6512 UO->getSubExpr()->IgnoreParenCasts()->
6513 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
6514 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
6515 S.PDiag(diag::warn_binding_null_to_reference)
6516 << UO->getSubExpr()->getSourceRange());
6520 MaterializeTemporaryExpr *
6521 Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
6522 bool BoundToLvalueReference) {
6523 auto MTE = new (Context)
6524 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
6526 // Order an ExprWithCleanups for lifetime marks.
6528 // TODO: It'll be good to have a single place to check the access of the
6529 // destructor and generate ExprWithCleanups for various uses. Currently these
6530 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
6531 // but there may be a chance to merge them.
6532 Cleanup.setExprNeedsCleanups(false);
6536 ExprResult Sema::TemporaryMaterializationConversion(Expr *E) {
6537 // In C++98, we don't want to implicitly create an xvalue.
6538 // FIXME: This means that AST consumers need to deal with "prvalues" that
6539 // denote materialized temporaries. Maybe we should add another ValueKind
6540 // for "xvalue pretending to be a prvalue" for C++98 support.
6541 if (!E->isRValue() || !getLangOpts().CPlusPlus11)
6544 // C++1z [conv.rval]/1: T shall be a complete type.
6545 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
6546 // If so, we should check for a non-abstract class type here too.
6547 QualType T = E->getType();
6548 if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
6551 return CreateMaterializeTemporaryExpr(E->getType(), E, false);
6555 InitializationSequence::Perform(Sema &S,
6556 const InitializedEntity &Entity,
6557 const InitializationKind &Kind,
6559 QualType *ResultType) {
6561 Diagnose(S, Entity, Kind, Args);
6564 if (!ZeroInitializationFixit.empty()) {
6565 unsigned DiagID = diag::err_default_init_const;
6566 if (Decl *D = Entity.getDecl())
6567 if (S.getLangOpts().MSVCCompat && D->hasAttr<SelectAnyAttr>())
6568 DiagID = diag::ext_default_init_const;
6570 // The initialization would have succeeded with this fixit. Since the fixit
6571 // is on the error, we need to build a valid AST in this case, so this isn't
6572 // handled in the Failed() branch above.
6573 QualType DestType = Entity.getType();
6574 S.Diag(Kind.getLocation(), DiagID)
6575 << DestType << (bool)DestType->getAs<RecordType>()
6576 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
6577 ZeroInitializationFixit);
6580 if (getKind() == DependentSequence) {
6581 // If the declaration is a non-dependent, incomplete array type
6582 // that has an initializer, then its type will be completed once
6583 // the initializer is instantiated.
6584 if (ResultType && !Entity.getType()->isDependentType() &&
6586 QualType DeclType = Entity.getType();
6587 if (const IncompleteArrayType *ArrayT
6588 = S.Context.getAsIncompleteArrayType(DeclType)) {
6589 // FIXME: We don't currently have the ability to accurately
6590 // compute the length of an initializer list without
6591 // performing full type-checking of the initializer list
6592 // (since we have to determine where braces are implicitly
6593 // introduced and such). So, we fall back to making the array
6594 // type a dependently-sized array type with no specified
6596 if (isa<InitListExpr>((Expr *)Args[0])) {
6597 SourceRange Brackets;
6599 // Scavange the location of the brackets from the entity, if we can.
6600 if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) {
6601 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
6602 TypeLoc TL = TInfo->getTypeLoc();
6603 if (IncompleteArrayTypeLoc ArrayLoc =
6604 TL.getAs<IncompleteArrayTypeLoc>())
6605 Brackets = ArrayLoc.getBracketsRange();
6610 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
6611 /*NumElts=*/nullptr,
6612 ArrayT->getSizeModifier(),
6613 ArrayT->getIndexTypeCVRQualifiers(),
6619 if (Kind.getKind() == InitializationKind::IK_Direct &&
6620 !Kind.isExplicitCast()) {
6621 // Rebuild the ParenListExpr.
6622 SourceRange ParenRange = Kind.getParenRange();
6623 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
6626 assert(Kind.getKind() == InitializationKind::IK_Copy ||
6627 Kind.isExplicitCast() ||
6628 Kind.getKind() == InitializationKind::IK_DirectList);
6629 return ExprResult(Args[0]);
6632 // No steps means no initialization.
6634 return ExprResult((Expr *)nullptr);
6636 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
6637 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
6638 !Entity.isParameterKind()) {
6639 // Produce a C++98 compatibility warning if we are initializing a reference
6640 // from an initializer list. For parameters, we produce a better warning
6642 Expr *Init = Args[0];
6643 S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
6644 << Init->getSourceRange();
6647 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
6648 QualType ETy = Entity.getType();
6649 Qualifiers TyQualifiers = ETy.getQualifiers();
6650 bool HasGlobalAS = TyQualifiers.hasAddressSpace() &&
6651 TyQualifiers.getAddressSpace() == LangAS::opencl_global;
6653 if (S.getLangOpts().OpenCLVersion >= 200 &&
6654 ETy->isAtomicType() && !HasGlobalAS &&
6655 Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
6656 S.Diag(Args[0]->getLocStart(), diag::err_opencl_atomic_init) << 1 <<
6657 SourceRange(Entity.getDecl()->getLocStart(), Args[0]->getLocEnd());
6661 // Diagnose cases where we initialize a pointer to an array temporary, and the
6662 // pointer obviously outlives the temporary.
6663 if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
6664 Entity.getType()->isPointerType() &&
6665 InitializedEntityOutlivesFullExpression(Entity)) {
6666 const Expr *Init = Args[0]->skipRValueSubobjectAdjustments();
6667 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
6668 Init = MTE->GetTemporaryExpr();
6669 Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
6670 if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
6671 S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
6672 << Init->getSourceRange();
6675 QualType DestType = Entity.getType().getNonReferenceType();
6676 // FIXME: Ugly hack around the fact that Entity.getType() is not
6677 // the same as Entity.getDecl()->getType() in cases involving type merging,
6678 // and we want latter when it makes sense.
6680 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
6683 ExprResult CurInit((Expr *)nullptr);
6684 SmallVector<Expr*, 4> ArrayLoopCommonExprs;
6686 // For initialization steps that start with a single initializer,
6687 // grab the only argument out the Args and place it into the "current"
6689 switch (Steps.front().Kind) {
6690 case SK_ResolveAddressOfOverloadedFunction:
6691 case SK_CastDerivedToBaseRValue:
6692 case SK_CastDerivedToBaseXValue:
6693 case SK_CastDerivedToBaseLValue:
6694 case SK_BindReference:
6695 case SK_BindReferenceToTemporary:
6697 case SK_ExtraneousCopyToTemporary:
6698 case SK_UserConversion:
6699 case SK_QualificationConversionLValue:
6700 case SK_QualificationConversionXValue:
6701 case SK_QualificationConversionRValue:
6702 case SK_AtomicConversion:
6703 case SK_LValueToRValue:
6704 case SK_ConversionSequence:
6705 case SK_ConversionSequenceNoNarrowing:
6706 case SK_ListInitialization:
6707 case SK_UnwrapInitList:
6708 case SK_RewrapInitList:
6709 case SK_CAssignment:
6711 case SK_ObjCObjectConversion:
6712 case SK_ArrayLoopIndex:
6713 case SK_ArrayLoopInit:
6715 case SK_GNUArrayInit:
6716 case SK_ParenthesizedArrayInit:
6717 case SK_PassByIndirectCopyRestore:
6718 case SK_PassByIndirectRestore:
6719 case SK_ProduceObjCObject:
6720 case SK_StdInitializerList:
6721 case SK_OCLSamplerInit:
6722 case SK_OCLZeroEvent:
6723 case SK_OCLZeroQueue: {
6724 assert(Args.size() == 1);
6726 if (!CurInit.get()) return ExprError();
6730 case SK_ConstructorInitialization:
6731 case SK_ConstructorInitializationFromList:
6732 case SK_StdInitializerListConstructorCall:
6733 case SK_ZeroInitialization:
6737 // Promote from an unevaluated context to an unevaluated list context in
6738 // C++11 list-initialization; we need to instantiate entities usable in
6739 // constant expressions here in order to perform narrowing checks =(
6740 EnterExpressionEvaluationContext Evaluated(
6741 S, EnterExpressionEvaluationContext::InitList,
6742 CurInit.get() && isa<InitListExpr>(CurInit.get()));
6744 // C++ [class.abstract]p2:
6745 // no objects of an abstract class can be created except as subobjects
6746 // of a class derived from it
6747 auto checkAbstractType = [&](QualType T) -> bool {
6748 if (Entity.getKind() == InitializedEntity::EK_Base ||
6749 Entity.getKind() == InitializedEntity::EK_Delegating)
6751 return S.RequireNonAbstractType(Kind.getLocation(), T,
6752 diag::err_allocation_of_abstract_type);
6755 // Walk through the computed steps for the initialization sequence,
6756 // performing the specified conversions along the way.
6757 bool ConstructorInitRequiresZeroInit = false;
6758 for (step_iterator Step = step_begin(), StepEnd = step_end();
6759 Step != StepEnd; ++Step) {
6760 if (CurInit.isInvalid())
6763 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
6765 switch (Step->Kind) {
6766 case SK_ResolveAddressOfOverloadedFunction:
6767 // Overload resolution determined which function invoke; update the
6768 // initializer to reflect that choice.
6769 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
6770 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
6772 CurInit = S.FixOverloadedFunctionReference(CurInit,
6773 Step->Function.FoundDecl,
6774 Step->Function.Function);
6777 case SK_CastDerivedToBaseRValue:
6778 case SK_CastDerivedToBaseXValue:
6779 case SK_CastDerivedToBaseLValue: {
6780 // We have a derived-to-base cast that produces either an rvalue or an
6781 // lvalue. Perform that cast.
6783 CXXCastPath BasePath;
6785 // Casts to inaccessible base classes are allowed with C-style casts.
6786 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
6787 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
6788 CurInit.get()->getLocStart(),
6789 CurInit.get()->getSourceRange(),
6790 &BasePath, IgnoreBaseAccess))
6794 Step->Kind == SK_CastDerivedToBaseLValue ?
6796 (Step->Kind == SK_CastDerivedToBaseXValue ?
6800 ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
6801 CurInit.get(), &BasePath, VK);
6805 case SK_BindReference:
6806 // Reference binding does not have any corresponding ASTs.
6808 // Check exception specifications
6809 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
6812 // We don't check for e.g. function pointers here, since address
6813 // availability checks should only occur when the function first decays
6814 // into a pointer or reference.
6815 if (CurInit.get()->getType()->isFunctionProtoType()) {
6816 if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
6817 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
6818 if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
6819 DRE->getLocStart()))
6825 // Even though we didn't materialize a temporary, the binding may still
6826 // extend the lifetime of a temporary. This happens if we bind a reference
6827 // to the result of a cast to reference type.
6828 if (const InitializedEntity *ExtendingEntity =
6829 getEntityForTemporaryLifetimeExtension(&Entity))
6830 if (performReferenceExtension(CurInit.get(), ExtendingEntity))
6831 warnOnLifetimeExtension(S, Entity, CurInit.get(),
6832 /*IsInitializerList=*/false,
6833 ExtendingEntity->getDecl());
6835 CheckForNullPointerDereference(S, CurInit.get());
6838 case SK_BindReferenceToTemporary: {
6839 // Make sure the "temporary" is actually an rvalue.
6840 assert(CurInit.get()->isRValue() && "not a temporary");
6842 // Check exception specifications
6843 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
6846 // Materialize the temporary into memory.
6847 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
6848 Step->Type, CurInit.get(), Entity.getType()->isLValueReferenceType());
6850 // Maybe lifetime-extend the temporary's subobjects to match the
6851 // entity's lifetime.
6852 if (const InitializedEntity *ExtendingEntity =
6853 getEntityForTemporaryLifetimeExtension(&Entity))
6854 if (performReferenceExtension(MTE, ExtendingEntity))
6855 warnOnLifetimeExtension(S, Entity, CurInit.get(),
6856 /*IsInitializerList=*/false,
6857 ExtendingEntity->getDecl());
6859 // If we're extending this temporary to automatic storage duration -- we
6860 // need to register its cleanup during the full-expression's cleanups.
6861 if (MTE->getStorageDuration() == SD_Automatic &&
6862 MTE->getType().isDestructedType())
6863 S.Cleanup.setExprNeedsCleanups(true);
6870 if (checkAbstractType(Step->Type))
6873 // If the overall initialization is initializing a temporary, we already
6874 // bound our argument if it was necessary to do so. If not (if we're
6875 // ultimately initializing a non-temporary), our argument needs to be
6876 // bound since it's initializing a function parameter.
6877 // FIXME: This is a mess. Rationalize temporary destruction.
6878 if (!shouldBindAsTemporary(Entity))
6879 CurInit = S.MaybeBindToTemporary(CurInit.get());
6880 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
6881 /*IsExtraneousCopy=*/false);
6884 case SK_ExtraneousCopyToTemporary:
6885 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
6886 /*IsExtraneousCopy=*/true);
6889 case SK_UserConversion: {
6890 // We have a user-defined conversion that invokes either a constructor
6891 // or a conversion function.
6893 FunctionDecl *Fn = Step->Function.Function;
6894 DeclAccessPair FoundFn = Step->Function.FoundDecl;
6895 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
6896 bool CreatedObject = false;
6897 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
6898 // Build a call to the selected constructor.
6899 SmallVector<Expr*, 8> ConstructorArgs;
6900 SourceLocation Loc = CurInit.get()->getLocStart();
6902 // Determine the arguments required to actually perform the constructor
6904 Expr *Arg = CurInit.get();
6905 if (S.CompleteConstructorCall(Constructor,
6906 MultiExprArg(&Arg, 1),
6907 Loc, ConstructorArgs))
6910 // Build an expression that constructs a temporary.
6911 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type,
6912 FoundFn, Constructor,
6914 HadMultipleCandidates,
6916 /*StdInitListInit*/ false,
6918 CXXConstructExpr::CK_Complete,
6920 if (CurInit.isInvalid())
6923 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
6925 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6928 CastKind = CK_ConstructorConversion;
6929 CreatedObject = true;
6931 // Build a call to the conversion function.
6932 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
6933 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
6935 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
6938 // FIXME: Should we move this initialization into a separate
6939 // derived-to-base conversion? I believe the answer is "no", because
6940 // we don't want to turn off access control here for c-style casts.
6941 CurInit = S.PerformObjectArgumentInitialization(CurInit.get(),
6942 /*Qualifier=*/nullptr,
6943 FoundFn, Conversion);
6944 if (CurInit.isInvalid())
6947 // Build the actual call to the conversion function.
6948 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
6949 HadMultipleCandidates);
6950 if (CurInit.isInvalid())
6953 CastKind = CK_UserDefinedConversion;
6954 CreatedObject = Conversion->getReturnType()->isRecordType();
6957 if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
6960 CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
6961 CastKind, CurInit.get(), nullptr,
6962 CurInit.get()->getValueKind());
6964 if (shouldBindAsTemporary(Entity))
6965 // The overall entity is temporary, so this expression should be
6966 // destroyed at the end of its full-expression.
6967 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
6968 else if (CreatedObject && shouldDestroyEntity(Entity)) {
6969 // The object outlasts the full-expression, but we need to prepare for
6970 // a destructor being run on it.
6971 // FIXME: It makes no sense to do this here. This should happen
6972 // regardless of how we initialized the entity.
6973 QualType T = CurInit.get()->getType();
6974 if (const RecordType *Record = T->getAs<RecordType>()) {
6975 CXXDestructorDecl *Destructor
6976 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
6977 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
6978 S.PDiag(diag::err_access_dtor_temp) << T);
6979 S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
6980 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
6987 case SK_QualificationConversionLValue:
6988 case SK_QualificationConversionXValue:
6989 case SK_QualificationConversionRValue: {
6990 // Perform a qualification conversion; these can never go wrong.
6992 Step->Kind == SK_QualificationConversionLValue ?
6994 (Step->Kind == SK_QualificationConversionXValue ?
6997 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK);
7001 case SK_AtomicConversion: {
7002 assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic");
7003 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
7004 CK_NonAtomicToAtomic, VK_RValue);
7008 case SK_LValueToRValue: {
7009 assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
7010 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
7011 CK_LValueToRValue, CurInit.get(),
7012 /*BasePath=*/nullptr, VK_RValue);
7016 case SK_ConversionSequence:
7017 case SK_ConversionSequenceNoNarrowing: {
7018 Sema::CheckedConversionKind CCK
7019 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
7020 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
7021 : Kind.isExplicitCast()? Sema::CCK_OtherCast
7022 : Sema::CCK_ImplicitConversion;
7023 ExprResult CurInitExprRes =
7024 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
7025 getAssignmentAction(Entity), CCK);
7026 if (CurInitExprRes.isInvalid())
7029 S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), CurInit.get());
7031 CurInit = CurInitExprRes;
7033 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
7034 S.getLangOpts().CPlusPlus)
7035 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
7041 case SK_ListInitialization: {
7042 if (checkAbstractType(Step->Type))
7045 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
7046 // If we're not initializing the top-level entity, we need to create an
7047 // InitializeTemporary entity for our target type.
7048 QualType Ty = Step->Type;
7049 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
7050 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
7051 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
7052 InitListChecker PerformInitList(S, InitEntity,
7053 InitList, Ty, /*VerifyOnly=*/false,
7054 /*TreatUnavailableAsInvalid=*/false);
7055 if (PerformInitList.HadError())
7058 // Hack: We must update *ResultType if available in order to set the
7059 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
7060 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
7062 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
7063 if ((*ResultType)->isRValueReferenceType())
7064 Ty = S.Context.getRValueReferenceType(Ty);
7065 else if ((*ResultType)->isLValueReferenceType())
7066 Ty = S.Context.getLValueReferenceType(Ty,
7067 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
7071 InitListExpr *StructuredInitList =
7072 PerformInitList.getFullyStructuredList();
7074 CurInit = shouldBindAsTemporary(InitEntity)
7075 ? S.MaybeBindToTemporary(StructuredInitList)
7076 : StructuredInitList;
7080 case SK_ConstructorInitializationFromList: {
7081 if (checkAbstractType(Step->Type))
7084 // When an initializer list is passed for a parameter of type "reference
7085 // to object", we don't get an EK_Temporary entity, but instead an
7086 // EK_Parameter entity with reference type.
7087 // FIXME: This is a hack. What we really should do is create a user
7088 // conversion step for this case, but this makes it considerably more
7089 // complicated. For now, this will do.
7090 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
7091 Entity.getType().getNonReferenceType());
7092 bool UseTemporary = Entity.getType()->isReferenceType();
7093 assert(Args.size() == 1 && "expected a single argument for list init");
7094 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
7095 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
7096 << InitList->getSourceRange();
7097 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
7098 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
7101 ConstructorInitRequiresZeroInit,
7102 /*IsListInitialization*/true,
7103 /*IsStdInitListInit*/false,
7104 InitList->getLBraceLoc(),
7105 InitList->getRBraceLoc());
7109 case SK_UnwrapInitList:
7110 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
7113 case SK_RewrapInitList: {
7114 Expr *E = CurInit.get();
7115 InitListExpr *Syntactic = Step->WrappingSyntacticList;
7116 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
7117 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
7118 ILE->setSyntacticForm(Syntactic);
7119 ILE->setType(E->getType());
7120 ILE->setValueKind(E->getValueKind());
7125 case SK_ConstructorInitialization:
7126 case SK_StdInitializerListConstructorCall: {
7127 if (checkAbstractType(Step->Type))
7130 // When an initializer list is passed for a parameter of type "reference
7131 // to object", we don't get an EK_Temporary entity, but instead an
7132 // EK_Parameter entity with reference type.
7133 // FIXME: This is a hack. What we really should do is create a user
7134 // conversion step for this case, but this makes it considerably more
7135 // complicated. For now, this will do.
7136 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
7137 Entity.getType().getNonReferenceType());
7138 bool UseTemporary = Entity.getType()->isReferenceType();
7139 bool IsStdInitListInit =
7140 Step->Kind == SK_StdInitializerListConstructorCall;
7141 Expr *Source = CurInit.get();
7142 CurInit = PerformConstructorInitialization(
7143 S, UseTemporary ? TempEntity : Entity, Kind,
7144 Source ? MultiExprArg(Source) : Args, *Step,
7145 ConstructorInitRequiresZeroInit,
7146 /*IsListInitialization*/ IsStdInitListInit,
7147 /*IsStdInitListInitialization*/ IsStdInitListInit,
7148 /*LBraceLoc*/ SourceLocation(),
7149 /*RBraceLoc*/ SourceLocation());
7153 case SK_ZeroInitialization: {
7154 step_iterator NextStep = Step;
7156 if (NextStep != StepEnd &&
7157 (NextStep->Kind == SK_ConstructorInitialization ||
7158 NextStep->Kind == SK_ConstructorInitializationFromList)) {
7159 // The need for zero-initialization is recorded directly into
7160 // the call to the object's constructor within the next step.
7161 ConstructorInitRequiresZeroInit = true;
7162 } else if (Kind.getKind() == InitializationKind::IK_Value &&
7163 S.getLangOpts().CPlusPlus &&
7164 !Kind.isImplicitValueInit()) {
7165 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
7167 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
7168 Kind.getRange().getBegin());
7170 CurInit = new (S.Context) CXXScalarValueInitExpr(
7171 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
7172 Kind.getRange().getEnd());
7174 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
7179 case SK_CAssignment: {
7180 QualType SourceType = CurInit.get()->getType();
7181 // Save off the initial CurInit in case we need to emit a diagnostic
7182 ExprResult InitialCurInit = CurInit;
7183 ExprResult Result = CurInit;
7184 Sema::AssignConvertType ConvTy =
7185 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
7186 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
7187 if (Result.isInvalid())
7191 // If this is a call, allow conversion to a transparent union.
7192 ExprResult CurInitExprRes = CurInit;
7193 if (ConvTy != Sema::Compatible &&
7194 Entity.isParameterKind() &&
7195 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
7196 == Sema::Compatible)
7197 ConvTy = Sema::Compatible;
7198 if (CurInitExprRes.isInvalid())
7200 CurInit = CurInitExprRes;
7203 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
7204 Step->Type, SourceType,
7205 InitialCurInit.get(),
7206 getAssignmentAction(Entity, true),
7208 PrintInitLocationNote(S, Entity);
7210 } else if (Complained)
7211 PrintInitLocationNote(S, Entity);
7215 case SK_StringInit: {
7216 QualType Ty = Step->Type;
7217 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
7218 S.Context.getAsArrayType(Ty), S);
7222 case SK_ObjCObjectConversion:
7223 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
7224 CK_ObjCObjectLValueCast,
7225 CurInit.get()->getValueKind());
7228 case SK_ArrayLoopIndex: {
7229 Expr *Cur = CurInit.get();
7230 Expr *BaseExpr = new (S.Context)
7231 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
7232 Cur->getValueKind(), Cur->getObjectKind(), Cur);
7234 new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType());
7235 CurInit = S.CreateBuiltinArraySubscriptExpr(
7236 BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
7237 ArrayLoopCommonExprs.push_back(BaseExpr);
7241 case SK_ArrayLoopInit: {
7242 assert(!ArrayLoopCommonExprs.empty() &&
7243 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
7244 Expr *Common = ArrayLoopCommonExprs.pop_back_val();
7245 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
7250 case SK_GNUArrayInit:
7251 // Okay: we checked everything before creating this step. Note that
7252 // this is a GNU extension.
7253 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
7254 << Step->Type << CurInit.get()->getType()
7255 << CurInit.get()->getSourceRange();
7258 // If the destination type is an incomplete array type, update the
7259 // type accordingly.
7261 if (const IncompleteArrayType *IncompleteDest
7262 = S.Context.getAsIncompleteArrayType(Step->Type)) {
7263 if (const ConstantArrayType *ConstantSource
7264 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
7265 *ResultType = S.Context.getConstantArrayType(
7266 IncompleteDest->getElementType(),
7267 ConstantSource->getSize(),
7268 ArrayType::Normal, 0);
7274 case SK_ParenthesizedArrayInit:
7275 // Okay: we checked everything before creating this step. Note that
7276 // this is a GNU extension.
7277 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
7278 << CurInit.get()->getSourceRange();
7281 case SK_PassByIndirectCopyRestore:
7282 case SK_PassByIndirectRestore:
7283 checkIndirectCopyRestoreSource(S, CurInit.get());
7284 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
7285 CurInit.get(), Step->Type,
7286 Step->Kind == SK_PassByIndirectCopyRestore);
7289 case SK_ProduceObjCObject:
7291 ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
7292 CurInit.get(), nullptr, VK_RValue);
7295 case SK_StdInitializerList: {
7296 S.Diag(CurInit.get()->getExprLoc(),
7297 diag::warn_cxx98_compat_initializer_list_init)
7298 << CurInit.get()->getSourceRange();
7300 // Materialize the temporary into memory.
7301 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
7302 CurInit.get()->getType(), CurInit.get(),
7303 /*BoundToLvalueReference=*/false);
7305 // Maybe lifetime-extend the array temporary's subobjects to match the
7306 // entity's lifetime.
7307 if (const InitializedEntity *ExtendingEntity =
7308 getEntityForTemporaryLifetimeExtension(&Entity))
7309 if (performReferenceExtension(MTE, ExtendingEntity))
7310 warnOnLifetimeExtension(S, Entity, CurInit.get(),
7311 /*IsInitializerList=*/true,
7312 ExtendingEntity->getDecl());
7314 // Wrap it in a construction of a std::initializer_list<T>.
7315 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
7317 // Bind the result, in case the library has given initializer_list a
7318 // non-trivial destructor.
7319 if (shouldBindAsTemporary(Entity))
7320 CurInit = S.MaybeBindToTemporary(CurInit.get());
7324 case SK_OCLSamplerInit: {
7325 // Sampler initialzation have 5 cases:
7326 // 1. function argument passing
7327 // 1a. argument is a file-scope variable
7328 // 1b. argument is a function-scope variable
7329 // 1c. argument is one of caller function's parameters
7330 // 2. variable initialization
7331 // 2a. initializing a file-scope variable
7332 // 2b. initializing a function-scope variable
7334 // For file-scope variables, since they cannot be initialized by function
7335 // call of __translate_sampler_initializer in LLVM IR, their references
7336 // need to be replaced by a cast from their literal initializers to
7337 // sampler type. Since sampler variables can only be used in function
7338 // calls as arguments, we only need to replace them when handling the
7339 // argument passing.
7340 assert(Step->Type->isSamplerT() &&
7341 "Sampler initialization on non-sampler type.");
7342 Expr *Init = CurInit.get();
7343 QualType SourceType = Init->getType();
7345 if (Entity.isParameterKind()) {
7346 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
7347 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
7350 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
7351 auto Var = cast<VarDecl>(DRE->getDecl());
7353 // No cast from integer to sampler is needed.
7354 if (!Var->hasGlobalStorage()) {
7355 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
7356 CK_LValueToRValue, Init,
7357 /*BasePath=*/nullptr, VK_RValue);
7361 // For function call with a file-scope sampler variable as argument,
7362 // get the integer literal.
7363 // Do not diagnose if the file-scope variable does not have initializer
7364 // since this has already been diagnosed when parsing the variable
7366 if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
7368 Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
7369 Var->getInit()))->getSubExpr();
7370 SourceType = Init->getType();
7374 // Check initializer is 32 bit integer constant.
7375 // If the initializer is taken from global variable, do not diagnose since
7376 // this has already been done when parsing the variable declaration.
7377 if (!Init->isConstantInitializer(S.Context, false))
7380 if (!SourceType->isIntegerType() ||
7381 32 != S.Context.getIntWidth(SourceType)) {
7382 S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
7387 llvm::APSInt Result;
7388 Init->EvaluateAsInt(Result, S.Context);
7389 const uint64_t SamplerValue = Result.getLimitedValue();
7390 // 32-bit value of sampler's initializer is interpreted as
7391 // bit-field with the following structure:
7392 // |unspecified|Filter|Addressing Mode| Normalized Coords|
7393 // |31 6|5 4|3 1| 0|
7394 // This structure corresponds to enum values of sampler properties
7395 // defined in SPIR spec v1.2 and also opencl-c.h
7396 unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
7397 unsigned FilterMode = (0x30 & SamplerValue) >> 4;
7398 if (FilterMode != 1 && FilterMode != 2)
7399 S.Diag(Kind.getLocation(),
7400 diag::warn_sampler_initializer_invalid_bits)
7402 if (AddressingMode > 4)
7403 S.Diag(Kind.getLocation(),
7404 diag::warn_sampler_initializer_invalid_bits)
7405 << "Addressing Mode";
7408 // Cases 1a, 2a and 2b
7409 // Insert cast from integer to sampler.
7410 CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy,
7411 CK_IntToOCLSampler);
7414 case SK_OCLZeroEvent: {
7415 assert(Step->Type->isEventT() &&
7416 "Event initialization on non-event type.");
7418 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
7420 CurInit.get()->getValueKind());
7423 case SK_OCLZeroQueue: {
7424 assert(Step->Type->isQueueT() &&
7425 "Event initialization on non queue type.");
7427 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
7429 CurInit.get()->getValueKind());
7435 // Diagnose non-fatal problems with the completed initialization.
7436 if (Entity.getKind() == InitializedEntity::EK_Member &&
7437 cast<FieldDecl>(Entity.getDecl())->isBitField())
7438 S.CheckBitFieldInitialization(Kind.getLocation(),
7439 cast<FieldDecl>(Entity.getDecl()),
7442 // Check for std::move on construction.
7443 if (const Expr *E = CurInit.get()) {
7444 CheckMoveOnConstruction(S, E,
7445 Entity.getKind() == InitializedEntity::EK_Result);
7451 /// Somewhere within T there is an uninitialized reference subobject.
7452 /// Dig it out and diagnose it.
7453 static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
7455 if (T->isReferenceType()) {
7456 S.Diag(Loc, diag::err_reference_without_init)
7457 << T.getNonReferenceType();
7461 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7462 if (!RD || !RD->hasUninitializedReferenceMember())
7465 for (const auto *FI : RD->fields()) {
7466 if (FI->isUnnamedBitfield())
7469 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
7470 S.Diag(Loc, diag::note_value_initialization_here) << RD;
7475 for (const auto &BI : RD->bases()) {
7476 if (DiagnoseUninitializedReference(S, BI.getLocStart(), BI.getType())) {
7477 S.Diag(Loc, diag::note_value_initialization_here) << RD;
7486 //===----------------------------------------------------------------------===//
7487 // Diagnose initialization failures
7488 //===----------------------------------------------------------------------===//
7490 /// Emit notes associated with an initialization that failed due to a
7491 /// "simple" conversion failure.
7492 static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
7494 QualType destType = entity.getType();
7495 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
7496 op->getType()->isObjCObjectPointerType()) {
7498 // Emit a possible note about the conversion failing because the
7499 // operand is a message send with a related result type.
7500 S.EmitRelatedResultTypeNote(op);
7502 // Emit a possible note about a return failing because we're
7503 // expecting a related result type.
7504 if (entity.getKind() == InitializedEntity::EK_Result)
7505 S.EmitRelatedResultTypeNoteForReturn(destType);
7509 static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
7510 InitListExpr *InitList) {
7511 QualType DestType = Entity.getType();
7514 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
7515 QualType ArrayType = S.Context.getConstantArrayType(
7517 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
7518 InitList->getNumInits()),
7519 clang::ArrayType::Normal, 0);
7520 InitializedEntity HiddenArray =
7521 InitializedEntity::InitializeTemporary(ArrayType);
7522 return diagnoseListInit(S, HiddenArray, InitList);
7525 if (DestType->isReferenceType()) {
7526 // A list-initialization failure for a reference means that we tried to
7527 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
7528 // inner initialization failed.
7529 QualType T = DestType->getAs<ReferenceType>()->getPointeeType();
7530 diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
7531 SourceLocation Loc = InitList->getLocStart();
7532 if (auto *D = Entity.getDecl())
7533 Loc = D->getLocation();
7534 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
7538 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
7539 /*VerifyOnly=*/false,
7540 /*TreatUnavailableAsInvalid=*/false);
7541 assert(DiagnoseInitList.HadError() &&
7542 "Inconsistent init list check result.");
7545 bool InitializationSequence::Diagnose(Sema &S,
7546 const InitializedEntity &Entity,
7547 const InitializationKind &Kind,
7548 ArrayRef<Expr *> Args) {
7552 QualType DestType = Entity.getType();
7554 case FK_TooManyInitsForReference:
7555 // FIXME: Customize for the initialized entity?
7557 // Dig out the reference subobject which is uninitialized and diagnose it.
7558 // If this is value-initialization, this could be nested some way within
7560 assert(Kind.getKind() == InitializationKind::IK_Value ||
7561 DestType->isReferenceType());
7563 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
7564 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
7566 } else // FIXME: diagnostic below could be better!
7567 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
7568 << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
7570 case FK_ParenthesizedListInitForReference:
7571 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
7572 << 1 << Entity.getType() << Args[0]->getSourceRange();
7575 case FK_ArrayNeedsInitList:
7576 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
7578 case FK_ArrayNeedsInitListOrStringLiteral:
7579 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
7581 case FK_ArrayNeedsInitListOrWideStringLiteral:
7582 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
7584 case FK_NarrowStringIntoWideCharArray:
7585 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
7587 case FK_WideStringIntoCharArray:
7588 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
7590 case FK_IncompatWideStringIntoWideChar:
7591 S.Diag(Kind.getLocation(),
7592 diag::err_array_init_incompat_wide_string_into_wchar);
7594 case FK_ArrayTypeMismatch:
7595 case FK_NonConstantArrayInit:
7596 S.Diag(Kind.getLocation(),
7597 (Failure == FK_ArrayTypeMismatch
7598 ? diag::err_array_init_different_type
7599 : diag::err_array_init_non_constant_array))
7600 << DestType.getNonReferenceType()
7601 << Args[0]->getType()
7602 << Args[0]->getSourceRange();
7605 case FK_VariableLengthArrayHasInitializer:
7606 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
7607 << Args[0]->getSourceRange();
7610 case FK_AddressOfOverloadFailed: {
7611 DeclAccessPair Found;
7612 S.ResolveAddressOfOverloadedFunction(Args[0],
7613 DestType.getNonReferenceType(),
7619 case FK_AddressOfUnaddressableFunction: {
7620 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(Args[0])->getDecl());
7621 S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
7622 Args[0]->getLocStart());
7626 case FK_ReferenceInitOverloadFailed:
7627 case FK_UserConversionOverloadFailed:
7628 switch (FailedOverloadResult) {
7630 if (Failure == FK_UserConversionOverloadFailed)
7631 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
7632 << Args[0]->getType() << DestType
7633 << Args[0]->getSourceRange();
7635 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
7636 << DestType << Args[0]->getType()
7637 << Args[0]->getSourceRange();
7639 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
7642 case OR_No_Viable_Function:
7643 if (!S.RequireCompleteType(Kind.getLocation(),
7644 DestType.getNonReferenceType(),
7645 diag::err_typecheck_nonviable_condition_incomplete,
7646 Args[0]->getType(), Args[0]->getSourceRange()))
7647 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
7648 << (Entity.getKind() == InitializedEntity::EK_Result)
7649 << Args[0]->getType() << Args[0]->getSourceRange()
7650 << DestType.getNonReferenceType();
7652 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
7656 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
7657 << Args[0]->getType() << DestType.getNonReferenceType()
7658 << Args[0]->getSourceRange();
7659 OverloadCandidateSet::iterator Best;
7660 OverloadingResult Ovl
7661 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
7662 if (Ovl == OR_Deleted) {
7663 S.NoteDeletedFunction(Best->Function);
7665 llvm_unreachable("Inconsistent overload resolution?");
7671 llvm_unreachable("Conversion did not fail!");
7675 case FK_NonConstLValueReferenceBindingToTemporary:
7676 if (isa<InitListExpr>(Args[0])) {
7677 S.Diag(Kind.getLocation(),
7678 diag::err_lvalue_reference_bind_to_initlist)
7679 << DestType.getNonReferenceType().isVolatileQualified()
7680 << DestType.getNonReferenceType()
7681 << Args[0]->getSourceRange();
7686 case FK_NonConstLValueReferenceBindingToUnrelated:
7687 S.Diag(Kind.getLocation(),
7688 Failure == FK_NonConstLValueReferenceBindingToTemporary
7689 ? diag::err_lvalue_reference_bind_to_temporary
7690 : diag::err_lvalue_reference_bind_to_unrelated)
7691 << DestType.getNonReferenceType().isVolatileQualified()
7692 << DestType.getNonReferenceType()
7693 << Args[0]->getType()
7694 << Args[0]->getSourceRange();
7697 case FK_NonConstLValueReferenceBindingToBitfield: {
7698 // We don't necessarily have an unambiguous source bit-field.
7699 FieldDecl *BitField = Args[0]->getSourceBitField();
7700 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
7701 << DestType.isVolatileQualified()
7702 << (BitField ? BitField->getDeclName() : DeclarationName())
7703 << (BitField != nullptr)
7704 << Args[0]->getSourceRange();
7706 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
7710 case FK_NonConstLValueReferenceBindingToVectorElement:
7711 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
7712 << DestType.isVolatileQualified()
7713 << Args[0]->getSourceRange();
7716 case FK_RValueReferenceBindingToLValue:
7717 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
7718 << DestType.getNonReferenceType() << Args[0]->getType()
7719 << Args[0]->getSourceRange();
7722 case FK_ReferenceInitDropsQualifiers: {
7723 QualType SourceType = Args[0]->getType();
7724 QualType NonRefType = DestType.getNonReferenceType();
7725 Qualifiers DroppedQualifiers =
7726 SourceType.getQualifiers() - NonRefType.getQualifiers();
7728 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
7731 << DroppedQualifiers.getCVRQualifiers()
7732 << Args[0]->getSourceRange();
7736 case FK_ReferenceInitFailed:
7737 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
7738 << DestType.getNonReferenceType()
7739 << Args[0]->isLValue()
7740 << Args[0]->getType()
7741 << Args[0]->getSourceRange();
7742 emitBadConversionNotes(S, Entity, Args[0]);
7745 case FK_ConversionFailed: {
7746 QualType FromType = Args[0]->getType();
7747 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
7748 << (int)Entity.getKind()
7750 << Args[0]->isLValue()
7752 << Args[0]->getSourceRange();
7753 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
7754 S.Diag(Kind.getLocation(), PDiag);
7755 emitBadConversionNotes(S, Entity, Args[0]);
7759 case FK_ConversionFromPropertyFailed:
7760 // No-op. This error has already been reported.
7763 case FK_TooManyInitsForScalar: {
7766 auto *InitList = dyn_cast<InitListExpr>(Args[0]);
7767 if (InitList && InitList->getNumInits() >= 1) {
7768 R = SourceRange(InitList->getInit(0)->getLocEnd(), InitList->getLocEnd());
7770 assert(Args.size() > 1 && "Expected multiple initializers!");
7771 R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
7774 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
7775 if (Kind.isCStyleOrFunctionalCast())
7776 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
7779 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
7780 << /*scalar=*/2 << R;
7784 case FK_ParenthesizedListInitForScalar:
7785 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
7786 << 0 << Entity.getType() << Args[0]->getSourceRange();
7789 case FK_ReferenceBindingToInitList:
7790 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
7791 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
7794 case FK_InitListBadDestinationType:
7795 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
7796 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
7799 case FK_ListConstructorOverloadFailed:
7800 case FK_ConstructorOverloadFailed: {
7801 SourceRange ArgsRange;
7803 ArgsRange = SourceRange(Args.front()->getLocStart(),
7804 Args.back()->getLocEnd());
7806 if (Failure == FK_ListConstructorOverloadFailed) {
7807 assert(Args.size() == 1 &&
7808 "List construction from other than 1 argument.");
7809 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
7810 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
7813 // FIXME: Using "DestType" for the entity we're printing is probably
7815 switch (FailedOverloadResult) {
7817 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
7818 << DestType << ArgsRange;
7819 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
7822 case OR_No_Viable_Function:
7823 if (Kind.getKind() == InitializationKind::IK_Default &&
7824 (Entity.getKind() == InitializedEntity::EK_Base ||
7825 Entity.getKind() == InitializedEntity::EK_Member) &&
7826 isa<CXXConstructorDecl>(S.CurContext)) {
7827 // This is implicit default initialization of a member or
7828 // base within a constructor. If no viable function was
7829 // found, notify the user that they need to explicitly
7830 // initialize this base/member.
7831 CXXConstructorDecl *Constructor
7832 = cast<CXXConstructorDecl>(S.CurContext);
7833 const CXXRecordDecl *InheritedFrom = nullptr;
7834 if (auto Inherited = Constructor->getInheritedConstructor())
7835 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
7836 if (Entity.getKind() == InitializedEntity::EK_Base) {
7837 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
7838 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
7839 << S.Context.getTypeDeclType(Constructor->getParent())
7844 RecordDecl *BaseDecl
7845 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
7847 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
7848 << S.Context.getTagDeclType(BaseDecl);
7850 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
7851 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
7852 << S.Context.getTypeDeclType(Constructor->getParent())
7856 S.Diag(Entity.getDecl()->getLocation(),
7857 diag::note_member_declared_at);
7859 if (const RecordType *Record
7860 = Entity.getType()->getAs<RecordType>())
7861 S.Diag(Record->getDecl()->getLocation(),
7862 diag::note_previous_decl)
7863 << S.Context.getTagDeclType(Record->getDecl());
7868 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
7869 << DestType << ArgsRange;
7870 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
7874 OverloadCandidateSet::iterator Best;
7875 OverloadingResult Ovl
7876 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
7877 if (Ovl != OR_Deleted) {
7878 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
7879 << true << DestType << ArgsRange;
7880 llvm_unreachable("Inconsistent overload resolution?");
7884 // If this is a defaulted or implicitly-declared function, then
7885 // it was implicitly deleted. Make it clear that the deletion was
7887 if (S.isImplicitlyDeleted(Best->Function))
7888 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
7889 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
7890 << DestType << ArgsRange;
7892 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
7893 << true << DestType << ArgsRange;
7895 S.NoteDeletedFunction(Best->Function);
7900 llvm_unreachable("Conversion did not fail!");
7905 case FK_DefaultInitOfConst:
7906 if (Entity.getKind() == InitializedEntity::EK_Member &&
7907 isa<CXXConstructorDecl>(S.CurContext)) {
7908 // This is implicit default-initialization of a const member in
7909 // a constructor. Complain that it needs to be explicitly
7911 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
7912 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
7913 << (Constructor->getInheritedConstructor() ? 2 :
7914 Constructor->isImplicit() ? 1 : 0)
7915 << S.Context.getTypeDeclType(Constructor->getParent())
7917 << Entity.getName();
7918 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
7919 << Entity.getName();
7921 S.Diag(Kind.getLocation(), diag::err_default_init_const)
7922 << DestType << (bool)DestType->getAs<RecordType>();
7927 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
7928 diag::err_init_incomplete_type);
7931 case FK_ListInitializationFailed: {
7932 // Run the init list checker again to emit diagnostics.
7933 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
7934 diagnoseListInit(S, Entity, InitList);
7938 case FK_PlaceholderType: {
7939 // FIXME: Already diagnosed!
7943 case FK_ExplicitConstructor: {
7944 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
7945 << Args[0]->getSourceRange();
7946 OverloadCandidateSet::iterator Best;
7947 OverloadingResult Ovl
7948 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
7950 assert(Ovl == OR_Success && "Inconsistent overload resolution");
7951 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
7952 S.Diag(CtorDecl->getLocation(),
7953 diag::note_explicit_ctor_deduction_guide_here) << false;
7958 PrintInitLocationNote(S, Entity);
7962 void InitializationSequence::dump(raw_ostream &OS) const {
7963 switch (SequenceKind) {
7964 case FailedSequence: {
7965 OS << "Failed sequence: ";
7967 case FK_TooManyInitsForReference:
7968 OS << "too many initializers for reference";
7971 case FK_ParenthesizedListInitForReference:
7972 OS << "parenthesized list init for reference";
7975 case FK_ArrayNeedsInitList:
7976 OS << "array requires initializer list";
7979 case FK_AddressOfUnaddressableFunction:
7980 OS << "address of unaddressable function was taken";
7983 case FK_ArrayNeedsInitListOrStringLiteral:
7984 OS << "array requires initializer list or string literal";
7987 case FK_ArrayNeedsInitListOrWideStringLiteral:
7988 OS << "array requires initializer list or wide string literal";
7991 case FK_NarrowStringIntoWideCharArray:
7992 OS << "narrow string into wide char array";
7995 case FK_WideStringIntoCharArray:
7996 OS << "wide string into char array";
7999 case FK_IncompatWideStringIntoWideChar:
8000 OS << "incompatible wide string into wide char array";
8003 case FK_ArrayTypeMismatch:
8004 OS << "array type mismatch";
8007 case FK_NonConstantArrayInit:
8008 OS << "non-constant array initializer";
8011 case FK_AddressOfOverloadFailed:
8012 OS << "address of overloaded function failed";
8015 case FK_ReferenceInitOverloadFailed:
8016 OS << "overload resolution for reference initialization failed";
8019 case FK_NonConstLValueReferenceBindingToTemporary:
8020 OS << "non-const lvalue reference bound to temporary";
8023 case FK_NonConstLValueReferenceBindingToBitfield:
8024 OS << "non-const lvalue reference bound to bit-field";
8027 case FK_NonConstLValueReferenceBindingToVectorElement:
8028 OS << "non-const lvalue reference bound to vector element";
8031 case FK_NonConstLValueReferenceBindingToUnrelated:
8032 OS << "non-const lvalue reference bound to unrelated type";
8035 case FK_RValueReferenceBindingToLValue:
8036 OS << "rvalue reference bound to an lvalue";
8039 case FK_ReferenceInitDropsQualifiers:
8040 OS << "reference initialization drops qualifiers";
8043 case FK_ReferenceInitFailed:
8044 OS << "reference initialization failed";
8047 case FK_ConversionFailed:
8048 OS << "conversion failed";
8051 case FK_ConversionFromPropertyFailed:
8052 OS << "conversion from property failed";
8055 case FK_TooManyInitsForScalar:
8056 OS << "too many initializers for scalar";
8059 case FK_ParenthesizedListInitForScalar:
8060 OS << "parenthesized list init for reference";
8063 case FK_ReferenceBindingToInitList:
8064 OS << "referencing binding to initializer list";
8067 case FK_InitListBadDestinationType:
8068 OS << "initializer list for non-aggregate, non-scalar type";
8071 case FK_UserConversionOverloadFailed:
8072 OS << "overloading failed for user-defined conversion";
8075 case FK_ConstructorOverloadFailed:
8076 OS << "constructor overloading failed";
8079 case FK_DefaultInitOfConst:
8080 OS << "default initialization of a const variable";
8084 OS << "initialization of incomplete type";
8087 case FK_ListInitializationFailed:
8088 OS << "list initialization checker failure";
8091 case FK_VariableLengthArrayHasInitializer:
8092 OS << "variable length array has an initializer";
8095 case FK_PlaceholderType:
8096 OS << "initializer expression isn't contextually valid";
8099 case FK_ListConstructorOverloadFailed:
8100 OS << "list constructor overloading failed";
8103 case FK_ExplicitConstructor:
8104 OS << "list copy initialization chose explicit constructor";
8111 case DependentSequence:
8112 OS << "Dependent sequence\n";
8115 case NormalSequence:
8116 OS << "Normal sequence: ";
8120 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
8121 if (S != step_begin()) {
8126 case SK_ResolveAddressOfOverloadedFunction:
8127 OS << "resolve address of overloaded function";
8130 case SK_CastDerivedToBaseRValue:
8131 OS << "derived-to-base (rvalue)";
8134 case SK_CastDerivedToBaseXValue:
8135 OS << "derived-to-base (xvalue)";
8138 case SK_CastDerivedToBaseLValue:
8139 OS << "derived-to-base (lvalue)";
8142 case SK_BindReference:
8143 OS << "bind reference to lvalue";
8146 case SK_BindReferenceToTemporary:
8147 OS << "bind reference to a temporary";
8151 OS << "final copy in class direct-initialization";
8154 case SK_ExtraneousCopyToTemporary:
8155 OS << "extraneous C++03 copy to temporary";
8158 case SK_UserConversion:
8159 OS << "user-defined conversion via " << *S->Function.Function;
8162 case SK_QualificationConversionRValue:
8163 OS << "qualification conversion (rvalue)";
8166 case SK_QualificationConversionXValue:
8167 OS << "qualification conversion (xvalue)";
8170 case SK_QualificationConversionLValue:
8171 OS << "qualification conversion (lvalue)";
8174 case SK_AtomicConversion:
8175 OS << "non-atomic-to-atomic conversion";
8178 case SK_LValueToRValue:
8179 OS << "load (lvalue to rvalue)";
8182 case SK_ConversionSequence:
8183 OS << "implicit conversion sequence (";
8184 S->ICS->dump(); // FIXME: use OS
8188 case SK_ConversionSequenceNoNarrowing:
8189 OS << "implicit conversion sequence with narrowing prohibited (";
8190 S->ICS->dump(); // FIXME: use OS
8194 case SK_ListInitialization:
8195 OS << "list aggregate initialization";
8198 case SK_UnwrapInitList:
8199 OS << "unwrap reference initializer list";
8202 case SK_RewrapInitList:
8203 OS << "rewrap reference initializer list";
8206 case SK_ConstructorInitialization:
8207 OS << "constructor initialization";
8210 case SK_ConstructorInitializationFromList:
8211 OS << "list initialization via constructor";
8214 case SK_ZeroInitialization:
8215 OS << "zero initialization";
8218 case SK_CAssignment:
8219 OS << "C assignment";
8223 OS << "string initialization";
8226 case SK_ObjCObjectConversion:
8227 OS << "Objective-C object conversion";
8230 case SK_ArrayLoopIndex:
8231 OS << "indexing for array initialization loop";
8234 case SK_ArrayLoopInit:
8235 OS << "array initialization loop";
8239 OS << "array initialization";
8242 case SK_GNUArrayInit:
8243 OS << "array initialization (GNU extension)";
8246 case SK_ParenthesizedArrayInit:
8247 OS << "parenthesized array initialization";
8250 case SK_PassByIndirectCopyRestore:
8251 OS << "pass by indirect copy and restore";
8254 case SK_PassByIndirectRestore:
8255 OS << "pass by indirect restore";
8258 case SK_ProduceObjCObject:
8259 OS << "Objective-C object retension";
8262 case SK_StdInitializerList:
8263 OS << "std::initializer_list from initializer list";
8266 case SK_StdInitializerListConstructorCall:
8267 OS << "list initialization from std::initializer_list";
8270 case SK_OCLSamplerInit:
8271 OS << "OpenCL sampler_t from integer constant";
8274 case SK_OCLZeroEvent:
8275 OS << "OpenCL event_t from zero";
8278 case SK_OCLZeroQueue:
8279 OS << "OpenCL queue_t from zero";
8283 OS << " [" << S->Type.getAsString() << ']';
8289 void InitializationSequence::dump() const {
8293 static void DiagnoseNarrowingInInitList(Sema &S,
8294 const ImplicitConversionSequence &ICS,
8295 QualType PreNarrowingType,
8296 QualType EntityType,
8297 const Expr *PostInit) {
8298 const StandardConversionSequence *SCS = nullptr;
8299 switch (ICS.getKind()) {
8300 case ImplicitConversionSequence::StandardConversion:
8301 SCS = &ICS.Standard;
8303 case ImplicitConversionSequence::UserDefinedConversion:
8304 SCS = &ICS.UserDefined.After;
8306 case ImplicitConversionSequence::AmbiguousConversion:
8307 case ImplicitConversionSequence::EllipsisConversion:
8308 case ImplicitConversionSequence::BadConversion:
8312 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
8313 APValue ConstantValue;
8314 QualType ConstantType;
8315 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
8317 case NK_Not_Narrowing:
8318 case NK_Dependent_Narrowing:
8319 // No narrowing occurred.
8322 case NK_Type_Narrowing:
8323 // This was a floating-to-integer conversion, which is always considered a
8324 // narrowing conversion even if the value is a constant and can be
8325 // represented exactly as an integer.
8326 S.Diag(PostInit->getLocStart(),
8327 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
8328 ? diag::warn_init_list_type_narrowing
8329 : diag::ext_init_list_type_narrowing)
8330 << PostInit->getSourceRange()
8331 << PreNarrowingType.getLocalUnqualifiedType()
8332 << EntityType.getLocalUnqualifiedType();
8335 case NK_Constant_Narrowing:
8336 // A constant value was narrowed.
8337 S.Diag(PostInit->getLocStart(),
8338 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
8339 ? diag::warn_init_list_constant_narrowing
8340 : diag::ext_init_list_constant_narrowing)
8341 << PostInit->getSourceRange()
8342 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
8343 << EntityType.getLocalUnqualifiedType();
8346 case NK_Variable_Narrowing:
8347 // A variable's value may have been narrowed.
8348 S.Diag(PostInit->getLocStart(),
8349 (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
8350 ? diag::warn_init_list_variable_narrowing
8351 : diag::ext_init_list_variable_narrowing)
8352 << PostInit->getSourceRange()
8353 << PreNarrowingType.getLocalUnqualifiedType()
8354 << EntityType.getLocalUnqualifiedType();
8358 SmallString<128> StaticCast;
8359 llvm::raw_svector_ostream OS(StaticCast);
8360 OS << "static_cast<";
8361 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
8362 // It's important to use the typedef's name if there is one so that the
8363 // fixit doesn't break code using types like int64_t.
8365 // FIXME: This will break if the typedef requires qualification. But
8366 // getQualifiedNameAsString() includes non-machine-parsable components.
8367 OS << *TT->getDecl();
8368 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
8369 OS << BT->getName(S.getLangOpts());
8371 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
8372 // with a broken cast.
8376 S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_silence)
8377 << PostInit->getSourceRange()
8378 << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
8379 << FixItHint::CreateInsertion(
8380 S.getLocForEndOfToken(PostInit->getLocEnd()), ")");
8383 //===----------------------------------------------------------------------===//
8384 // Initialization helper functions
8385 //===----------------------------------------------------------------------===//
8387 Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
8389 if (Init.isInvalid())
8392 Expr *InitE = Init.get();
8393 assert(InitE && "No initialization expression");
8395 InitializationKind Kind
8396 = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
8397 InitializationSequence Seq(*this, Entity, Kind, InitE);
8398 return !Seq.Failed();
8402 Sema::PerformCopyInitialization(const InitializedEntity &Entity,
8403 SourceLocation EqualLoc,
8405 bool TopLevelOfInitList,
8406 bool AllowExplicit) {
8407 if (Init.isInvalid())
8410 Expr *InitE = Init.get();
8411 assert(InitE && "No initialization expression?");
8413 if (EqualLoc.isInvalid())
8414 EqualLoc = InitE->getLocStart();
8416 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
8419 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
8421 // Prevent infinite recursion when performing parameter copy-initialization.
8422 const bool ShouldTrackCopy =
8423 Entity.isParameterKind() && Seq.isConstructorInitialization();
8424 if (ShouldTrackCopy) {
8425 if (llvm::find(CurrentParameterCopyTypes, Entity.getType()) !=
8426 CurrentParameterCopyTypes.end()) {
8427 Seq.SetOverloadFailure(
8428 InitializationSequence::FK_ConstructorOverloadFailed,
8429 OR_No_Viable_Function);
8431 // Try to give a meaningful diagnostic note for the problematic
8433 const auto LastStep = Seq.step_end() - 1;
8434 assert(LastStep->Kind ==
8435 InitializationSequence::SK_ConstructorInitialization);
8436 const FunctionDecl *Function = LastStep->Function.Function;
8438 llvm::find_if(Seq.getFailedCandidateSet(),
8439 [Function](const OverloadCandidate &Candidate) -> bool {
8440 return Candidate.Viable &&
8441 Candidate.Function == Function &&
8442 Candidate.Conversions.size() > 0;
8444 if (Candidate != Seq.getFailedCandidateSet().end() &&
8445 Function->getNumParams() > 0) {
8446 Candidate->Viable = false;
8447 Candidate->FailureKind = ovl_fail_bad_conversion;
8448 Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion,
8450 Function->getParamDecl(0)->getType());
8453 CurrentParameterCopyTypes.push_back(Entity.getType());
8456 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
8458 if (ShouldTrackCopy)
8459 CurrentParameterCopyTypes.pop_back();
8464 /// Determine whether RD is, or is derived from, a specialization of CTD.
8465 static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD,
8466 ClassTemplateDecl *CTD) {
8467 auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
8468 auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
8469 return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
8471 return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
8474 QualType Sema::DeduceTemplateSpecializationFromInitializer(
8475 TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
8476 const InitializationKind &Kind, MultiExprArg Inits) {
8477 auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
8478 TSInfo->getType()->getContainedDeducedType());
8479 assert(DeducedTST && "not a deduced template specialization type");
8481 // We can only perform deduction for class templates.
8482 auto TemplateName = DeducedTST->getTemplateName();
8484 dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
8486 Diag(Kind.getLocation(),
8487 diag::err_deduced_non_class_template_specialization_type)
8488 << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName;
8489 if (auto *TD = TemplateName.getAsTemplateDecl())
8490 Diag(TD->getLocation(), diag::note_template_decl_here);
8494 // Can't deduce from dependent arguments.
8495 if (Expr::hasAnyTypeDependentArguments(Inits))
8496 return Context.DependentTy;
8498 // FIXME: Perform "exact type" matching first, per CWG discussion?
8499 // Or implement this via an implied 'T(T) -> T' deduction guide?
8501 // FIXME: Do we need/want a std::initializer_list<T> special case?
8503 // Look up deduction guides, including those synthesized from constructors.
8505 // C++1z [over.match.class.deduct]p1:
8506 // A set of functions and function templates is formed comprising:
8507 // - For each constructor of the class template designated by the
8508 // template-name, a function template [...]
8509 // - For each deduction-guide, a function or function template [...]
8510 DeclarationNameInfo NameInfo(
8511 Context.DeclarationNames.getCXXDeductionGuideName(Template),
8512 TSInfo->getTypeLoc().getEndLoc());
8513 LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
8514 LookupQualifiedName(Guides, Template->getDeclContext());
8516 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
8517 // clear on this, but they're not found by name so access does not apply.
8518 Guides.suppressDiagnostics();
8520 // Figure out if this is list-initialization.
8521 InitListExpr *ListInit =
8522 (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
8523 ? dyn_cast<InitListExpr>(Inits[0])
8526 // C++1z [over.match.class.deduct]p1:
8527 // Initialization and overload resolution are performed as described in
8528 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
8529 // (as appropriate for the type of initialization performed) for an object
8530 // of a hypothetical class type, where the selected functions and function
8531 // templates are considered to be the constructors of that class type
8533 // Since we know we're initializing a class type of a type unrelated to that
8534 // of the initializer, this reduces to something fairly reasonable.
8535 OverloadCandidateSet Candidates(Kind.getLocation(),
8536 OverloadCandidateSet::CSK_Normal);
8537 OverloadCandidateSet::iterator Best;
8538 auto tryToResolveOverload =
8539 [&](bool OnlyListConstructors) -> OverloadingResult {
8540 Candidates.clear(OverloadCandidateSet::CSK_Normal);
8541 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
8542 NamedDecl *D = (*I)->getUnderlyingDecl();
8543 if (D->isInvalidDecl())
8546 auto *TD = dyn_cast<FunctionTemplateDecl>(D);
8547 auto *GD = dyn_cast_or_null<CXXDeductionGuideDecl>(
8548 TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
8552 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
8553 // For copy-initialization, the candidate functions are all the
8554 // converting constructors (12.3.1) of that class.
8555 // C++ [over.match.copy]p1: (non-list copy-initialization from class)
8556 // The converting constructors of T are candidate functions.
8557 if (Kind.isCopyInit() && !ListInit) {
8558 // Only consider converting constructors.
8559 if (GD->isExplicit())
8562 // When looking for a converting constructor, deduction guides that
8563 // could never be called with one argument are not interesting to
8565 if (GD->getMinRequiredArguments() > 1 ||
8566 (GD->getNumParams() == 0 && !GD->isVariadic()))
8570 // C++ [over.match.list]p1.1: (first phase list initialization)
8571 // Initially, the candidate functions are the initializer-list
8572 // constructors of the class T
8573 if (OnlyListConstructors && !isInitListConstructor(GD))
8576 // C++ [over.match.list]p1.2: (second phase list initialization)
8577 // the candidate functions are all the constructors of the class T
8578 // C++ [over.match.ctor]p1: (all other cases)
8579 // the candidate functions are all the constructors of the class of
8580 // the object being initialized
8582 // C++ [over.best.ics]p4:
8583 // When [...] the constructor [...] is a candidate by
8584 // - [over.match.copy] (in all cases)
8585 // FIXME: The "second phase of [over.match.list] case can also
8586 // theoretically happen here, but it's not clear whether we can
8587 // ever have a parameter of the right type.
8588 bool SuppressUserConversions = Kind.isCopyInit();
8591 AddTemplateOverloadCandidate(TD, I.getPair(), /*ExplicitArgs*/ nullptr,
8593 SuppressUserConversions);
8595 AddOverloadCandidate(GD, I.getPair(), Inits, Candidates,
8596 SuppressUserConversions);
8598 return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
8601 OverloadingResult Result = OR_No_Viable_Function;
8603 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
8604 // try initializer-list constructors.
8606 bool TryListConstructors = true;
8608 // Try list constructors unless the list is empty and the class has one or
8609 // more default constructors, in which case those constructors win.
8610 if (!ListInit->getNumInits()) {
8611 for (NamedDecl *D : Guides) {
8612 auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
8613 if (FD && FD->getMinRequiredArguments() == 0) {
8614 TryListConstructors = false;
8618 } else if (ListInit->getNumInits() == 1) {
8619 // C++ [over.match.class.deduct]:
8620 // As an exception, the first phase in [over.match.list] (considering
8621 // initializer-list constructors) is omitted if the initializer list
8622 // consists of a single expression of type cv U, where U is a
8623 // specialization of C or a class derived from a specialization of C.
8624 Expr *E = ListInit->getInit(0);
8625 auto *RD = E->getType()->getAsCXXRecordDecl();
8626 if (!isa<InitListExpr>(E) && RD &&
8627 isOrIsDerivedFromSpecializationOf(RD, Template))
8628 TryListConstructors = false;
8631 if (TryListConstructors)
8632 Result = tryToResolveOverload(/*OnlyListConstructor*/true);
8633 // Then unwrap the initializer list and try again considering all
8635 Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
8638 // If list-initialization fails, or if we're doing any other kind of
8639 // initialization, we (eventually) consider constructors.
8640 if (Result == OR_No_Viable_Function)
8641 Result = tryToResolveOverload(/*OnlyListConstructor*/false);
8645 Diag(Kind.getLocation(), diag::err_deduced_class_template_ctor_ambiguous)
8647 // FIXME: For list-initialization candidates, it'd usually be better to
8648 // list why they were not viable when given the initializer list itself as
8650 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Inits);
8653 case OR_No_Viable_Function: {
8654 CXXRecordDecl *Primary =
8655 cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
8657 isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary));
8658 Diag(Kind.getLocation(),
8659 Complete ? diag::err_deduced_class_template_ctor_no_viable
8660 : diag::err_deduced_class_template_incomplete)
8661 << TemplateName << !Guides.empty();
8662 Candidates.NoteCandidates(*this, OCD_AllCandidates, Inits);
8667 Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
8669 NoteDeletedFunction(Best->Function);
8674 // C++ [over.match.list]p1:
8675 // In copy-list-initialization, if an explicit constructor is chosen, the
8676 // initialization is ill-formed.
8677 if (Kind.isCopyInit() && ListInit &&
8678 cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
8679 bool IsDeductionGuide = !Best->Function->isImplicit();
8680 Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
8681 << TemplateName << IsDeductionGuide;
8682 Diag(Best->Function->getLocation(),
8683 diag::note_explicit_ctor_deduction_guide_here)
8684 << IsDeductionGuide;
8688 // Make sure we didn't select an unusable deduction guide, and mark it
8690 DiagnoseUseOfDecl(Best->Function, Kind.getLocation());
8691 MarkFunctionReferenced(Kind.getLocation(), Best->Function);
8695 // C++ [dcl.type.class.deduct]p1:
8696 // The placeholder is replaced by the return type of the function selected
8697 // by overload resolution for class template deduction.
8698 return SubstAutoType(TSInfo->getType(), Best->Function->getReturnType());