1 //===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements semantic analysis for initializers.
11 //===----------------------------------------------------------------------===//
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/DeclObjC.h"
15 #include "clang/AST/ExprCXX.h"
16 #include "clang/AST/ExprObjC.h"
17 #include "clang/AST/ExprOpenMP.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 /// 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,
52 SIF_UTF8StringIntoPlainChar,
53 SIF_PlainStringIntoUTF8Char,
57 /// Check whether the array of type AT can be initialized by the Init
58 /// expression by means of string initialization. Returns SIF_None if so,
59 /// otherwise returns a StringInitFailureKind that describes why the
60 /// initialization would not work.
61 static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
62 ASTContext &Context) {
63 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
66 // See if this is a string literal or @encode.
67 Init = Init->IgnoreParens();
69 // Handle @encode, which is a narrow string.
70 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
73 // Otherwise we can only handle string literals.
74 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
78 const QualType ElemTy =
79 Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
81 switch (SL->getKind()) {
82 case StringLiteral::UTF8:
83 // char8_t array can be initialized with a UTF-8 string.
84 if (ElemTy->isChar8Type())
87 case StringLiteral::Ascii:
88 // char array can be initialized with a narrow string.
89 // Only allow char x[] = "foo"; not char x[] = L"foo";
90 if (ElemTy->isCharType())
91 return (SL->getKind() == StringLiteral::UTF8 &&
92 Context.getLangOpts().Char8)
93 ? SIF_UTF8StringIntoPlainChar
95 if (ElemTy->isChar8Type())
96 return SIF_PlainStringIntoUTF8Char;
97 if (IsWideCharCompatible(ElemTy, Context))
98 return SIF_NarrowStringIntoWideChar;
100 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
101 // "An array with element type compatible with a qualified or unqualified
102 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
103 // string literal with the corresponding encoding prefix (L, u, or U,
104 // respectively), optionally enclosed in braces.
105 case StringLiteral::UTF16:
106 if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
108 if (ElemTy->isCharType() || ElemTy->isChar8Type())
109 return SIF_WideStringIntoChar;
110 if (IsWideCharCompatible(ElemTy, Context))
111 return SIF_IncompatWideStringIntoWideChar;
113 case StringLiteral::UTF32:
114 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
116 if (ElemTy->isCharType() || ElemTy->isChar8Type())
117 return SIF_WideStringIntoChar;
118 if (IsWideCharCompatible(ElemTy, Context))
119 return SIF_IncompatWideStringIntoWideChar;
121 case StringLiteral::Wide:
122 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
124 if (ElemTy->isCharType() || ElemTy->isChar8Type())
125 return SIF_WideStringIntoChar;
126 if (IsWideCharCompatible(ElemTy, Context))
127 return SIF_IncompatWideStringIntoWideChar;
131 llvm_unreachable("missed a StringLiteral kind?");
134 static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
135 ASTContext &Context) {
136 const ArrayType *arrayType = Context.getAsArrayType(declType);
139 return IsStringInit(init, arrayType, Context);
142 /// Update the type of a string literal, including any surrounding parentheses,
143 /// to match the type of the object which it is initializing.
144 static void updateStringLiteralType(Expr *E, QualType Ty) {
147 E->setValueKind(VK_RValue);
148 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E)) {
150 } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
151 E = PE->getSubExpr();
152 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
153 assert(UO->getOpcode() == UO_Extension);
154 E = UO->getSubExpr();
155 } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) {
156 E = GSE->getResultExpr();
157 } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) {
158 E = CE->getChosenSubExpr();
160 llvm_unreachable("unexpected expr in string literal init");
165 /// Fix a compound literal initializing an array so it's correctly marked
167 static void updateGNUCompoundLiteralRValue(Expr *E) {
169 E->setValueKind(VK_RValue);
170 if (isa<CompoundLiteralExpr>(E)) {
172 } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
173 E = PE->getSubExpr();
174 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
175 assert(UO->getOpcode() == UO_Extension);
176 E = UO->getSubExpr();
177 } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) {
178 E = GSE->getResultExpr();
179 } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) {
180 E = CE->getChosenSubExpr();
182 llvm_unreachable("unexpected expr in array compound literal init");
187 static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
189 // Get the length of the string as parsed.
190 auto *ConstantArrayTy =
191 cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
192 uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
194 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
195 // C99 6.7.8p14. We have an array of character type with unknown size
196 // being initialized to a string literal.
197 llvm::APInt ConstVal(32, StrLength);
198 // Return a new array type (C99 6.7.8p22).
199 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
201 ArrayType::Normal, 0);
202 updateStringLiteralType(Str, DeclT);
206 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
208 // We have an array of character type with known size. However,
209 // the size may be smaller or larger than the string we are initializing.
210 // FIXME: Avoid truncation for 64-bit length strings.
211 if (S.getLangOpts().CPlusPlus) {
212 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
213 // For Pascal strings it's OK to strip off the terminating null character,
214 // so the example below is valid:
216 // unsigned char a[2] = "\pa";
221 // [dcl.init.string]p2
222 if (StrLength > CAT->getSize().getZExtValue())
223 S.Diag(Str->getBeginLoc(),
224 diag::err_initializer_string_for_char_array_too_long)
225 << Str->getSourceRange();
228 if (StrLength-1 > CAT->getSize().getZExtValue())
229 S.Diag(Str->getBeginLoc(),
230 diag::ext_initializer_string_for_char_array_too_long)
231 << Str->getSourceRange();
234 // Set the type to the actual size that we are initializing. If we have
236 // char x[1] = "foo";
237 // then this will set the string literal's type to char[1].
238 updateStringLiteralType(Str, DeclT);
241 //===----------------------------------------------------------------------===//
242 // Semantic checking for initializer lists.
243 //===----------------------------------------------------------------------===//
247 /// Semantic checking for initializer lists.
249 /// The InitListChecker class contains a set of routines that each
250 /// handle the initialization of a certain kind of entity, e.g.,
251 /// arrays, vectors, struct/union types, scalars, etc. The
252 /// InitListChecker itself performs a recursive walk of the subobject
253 /// structure of the type to be initialized, while stepping through
254 /// the initializer list one element at a time. The IList and Index
255 /// parameters to each of the Check* routines contain the active
256 /// (syntactic) initializer list and the index into that initializer
257 /// list that represents the current initializer. Each routine is
258 /// responsible for moving that Index forward as it consumes elements.
260 /// Each Check* routine also has a StructuredList/StructuredIndex
261 /// arguments, which contains the current "structured" (semantic)
262 /// initializer list and the index into that initializer list where we
263 /// are copying initializers as we map them over to the semantic
264 /// list. Once we have completed our recursive walk of the subobject
265 /// structure, we will have constructed a full semantic initializer
268 /// C99 designators cause changes in the initializer list traversal,
269 /// because they make the initialization "jump" into a specific
270 /// subobject and then continue the initialization from that
271 /// point. CheckDesignatedInitializer() recursively steps into the
272 /// designated subobject and manages backing out the recursion to
273 /// initialize the subobjects after the one designated.
274 class InitListChecker {
277 bool VerifyOnly; // no diagnostics, no structure building
278 bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
279 llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
280 InitListExpr *FullyStructuredList;
282 void CheckImplicitInitList(const InitializedEntity &Entity,
283 InitListExpr *ParentIList, QualType T,
284 unsigned &Index, InitListExpr *StructuredList,
285 unsigned &StructuredIndex);
286 void CheckExplicitInitList(const InitializedEntity &Entity,
287 InitListExpr *IList, QualType &T,
288 InitListExpr *StructuredList,
289 bool TopLevelObject = false);
290 void CheckListElementTypes(const InitializedEntity &Entity,
291 InitListExpr *IList, QualType &DeclType,
292 bool SubobjectIsDesignatorContext,
294 InitListExpr *StructuredList,
295 unsigned &StructuredIndex,
296 bool TopLevelObject = false);
297 void CheckSubElementType(const InitializedEntity &Entity,
298 InitListExpr *IList, QualType ElemType,
300 InitListExpr *StructuredList,
301 unsigned &StructuredIndex);
302 void CheckComplexType(const InitializedEntity &Entity,
303 InitListExpr *IList, QualType DeclType,
305 InitListExpr *StructuredList,
306 unsigned &StructuredIndex);
307 void CheckScalarType(const InitializedEntity &Entity,
308 InitListExpr *IList, QualType DeclType,
310 InitListExpr *StructuredList,
311 unsigned &StructuredIndex);
312 void CheckReferenceType(const InitializedEntity &Entity,
313 InitListExpr *IList, QualType DeclType,
315 InitListExpr *StructuredList,
316 unsigned &StructuredIndex);
317 void CheckVectorType(const InitializedEntity &Entity,
318 InitListExpr *IList, QualType DeclType, unsigned &Index,
319 InitListExpr *StructuredList,
320 unsigned &StructuredIndex);
321 void CheckStructUnionTypes(const InitializedEntity &Entity,
322 InitListExpr *IList, QualType DeclType,
323 CXXRecordDecl::base_class_range Bases,
324 RecordDecl::field_iterator Field,
325 bool SubobjectIsDesignatorContext, unsigned &Index,
326 InitListExpr *StructuredList,
327 unsigned &StructuredIndex,
328 bool TopLevelObject = false);
329 void CheckArrayType(const InitializedEntity &Entity,
330 InitListExpr *IList, QualType &DeclType,
331 llvm::APSInt elementIndex,
332 bool SubobjectIsDesignatorContext, unsigned &Index,
333 InitListExpr *StructuredList,
334 unsigned &StructuredIndex);
335 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
336 InitListExpr *IList, DesignatedInitExpr *DIE,
338 QualType &CurrentObjectType,
339 RecordDecl::field_iterator *NextField,
340 llvm::APSInt *NextElementIndex,
342 InitListExpr *StructuredList,
343 unsigned &StructuredIndex,
344 bool FinishSubobjectInit,
345 bool TopLevelObject);
346 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
347 QualType CurrentObjectType,
348 InitListExpr *StructuredList,
349 unsigned StructuredIndex,
350 SourceRange InitRange,
351 bool IsFullyOverwritten = false);
352 void UpdateStructuredListElement(InitListExpr *StructuredList,
353 unsigned &StructuredIndex,
355 int numArrayElements(QualType DeclType);
356 int numStructUnionElements(QualType DeclType);
358 static ExprResult PerformEmptyInit(Sema &SemaRef,
360 const InitializedEntity &Entity,
362 bool TreatUnavailableAsInvalid);
364 // Explanation on the "FillWithNoInit" mode:
366 // Assume we have the following definitions (Case#1):
367 // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
368 // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
370 // l.lp.x[1][0..1] should not be filled with implicit initializers because the
371 // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
373 // But if we have (Case#2):
374 // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
376 // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
377 // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
379 // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
380 // in the InitListExpr, the "holes" in Case#1 are filled not with empty
381 // initializers but with special "NoInitExpr" place holders, which tells the
382 // CodeGen not to generate any initializers for these parts.
383 void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
384 const InitializedEntity &ParentEntity,
385 InitListExpr *ILE, bool &RequiresSecondPass,
386 bool FillWithNoInit);
387 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
388 const InitializedEntity &ParentEntity,
389 InitListExpr *ILE, bool &RequiresSecondPass,
390 bool FillWithNoInit = false);
391 void FillInEmptyInitializations(const InitializedEntity &Entity,
392 InitListExpr *ILE, bool &RequiresSecondPass,
393 InitListExpr *OuterILE, unsigned OuterIndex,
394 bool FillWithNoInit = false);
395 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
396 Expr *InitExpr, FieldDecl *Field,
397 bool TopLevelObject);
398 void CheckEmptyInitializable(const InitializedEntity &Entity,
402 InitListChecker(Sema &S, const InitializedEntity &Entity,
403 InitListExpr *IL, QualType &T, bool VerifyOnly,
404 bool TreatUnavailableAsInvalid);
405 bool HadError() { return hadError; }
407 // Retrieves the fully-structured initializer list used for
408 // semantic analysis and code generation.
409 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
412 } // end anonymous namespace
414 ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef,
416 const InitializedEntity &Entity,
418 bool TreatUnavailableAsInvalid) {
419 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
421 MultiExprArg SubInit;
423 InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
425 // C++ [dcl.init.aggr]p7:
426 // If there are fewer initializer-clauses in the list than there are
427 // members in the aggregate, then each member not explicitly initialized
429 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
430 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
433 // shall be initialized [...] from an empty initializer list.
435 // We apply the resolution of this DR to C++11 but not C++98, since C++98
436 // does not have useful semantics for initialization from an init list.
437 // We treat this as copy-initialization, because aggregate initialization
438 // always performs copy-initialization on its elements.
440 // Only do this if we're initializing a class type, to avoid filling in
441 // the initializer list where possible.
442 InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context)
443 InitListExpr(SemaRef.Context, Loc, None, Loc);
444 InitExpr->setType(SemaRef.Context.VoidTy);
446 Kind = InitializationKind::CreateCopy(Loc, Loc);
449 // shall be value-initialized.
452 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
453 // libstdc++4.6 marks the vector default constructor as explicit in
454 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
455 // stlport does so too. Look for std::__debug for libstdc++, and for
456 // std:: for stlport. This is effectively a compiler-side implementation of
458 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
459 InitializationSequence::FK_ExplicitConstructor) {
460 OverloadCandidateSet::iterator Best;
461 OverloadingResult O =
462 InitSeq.getFailedCandidateSet()
463 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
465 assert(O == OR_Success && "Inconsistent overload resolution");
466 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
467 CXXRecordDecl *R = CtorDecl->getParent();
469 if (CtorDecl->getMinRequiredArguments() == 0 &&
470 CtorDecl->isExplicit() && R->getDeclName() &&
471 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
472 bool IsInStd = false;
473 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
474 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
475 if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
479 if (IsInStd && llvm::StringSwitch<bool>(R->getName())
480 .Cases("basic_string", "deque", "forward_list", true)
481 .Cases("list", "map", "multimap", "multiset", true)
482 .Cases("priority_queue", "queue", "set", "stack", true)
483 .Cases("unordered_map", "unordered_set", "vector", true)
485 InitSeq.InitializeFrom(
487 InitializationKind::CreateValue(Loc, Loc, Loc, true),
488 MultiExprArg(), /*TopLevelOfInitList=*/false,
489 TreatUnavailableAsInvalid);
490 // Emit a warning for this. System header warnings aren't shown
491 // by default, but people working on system headers should see it.
493 SemaRef.Diag(CtorDecl->getLocation(),
494 diag::warn_invalid_initializer_from_system_header);
495 if (Entity.getKind() == InitializedEntity::EK_Member)
496 SemaRef.Diag(Entity.getDecl()->getLocation(),
497 diag::note_used_in_initialization_here);
498 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
499 SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
506 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
507 if (Entity.getKind() == InitializedEntity::EK_Member)
508 SemaRef.Diag(Entity.getDecl()->getLocation(),
509 diag::note_in_omitted_aggregate_initializer)
510 << /*field*/1 << Entity.getDecl();
511 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
512 bool IsTrailingArrayNewMember =
513 Entity.getParent() &&
514 Entity.getParent()->isVariableLengthArrayNew();
515 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
516 << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
517 << Entity.getElementIndex();
523 return VerifyOnly ? ExprResult(static_cast<Expr *>(nullptr))
524 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
527 void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
528 SourceLocation Loc) {
530 "CheckEmptyInitializable is only inteded for verification mode.");
531 if (PerformEmptyInit(SemaRef, Loc, Entity, /*VerifyOnly*/true,
532 TreatUnavailableAsInvalid).isInvalid())
536 void InitListChecker::FillInEmptyInitForBase(
537 unsigned Init, const CXXBaseSpecifier &Base,
538 const InitializedEntity &ParentEntity, InitListExpr *ILE,
539 bool &RequiresSecondPass, bool FillWithNoInit) {
540 assert(Init < ILE->getNumInits() && "should have been expanded");
542 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
543 SemaRef.Context, &Base, false, &ParentEntity);
545 if (!ILE->getInit(Init)) {
546 ExprResult BaseInit =
548 ? new (SemaRef.Context) NoInitExpr(Base.getType())
549 : PerformEmptyInit(SemaRef, ILE->getEndLoc(), BaseEntity,
550 /*VerifyOnly*/ false, TreatUnavailableAsInvalid);
551 if (BaseInit.isInvalid()) {
556 ILE->setInit(Init, BaseInit.getAs<Expr>());
557 } else if (InitListExpr *InnerILE =
558 dyn_cast<InitListExpr>(ILE->getInit(Init))) {
559 FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,
560 ILE, Init, FillWithNoInit);
561 } else if (DesignatedInitUpdateExpr *InnerDIUE =
562 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
563 FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
564 RequiresSecondPass, ILE, Init,
565 /*FillWithNoInit =*/true);
569 void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
570 const InitializedEntity &ParentEntity,
572 bool &RequiresSecondPass,
573 bool FillWithNoInit) {
574 SourceLocation Loc = ILE->getEndLoc();
575 unsigned NumInits = ILE->getNumInits();
576 InitializedEntity MemberEntity
577 = InitializedEntity::InitializeMember(Field, &ParentEntity);
579 if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
580 if (!RType->getDecl()->isUnion())
581 assert(Init < NumInits && "This ILE should have been expanded");
583 if (Init >= NumInits || !ILE->getInit(Init)) {
584 if (FillWithNoInit) {
585 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
587 ILE->setInit(Init, Filler);
589 ILE->updateInit(SemaRef.Context, Init, Filler);
592 // C++1y [dcl.init.aggr]p7:
593 // If there are fewer initializer-clauses in the list than there are
594 // members in the aggregate, then each member not explicitly initialized
595 // shall be initialized from its brace-or-equal-initializer [...]
596 if (Field->hasInClassInitializer()) {
597 ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
598 if (DIE.isInvalid()) {
602 SemaRef.checkInitializerLifetime(MemberEntity, DIE.get());
604 ILE->setInit(Init, DIE.get());
606 ILE->updateInit(SemaRef.Context, Init, DIE.get());
607 RequiresSecondPass = true;
612 if (Field->getType()->isReferenceType()) {
613 // C++ [dcl.init.aggr]p9:
614 // If an incomplete or empty initializer-list leaves a
615 // member of reference type uninitialized, the program is
617 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
619 << ILE->getSyntacticForm()->getSourceRange();
620 SemaRef.Diag(Field->getLocation(),
621 diag::note_uninit_reference_member);
626 ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
628 TreatUnavailableAsInvalid);
629 if (MemberInit.isInvalid()) {
636 } else if (Init < NumInits) {
637 ILE->setInit(Init, MemberInit.getAs<Expr>());
638 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
639 // Empty initialization requires a constructor call, so
640 // extend the initializer list to include the constructor
641 // call and make a note that we'll need to take another pass
642 // through the initializer list.
643 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
644 RequiresSecondPass = true;
646 } else if (InitListExpr *InnerILE
647 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
648 FillInEmptyInitializations(MemberEntity, InnerILE,
649 RequiresSecondPass, ILE, Init, FillWithNoInit);
650 else if (DesignatedInitUpdateExpr *InnerDIUE
651 = dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init)))
652 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
653 RequiresSecondPass, ILE, Init,
654 /*FillWithNoInit =*/true);
657 /// Recursively replaces NULL values within the given initializer list
658 /// with expressions that perform value-initialization of the
659 /// appropriate type, and finish off the InitListExpr formation.
661 InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
663 bool &RequiresSecondPass,
664 InitListExpr *OuterILE,
666 bool FillWithNoInit) {
667 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
668 "Should not have void type");
670 // If this is a nested initializer list, we might have changed its contents
671 // (and therefore some of its properties, such as instantiation-dependence)
672 // while filling it in. Inform the outer initializer list so that its state
673 // can be updated to match.
674 // FIXME: We should fully build the inner initializers before constructing
675 // the outer InitListExpr instead of mutating AST nodes after they have
676 // been used as subexpressions of other nodes.
677 struct UpdateOuterILEWithUpdatedInit {
680 ~UpdateOuterILEWithUpdatedInit() {
682 Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
684 } UpdateOuterRAII = {OuterILE, OuterIndex};
686 // A transparent ILE is not performing aggregate initialization and should
688 if (ILE->isTransparent())
691 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
692 const RecordDecl *RDecl = RType->getDecl();
693 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
694 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
695 Entity, ILE, RequiresSecondPass, FillWithNoInit);
696 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
697 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
698 for (auto *Field : RDecl->fields()) {
699 if (Field->hasInClassInitializer()) {
700 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
706 // The fields beyond ILE->getNumInits() are default initialized, so in
707 // order to leave them uninitialized, the ILE is expanded and the extra
708 // fields are then filled with NoInitExpr.
709 unsigned NumElems = numStructUnionElements(ILE->getType());
710 if (RDecl->hasFlexibleArrayMember())
712 if (ILE->getNumInits() < NumElems)
713 ILE->resizeInits(SemaRef.Context, NumElems);
717 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
718 for (auto &Base : CXXRD->bases()) {
722 FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
728 for (auto *Field : RDecl->fields()) {
729 if (Field->isUnnamedBitfield())
735 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
742 // Only look at the first initialization of a union.
743 if (RDecl->isUnion())
751 QualType ElementType;
753 InitializedEntity ElementEntity = Entity;
754 unsigned NumInits = ILE->getNumInits();
755 unsigned NumElements = NumInits;
756 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
757 ElementType = AType->getElementType();
758 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
759 NumElements = CAType->getSize().getZExtValue();
760 // For an array new with an unknown bound, ask for one additional element
761 // in order to populate the array filler.
762 if (Entity.isVariableLengthArrayNew())
764 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
766 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
767 ElementType = VType->getElementType();
768 NumElements = VType->getNumElements();
769 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
772 ElementType = ILE->getType();
774 for (unsigned Init = 0; Init != NumElements; ++Init) {
778 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
779 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
780 ElementEntity.setElementIndex(Init);
782 if (Init >= NumInits && ILE->hasArrayFiller())
785 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
786 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
787 ILE->setInit(Init, ILE->getArrayFiller());
788 else if (!InitExpr && !ILE->hasArrayFiller()) {
789 Expr *Filler = nullptr;
792 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
794 ExprResult ElementInit =
795 PerformEmptyInit(SemaRef, ILE->getEndLoc(), ElementEntity,
796 /*VerifyOnly*/ false, TreatUnavailableAsInvalid);
797 if (ElementInit.isInvalid()) {
802 Filler = ElementInit.getAs<Expr>();
807 } else if (Init < NumInits) {
808 // For arrays, just set the expression used for value-initialization
809 // of the "holes" in the array.
810 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
811 ILE->setArrayFiller(Filler);
813 ILE->setInit(Init, Filler);
815 // For arrays, just set the expression used for value-initialization
816 // of the rest of elements and exit.
817 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
818 ILE->setArrayFiller(Filler);
822 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
823 // Empty initialization requires a constructor call, so
824 // extend the initializer list to include the constructor
825 // call and make a note that we'll need to take another pass
826 // through the initializer list.
827 ILE->updateInit(SemaRef.Context, Init, Filler);
828 RequiresSecondPass = true;
831 } else if (InitListExpr *InnerILE
832 = dyn_cast_or_null<InitListExpr>(InitExpr))
833 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
834 ILE, Init, FillWithNoInit);
835 else if (DesignatedInitUpdateExpr *InnerDIUE
836 = dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr))
837 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
838 RequiresSecondPass, ILE, Init,
839 /*FillWithNoInit =*/true);
843 InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
844 InitListExpr *IL, QualType &T,
846 bool TreatUnavailableAsInvalid)
847 : SemaRef(S), VerifyOnly(VerifyOnly),
848 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid) {
849 // FIXME: Check that IL isn't already the semantic form of some other
850 // InitListExpr. If it is, we'd create a broken AST.
854 FullyStructuredList =
855 getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
856 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
857 /*TopLevelObject=*/true);
859 if (!hadError && !VerifyOnly) {
860 bool RequiresSecondPass = false;
861 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
862 /*OuterILE=*/nullptr, /*OuterIndex=*/0);
863 if (RequiresSecondPass && !hadError)
864 FillInEmptyInitializations(Entity, FullyStructuredList,
865 RequiresSecondPass, nullptr, 0);
869 int InitListChecker::numArrayElements(QualType DeclType) {
870 // FIXME: use a proper constant
871 int maxElements = 0x7FFFFFFF;
872 if (const ConstantArrayType *CAT =
873 SemaRef.Context.getAsConstantArrayType(DeclType)) {
874 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
879 int InitListChecker::numStructUnionElements(QualType DeclType) {
880 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
881 int InitializableMembers = 0;
882 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
883 InitializableMembers += CXXRD->getNumBases();
884 for (const auto *Field : structDecl->fields())
885 if (!Field->isUnnamedBitfield())
886 ++InitializableMembers;
888 if (structDecl->isUnion())
889 return std::min(InitializableMembers, 1);
890 return InitializableMembers - structDecl->hasFlexibleArrayMember();
893 /// Determine whether Entity is an entity for which it is idiomatic to elide
894 /// the braces in aggregate initialization.
895 static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) {
896 // Recursive initialization of the one and only field within an aggregate
897 // class is considered idiomatic. This case arises in particular for
898 // initialization of std::array, where the C++ standard suggests the idiom of
900 // std::array<T, N> arr = {1, 2, 3};
902 // (where std::array is an aggregate struct containing a single array field.
904 // FIXME: Should aggregate initialization of a struct with a single
905 // base class and no members also suppress the warning?
906 if (Entity.getKind() != InitializedEntity::EK_Member || !Entity.getParent())
910 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
911 if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD))
912 if (CXXRD->getNumBases())
915 auto FieldIt = ParentRD->field_begin();
916 assert(FieldIt != ParentRD->field_end() &&
917 "no fields but have initializer for member?");
918 return ++FieldIt == ParentRD->field_end();
921 /// Check whether the range of the initializer \p ParentIList from element
922 /// \p Index onwards can be used to initialize an object of type \p T. Update
923 /// \p Index to indicate how many elements of the list were consumed.
925 /// This also fills in \p StructuredList, from element \p StructuredIndex
926 /// onwards, with the fully-braced, desugared form of the initialization.
927 void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
928 InitListExpr *ParentIList,
929 QualType T, unsigned &Index,
930 InitListExpr *StructuredList,
931 unsigned &StructuredIndex) {
934 if (T->isArrayType())
935 maxElements = numArrayElements(T);
936 else if (T->isRecordType())
937 maxElements = numStructUnionElements(T);
938 else if (T->isVectorType())
939 maxElements = T->getAs<VectorType>()->getNumElements();
941 llvm_unreachable("CheckImplicitInitList(): Illegal type");
943 if (maxElements == 0) {
945 SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(),
946 diag::err_implicit_empty_initializer);
952 // Build a structured initializer list corresponding to this subobject.
953 InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(
954 ParentIList, Index, T, StructuredList, StructuredIndex,
955 SourceRange(ParentIList->getInit(Index)->getBeginLoc(),
956 ParentIList->getSourceRange().getEnd()));
957 unsigned StructuredSubobjectInitIndex = 0;
959 // Check the element types and build the structural subobject.
960 unsigned StartIndex = Index;
961 CheckListElementTypes(Entity, ParentIList, T,
962 /*SubobjectIsDesignatorContext=*/false, Index,
963 StructuredSubobjectInitList,
964 StructuredSubobjectInitIndex);
967 StructuredSubobjectInitList->setType(T);
969 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
970 // Update the structured sub-object initializer so that it's ending
971 // range corresponds with the end of the last initializer it used.
972 if (EndIndex < ParentIList->getNumInits() &&
973 ParentIList->getInit(EndIndex)) {
974 SourceLocation EndLoc
975 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
976 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
979 // Complain about missing braces.
980 if ((T->isArrayType() || T->isRecordType()) &&
981 !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
982 !isIdiomaticBraceElisionEntity(Entity)) {
983 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
984 diag::warn_missing_braces)
985 << StructuredSubobjectInitList->getSourceRange()
986 << FixItHint::CreateInsertion(
987 StructuredSubobjectInitList->getBeginLoc(), "{")
988 << FixItHint::CreateInsertion(
989 SemaRef.getLocForEndOfToken(
990 StructuredSubobjectInitList->getEndLoc()),
994 // Warn if this type won't be an aggregate in future versions of C++.
995 auto *CXXRD = T->getAsCXXRecordDecl();
996 if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
997 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
998 diag::warn_cxx2a_compat_aggregate_init_with_ctors)
999 << StructuredSubobjectInitList->getSourceRange() << T;
1004 /// Warn that \p Entity was of scalar type and was initialized by a
1005 /// single-element braced initializer list.
1006 static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
1007 SourceRange Braces) {
1008 // Don't warn during template instantiation. If the initialization was
1009 // non-dependent, we warned during the initial parse; otherwise, the
1010 // type might not be scalar in some uses of the template.
1011 if (S.inTemplateInstantiation())
1014 unsigned DiagID = 0;
1016 switch (Entity.getKind()) {
1017 case InitializedEntity::EK_VectorElement:
1018 case InitializedEntity::EK_ComplexElement:
1019 case InitializedEntity::EK_ArrayElement:
1020 case InitializedEntity::EK_Parameter:
1021 case InitializedEntity::EK_Parameter_CF_Audited:
1022 case InitializedEntity::EK_Result:
1023 // Extra braces here are suspicious.
1024 DiagID = diag::warn_braces_around_scalar_init;
1027 case InitializedEntity::EK_Member:
1028 // Warn on aggregate initialization but not on ctor init list or
1029 // default member initializer.
1030 if (Entity.getParent())
1031 DiagID = diag::warn_braces_around_scalar_init;
1034 case InitializedEntity::EK_Variable:
1035 case InitializedEntity::EK_LambdaCapture:
1036 // No warning, might be direct-list-initialization.
1037 // FIXME: Should we warn for copy-list-initialization in these cases?
1040 case InitializedEntity::EK_New:
1041 case InitializedEntity::EK_Temporary:
1042 case InitializedEntity::EK_CompoundLiteralInit:
1043 // No warning, braces are part of the syntax of the underlying construct.
1046 case InitializedEntity::EK_RelatedResult:
1047 // No warning, we already warned when initializing the result.
1050 case InitializedEntity::EK_Exception:
1051 case InitializedEntity::EK_Base:
1052 case InitializedEntity::EK_Delegating:
1053 case InitializedEntity::EK_BlockElement:
1054 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
1055 case InitializedEntity::EK_Binding:
1056 case InitializedEntity::EK_StmtExprResult:
1057 llvm_unreachable("unexpected braced scalar init");
1061 S.Diag(Braces.getBegin(), DiagID)
1063 << FixItHint::CreateRemoval(Braces.getBegin())
1064 << FixItHint::CreateRemoval(Braces.getEnd());
1068 /// Check whether the initializer \p IList (that was written with explicit
1069 /// braces) can be used to initialize an object of type \p T.
1071 /// This also fills in \p StructuredList with the fully-braced, desugared
1072 /// form of the initialization.
1073 void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
1074 InitListExpr *IList, QualType &T,
1075 InitListExpr *StructuredList,
1076 bool TopLevelObject) {
1078 SyntacticToSemantic[IList] = StructuredList;
1079 StructuredList->setSyntacticForm(IList);
1082 unsigned Index = 0, StructuredIndex = 0;
1083 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
1084 Index, StructuredList, StructuredIndex, TopLevelObject);
1086 QualType ExprTy = T;
1087 if (!ExprTy->isArrayType())
1088 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
1089 IList->setType(ExprTy);
1090 StructuredList->setType(ExprTy);
1095 if (Index < IList->getNumInits()) {
1096 // We have leftover initializers
1098 if (SemaRef.getLangOpts().CPlusPlus ||
1099 (SemaRef.getLangOpts().OpenCL &&
1100 IList->getType()->isVectorType())) {
1106 if (StructuredIndex == 1 &&
1107 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1109 unsigned DK = diag::ext_excess_initializers_in_char_array_initializer;
1110 if (SemaRef.getLangOpts().CPlusPlus) {
1111 DK = diag::err_excess_initializers_in_char_array_initializer;
1115 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1116 << IList->getInit(Index)->getSourceRange();
1117 } else if (!T->isIncompleteType()) {
1118 // Don't complain for incomplete types, since we'll get an error
1120 QualType CurrentObjectType = StructuredList->getType();
1122 CurrentObjectType->isArrayType()? 0 :
1123 CurrentObjectType->isVectorType()? 1 :
1124 CurrentObjectType->isScalarType()? 2 :
1125 CurrentObjectType->isUnionType()? 3 :
1128 unsigned DK = diag::ext_excess_initializers;
1129 if (SemaRef.getLangOpts().CPlusPlus) {
1130 DK = diag::err_excess_initializers;
1133 if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
1134 DK = diag::err_excess_initializers;
1138 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1139 << initKind << IList->getInit(Index)->getSourceRange();
1144 if (T->isScalarType() && IList->getNumInits() == 1 &&
1145 !isa<InitListExpr>(IList->getInit(0)))
1146 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
1148 // Warn if this is a class type that won't be an aggregate in future
1150 auto *CXXRD = T->getAsCXXRecordDecl();
1151 if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1152 // Don't warn if there's an equivalent default constructor that would be
1154 bool HasEquivCtor = false;
1155 if (IList->getNumInits() == 0) {
1156 auto *CD = SemaRef.LookupDefaultConstructor(CXXRD);
1157 HasEquivCtor = CD && !CD->isDeleted();
1160 if (!HasEquivCtor) {
1161 SemaRef.Diag(IList->getBeginLoc(),
1162 diag::warn_cxx2a_compat_aggregate_init_with_ctors)
1163 << IList->getSourceRange() << T;
1169 void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
1170 InitListExpr *IList,
1172 bool SubobjectIsDesignatorContext,
1174 InitListExpr *StructuredList,
1175 unsigned &StructuredIndex,
1176 bool TopLevelObject) {
1177 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1178 // Explicitly braced initializer for complex type can be real+imaginary
1180 CheckComplexType(Entity, IList, DeclType, Index,
1181 StructuredList, StructuredIndex);
1182 } else if (DeclType->isScalarType()) {
1183 CheckScalarType(Entity, IList, DeclType, Index,
1184 StructuredList, StructuredIndex);
1185 } else if (DeclType->isVectorType()) {
1186 CheckVectorType(Entity, IList, DeclType, Index,
1187 StructuredList, StructuredIndex);
1188 } else if (DeclType->isRecordType()) {
1189 assert(DeclType->isAggregateType() &&
1190 "non-aggregate records should be handed in CheckSubElementType");
1191 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1193 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
1194 CXXRecordDecl::base_class_iterator());
1195 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1196 Bases = CXXRD->bases();
1197 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1198 SubobjectIsDesignatorContext, Index, StructuredList,
1199 StructuredIndex, TopLevelObject);
1200 } else if (DeclType->isArrayType()) {
1202 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1204 CheckArrayType(Entity, IList, DeclType, Zero,
1205 SubobjectIsDesignatorContext, Index,
1206 StructuredList, StructuredIndex);
1207 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1208 // This type is invalid, issue a diagnostic.
1211 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1214 } else if (DeclType->isReferenceType()) {
1215 CheckReferenceType(Entity, IList, DeclType, Index,
1216 StructuredList, StructuredIndex);
1217 } else if (DeclType->isObjCObjectType()) {
1219 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType;
1221 } else if (DeclType->isOCLIntelSubgroupAVCType()) {
1222 // Checks for scalar type are sufficient for these types too.
1223 CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1227 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1233 void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
1234 InitListExpr *IList,
1237 InitListExpr *StructuredList,
1238 unsigned &StructuredIndex) {
1239 Expr *expr = IList->getInit(Index);
1241 if (ElemType->isReferenceType())
1242 return CheckReferenceType(Entity, IList, ElemType, Index,
1243 StructuredList, StructuredIndex);
1245 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
1246 if (SubInitList->getNumInits() == 1 &&
1247 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1249 expr = SubInitList->getInit(0);
1250 } else if (!SemaRef.getLangOpts().CPlusPlus) {
1251 InitListExpr *InnerStructuredList
1252 = getStructuredSubobjectInit(IList, Index, ElemType,
1253 StructuredList, StructuredIndex,
1254 SubInitList->getSourceRange(), true);
1255 CheckExplicitInitList(Entity, SubInitList, ElemType,
1256 InnerStructuredList);
1258 if (!hadError && !VerifyOnly) {
1259 bool RequiresSecondPass = false;
1260 FillInEmptyInitializations(Entity, InnerStructuredList,
1261 RequiresSecondPass, StructuredList,
1263 if (RequiresSecondPass && !hadError)
1264 FillInEmptyInitializations(Entity, InnerStructuredList,
1265 RequiresSecondPass, StructuredList,
1272 // C++ initialization is handled later.
1273 } else if (isa<ImplicitValueInitExpr>(expr)) {
1274 // This happens during template instantiation when we see an InitListExpr
1275 // that we've already checked once.
1276 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
1277 "found implicit initialization for the wrong type");
1279 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1284 if (SemaRef.getLangOpts().CPlusPlus) {
1285 // C++ [dcl.init.aggr]p2:
1286 // Each member is copy-initialized from the corresponding
1287 // initializer-clause.
1289 // FIXME: Better EqualLoc?
1290 InitializationKind Kind =
1291 InitializationKind::CreateCopy(expr->getBeginLoc(), SourceLocation());
1293 // Vector elements can be initialized from other vectors in which case
1294 // we need initialization entity with a type of a vector (and not a vector
1295 // element!) initializing multiple vector elements.
1297 (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType())
1298 ? InitializedEntity::InitializeTemporary(ElemType)
1301 InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr,
1302 /*TopLevelOfInitList*/ true);
1304 // C++14 [dcl.init.aggr]p13:
1305 // If the assignment-expression can initialize a member, the member is
1306 // initialized. Otherwise [...] brace elision is assumed
1308 // Brace elision is never performed if the element is not an
1309 // assignment-expression.
1310 if (Seq || isa<InitListExpr>(expr)) {
1312 ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr);
1313 if (Result.isInvalid())
1316 UpdateStructuredListElement(StructuredList, StructuredIndex,
1317 Result.getAs<Expr>());
1324 // Fall through for subaggregate initialization
1325 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1326 // FIXME: Need to handle atomic aggregate types with implicit init lists.
1327 return CheckScalarType(Entity, IList, ElemType, Index,
1328 StructuredList, StructuredIndex);
1329 } else if (const ArrayType *arrayType =
1330 SemaRef.Context.getAsArrayType(ElemType)) {
1331 // arrayType can be incomplete if we're initializing a flexible
1332 // array member. There's nothing we can do with the completed
1333 // type here, though.
1335 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
1337 CheckStringInit(expr, ElemType, arrayType, SemaRef);
1338 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1344 // Fall through for subaggregate initialization.
1347 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
1348 ElemType->isOpenCLSpecificType()) && "Unexpected type");
1352 // The initializer for a structure or union object that has
1353 // automatic storage duration shall be either an initializer
1354 // list as described below, or a single expression that has
1355 // compatible structure or union type. In the latter case, the
1356 // initial value of the object, including unnamed members, is
1357 // that of the expression.
1358 ExprResult ExprRes = expr;
1359 if (SemaRef.CheckSingleAssignmentConstraints(
1360 ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
1361 if (ExprRes.isInvalid())
1364 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
1365 if (ExprRes.isInvalid())
1368 UpdateStructuredListElement(StructuredList, StructuredIndex,
1369 ExprRes.getAs<Expr>());
1374 // Fall through for subaggregate initialization
1377 // C++ [dcl.init.aggr]p12:
1379 // [...] Otherwise, if the member is itself a non-empty
1380 // subaggregate, brace elision is assumed and the initializer is
1381 // considered for the initialization of the first member of
1382 // the subaggregate.
1383 // OpenCL vector initializer is handled elsewhere.
1384 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1385 ElemType->isAggregateType()) {
1386 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1391 // We cannot initialize this element, so let
1392 // PerformCopyInitialization produce the appropriate diagnostic.
1393 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
1394 /*TopLevelOfInitList=*/true);
1402 void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1403 InitListExpr *IList, QualType DeclType,
1405 InitListExpr *StructuredList,
1406 unsigned &StructuredIndex) {
1407 assert(Index == 0 && "Index in explicit init list must be zero");
1409 // As an extension, clang supports complex initializers, which initialize
1410 // a complex number component-wise. When an explicit initializer list for
1411 // a complex number contains two two initializers, this extension kicks in:
1412 // it exepcts the initializer list to contain two elements convertible to
1413 // the element type of the complex type. The first element initializes
1414 // the real part, and the second element intitializes the imaginary part.
1416 if (IList->getNumInits() != 2)
1417 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1420 // This is an extension in C. (The builtin _Complex type does not exist
1421 // in the C++ standard.)
1422 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
1423 SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init)
1424 << IList->getSourceRange();
1426 // Initialize the complex number.
1427 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
1428 InitializedEntity ElementEntity =
1429 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1431 for (unsigned i = 0; i < 2; ++i) {
1432 ElementEntity.setElementIndex(Index);
1433 CheckSubElementType(ElementEntity, IList, elementType, Index,
1434 StructuredList, StructuredIndex);
1438 void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
1439 InitListExpr *IList, QualType DeclType,
1441 InitListExpr *StructuredList,
1442 unsigned &StructuredIndex) {
1443 if (Index >= IList->getNumInits()) {
1445 SemaRef.Diag(IList->getBeginLoc(),
1446 SemaRef.getLangOpts().CPlusPlus11
1447 ? diag::warn_cxx98_compat_empty_scalar_initializer
1448 : diag::err_empty_scalar_initializer)
1449 << IList->getSourceRange();
1450 hadError = !SemaRef.getLangOpts().CPlusPlus11;
1456 Expr *expr = IList->getInit(Index);
1457 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
1458 // FIXME: This is invalid, and accepting it causes overload resolution
1459 // to pick the wrong overload in some corner cases.
1461 SemaRef.Diag(SubIList->getBeginLoc(),
1462 diag::ext_many_braces_around_scalar_init)
1463 << SubIList->getSourceRange();
1465 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1468 } else if (isa<DesignatedInitExpr>(expr)) {
1470 SemaRef.Diag(expr->getBeginLoc(), diag::err_designator_for_scalar_init)
1471 << DeclType << expr->getSourceRange();
1479 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
1486 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1487 /*TopLevelOfInitList=*/true);
1489 Expr *ResultExpr = nullptr;
1491 if (Result.isInvalid())
1492 hadError = true; // types weren't compatible.
1494 ResultExpr = Result.getAs<Expr>();
1496 if (ResultExpr != expr) {
1497 // The type was promoted, update initializer list.
1498 IList->setInit(Index, ResultExpr);
1504 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1508 void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1509 InitListExpr *IList, QualType DeclType,
1511 InitListExpr *StructuredList,
1512 unsigned &StructuredIndex) {
1513 if (Index >= IList->getNumInits()) {
1514 // FIXME: It would be wonderful if we could point at the actual member. In
1515 // general, it would be useful to pass location information down the stack,
1516 // so that we know the location (or decl) of the "current object" being
1519 SemaRef.Diag(IList->getBeginLoc(),
1520 diag::err_init_reference_member_uninitialized)
1521 << DeclType << IList->getSourceRange();
1528 Expr *expr = IList->getInit(Index);
1529 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1531 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list)
1532 << DeclType << IList->getSourceRange();
1540 if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
1547 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1548 /*TopLevelOfInitList=*/true);
1550 if (Result.isInvalid())
1553 expr = Result.getAs<Expr>();
1554 IList->setInit(Index, expr);
1559 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1563 void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1564 InitListExpr *IList, QualType DeclType,
1566 InitListExpr *StructuredList,
1567 unsigned &StructuredIndex) {
1568 const VectorType *VT = DeclType->getAs<VectorType>();
1569 unsigned maxElements = VT->getNumElements();
1570 unsigned numEltsInit = 0;
1571 QualType elementType = VT->getElementType();
1573 if (Index >= IList->getNumInits()) {
1574 // Make sure the element type can be value-initialized.
1576 CheckEmptyInitializable(
1577 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1578 IList->getEndLoc());
1582 if (!SemaRef.getLangOpts().OpenCL) {
1583 // If the initializing element is a vector, try to copy-initialize
1584 // instead of breaking it apart (which is doomed to failure anyway).
1585 Expr *Init = IList->getInit(Index);
1586 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1588 if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
1595 SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init,
1596 /*TopLevelOfInitList=*/true);
1598 Expr *ResultExpr = nullptr;
1599 if (Result.isInvalid())
1600 hadError = true; // types weren't compatible.
1602 ResultExpr = Result.getAs<Expr>();
1604 if (ResultExpr != Init) {
1605 // The type was promoted, update initializer list.
1606 IList->setInit(Index, ResultExpr);
1612 UpdateStructuredListElement(StructuredList, StructuredIndex,
1618 InitializedEntity ElementEntity =
1619 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1621 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1622 // Don't attempt to go past the end of the init list
1623 if (Index >= IList->getNumInits()) {
1625 CheckEmptyInitializable(ElementEntity, IList->getEndLoc());
1629 ElementEntity.setElementIndex(Index);
1630 CheckSubElementType(ElementEntity, IList, elementType, Index,
1631 StructuredList, StructuredIndex);
1637 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1638 const VectorType *T = Entity.getType()->getAs<VectorType>();
1639 if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1640 T->getVectorKind() == VectorType::NeonPolyVector)) {
1641 // The ability to use vector initializer lists is a GNU vector extension
1642 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1643 // endian machines it works fine, however on big endian machines it
1644 // exhibits surprising behaviour:
1646 // uint32x2_t x = {42, 64};
1647 // return vget_lane_u32(x, 0); // Will return 64.
1649 // Because of this, explicitly call out that it is non-portable.
1651 SemaRef.Diag(IList->getBeginLoc(),
1652 diag::warn_neon_vector_initializer_non_portable);
1654 const char *typeCode;
1655 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1657 if (elementType->isFloatingType())
1659 else if (elementType->isSignedIntegerType())
1661 else if (elementType->isUnsignedIntegerType())
1664 llvm_unreachable("Invalid element type!");
1666 SemaRef.Diag(IList->getBeginLoc(),
1667 SemaRef.Context.getTypeSize(VT) > 64
1668 ? diag::note_neon_vector_initializer_non_portable_q
1669 : diag::note_neon_vector_initializer_non_portable)
1670 << typeCode << typeSize;
1676 InitializedEntity ElementEntity =
1677 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1679 // OpenCL initializers allows vectors to be constructed from vectors.
1680 for (unsigned i = 0; i < maxElements; ++i) {
1681 // Don't attempt to go past the end of the init list
1682 if (Index >= IList->getNumInits())
1685 ElementEntity.setElementIndex(Index);
1687 QualType IType = IList->getInit(Index)->getType();
1688 if (!IType->isVectorType()) {
1689 CheckSubElementType(ElementEntity, IList, elementType, Index,
1690 StructuredList, StructuredIndex);
1694 const VectorType *IVT = IType->getAs<VectorType>();
1695 unsigned numIElts = IVT->getNumElements();
1697 if (IType->isExtVectorType())
1698 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1700 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
1701 IVT->getVectorKind());
1702 CheckSubElementType(ElementEntity, IList, VecType, Index,
1703 StructuredList, StructuredIndex);
1704 numEltsInit += numIElts;
1708 // OpenCL requires all elements to be initialized.
1709 if (numEltsInit != maxElements) {
1711 SemaRef.Diag(IList->getBeginLoc(),
1712 diag::err_vector_incorrect_num_initializers)
1713 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1718 /// Check if the type of a class element has an accessible destructor, and marks
1719 /// it referenced. Returns true if we shouldn't form a reference to the
1722 /// Aggregate initialization requires a class element's destructor be
1723 /// accessible per 11.6.1 [dcl.init.aggr]:
1725 /// The destructor for each element of class type is potentially invoked
1726 /// (15.4 [class.dtor]) from the context where the aggregate initialization
1728 static bool checkDestructorReference(QualType ElementType, SourceLocation Loc,
1730 auto *CXXRD = ElementType->getAsCXXRecordDecl();
1734 CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(CXXRD);
1735 SemaRef.CheckDestructorAccess(Loc, Destructor,
1736 SemaRef.PDiag(diag::err_access_dtor_temp)
1738 SemaRef.MarkFunctionReferenced(Loc, Destructor);
1739 return SemaRef.DiagnoseUseOfDecl(Destructor, Loc);
1742 void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
1743 InitListExpr *IList, QualType &DeclType,
1744 llvm::APSInt elementIndex,
1745 bool SubobjectIsDesignatorContext,
1747 InitListExpr *StructuredList,
1748 unsigned &StructuredIndex) {
1749 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1752 if (checkDestructorReference(arrayType->getElementType(),
1753 IList->getEndLoc(), SemaRef)) {
1759 // Check for the special-case of initializing an array with a string.
1760 if (Index < IList->getNumInits()) {
1761 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1763 // We place the string literal directly into the resulting
1764 // initializer list. This is the only place where the structure
1765 // of the structured initializer list doesn't match exactly,
1766 // because doing so would involve allocating one character
1767 // constant for each string.
1769 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1770 UpdateStructuredListElement(StructuredList, StructuredIndex,
1771 IList->getInit(Index));
1772 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1778 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
1779 // Check for VLAs; in standard C it would be possible to check this
1780 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1781 // them in all sorts of strange places).
1783 SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),
1784 diag::err_variable_object_no_init)
1785 << VAT->getSizeExpr()->getSourceRange();
1792 // We might know the maximum number of elements in advance.
1793 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1794 elementIndex.isUnsigned());
1795 bool maxElementsKnown = false;
1796 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
1797 maxElements = CAT->getSize();
1798 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
1799 elementIndex.setIsUnsigned(maxElements.isUnsigned());
1800 maxElementsKnown = true;
1803 QualType elementType = arrayType->getElementType();
1804 while (Index < IList->getNumInits()) {
1805 Expr *Init = IList->getInit(Index);
1806 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1807 // If we're not the subobject that matches up with the '{' for
1808 // the designator, we shouldn't be handling the
1809 // designator. Return immediately.
1810 if (!SubobjectIsDesignatorContext)
1813 // Handle this designated initializer. elementIndex will be
1814 // updated to be the next array element we'll initialize.
1815 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1816 DeclType, nullptr, &elementIndex, Index,
1817 StructuredList, StructuredIndex, true,
1823 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1824 maxElements = maxElements.extend(elementIndex.getBitWidth());
1825 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1826 elementIndex = elementIndex.extend(maxElements.getBitWidth());
1827 elementIndex.setIsUnsigned(maxElements.isUnsigned());
1829 // If the array is of incomplete type, keep track of the number of
1830 // elements in the initializer.
1831 if (!maxElementsKnown && elementIndex > maxElements)
1832 maxElements = elementIndex;
1837 // If we know the maximum number of elements, and we've already
1838 // hit it, stop consuming elements in the initializer list.
1839 if (maxElementsKnown && elementIndex == maxElements)
1842 InitializedEntity ElementEntity =
1843 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
1845 // Check this element.
1846 CheckSubElementType(ElementEntity, IList, elementType, Index,
1847 StructuredList, StructuredIndex);
1850 // If the array is of incomplete type, keep track of the number of
1851 // elements in the initializer.
1852 if (!maxElementsKnown && elementIndex > maxElements)
1853 maxElements = elementIndex;
1855 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
1856 // If this is an incomplete array type, the actual type needs to
1857 // be calculated here.
1858 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
1859 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
1860 // Sizing an array implicitly to zero is not allowed by ISO C,
1861 // but is supported by GNU.
1862 SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
1865 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
1866 ArrayType::Normal, 0);
1868 if (!hadError && VerifyOnly) {
1869 // If there are any members of the array that get value-initialized, check
1870 // that is possible. That happens if we know the bound and don't have
1871 // enough elements, or if we're performing an array new with an unknown
1873 // FIXME: This needs to detect holes left by designated initializers too.
1874 if ((maxElementsKnown && elementIndex < maxElements) ||
1875 Entity.isVariableLengthArrayNew())
1876 CheckEmptyInitializable(
1877 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1878 IList->getEndLoc());
1882 bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1885 bool TopLevelObject) {
1886 // Handle GNU flexible array initializers.
1887 unsigned FlexArrayDiag;
1888 if (isa<InitListExpr>(InitExpr) &&
1889 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1890 // Empty flexible array init always allowed as an extension
1891 FlexArrayDiag = diag::ext_flexible_array_init;
1892 } else if (SemaRef.getLangOpts().CPlusPlus) {
1893 // Disallow flexible array init in C++; it is not required for gcc
1894 // compatibility, and it needs work to IRGen correctly in general.
1895 FlexArrayDiag = diag::err_flexible_array_init;
1896 } else if (!TopLevelObject) {
1897 // Disallow flexible array init on non-top-level object
1898 FlexArrayDiag = diag::err_flexible_array_init;
1899 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1900 // Disallow flexible array init on anything which is not a variable.
1901 FlexArrayDiag = diag::err_flexible_array_init;
1902 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1903 // Disallow flexible array init on local variables.
1904 FlexArrayDiag = diag::err_flexible_array_init;
1906 // Allow other cases.
1907 FlexArrayDiag = diag::ext_flexible_array_init;
1911 SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
1912 << InitExpr->getBeginLoc();
1913 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1917 return FlexArrayDiag != diag::ext_flexible_array_init;
1920 void InitListChecker::CheckStructUnionTypes(
1921 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
1922 CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field,
1923 bool SubobjectIsDesignatorContext, unsigned &Index,
1924 InitListExpr *StructuredList, unsigned &StructuredIndex,
1925 bool TopLevelObject) {
1926 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
1928 // If the record is invalid, some of it's members are invalid. To avoid
1929 // confusion, we forgo checking the intializer for the entire record.
1930 if (structDecl->isInvalidDecl()) {
1931 // Assume it was supposed to consume a single initializer.
1937 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1938 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1941 for (FieldDecl *FD : RD->fields()) {
1942 QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
1943 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
1949 // If there's a default initializer, use it.
1950 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1953 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1954 Field != FieldEnd; ++Field) {
1955 if (Field->hasInClassInitializer()) {
1956 StructuredList->setInitializedFieldInUnion(*Field);
1957 // FIXME: Actually build a CXXDefaultInitExpr?
1963 // Value-initialize the first member of the union that isn't an unnamed
1965 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1966 Field != FieldEnd; ++Field) {
1967 if (!Field->isUnnamedBitfield()) {
1969 CheckEmptyInitializable(
1970 InitializedEntity::InitializeMember(*Field, &Entity),
1971 IList->getEndLoc());
1973 StructuredList->setInitializedFieldInUnion(*Field);
1980 bool InitializedSomething = false;
1982 // If we have any base classes, they are initialized prior to the fields.
1983 for (auto &Base : Bases) {
1984 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
1986 // Designated inits always initialize fields, so if we see one, all
1987 // remaining base classes have no explicit initializer.
1988 if (Init && isa<DesignatedInitExpr>(Init))
1991 SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
1992 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
1993 SemaRef.Context, &Base, false, &Entity);
1995 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
1996 StructuredList, StructuredIndex);
1997 InitializedSomething = true;
1998 } else if (VerifyOnly) {
1999 CheckEmptyInitializable(BaseEntity, InitLoc);
2003 if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) {
2009 // If structDecl is a forward declaration, this loop won't do
2010 // anything except look at designated initializers; That's okay,
2011 // because an error should get printed out elsewhere. It might be
2012 // worthwhile to skip over the rest of the initializer, though.
2013 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
2014 RecordDecl::field_iterator FieldEnd = RD->field_end();
2015 bool CheckForMissingFields =
2016 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
2017 bool HasDesignatedInit = false;
2019 while (Index < IList->getNumInits()) {
2020 Expr *Init = IList->getInit(Index);
2021 SourceLocation InitLoc = Init->getBeginLoc();
2023 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2024 // If we're not the subobject that matches up with the '{' for
2025 // the designator, we shouldn't be handling the
2026 // designator. Return immediately.
2027 if (!SubobjectIsDesignatorContext)
2030 HasDesignatedInit = true;
2032 // Handle this designated initializer. Field will be updated to
2033 // the next field that we'll be initializing.
2034 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
2035 DeclType, &Field, nullptr, Index,
2036 StructuredList, StructuredIndex,
2037 true, TopLevelObject))
2039 else if (!VerifyOnly) {
2040 // Find the field named by the designated initializer.
2041 RecordDecl::field_iterator F = RD->field_begin();
2042 while (std::next(F) != Field)
2044 QualType ET = SemaRef.Context.getBaseElementType(F->getType());
2045 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2051 InitializedSomething = true;
2053 // Disable check for missing fields when designators are used.
2054 // This matches gcc behaviour.
2055 CheckForMissingFields = false;
2059 if (Field == FieldEnd) {
2060 // We've run out of fields. We're done.
2064 // We've already initialized a member of a union. We're done.
2065 if (InitializedSomething && DeclType->isUnionType())
2068 // If we've hit the flexible array member at the end, we're done.
2069 if (Field->getType()->isIncompleteArrayType())
2072 if (Field->isUnnamedBitfield()) {
2073 // Don't initialize unnamed bitfields, e.g. "int : 20;"
2078 // Make sure we can use this declaration.
2081 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2083 InvalidUse = SemaRef.DiagnoseUseOfDecl(
2084 *Field, IList->getInit(Index)->getBeginLoc());
2093 QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
2094 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2100 InitializedEntity MemberEntity =
2101 InitializedEntity::InitializeMember(*Field, &Entity);
2102 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2103 StructuredList, StructuredIndex);
2104 InitializedSomething = true;
2106 if (DeclType->isUnionType() && !VerifyOnly) {
2107 // Initialize the first field within the union.
2108 StructuredList->setInitializedFieldInUnion(*Field);
2114 // Emit warnings for missing struct field initializers.
2115 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
2116 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
2117 !DeclType->isUnionType()) {
2118 // It is possible we have one or more unnamed bitfields remaining.
2119 // Find first (if any) named field and emit warning.
2120 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
2122 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
2123 SemaRef.Diag(IList->getSourceRange().getEnd(),
2124 diag::warn_missing_field_initializers) << *it;
2130 // Check that any remaining fields can be value-initialized.
2131 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
2132 !Field->getType()->isIncompleteArrayType()) {
2133 // FIXME: Should check for holes left by designated initializers too.
2134 for (; Field != FieldEnd && !hadError; ++Field) {
2135 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
2136 CheckEmptyInitializable(
2137 InitializedEntity::InitializeMember(*Field, &Entity),
2138 IList->getEndLoc());
2142 // Check that the types of the remaining fields have accessible destructors.
2144 // If the initializer expression has a designated initializer, check the
2145 // elements for which a designated initializer is not provided too.
2146 RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
2148 for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
2149 QualType ET = SemaRef.Context.getBaseElementType(I->getType());
2150 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2157 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
2158 Index >= IList->getNumInits())
2161 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
2168 InitializedEntity MemberEntity =
2169 InitializedEntity::InitializeMember(*Field, &Entity);
2171 if (isa<InitListExpr>(IList->getInit(Index)))
2172 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2173 StructuredList, StructuredIndex);
2175 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
2176 StructuredList, StructuredIndex);
2179 /// Expand a field designator that refers to a member of an
2180 /// anonymous struct or union into a series of field designators that
2181 /// refers to the field within the appropriate subobject.
2183 static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
2184 DesignatedInitExpr *DIE,
2186 IndirectFieldDecl *IndirectField) {
2187 typedef DesignatedInitExpr::Designator Designator;
2189 // Build the replacement designators.
2190 SmallVector<Designator, 4> Replacements;
2191 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2192 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2194 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
2195 DIE->getDesignator(DesigIdx)->getDotLoc(),
2196 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2198 Replacements.push_back(Designator((IdentifierInfo *)nullptr,
2199 SourceLocation(), SourceLocation()));
2200 assert(isa<FieldDecl>(*PI));
2201 Replacements.back().setField(cast<FieldDecl>(*PI));
2204 // Expand the current designator into the set of replacement
2205 // designators, so we have a full subobject path down to where the
2206 // member of the anonymous struct/union is actually stored.
2207 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
2208 &Replacements[0] + Replacements.size());
2211 static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
2212 DesignatedInitExpr *DIE) {
2213 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2214 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2215 for (unsigned I = 0; I < NumIndexExprs; ++I)
2216 IndexExprs[I] = DIE->getSubExpr(I + 1);
2217 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2219 DIE->getEqualOrColonLoc(),
2220 DIE->usesGNUSyntax(), DIE->getInit());
2225 // Callback to only accept typo corrections that are for field members of
2226 // the given struct or union.
2227 class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {
2229 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
2232 bool ValidateCandidate(const TypoCorrection &candidate) override {
2233 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2234 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2237 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2238 return llvm::make_unique<FieldInitializerValidatorCCC>(*this);
2245 } // end anonymous namespace
2247 /// Check the well-formedness of a C99 designated initializer.
2249 /// Determines whether the designated initializer @p DIE, which
2250 /// resides at the given @p Index within the initializer list @p
2251 /// IList, is well-formed for a current object of type @p DeclType
2252 /// (C99 6.7.8). The actual subobject that this designator refers to
2253 /// within the current subobject is returned in either
2254 /// @p NextField or @p NextElementIndex (whichever is appropriate).
2256 /// @param IList The initializer list in which this designated
2257 /// initializer occurs.
2259 /// @param DIE The designated initializer expression.
2261 /// @param DesigIdx The index of the current designator.
2263 /// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2264 /// into which the designation in @p DIE should refer.
2266 /// @param NextField If non-NULL and the first designator in @p DIE is
2267 /// a field, this will be set to the field declaration corresponding
2268 /// to the field named by the designator.
2270 /// @param NextElementIndex If non-NULL and the first designator in @p
2271 /// DIE is an array designator or GNU array-range designator, this
2272 /// will be set to the last index initialized by this designator.
2274 /// @param Index Index into @p IList where the designated initializer
2277 /// @param StructuredList The initializer list expression that
2278 /// describes all of the subobject initializers in the order they'll
2279 /// actually be initialized.
2281 /// @returns true if there was an error, false otherwise.
2283 InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2284 InitListExpr *IList,
2285 DesignatedInitExpr *DIE,
2287 QualType &CurrentObjectType,
2288 RecordDecl::field_iterator *NextField,
2289 llvm::APSInt *NextElementIndex,
2291 InitListExpr *StructuredList,
2292 unsigned &StructuredIndex,
2293 bool FinishSubobjectInit,
2294 bool TopLevelObject) {
2295 if (DesigIdx == DIE->size()) {
2296 // Check the actual initialization for the designated object type.
2297 bool prevHadError = hadError;
2299 // Temporarily remove the designator expression from the
2300 // initializer list that the child calls see, so that we don't try
2301 // to re-process the designator.
2302 unsigned OldIndex = Index;
2303 IList->setInit(OldIndex, DIE->getInit());
2305 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
2306 StructuredList, StructuredIndex);
2308 // Restore the designated initializer expression in the syntactic
2309 // form of the initializer list.
2310 if (IList->getInit(OldIndex) != DIE->getInit())
2311 DIE->setInit(IList->getInit(OldIndex));
2312 IList->setInit(OldIndex, DIE);
2314 return hadError && !prevHadError;
2317 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
2318 bool IsFirstDesignator = (DesigIdx == 0);
2320 assert((IsFirstDesignator || StructuredList) &&
2321 "Need a non-designated initializer list to start from");
2323 // Determine the structural initializer list that corresponds to the
2324 // current subobject.
2325 if (IsFirstDesignator)
2326 StructuredList = SyntacticToSemantic.lookup(IList);
2328 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2329 StructuredList->getInit(StructuredIndex) : nullptr;
2330 if (!ExistingInit && StructuredList->hasArrayFiller())
2331 ExistingInit = StructuredList->getArrayFiller();
2334 StructuredList = getStructuredSubobjectInit(
2335 IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
2336 SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
2337 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2338 StructuredList = Result;
2340 if (DesignatedInitUpdateExpr *E =
2341 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2342 StructuredList = E->getUpdater();
2344 DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
2345 DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(),
2346 ExistingInit, DIE->getEndLoc());
2347 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2348 StructuredList = DIUE->getUpdater();
2351 // We need to check on source range validity because the previous
2352 // initializer does not have to be an explicit initializer. e.g.,
2354 // struct P { int a, b; };
2355 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2357 // There is an overwrite taking place because the first braced initializer
2358 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
2359 if (ExistingInit->getSourceRange().isValid()) {
2360 // We are creating an initializer list that initializes the
2361 // subobjects of the current object, but there was already an
2362 // initialization that completely initialized the current
2363 // subobject, e.g., by a compound literal:
2365 // struct X { int a, b; };
2366 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2368 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2369 // designated initializer re-initializes the whole
2370 // subobject [0], overwriting previous initializers.
2371 SemaRef.Diag(D->getBeginLoc(),
2372 diag::warn_subobject_initializer_overrides)
2373 << SourceRange(D->getBeginLoc(), DIE->getEndLoc());
2375 SemaRef.Diag(ExistingInit->getBeginLoc(),
2376 diag::note_previous_initializer)
2377 << /*FIXME:has side effects=*/0 << ExistingInit->getSourceRange();
2381 assert(StructuredList && "Expected a structured initializer list");
2384 if (D->isFieldDesignator()) {
2387 // If a designator has the form
2391 // then the current object (defined below) shall have
2392 // structure or union type and the identifier shall be the
2393 // name of a member of that type.
2394 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
2396 SourceLocation Loc = D->getDotLoc();
2397 if (Loc.isInvalid())
2398 Loc = D->getFieldLoc();
2400 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
2401 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2406 FieldDecl *KnownField = D->getField();
2408 IdentifierInfo *FieldName = D->getFieldName();
2409 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
2410 for (NamedDecl *ND : Lookup) {
2411 if (auto *FD = dyn_cast<FieldDecl>(ND)) {
2415 if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
2416 // In verify mode, don't modify the original.
2418 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2419 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
2420 D = DIE->getDesignator(DesigIdx);
2421 KnownField = cast<FieldDecl>(*IFD->chain_begin());
2428 return true; // No typo correction when just trying this out.
2431 // Name lookup found something, but it wasn't a field.
2432 if (!Lookup.empty()) {
2433 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2435 SemaRef.Diag(Lookup.front()->getLocation(),
2436 diag::note_field_designator_found);
2441 // Name lookup didn't find anything.
2442 // Determine whether this was a typo for another field name.
2443 FieldInitializerValidatorCCC CCC(RT->getDecl());
2444 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2445 DeclarationNameInfo(FieldName, D->getFieldLoc()),
2446 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC,
2447 Sema::CTK_ErrorRecovery, RT->getDecl())) {
2448 SemaRef.diagnoseTypo(
2450 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
2451 << FieldName << CurrentObjectType);
2452 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
2455 // Typo correction didn't find anything.
2456 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
2457 << FieldName << CurrentObjectType;
2464 unsigned FieldIndex = 0;
2466 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2467 FieldIndex = CXXRD->getNumBases();
2469 for (auto *FI : RT->getDecl()->fields()) {
2470 if (FI->isUnnamedBitfield())
2472 if (declaresSameEntity(KnownField, FI)) {
2479 RecordDecl::field_iterator Field =
2480 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
2482 // All of the fields of a union are located at the same place in
2483 // the initializer list.
2484 if (RT->getDecl()->isUnion()) {
2487 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
2488 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
2489 assert(StructuredList->getNumInits() == 1
2490 && "A union should never have more than one initializer!");
2492 Expr *ExistingInit = StructuredList->getInit(0);
2494 // We're about to throw away an initializer, emit warning.
2495 SemaRef.Diag(D->getFieldLoc(),
2496 diag::warn_initializer_overrides)
2497 << D->getSourceRange();
2498 SemaRef.Diag(ExistingInit->getBeginLoc(),
2499 diag::note_previous_initializer)
2500 << /*FIXME:has side effects=*/0
2501 << ExistingInit->getSourceRange();
2504 // remove existing initializer
2505 StructuredList->resizeInits(SemaRef.Context, 0);
2506 StructuredList->setInitializedFieldInUnion(nullptr);
2509 StructuredList->setInitializedFieldInUnion(*Field);
2513 // Make sure we can use this declaration.
2516 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2518 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
2525 // Update the designator with the field declaration.
2526 D->setField(*Field);
2528 // Make sure that our non-designated initializer list has space
2529 // for a subobject corresponding to this field.
2530 if (FieldIndex >= StructuredList->getNumInits())
2531 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2534 // This designator names a flexible array member.
2535 if (Field->getType()->isIncompleteArrayType()) {
2536 bool Invalid = false;
2537 if ((DesigIdx + 1) != DIE->size()) {
2538 // We can't designate an object within the flexible array
2539 // member (because GCC doesn't allow it).
2541 DesignatedInitExpr::Designator *NextD
2542 = DIE->getDesignator(DesigIdx + 1);
2543 SemaRef.Diag(NextD->getBeginLoc(),
2544 diag::err_designator_into_flexible_array_member)
2545 << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
2546 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2552 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2553 !isa<StringLiteral>(DIE->getInit())) {
2554 // The initializer is not an initializer list.
2556 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
2557 diag::err_flexible_array_init_needs_braces)
2558 << DIE->getInit()->getSourceRange();
2559 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2565 // Check GNU flexible array initializer.
2566 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
2575 // Initialize the array.
2576 bool prevHadError = hadError;
2577 unsigned newStructuredIndex = FieldIndex;
2578 unsigned OldIndex = Index;
2579 IList->setInit(Index, DIE->getInit());
2581 InitializedEntity MemberEntity =
2582 InitializedEntity::InitializeMember(*Field, &Entity);
2583 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2584 StructuredList, newStructuredIndex);
2586 IList->setInit(OldIndex, DIE);
2587 if (hadError && !prevHadError) {
2592 StructuredIndex = FieldIndex;
2596 // Recurse to check later designated subobjects.
2597 QualType FieldType = Field->getType();
2598 unsigned newStructuredIndex = FieldIndex;
2600 InitializedEntity MemberEntity =
2601 InitializedEntity::InitializeMember(*Field, &Entity);
2602 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
2603 FieldType, nullptr, nullptr, Index,
2604 StructuredList, newStructuredIndex,
2605 FinishSubobjectInit, false))
2609 // Find the position of the next field to be initialized in this
2614 // If this the first designator, our caller will continue checking
2615 // the rest of this struct/class/union subobject.
2616 if (IsFirstDesignator) {
2619 StructuredIndex = FieldIndex;
2623 if (!FinishSubobjectInit)
2626 // We've already initialized something in the union; we're done.
2627 if (RT->getDecl()->isUnion())
2630 // Check the remaining fields within this class/struct/union subobject.
2631 bool prevHadError = hadError;
2634 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
2635 CXXRecordDecl::base_class_iterator());
2636 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
2637 false, Index, StructuredList, FieldIndex);
2638 return hadError && !prevHadError;
2643 // If a designator has the form
2645 // [ constant-expression ]
2647 // then the current object (defined below) shall have array
2648 // type and the expression shall be an integer constant
2649 // expression. If the array is of unknown size, any
2650 // nonnegative value is valid.
2652 // Additionally, cope with the GNU extension that permits
2653 // designators of the form
2655 // [ constant-expression ... constant-expression ]
2656 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
2659 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2660 << CurrentObjectType;
2665 Expr *IndexExpr = nullptr;
2666 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2667 if (D->isArrayDesignator()) {
2668 IndexExpr = DIE->getArrayIndex(*D);
2669 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
2670 DesignatedEndIndex = DesignatedStartIndex;
2672 assert(D->isArrayRangeDesignator() && "Need array-range designator");
2674 DesignatedStartIndex =
2675 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
2676 DesignatedEndIndex =
2677 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
2678 IndexExpr = DIE->getArrayRangeEnd(*D);
2680 // Codegen can't handle evaluating array range designators that have side
2681 // effects, because we replicate the AST value for each initialized element.
2682 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2683 // elements with something that has a side effect, so codegen can emit an
2684 // "error unsupported" error instead of miscompiling the app.
2685 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
2686 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
2687 FullyStructuredList->sawArrayRangeDesignator();
2690 if (isa<ConstantArrayType>(AT)) {
2691 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
2692 DesignatedStartIndex
2693 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
2694 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
2696 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
2697 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2698 if (DesignatedEndIndex >= MaxElements) {
2700 SemaRef.Diag(IndexExpr->getBeginLoc(),
2701 diag::err_array_designator_too_large)
2702 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2703 << IndexExpr->getSourceRange();
2708 unsigned DesignatedIndexBitWidth =
2709 ConstantArrayType::getMaxSizeBits(SemaRef.Context);
2710 DesignatedStartIndex =
2711 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
2712 DesignatedEndIndex =
2713 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
2714 DesignatedStartIndex.setIsUnsigned(true);
2715 DesignatedEndIndex.setIsUnsigned(true);
2718 if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2719 // We're modifying a string literal init; we have to decompose the string
2720 // so we can modify the individual characters.
2721 ASTContext &Context = SemaRef.Context;
2722 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2724 // Compute the character type
2725 QualType CharTy = AT->getElementType();
2727 // Compute the type of the integer literals.
2728 QualType PromotedCharTy = CharTy;
2729 if (CharTy->isPromotableIntegerType())
2730 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2731 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2733 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2734 // Get the length of the string.
2735 uint64_t StrLen = SL->getLength();
2736 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2737 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2738 StructuredList->resizeInits(Context, StrLen);
2740 // Build a literal for each character in the string, and put them into
2742 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2743 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2744 Expr *Init = new (Context) IntegerLiteral(
2745 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2746 if (CharTy != PromotedCharTy)
2747 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2748 Init, nullptr, VK_RValue);
2749 StructuredList->updateInit(Context, i, Init);
2752 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2754 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2756 // Get the length of the string.
2757 uint64_t StrLen = Str.size();
2758 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2759 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2760 StructuredList->resizeInits(Context, StrLen);
2762 // Build a literal for each character in the string, and put them into
2764 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2765 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2766 Expr *Init = new (Context) IntegerLiteral(
2767 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2768 if (CharTy != PromotedCharTy)
2769 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2770 Init, nullptr, VK_RValue);
2771 StructuredList->updateInit(Context, i, Init);
2776 // Make sure that our non-designated initializer list has space
2777 // for a subobject corresponding to this array element.
2779 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
2780 StructuredList->resizeInits(SemaRef.Context,
2781 DesignatedEndIndex.getZExtValue() + 1);
2783 // Repeatedly perform subobject initializations in the range
2784 // [DesignatedStartIndex, DesignatedEndIndex].
2786 // Move to the next designator
2787 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2788 unsigned OldIndex = Index;
2790 InitializedEntity ElementEntity =
2791 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
2793 while (DesignatedStartIndex <= DesignatedEndIndex) {
2794 // Recurse to check later designated subobjects.
2795 QualType ElementType = AT->getElementType();
2798 ElementEntity.setElementIndex(ElementIndex);
2799 if (CheckDesignatedInitializer(
2800 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
2801 nullptr, Index, StructuredList, ElementIndex,
2802 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
2806 // Move to the next index in the array that we'll be initializing.
2807 ++DesignatedStartIndex;
2808 ElementIndex = DesignatedStartIndex.getZExtValue();
2811 // If this the first designator, our caller will continue checking
2812 // the rest of this array subobject.
2813 if (IsFirstDesignator) {
2814 if (NextElementIndex)
2815 *NextElementIndex = DesignatedStartIndex;
2816 StructuredIndex = ElementIndex;
2820 if (!FinishSubobjectInit)
2823 // Check the remaining elements within this array subobject.
2824 bool prevHadError = hadError;
2825 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
2826 /*SubobjectIsDesignatorContext=*/false, Index,
2827 StructuredList, ElementIndex);
2828 return hadError && !prevHadError;
2831 // Get the structured initializer list for a subobject of type
2832 // @p CurrentObjectType.
2834 InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2835 QualType CurrentObjectType,
2836 InitListExpr *StructuredList,
2837 unsigned StructuredIndex,
2838 SourceRange InitRange,
2839 bool IsFullyOverwritten) {
2841 return nullptr; // No structured list in verification-only mode.
2842 Expr *ExistingInit = nullptr;
2843 if (!StructuredList)
2844 ExistingInit = SyntacticToSemantic.lookup(IList);
2845 else if (StructuredIndex < StructuredList->getNumInits())
2846 ExistingInit = StructuredList->getInit(StructuredIndex);
2848 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2849 // There might have already been initializers for subobjects of the current
2850 // object, but a subsequent initializer list will overwrite the entirety
2851 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
2853 // struct P { char x[6]; };
2854 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
2856 // The first designated initializer is ignored, and l.x is just "f".
2857 if (!IsFullyOverwritten)
2861 // We are creating an initializer list that initializes the
2862 // subobjects of the current object, but there was already an
2863 // initialization that completely initialized the current
2864 // subobject, e.g., by a compound literal:
2866 // struct X { int a, b; };
2867 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2869 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2870 // designated initializer re-initializes the whole
2871 // subobject [0], overwriting previous initializers.
2872 SemaRef.Diag(InitRange.getBegin(),
2873 diag::warn_subobject_initializer_overrides)
2875 SemaRef.Diag(ExistingInit->getBeginLoc(), diag::note_previous_initializer)
2876 << /*FIXME:has side effects=*/0 << ExistingInit->getSourceRange();
2879 InitListExpr *Result
2880 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2881 InitRange.getBegin(), None,
2882 InitRange.getEnd());
2884 QualType ResultType = CurrentObjectType;
2885 if (!ResultType->isArrayType())
2886 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2887 Result->setType(ResultType);
2889 // Pre-allocate storage for the structured initializer list.
2890 unsigned NumElements = 0;
2891 unsigned NumInits = 0;
2892 bool GotNumInits = false;
2893 if (!StructuredList) {
2894 NumInits = IList->getNumInits();
2896 } else if (Index < IList->getNumInits()) {
2897 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
2898 NumInits = SubList->getNumInits();
2903 if (const ArrayType *AType
2904 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2905 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2906 NumElements = CAType->getSize().getZExtValue();
2907 // Simple heuristic so that we don't allocate a very large
2908 // initializer with many empty entries at the end.
2909 if (GotNumInits && NumElements > NumInits)
2912 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
2913 NumElements = VType->getNumElements();
2914 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
2915 RecordDecl *RDecl = RType->getDecl();
2916 if (RDecl->isUnion())
2919 NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
2922 Result->reserveInits(SemaRef.Context, NumElements);
2924 // Link this new initializer list into the structured initializer
2927 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
2929 Result->setSyntacticForm(IList);
2930 SyntacticToSemantic[IList] = Result;
2936 /// Update the initializer at index @p StructuredIndex within the
2937 /// structured initializer list to the value @p expr.
2938 void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2939 unsigned &StructuredIndex,
2941 // No structured initializer list to update
2942 if (!StructuredList)
2945 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2946 StructuredIndex, expr)) {
2947 // This initializer overwrites a previous initializer. Warn.
2948 // We need to check on source range validity because the previous
2949 // initializer does not have to be an explicit initializer.
2950 // struct P { int a, b; };
2951 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2952 // There is an overwrite taking place because the first braced initializer
2953 // list "{ .a = 2 }' already provides value for .p.b (which is zero).
2954 if (PrevInit->getSourceRange().isValid()) {
2955 SemaRef.Diag(expr->getBeginLoc(), diag::warn_initializer_overrides)
2956 << expr->getSourceRange();
2958 SemaRef.Diag(PrevInit->getBeginLoc(), diag::note_previous_initializer)
2959 << /*FIXME:has side effects=*/0 << PrevInit->getSourceRange();
2966 /// Check that the given Index expression is a valid array designator
2967 /// value. This is essentially just a wrapper around
2968 /// VerifyIntegerConstantExpression that also checks for negative values
2969 /// and produces a reasonable diagnostic if there is a
2970 /// failure. Returns the index expression, possibly with an implicit cast
2971 /// added, on success. If everything went okay, Value will receive the
2972 /// value of the constant expression.
2974 CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
2975 SourceLocation Loc = Index->getBeginLoc();
2977 // Make sure this is an integer constant expression.
2978 ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2979 if (Result.isInvalid())
2982 if (Value.isSigned() && Value.isNegative())
2983 return S.Diag(Loc, diag::err_array_designator_negative)
2984 << Value.toString(10) << Index->getSourceRange();
2986 Value.setIsUnsigned(true);
2990 ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
2994 typedef DesignatedInitExpr::Designator ASTDesignator;
2996 bool Invalid = false;
2997 SmallVector<ASTDesignator, 32> Designators;
2998 SmallVector<Expr *, 32> InitExpressions;
3000 // Build designators and check array designator expressions.
3001 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
3002 const Designator &D = Desig.getDesignator(Idx);
3003 switch (D.getKind()) {
3004 case Designator::FieldDesignator:
3005 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
3009 case Designator::ArrayDesignator: {
3010 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
3011 llvm::APSInt IndexValue;
3012 if (!Index->isTypeDependent() && !Index->isValueDependent())
3013 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
3017 Designators.push_back(ASTDesignator(InitExpressions.size(),
3019 D.getRBracketLoc()));
3020 InitExpressions.push_back(Index);
3025 case Designator::ArrayRangeDesignator: {
3026 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
3027 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
3028 llvm::APSInt StartValue;
3029 llvm::APSInt EndValue;
3030 bool StartDependent = StartIndex->isTypeDependent() ||
3031 StartIndex->isValueDependent();
3032 bool EndDependent = EndIndex->isTypeDependent() ||
3033 EndIndex->isValueDependent();
3034 if (!StartDependent)
3036 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
3038 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
3040 if (!StartIndex || !EndIndex)
3043 // Make sure we're comparing values with the same bit width.
3044 if (StartDependent || EndDependent) {
3045 // Nothing to compute.
3046 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
3047 EndValue = EndValue.extend(StartValue.getBitWidth());
3048 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
3049 StartValue = StartValue.extend(EndValue.getBitWidth());
3051 if (!StartDependent && !EndDependent && EndValue < StartValue) {
3052 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
3053 << StartValue.toString(10) << EndValue.toString(10)
3054 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
3057 Designators.push_back(ASTDesignator(InitExpressions.size(),
3060 D.getRBracketLoc()));
3061 InitExpressions.push_back(StartIndex);
3062 InitExpressions.push_back(EndIndex);
3070 if (Invalid || Init.isInvalid())
3073 // Clear out the expressions within the designation.
3074 Desig.ClearExprs(*this);
3076 DesignatedInitExpr *DIE
3077 = DesignatedInitExpr::Create(Context,
3079 InitExpressions, Loc, GNUSyntax,
3080 Init.getAs<Expr>());
3082 if (!getLangOpts().C99)
3083 Diag(DIE->getBeginLoc(), diag::ext_designated_init)
3084 << DIE->getSourceRange();
3089 //===----------------------------------------------------------------------===//
3090 // Initialization entity
3091 //===----------------------------------------------------------------------===//
3093 InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
3094 const InitializedEntity &Parent)
3095 : Parent(&Parent), Index(Index)
3097 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
3098 Kind = EK_ArrayElement;
3099 Type = AT->getElementType();
3100 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
3101 Kind = EK_VectorElement;
3102 Type = VT->getElementType();
3104 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
3105 assert(CT && "Unexpected type");
3106 Kind = EK_ComplexElement;
3107 Type = CT->getElementType();
3112 InitializedEntity::InitializeBase(ASTContext &Context,
3113 const CXXBaseSpecifier *Base,
3114 bool IsInheritedVirtualBase,
3115 const InitializedEntity *Parent) {
3116 InitializedEntity Result;
3117 Result.Kind = EK_Base;
3118 Result.Parent = Parent;
3119 Result.Base = reinterpret_cast<uintptr_t>(Base);
3120 if (IsInheritedVirtualBase)
3121 Result.Base |= 0x01;
3123 Result.Type = Base->getType();
3127 DeclarationName InitializedEntity::getName() const {
3128 switch (getKind()) {
3130 case EK_Parameter_CF_Audited: {
3131 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
3132 return (D ? D->getDeclName() : DeclarationName());
3138 return Variable.VariableOrMember->getDeclName();
3140 case EK_LambdaCapture:
3141 return DeclarationName(Capture.VarID);
3144 case EK_StmtExprResult:
3150 case EK_ArrayElement:
3151 case EK_VectorElement:
3152 case EK_ComplexElement:
3153 case EK_BlockElement:
3154 case EK_LambdaToBlockConversionBlockElement:
3155 case EK_CompoundLiteralInit:
3156 case EK_RelatedResult:
3157 return DeclarationName();
3160 llvm_unreachable("Invalid EntityKind!");
3163 ValueDecl *InitializedEntity::getDecl() const {
3164 switch (getKind()) {
3168 return Variable.VariableOrMember;
3171 case EK_Parameter_CF_Audited:
3172 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
3175 case EK_StmtExprResult:
3181 case EK_ArrayElement:
3182 case EK_VectorElement:
3183 case EK_ComplexElement:
3184 case EK_BlockElement:
3185 case EK_LambdaToBlockConversionBlockElement:
3186 case EK_LambdaCapture:
3187 case EK_CompoundLiteralInit:
3188 case EK_RelatedResult:
3192 llvm_unreachable("Invalid EntityKind!");
3195 bool InitializedEntity::allowsNRVO() const {
3196 switch (getKind()) {
3199 return LocAndNRVO.NRVO;
3201 case EK_StmtExprResult:
3204 case EK_Parameter_CF_Audited:
3209 case EK_CompoundLiteralInit:
3212 case EK_ArrayElement:
3213 case EK_VectorElement:
3214 case EK_ComplexElement:
3215 case EK_BlockElement:
3216 case EK_LambdaToBlockConversionBlockElement:
3217 case EK_LambdaCapture:
3218 case EK_RelatedResult:
3225 unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
3226 assert(getParent() != this);
3227 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3228 for (unsigned I = 0; I != Depth; ++I)
3231 switch (getKind()) {
3232 case EK_Variable: OS << "Variable"; break;
3233 case EK_Parameter: OS << "Parameter"; break;
3234 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3236 case EK_Result: OS << "Result"; break;
3237 case EK_StmtExprResult: OS << "StmtExprResult"; break;
3238 case EK_Exception: OS << "Exception"; break;
3239 case EK_Member: OS << "Member"; break;
3240 case EK_Binding: OS << "Binding"; break;
3241 case EK_New: OS << "New"; break;
3242 case EK_Temporary: OS << "Temporary"; break;
3243 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
3244 case EK_RelatedResult: OS << "RelatedResult"; break;
3245 case EK_Base: OS << "Base"; break;
3246 case EK_Delegating: OS << "Delegating"; break;
3247 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3248 case EK_VectorElement: OS << "VectorElement " << Index; break;
3249 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3250 case EK_BlockElement: OS << "Block"; break;
3251 case EK_LambdaToBlockConversionBlockElement:
3252 OS << "Block (lambda)";
3254 case EK_LambdaCapture:
3255 OS << "LambdaCapture ";
3256 OS << DeclarationName(Capture.VarID);
3260 if (auto *D = getDecl()) {
3262 D->printQualifiedName(OS);
3265 OS << " '" << getType().getAsString() << "'\n";
3270 LLVM_DUMP_METHOD void InitializedEntity::dump() const {
3271 dumpImpl(llvm::errs());
3274 //===----------------------------------------------------------------------===//
3275 // Initialization sequence
3276 //===----------------------------------------------------------------------===//
3278 void InitializationSequence::Step::Destroy() {
3280 case SK_ResolveAddressOfOverloadedFunction:
3281 case SK_CastDerivedToBaseRValue:
3282 case SK_CastDerivedToBaseXValue:
3283 case SK_CastDerivedToBaseLValue:
3284 case SK_BindReference:
3285 case SK_BindReferenceToTemporary:
3287 case SK_ExtraneousCopyToTemporary:
3288 case SK_UserConversion:
3289 case SK_QualificationConversionRValue:
3290 case SK_QualificationConversionXValue:
3291 case SK_QualificationConversionLValue:
3292 case SK_AtomicConversion:
3293 case SK_ListInitialization:
3294 case SK_UnwrapInitList:
3295 case SK_RewrapInitList:
3296 case SK_ConstructorInitialization:
3297 case SK_ConstructorInitializationFromList:
3298 case SK_ZeroInitialization:
3299 case SK_CAssignment:
3301 case SK_ObjCObjectConversion:
3302 case SK_ArrayLoopIndex:
3303 case SK_ArrayLoopInit:
3305 case SK_GNUArrayInit:
3306 case SK_ParenthesizedArrayInit:
3307 case SK_PassByIndirectCopyRestore:
3308 case SK_PassByIndirectRestore:
3309 case SK_ProduceObjCObject:
3310 case SK_StdInitializerList:
3311 case SK_StdInitializerListConstructorCall:
3312 case SK_OCLSamplerInit:
3313 case SK_OCLZeroOpaqueType:
3316 case SK_ConversionSequence:
3317 case SK_ConversionSequenceNoNarrowing:
3322 bool InitializationSequence::isDirectReferenceBinding() const {
3323 // There can be some lvalue adjustments after the SK_BindReference step.
3324 for (auto I = Steps.rbegin(); I != Steps.rend(); ++I) {
3325 if (I->Kind == SK_BindReference)
3327 if (I->Kind == SK_BindReferenceToTemporary)
3333 bool InitializationSequence::isAmbiguous() const {
3337 switch (getFailureKind()) {
3338 case FK_TooManyInitsForReference:
3339 case FK_ParenthesizedListInitForReference:
3340 case FK_ArrayNeedsInitList:
3341 case FK_ArrayNeedsInitListOrStringLiteral:
3342 case FK_ArrayNeedsInitListOrWideStringLiteral:
3343 case FK_NarrowStringIntoWideCharArray:
3344 case FK_WideStringIntoCharArray:
3345 case FK_IncompatWideStringIntoWideChar:
3346 case FK_PlainStringIntoUTF8Char:
3347 case FK_UTF8StringIntoPlainChar:
3348 case FK_AddressOfOverloadFailed: // FIXME: Could do better
3349 case FK_NonConstLValueReferenceBindingToTemporary:
3350 case FK_NonConstLValueReferenceBindingToBitfield:
3351 case FK_NonConstLValueReferenceBindingToVectorElement:
3352 case FK_NonConstLValueReferenceBindingToUnrelated:
3353 case FK_RValueReferenceBindingToLValue:
3354 case FK_ReferenceAddrspaceMismatchTemporary:
3355 case FK_ReferenceInitDropsQualifiers:
3356 case FK_ReferenceInitFailed:
3357 case FK_ConversionFailed:
3358 case FK_ConversionFromPropertyFailed:
3359 case FK_TooManyInitsForScalar:
3360 case FK_ParenthesizedListInitForScalar:
3361 case FK_ReferenceBindingToInitList:
3362 case FK_InitListBadDestinationType:
3363 case FK_DefaultInitOfConst:
3365 case FK_ArrayTypeMismatch:
3366 case FK_NonConstantArrayInit:
3367 case FK_ListInitializationFailed:
3368 case FK_VariableLengthArrayHasInitializer:
3369 case FK_PlaceholderType:
3370 case FK_ExplicitConstructor:
3371 case FK_AddressOfUnaddressableFunction:
3374 case FK_ReferenceInitOverloadFailed:
3375 case FK_UserConversionOverloadFailed:
3376 case FK_ConstructorOverloadFailed:
3377 case FK_ListConstructorOverloadFailed:
3378 return FailedOverloadResult == OR_Ambiguous;
3381 llvm_unreachable("Invalid EntityKind!");
3384 bool InitializationSequence::isConstructorInitialization() const {
3385 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3389 InitializationSequence
3390 ::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3391 DeclAccessPair Found,
3392 bool HadMultipleCandidates) {
3394 S.Kind = SK_ResolveAddressOfOverloadedFunction;
3395 S.Type = Function->getType();
3396 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3397 S.Function.Function = Function;
3398 S.Function.FoundDecl = Found;
3402 void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
3406 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
3407 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3408 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
3414 void InitializationSequence::AddReferenceBindingStep(QualType T,
3415 bool BindingTemporary) {
3417 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3422 void InitializationSequence::AddFinalCopy(QualType T) {
3424 S.Kind = SK_FinalCopy;
3429 void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
3431 S.Kind = SK_ExtraneousCopyToTemporary;
3437 InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
3438 DeclAccessPair FoundDecl,
3440 bool HadMultipleCandidates) {
3442 S.Kind = SK_UserConversion;
3444 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3445 S.Function.Function = Function;
3446 S.Function.FoundDecl = FoundDecl;
3450 void InitializationSequence::AddQualificationConversionStep(QualType Ty,
3453 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
3456 S.Kind = SK_QualificationConversionRValue;
3459 S.Kind = SK_QualificationConversionXValue;
3462 S.Kind = SK_QualificationConversionLValue;
3469 void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
3471 S.Kind = SK_AtomicConversion;
3476 void InitializationSequence::AddConversionSequenceStep(
3477 const ImplicitConversionSequence &ICS, QualType T,
3478 bool TopLevelOfInitList) {
3480 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3481 : SK_ConversionSequence;
3483 S.ICS = new ImplicitConversionSequence(ICS);
3487 void InitializationSequence::AddListInitializationStep(QualType T) {
3489 S.Kind = SK_ListInitialization;
3494 void InitializationSequence::AddConstructorInitializationStep(
3495 DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3496 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
3498 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
3499 : SK_ConstructorInitializationFromList
3500 : SK_ConstructorInitialization;
3502 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3503 S.Function.Function = Constructor;
3504 S.Function.FoundDecl = FoundDecl;
3508 void InitializationSequence::AddZeroInitializationStep(QualType T) {
3510 S.Kind = SK_ZeroInitialization;
3515 void InitializationSequence::AddCAssignmentStep(QualType T) {
3517 S.Kind = SK_CAssignment;
3522 void InitializationSequence::AddStringInitStep(QualType T) {
3524 S.Kind = SK_StringInit;
3529 void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
3531 S.Kind = SK_ObjCObjectConversion;
3536 void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) {
3538 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
3543 void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) {
3545 S.Kind = SK_ArrayLoopIndex;
3547 Steps.insert(Steps.begin(), S);
3549 S.Kind = SK_ArrayLoopInit;
3554 void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
3556 S.Kind = SK_ParenthesizedArrayInit;
3561 void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
3564 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3565 : SK_PassByIndirectRestore);
3570 void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3572 S.Kind = SK_ProduceObjCObject;
3577 void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3579 S.Kind = SK_StdInitializerList;
3584 void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3586 S.Kind = SK_OCLSamplerInit;
3591 void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T) {
3593 S.Kind = SK_OCLZeroOpaqueType;
3598 void InitializationSequence::RewrapReferenceInitList(QualType T,
3599 InitListExpr *Syntactic) {
3600 assert(Syntactic->getNumInits() == 1 &&
3601 "Can only rewrap trivial init lists.");
3603 S.Kind = SK_UnwrapInitList;
3604 S.Type = Syntactic->getInit(0)->getType();
3605 Steps.insert(Steps.begin(), S);
3607 S.Kind = SK_RewrapInitList;
3609 S.WrappingSyntacticList = Syntactic;
3613 void InitializationSequence::SetOverloadFailure(FailureKind Failure,
3614 OverloadingResult Result) {
3615 setSequenceKind(FailedSequence);
3616 this->Failure = Failure;
3617 this->FailedOverloadResult = Result;
3620 //===----------------------------------------------------------------------===//
3621 // Attempt initialization
3622 //===----------------------------------------------------------------------===//
3624 /// Tries to add a zero initializer. Returns true if that worked.
3626 maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
3627 const InitializedEntity &Entity) {
3628 if (Entity.getKind() != InitializedEntity::EK_Variable)
3631 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
3632 if (VD->getInit() || VD->getEndLoc().isMacroID())
3635 QualType VariableTy = VD->getType().getCanonicalType();
3636 SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc());
3637 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
3638 if (!Init.empty()) {
3639 Sequence.AddZeroInitializationStep(Entity.getType());
3640 Sequence.SetZeroInitializationFixit(Init, Loc);
3646 static void MaybeProduceObjCObject(Sema &S,
3647 InitializationSequence &Sequence,
3648 const InitializedEntity &Entity) {
3649 if (!S.getLangOpts().ObjCAutoRefCount) return;
3651 /// When initializing a parameter, produce the value if it's marked
3652 /// __attribute__((ns_consumed)).
3653 if (Entity.isParameterKind()) {
3654 if (!Entity.isParameterConsumed())
3657 assert(Entity.getType()->isObjCRetainableType() &&
3658 "consuming an object of unretainable type?");
3659 Sequence.AddProduceObjCObjectStep(Entity.getType());
3661 /// When initializing a return value, if the return type is a
3662 /// retainable type, then returns need to immediately retain the
3663 /// object. If an autorelease is required, it will be done at the
3665 } else if (Entity.getKind() == InitializedEntity::EK_Result ||
3666 Entity.getKind() == InitializedEntity::EK_StmtExprResult) {
3667 if (!Entity.getType()->isObjCRetainableType())
3670 Sequence.AddProduceObjCObjectStep(Entity.getType());
3674 static void TryListInitialization(Sema &S,
3675 const InitializedEntity &Entity,
3676 const InitializationKind &Kind,
3677 InitListExpr *InitList,
3678 InitializationSequence &Sequence,
3679 bool TreatUnavailableAsInvalid);
3681 /// When initializing from init list via constructor, handle
3682 /// initialization of an object of type std::initializer_list<T>.
3684 /// \return true if we have handled initialization of an object of type
3685 /// std::initializer_list<T>, false otherwise.
3686 static bool TryInitializerListConstruction(Sema &S,
3689 InitializationSequence &Sequence,
3690 bool TreatUnavailableAsInvalid) {
3692 if (!S.isStdInitializerList(DestType, &E))
3695 if (!S.isCompleteType(List->getExprLoc(), E)) {
3696 Sequence.setIncompleteTypeFailure(E);
3700 // Try initializing a temporary array from the init list.
3701 QualType ArrayType = S.Context.getConstantArrayType(
3702 E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3703 List->getNumInits()),
3704 clang::ArrayType::Normal, 0);
3705 InitializedEntity HiddenArray =
3706 InitializedEntity::InitializeTemporary(ArrayType);
3707 InitializationKind Kind = InitializationKind::CreateDirectList(
3708 List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
3709 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
3710 TreatUnavailableAsInvalid);
3712 Sequence.AddStdInitializerListConstructionStep(DestType);
3716 /// Determine if the constructor has the signature of a copy or move
3717 /// constructor for the type T of the class in which it was found. That is,
3718 /// determine if its first parameter is of type T or reference to (possibly
3719 /// cv-qualified) T.
3720 static bool hasCopyOrMoveCtorParam(ASTContext &Ctx,
3721 const ConstructorInfo &Info) {
3722 if (Info.Constructor->getNumParams() == 0)
3726 Info.Constructor->getParamDecl(0)->getType().getNonReferenceType();
3728 Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
3730 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
3733 static OverloadingResult
3734 ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
3736 OverloadCandidateSet &CandidateSet,
3738 DeclContext::lookup_result Ctors,
3739 OverloadCandidateSet::iterator &Best,
3740 bool CopyInitializing, bool AllowExplicit,
3741 bool OnlyListConstructors, bool IsListInit,
3742 bool SecondStepOfCopyInit = false) {
3743 CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor);
3744 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
3746 for (NamedDecl *D : Ctors) {
3747 auto Info = getConstructorInfo(D);
3748 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
3751 if (!AllowExplicit && Info.Constructor->isExplicit())
3754 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
3757 // C++11 [over.best.ics]p4:
3758 // ... and the constructor or user-defined conversion function is a
3760 // - 13.3.1.3, when the argument is the temporary in the second step
3761 // of a class copy-initialization, or
3762 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
3763 // - the second phase of 13.3.1.7 when the initializer list has exactly
3764 // one element that is itself an initializer list, and the target is
3765 // the first parameter of a constructor of class X, and the conversion
3766 // is to X or reference to (possibly cv-qualified X),
3767 // user-defined conversion sequences are not considered.
3768 bool SuppressUserConversions =
3769 SecondStepOfCopyInit ||
3770 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
3771 hasCopyOrMoveCtorParam(S.Context, Info));
3773 if (Info.ConstructorTmpl)
3774 S.AddTemplateOverloadCandidate(
3775 Info.ConstructorTmpl, Info.FoundDecl,
3776 /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions,
3777 /*PartialOverloading=*/false, AllowExplicit);
3779 // C++ [over.match.copy]p1:
3780 // - When initializing a temporary to be bound to the first parameter
3781 // of a constructor [for type T] that takes a reference to possibly
3782 // cv-qualified T as its first argument, called with a single
3783 // argument in the context of direct-initialization, explicit
3784 // conversion functions are also considered.
3785 // FIXME: What if a constructor template instantiates to such a signature?
3786 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
3788 hasCopyOrMoveCtorParam(S.Context, Info);
3789 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
3790 CandidateSet, SuppressUserConversions,
3791 /*PartialOverloading=*/false, AllowExplicit,
3796 // FIXME: Work around a bug in C++17 guaranteed copy elision.
3798 // When initializing an object of class type T by constructor
3799 // ([over.match.ctor]) or by list-initialization ([over.match.list])
3800 // from a single expression of class type U, conversion functions of
3801 // U that convert to the non-reference type cv T are candidates.
3802 // Explicit conversion functions are only candidates during
3803 // direct-initialization.
3805 // Note: SecondStepOfCopyInit is only ever true in this case when
3806 // evaluating whether to produce a C++98 compatibility warning.
3807 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
3808 !SecondStepOfCopyInit) {
3809 Expr *Initializer = Args[0];
3810 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
3811 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
3812 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
3813 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3815 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3816 D = D->getUnderlyingDecl();
3818 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3819 CXXConversionDecl *Conv;
3821 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3823 Conv = cast<CXXConversionDecl>(D);
3825 if (AllowExplicit || !Conv->isExplicit()) {
3827 S.AddTemplateConversionCandidate(
3828 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
3829 CandidateSet, AllowExplicit, AllowExplicit,
3830 /*AllowResultConversion*/ false);
3832 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
3833 DestType, CandidateSet, AllowExplicit,
3835 /*AllowResultConversion*/ false);
3841 // Perform overload resolution and return the result.
3842 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3845 /// Attempt initialization by constructor (C++ [dcl.init]), which
3846 /// enumerates the constructors of the initialized entity and performs overload
3847 /// resolution to select the best.
3848 /// \param DestType The destination class type.
3849 /// \param DestArrayType The destination type, which is either DestType or
3850 /// a (possibly multidimensional) array of DestType.
3851 /// \param IsListInit Is this list-initialization?
3852 /// \param IsInitListCopy Is this non-list-initialization resulting from a
3853 /// list-initialization from {x} where x is the same
3854 /// type as the entity?
3855 static void TryConstructorInitialization(Sema &S,
3856 const InitializedEntity &Entity,
3857 const InitializationKind &Kind,
3858 MultiExprArg Args, QualType DestType,
3859 QualType DestArrayType,
3860 InitializationSequence &Sequence,
3861 bool IsListInit = false,
3862 bool IsInitListCopy = false) {
3863 assert(((!IsListInit && !IsInitListCopy) ||
3864 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
3865 "IsListInit/IsInitListCopy must come with a single initializer list "
3868 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
3869 MultiExprArg UnwrappedArgs =
3870 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
3872 // The type we're constructing needs to be complete.
3873 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
3874 Sequence.setIncompleteTypeFailure(DestType);
3878 // C++17 [dcl.init]p17:
3879 // - If the initializer expression is a prvalue and the cv-unqualified
3880 // version of the source type is the same class as the class of the
3881 // destination, the initializer expression is used to initialize the
3882 // destination object.
3883 // Per DR (no number yet), this does not apply when initializing a base
3884 // class or delegating to another constructor from a mem-initializer.
3885 // ObjC++: Lambda captured by the block in the lambda to block conversion
3886 // should avoid copy elision.
3887 if (S.getLangOpts().CPlusPlus17 &&
3888 Entity.getKind() != InitializedEntity::EK_Base &&
3889 Entity.getKind() != InitializedEntity::EK_Delegating &&
3891 InitializedEntity::EK_LambdaToBlockConversionBlockElement &&
3892 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isRValue() &&
3893 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
3894 // Convert qualifications if necessary.
3895 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
3897 Sequence.RewrapReferenceInitList(DestType, ILE);
3901 const RecordType *DestRecordType = DestType->getAs<RecordType>();
3902 assert(DestRecordType && "Constructor initialization requires record type");
3903 CXXRecordDecl *DestRecordDecl
3904 = cast<CXXRecordDecl>(DestRecordType->getDecl());
3906 // Build the candidate set directly in the initialization sequence
3907 // structure, so that it will persist if we fail.
3908 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3910 // Determine whether we are allowed to call explicit constructors or
3911 // explicit conversion operators.
3912 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
3913 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
3915 // - Otherwise, if T is a class type, constructors are considered. The
3916 // applicable constructors are enumerated, and the best one is chosen
3917 // through overload resolution.
3918 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
3920 OverloadingResult Result = OR_No_Viable_Function;
3921 OverloadCandidateSet::iterator Best;
3922 bool AsInitializerList = false;
3924 // C++11 [over.match.list]p1, per DR1467:
3925 // When objects of non-aggregate type T are list-initialized, such that
3926 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
3927 // according to the rules in this section, overload resolution selects
3928 // the constructor in two phases:
3930 // - Initially, the candidate functions are the initializer-list
3931 // constructors of the class T and the argument list consists of the
3932 // initializer list as a single argument.
3934 AsInitializerList = true;
3936 // If the initializer list has no elements and T has a default constructor,
3937 // the first phase is omitted.
3938 if (!(UnwrappedArgs.empty() && DestRecordDecl->hasDefaultConstructor()))
3939 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
3940 CandidateSet, DestType, Ctors, Best,
3941 CopyInitialization, AllowExplicit,
3942 /*OnlyListConstructors=*/true,
3946 // C++11 [over.match.list]p1:
3947 // - If no viable initializer-list constructor is found, overload resolution
3948 // is performed again, where the candidate functions are all the
3949 // constructors of the class T and the argument list consists of the
3950 // elements of the initializer list.
3951 if (Result == OR_No_Viable_Function) {
3952 AsInitializerList = false;
3953 Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs,
3954 CandidateSet, DestType, Ctors, Best,
3955 CopyInitialization, AllowExplicit,
3956 /*OnlyListConstructors=*/false,
3960 Sequence.SetOverloadFailure(IsListInit ?
3961 InitializationSequence::FK_ListConstructorOverloadFailed :
3962 InitializationSequence::FK_ConstructorOverloadFailed,
3967 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3969 // In C++17, ResolveConstructorOverload can select a conversion function
3970 // instead of a constructor.
3971 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
3972 // Add the user-defined conversion step that calls the conversion function.
3973 QualType ConvType = CD->getConversionType();
3974 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
3975 "should not have selected this conversion function");
3976 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
3977 HadMultipleCandidates);
3978 if (!S.Context.hasSameType(ConvType, DestType))
3979 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
3981 Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
3985 // C++11 [dcl.init]p6:
3986 // If a program calls for the default initialization of an object
3987 // of a const-qualified type T, T shall be a class type with a
3988 // user-provided default constructor.
3989 // C++ core issue 253 proposal:
3990 // If the implicit default constructor initializes all subobjects, no
3991 // initializer should be required.
3992 // The 253 proposal is for example needed to process libstdc++ headers in 5.x.
3993 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3994 if (Kind.getKind() == InitializationKind::IK_Default &&
3995 Entity.getType().isConstQualified()) {
3996 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
3997 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
3998 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
4003 // C++11 [over.match.list]p1:
4004 // In copy-list-initialization, if an explicit constructor is chosen, the
4005 // initializer is ill-formed.
4006 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
4007 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
4011 // Add the constructor initialization step. Any cv-qualification conversion is
4012 // subsumed by the initialization.
4013 Sequence.AddConstructorInitializationStep(
4014 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
4015 IsListInit | IsInitListCopy, AsInitializerList);
4019 ResolveOverloadedFunctionForReferenceBinding(Sema &S,
4021 QualType &SourceType,
4022 QualType &UnqualifiedSourceType,
4023 QualType UnqualifiedTargetType,
4024 InitializationSequence &Sequence) {
4025 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
4026 S.Context.OverloadTy) {
4027 DeclAccessPair Found;
4028 bool HadMultipleCandidates = false;
4029 if (FunctionDecl *Fn
4030 = S.ResolveAddressOfOverloadedFunction(Initializer,
4031 UnqualifiedTargetType,
4033 &HadMultipleCandidates)) {
4034 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
4035 HadMultipleCandidates);
4036 SourceType = Fn->getType();
4037 UnqualifiedSourceType = SourceType.getUnqualifiedType();
4038 } else if (!UnqualifiedTargetType->isRecordType()) {
4039 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4046 static void TryReferenceInitializationCore(Sema &S,
4047 const InitializedEntity &Entity,
4048 const InitializationKind &Kind,
4050 QualType cv1T1, QualType T1,
4052 QualType cv2T2, QualType T2,
4054 InitializationSequence &Sequence);
4056 static void TryValueInitialization(Sema &S,
4057 const InitializedEntity &Entity,
4058 const InitializationKind &Kind,
4059 InitializationSequence &Sequence,
4060 InitListExpr *InitList = nullptr);
4062 /// Attempt list initialization of a reference.
4063 static void TryReferenceListInitialization(Sema &S,
4064 const InitializedEntity &Entity,
4065 const InitializationKind &Kind,
4066 InitListExpr *InitList,
4067 InitializationSequence &Sequence,
4068 bool TreatUnavailableAsInvalid) {
4069 // First, catch C++03 where this isn't possible.
4070 if (!S.getLangOpts().CPlusPlus11) {
4071 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4074 // Can't reference initialize a compound literal.
4075 if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
4076 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4080 QualType DestType = Entity.getType();
4081 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4083 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4085 // Reference initialization via an initializer list works thus:
4086 // If the initializer list consists of a single element that is
4087 // reference-related to the referenced type, bind directly to that element
4088 // (possibly creating temporaries).
4089 // Otherwise, initialize a temporary with the initializer list and
4091 if (InitList->getNumInits() == 1) {
4092 Expr *Initializer = InitList->getInit(0);
4093 QualType cv2T2 = Initializer->getType();
4095 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4097 // If this fails, creating a temporary wouldn't work either.
4098 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4102 SourceLocation DeclLoc = Initializer->getBeginLoc();
4103 bool dummy1, dummy2, dummy3;
4104 Sema::ReferenceCompareResult RefRelationship
4105 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
4107 if (RefRelationship >= Sema::Ref_Related) {
4108 // Try to bind the reference here.
4109 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4110 T1Quals, cv2T2, T2, T2Quals, Sequence);
4112 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4116 // Update the initializer if we've resolved an overloaded function.
4117 if (Sequence.step_begin() != Sequence.step_end())
4118 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4121 // Not reference-related. Create a temporary and bind to that.
4122 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
4124 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
4125 TreatUnavailableAsInvalid);
4127 if (DestType->isRValueReferenceType() ||
4128 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
4129 Sequence.AddReferenceBindingStep(cv1T1, /*BindingTemporary=*/true);
4132 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
4136 /// Attempt list initialization (C++0x [dcl.init.list])
4137 static void TryListInitialization(Sema &S,
4138 const InitializedEntity &Entity,
4139 const InitializationKind &Kind,
4140 InitListExpr *InitList,
4141 InitializationSequence &Sequence,
4142 bool TreatUnavailableAsInvalid) {
4143 QualType DestType = Entity.getType();
4145 // C++ doesn't allow scalar initialization with more than one argument.
4146 // But C99 complex numbers are scalars and it makes sense there.
4147 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
4148 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
4149 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
4152 if (DestType->isReferenceType()) {
4153 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
4154 TreatUnavailableAsInvalid);
4158 if (DestType->isRecordType() &&
4159 !S.isCompleteType(InitList->getBeginLoc(), DestType)) {
4160 Sequence.setIncompleteTypeFailure(DestType);
4164 // C++11 [dcl.init.list]p3, per DR1467:
4165 // - If T is a class type and the initializer list has a single element of
4166 // type cv U, where U is T or a class derived from T, the object is
4167 // initialized from that element (by copy-initialization for
4168 // copy-list-initialization, or by direct-initialization for
4169 // direct-list-initialization).
4170 // - Otherwise, if T is a character array and the initializer list has a
4171 // single element that is an appropriately-typed string literal
4172 // (8.5.2 [dcl.init.string]), initialization is performed as described
4174 // - Otherwise, if T is an aggregate, [...] (continue below).
4175 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
4176 if (DestType->isRecordType()) {
4177 QualType InitType = InitList->getInit(0)->getType();
4178 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
4179 S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {
4180 Expr *InitListAsExpr = InitList;
4181 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4183 /*InitListSyntax*/false,
4184 /*IsInitListCopy*/true);
4188 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
4189 Expr *SubInit[1] = {InitList->getInit(0)};
4190 if (!isa<VariableArrayType>(DestAT) &&
4191 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
4192 InitializationKind SubKind =
4193 Kind.getKind() == InitializationKind::IK_DirectList
4194 ? InitializationKind::CreateDirect(Kind.getLocation(),
4195 InitList->getLBraceLoc(),
4196 InitList->getRBraceLoc())
4198 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4199 /*TopLevelOfInitList*/ true,
4200 TreatUnavailableAsInvalid);
4202 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4203 // the element is not an appropriately-typed string literal, in which
4204 // case we should proceed as in C++11 (below).
4206 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4213 // C++11 [dcl.init.list]p3:
4214 // - If T is an aggregate, aggregate initialization is performed.
4215 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
4216 (S.getLangOpts().CPlusPlus11 &&
4217 S.isStdInitializerList(DestType, nullptr))) {
4218 if (S.getLangOpts().CPlusPlus11) {
4219 // - Otherwise, if the initializer list has no elements and T is a
4220 // class type with a default constructor, the object is
4221 // value-initialized.
4222 if (InitList->getNumInits() == 0) {
4223 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4224 if (RD->hasDefaultConstructor()) {
4225 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
4230 // - Otherwise, if T is a specialization of std::initializer_list<E>,
4231 // an initializer_list object constructed [...]
4232 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
4233 TreatUnavailableAsInvalid))
4236 // - Otherwise, if T is a class type, constructors are considered.
4237 Expr *InitListAsExpr = InitList;
4238 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4239 DestType, Sequence, /*InitListSyntax*/true);
4241 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
4245 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
4246 InitList->getNumInits() == 1) {
4247 Expr *E = InitList->getInit(0);
4249 // - Otherwise, if T is an enumeration with a fixed underlying type,
4250 // the initializer-list has a single element v, and the initialization
4251 // is direct-list-initialization, the object is initialized with the
4252 // value T(v); if a narrowing conversion is required to convert v to
4253 // the underlying type of T, the program is ill-formed.
4254 auto *ET = DestType->getAs<EnumType>();
4255 if (S.getLangOpts().CPlusPlus17 &&
4256 Kind.getKind() == InitializationKind::IK_DirectList &&
4257 ET && ET->getDecl()->isFixed() &&
4258 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
4259 (E->getType()->isIntegralOrEnumerationType() ||
4260 E->getType()->isFloatingType())) {
4261 // There are two ways that T(v) can work when T is an enumeration type.
4262 // If there is either an implicit conversion sequence from v to T or
4263 // a conversion function that can convert from v to T, then we use that.
4264 // Otherwise, if v is of integral, enumeration, or floating-point type,
4265 // it is converted to the enumeration type via its underlying type.
4266 // There is no overlap possible between these two cases (except when the
4267 // source value is already of the destination type), and the first
4268 // case is handled by the general case for single-element lists below.
4269 ImplicitConversionSequence ICS;
4271 ICS.Standard.setAsIdentityConversion();
4273 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4274 // If E is of a floating-point type, then the conversion is ill-formed
4275 // due to narrowing, but go through the motions in order to produce the
4276 // right diagnostic.
4277 ICS.Standard.Second = E->getType()->isFloatingType()
4278 ? ICK_Floating_Integral
4279 : ICK_Integral_Conversion;
4280 ICS.Standard.setFromType(E->getType());
4281 ICS.Standard.setToType(0, E->getType());
4282 ICS.Standard.setToType(1, DestType);
4283 ICS.Standard.setToType(2, DestType);
4284 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
4285 /*TopLevelOfInitList*/true);
4286 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4290 // - Otherwise, if the initializer list has a single element of type E
4291 // [...references are handled above...], the object or reference is
4292 // initialized from that element (by copy-initialization for
4293 // copy-list-initialization, or by direct-initialization for
4294 // direct-list-initialization); if a narrowing conversion is required
4295 // to convert the element to T, the program is ill-formed.
4297 // Per core-24034, this is direct-initialization if we were performing
4298 // direct-list-initialization and copy-initialization otherwise.
4299 // We can't use InitListChecker for this, because it always performs
4300 // copy-initialization. This only matters if we might use an 'explicit'
4301 // conversion operator, so we only need to handle the cases where the source
4302 // is of record type.
4303 if (InitList->getInit(0)->getType()->isRecordType()) {
4304 InitializationKind SubKind =
4305 Kind.getKind() == InitializationKind::IK_DirectList
4306 ? InitializationKind::CreateDirect(Kind.getLocation(),
4307 InitList->getLBraceLoc(),
4308 InitList->getRBraceLoc())
4310 Expr *SubInit[1] = { InitList->getInit(0) };
4311 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4312 /*TopLevelOfInitList*/true,
4313 TreatUnavailableAsInvalid);
4315 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4320 InitListChecker CheckInitList(S, Entity, InitList,
4321 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
4322 if (CheckInitList.HadError()) {
4323 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
4327 // Add the list initialization step with the built init list.
4328 Sequence.AddListInitializationStep(DestType);
4331 /// Try a reference initialization that involves calling a conversion
4333 static OverloadingResult TryRefInitWithConversionFunction(
4334 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4335 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
4336 InitializationSequence &Sequence) {
4337 QualType DestType = Entity.getType();
4338 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4339 QualType T1 = cv1T1.getUnqualifiedType();
4340 QualType cv2T2 = Initializer->getType();
4341 QualType T2 = cv2T2.getUnqualifiedType();
4344 bool ObjCConversion;
4345 bool ObjCLifetimeConversion;
4346 assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2,
4347 DerivedToBase, ObjCConversion,
4348 ObjCLifetimeConversion) &&
4349 "Must have incompatible references when binding via conversion");
4350 (void)DerivedToBase;
4351 (void)ObjCConversion;
4352 (void)ObjCLifetimeConversion;
4354 // Build the candidate set directly in the initialization sequence
4355 // structure, so that it will persist if we fail.
4356 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4357 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4359 // Determine whether we are allowed to call explicit conversion operators.
4360 // Note that none of [over.match.copy], [over.match.conv], nor
4361 // [over.match.ref] permit an explicit constructor to be chosen when
4362 // initializing a reference, not even for direct-initialization.
4363 bool AllowExplicitCtors = false;
4364 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
4366 const RecordType *T1RecordType = nullptr;
4367 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
4368 S.isCompleteType(Kind.getLocation(), T1)) {
4369 // The type we're converting to is a class type. Enumerate its constructors
4370 // to see if there is a suitable conversion.
4371 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
4373 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
4374 auto Info = getConstructorInfo(D);
4375 if (!Info.Constructor)
4378 if (!Info.Constructor->isInvalidDecl() &&
4379 Info.Constructor->isConvertingConstructor(AllowExplicitCtors)) {
4380 if (Info.ConstructorTmpl)
4381 S.AddTemplateOverloadCandidate(
4382 Info.ConstructorTmpl, Info.FoundDecl,
4383 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
4384 /*SuppressUserConversions=*/true,
4385 /*PartialOverloading*/ false, AllowExplicitCtors);
4387 S.AddOverloadCandidate(
4388 Info.Constructor, Info.FoundDecl, Initializer, CandidateSet,
4389 /*SuppressUserConversions=*/true,
4390 /*PartialOverloading*/ false, AllowExplicitCtors);
4394 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
4395 return OR_No_Viable_Function;
4397 const RecordType *T2RecordType = nullptr;
4398 if ((T2RecordType = T2->getAs<RecordType>()) &&
4399 S.isCompleteType(Kind.getLocation(), T2)) {
4400 // The type we're converting from is a class type, enumerate its conversion
4402 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4404 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4405 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4407 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4408 if (isa<UsingShadowDecl>(D))
4409 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4411 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4412 CXXConversionDecl *Conv;
4414 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4416 Conv = cast<CXXConversionDecl>(D);
4418 // If the conversion function doesn't return a reference type,
4419 // it can't be considered for this conversion unless we're allowed to
4420 // consider rvalues.
4421 // FIXME: Do we need to make sure that we only consider conversion
4422 // candidates with reference-compatible results? That might be needed to
4424 if ((AllowExplicitConvs || !Conv->isExplicit()) &&
4426 Conv->getConversionType()->isLValueReferenceType())) {
4428 S.AddTemplateConversionCandidate(
4429 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4431 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
4433 S.AddConversionCandidate(
4434 Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet,
4435 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
4439 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4440 return OR_No_Viable_Function;
4442 SourceLocation DeclLoc = Initializer->getBeginLoc();
4444 // Perform overload resolution. If it fails, return the failed result.
4445 OverloadCandidateSet::iterator Best;
4446 if (OverloadingResult Result
4447 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
4450 FunctionDecl *Function = Best->Function;
4451 // This is the overload that will be used for this initialization step if we
4452 // use this initialization. Mark it as referenced.
4453 Function->setReferenced();
4455 // Compute the returned type and value kind of the conversion.
4457 if (isa<CXXConversionDecl>(Function))
4458 cv3T3 = Function->getReturnType();
4462 ExprValueKind VK = VK_RValue;
4463 if (cv3T3->isLValueReferenceType())
4465 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
4466 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
4467 cv3T3 = cv3T3.getNonLValueExprType(S.Context);
4469 // Add the user-defined conversion step.
4470 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4471 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
4472 HadMultipleCandidates);
4474 // Determine whether we'll need to perform derived-to-base adjustments or
4475 // other conversions.
4476 bool NewDerivedToBase = false;
4477 bool NewObjCConversion = false;
4478 bool NewObjCLifetimeConversion = false;
4479 Sema::ReferenceCompareResult NewRefRelationship
4480 = S.CompareReferenceRelationship(DeclLoc, T1, cv3T3,
4481 NewDerivedToBase, NewObjCConversion,
4482 NewObjCLifetimeConversion);
4484 // Add the final conversion sequence, if necessary.
4485 if (NewRefRelationship == Sema::Ref_Incompatible) {
4486 assert(!isa<CXXConstructorDecl>(Function) &&
4487 "should not have conversion after constructor");
4489 ImplicitConversionSequence ICS;
4491 ICS.Standard = Best->FinalConversion;
4492 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
4494 // Every implicit conversion results in a prvalue, except for a glvalue
4495 // derived-to-base conversion, which we handle below.
4496 cv3T3 = ICS.Standard.getToType(2);
4500 // If the converted initializer is a prvalue, its type T4 is adjusted to
4501 // type "cv1 T4" and the temporary materialization conversion is applied.
4503 // We adjust the cv-qualifications to match the reference regardless of
4504 // whether we have a prvalue so that the AST records the change. In this
4505 // case, T4 is "cv3 T3".
4506 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
4507 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
4508 Sequence.AddQualificationConversionStep(cv1T4, VK);
4509 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_RValue);
4510 VK = IsLValueRef ? VK_LValue : VK_XValue;
4512 if (NewDerivedToBase)
4513 Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
4514 else if (NewObjCConversion)
4515 Sequence.AddObjCObjectConversionStep(cv1T1);
4520 static void CheckCXX98CompatAccessibleCopy(Sema &S,
4521 const InitializedEntity &Entity,
4524 /// Attempt reference initialization (C++0x [dcl.init.ref])
4525 static void TryReferenceInitialization(Sema &S,
4526 const InitializedEntity &Entity,
4527 const InitializationKind &Kind,
4529 InitializationSequence &Sequence) {
4530 QualType DestType = Entity.getType();
4531 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4533 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4534 QualType cv2T2 = Initializer->getType();
4536 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4538 // If the initializer is the address of an overloaded function, try
4539 // to resolve the overloaded function. If all goes well, T2 is the
4540 // type of the resulting function.
4541 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4545 // Delegate everything else to a subfunction.
4546 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4547 T1Quals, cv2T2, T2, T2Quals, Sequence);
4550 /// Determine whether an expression is a non-referenceable glvalue (one to
4551 /// which a reference can never bind). Attempting to bind a reference to
4552 /// such a glvalue will always create a temporary.
4553 static bool isNonReferenceableGLValue(Expr *E) {
4554 return E->refersToBitField() || E->refersToVectorElement();
4557 /// Reference initialization without resolving overloaded functions.
4558 static void TryReferenceInitializationCore(Sema &S,
4559 const InitializedEntity &Entity,
4560 const InitializationKind &Kind,
4562 QualType cv1T1, QualType T1,
4564 QualType cv2T2, QualType T2,
4566 InitializationSequence &Sequence) {
4567 QualType DestType = Entity.getType();
4568 SourceLocation DeclLoc = Initializer->getBeginLoc();
4569 // Compute some basic properties of the types and the initializer.
4570 bool isLValueRef = DestType->isLValueReferenceType();
4571 bool isRValueRef = !isLValueRef;
4572 bool DerivedToBase = false;
4573 bool ObjCConversion = false;
4574 bool ObjCLifetimeConversion = false;
4575 Expr::Classification InitCategory = Initializer->Classify(S.Context);
4576 Sema::ReferenceCompareResult RefRelationship
4577 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
4578 ObjCConversion, ObjCLifetimeConversion);
4580 // C++0x [dcl.init.ref]p5:
4581 // A reference to type "cv1 T1" is initialized by an expression of type
4582 // "cv2 T2" as follows:
4584 // - If the reference is an lvalue reference and the initializer
4586 // Note the analogous bullet points for rvalue refs to functions. Because
4587 // there are no function rvalues in C++, rvalue refs to functions are treated
4588 // like lvalue refs.
4589 OverloadingResult ConvOvlResult = OR_Success;
4590 bool T1Function = T1->isFunctionType();
4591 if (isLValueRef || T1Function) {
4592 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
4593 (RefRelationship == Sema::Ref_Compatible ||
4594 (Kind.isCStyleOrFunctionalCast() &&
4595 RefRelationship == Sema::Ref_Related))) {
4596 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
4597 // reference-compatible with "cv2 T2," or
4598 if (T1Quals != T2Quals)
4599 // Convert to cv1 T2. This should only add qualifiers unless this is a
4600 // c-style cast. The removal of qualifiers in that case notionally
4601 // happens after the reference binding, but that doesn't matter.
4602 Sequence.AddQualificationConversionStep(
4603 S.Context.getQualifiedType(T2, T1Quals),
4604 Initializer->getValueKind());
4606 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
4607 else if (ObjCConversion)
4608 Sequence.AddObjCObjectConversionStep(cv1T1);
4610 // We only create a temporary here when binding a reference to a
4611 // bit-field or vector element. Those cases are't supposed to be
4612 // handled by this bullet, but the outcome is the same either way.
4613 Sequence.AddReferenceBindingStep(cv1T1, false);
4617 // - has a class type (i.e., T2 is a class type), where T1 is not
4618 // reference-related to T2, and can be implicitly converted to an
4619 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
4620 // with "cv3 T3" (this conversion is selected by enumerating the
4621 // applicable conversion functions (13.3.1.6) and choosing the best
4622 // one through overload resolution (13.3)),
4623 // If we have an rvalue ref to function type here, the rhs must be
4624 // an rvalue. DR1287 removed the "implicitly" here.
4625 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
4626 (isLValueRef || InitCategory.isRValue())) {
4627 ConvOvlResult = TryRefInitWithConversionFunction(
4628 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
4629 /*IsLValueRef*/ isLValueRef, Sequence);
4630 if (ConvOvlResult == OR_Success)
4632 if (ConvOvlResult != OR_No_Viable_Function)
4633 Sequence.SetOverloadFailure(
4634 InitializationSequence::FK_ReferenceInitOverloadFailed,
4639 // - Otherwise, the reference shall be an lvalue reference to a
4640 // non-volatile const type (i.e., cv1 shall be const), or the reference
4641 // shall be an rvalue reference.
4642 // For address spaces, we interpret this to mean that an addr space
4643 // of a reference "cv1 T1" is a superset of addr space of "cv2 T2".
4644 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile() &&
4645 T1Quals.isAddressSpaceSupersetOf(T2Quals))) {
4646 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4647 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4648 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4649 Sequence.SetOverloadFailure(
4650 InitializationSequence::FK_ReferenceInitOverloadFailed,
4652 else if (!InitCategory.isLValue())
4654 T1Quals.isAddressSpaceSupersetOf(T2Quals)
4655 ? InitializationSequence::
4656 FK_NonConstLValueReferenceBindingToTemporary
4657 : InitializationSequence::FK_ReferenceInitDropsQualifiers);
4659 InitializationSequence::FailureKind FK;
4660 switch (RefRelationship) {
4661 case Sema::Ref_Compatible:
4662 if (Initializer->refersToBitField())
4663 FK = InitializationSequence::
4664 FK_NonConstLValueReferenceBindingToBitfield;
4665 else if (Initializer->refersToVectorElement())
4666 FK = InitializationSequence::
4667 FK_NonConstLValueReferenceBindingToVectorElement;
4669 llvm_unreachable("unexpected kind of compatible initializer");
4671 case Sema::Ref_Related:
4672 FK = InitializationSequence::FK_ReferenceInitDropsQualifiers;
4674 case Sema::Ref_Incompatible:
4675 FK = InitializationSequence::
4676 FK_NonConstLValueReferenceBindingToUnrelated;
4679 Sequence.SetFailed(FK);
4684 // - If the initializer expression
4686 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
4687 // [1z] rvalue (but not a bit-field) or
4688 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
4690 // Note: functions are handled above and below rather than here...
4692 (RefRelationship == Sema::Ref_Compatible ||
4693 (Kind.isCStyleOrFunctionalCast() &&
4694 RefRelationship == Sema::Ref_Related)) &&
4695 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
4696 (InitCategory.isPRValue() &&
4697 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
4698 T2->isArrayType())))) {
4699 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_RValue;
4700 if (InitCategory.isPRValue() && T2->isRecordType()) {
4701 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
4702 // compiler the freedom to perform a copy here or bind to the
4703 // object, while C++0x requires that we bind directly to the
4704 // object. Hence, we always bind to the object without making an
4705 // extra copy. However, in C++03 requires that we check for the
4706 // presence of a suitable copy constructor:
4708 // The constructor that would be used to make the copy shall
4709 // be callable whether or not the copy is actually done.
4710 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
4711 Sequence.AddExtraneousCopyToTemporary(cv2T2);
4712 else if (S.getLangOpts().CPlusPlus11)
4713 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
4716 // C++1z [dcl.init.ref]/5.2.1.2:
4717 // If the converted initializer is a prvalue, its type T4 is adjusted
4718 // to type "cv1 T4" and the temporary materialization conversion is
4720 // Postpone address space conversions to after the temporary materialization
4721 // conversion to allow creating temporaries in the alloca address space.
4722 auto T1QualsIgnoreAS = T1Quals;
4723 auto T2QualsIgnoreAS = T2Quals;
4724 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
4725 T1QualsIgnoreAS.removeAddressSpace();
4726 T2QualsIgnoreAS.removeAddressSpace();
4728 QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1QualsIgnoreAS);
4729 if (T1QualsIgnoreAS != T2QualsIgnoreAS)
4730 Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
4731 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_RValue);
4732 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
4733 // Add addr space conversion if required.
4734 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
4735 auto T4Quals = cv1T4.getQualifiers();
4736 T4Quals.addAddressSpace(T1Quals.getAddressSpace());
4737 QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals);
4738 Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind);
4741 // In any case, the reference is bound to the resulting glvalue (or to
4742 // an appropriate base class subobject).
4744 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
4745 else if (ObjCConversion)
4746 Sequence.AddObjCObjectConversionStep(cv1T1);
4750 // - has a class type (i.e., T2 is a class type), where T1 is not
4751 // reference-related to T2, and can be implicitly converted to an
4752 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
4753 // where "cv1 T1" is reference-compatible with "cv3 T3",
4755 // DR1287 removes the "implicitly" here.
4756 if (T2->isRecordType()) {
4757 if (RefRelationship == Sema::Ref_Incompatible) {
4758 ConvOvlResult = TryRefInitWithConversionFunction(
4759 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
4760 /*IsLValueRef*/ isLValueRef, Sequence);
4762 Sequence.SetOverloadFailure(
4763 InitializationSequence::FK_ReferenceInitOverloadFailed,
4769 if (RefRelationship == Sema::Ref_Compatible &&
4770 isRValueRef && InitCategory.isLValue()) {
4772 InitializationSequence::FK_RValueReferenceBindingToLValue);
4776 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4780 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
4781 // from the initializer expression using the rules for a non-reference
4782 // copy-initialization (8.5). The reference is then bound to the
4785 // Ignore address space of reference type at this point and perform address
4786 // space conversion after the reference binding step.
4787 QualType cv1T1IgnoreAS =
4788 T1Quals.hasAddressSpace()
4789 ? S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace())
4792 InitializedEntity TempEntity =
4793 InitializedEntity::InitializeTemporary(cv1T1IgnoreAS);
4795 // FIXME: Why do we use an implicit conversion here rather than trying
4796 // copy-initialization?
4797 ImplicitConversionSequence ICS
4798 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
4799 /*SuppressUserConversions=*/false,
4800 /*AllowExplicit=*/false,
4801 /*FIXME:InOverloadResolution=*/false,
4802 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4803 /*AllowObjCWritebackConversion=*/false);
4806 // FIXME: Use the conversion function set stored in ICS to turn
4807 // this into an overloading ambiguity diagnostic. However, we need
4808 // to keep that set as an OverloadCandidateSet rather than as some
4809 // other kind of set.
4810 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4811 Sequence.SetOverloadFailure(
4812 InitializationSequence::FK_ReferenceInitOverloadFailed,
4814 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4815 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4817 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
4820 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
4823 // [...] If T1 is reference-related to T2, cv1 must be the
4824 // same cv-qualification as, or greater cv-qualification
4825 // than, cv2; otherwise, the program is ill-formed.
4826 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
4827 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
4828 if ((RefRelationship == Sema::Ref_Related &&
4829 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) ||
4830 !T1Quals.isAddressSpaceSupersetOf(T2Quals)) {
4831 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4835 // [...] If T1 is reference-related to T2 and the reference is an rvalue
4836 // reference, the initializer expression shall not be an lvalue.
4837 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
4838 InitCategory.isLValue()) {
4840 InitializationSequence::FK_RValueReferenceBindingToLValue);
4844 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true);
4846 if (T1Quals.hasAddressSpace()) {
4847 if (!Qualifiers::isAddressSpaceSupersetOf(T1Quals.getAddressSpace(),
4850 InitializationSequence::FK_ReferenceAddrspaceMismatchTemporary);
4853 Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue
4858 /// Attempt character array initialization from a string literal
4859 /// (C++ [dcl.init.string], C99 6.7.8).
4860 static void TryStringLiteralInitialization(Sema &S,
4861 const InitializedEntity &Entity,
4862 const InitializationKind &Kind,
4864 InitializationSequence &Sequence) {
4865 Sequence.AddStringInitStep(Entity.getType());
4868 /// Attempt value initialization (C++ [dcl.init]p7).
4869 static void TryValueInitialization(Sema &S,
4870 const InitializedEntity &Entity,
4871 const InitializationKind &Kind,
4872 InitializationSequence &Sequence,
4873 InitListExpr *InitList) {
4874 assert((!InitList || InitList->getNumInits() == 0) &&
4875 "Shouldn't use value-init for non-empty init lists");
4877 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
4879 // To value-initialize an object of type T means:
4880 QualType T = Entity.getType();
4882 // -- if T is an array type, then each element is value-initialized;
4883 T = S.Context.getBaseElementType(T);
4885 if (const RecordType *RT = T->getAs<RecordType>()) {
4886 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
4887 bool NeedZeroInitialization = true;
4889 // -- if T is a class type (clause 9) with a user-declared constructor
4890 // (12.1), then the default constructor for T is called (and the
4891 // initialization is ill-formed if T has no accessible default
4894 // -- if T is a class type (clause 9) with either no default constructor
4895 // (12.1 [class.ctor]) or a default constructor that is user-provided
4896 // or deleted, then the object is default-initialized;
4898 // Note that the C++11 rule is the same as the C++98 rule if there are no
4899 // defaulted or deleted constructors, so we just use it unconditionally.
4900 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
4901 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
4902 NeedZeroInitialization = false;
4904 // -- if T is a (possibly cv-qualified) non-union class type without a
4905 // user-provided or deleted default constructor, then the object is
4906 // zero-initialized and, if T has a non-trivial default constructor,
4907 // default-initialized;
4908 // The 'non-union' here was removed by DR1502. The 'non-trivial default
4909 // constructor' part was removed by DR1507.
4910 if (NeedZeroInitialization)
4911 Sequence.AddZeroInitializationStep(Entity.getType());
4914 // -- if T is a non-union class type without a user-declared constructor,
4915 // then every non-static data member and base class component of T is
4916 // value-initialized;
4917 // [...] A program that calls for [...] value-initialization of an
4918 // entity of reference type is ill-formed.
4920 // C++11 doesn't need this handling, because value-initialization does not
4921 // occur recursively there, and the implicit default constructor is
4922 // defined as deleted in the problematic cases.
4923 if (!S.getLangOpts().CPlusPlus11 &&
4924 ClassDecl->hasUninitializedReferenceMember()) {
4925 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
4929 // If this is list-value-initialization, pass the empty init list on when
4930 // building the constructor call. This affects the semantics of a few
4931 // things (such as whether an explicit default constructor can be called).
4932 Expr *InitListAsExpr = InitList;
4933 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
4934 bool InitListSyntax = InitList;
4936 // FIXME: Instead of creating a CXXConstructExpr of array type here,
4937 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
4938 return TryConstructorInitialization(
4939 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
4943 Sequence.AddZeroInitializationStep(Entity.getType());
4946 /// Attempt default initialization (C++ [dcl.init]p6).
4947 static void TryDefaultInitialization(Sema &S,
4948 const InitializedEntity &Entity,
4949 const InitializationKind &Kind,
4950 InitializationSequence &Sequence) {
4951 assert(Kind.getKind() == InitializationKind::IK_Default);
4953 // C++ [dcl.init]p6:
4954 // To default-initialize an object of type T means:
4955 // - if T is an array type, each element is default-initialized;
4956 QualType DestType = S.Context.getBaseElementType(Entity.getType());
4958 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
4959 // constructor for T is called (and the initialization is ill-formed if
4960 // T has no accessible default constructor);
4961 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
4962 TryConstructorInitialization(S, Entity, Kind, None, DestType,
4963 Entity.getType(), Sequence);
4967 // - otherwise, no initialization is performed.
4969 // If a program calls for the default initialization of an object of
4970 // a const-qualified type T, T shall be a class type with a user-provided
4971 // default constructor.
4972 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
4973 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4974 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
4978 // If the destination type has a lifetime property, zero-initialize it.
4979 if (DestType.getQualifiers().hasObjCLifetime()) {
4980 Sequence.AddZeroInitializationStep(Entity.getType());
4985 /// Attempt a user-defined conversion between two types (C++ [dcl.init]),
4986 /// which enumerates all conversion functions and performs overload resolution
4987 /// to select the best.
4988 static void TryUserDefinedConversion(Sema &S,
4990 const InitializationKind &Kind,
4992 InitializationSequence &Sequence,
4993 bool TopLevelOfInitList) {
4994 assert(!DestType->isReferenceType() && "References are handled elsewhere");
4995 QualType SourceType = Initializer->getType();
4996 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4997 "Must have a class type to perform a user-defined conversion");
4999 // Build the candidate set directly in the initialization sequence
5000 // structure, so that it will persist if we fail.
5001 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
5002 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
5003 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
5005 // Determine whether we are allowed to call explicit constructors or
5006 // explicit conversion operators.
5007 bool AllowExplicit = Kind.AllowExplicit();
5009 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
5010 // The type we're converting to is a class type. Enumerate its constructors
5011 // to see if there is a suitable conversion.
5012 CXXRecordDecl *DestRecordDecl
5013 = cast<CXXRecordDecl>(DestRecordType->getDecl());
5015 // Try to complete the type we're converting to.
5016 if (S.isCompleteType(Kind.getLocation(), DestType)) {
5017 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
5018 auto Info = getConstructorInfo(D);
5019 if (!Info.Constructor)
5022 if (!Info.Constructor->isInvalidDecl() &&
5023 Info.Constructor->isConvertingConstructor(AllowExplicit)) {
5024 if (Info.ConstructorTmpl)
5025 S.AddTemplateOverloadCandidate(
5026 Info.ConstructorTmpl, Info.FoundDecl,
5027 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
5028 /*SuppressUserConversions=*/true,
5029 /*PartialOverloading*/ false, AllowExplicit);
5031 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
5032 Initializer, CandidateSet,
5033 /*SuppressUserConversions=*/true,
5034 /*PartialOverloading*/ false, AllowExplicit);
5040 SourceLocation DeclLoc = Initializer->getBeginLoc();
5042 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
5043 // The type we're converting from is a class type, enumerate its conversion
5046 // We can only enumerate the conversion functions for a complete type; if
5047 // the type isn't complete, simply skip this step.
5048 if (S.isCompleteType(DeclLoc, SourceType)) {
5049 CXXRecordDecl *SourceRecordDecl
5050 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
5052 const auto &Conversions =
5053 SourceRecordDecl->getVisibleConversionFunctions();
5054 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5056 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
5057 if (isa<UsingShadowDecl>(D))
5058 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5060 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5061 CXXConversionDecl *Conv;
5063 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5065 Conv = cast<CXXConversionDecl>(D);
5067 if (AllowExplicit || !Conv->isExplicit()) {
5069 S.AddTemplateConversionCandidate(
5070 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
5071 CandidateSet, AllowExplicit, AllowExplicit);
5073 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
5074 DestType, CandidateSet, AllowExplicit,
5081 // Perform overload resolution. If it fails, return the failed result.
5082 OverloadCandidateSet::iterator Best;
5083 if (OverloadingResult Result
5084 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5085 Sequence.SetOverloadFailure(
5086 InitializationSequence::FK_UserConversionOverloadFailed,
5091 FunctionDecl *Function = Best->Function;
5092 Function->setReferenced();
5093 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5095 if (isa<CXXConstructorDecl>(Function)) {
5096 // Add the user-defined conversion step. Any cv-qualification conversion is
5097 // subsumed by the initialization. Per DR5, the created temporary is of the
5098 // cv-unqualified type of the destination.
5099 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
5100 DestType.getUnqualifiedType(),
5101 HadMultipleCandidates);
5103 // C++14 and before:
5104 // - if the function is a constructor, the call initializes a temporary
5105 // of the cv-unqualified version of the destination type. The [...]
5106 // temporary [...] is then used to direct-initialize, according to the
5107 // rules above, the object that is the destination of the
5108 // copy-initialization.
5109 // Note that this just performs a simple object copy from the temporary.
5112 // - if the function is a constructor, the call is a prvalue of the
5113 // cv-unqualified version of the destination type whose return object
5114 // is initialized by the constructor. The call is used to
5115 // direct-initialize, according to the rules above, the object that
5116 // is the destination of the copy-initialization.
5117 // Therefore we need to do nothing further.
5119 // FIXME: Mark this copy as extraneous.
5120 if (!S.getLangOpts().CPlusPlus17)
5121 Sequence.AddFinalCopy(DestType);
5122 else if (DestType.hasQualifiers())
5123 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
5127 // Add the user-defined conversion step that calls the conversion function.
5128 QualType ConvType = Function->getCallResultType();
5129 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
5130 HadMultipleCandidates);
5132 if (ConvType->getAs<RecordType>()) {
5133 // The call is used to direct-initialize [...] the object that is the
5134 // destination of the copy-initialization.
5136 // In C++17, this does not call a constructor if we enter /17.6.1:
5137 // - If the initializer expression is a prvalue and the cv-unqualified
5138 // version of the source type is the same as the class of the
5139 // destination [... do not make an extra copy]
5141 // FIXME: Mark this copy as extraneous.
5142 if (!S.getLangOpts().CPlusPlus17 ||
5143 Function->getReturnType()->isReferenceType() ||
5144 !S.Context.hasSameUnqualifiedType(ConvType, DestType))
5145 Sequence.AddFinalCopy(DestType);
5146 else if (!S.Context.hasSameType(ConvType, DestType))
5147 Sequence.AddQualificationConversionStep(DestType, VK_RValue);
5151 // If the conversion following the call to the conversion function
5152 // is interesting, add it as a separate step.
5153 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
5154 Best->FinalConversion.Third) {
5155 ImplicitConversionSequence ICS;
5157 ICS.Standard = Best->FinalConversion;
5158 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
5162 /// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
5163 /// a function with a pointer return type contains a 'return false;' statement.
5164 /// In C++11, 'false' is not a null pointer, so this breaks the build of any
5165 /// code using that header.
5167 /// Work around this by treating 'return false;' as zero-initializing the result
5168 /// if it's used in a pointer-returning function in a system header.
5169 static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
5170 const InitializedEntity &Entity,
5172 return S.getLangOpts().CPlusPlus11 &&
5173 Entity.getKind() == InitializedEntity::EK_Result &&
5174 Entity.getType()->isPointerType() &&
5175 isa<CXXBoolLiteralExpr>(Init) &&
5176 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
5177 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
5180 /// The non-zero enum values here are indexes into diagnostic alternatives.
5181 enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
5183 /// Determines whether this expression is an acceptable ICR source.
5184 static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
5185 bool isAddressOf, bool &isWeakAccess) {
5187 e = e->IgnoreParens();
5189 // Skip address-of nodes.
5190 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
5191 if (op->getOpcode() == UO_AddrOf)
5192 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
5195 // Skip certain casts.
5196 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
5197 switch (ce->getCastKind()) {
5200 case CK_LValueBitCast:
5202 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
5204 case CK_ArrayToPointerDecay:
5205 return IIK_nonscalar;
5207 case CK_NullToPointer:
5214 // If we have a declaration reference, it had better be a local variable.
5215 } else if (isa<DeclRefExpr>(e)) {
5216 // set isWeakAccess to true, to mean that there will be an implicit
5217 // load which requires a cleanup.
5218 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
5219 isWeakAccess = true;
5221 if (!isAddressOf) return IIK_nonlocal;
5223 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
5224 if (!var) return IIK_nonlocal;
5226 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
5228 // If we have a conditional operator, check both sides.
5229 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
5230 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
5234 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
5236 // These are never scalar.
5237 } else if (isa<ArraySubscriptExpr>(e)) {
5238 return IIK_nonscalar;
5240 // Otherwise, it needs to be a null pointer constant.
5242 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
5243 ? IIK_okay : IIK_nonlocal);
5246 return IIK_nonlocal;
5249 /// Check whether the given expression is a valid operand for an
5250 /// indirect copy/restore.
5251 static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
5252 assert(src->isRValue());
5253 bool isWeakAccess = false;
5254 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
5255 // If isWeakAccess to true, there will be an implicit
5256 // load which requires a cleanup.
5257 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
5258 S.Cleanup.setExprNeedsCleanups(true);
5260 if (iik == IIK_okay) return;
5262 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
5263 << ((unsigned) iik - 1) // shift index into diagnostic explanations
5264 << src->getSourceRange();
5267 /// Determine whether we have compatible array types for the
5268 /// purposes of GNU by-copy array initialization.
5269 static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
5270 const ArrayType *Source) {
5271 // If the source and destination array types are equivalent, we're
5273 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
5276 // Make sure that the element types are the same.
5277 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
5280 // The only mismatch we allow is when the destination is an
5281 // incomplete array type and the source is a constant array type.
5282 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
5285 static bool tryObjCWritebackConversion(Sema &S,
5286 InitializationSequence &Sequence,
5287 const InitializedEntity &Entity,
5288 Expr *Initializer) {
5289 bool ArrayDecay = false;
5290 QualType ArgType = Initializer->getType();
5291 QualType ArgPointee;
5292 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
5294 ArgPointee = ArgArrayType->getElementType();
5295 ArgType = S.Context.getPointerType(ArgPointee);
5298 // Handle write-back conversion.
5299 QualType ConvertedArgType;
5300 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
5304 // We should copy unless we're passing to an argument explicitly
5306 bool ShouldCopy = true;
5307 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5308 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5310 // Do we need an lvalue conversion?
5311 if (ArrayDecay || Initializer->isGLValue()) {
5312 ImplicitConversionSequence ICS;
5314 ICS.Standard.setAsIdentityConversion();
5316 QualType ResultType;
5318 ICS.Standard.First = ICK_Array_To_Pointer;
5319 ResultType = S.Context.getPointerType(ArgPointee);
5321 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
5322 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
5325 Sequence.AddConversionSequenceStep(ICS, ResultType);
5328 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
5332 static bool TryOCLSamplerInitialization(Sema &S,
5333 InitializationSequence &Sequence,
5335 Expr *Initializer) {
5336 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
5337 (!Initializer->isIntegerConstantExpr(S.Context) &&
5338 !Initializer->getType()->isSamplerT()))
5341 Sequence.AddOCLSamplerInitStep(DestType);
5345 static bool IsZeroInitializer(Expr *Initializer, Sema &S) {
5346 return Initializer->isIntegerConstantExpr(S.getASTContext()) &&
5347 (Initializer->EvaluateKnownConstInt(S.getASTContext()) == 0);
5350 static bool TryOCLZeroOpaqueTypeInitialization(Sema &S,
5351 InitializationSequence &Sequence,
5353 Expr *Initializer) {
5354 if (!S.getLangOpts().OpenCL)
5358 // OpenCL 1.2 spec, s6.12.10
5360 // The event argument can also be used to associate the
5361 // async_work_group_copy with a previous async copy allowing
5362 // an event to be shared by multiple async copies; otherwise
5363 // event should be zero.
5365 if (DestType->isEventT() || DestType->isQueueT()) {
5366 if (!IsZeroInitializer(Initializer, S))
5369 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
5373 // We should allow zero initialization for all types defined in the
5374 // cl_intel_device_side_avc_motion_estimation extension, except
5375 // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t.
5376 if (S.getOpenCLOptions().isEnabled(
5377 "cl_intel_device_side_avc_motion_estimation") &&
5378 DestType->isOCLIntelSubgroupAVCType()) {
5379 if (DestType->isOCLIntelSubgroupAVCMcePayloadType() ||
5380 DestType->isOCLIntelSubgroupAVCMceResultType())
5382 if (!IsZeroInitializer(Initializer, S))
5385 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
5392 InitializationSequence::InitializationSequence(Sema &S,
5393 const InitializedEntity &Entity,
5394 const InitializationKind &Kind,
5396 bool TopLevelOfInitList,
5397 bool TreatUnavailableAsInvalid)
5398 : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
5399 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
5400 TreatUnavailableAsInvalid);
5403 /// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
5404 /// address of that function, this returns true. Otherwise, it returns false.
5405 static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
5406 auto *DRE = dyn_cast<DeclRefExpr>(E);
5407 if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
5410 return !S.checkAddressOfFunctionIsAvailable(
5411 cast<FunctionDecl>(DRE->getDecl()));
5414 /// Determine whether we can perform an elementwise array copy for this kind
5416 static bool canPerformArrayCopy(const InitializedEntity &Entity) {
5417 switch (Entity.getKind()) {
5418 case InitializedEntity::EK_LambdaCapture:
5419 // C++ [expr.prim.lambda]p24:
5420 // For array members, the array elements are direct-initialized in
5421 // increasing subscript order.
5424 case InitializedEntity::EK_Variable:
5425 // C++ [dcl.decomp]p1:
5426 // [...] each element is copy-initialized or direct-initialized from the
5427 // corresponding element of the assignment-expression [...]
5428 return isa<DecompositionDecl>(Entity.getDecl());
5430 case InitializedEntity::EK_Member:
5431 // C++ [class.copy.ctor]p14:
5432 // - if the member is an array, each element is direct-initialized with
5433 // the corresponding subobject of x
5434 return Entity.isImplicitMemberInitializer();
5436 case InitializedEntity::EK_ArrayElement:
5437 // All the above cases are intended to apply recursively, even though none
5438 // of them actually say that.
5439 if (auto *E = Entity.getParent())
5440 return canPerformArrayCopy(*E);
5450 void InitializationSequence::InitializeFrom(Sema &S,
5451 const InitializedEntity &Entity,
5452 const InitializationKind &Kind,
5454 bool TopLevelOfInitList,
5455 bool TreatUnavailableAsInvalid) {
5456 ASTContext &Context = S.Context;
5458 // Eliminate non-overload placeholder types in the arguments. We
5459 // need to do this before checking whether types are dependent
5460 // because lowering a pseudo-object expression might well give us
5461 // something of dependent type.
5462 for (unsigned I = 0, E = Args.size(); I != E; ++I)
5463 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
5464 // FIXME: should we be doing this here?
5465 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
5466 if (result.isInvalid()) {
5467 SetFailed(FK_PlaceholderType);
5470 Args[I] = result.get();
5473 // C++0x [dcl.init]p16:
5474 // The semantics of initializers are as follows. The destination type is
5475 // the type of the object or reference being initialized and the source
5476 // type is the type of the initializer expression. The source type is not
5477 // defined when the initializer is a braced-init-list or when it is a
5478 // parenthesized list of expressions.
5479 QualType DestType = Entity.getType();
5481 if (DestType->isDependentType() ||
5482 Expr::hasAnyTypeDependentArguments(Args)) {
5483 SequenceKind = DependentSequence;
5487 // Almost everything is a normal sequence.
5488 setSequenceKind(NormalSequence);
5490 QualType SourceType;
5491 Expr *Initializer = nullptr;
5492 if (Args.size() == 1) {
5493 Initializer = Args[0];
5494 if (S.getLangOpts().ObjC) {
5495 if (S.CheckObjCBridgeRelatedConversions(Initializer->getBeginLoc(),
5496 DestType, Initializer->getType(),
5498 S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
5499 Args[0] = Initializer;
5501 if (!isa<InitListExpr>(Initializer))
5502 SourceType = Initializer->getType();
5505 // - If the initializer is a (non-parenthesized) braced-init-list, the
5506 // object is list-initialized (8.5.4).
5507 if (Kind.getKind() != InitializationKind::IK_Direct) {
5508 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
5509 TryListInitialization(S, Entity, Kind, InitList, *this,
5510 TreatUnavailableAsInvalid);
5515 // - If the destination type is a reference type, see 8.5.3.
5516 if (DestType->isReferenceType()) {
5517 // C++0x [dcl.init.ref]p1:
5518 // A variable declared to be a T& or T&&, that is, "reference to type T"
5519 // (8.3.2), shall be initialized by an object, or function, of type T or
5520 // by an object that can be converted into a T.
5521 // (Therefore, multiple arguments are not permitted.)
5522 if (Args.size() != 1)
5523 SetFailed(FK_TooManyInitsForReference);
5524 // C++17 [dcl.init.ref]p5:
5525 // A reference [...] is initialized by an expression [...] as follows:
5526 // If the initializer is not an expression, presumably we should reject,
5527 // but the standard fails to actually say so.
5528 else if (isa<InitListExpr>(Args[0]))
5529 SetFailed(FK_ParenthesizedListInitForReference);
5531 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
5535 // - If the initializer is (), the object is value-initialized.
5536 if (Kind.getKind() == InitializationKind::IK_Value ||
5537 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
5538 TryValueInitialization(S, Entity, Kind, *this);
5542 // Handle default initialization.
5543 if (Kind.getKind() == InitializationKind::IK_Default) {
5544 TryDefaultInitialization(S, Entity, Kind, *this);
5548 // - If the destination type is an array of characters, an array of
5549 // char16_t, an array of char32_t, or an array of wchar_t, and the
5550 // initializer is a string literal, see 8.5.2.
5551 // - Otherwise, if the destination type is an array, the program is
5553 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
5554 if (Initializer && isa<VariableArrayType>(DestAT)) {
5555 SetFailed(FK_VariableLengthArrayHasInitializer);
5560 switch (IsStringInit(Initializer, DestAT, Context)) {
5562 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
5564 case SIF_NarrowStringIntoWideChar:
5565 SetFailed(FK_NarrowStringIntoWideCharArray);
5567 case SIF_WideStringIntoChar:
5568 SetFailed(FK_WideStringIntoCharArray);
5570 case SIF_IncompatWideStringIntoWideChar:
5571 SetFailed(FK_IncompatWideStringIntoWideChar);
5573 case SIF_PlainStringIntoUTF8Char:
5574 SetFailed(FK_PlainStringIntoUTF8Char);
5576 case SIF_UTF8StringIntoPlainChar:
5577 SetFailed(FK_UTF8StringIntoPlainChar);
5584 // Some kinds of initialization permit an array to be initialized from
5585 // another array of the same type, and perform elementwise initialization.
5586 if (Initializer && isa<ConstantArrayType>(DestAT) &&
5587 S.Context.hasSameUnqualifiedType(Initializer->getType(),
5588 Entity.getType()) &&
5589 canPerformArrayCopy(Entity)) {
5590 // If source is a prvalue, use it directly.
5591 if (Initializer->getValueKind() == VK_RValue) {
5592 AddArrayInitStep(DestType, /*IsGNUExtension*/false);
5596 // Emit element-at-a-time copy loop.
5597 InitializedEntity Element =
5598 InitializedEntity::InitializeElement(S.Context, 0, Entity);
5600 Context.getAsArrayType(Initializer->getType())->getElementType();
5601 OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
5602 Initializer->getValueKind(),
5603 Initializer->getObjectKind());
5604 Expr *OVEAsExpr = &OVE;
5605 InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList,
5606 TreatUnavailableAsInvalid);
5608 AddArrayInitLoopStep(Entity.getType(), InitEltT);
5612 // Note: as an GNU C extension, we allow initialization of an
5613 // array from a compound literal that creates an array of the same
5614 // type, so long as the initializer has no side effects.
5615 if (!S.getLangOpts().CPlusPlus && Initializer &&
5616 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
5617 Initializer->getType()->isArrayType()) {
5618 const ArrayType *SourceAT
5619 = Context.getAsArrayType(Initializer->getType());
5620 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
5621 SetFailed(FK_ArrayTypeMismatch);
5622 else if (Initializer->HasSideEffects(S.Context))
5623 SetFailed(FK_NonConstantArrayInit);
5625 AddArrayInitStep(DestType, /*IsGNUExtension*/true);
5628 // Note: as a GNU C++ extension, we allow list-initialization of a
5629 // class member of array type from a parenthesized initializer list.
5630 else if (S.getLangOpts().CPlusPlus &&
5631 Entity.getKind() == InitializedEntity::EK_Member &&
5632 Initializer && isa<InitListExpr>(Initializer)) {
5633 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
5634 *this, TreatUnavailableAsInvalid);
5635 AddParenthesizedArrayInitStep(DestType);
5636 } else if (DestAT->getElementType()->isCharType())
5637 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
5638 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
5639 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
5641 SetFailed(FK_ArrayNeedsInitList);
5646 // Determine whether we should consider writeback conversions for
5648 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
5649 Entity.isParameterKind();
5651 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
5654 // We're at the end of the line for C: it's either a write-back conversion
5655 // or it's a C assignment. There's no need to check anything else.
5656 if (!S.getLangOpts().CPlusPlus) {
5657 // If allowed, check whether this is an Objective-C writeback conversion.
5658 if (allowObjCWritebackConversion &&
5659 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
5663 if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer))
5666 // Handle initialization in C
5667 AddCAssignmentStep(DestType);
5668 MaybeProduceObjCObject(S, *this, Entity);
5672 assert(S.getLangOpts().CPlusPlus);
5674 // - If the destination type is a (possibly cv-qualified) class type:
5675 if (DestType->isRecordType()) {
5676 // - If the initialization is direct-initialization, or if it is
5677 // copy-initialization where the cv-unqualified version of the
5678 // source type is the same class as, or a derived class of, the
5679 // class of the destination, constructors are considered. [...]
5680 if (Kind.getKind() == InitializationKind::IK_Direct ||
5681 (Kind.getKind() == InitializationKind::IK_Copy &&
5682 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
5683 S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType, DestType))))
5684 TryConstructorInitialization(S, Entity, Kind, Args,
5685 DestType, DestType, *this);
5686 // - Otherwise (i.e., for the remaining copy-initialization cases),
5687 // user-defined conversion sequences that can convert from the source
5688 // type to the destination type or (when a conversion function is
5689 // used) to a derived class thereof are enumerated as described in
5690 // 13.3.1.4, and the best one is chosen through overload resolution
5693 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
5694 TopLevelOfInitList);
5698 assert(Args.size() >= 1 && "Zero-argument case handled above");
5700 // The remaining cases all need a source type.
5701 if (Args.size() > 1) {
5702 SetFailed(FK_TooManyInitsForScalar);
5704 } else if (isa<InitListExpr>(Args[0])) {
5705 SetFailed(FK_ParenthesizedListInitForScalar);
5709 // - Otherwise, if the source type is a (possibly cv-qualified) class
5710 // type, conversion functions are considered.
5711 if (!SourceType.isNull() && SourceType->isRecordType()) {
5712 // For a conversion to _Atomic(T) from either T or a class type derived
5713 // from T, initialize the T object then convert to _Atomic type.
5714 bool NeedAtomicConversion = false;
5715 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
5716 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
5717 S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType,
5718 Atomic->getValueType())) {
5719 DestType = Atomic->getValueType();
5720 NeedAtomicConversion = true;
5724 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
5725 TopLevelOfInitList);
5726 MaybeProduceObjCObject(S, *this, Entity);
5727 if (!Failed() && NeedAtomicConversion)
5728 AddAtomicConversionStep(Entity.getType());
5732 // - Otherwise, the initial value of the object being initialized is the
5733 // (possibly converted) value of the initializer expression. Standard
5734 // conversions (Clause 4) will be used, if necessary, to convert the
5735 // initializer expression to the cv-unqualified version of the
5736 // destination type; no user-defined conversions are considered.
5738 ImplicitConversionSequence ICS
5739 = S.TryImplicitConversion(Initializer, DestType,
5740 /*SuppressUserConversions*/true,
5741 /*AllowExplicitConversions*/ false,
5742 /*InOverloadResolution*/ false,
5743 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5744 allowObjCWritebackConversion);
5746 if (ICS.isStandard() &&
5747 ICS.Standard.Second == ICK_Writeback_Conversion) {
5748 // Objective-C ARC writeback conversion.
5750 // We should copy unless we're passing to an argument explicitly
5752 bool ShouldCopy = true;
5753 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5754 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5756 // If there was an lvalue adjustment, add it as a separate conversion.
5757 if (ICS.Standard.First == ICK_Array_To_Pointer ||
5758 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5759 ImplicitConversionSequence LvalueICS;
5760 LvalueICS.setStandard();
5761 LvalueICS.Standard.setAsIdentityConversion();
5762 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
5763 LvalueICS.Standard.First = ICS.Standard.First;
5764 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
5767 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
5768 } else if (ICS.isBad()) {
5770 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
5771 AddZeroInitializationStep(Entity.getType());
5772 } else if (Initializer->getType() == Context.OverloadTy &&
5773 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
5775 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
5776 else if (Initializer->getType()->isFunctionType() &&
5777 isExprAnUnaddressableFunction(S, Initializer))
5778 SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction);
5780 SetFailed(InitializationSequence::FK_ConversionFailed);
5782 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
5784 MaybeProduceObjCObject(S, *this, Entity);
5788 InitializationSequence::~InitializationSequence() {
5789 for (auto &S : Steps)
5793 //===----------------------------------------------------------------------===//
5794 // Perform initialization
5795 //===----------------------------------------------------------------------===//
5796 static Sema::AssignmentAction
5797 getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
5798 switch(Entity.getKind()) {
5799 case InitializedEntity::EK_Variable:
5800 case InitializedEntity::EK_New:
5801 case InitializedEntity::EK_Exception:
5802 case InitializedEntity::EK_Base:
5803 case InitializedEntity::EK_Delegating:
5804 return Sema::AA_Initializing;
5806 case InitializedEntity::EK_Parameter:
5807 if (Entity.getDecl() &&
5808 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5809 return Sema::AA_Sending;
5811 return Sema::AA_Passing;
5813 case InitializedEntity::EK_Parameter_CF_Audited:
5814 if (Entity.getDecl() &&
5815 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
5816 return Sema::AA_Sending;
5818 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
5820 case InitializedEntity::EK_Result:
5821 case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right.
5822 return Sema::AA_Returning;
5824 case InitializedEntity::EK_Temporary:
5825 case InitializedEntity::EK_RelatedResult:
5826 // FIXME: Can we tell apart casting vs. converting?
5827 return Sema::AA_Casting;
5829 case InitializedEntity::EK_Member:
5830 case InitializedEntity::EK_Binding:
5831 case InitializedEntity::EK_ArrayElement:
5832 case InitializedEntity::EK_VectorElement:
5833 case InitializedEntity::EK_ComplexElement:
5834 case InitializedEntity::EK_BlockElement:
5835 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
5836 case InitializedEntity::EK_LambdaCapture:
5837 case InitializedEntity::EK_CompoundLiteralInit:
5838 return Sema::AA_Initializing;
5841 llvm_unreachable("Invalid EntityKind!");
5844 /// Whether we should bind a created object as a temporary when
5845 /// initializing the given entity.
5846 static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
5847 switch (Entity.getKind()) {
5848 case InitializedEntity::EK_ArrayElement:
5849 case InitializedEntity::EK_Member:
5850 case InitializedEntity::EK_Result:
5851 case InitializedEntity::EK_StmtExprResult:
5852 case InitializedEntity::EK_New:
5853 case InitializedEntity::EK_Variable:
5854 case InitializedEntity::EK_Base:
5855 case InitializedEntity::EK_Delegating:
5856 case InitializedEntity::EK_VectorElement:
5857 case InitializedEntity::EK_ComplexElement:
5858 case InitializedEntity::EK_Exception:
5859 case InitializedEntity::EK_BlockElement:
5860 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
5861 case InitializedEntity::EK_LambdaCapture:
5862 case InitializedEntity::EK_CompoundLiteralInit:
5865 case InitializedEntity::EK_Parameter:
5866 case InitializedEntity::EK_Parameter_CF_Audited:
5867 case InitializedEntity::EK_Temporary:
5868 case InitializedEntity::EK_RelatedResult:
5869 case InitializedEntity::EK_Binding:
5873 llvm_unreachable("missed an InitializedEntity kind?");
5876 /// Whether the given entity, when initialized with an object
5877 /// created for that initialization, requires destruction.
5878 static bool shouldDestroyEntity(const InitializedEntity &Entity) {
5879 switch (Entity.getKind()) {
5880 case InitializedEntity::EK_Result:
5881 case InitializedEntity::EK_StmtExprResult:
5882 case InitializedEntity::EK_New:
5883 case InitializedEntity::EK_Base:
5884 case InitializedEntity::EK_Delegating:
5885 case InitializedEntity::EK_VectorElement:
5886 case InitializedEntity::EK_ComplexElement:
5887 case InitializedEntity::EK_BlockElement:
5888 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
5889 case InitializedEntity::EK_LambdaCapture:
5892 case InitializedEntity::EK_Member:
5893 case InitializedEntity::EK_Binding:
5894 case InitializedEntity::EK_Variable:
5895 case InitializedEntity::EK_Parameter:
5896 case InitializedEntity::EK_Parameter_CF_Audited:
5897 case InitializedEntity::EK_Temporary:
5898 case InitializedEntity::EK_ArrayElement:
5899 case InitializedEntity::EK_Exception:
5900 case InitializedEntity::EK_CompoundLiteralInit:
5901 case InitializedEntity::EK_RelatedResult:
5905 llvm_unreachable("missed an InitializedEntity kind?");
5908 /// Get the location at which initialization diagnostics should appear.
5909 static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
5910 Expr *Initializer) {
5911 switch (Entity.getKind()) {
5912 case InitializedEntity::EK_Result:
5913 case InitializedEntity::EK_StmtExprResult:
5914 return Entity.getReturnLoc();
5916 case InitializedEntity::EK_Exception:
5917 return Entity.getThrowLoc();
5919 case InitializedEntity::EK_Variable:
5920 case InitializedEntity::EK_Binding:
5921 return Entity.getDecl()->getLocation();
5923 case InitializedEntity::EK_LambdaCapture:
5924 return Entity.getCaptureLoc();
5926 case InitializedEntity::EK_ArrayElement:
5927 case InitializedEntity::EK_Member:
5928 case InitializedEntity::EK_Parameter:
5929 case InitializedEntity::EK_Parameter_CF_Audited:
5930 case InitializedEntity::EK_Temporary:
5931 case InitializedEntity::EK_New:
5932 case InitializedEntity::EK_Base:
5933 case InitializedEntity::EK_Delegating:
5934 case InitializedEntity::EK_VectorElement:
5935 case InitializedEntity::EK_ComplexElement:
5936 case InitializedEntity::EK_BlockElement:
5937 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
5938 case InitializedEntity::EK_CompoundLiteralInit:
5939 case InitializedEntity::EK_RelatedResult:
5940 return Initializer->getBeginLoc();
5942 llvm_unreachable("missed an InitializedEntity kind?");
5945 /// Make a (potentially elidable) temporary copy of the object
5946 /// provided by the given initializer by calling the appropriate copy
5949 /// \param S The Sema object used for type-checking.
5951 /// \param T The type of the temporary object, which must either be
5952 /// the type of the initializer expression or a superclass thereof.
5954 /// \param Entity The entity being initialized.
5956 /// \param CurInit The initializer expression.
5958 /// \param IsExtraneousCopy Whether this is an "extraneous" copy that
5959 /// is permitted in C++03 (but not C++0x) when binding a reference to
5962 /// \returns An expression that copies the initializer expression into
5963 /// a temporary object, or an error expression if a copy could not be
5965 static ExprResult CopyObject(Sema &S,
5967 const InitializedEntity &Entity,
5969 bool IsExtraneousCopy) {
5970 if (CurInit.isInvalid())
5972 // Determine which class type we're copying to.
5973 Expr *CurInitExpr = (Expr *)CurInit.get();
5974 CXXRecordDecl *Class = nullptr;
5975 if (const RecordType *Record = T->getAs<RecordType>())
5976 Class = cast<CXXRecordDecl>(Record->getDecl());
5980 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
5982 // Make sure that the type we are copying is complete.
5983 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
5986 // Perform overload resolution using the class's constructors. Per
5987 // C++11 [dcl.init]p16, second bullet for class types, this initialization
5988 // is direct-initialization.
5989 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5990 DeclContext::lookup_result Ctors = S.LookupConstructors(Class);
5992 OverloadCandidateSet::iterator Best;
5993 switch (ResolveConstructorOverload(
5994 S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
5995 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
5996 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
5997 /*SecondStepOfCopyInit=*/true)) {
6001 case OR_No_Viable_Function:
6002 CandidateSet.NoteCandidates(
6003 PartialDiagnosticAt(
6004 Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext()
6005 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
6006 : diag::err_temp_copy_no_viable)
6007 << (int)Entity.getKind() << CurInitExpr->getType()
6008 << CurInitExpr->getSourceRange()),
6009 S, OCD_AllCandidates, CurInitExpr);
6010 if (!IsExtraneousCopy || S.isSFINAEContext())
6015 CandidateSet.NoteCandidates(
6016 PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous)
6017 << (int)Entity.getKind()
6018 << CurInitExpr->getType()
6019 << CurInitExpr->getSourceRange()),
6020 S, OCD_ViableCandidates, CurInitExpr);
6024 S.Diag(Loc, diag::err_temp_copy_deleted)
6025 << (int)Entity.getKind() << CurInitExpr->getType()
6026 << CurInitExpr->getSourceRange();
6027 S.NoteDeletedFunction(Best->Function);
6031 bool HadMultipleCandidates = CandidateSet.size() > 1;
6033 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
6034 SmallVector<Expr*, 8> ConstructorArgs;
6035 CurInit.get(); // Ownership transferred into MultiExprArg, below.
6037 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
6040 if (IsExtraneousCopy) {
6041 // If this is a totally extraneous copy for C++03 reference
6042 // binding purposes, just return the original initialization
6043 // expression. We don't generate an (elided) copy operation here
6044 // because doing so would require us to pass down a flag to avoid
6045 // infinite recursion, where each step adds another extraneous,
6048 // Instantiate the default arguments of any extra parameters in
6049 // the selected copy constructor, as if we were going to create a
6050 // proper call to the copy constructor.
6051 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
6052 ParmVarDecl *Parm = Constructor->getParamDecl(I);
6053 if (S.RequireCompleteType(Loc, Parm->getType(),
6054 diag::err_call_incomplete_argument))
6057 // Build the default argument expression; we don't actually care
6058 // if this succeeds or not, because this routine will complain
6059 // if there was a problem.
6060 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
6066 // Determine the arguments required to actually perform the
6067 // constructor call (we might have derived-to-base conversions, or
6068 // the copy constructor may have default arguments).
6069 if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
6072 // C++0x [class.copy]p32:
6073 // When certain criteria are met, an implementation is allowed to
6074 // omit the copy/move construction of a class object, even if the
6075 // copy/move constructor and/or destructor for the object have
6076 // side effects. [...]
6077 // - when a temporary class object that has not been bound to a
6078 // reference (12.2) would be copied/moved to a class object
6079 // with the same cv-unqualified type, the copy/move operation
6080 // can be omitted by constructing the temporary object
6081 // directly into the target of the omitted copy/move
6083 // Note that the other three bullets are handled elsewhere. Copy
6084 // elision for return statements and throw expressions are handled as part
6085 // of constructor initialization, while copy elision for exception handlers
6086 // is handled by the run-time.
6088 // FIXME: If the function parameter is not the same type as the temporary, we
6089 // should still be able to elide the copy, but we don't have a way to
6090 // represent in the AST how much should be elided in this case.
6092 CurInitExpr->isTemporaryObject(S.Context, Class) &&
6093 S.Context.hasSameUnqualifiedType(
6094 Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
6095 CurInitExpr->getType());
6097 // Actually perform the constructor call.
6098 CurInit = S.BuildCXXConstructExpr(Loc, T, Best->FoundDecl, Constructor,
6101 HadMultipleCandidates,
6103 /*StdInitListInit*/ false,
6105 CXXConstructExpr::CK_Complete,
6108 // If we're supposed to bind temporaries, do so.
6109 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
6110 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
6114 /// Check whether elidable copy construction for binding a reference to
6115 /// a temporary would have succeeded if we were building in C++98 mode, for
6117 static void CheckCXX98CompatAccessibleCopy(Sema &S,
6118 const InitializedEntity &Entity,
6119 Expr *CurInitExpr) {
6120 assert(S.getLangOpts().CPlusPlus11);
6122 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
6126 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
6127 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
6130 // Find constructors which would have been considered.
6131 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6132 DeclContext::lookup_result Ctors =
6133 S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl()));
6135 // Perform overload resolution.
6136 OverloadCandidateSet::iterator Best;
6137 OverloadingResult OR = ResolveConstructorOverload(
6138 S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
6139 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
6140 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
6141 /*SecondStepOfCopyInit=*/true);
6143 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
6144 << OR << (int)Entity.getKind() << CurInitExpr->getType()
6145 << CurInitExpr->getSourceRange();
6149 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
6150 Best->FoundDecl, Entity, Diag);
6151 // FIXME: Check default arguments as far as that's possible.
6154 case OR_No_Viable_Function:
6155 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
6156 OCD_AllCandidates, CurInitExpr);
6160 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
6161 OCD_ViableCandidates, CurInitExpr);
6166 S.NoteDeletedFunction(Best->Function);
6171 void InitializationSequence::PrintInitLocationNote(Sema &S,
6172 const InitializedEntity &Entity) {
6173 if (Entity.isParameterKind() && Entity.getDecl()) {
6174 if (Entity.getDecl()->getLocation().isInvalid())
6177 if (Entity.getDecl()->getDeclName())
6178 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
6179 << Entity.getDecl()->getDeclName();
6181 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
6183 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
6184 Entity.getMethodDecl())
6185 S.Diag(Entity.getMethodDecl()->getLocation(),
6186 diag::note_method_return_type_change)
6187 << Entity.getMethodDecl()->getDeclName();
6190 /// Returns true if the parameters describe a constructor initialization of
6191 /// an explicit temporary object, e.g. "Point(x, y)".
6192 static bool isExplicitTemporary(const InitializedEntity &Entity,
6193 const InitializationKind &Kind,
6195 switch (Entity.getKind()) {
6196 case InitializedEntity::EK_Temporary:
6197 case InitializedEntity::EK_CompoundLiteralInit:
6198 case InitializedEntity::EK_RelatedResult:
6204 switch (Kind.getKind()) {
6205 case InitializationKind::IK_DirectList:
6207 // FIXME: Hack to work around cast weirdness.
6208 case InitializationKind::IK_Direct:
6209 case InitializationKind::IK_Value:
6210 return NumArgs != 1;
6217 PerformConstructorInitialization(Sema &S,
6218 const InitializedEntity &Entity,
6219 const InitializationKind &Kind,
6221 const InitializationSequence::Step& Step,
6222 bool &ConstructorInitRequiresZeroInit,
6223 bool IsListInitialization,
6224 bool IsStdInitListInitialization,
6225 SourceLocation LBraceLoc,
6226 SourceLocation RBraceLoc) {
6227 unsigned NumArgs = Args.size();
6228 CXXConstructorDecl *Constructor
6229 = cast<CXXConstructorDecl>(Step.Function.Function);
6230 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
6232 // Build a call to the selected constructor.
6233 SmallVector<Expr*, 8> ConstructorArgs;
6234 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
6235 ? Kind.getEqualLoc()
6236 : Kind.getLocation();
6238 if (Kind.getKind() == InitializationKind::IK_Default) {
6239 // Force even a trivial, implicit default constructor to be
6240 // semantically checked. We do this explicitly because we don't build
6241 // the definition for completely trivial constructors.
6242 assert(Constructor->getParent() && "No parent class for constructor.");
6243 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
6244 Constructor->isTrivial() && !Constructor->isUsed(false))
6245 S.DefineImplicitDefaultConstructor(Loc, Constructor);
6248 ExprResult CurInit((Expr *)nullptr);
6250 // C++ [over.match.copy]p1:
6251 // - When initializing a temporary to be bound to the first parameter
6252 // of a constructor that takes a reference to possibly cv-qualified
6253 // T as its first argument, called with a single argument in the
6254 // context of direct-initialization, explicit conversion functions
6255 // are also considered.
6256 bool AllowExplicitConv =
6257 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
6258 hasCopyOrMoveCtorParam(S.Context,
6259 getConstructorInfo(Step.Function.FoundDecl));
6261 // Determine the arguments required to actually perform the constructor
6263 if (S.CompleteConstructorCall(Constructor, Args,
6264 Loc, ConstructorArgs,
6266 IsListInitialization))
6270 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
6271 // An explicitly-constructed temporary, e.g., X(1, 2).
6272 if (S.DiagnoseUseOfDecl(Constructor, Loc))
6275 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6277 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
6278 SourceRange ParenOrBraceRange =
6279 (Kind.getKind() == InitializationKind::IK_DirectList)
6280 ? SourceRange(LBraceLoc, RBraceLoc)
6281 : Kind.getParenOrBraceRange();
6283 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
6284 Step.Function.FoundDecl.getDecl())) {
6285 Constructor = S.findInheritingConstructor(Loc, Constructor, Shadow);
6286 if (S.DiagnoseUseOfDecl(Constructor, Loc))
6289 S.MarkFunctionReferenced(Loc, Constructor);
6291 CurInit = CXXTemporaryObjectExpr::Create(
6292 S.Context, Constructor,
6293 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
6294 ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
6295 IsListInitialization, IsStdInitListInitialization,
6296 ConstructorInitRequiresZeroInit);
6298 CXXConstructExpr::ConstructionKind ConstructKind =
6299 CXXConstructExpr::CK_Complete;
6301 if (Entity.getKind() == InitializedEntity::EK_Base) {
6302 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
6303 CXXConstructExpr::CK_VirtualBase :
6304 CXXConstructExpr::CK_NonVirtualBase;
6305 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
6306 ConstructKind = CXXConstructExpr::CK_Delegating;
6309 // Only get the parenthesis or brace range if it is a list initialization or
6310 // direct construction.
6311 SourceRange ParenOrBraceRange;
6312 if (IsListInitialization)
6313 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
6314 else if (Kind.getKind() == InitializationKind::IK_Direct)
6315 ParenOrBraceRange = Kind.getParenOrBraceRange();
6317 // If the entity allows NRVO, mark the construction as elidable
6319 if (Entity.allowsNRVO())
6320 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
6321 Step.Function.FoundDecl,
6322 Constructor, /*Elidable=*/true,
6324 HadMultipleCandidates,
6325 IsListInitialization,
6326 IsStdInitListInitialization,
6327 ConstructorInitRequiresZeroInit,
6331 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
6332 Step.Function.FoundDecl,
6335 HadMultipleCandidates,
6336 IsListInitialization,
6337 IsStdInitListInitialization,
6338 ConstructorInitRequiresZeroInit,
6342 if (CurInit.isInvalid())
6345 // Only check access if all of that succeeded.
6346 S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity);
6347 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
6350 if (const ArrayType *AT = S.Context.getAsArrayType(Entity.getType()))
6351 if (checkDestructorReference(S.Context.getBaseElementType(AT), Loc, S))
6354 if (shouldBindAsTemporary(Entity))
6355 CurInit = S.MaybeBindToTemporary(CurInit.get());
6362 /// The lifetime of a temporary bound to this entity ends at the end of the
6363 /// full-expression, and that's (probably) fine.
6366 /// The lifetime of a temporary bound to this entity is extended to the
6367 /// lifeitme of the entity itself.
6370 /// The lifetime of a temporary bound to this entity probably ends too soon,
6371 /// because the entity is allocated in a new-expression.
6374 /// The lifetime of a temporary bound to this entity ends too soon, because
6375 /// the entity is a return object.
6378 /// The lifetime of a temporary bound to this entity ends too soon, because
6379 /// the entity is the result of a statement expression.
6382 /// This is a mem-initializer: if it would extend a temporary (other than via
6383 /// a default member initializer), the program is ill-formed.
6386 using LifetimeResult =
6387 llvm::PointerIntPair<const InitializedEntity *, 3, LifetimeKind>;
6390 /// Determine the declaration which an initialized entity ultimately refers to,
6391 /// for the purpose of lifetime-extending a temporary bound to a reference in
6392 /// the initialization of \p Entity.
6393 static LifetimeResult getEntityLifetime(
6394 const InitializedEntity *Entity,
6395 const InitializedEntity *InitField = nullptr) {
6396 // C++11 [class.temporary]p5:
6397 switch (Entity->getKind()) {
6398 case InitializedEntity::EK_Variable:
6399 // The temporary [...] persists for the lifetime of the reference
6400 return {Entity, LK_Extended};
6402 case InitializedEntity::EK_Member:
6403 // For subobjects, we look at the complete object.
6404 if (Entity->getParent())
6405 return getEntityLifetime(Entity->getParent(), Entity);
6408 // C++17 [class.base.init]p8:
6409 // A temporary expression bound to a reference member in a
6410 // mem-initializer is ill-formed.
6411 // C++17 [class.base.init]p11:
6412 // A temporary expression bound to a reference member from a
6413 // default member initializer is ill-formed.
6415 // The context of p11 and its example suggest that it's only the use of a
6416 // default member initializer from a constructor that makes the program
6417 // ill-formed, not its mere existence, and that it can even be used by
6418 // aggregate initialization.
6419 return {Entity, Entity->isDefaultMemberInitializer() ? LK_Extended
6420 : LK_MemInitializer};
6422 case InitializedEntity::EK_Binding:
6423 // Per [dcl.decomp]p3, the binding is treated as a variable of reference
6425 return {Entity, LK_Extended};
6427 case InitializedEntity::EK_Parameter:
6428 case InitializedEntity::EK_Parameter_CF_Audited:
6429 // -- A temporary bound to a reference parameter in a function call
6430 // persists until the completion of the full-expression containing
6432 return {nullptr, LK_FullExpression};
6434 case InitializedEntity::EK_Result:
6435 // -- The lifetime of a temporary bound to the returned value in a
6436 // function return statement is not extended; the temporary is
6437 // destroyed at the end of the full-expression in the return statement.
6438 return {nullptr, LK_Return};
6440 case InitializedEntity::EK_StmtExprResult:
6441 // FIXME: Should we lifetime-extend through the result of a statement
6443 return {nullptr, LK_StmtExprResult};
6445 case InitializedEntity::EK_New:
6446 // -- A temporary bound to a reference in a new-initializer persists
6447 // until the completion of the full-expression containing the
6449 return {nullptr, LK_New};
6451 case InitializedEntity::EK_Temporary:
6452 case InitializedEntity::EK_CompoundLiteralInit:
6453 case InitializedEntity::EK_RelatedResult:
6454 // We don't yet know the storage duration of the surrounding temporary.
6455 // Assume it's got full-expression duration for now, it will patch up our
6456 // storage duration if that's not correct.
6457 return {nullptr, LK_FullExpression};
6459 case InitializedEntity::EK_ArrayElement:
6460 // For subobjects, we look at the complete object.
6461 return getEntityLifetime(Entity->getParent(), InitField);
6463 case InitializedEntity::EK_Base:
6464 // For subobjects, we look at the complete object.
6465 if (Entity->getParent())
6466 return getEntityLifetime(Entity->getParent(), InitField);
6467 return {InitField, LK_MemInitializer};
6469 case InitializedEntity::EK_Delegating:
6470 // We can reach this case for aggregate initialization in a constructor:
6471 // struct A { int &&r; };
6472 // struct B : A { B() : A{0} {} };
6473 // In this case, use the outermost field decl as the context.
6474 return {InitField, LK_MemInitializer};
6476 case InitializedEntity::EK_BlockElement:
6477 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
6478 case InitializedEntity::EK_LambdaCapture:
6479 case InitializedEntity::EK_VectorElement:
6480 case InitializedEntity::EK_ComplexElement:
6481 return {nullptr, LK_FullExpression};
6483 case InitializedEntity::EK_Exception:
6484 // FIXME: Can we diagnose lifetime problems with exceptions?
6485 return {nullptr, LK_FullExpression};
6487 llvm_unreachable("unknown entity kind");
6491 enum ReferenceKind {
6492 /// Lifetime would be extended by a reference binding to a temporary.
6493 RK_ReferenceBinding,
6494 /// Lifetime would be extended by a std::initializer_list object binding to
6495 /// its backing array.
6496 RK_StdInitializerList,
6499 /// A temporary or local variable. This will be one of:
6500 /// * A MaterializeTemporaryExpr.
6501 /// * A DeclRefExpr whose declaration is a local.
6502 /// * An AddrLabelExpr.
6503 /// * A BlockExpr for a block with captures.
6504 using Local = Expr*;
6506 /// Expressions we stepped over when looking for the local state. Any steps
6507 /// that would inhibit lifetime extension or take us out of subexpressions of
6508 /// the initializer are included.
6509 struct IndirectLocalPathEntry {
6518 const Decl *D = nullptr;
6519 IndirectLocalPathEntry() {}
6520 IndirectLocalPathEntry(EntryKind K, Expr *E) : Kind(K), E(E) {}
6521 IndirectLocalPathEntry(EntryKind K, Expr *E, const Decl *D)
6522 : Kind(K), E(E), D(D) {}
6525 using IndirectLocalPath = llvm::SmallVectorImpl<IndirectLocalPathEntry>;
6527 struct RevertToOldSizeRAII {
6528 IndirectLocalPath &Path;
6529 unsigned OldSize = Path.size();
6530 RevertToOldSizeRAII(IndirectLocalPath &Path) : Path(Path) {}
6531 ~RevertToOldSizeRAII() { Path.resize(OldSize); }
6534 using LocalVisitor = llvm::function_ref<bool(IndirectLocalPath &Path, Local L,
6538 static bool isVarOnPath(IndirectLocalPath &Path, VarDecl *VD) {
6540 if (E.Kind == IndirectLocalPathEntry::VarInit && E.D == VD)
6545 static bool pathContainsInit(IndirectLocalPath &Path) {
6546 return llvm::any_of(Path, [=](IndirectLocalPathEntry E) {
6547 return E.Kind == IndirectLocalPathEntry::DefaultInit ||
6548 E.Kind == IndirectLocalPathEntry::VarInit;
6552 static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
6553 Expr *Init, LocalVisitor Visit,
6554 bool RevisitSubinits);
6556 static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
6557 Expr *Init, ReferenceKind RK,
6558 LocalVisitor Visit);
6560 static bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD) {
6561 const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
6564 // Don't declare this variable in the second operand of the for-statement;
6565 // GCC miscompiles that by ending its lifetime before evaluating the
6566 // third operand. See gcc.gnu.org/PR86769.
6567 AttributedTypeLoc ATL;
6568 for (TypeLoc TL = TSI->getTypeLoc();
6569 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6570 TL = ATL.getModifiedLoc()) {
6571 if (ATL.getAttrAs<LifetimeBoundAttr>())
6577 static void visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call,
6578 LocalVisitor Visit) {
6579 const FunctionDecl *Callee;
6580 ArrayRef<Expr*> Args;
6582 if (auto *CE = dyn_cast<CallExpr>(Call)) {
6583 Callee = CE->getDirectCallee();
6584 Args = llvm::makeArrayRef(CE->getArgs(), CE->getNumArgs());
6586 auto *CCE = cast<CXXConstructExpr>(Call);
6587 Callee = CCE->getConstructor();
6588 Args = llvm::makeArrayRef(CCE->getArgs(), CCE->getNumArgs());
6593 Expr *ObjectArg = nullptr;
6594 if (isa<CXXOperatorCallExpr>(Call) && Callee->isCXXInstanceMember()) {
6595 ObjectArg = Args[0];
6596 Args = Args.slice(1);
6597 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) {
6598 ObjectArg = MCE->getImplicitObjectArgument();
6601 auto VisitLifetimeBoundArg = [&](const Decl *D, Expr *Arg) {
6602 Path.push_back({IndirectLocalPathEntry::LifetimeBoundCall, Arg, D});
6603 if (Arg->isGLValue())
6604 visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
6607 visitLocalsRetainedByInitializer(Path, Arg, Visit, true);
6611 if (ObjectArg && implicitObjectParamIsLifetimeBound(Callee))
6612 VisitLifetimeBoundArg(Callee, ObjectArg);
6614 for (unsigned I = 0,
6615 N = std::min<unsigned>(Callee->getNumParams(), Args.size());
6617 if (Callee->getParamDecl(I)->hasAttr<LifetimeBoundAttr>())
6618 VisitLifetimeBoundArg(Callee->getParamDecl(I), Args[I]);
6622 /// Visit the locals that would be reachable through a reference bound to the
6623 /// glvalue expression \c Init.
6624 static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
6625 Expr *Init, ReferenceKind RK,
6626 LocalVisitor Visit) {
6627 RevertToOldSizeRAII RAII(Path);
6629 // Walk past any constructs which we can lifetime-extend across.
6634 if (auto *FE = dyn_cast<FullExpr>(Init))
6635 Init = FE->getSubExpr();
6637 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
6638 // If this is just redundant braces around an initializer, step over it.
6639 if (ILE->isTransparent())
6640 Init = ILE->getInit(0);
6643 // Step over any subobject adjustments; we may have a materialized
6644 // temporary inside them.
6645 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
6647 // Per current approach for DR1376, look through casts to reference type
6648 // when performing lifetime extension.
6649 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
6650 if (CE->getSubExpr()->isGLValue())
6651 Init = CE->getSubExpr();
6653 // Per the current approach for DR1299, look through array element access
6654 // on array glvalues when performing lifetime extension.
6655 if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init)) {
6656 Init = ASE->getBase();
6657 auto *ICE = dyn_cast<ImplicitCastExpr>(Init);
6658 if (ICE && ICE->getCastKind() == CK_ArrayToPointerDecay)
6659 Init = ICE->getSubExpr();
6661 // We can't lifetime extend through this but we might still find some
6662 // retained temporaries.
6663 return visitLocalsRetainedByInitializer(Path, Init, Visit, true);
6666 // Step into CXXDefaultInitExprs so we can diagnose cases where a
6667 // constructor inherits one as an implicit mem-initializer.
6668 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
6670 {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
6671 Init = DIE->getExpr();
6673 } while (Init != Old);
6675 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) {
6676 if (Visit(Path, Local(MTE), RK))
6677 visitLocalsRetainedByInitializer(Path, MTE->GetTemporaryExpr(), Visit,
6681 if (isa<CallExpr>(Init))
6682 return visitLifetimeBoundArguments(Path, Init, Visit);
6684 switch (Init->getStmtClass()) {
6685 case Stmt::DeclRefExprClass: {
6686 // If we find the name of a local non-reference parameter, we could have a
6687 // lifetime problem.
6688 auto *DRE = cast<DeclRefExpr>(Init);
6689 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
6690 if (VD && VD->hasLocalStorage() &&
6691 !DRE->refersToEnclosingVariableOrCapture()) {
6692 if (!VD->getType()->isReferenceType()) {
6693 Visit(Path, Local(DRE), RK);
6694 } else if (isa<ParmVarDecl>(DRE->getDecl())) {
6695 // The lifetime of a reference parameter is unknown; assume it's OK
6698 } else if (VD->getInit() && !isVarOnPath(Path, VD)) {
6699 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
6700 visitLocalsRetainedByReferenceBinding(Path, VD->getInit(),
6701 RK_ReferenceBinding, Visit);
6707 case Stmt::UnaryOperatorClass: {
6708 // The only unary operator that make sense to handle here
6709 // is Deref. All others don't resolve to a "name." This includes
6710 // handling all sorts of rvalues passed to a unary operator.
6711 const UnaryOperator *U = cast<UnaryOperator>(Init);
6712 if (U->getOpcode() == UO_Deref)
6713 visitLocalsRetainedByInitializer(Path, U->getSubExpr(), Visit, true);
6717 case Stmt::OMPArraySectionExprClass: {
6718 visitLocalsRetainedByInitializer(
6719 Path, cast<OMPArraySectionExpr>(Init)->getBase(), Visit, true);
6723 case Stmt::ConditionalOperatorClass:
6724 case Stmt::BinaryConditionalOperatorClass: {
6725 auto *C = cast<AbstractConditionalOperator>(Init);
6726 if (!C->getTrueExpr()->getType()->isVoidType())
6727 visitLocalsRetainedByReferenceBinding(Path, C->getTrueExpr(), RK, Visit);
6728 if (!C->getFalseExpr()->getType()->isVoidType())
6729 visitLocalsRetainedByReferenceBinding(Path, C->getFalseExpr(), RK, Visit);
6733 // FIXME: Visit the left-hand side of an -> or ->*.
6740 /// Visit the locals that would be reachable through an object initialized by
6741 /// the prvalue expression \c Init.
6742 static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
6743 Expr *Init, LocalVisitor Visit,
6744 bool RevisitSubinits) {
6745 RevertToOldSizeRAII RAII(Path);
6751 // Step into CXXDefaultInitExprs so we can diagnose cases where a
6752 // constructor inherits one as an implicit mem-initializer.
6753 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
6754 Path.push_back({IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
6755 Init = DIE->getExpr();
6758 if (auto *FE = dyn_cast<FullExpr>(Init))
6759 Init = FE->getSubExpr();
6761 // Dig out the expression which constructs the extended temporary.
6762 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
6764 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
6765 Init = BTE->getSubExpr();
6767 Init = Init->IgnoreParens();
6769 // Step over value-preserving rvalue casts.
6770 if (auto *CE = dyn_cast<CastExpr>(Init)) {
6771 switch (CE->getCastKind()) {
6772 case CK_LValueToRValue:
6773 // If we can match the lvalue to a const object, we can look at its
6775 Path.push_back({IndirectLocalPathEntry::LValToRVal, CE});
6776 return visitLocalsRetainedByReferenceBinding(
6777 Path, Init, RK_ReferenceBinding,
6778 [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool {
6779 if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
6780 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
6781 if (VD && VD->getType().isConstQualified() && VD->getInit() &&
6782 !isVarOnPath(Path, VD)) {
6783 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
6784 visitLocalsRetainedByInitializer(Path, VD->getInit(), Visit, true);
6786 } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L)) {
6787 if (MTE->getType().isConstQualified())
6788 visitLocalsRetainedByInitializer(Path, MTE->GetTemporaryExpr(),
6794 // We assume that objects can be retained by pointers cast to integers,
6795 // but not if the integer is cast to floating-point type or to _Complex.
6796 // We assume that casts to 'bool' do not preserve enough information to
6797 // retain a local object.
6800 case CK_BaseToDerived:
6801 case CK_DerivedToBase:
6802 case CK_UncheckedDerivedToBase:
6805 case CK_UserDefinedConversion:
6806 case CK_ConstructorConversion:
6807 case CK_IntegralToPointer:
6808 case CK_PointerToIntegral:
6809 case CK_VectorSplat:
6810 case CK_IntegralCast:
6811 case CK_CPointerToObjCPointerCast:
6812 case CK_BlockPointerToObjCPointerCast:
6813 case CK_AnyPointerToBlockPointerCast:
6814 case CK_AddressSpaceConversion:
6817 case CK_ArrayToPointerDecay:
6818 // Model array-to-pointer decay as taking the address of the array
6820 Path.push_back({IndirectLocalPathEntry::AddressOf, CE});
6821 return visitLocalsRetainedByReferenceBinding(Path, CE->getSubExpr(),
6822 RK_ReferenceBinding, Visit);
6828 Init = CE->getSubExpr();
6830 } while (Old != Init);
6832 // C++17 [dcl.init.list]p6:
6833 // initializing an initializer_list object from the array extends the
6834 // lifetime of the array exactly like binding a reference to a temporary.
6835 if (auto *ILE = dyn_cast<CXXStdInitializerListExpr>(Init))
6836 return visitLocalsRetainedByReferenceBinding(Path, ILE->getSubExpr(),
6837 RK_StdInitializerList, Visit);
6839 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
6840 // We already visited the elements of this initializer list while
6841 // performing the initialization. Don't visit them again unless we've
6842 // changed the lifetime of the initialized entity.
6843 if (!RevisitSubinits)
6846 if (ILE->isTransparent())
6847 return visitLocalsRetainedByInitializer(Path, ILE->getInit(0), Visit,
6850 if (ILE->getType()->isArrayType()) {
6851 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
6852 visitLocalsRetainedByInitializer(Path, ILE->getInit(I), Visit,
6857 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
6858 assert(RD->isAggregate() && "aggregate init on non-aggregate");
6860 // If we lifetime-extend a braced initializer which is initializing an
6861 // aggregate, and that aggregate contains reference members which are
6862 // bound to temporaries, those temporaries are also lifetime-extended.
6863 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
6864 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
6865 visitLocalsRetainedByReferenceBinding(Path, ILE->getInit(0),
6866 RK_ReferenceBinding, Visit);
6869 for (; Index < RD->getNumBases() && Index < ILE->getNumInits(); ++Index)
6870 visitLocalsRetainedByInitializer(Path, ILE->getInit(Index), Visit,
6872 for (const auto *I : RD->fields()) {
6873 if (Index >= ILE->getNumInits())
6875 if (I->isUnnamedBitfield())
6877 Expr *SubInit = ILE->getInit(Index);
6878 if (I->getType()->isReferenceType())
6879 visitLocalsRetainedByReferenceBinding(Path, SubInit,
6880 RK_ReferenceBinding, Visit);
6882 // This might be either aggregate-initialization of a member or
6883 // initialization of a std::initializer_list object. Regardless,
6884 // we should recursively lifetime-extend that initializer.
6885 visitLocalsRetainedByInitializer(Path, SubInit, Visit,
6894 // The lifetime of an init-capture is that of the closure object constructed
6895 // by a lambda-expression.
6896 if (auto *LE = dyn_cast<LambdaExpr>(Init)) {
6897 for (Expr *E : LE->capture_inits()) {
6901 visitLocalsRetainedByReferenceBinding(Path, E, RK_ReferenceBinding,
6904 visitLocalsRetainedByInitializer(Path, E, Visit, true);
6908 if (isa<CallExpr>(Init) || isa<CXXConstructExpr>(Init))
6909 return visitLifetimeBoundArguments(Path, Init, Visit);
6911 switch (Init->getStmtClass()) {
6912 case Stmt::UnaryOperatorClass: {
6913 auto *UO = cast<UnaryOperator>(Init);
6914 // If the initializer is the address of a local, we could have a lifetime
6916 if (UO->getOpcode() == UO_AddrOf) {
6917 // If this is &rvalue, then it's ill-formed and we have already diagnosed
6918 // it. Don't produce a redundant warning about the lifetime of the
6920 if (isa<MaterializeTemporaryExpr>(UO->getSubExpr()))
6923 Path.push_back({IndirectLocalPathEntry::AddressOf, UO});
6924 visitLocalsRetainedByReferenceBinding(Path, UO->getSubExpr(),
6925 RK_ReferenceBinding, Visit);
6930 case Stmt::BinaryOperatorClass: {
6931 // Handle pointer arithmetic.
6932 auto *BO = cast<BinaryOperator>(Init);
6933 BinaryOperatorKind BOK = BO->getOpcode();
6934 if (!BO->getType()->isPointerType() || (BOK != BO_Add && BOK != BO_Sub))
6937 if (BO->getLHS()->getType()->isPointerType())
6938 visitLocalsRetainedByInitializer(Path, BO->getLHS(), Visit, true);
6939 else if (BO->getRHS()->getType()->isPointerType())
6940 visitLocalsRetainedByInitializer(Path, BO->getRHS(), Visit, true);
6944 case Stmt::ConditionalOperatorClass:
6945 case Stmt::BinaryConditionalOperatorClass: {
6946 auto *C = cast<AbstractConditionalOperator>(Init);
6947 // In C++, we can have a throw-expression operand, which has 'void' type
6948 // and isn't interesting from a lifetime perspective.
6949 if (!C->getTrueExpr()->getType()->isVoidType())
6950 visitLocalsRetainedByInitializer(Path, C->getTrueExpr(), Visit, true);
6951 if (!C->getFalseExpr()->getType()->isVoidType())
6952 visitLocalsRetainedByInitializer(Path, C->getFalseExpr(), Visit, true);
6956 case Stmt::BlockExprClass:
6957 if (cast<BlockExpr>(Init)->getBlockDecl()->hasCaptures()) {
6958 // This is a local block, whose lifetime is that of the function.
6959 Visit(Path, Local(cast<BlockExpr>(Init)), RK_ReferenceBinding);
6963 case Stmt::AddrLabelExprClass:
6964 // We want to warn if the address of a label would escape the function.
6965 Visit(Path, Local(cast<AddrLabelExpr>(Init)), RK_ReferenceBinding);
6973 /// Determine whether this is an indirect path to a temporary that we are
6974 /// supposed to lifetime-extend along (but don't).
6975 static bool shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path) {
6976 for (auto Elem : Path) {
6977 if (Elem.Kind != IndirectLocalPathEntry::DefaultInit)
6983 /// Find the range for the first interesting entry in the path at or after I.
6984 static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I,
6986 for (unsigned N = Path.size(); I != N; ++I) {
6987 switch (Path[I].Kind) {
6988 case IndirectLocalPathEntry::AddressOf:
6989 case IndirectLocalPathEntry::LValToRVal:
6990 case IndirectLocalPathEntry::LifetimeBoundCall:
6991 // These exist primarily to mark the path as not permitting or
6992 // supporting lifetime extension.
6995 case IndirectLocalPathEntry::DefaultInit:
6996 case IndirectLocalPathEntry::VarInit:
6997 return Path[I].E->getSourceRange();
7000 return E->getSourceRange();
7003 void Sema::checkInitializerLifetime(const InitializedEntity &Entity,
7005 LifetimeResult LR = getEntityLifetime(&Entity);
7006 LifetimeKind LK = LR.getInt();
7007 const InitializedEntity *ExtendingEntity = LR.getPointer();
7009 // If this entity doesn't have an interesting lifetime, don't bother looking
7010 // for temporaries within its initializer.
7011 if (LK == LK_FullExpression)
7014 auto TemporaryVisitor = [&](IndirectLocalPath &Path, Local L,
7015 ReferenceKind RK) -> bool {
7016 SourceRange DiagRange = nextPathEntryRange(Path, 0, L);
7017 SourceLocation DiagLoc = DiagRange.getBegin();
7020 case LK_FullExpression:
7021 llvm_unreachable("already handled this");
7024 auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L);
7026 // The initialized entity has lifetime beyond the full-expression,
7027 // and the local entity does too, so don't warn.
7029 // FIXME: We should consider warning if a static / thread storage
7030 // duration variable retains an automatic storage duration local.
7034 // Lifetime-extend the temporary.
7036 // Update the storage duration of the materialized temporary.
7037 // FIXME: Rebuild the expression instead of mutating it.
7038 MTE->setExtendingDecl(ExtendingEntity->getDecl(),
7039 ExtendingEntity->allocateManglingNumber());
7040 // Also visit the temporaries lifetime-extended by this initializer.
7044 if (shouldLifetimeExtendThroughPath(Path)) {
7045 // We're supposed to lifetime-extend the temporary along this path (per
7046 // the resolution of DR1815), but we don't support that yet.
7048 // FIXME: Properly handle this situation. Perhaps the easiest approach
7049 // would be to clone the initializer expression on each use that would
7050 // lifetime extend its temporaries.
7051 Diag(DiagLoc, diag::warn_unsupported_lifetime_extension)
7054 // If the path goes through the initialization of a variable or field,
7055 // it can't possibly reach a temporary created in this full-expression.
7056 // We will have already diagnosed any problems with the initializer.
7057 if (pathContainsInit(Path))
7060 Diag(DiagLoc, diag::warn_dangling_variable)
7061 << RK << !Entity.getParent()
7062 << ExtendingEntity->getDecl()->isImplicit()
7063 << ExtendingEntity->getDecl() << Init->isGLValue() << DiagRange;
7068 case LK_MemInitializer: {
7069 if (isa<MaterializeTemporaryExpr>(L)) {
7070 // Under C++ DR1696, if a mem-initializer (or a default member
7071 // initializer used by the absence of one) would lifetime-extend a
7072 // temporary, the program is ill-formed.
7073 if (auto *ExtendingDecl =
7074 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
7075 bool IsSubobjectMember = ExtendingEntity != &Entity;
7076 Diag(DiagLoc, shouldLifetimeExtendThroughPath(Path)
7077 ? diag::err_dangling_member
7078 : diag::warn_dangling_member)
7079 << ExtendingDecl << IsSubobjectMember << RK << DiagRange;
7080 // Don't bother adding a note pointing to the field if we're inside
7081 // its default member initializer; our primary diagnostic points to
7082 // the same place in that case.
7084 Path.back().Kind != IndirectLocalPathEntry::DefaultInit) {
7085 Diag(ExtendingDecl->getLocation(),
7086 diag::note_lifetime_extending_member_declared_here)
7087 << RK << IsSubobjectMember;
7090 // We have a mem-initializer but no particular field within it; this
7091 // is either a base class or a delegating initializer directly
7092 // initializing the base-class from something that doesn't live long
7095 // FIXME: Warn on this.
7099 // Paths via a default initializer can only occur during error recovery
7100 // (there's no other way that a default initializer can refer to a
7101 // local). Don't produce a bogus warning on those cases.
7102 if (pathContainsInit(Path))
7105 auto *DRE = dyn_cast<DeclRefExpr>(L);
7106 auto *VD = DRE ? dyn_cast<VarDecl>(DRE->getDecl()) : nullptr;
7108 // A member was initialized to a local block.
7109 // FIXME: Warn on this.
7114 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
7115 bool IsPointer = Member->getType()->isAnyPointerType();
7116 Diag(DiagLoc, IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
7117 : diag::warn_bind_ref_member_to_parameter)
7118 << Member << VD << isa<ParmVarDecl>(VD) << DiagRange;
7119 Diag(Member->getLocation(),
7120 diag::note_ref_or_ptr_member_declared_here)
7121 << (unsigned)IsPointer;
7128 if (isa<MaterializeTemporaryExpr>(L)) {
7129 Diag(DiagLoc, RK == RK_ReferenceBinding
7130 ? diag::warn_new_dangling_reference
7131 : diag::warn_new_dangling_initializer_list)
7132 << !Entity.getParent() << DiagRange;
7134 // We can't determine if the allocation outlives the local declaration.
7140 case LK_StmtExprResult:
7141 if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
7142 // We can't determine if the local variable outlives the statement
7144 if (LK == LK_StmtExprResult)
7146 Diag(DiagLoc, diag::warn_ret_stack_addr_ref)
7147 << Entity.getType()->isReferenceType() << DRE->getDecl()
7148 << isa<ParmVarDecl>(DRE->getDecl()) << DiagRange;
7149 } else if (isa<BlockExpr>(L)) {
7150 Diag(DiagLoc, diag::err_ret_local_block) << DiagRange;
7151 } else if (isa<AddrLabelExpr>(L)) {
7152 // Don't warn when returning a label from a statement expression.
7153 // Leaving the scope doesn't end its lifetime.
7154 if (LK == LK_StmtExprResult)
7156 Diag(DiagLoc, diag::warn_ret_addr_label) << DiagRange;
7158 Diag(DiagLoc, diag::warn_ret_local_temp_addr_ref)
7159 << Entity.getType()->isReferenceType() << DiagRange;
7164 for (unsigned I = 0; I != Path.size(); ++I) {
7165 auto Elem = Path[I];
7167 switch (Elem.Kind) {
7168 case IndirectLocalPathEntry::AddressOf:
7169 case IndirectLocalPathEntry::LValToRVal:
7170 // These exist primarily to mark the path as not permitting or
7171 // supporting lifetime extension.
7174 case IndirectLocalPathEntry::LifetimeBoundCall:
7175 // FIXME: Consider adding a note for this.
7178 case IndirectLocalPathEntry::DefaultInit: {
7179 auto *FD = cast<FieldDecl>(Elem.D);
7180 Diag(FD->getLocation(), diag::note_init_with_default_member_initalizer)
7181 << FD << nextPathEntryRange(Path, I + 1, L);
7185 case IndirectLocalPathEntry::VarInit:
7186 const VarDecl *VD = cast<VarDecl>(Elem.D);
7187 Diag(VD->getLocation(), diag::note_local_var_initializer)
7188 << VD->getType()->isReferenceType()
7189 << VD->isImplicit() << VD->getDeclName()
7190 << nextPathEntryRange(Path, I + 1, L);
7195 // We didn't lifetime-extend, so don't go any further; we don't need more
7196 // warnings or errors on inner temporaries within this one's initializer.
7200 llvm::SmallVector<IndirectLocalPathEntry, 8> Path;
7201 if (Init->isGLValue())
7202 visitLocalsRetainedByReferenceBinding(Path, Init, RK_ReferenceBinding,
7205 visitLocalsRetainedByInitializer(Path, Init, TemporaryVisitor, false);
7208 static void DiagnoseNarrowingInInitList(Sema &S,
7209 const ImplicitConversionSequence &ICS,
7210 QualType PreNarrowingType,
7211 QualType EntityType,
7212 const Expr *PostInit);
7214 /// Provide warnings when std::move is used on construction.
7215 static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
7216 bool IsReturnStmt) {
7220 if (S.inTemplateInstantiation())
7223 QualType DestType = InitExpr->getType();
7224 if (!DestType->isRecordType())
7227 unsigned DiagID = 0;
7229 const CXXConstructExpr *CCE =
7230 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
7231 if (!CCE || CCE->getNumArgs() != 1)
7234 if (!CCE->getConstructor()->isCopyOrMoveConstructor())
7237 InitExpr = CCE->getArg(0)->IgnoreImpCasts();
7240 // Find the std::move call and get the argument.
7241 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
7242 if (!CE || !CE->isCallToStdMove())
7245 const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
7248 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
7249 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
7252 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
7253 if (!VD || !VD->hasLocalStorage())
7256 // __block variables are not moved implicitly.
7257 if (VD->hasAttr<BlocksAttr>())
7260 QualType SourceType = VD->getType();
7261 if (!SourceType->isRecordType())
7264 if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
7268 // If we're returning a function parameter, copy elision
7270 if (isa<ParmVarDecl>(VD))
7271 DiagID = diag::warn_redundant_move_on_return;
7273 DiagID = diag::warn_pessimizing_move_on_return;
7275 DiagID = diag::warn_pessimizing_move_on_initialization;
7276 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
7277 if (!ArgStripped->isRValue() || !ArgStripped->getType()->isRecordType())
7281 S.Diag(CE->getBeginLoc(), DiagID);
7283 // Get all the locations for a fix-it. Don't emit the fix-it if any location
7284 // is within a macro.
7285 SourceLocation CallBegin = CE->getCallee()->getBeginLoc();
7286 if (CallBegin.isMacroID())
7288 SourceLocation RParen = CE->getRParenLoc();
7289 if (RParen.isMacroID())
7291 SourceLocation LParen;
7292 SourceLocation ArgLoc = Arg->getBeginLoc();
7294 // Special testing for the argument location. Since the fix-it needs the
7295 // location right before the argument, the argument location can be in a
7296 // macro only if it is at the beginning of the macro.
7297 while (ArgLoc.isMacroID() &&
7298 S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) {
7299 ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).getBegin();
7302 if (LParen.isMacroID())
7305 LParen = ArgLoc.getLocWithOffset(-1);
7307 S.Diag(CE->getBeginLoc(), diag::note_remove_move)
7308 << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
7309 << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
7312 static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
7313 // Check to see if we are dereferencing a null pointer. If so, this is
7314 // undefined behavior, so warn about it. This only handles the pattern
7315 // "*null", which is a very syntactic check.
7316 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
7317 if (UO->getOpcode() == UO_Deref &&
7318 UO->getSubExpr()->IgnoreParenCasts()->
7319 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
7320 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
7321 S.PDiag(diag::warn_binding_null_to_reference)
7322 << UO->getSubExpr()->getSourceRange());
7326 MaterializeTemporaryExpr *
7327 Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
7328 bool BoundToLvalueReference) {
7329 auto MTE = new (Context)
7330 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
7332 // Order an ExprWithCleanups for lifetime marks.
7334 // TODO: It'll be good to have a single place to check the access of the
7335 // destructor and generate ExprWithCleanups for various uses. Currently these
7336 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
7337 // but there may be a chance to merge them.
7338 Cleanup.setExprNeedsCleanups(false);
7342 ExprResult Sema::TemporaryMaterializationConversion(Expr *E) {
7343 // In C++98, we don't want to implicitly create an xvalue.
7344 // FIXME: This means that AST consumers need to deal with "prvalues" that
7345 // denote materialized temporaries. Maybe we should add another ValueKind
7346 // for "xvalue pretending to be a prvalue" for C++98 support.
7347 if (!E->isRValue() || !getLangOpts().CPlusPlus11)
7350 // C++1z [conv.rval]/1: T shall be a complete type.
7351 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
7352 // If so, we should check for a non-abstract class type here too.
7353 QualType T = E->getType();
7354 if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
7357 return CreateMaterializeTemporaryExpr(E->getType(), E, false);
7360 ExprResult Sema::PerformQualificationConversion(Expr *E, QualType Ty,
7362 CheckedConversionKind CCK) {
7364 CastKind CK = CK_NoOp;
7366 if (VK == VK_RValue) {
7367 auto PointeeTy = Ty->getPointeeType();
7368 auto ExprPointeeTy = E->getType()->getPointeeType();
7369 if (!PointeeTy.isNull() &&
7370 PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace())
7371 CK = CK_AddressSpaceConversion;
7372 } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) {
7373 CK = CK_AddressSpaceConversion;
7376 return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK);
7379 ExprResult InitializationSequence::Perform(Sema &S,
7380 const InitializedEntity &Entity,
7381 const InitializationKind &Kind,
7383 QualType *ResultType) {
7385 Diagnose(S, Entity, Kind, Args);
7388 if (!ZeroInitializationFixit.empty()) {
7389 unsigned DiagID = diag::err_default_init_const;
7390 if (Decl *D = Entity.getDecl())
7391 if (S.getLangOpts().MSVCCompat && D->hasAttr<SelectAnyAttr>())
7392 DiagID = diag::ext_default_init_const;
7394 // The initialization would have succeeded with this fixit. Since the fixit
7395 // is on the error, we need to build a valid AST in this case, so this isn't
7396 // handled in the Failed() branch above.
7397 QualType DestType = Entity.getType();
7398 S.Diag(Kind.getLocation(), DiagID)
7399 << DestType << (bool)DestType->getAs<RecordType>()
7400 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
7401 ZeroInitializationFixit);
7404 if (getKind() == DependentSequence) {
7405 // If the declaration is a non-dependent, incomplete array type
7406 // that has an initializer, then its type will be completed once
7407 // the initializer is instantiated.
7408 if (ResultType && !Entity.getType()->isDependentType() &&
7410 QualType DeclType = Entity.getType();
7411 if (const IncompleteArrayType *ArrayT
7412 = S.Context.getAsIncompleteArrayType(DeclType)) {
7413 // FIXME: We don't currently have the ability to accurately
7414 // compute the length of an initializer list without
7415 // performing full type-checking of the initializer list
7416 // (since we have to determine where braces are implicitly
7417 // introduced and such). So, we fall back to making the array
7418 // type a dependently-sized array type with no specified
7420 if (isa<InitListExpr>((Expr *)Args[0])) {
7421 SourceRange Brackets;
7423 // Scavange the location of the brackets from the entity, if we can.
7424 if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) {
7425 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
7426 TypeLoc TL = TInfo->getTypeLoc();
7427 if (IncompleteArrayTypeLoc ArrayLoc =
7428 TL.getAs<IncompleteArrayTypeLoc>())
7429 Brackets = ArrayLoc.getBracketsRange();
7434 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
7435 /*NumElts=*/nullptr,
7436 ArrayT->getSizeModifier(),
7437 ArrayT->getIndexTypeCVRQualifiers(),
7443 if (Kind.getKind() == InitializationKind::IK_Direct &&
7444 !Kind.isExplicitCast()) {
7445 // Rebuild the ParenListExpr.
7446 SourceRange ParenRange = Kind.getParenOrBraceRange();
7447 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
7450 assert(Kind.getKind() == InitializationKind::IK_Copy ||
7451 Kind.isExplicitCast() ||
7452 Kind.getKind() == InitializationKind::IK_DirectList);
7453 return ExprResult(Args[0]);
7456 // No steps means no initialization.
7458 return ExprResult((Expr *)nullptr);
7460 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
7461 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
7462 !Entity.isParameterKind()) {
7463 // Produce a C++98 compatibility warning if we are initializing a reference
7464 // from an initializer list. For parameters, we produce a better warning
7466 Expr *Init = Args[0];
7467 S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init)
7468 << Init->getSourceRange();
7471 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
7472 QualType ETy = Entity.getType();
7473 Qualifiers TyQualifiers = ETy.getQualifiers();
7474 bool HasGlobalAS = TyQualifiers.hasAddressSpace() &&
7475 TyQualifiers.getAddressSpace() == LangAS::opencl_global;
7477 if (S.getLangOpts().OpenCLVersion >= 200 &&
7478 ETy->isAtomicType() && !HasGlobalAS &&
7479 Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
7480 S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init)
7482 << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc());
7486 QualType DestType = Entity.getType().getNonReferenceType();
7487 // FIXME: Ugly hack around the fact that Entity.getType() is not
7488 // the same as Entity.getDecl()->getType() in cases involving type merging,
7489 // and we want latter when it makes sense.
7491 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
7494 ExprResult CurInit((Expr *)nullptr);
7495 SmallVector<Expr*, 4> ArrayLoopCommonExprs;
7497 // For initialization steps that start with a single initializer,
7498 // grab the only argument out the Args and place it into the "current"
7500 switch (Steps.front().Kind) {
7501 case SK_ResolveAddressOfOverloadedFunction:
7502 case SK_CastDerivedToBaseRValue:
7503 case SK_CastDerivedToBaseXValue:
7504 case SK_CastDerivedToBaseLValue:
7505 case SK_BindReference:
7506 case SK_BindReferenceToTemporary:
7508 case SK_ExtraneousCopyToTemporary:
7509 case SK_UserConversion:
7510 case SK_QualificationConversionLValue:
7511 case SK_QualificationConversionXValue:
7512 case SK_QualificationConversionRValue:
7513 case SK_AtomicConversion:
7514 case SK_ConversionSequence:
7515 case SK_ConversionSequenceNoNarrowing:
7516 case SK_ListInitialization:
7517 case SK_UnwrapInitList:
7518 case SK_RewrapInitList:
7519 case SK_CAssignment:
7521 case SK_ObjCObjectConversion:
7522 case SK_ArrayLoopIndex:
7523 case SK_ArrayLoopInit:
7525 case SK_GNUArrayInit:
7526 case SK_ParenthesizedArrayInit:
7527 case SK_PassByIndirectCopyRestore:
7528 case SK_PassByIndirectRestore:
7529 case SK_ProduceObjCObject:
7530 case SK_StdInitializerList:
7531 case SK_OCLSamplerInit:
7532 case SK_OCLZeroOpaqueType: {
7533 assert(Args.size() == 1);
7535 if (!CurInit.get()) return ExprError();
7539 case SK_ConstructorInitialization:
7540 case SK_ConstructorInitializationFromList:
7541 case SK_StdInitializerListConstructorCall:
7542 case SK_ZeroInitialization:
7546 // Promote from an unevaluated context to an unevaluated list context in
7547 // C++11 list-initialization; we need to instantiate entities usable in
7548 // constant expressions here in order to perform narrowing checks =(
7549 EnterExpressionEvaluationContext Evaluated(
7550 S, EnterExpressionEvaluationContext::InitList,
7551 CurInit.get() && isa<InitListExpr>(CurInit.get()));
7553 // C++ [class.abstract]p2:
7554 // no objects of an abstract class can be created except as subobjects
7555 // of a class derived from it
7556 auto checkAbstractType = [&](QualType T) -> bool {
7557 if (Entity.getKind() == InitializedEntity::EK_Base ||
7558 Entity.getKind() == InitializedEntity::EK_Delegating)
7560 return S.RequireNonAbstractType(Kind.getLocation(), T,
7561 diag::err_allocation_of_abstract_type);
7564 // Walk through the computed steps for the initialization sequence,
7565 // performing the specified conversions along the way.
7566 bool ConstructorInitRequiresZeroInit = false;
7567 for (step_iterator Step = step_begin(), StepEnd = step_end();
7568 Step != StepEnd; ++Step) {
7569 if (CurInit.isInvalid())
7572 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
7574 switch (Step->Kind) {
7575 case SK_ResolveAddressOfOverloadedFunction:
7576 // Overload resolution determined which function invoke; update the
7577 // initializer to reflect that choice.
7578 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
7579 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
7581 CurInit = S.FixOverloadedFunctionReference(CurInit,
7582 Step->Function.FoundDecl,
7583 Step->Function.Function);
7586 case SK_CastDerivedToBaseRValue:
7587 case SK_CastDerivedToBaseXValue:
7588 case SK_CastDerivedToBaseLValue: {
7589 // We have a derived-to-base cast that produces either an rvalue or an
7590 // lvalue. Perform that cast.
7592 CXXCastPath BasePath;
7594 // Casts to inaccessible base classes are allowed with C-style casts.
7595 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
7596 if (S.CheckDerivedToBaseConversion(
7597 SourceType, Step->Type, CurInit.get()->getBeginLoc(),
7598 CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess))
7602 Step->Kind == SK_CastDerivedToBaseLValue ?
7604 (Step->Kind == SK_CastDerivedToBaseXValue ?
7608 ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase,
7609 CurInit.get(), &BasePath, VK);
7613 case SK_BindReference:
7614 // Reference binding does not have any corresponding ASTs.
7616 // Check exception specifications
7617 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
7620 // We don't check for e.g. function pointers here, since address
7621 // availability checks should only occur when the function first decays
7622 // into a pointer or reference.
7623 if (CurInit.get()->getType()->isFunctionProtoType()) {
7624 if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
7625 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
7626 if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
7627 DRE->getBeginLoc()))
7633 CheckForNullPointerDereference(S, CurInit.get());
7636 case SK_BindReferenceToTemporary: {
7637 // Make sure the "temporary" is actually an rvalue.
7638 assert(CurInit.get()->isRValue() && "not a temporary");
7640 // Check exception specifications
7641 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
7644 // Materialize the temporary into memory.
7645 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
7646 Step->Type, CurInit.get(), Entity.getType()->isLValueReferenceType());
7649 // If we're extending this temporary to automatic storage duration -- we
7650 // need to register its cleanup during the full-expression's cleanups.
7651 if (MTE->getStorageDuration() == SD_Automatic &&
7652 MTE->getType().isDestructedType())
7653 S.Cleanup.setExprNeedsCleanups(true);
7658 if (checkAbstractType(Step->Type))
7661 // If the overall initialization is initializing a temporary, we already
7662 // bound our argument if it was necessary to do so. If not (if we're
7663 // ultimately initializing a non-temporary), our argument needs to be
7664 // bound since it's initializing a function parameter.
7665 // FIXME: This is a mess. Rationalize temporary destruction.
7666 if (!shouldBindAsTemporary(Entity))
7667 CurInit = S.MaybeBindToTemporary(CurInit.get());
7668 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
7669 /*IsExtraneousCopy=*/false);
7672 case SK_ExtraneousCopyToTemporary:
7673 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
7674 /*IsExtraneousCopy=*/true);
7677 case SK_UserConversion: {
7678 // We have a user-defined conversion that invokes either a constructor
7679 // or a conversion function.
7681 FunctionDecl *Fn = Step->Function.Function;
7682 DeclAccessPair FoundFn = Step->Function.FoundDecl;
7683 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
7684 bool CreatedObject = false;
7685 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
7686 // Build a call to the selected constructor.
7687 SmallVector<Expr*, 8> ConstructorArgs;
7688 SourceLocation Loc = CurInit.get()->getBeginLoc();
7690 // Determine the arguments required to actually perform the constructor
7692 Expr *Arg = CurInit.get();
7693 if (S.CompleteConstructorCall(Constructor,
7694 MultiExprArg(&Arg, 1),
7695 Loc, ConstructorArgs))
7698 // Build an expression that constructs a temporary.
7699 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type,
7700 FoundFn, Constructor,
7702 HadMultipleCandidates,
7704 /*StdInitListInit*/ false,
7706 CXXConstructExpr::CK_Complete,
7708 if (CurInit.isInvalid())
7711 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
7713 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
7716 CastKind = CK_ConstructorConversion;
7717 CreatedObject = true;
7719 // Build a call to the conversion function.
7720 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
7721 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
7723 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
7726 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
7727 HadMultipleCandidates);
7728 if (CurInit.isInvalid())
7731 CastKind = CK_UserDefinedConversion;
7732 CreatedObject = Conversion->getReturnType()->isRecordType();
7735 if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
7738 CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(),
7739 CastKind, CurInit.get(), nullptr,
7740 CurInit.get()->getValueKind());
7742 if (shouldBindAsTemporary(Entity))
7743 // The overall entity is temporary, so this expression should be
7744 // destroyed at the end of its full-expression.
7745 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
7746 else if (CreatedObject && shouldDestroyEntity(Entity)) {
7747 // The object outlasts the full-expression, but we need to prepare for
7748 // a destructor being run on it.
7749 // FIXME: It makes no sense to do this here. This should happen
7750 // regardless of how we initialized the entity.
7751 QualType T = CurInit.get()->getType();
7752 if (const RecordType *Record = T->getAs<RecordType>()) {
7753 CXXDestructorDecl *Destructor
7754 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
7755 S.CheckDestructorAccess(CurInit.get()->getBeginLoc(), Destructor,
7756 S.PDiag(diag::err_access_dtor_temp) << T);
7757 S.MarkFunctionReferenced(CurInit.get()->getBeginLoc(), Destructor);
7758 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc()))
7765 case SK_QualificationConversionLValue:
7766 case SK_QualificationConversionXValue:
7767 case SK_QualificationConversionRValue: {
7768 // Perform a qualification conversion; these can never go wrong.
7770 Step->Kind == SK_QualificationConversionLValue
7772 : (Step->Kind == SK_QualificationConversionXValue ? VK_XValue
7774 CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK);
7778 case SK_AtomicConversion: {
7779 assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic");
7780 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
7781 CK_NonAtomicToAtomic, VK_RValue);
7785 case SK_ConversionSequence:
7786 case SK_ConversionSequenceNoNarrowing: {
7787 if (const auto *FromPtrType =
7788 CurInit.get()->getType()->getAs<PointerType>()) {
7789 if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) {
7790 if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
7791 !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
7792 S.Diag(CurInit.get()->getExprLoc(),
7793 diag::warn_noderef_to_dereferenceable_pointer)
7794 << CurInit.get()->getSourceRange();
7799 Sema::CheckedConversionKind CCK
7800 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
7801 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
7802 : Kind.isExplicitCast()? Sema::CCK_OtherCast
7803 : Sema::CCK_ImplicitConversion;
7804 ExprResult CurInitExprRes =
7805 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
7806 getAssignmentAction(Entity), CCK);
7807 if (CurInitExprRes.isInvalid())
7810 S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), CurInit.get());
7812 CurInit = CurInitExprRes;
7814 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
7815 S.getLangOpts().CPlusPlus)
7816 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
7822 case SK_ListInitialization: {
7823 if (checkAbstractType(Step->Type))
7826 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
7827 // If we're not initializing the top-level entity, we need to create an
7828 // InitializeTemporary entity for our target type.
7829 QualType Ty = Step->Type;
7830 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
7831 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
7832 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
7833 InitListChecker PerformInitList(S, InitEntity,
7834 InitList, Ty, /*VerifyOnly=*/false,
7835 /*TreatUnavailableAsInvalid=*/false);
7836 if (PerformInitList.HadError())
7839 // Hack: We must update *ResultType if available in order to set the
7840 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
7841 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
7843 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
7844 if ((*ResultType)->isRValueReferenceType())
7845 Ty = S.Context.getRValueReferenceType(Ty);
7846 else if ((*ResultType)->isLValueReferenceType())
7847 Ty = S.Context.getLValueReferenceType(Ty,
7848 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
7852 InitListExpr *StructuredInitList =
7853 PerformInitList.getFullyStructuredList();
7855 CurInit = shouldBindAsTemporary(InitEntity)
7856 ? S.MaybeBindToTemporary(StructuredInitList)
7857 : StructuredInitList;
7861 case SK_ConstructorInitializationFromList: {
7862 if (checkAbstractType(Step->Type))
7865 // When an initializer list is passed for a parameter of type "reference
7866 // to object", we don't get an EK_Temporary entity, but instead an
7867 // EK_Parameter entity with reference type.
7868 // FIXME: This is a hack. What we really should do is create a user
7869 // conversion step for this case, but this makes it considerably more
7870 // complicated. For now, this will do.
7871 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
7872 Entity.getType().getNonReferenceType());
7873 bool UseTemporary = Entity.getType()->isReferenceType();
7874 assert(Args.size() == 1 && "expected a single argument for list init");
7875 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
7876 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
7877 << InitList->getSourceRange();
7878 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
7879 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
7882 ConstructorInitRequiresZeroInit,
7883 /*IsListInitialization*/true,
7884 /*IsStdInitListInit*/false,
7885 InitList->getLBraceLoc(),
7886 InitList->getRBraceLoc());
7890 case SK_UnwrapInitList:
7891 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
7894 case SK_RewrapInitList: {
7895 Expr *E = CurInit.get();
7896 InitListExpr *Syntactic = Step->WrappingSyntacticList;
7897 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
7898 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
7899 ILE->setSyntacticForm(Syntactic);
7900 ILE->setType(E->getType());
7901 ILE->setValueKind(E->getValueKind());
7906 case SK_ConstructorInitialization:
7907 case SK_StdInitializerListConstructorCall: {
7908 if (checkAbstractType(Step->Type))
7911 // When an initializer list is passed for a parameter of type "reference
7912 // to object", we don't get an EK_Temporary entity, but instead an
7913 // EK_Parameter entity with reference type.
7914 // FIXME: This is a hack. What we really should do is create a user
7915 // conversion step for this case, but this makes it considerably more
7916 // complicated. For now, this will do.
7917 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
7918 Entity.getType().getNonReferenceType());
7919 bool UseTemporary = Entity.getType()->isReferenceType();
7920 bool IsStdInitListInit =
7921 Step->Kind == SK_StdInitializerListConstructorCall;
7922 Expr *Source = CurInit.get();
7923 SourceRange Range = Kind.hasParenOrBraceRange()
7924 ? Kind.getParenOrBraceRange()
7926 CurInit = PerformConstructorInitialization(
7927 S, UseTemporary ? TempEntity : Entity, Kind,
7928 Source ? MultiExprArg(Source) : Args, *Step,
7929 ConstructorInitRequiresZeroInit,
7930 /*IsListInitialization*/ IsStdInitListInit,
7931 /*IsStdInitListInitialization*/ IsStdInitListInit,
7932 /*LBraceLoc*/ Range.getBegin(),
7933 /*RBraceLoc*/ Range.getEnd());
7937 case SK_ZeroInitialization: {
7938 step_iterator NextStep = Step;
7940 if (NextStep != StepEnd &&
7941 (NextStep->Kind == SK_ConstructorInitialization ||
7942 NextStep->Kind == SK_ConstructorInitializationFromList)) {
7943 // The need for zero-initialization is recorded directly into
7944 // the call to the object's constructor within the next step.
7945 ConstructorInitRequiresZeroInit = true;
7946 } else if (Kind.getKind() == InitializationKind::IK_Value &&
7947 S.getLangOpts().CPlusPlus &&
7948 !Kind.isImplicitValueInit()) {
7949 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
7951 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
7952 Kind.getRange().getBegin());
7954 CurInit = new (S.Context) CXXScalarValueInitExpr(
7955 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
7956 Kind.getRange().getEnd());
7958 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
7963 case SK_CAssignment: {
7964 QualType SourceType = CurInit.get()->getType();
7966 // Save off the initial CurInit in case we need to emit a diagnostic
7967 ExprResult InitialCurInit = CurInit;
7968 ExprResult Result = CurInit;
7969 Sema::AssignConvertType ConvTy =
7970 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
7971 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
7972 if (Result.isInvalid())
7976 // If this is a call, allow conversion to a transparent union.
7977 ExprResult CurInitExprRes = CurInit;
7978 if (ConvTy != Sema::Compatible &&
7979 Entity.isParameterKind() &&
7980 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
7981 == Sema::Compatible)
7982 ConvTy = Sema::Compatible;
7983 if (CurInitExprRes.isInvalid())
7985 CurInit = CurInitExprRes;
7988 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
7989 Step->Type, SourceType,
7990 InitialCurInit.get(),
7991 getAssignmentAction(Entity, true),
7993 PrintInitLocationNote(S, Entity);
7995 } else if (Complained)
7996 PrintInitLocationNote(S, Entity);
8000 case SK_StringInit: {
8001 QualType Ty = Step->Type;
8002 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
8003 S.Context.getAsArrayType(Ty), S);
8007 case SK_ObjCObjectConversion:
8008 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8009 CK_ObjCObjectLValueCast,
8010 CurInit.get()->getValueKind());
8013 case SK_ArrayLoopIndex: {
8014 Expr *Cur = CurInit.get();
8015 Expr *BaseExpr = new (S.Context)
8016 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
8017 Cur->getValueKind(), Cur->getObjectKind(), Cur);
8019 new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType());
8020 CurInit = S.CreateBuiltinArraySubscriptExpr(
8021 BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
8022 ArrayLoopCommonExprs.push_back(BaseExpr);
8026 case SK_ArrayLoopInit: {
8027 assert(!ArrayLoopCommonExprs.empty() &&
8028 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
8029 Expr *Common = ArrayLoopCommonExprs.pop_back_val();
8030 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
8035 case SK_GNUArrayInit:
8036 // Okay: we checked everything before creating this step. Note that
8037 // this is a GNU extension.
8038 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
8039 << Step->Type << CurInit.get()->getType()
8040 << CurInit.get()->getSourceRange();
8041 updateGNUCompoundLiteralRValue(CurInit.get());
8044 // If the destination type is an incomplete array type, update the
8045 // type accordingly.
8047 if (const IncompleteArrayType *IncompleteDest
8048 = S.Context.getAsIncompleteArrayType(Step->Type)) {
8049 if (const ConstantArrayType *ConstantSource
8050 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
8051 *ResultType = S.Context.getConstantArrayType(
8052 IncompleteDest->getElementType(),
8053 ConstantSource->getSize(),
8054 ArrayType::Normal, 0);
8060 case SK_ParenthesizedArrayInit:
8061 // Okay: we checked everything before creating this step. Note that
8062 // this is a GNU extension.
8063 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
8064 << CurInit.get()->getSourceRange();
8067 case SK_PassByIndirectCopyRestore:
8068 case SK_PassByIndirectRestore:
8069 checkIndirectCopyRestoreSource(S, CurInit.get());
8070 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
8071 CurInit.get(), Step->Type,
8072 Step->Kind == SK_PassByIndirectCopyRestore);
8075 case SK_ProduceObjCObject:
8077 ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject,
8078 CurInit.get(), nullptr, VK_RValue);
8081 case SK_StdInitializerList: {
8082 S.Diag(CurInit.get()->getExprLoc(),
8083 diag::warn_cxx98_compat_initializer_list_init)
8084 << CurInit.get()->getSourceRange();
8086 // Materialize the temporary into memory.
8087 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
8088 CurInit.get()->getType(), CurInit.get(),
8089 /*BoundToLvalueReference=*/false);
8091 // Wrap it in a construction of a std::initializer_list<T>.
8092 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
8094 // Bind the result, in case the library has given initializer_list a
8095 // non-trivial destructor.
8096 if (shouldBindAsTemporary(Entity))
8097 CurInit = S.MaybeBindToTemporary(CurInit.get());
8101 case SK_OCLSamplerInit: {
8102 // Sampler initialization have 5 cases:
8103 // 1. function argument passing
8104 // 1a. argument is a file-scope variable
8105 // 1b. argument is a function-scope variable
8106 // 1c. argument is one of caller function's parameters
8107 // 2. variable initialization
8108 // 2a. initializing a file-scope variable
8109 // 2b. initializing a function-scope variable
8111 // For file-scope variables, since they cannot be initialized by function
8112 // call of __translate_sampler_initializer in LLVM IR, their references
8113 // need to be replaced by a cast from their literal initializers to
8114 // sampler type. Since sampler variables can only be used in function
8115 // calls as arguments, we only need to replace them when handling the
8116 // argument passing.
8117 assert(Step->Type->isSamplerT() &&
8118 "Sampler initialization on non-sampler type.");
8119 Expr *Init = CurInit.get()->IgnoreParens();
8120 QualType SourceType = Init->getType();
8122 if (Entity.isParameterKind()) {
8123 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
8124 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
8127 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
8128 auto Var = cast<VarDecl>(DRE->getDecl());
8130 // No cast from integer to sampler is needed.
8131 if (!Var->hasGlobalStorage()) {
8132 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
8133 CK_LValueToRValue, Init,
8134 /*BasePath=*/nullptr, VK_RValue);
8138 // For function call with a file-scope sampler variable as argument,
8139 // get the integer literal.
8140 // Do not diagnose if the file-scope variable does not have initializer
8141 // since this has already been diagnosed when parsing the variable
8143 if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
8145 Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
8146 Var->getInit()))->getSubExpr();
8147 SourceType = Init->getType();
8151 // Check initializer is 32 bit integer constant.
8152 // If the initializer is taken from global variable, do not diagnose since
8153 // this has already been done when parsing the variable declaration.
8154 if (!Init->isConstantInitializer(S.Context, false))
8157 if (!SourceType->isIntegerType() ||
8158 32 != S.Context.getIntWidth(SourceType)) {
8159 S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
8164 Expr::EvalResult EVResult;
8165 Init->EvaluateAsInt(EVResult, S.Context);
8166 llvm::APSInt Result = EVResult.Val.getInt();
8167 const uint64_t SamplerValue = Result.getLimitedValue();
8168 // 32-bit value of sampler's initializer is interpreted as
8169 // bit-field with the following structure:
8170 // |unspecified|Filter|Addressing Mode| Normalized Coords|
8171 // |31 6|5 4|3 1| 0|
8172 // This structure corresponds to enum values of sampler properties
8173 // defined in SPIR spec v1.2 and also opencl-c.h
8174 unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
8175 unsigned FilterMode = (0x30 & SamplerValue) >> 4;
8176 if (FilterMode != 1 && FilterMode != 2 &&
8177 !S.getOpenCLOptions().isEnabled(
8178 "cl_intel_device_side_avc_motion_estimation"))
8179 S.Diag(Kind.getLocation(),
8180 diag::warn_sampler_initializer_invalid_bits)
8182 if (AddressingMode > 4)
8183 S.Diag(Kind.getLocation(),
8184 diag::warn_sampler_initializer_invalid_bits)
8185 << "Addressing Mode";
8188 // Cases 1a, 2a and 2b
8189 // Insert cast from integer to sampler.
8190 CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy,
8191 CK_IntToOCLSampler);
8194 case SK_OCLZeroOpaqueType: {
8195 assert((Step->Type->isEventT() || Step->Type->isQueueT() ||
8196 Step->Type->isOCLIntelSubgroupAVCType()) &&
8197 "Wrong type for initialization of OpenCL opaque type.");
8199 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8200 CK_ZeroToOCLOpaqueType,
8201 CurInit.get()->getValueKind());
8207 // Check whether the initializer has a shorter lifetime than the initialized
8208 // entity, and if not, either lifetime-extend or warn as appropriate.
8209 if (auto *Init = CurInit.get())
8210 S.checkInitializerLifetime(Entity, Init);
8212 // Diagnose non-fatal problems with the completed initialization.
8213 if (Entity.getKind() == InitializedEntity::EK_Member &&
8214 cast<FieldDecl>(Entity.getDecl())->isBitField())
8215 S.CheckBitFieldInitialization(Kind.getLocation(),
8216 cast<FieldDecl>(Entity.getDecl()),
8219 // Check for std::move on construction.
8220 if (const Expr *E = CurInit.get()) {
8221 CheckMoveOnConstruction(S, E,
8222 Entity.getKind() == InitializedEntity::EK_Result);
8228 /// Somewhere within T there is an uninitialized reference subobject.
8229 /// Dig it out and diagnose it.
8230 static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
8232 if (T->isReferenceType()) {
8233 S.Diag(Loc, diag::err_reference_without_init)
8234 << T.getNonReferenceType();
8238 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
8239 if (!RD || !RD->hasUninitializedReferenceMember())
8242 for (const auto *FI : RD->fields()) {
8243 if (FI->isUnnamedBitfield())
8246 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
8247 S.Diag(Loc, diag::note_value_initialization_here) << RD;
8252 for (const auto &BI : RD->bases()) {
8253 if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) {
8254 S.Diag(Loc, diag::note_value_initialization_here) << RD;
8263 //===----------------------------------------------------------------------===//
8264 // Diagnose initialization failures
8265 //===----------------------------------------------------------------------===//
8267 /// Emit notes associated with an initialization that failed due to a
8268 /// "simple" conversion failure.
8269 static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
8271 QualType destType = entity.getType();
8272 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
8273 op->getType()->isObjCObjectPointerType()) {
8275 // Emit a possible note about the conversion failing because the
8276 // operand is a message send with a related result type.
8277 S.EmitRelatedResultTypeNote(op);
8279 // Emit a possible note about a return failing because we're
8280 // expecting a related result type.
8281 if (entity.getKind() == InitializedEntity::EK_Result)
8282 S.EmitRelatedResultTypeNoteForReturn(destType);
8286 static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
8287 InitListExpr *InitList) {
8288 QualType DestType = Entity.getType();
8291 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
8292 QualType ArrayType = S.Context.getConstantArrayType(
8294 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
8295 InitList->getNumInits()),
8296 clang::ArrayType::Normal, 0);
8297 InitializedEntity HiddenArray =
8298 InitializedEntity::InitializeTemporary(ArrayType);
8299 return diagnoseListInit(S, HiddenArray, InitList);
8302 if (DestType->isReferenceType()) {
8303 // A list-initialization failure for a reference means that we tried to
8304 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
8305 // inner initialization failed.
8306 QualType T = DestType->getAs<ReferenceType>()->getPointeeType();
8307 diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
8308 SourceLocation Loc = InitList->getBeginLoc();
8309 if (auto *D = Entity.getDecl())
8310 Loc = D->getLocation();
8311 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
8315 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
8316 /*VerifyOnly=*/false,
8317 /*TreatUnavailableAsInvalid=*/false);
8318 assert(DiagnoseInitList.HadError() &&
8319 "Inconsistent init list check result.");
8322 bool InitializationSequence::Diagnose(Sema &S,
8323 const InitializedEntity &Entity,
8324 const InitializationKind &Kind,
8325 ArrayRef<Expr *> Args) {
8329 // When we want to diagnose only one element of a braced-init-list,
8330 // we need to factor it out.
8332 if (Args.size() == 1) {
8333 auto *List = dyn_cast<InitListExpr>(Args[0]);
8334 if (List && List->getNumInits() == 1)
8335 OnlyArg = List->getInit(0);
8342 QualType DestType = Entity.getType();
8344 case FK_TooManyInitsForReference:
8345 // FIXME: Customize for the initialized entity?
8347 // Dig out the reference subobject which is uninitialized and diagnose it.
8348 // If this is value-initialization, this could be nested some way within
8350 assert(Kind.getKind() == InitializationKind::IK_Value ||
8351 DestType->isReferenceType());
8353 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
8354 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
8356 } else // FIXME: diagnostic below could be better!
8357 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
8358 << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
8360 case FK_ParenthesizedListInitForReference:
8361 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
8362 << 1 << Entity.getType() << Args[0]->getSourceRange();
8365 case FK_ArrayNeedsInitList:
8366 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
8368 case FK_ArrayNeedsInitListOrStringLiteral:
8369 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
8371 case FK_ArrayNeedsInitListOrWideStringLiteral:
8372 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
8374 case FK_NarrowStringIntoWideCharArray:
8375 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
8377 case FK_WideStringIntoCharArray:
8378 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
8380 case FK_IncompatWideStringIntoWideChar:
8381 S.Diag(Kind.getLocation(),
8382 diag::err_array_init_incompat_wide_string_into_wchar);
8384 case FK_PlainStringIntoUTF8Char:
8385 S.Diag(Kind.getLocation(),
8386 diag::err_array_init_plain_string_into_char8_t);
8387 S.Diag(Args.front()->getBeginLoc(),
8388 diag::note_array_init_plain_string_into_char8_t)
8389 << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8");
8391 case FK_UTF8StringIntoPlainChar:
8392 S.Diag(Kind.getLocation(),
8393 diag::err_array_init_utf8_string_into_char)
8394 << S.getLangOpts().CPlusPlus2a;
8396 case FK_ArrayTypeMismatch:
8397 case FK_NonConstantArrayInit:
8398 S.Diag(Kind.getLocation(),
8399 (Failure == FK_ArrayTypeMismatch
8400 ? diag::err_array_init_different_type
8401 : diag::err_array_init_non_constant_array))
8402 << DestType.getNonReferenceType()
8403 << OnlyArg->getType()
8404 << Args[0]->getSourceRange();
8407 case FK_VariableLengthArrayHasInitializer:
8408 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
8409 << Args[0]->getSourceRange();
8412 case FK_AddressOfOverloadFailed: {
8413 DeclAccessPair Found;
8414 S.ResolveAddressOfOverloadedFunction(OnlyArg,
8415 DestType.getNonReferenceType(),
8421 case FK_AddressOfUnaddressableFunction: {
8422 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl());
8423 S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
8424 OnlyArg->getBeginLoc());
8428 case FK_ReferenceInitOverloadFailed:
8429 case FK_UserConversionOverloadFailed:
8430 switch (FailedOverloadResult) {
8433 FailedCandidateSet.NoteCandidates(
8434 PartialDiagnosticAt(
8436 Failure == FK_UserConversionOverloadFailed
8437 ? (S.PDiag(diag::err_typecheck_ambiguous_condition)
8438 << OnlyArg->getType() << DestType
8439 << Args[0]->getSourceRange())
8440 : (S.PDiag(diag::err_ref_init_ambiguous)
8441 << DestType << OnlyArg->getType()
8442 << Args[0]->getSourceRange())),
8443 S, OCD_ViableCandidates, Args);
8446 case OR_No_Viable_Function: {
8447 auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args);
8448 if (!S.RequireCompleteType(Kind.getLocation(),
8449 DestType.getNonReferenceType(),
8450 diag::err_typecheck_nonviable_condition_incomplete,
8451 OnlyArg->getType(), Args[0]->getSourceRange()))
8452 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
8453 << (Entity.getKind() == InitializedEntity::EK_Result)
8454 << OnlyArg->getType() << Args[0]->getSourceRange()
8455 << DestType.getNonReferenceType();
8457 FailedCandidateSet.NoteCandidates(S, Args, Cands);
8461 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
8462 << OnlyArg->getType() << DestType.getNonReferenceType()
8463 << Args[0]->getSourceRange();
8464 OverloadCandidateSet::iterator Best;
8465 OverloadingResult Ovl
8466 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
8467 if (Ovl == OR_Deleted) {
8468 S.NoteDeletedFunction(Best->Function);
8470 llvm_unreachable("Inconsistent overload resolution?");
8476 llvm_unreachable("Conversion did not fail!");
8480 case FK_NonConstLValueReferenceBindingToTemporary:
8481 if (isa<InitListExpr>(Args[0])) {
8482 S.Diag(Kind.getLocation(),
8483 diag::err_lvalue_reference_bind_to_initlist)
8484 << DestType.getNonReferenceType().isVolatileQualified()
8485 << DestType.getNonReferenceType()
8486 << Args[0]->getSourceRange();
8491 case FK_NonConstLValueReferenceBindingToUnrelated:
8492 S.Diag(Kind.getLocation(),
8493 Failure == FK_NonConstLValueReferenceBindingToTemporary
8494 ? diag::err_lvalue_reference_bind_to_temporary
8495 : diag::err_lvalue_reference_bind_to_unrelated)
8496 << DestType.getNonReferenceType().isVolatileQualified()
8497 << DestType.getNonReferenceType()
8498 << OnlyArg->getType()
8499 << Args[0]->getSourceRange();
8502 case FK_NonConstLValueReferenceBindingToBitfield: {
8503 // We don't necessarily have an unambiguous source bit-field.
8504 FieldDecl *BitField = Args[0]->getSourceBitField();
8505 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
8506 << DestType.isVolatileQualified()
8507 << (BitField ? BitField->getDeclName() : DeclarationName())
8508 << (BitField != nullptr)
8509 << Args[0]->getSourceRange();
8511 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
8515 case FK_NonConstLValueReferenceBindingToVectorElement:
8516 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
8517 << DestType.isVolatileQualified()
8518 << Args[0]->getSourceRange();
8521 case FK_RValueReferenceBindingToLValue:
8522 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
8523 << DestType.getNonReferenceType() << OnlyArg->getType()
8524 << Args[0]->getSourceRange();
8527 case FK_ReferenceAddrspaceMismatchTemporary:
8528 S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace)
8529 << DestType << Args[0]->getSourceRange();
8532 case FK_ReferenceInitDropsQualifiers: {
8533 QualType SourceType = OnlyArg->getType();
8534 QualType NonRefType = DestType.getNonReferenceType();
8535 Qualifiers DroppedQualifiers =
8536 SourceType.getQualifiers() - NonRefType.getQualifiers();
8538 if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf(
8539 SourceType.getQualifiers()))
8540 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
8541 << NonRefType << SourceType << 1 /*addr space*/
8542 << Args[0]->getSourceRange();
8544 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
8545 << NonRefType << SourceType << 0 /*cv quals*/
8546 << Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers())
8547 << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange();
8551 case FK_ReferenceInitFailed:
8552 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
8553 << DestType.getNonReferenceType()
8554 << DestType.getNonReferenceType()->isIncompleteType()
8555 << OnlyArg->isLValue()
8556 << OnlyArg->getType()
8557 << Args[0]->getSourceRange();
8558 emitBadConversionNotes(S, Entity, Args[0]);
8561 case FK_ConversionFailed: {
8562 QualType FromType = OnlyArg->getType();
8563 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
8564 << (int)Entity.getKind()
8566 << OnlyArg->isLValue()
8568 << Args[0]->getSourceRange();
8569 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
8570 S.Diag(Kind.getLocation(), PDiag);
8571 emitBadConversionNotes(S, Entity, Args[0]);
8575 case FK_ConversionFromPropertyFailed:
8576 // No-op. This error has already been reported.
8579 case FK_TooManyInitsForScalar: {
8582 auto *InitList = dyn_cast<InitListExpr>(Args[0]);
8583 if (InitList && InitList->getNumInits() >= 1) {
8584 R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc());
8586 assert(Args.size() > 1 && "Expected multiple initializers!");
8587 R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc());
8590 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
8591 if (Kind.isCStyleOrFunctionalCast())
8592 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
8595 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
8596 << /*scalar=*/2 << R;
8600 case FK_ParenthesizedListInitForScalar:
8601 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
8602 << 0 << Entity.getType() << Args[0]->getSourceRange();
8605 case FK_ReferenceBindingToInitList:
8606 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
8607 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
8610 case FK_InitListBadDestinationType:
8611 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
8612 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
8615 case FK_ListConstructorOverloadFailed:
8616 case FK_ConstructorOverloadFailed: {
8617 SourceRange ArgsRange;
8620 SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
8622 if (Failure == FK_ListConstructorOverloadFailed) {
8623 assert(Args.size() == 1 &&
8624 "List construction from other than 1 argument.");
8625 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
8626 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
8629 // FIXME: Using "DestType" for the entity we're printing is probably
8631 switch (FailedOverloadResult) {
8633 FailedCandidateSet.NoteCandidates(
8634 PartialDiagnosticAt(Kind.getLocation(),
8635 S.PDiag(diag::err_ovl_ambiguous_init)
8636 << DestType << ArgsRange),
8637 S, OCD_ViableCandidates, Args);
8640 case OR_No_Viable_Function:
8641 if (Kind.getKind() == InitializationKind::IK_Default &&
8642 (Entity.getKind() == InitializedEntity::EK_Base ||
8643 Entity.getKind() == InitializedEntity::EK_Member) &&
8644 isa<CXXConstructorDecl>(S.CurContext)) {
8645 // This is implicit default initialization of a member or
8646 // base within a constructor. If no viable function was
8647 // found, notify the user that they need to explicitly
8648 // initialize this base/member.
8649 CXXConstructorDecl *Constructor
8650 = cast<CXXConstructorDecl>(S.CurContext);
8651 const CXXRecordDecl *InheritedFrom = nullptr;
8652 if (auto Inherited = Constructor->getInheritedConstructor())
8653 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
8654 if (Entity.getKind() == InitializedEntity::EK_Base) {
8655 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
8656 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
8657 << S.Context.getTypeDeclType(Constructor->getParent())
8662 RecordDecl *BaseDecl
8663 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
8665 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
8666 << S.Context.getTagDeclType(BaseDecl);
8668 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
8669 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
8670 << S.Context.getTypeDeclType(Constructor->getParent())
8674 S.Diag(Entity.getDecl()->getLocation(),
8675 diag::note_member_declared_at);
8677 if (const RecordType *Record
8678 = Entity.getType()->getAs<RecordType>())
8679 S.Diag(Record->getDecl()->getLocation(),
8680 diag::note_previous_decl)
8681 << S.Context.getTagDeclType(Record->getDecl());
8686 FailedCandidateSet.NoteCandidates(
8687 PartialDiagnosticAt(
8689 S.PDiag(diag::err_ovl_no_viable_function_in_init)
8690 << DestType << ArgsRange),
8691 S, OCD_AllCandidates, Args);
8695 OverloadCandidateSet::iterator Best;
8696 OverloadingResult Ovl
8697 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
8698 if (Ovl != OR_Deleted) {
8699 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
8700 << DestType << ArgsRange;
8701 llvm_unreachable("Inconsistent overload resolution?");
8705 // If this is a defaulted or implicitly-declared function, then
8706 // it was implicitly deleted. Make it clear that the deletion was
8708 if (S.isImplicitlyDeleted(Best->Function))
8709 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
8710 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
8711 << DestType << ArgsRange;
8713 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
8714 << DestType << ArgsRange;
8716 S.NoteDeletedFunction(Best->Function);
8721 llvm_unreachable("Conversion did not fail!");
8726 case FK_DefaultInitOfConst:
8727 if (Entity.getKind() == InitializedEntity::EK_Member &&
8728 isa<CXXConstructorDecl>(S.CurContext)) {
8729 // This is implicit default-initialization of a const member in
8730 // a constructor. Complain that it needs to be explicitly
8732 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
8733 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
8734 << (Constructor->getInheritedConstructor() ? 2 :
8735 Constructor->isImplicit() ? 1 : 0)
8736 << S.Context.getTypeDeclType(Constructor->getParent())
8738 << Entity.getName();
8739 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
8740 << Entity.getName();
8742 S.Diag(Kind.getLocation(), diag::err_default_init_const)
8743 << DestType << (bool)DestType->getAs<RecordType>();
8748 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
8749 diag::err_init_incomplete_type);
8752 case FK_ListInitializationFailed: {
8753 // Run the init list checker again to emit diagnostics.
8754 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
8755 diagnoseListInit(S, Entity, InitList);
8759 case FK_PlaceholderType: {
8760 // FIXME: Already diagnosed!
8764 case FK_ExplicitConstructor: {
8765 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
8766 << Args[0]->getSourceRange();
8767 OverloadCandidateSet::iterator Best;
8768 OverloadingResult Ovl
8769 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
8771 assert(Ovl == OR_Success && "Inconsistent overload resolution");
8772 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
8773 S.Diag(CtorDecl->getLocation(),
8774 diag::note_explicit_ctor_deduction_guide_here) << false;
8779 PrintInitLocationNote(S, Entity);
8783 void InitializationSequence::dump(raw_ostream &OS) const {
8784 switch (SequenceKind) {
8785 case FailedSequence: {
8786 OS << "Failed sequence: ";
8788 case FK_TooManyInitsForReference:
8789 OS << "too many initializers for reference";
8792 case FK_ParenthesizedListInitForReference:
8793 OS << "parenthesized list init for reference";
8796 case FK_ArrayNeedsInitList:
8797 OS << "array requires initializer list";
8800 case FK_AddressOfUnaddressableFunction:
8801 OS << "address of unaddressable function was taken";
8804 case FK_ArrayNeedsInitListOrStringLiteral:
8805 OS << "array requires initializer list or string literal";
8808 case FK_ArrayNeedsInitListOrWideStringLiteral:
8809 OS << "array requires initializer list or wide string literal";
8812 case FK_NarrowStringIntoWideCharArray:
8813 OS << "narrow string into wide char array";
8816 case FK_WideStringIntoCharArray:
8817 OS << "wide string into char array";
8820 case FK_IncompatWideStringIntoWideChar:
8821 OS << "incompatible wide string into wide char array";
8824 case FK_PlainStringIntoUTF8Char:
8825 OS << "plain string literal into char8_t array";
8828 case FK_UTF8StringIntoPlainChar:
8829 OS << "u8 string literal into char array";
8832 case FK_ArrayTypeMismatch:
8833 OS << "array type mismatch";
8836 case FK_NonConstantArrayInit:
8837 OS << "non-constant array initializer";
8840 case FK_AddressOfOverloadFailed:
8841 OS << "address of overloaded function failed";
8844 case FK_ReferenceInitOverloadFailed:
8845 OS << "overload resolution for reference initialization failed";
8848 case FK_NonConstLValueReferenceBindingToTemporary:
8849 OS << "non-const lvalue reference bound to temporary";
8852 case FK_NonConstLValueReferenceBindingToBitfield:
8853 OS << "non-const lvalue reference bound to bit-field";
8856 case FK_NonConstLValueReferenceBindingToVectorElement:
8857 OS << "non-const lvalue reference bound to vector element";
8860 case FK_NonConstLValueReferenceBindingToUnrelated:
8861 OS << "non-const lvalue reference bound to unrelated type";
8864 case FK_RValueReferenceBindingToLValue:
8865 OS << "rvalue reference bound to an lvalue";
8868 case FK_ReferenceInitDropsQualifiers:
8869 OS << "reference initialization drops qualifiers";
8872 case FK_ReferenceAddrspaceMismatchTemporary:
8873 OS << "reference with mismatching address space bound to temporary";
8876 case FK_ReferenceInitFailed:
8877 OS << "reference initialization failed";
8880 case FK_ConversionFailed:
8881 OS << "conversion failed";
8884 case FK_ConversionFromPropertyFailed:
8885 OS << "conversion from property failed";
8888 case FK_TooManyInitsForScalar:
8889 OS << "too many initializers for scalar";
8892 case FK_ParenthesizedListInitForScalar:
8893 OS << "parenthesized list init for reference";
8896 case FK_ReferenceBindingToInitList:
8897 OS << "referencing binding to initializer list";
8900 case FK_InitListBadDestinationType:
8901 OS << "initializer list for non-aggregate, non-scalar type";
8904 case FK_UserConversionOverloadFailed:
8905 OS << "overloading failed for user-defined conversion";
8908 case FK_ConstructorOverloadFailed:
8909 OS << "constructor overloading failed";
8912 case FK_DefaultInitOfConst:
8913 OS << "default initialization of a const variable";
8917 OS << "initialization of incomplete type";
8920 case FK_ListInitializationFailed:
8921 OS << "list initialization checker failure";
8924 case FK_VariableLengthArrayHasInitializer:
8925 OS << "variable length array has an initializer";
8928 case FK_PlaceholderType:
8929 OS << "initializer expression isn't contextually valid";
8932 case FK_ListConstructorOverloadFailed:
8933 OS << "list constructor overloading failed";
8936 case FK_ExplicitConstructor:
8937 OS << "list copy initialization chose explicit constructor";
8944 case DependentSequence:
8945 OS << "Dependent sequence\n";
8948 case NormalSequence:
8949 OS << "Normal sequence: ";
8953 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
8954 if (S != step_begin()) {
8959 case SK_ResolveAddressOfOverloadedFunction:
8960 OS << "resolve address of overloaded function";
8963 case SK_CastDerivedToBaseRValue:
8964 OS << "derived-to-base (rvalue)";
8967 case SK_CastDerivedToBaseXValue:
8968 OS << "derived-to-base (xvalue)";
8971 case SK_CastDerivedToBaseLValue:
8972 OS << "derived-to-base (lvalue)";
8975 case SK_BindReference:
8976 OS << "bind reference to lvalue";
8979 case SK_BindReferenceToTemporary:
8980 OS << "bind reference to a temporary";
8984 OS << "final copy in class direct-initialization";
8987 case SK_ExtraneousCopyToTemporary:
8988 OS << "extraneous C++03 copy to temporary";
8991 case SK_UserConversion:
8992 OS << "user-defined conversion via " << *S->Function.Function;
8995 case SK_QualificationConversionRValue:
8996 OS << "qualification conversion (rvalue)";
8999 case SK_QualificationConversionXValue:
9000 OS << "qualification conversion (xvalue)";
9003 case SK_QualificationConversionLValue:
9004 OS << "qualification conversion (lvalue)";
9007 case SK_AtomicConversion:
9008 OS << "non-atomic-to-atomic conversion";
9011 case SK_ConversionSequence:
9012 OS << "implicit conversion sequence (";
9013 S->ICS->dump(); // FIXME: use OS
9017 case SK_ConversionSequenceNoNarrowing:
9018 OS << "implicit conversion sequence with narrowing prohibited (";
9019 S->ICS->dump(); // FIXME: use OS
9023 case SK_ListInitialization:
9024 OS << "list aggregate initialization";
9027 case SK_UnwrapInitList:
9028 OS << "unwrap reference initializer list";
9031 case SK_RewrapInitList:
9032 OS << "rewrap reference initializer list";
9035 case SK_ConstructorInitialization:
9036 OS << "constructor initialization";
9039 case SK_ConstructorInitializationFromList:
9040 OS << "list initialization via constructor";
9043 case SK_ZeroInitialization:
9044 OS << "zero initialization";
9047 case SK_CAssignment:
9048 OS << "C assignment";
9052 OS << "string initialization";
9055 case SK_ObjCObjectConversion:
9056 OS << "Objective-C object conversion";
9059 case SK_ArrayLoopIndex:
9060 OS << "indexing for array initialization loop";
9063 case SK_ArrayLoopInit:
9064 OS << "array initialization loop";
9068 OS << "array initialization";
9071 case SK_GNUArrayInit:
9072 OS << "array initialization (GNU extension)";
9075 case SK_ParenthesizedArrayInit:
9076 OS << "parenthesized array initialization";
9079 case SK_PassByIndirectCopyRestore:
9080 OS << "pass by indirect copy and restore";
9083 case SK_PassByIndirectRestore:
9084 OS << "pass by indirect restore";
9087 case SK_ProduceObjCObject:
9088 OS << "Objective-C object retension";
9091 case SK_StdInitializerList:
9092 OS << "std::initializer_list from initializer list";
9095 case SK_StdInitializerListConstructorCall:
9096 OS << "list initialization from std::initializer_list";
9099 case SK_OCLSamplerInit:
9100 OS << "OpenCL sampler_t from integer constant";
9103 case SK_OCLZeroOpaqueType:
9104 OS << "OpenCL opaque type from zero";
9108 OS << " [" << S->Type.getAsString() << ']';
9114 void InitializationSequence::dump() const {
9118 static bool NarrowingErrs(const LangOptions &L) {
9119 return L.CPlusPlus11 &&
9120 (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015));
9123 static void DiagnoseNarrowingInInitList(Sema &S,
9124 const ImplicitConversionSequence &ICS,
9125 QualType PreNarrowingType,
9126 QualType EntityType,
9127 const Expr *PostInit) {
9128 const StandardConversionSequence *SCS = nullptr;
9129 switch (ICS.getKind()) {
9130 case ImplicitConversionSequence::StandardConversion:
9131 SCS = &ICS.Standard;
9133 case ImplicitConversionSequence::UserDefinedConversion:
9134 SCS = &ICS.UserDefined.After;
9136 case ImplicitConversionSequence::AmbiguousConversion:
9137 case ImplicitConversionSequence::EllipsisConversion:
9138 case ImplicitConversionSequence::BadConversion:
9142 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
9143 APValue ConstantValue;
9144 QualType ConstantType;
9145 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
9147 case NK_Not_Narrowing:
9148 case NK_Dependent_Narrowing:
9149 // No narrowing occurred.
9152 case NK_Type_Narrowing:
9153 // This was a floating-to-integer conversion, which is always considered a
9154 // narrowing conversion even if the value is a constant and can be
9155 // represented exactly as an integer.
9156 S.Diag(PostInit->getBeginLoc(), NarrowingErrs(S.getLangOpts())
9157 ? diag::ext_init_list_type_narrowing
9158 : diag::warn_init_list_type_narrowing)
9159 << PostInit->getSourceRange()
9160 << PreNarrowingType.getLocalUnqualifiedType()
9161 << EntityType.getLocalUnqualifiedType();
9164 case NK_Constant_Narrowing:
9165 // A constant value was narrowed.
9166 S.Diag(PostInit->getBeginLoc(),
9167 NarrowingErrs(S.getLangOpts())
9168 ? diag::ext_init_list_constant_narrowing
9169 : diag::warn_init_list_constant_narrowing)
9170 << PostInit->getSourceRange()
9171 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
9172 << EntityType.getLocalUnqualifiedType();
9175 case NK_Variable_Narrowing:
9176 // A variable's value may have been narrowed.
9177 S.Diag(PostInit->getBeginLoc(),
9178 NarrowingErrs(S.getLangOpts())
9179 ? diag::ext_init_list_variable_narrowing
9180 : diag::warn_init_list_variable_narrowing)
9181 << PostInit->getSourceRange()
9182 << PreNarrowingType.getLocalUnqualifiedType()
9183 << EntityType.getLocalUnqualifiedType();
9187 SmallString<128> StaticCast;
9188 llvm::raw_svector_ostream OS(StaticCast);
9189 OS << "static_cast<";
9190 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
9191 // It's important to use the typedef's name if there is one so that the
9192 // fixit doesn't break code using types like int64_t.
9194 // FIXME: This will break if the typedef requires qualification. But
9195 // getQualifiedNameAsString() includes non-machine-parsable components.
9196 OS << *TT->getDecl();
9197 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
9198 OS << BT->getName(S.getLangOpts());
9200 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
9201 // with a broken cast.
9205 S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence)
9206 << PostInit->getSourceRange()
9207 << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str())
9208 << FixItHint::CreateInsertion(
9209 S.getLocForEndOfToken(PostInit->getEndLoc()), ")");
9212 //===----------------------------------------------------------------------===//
9213 // Initialization helper functions
9214 //===----------------------------------------------------------------------===//
9216 Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
9218 if (Init.isInvalid())
9221 Expr *InitE = Init.get();
9222 assert(InitE && "No initialization expression");
9224 InitializationKind Kind =
9225 InitializationKind::CreateCopy(InitE->getBeginLoc(), SourceLocation());
9226 InitializationSequence Seq(*this, Entity, Kind, InitE);
9227 return !Seq.Failed();
9231 Sema::PerformCopyInitialization(const InitializedEntity &Entity,
9232 SourceLocation EqualLoc,
9234 bool TopLevelOfInitList,
9235 bool AllowExplicit) {
9236 if (Init.isInvalid())
9239 Expr *InitE = Init.get();
9240 assert(InitE && "No initialization expression?");
9242 if (EqualLoc.isInvalid())
9243 EqualLoc = InitE->getBeginLoc();
9245 InitializationKind Kind = InitializationKind::CreateCopy(
9246 InitE->getBeginLoc(), EqualLoc, AllowExplicit);
9247 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
9249 // Prevent infinite recursion when performing parameter copy-initialization.
9250 const bool ShouldTrackCopy =
9251 Entity.isParameterKind() && Seq.isConstructorInitialization();
9252 if (ShouldTrackCopy) {
9253 if (llvm::find(CurrentParameterCopyTypes, Entity.getType()) !=
9254 CurrentParameterCopyTypes.end()) {
9255 Seq.SetOverloadFailure(
9256 InitializationSequence::FK_ConstructorOverloadFailed,
9257 OR_No_Viable_Function);
9259 // Try to give a meaningful diagnostic note for the problematic
9261 const auto LastStep = Seq.step_end() - 1;
9262 assert(LastStep->Kind ==
9263 InitializationSequence::SK_ConstructorInitialization);
9264 const FunctionDecl *Function = LastStep->Function.Function;
9266 llvm::find_if(Seq.getFailedCandidateSet(),
9267 [Function](const OverloadCandidate &Candidate) -> bool {
9268 return Candidate.Viable &&
9269 Candidate.Function == Function &&
9270 Candidate.Conversions.size() > 0;
9272 if (Candidate != Seq.getFailedCandidateSet().end() &&
9273 Function->getNumParams() > 0) {
9274 Candidate->Viable = false;
9275 Candidate->FailureKind = ovl_fail_bad_conversion;
9276 Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion,
9278 Function->getParamDecl(0)->getType());
9281 CurrentParameterCopyTypes.push_back(Entity.getType());
9284 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
9286 if (ShouldTrackCopy)
9287 CurrentParameterCopyTypes.pop_back();
9292 /// Determine whether RD is, or is derived from, a specialization of CTD.
9293 static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD,
9294 ClassTemplateDecl *CTD) {
9295 auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
9296 auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
9297 return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
9299 return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
9302 QualType Sema::DeduceTemplateSpecializationFromInitializer(
9303 TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
9304 const InitializationKind &Kind, MultiExprArg Inits) {
9305 auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
9306 TSInfo->getType()->getContainedDeducedType());
9307 assert(DeducedTST && "not a deduced template specialization type");
9309 auto TemplateName = DeducedTST->getTemplateName();
9310 if (TemplateName.isDependent())
9311 return Context.DependentTy;
9313 // We can only perform deduction for class templates.
9315 dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
9317 Diag(Kind.getLocation(),
9318 diag::err_deduced_non_class_template_specialization_type)
9319 << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName;
9320 if (auto *TD = TemplateName.getAsTemplateDecl())
9321 Diag(TD->getLocation(), diag::note_template_decl_here);
9325 // Can't deduce from dependent arguments.
9326 if (Expr::hasAnyTypeDependentArguments(Inits)) {
9327 Diag(TSInfo->getTypeLoc().getBeginLoc(),
9328 diag::warn_cxx14_compat_class_template_argument_deduction)
9329 << TSInfo->getTypeLoc().getSourceRange() << 0;
9330 return Context.DependentTy;
9333 // FIXME: Perform "exact type" matching first, per CWG discussion?
9334 // Or implement this via an implied 'T(T) -> T' deduction guide?
9336 // FIXME: Do we need/want a std::initializer_list<T> special case?
9338 // Look up deduction guides, including those synthesized from constructors.
9340 // C++1z [over.match.class.deduct]p1:
9341 // A set of functions and function templates is formed comprising:
9342 // - For each constructor of the class template designated by the
9343 // template-name, a function template [...]
9344 // - For each deduction-guide, a function or function template [...]
9345 DeclarationNameInfo NameInfo(
9346 Context.DeclarationNames.getCXXDeductionGuideName(Template),
9347 TSInfo->getTypeLoc().getEndLoc());
9348 LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
9349 LookupQualifiedName(Guides, Template->getDeclContext());
9351 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
9352 // clear on this, but they're not found by name so access does not apply.
9353 Guides.suppressDiagnostics();
9355 // Figure out if this is list-initialization.
9356 InitListExpr *ListInit =
9357 (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
9358 ? dyn_cast<InitListExpr>(Inits[0])
9361 // C++1z [over.match.class.deduct]p1:
9362 // Initialization and overload resolution are performed as described in
9363 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
9364 // (as appropriate for the type of initialization performed) for an object
9365 // of a hypothetical class type, where the selected functions and function
9366 // templates are considered to be the constructors of that class type
9368 // Since we know we're initializing a class type of a type unrelated to that
9369 // of the initializer, this reduces to something fairly reasonable.
9370 OverloadCandidateSet Candidates(Kind.getLocation(),
9371 OverloadCandidateSet::CSK_Normal);
9372 OverloadCandidateSet::iterator Best;
9374 bool HasAnyDeductionGuide = false;
9375 bool AllowExplicit = !Kind.isCopyInit() || ListInit;
9377 auto tryToResolveOverload =
9378 [&](bool OnlyListConstructors) -> OverloadingResult {
9379 Candidates.clear(OverloadCandidateSet::CSK_Normal);
9380 HasAnyDeductionGuide = false;
9382 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
9383 NamedDecl *D = (*I)->getUnderlyingDecl();
9384 if (D->isInvalidDecl())
9387 auto *TD = dyn_cast<FunctionTemplateDecl>(D);
9388 auto *GD = dyn_cast_or_null<CXXDeductionGuideDecl>(
9389 TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
9393 if (!GD->isImplicit())
9394 HasAnyDeductionGuide = true;
9396 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
9397 // For copy-initialization, the candidate functions are all the
9398 // converting constructors (12.3.1) of that class.
9399 // C++ [over.match.copy]p1: (non-list copy-initialization from class)
9400 // The converting constructors of T are candidate functions.
9401 if (!AllowExplicit) {
9402 // Only consider converting constructors.
9403 if (GD->isExplicit())
9406 // When looking for a converting constructor, deduction guides that
9407 // could never be called with one argument are not interesting to
9409 if (GD->getMinRequiredArguments() > 1 ||
9410 (GD->getNumParams() == 0 && !GD->isVariadic()))
9414 // C++ [over.match.list]p1.1: (first phase list initialization)
9415 // Initially, the candidate functions are the initializer-list
9416 // constructors of the class T
9417 if (OnlyListConstructors && !isInitListConstructor(GD))
9420 // C++ [over.match.list]p1.2: (second phase list initialization)
9421 // the candidate functions are all the constructors of the class T
9422 // C++ [over.match.ctor]p1: (all other cases)
9423 // the candidate functions are all the constructors of the class of
9424 // the object being initialized
9426 // C++ [over.best.ics]p4:
9427 // When [...] the constructor [...] is a candidate by
9428 // - [over.match.copy] (in all cases)
9429 // FIXME: The "second phase of [over.match.list] case can also
9430 // theoretically happen here, but it's not clear whether we can
9431 // ever have a parameter of the right type.
9432 bool SuppressUserConversions = Kind.isCopyInit();
9435 AddTemplateOverloadCandidate(TD, I.getPair(), /*ExplicitArgs*/ nullptr,
9436 Inits, Candidates, SuppressUserConversions,
9437 /*PartialOverloading*/ false,
9440 AddOverloadCandidate(GD, I.getPair(), Inits, Candidates,
9441 SuppressUserConversions,
9442 /*PartialOverloading*/ false, AllowExplicit);
9444 return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
9447 OverloadingResult Result = OR_No_Viable_Function;
9449 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
9450 // try initializer-list constructors.
9452 bool TryListConstructors = true;
9454 // Try list constructors unless the list is empty and the class has one or
9455 // more default constructors, in which case those constructors win.
9456 if (!ListInit->getNumInits()) {
9457 for (NamedDecl *D : Guides) {
9458 auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
9459 if (FD && FD->getMinRequiredArguments() == 0) {
9460 TryListConstructors = false;
9464 } else if (ListInit->getNumInits() == 1) {
9465 // C++ [over.match.class.deduct]:
9466 // As an exception, the first phase in [over.match.list] (considering
9467 // initializer-list constructors) is omitted if the initializer list
9468 // consists of a single expression of type cv U, where U is a
9469 // specialization of C or a class derived from a specialization of C.
9470 Expr *E = ListInit->getInit(0);
9471 auto *RD = E->getType()->getAsCXXRecordDecl();
9472 if (!isa<InitListExpr>(E) && RD &&
9473 isCompleteType(Kind.getLocation(), E->getType()) &&
9474 isOrIsDerivedFromSpecializationOf(RD, Template))
9475 TryListConstructors = false;
9478 if (TryListConstructors)
9479 Result = tryToResolveOverload(/*OnlyListConstructor*/true);
9480 // Then unwrap the initializer list and try again considering all
9482 Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
9485 // If list-initialization fails, or if we're doing any other kind of
9486 // initialization, we (eventually) consider constructors.
9487 if (Result == OR_No_Viable_Function)
9488 Result = tryToResolveOverload(/*OnlyListConstructor*/false);
9492 // FIXME: For list-initialization candidates, it'd usually be better to
9493 // list why they were not viable when given the initializer list itself as
9495 Candidates.NoteCandidates(
9496 PartialDiagnosticAt(
9498 PDiag(diag::err_deduced_class_template_ctor_ambiguous)
9500 *this, OCD_ViableCandidates, Inits);
9503 case OR_No_Viable_Function: {
9504 CXXRecordDecl *Primary =
9505 cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
9507 isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary));
9508 Candidates.NoteCandidates(
9509 PartialDiagnosticAt(
9511 PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable
9512 : diag::err_deduced_class_template_incomplete)
9513 << TemplateName << !Guides.empty()),
9514 *this, OCD_AllCandidates, Inits);
9519 Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
9521 NoteDeletedFunction(Best->Function);
9526 // C++ [over.match.list]p1:
9527 // In copy-list-initialization, if an explicit constructor is chosen, the
9528 // initialization is ill-formed.
9529 if (Kind.isCopyInit() && ListInit &&
9530 cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
9531 bool IsDeductionGuide = !Best->Function->isImplicit();
9532 Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
9533 << TemplateName << IsDeductionGuide;
9534 Diag(Best->Function->getLocation(),
9535 diag::note_explicit_ctor_deduction_guide_here)
9536 << IsDeductionGuide;
9540 // Make sure we didn't select an unusable deduction guide, and mark it
9542 DiagnoseUseOfDecl(Best->Function, Kind.getLocation());
9543 MarkFunctionReferenced(Kind.getLocation(), Best->Function);
9547 // C++ [dcl.type.class.deduct]p1:
9548 // The placeholder is replaced by the return type of the function selected
9549 // by overload resolution for class template deduction.
9550 QualType DeducedType =
9551 SubstAutoType(TSInfo->getType(), Best->Function->getReturnType());
9552 Diag(TSInfo->getTypeLoc().getBeginLoc(),
9553 diag::warn_cxx14_compat_class_template_argument_deduction)
9554 << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType;
9556 // Warn if CTAD was used on a type that does not have any user-defined
9557 // deduction guides.
9558 if (!HasAnyDeductionGuide) {
9559 Diag(TSInfo->getTypeLoc().getBeginLoc(),
9560 diag::warn_ctad_maybe_unsupported)
9562 Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported);