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/IgnoreExpr.h"
19 #include "clang/AST/TypeLoc.h"
20 #include "clang/Basic/CharInfo.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "clang/Basic/Specifiers.h"
23 #include "clang/Basic/TargetInfo.h"
24 #include "clang/Sema/Designator.h"
25 #include "clang/Sema/EnterExpressionEvaluationContext.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/SemaInternal.h"
29 #include "llvm/ADT/APInt.h"
30 #include "llvm/ADT/FoldingSet.h"
31 #include "llvm/ADT/PointerIntPair.h"
32 #include "llvm/ADT/SmallString.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/StringExtras.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
38 using namespace clang
;
40 //===----------------------------------------------------------------------===//
41 // Sema Initialization Checking
42 //===----------------------------------------------------------------------===//
44 /// Check whether T is compatible with a wide character type (wchar_t,
45 /// char16_t or char32_t).
46 static bool IsWideCharCompatible(QualType T
, ASTContext
&Context
) {
47 if (Context
.typesAreCompatible(Context
.getWideCharType(), T
))
49 if (Context
.getLangOpts().CPlusPlus
|| Context
.getLangOpts().C11
) {
50 return Context
.typesAreCompatible(Context
.Char16Ty
, T
) ||
51 Context
.typesAreCompatible(Context
.Char32Ty
, T
);
56 enum StringInitFailureKind
{
58 SIF_NarrowStringIntoWideChar
,
59 SIF_WideStringIntoChar
,
60 SIF_IncompatWideStringIntoWideChar
,
61 SIF_UTF8StringIntoPlainChar
,
62 SIF_PlainStringIntoUTF8Char
,
66 /// Check whether the array of type AT can be initialized by the Init
67 /// expression by means of string initialization. Returns SIF_None if so,
68 /// otherwise returns a StringInitFailureKind that describes why the
69 /// initialization would not work.
70 static StringInitFailureKind
IsStringInit(Expr
*Init
, const ArrayType
*AT
,
71 ASTContext
&Context
) {
72 if (!isa
<ConstantArrayType
>(AT
) && !isa
<IncompleteArrayType
>(AT
))
75 // See if this is a string literal or @encode.
76 Init
= Init
->IgnoreParens();
78 // Handle @encode, which is a narrow string.
79 if (isa
<ObjCEncodeExpr
>(Init
) && AT
->getElementType()->isCharType())
82 // Otherwise we can only handle string literals.
83 StringLiteral
*SL
= dyn_cast
<StringLiteral
>(Init
);
87 const QualType ElemTy
=
88 Context
.getCanonicalType(AT
->getElementType()).getUnqualifiedType();
90 auto IsCharOrUnsignedChar
= [](const QualType
&T
) {
91 const BuiltinType
*BT
= dyn_cast
<BuiltinType
>(T
.getTypePtr());
92 return BT
&& BT
->isCharType() && BT
->getKind() != BuiltinType::SChar
;
95 switch (SL
->getKind()) {
96 case StringLiteral::UTF8
:
97 // char8_t array can be initialized with a UTF-8 string.
98 // - C++20 [dcl.init.string] (DR)
99 // Additionally, an array of char or unsigned char may be initialized
100 // by a UTF-8 string literal.
101 if (ElemTy
->isChar8Type() ||
102 (Context
.getLangOpts().Char8
&&
103 IsCharOrUnsignedChar(ElemTy
.getCanonicalType())))
106 case StringLiteral::Ordinary
:
107 // char array can be initialized with a narrow string.
108 // Only allow char x[] = "foo"; not char x[] = L"foo";
109 if (ElemTy
->isCharType())
110 return (SL
->getKind() == StringLiteral::UTF8
&&
111 Context
.getLangOpts().Char8
)
112 ? SIF_UTF8StringIntoPlainChar
114 if (ElemTy
->isChar8Type())
115 return SIF_PlainStringIntoUTF8Char
;
116 if (IsWideCharCompatible(ElemTy
, Context
))
117 return SIF_NarrowStringIntoWideChar
;
119 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
120 // "An array with element type compatible with a qualified or unqualified
121 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
122 // string literal with the corresponding encoding prefix (L, u, or U,
123 // respectively), optionally enclosed in braces.
124 case StringLiteral::UTF16
:
125 if (Context
.typesAreCompatible(Context
.Char16Ty
, ElemTy
))
127 if (ElemTy
->isCharType() || ElemTy
->isChar8Type())
128 return SIF_WideStringIntoChar
;
129 if (IsWideCharCompatible(ElemTy
, Context
))
130 return SIF_IncompatWideStringIntoWideChar
;
132 case StringLiteral::UTF32
:
133 if (Context
.typesAreCompatible(Context
.Char32Ty
, ElemTy
))
135 if (ElemTy
->isCharType() || ElemTy
->isChar8Type())
136 return SIF_WideStringIntoChar
;
137 if (IsWideCharCompatible(ElemTy
, Context
))
138 return SIF_IncompatWideStringIntoWideChar
;
140 case StringLiteral::Wide
:
141 if (Context
.typesAreCompatible(Context
.getWideCharType(), ElemTy
))
143 if (ElemTy
->isCharType() || ElemTy
->isChar8Type())
144 return SIF_WideStringIntoChar
;
145 if (IsWideCharCompatible(ElemTy
, Context
))
146 return SIF_IncompatWideStringIntoWideChar
;
148 case StringLiteral::Unevaluated
:
149 assert(false && "Unevaluated string literal in initialization");
153 llvm_unreachable("missed a StringLiteral kind?");
156 static StringInitFailureKind
IsStringInit(Expr
*init
, QualType declType
,
157 ASTContext
&Context
) {
158 const ArrayType
*arrayType
= Context
.getAsArrayType(declType
);
161 return IsStringInit(init
, arrayType
, Context
);
164 bool Sema::IsStringInit(Expr
*Init
, const ArrayType
*AT
) {
165 return ::IsStringInit(Init
, AT
, Context
) == SIF_None
;
168 /// Update the type of a string literal, including any surrounding parentheses,
169 /// to match the type of the object which it is initializing.
170 static void updateStringLiteralType(Expr
*E
, QualType Ty
) {
173 E
->setValueKind(VK_PRValue
);
174 if (isa
<StringLiteral
>(E
) || isa
<ObjCEncodeExpr
>(E
))
176 E
= IgnoreParensSingleStep(E
);
180 /// Fix a compound literal initializing an array so it's correctly marked
182 static void updateGNUCompoundLiteralRValue(Expr
*E
) {
184 E
->setValueKind(VK_PRValue
);
185 if (isa
<CompoundLiteralExpr
>(E
))
187 E
= IgnoreParensSingleStep(E
);
191 static void CheckStringInit(Expr
*Str
, QualType
&DeclT
, const ArrayType
*AT
,
193 // Get the length of the string as parsed.
194 auto *ConstantArrayTy
=
195 cast
<ConstantArrayType
>(Str
->getType()->getAsArrayTypeUnsafe());
196 uint64_t StrLength
= ConstantArrayTy
->getSize().getZExtValue();
198 if (const IncompleteArrayType
*IAT
= dyn_cast
<IncompleteArrayType
>(AT
)) {
199 // C99 6.7.8p14. We have an array of character type with unknown size
200 // being initialized to a string literal.
201 llvm::APInt
ConstVal(32, StrLength
);
202 // Return a new array type (C99 6.7.8p22).
203 DeclT
= S
.Context
.getConstantArrayType(
204 IAT
->getElementType(), ConstVal
, nullptr, ArraySizeModifier::Normal
, 0);
205 updateStringLiteralType(Str
, DeclT
);
209 const ConstantArrayType
*CAT
= cast
<ConstantArrayType
>(AT
);
211 // We have an array of character type with known size. However,
212 // the size may be smaller or larger than the string we are initializing.
213 // FIXME: Avoid truncation for 64-bit length strings.
214 if (S
.getLangOpts().CPlusPlus
) {
215 if (StringLiteral
*SL
= dyn_cast
<StringLiteral
>(Str
->IgnoreParens())) {
216 // For Pascal strings it's OK to strip off the terminating null character,
217 // so the example below is valid:
219 // unsigned char a[2] = "\pa";
224 // [dcl.init.string]p2
225 if (StrLength
> CAT
->getSize().getZExtValue())
226 S
.Diag(Str
->getBeginLoc(),
227 diag::err_initializer_string_for_char_array_too_long
)
228 << CAT
->getSize().getZExtValue() << StrLength
229 << Str
->getSourceRange();
232 if (StrLength
-1 > CAT
->getSize().getZExtValue())
233 S
.Diag(Str
->getBeginLoc(),
234 diag::ext_initializer_string_for_char_array_too_long
)
235 << Str
->getSourceRange();
238 // Set the type to the actual size that we are initializing. If we have
240 // char x[1] = "foo";
241 // then this will set the string literal's type to char[1].
242 updateStringLiteralType(Str
, DeclT
);
245 //===----------------------------------------------------------------------===//
246 // Semantic checking for initializer lists.
247 //===----------------------------------------------------------------------===//
251 /// Semantic checking for initializer lists.
253 /// The InitListChecker class contains a set of routines that each
254 /// handle the initialization of a certain kind of entity, e.g.,
255 /// arrays, vectors, struct/union types, scalars, etc. The
256 /// InitListChecker itself performs a recursive walk of the subobject
257 /// structure of the type to be initialized, while stepping through
258 /// the initializer list one element at a time. The IList and Index
259 /// parameters to each of the Check* routines contain the active
260 /// (syntactic) initializer list and the index into that initializer
261 /// list that represents the current initializer. Each routine is
262 /// responsible for moving that Index forward as it consumes elements.
264 /// Each Check* routine also has a StructuredList/StructuredIndex
265 /// arguments, which contains the current "structured" (semantic)
266 /// initializer list and the index into that initializer list where we
267 /// are copying initializers as we map them over to the semantic
268 /// list. Once we have completed our recursive walk of the subobject
269 /// structure, we will have constructed a full semantic initializer
272 /// C99 designators cause changes in the initializer list traversal,
273 /// because they make the initialization "jump" into a specific
274 /// subobject and then continue the initialization from that
275 /// point. CheckDesignatedInitializer() recursively steps into the
276 /// designated subobject and manages backing out the recursion to
277 /// initialize the subobjects after the one designated.
279 /// If an initializer list contains any designators, we build a placeholder
280 /// structured list even in 'verify only' mode, so that we can track which
281 /// elements need 'empty' initializtion.
282 class InitListChecker
{
284 bool hadError
= false;
285 bool VerifyOnly
; // No diagnostics.
286 bool TreatUnavailableAsInvalid
; // Used only in VerifyOnly mode.
287 bool InOverloadResolution
;
288 InitListExpr
*FullyStructuredList
= nullptr;
289 NoInitExpr
*DummyExpr
= nullptr;
290 SmallVectorImpl
<QualType
> *AggrDeductionCandidateParamTypes
= nullptr;
292 NoInitExpr
*getDummyInit() {
294 DummyExpr
= new (SemaRef
.Context
) NoInitExpr(SemaRef
.Context
.VoidTy
);
298 void CheckImplicitInitList(const InitializedEntity
&Entity
,
299 InitListExpr
*ParentIList
, QualType T
,
300 unsigned &Index
, InitListExpr
*StructuredList
,
301 unsigned &StructuredIndex
);
302 void CheckExplicitInitList(const InitializedEntity
&Entity
,
303 InitListExpr
*IList
, QualType
&T
,
304 InitListExpr
*StructuredList
,
305 bool TopLevelObject
= false);
306 void CheckListElementTypes(const InitializedEntity
&Entity
,
307 InitListExpr
*IList
, QualType
&DeclType
,
308 bool SubobjectIsDesignatorContext
,
310 InitListExpr
*StructuredList
,
311 unsigned &StructuredIndex
,
312 bool TopLevelObject
= false);
313 void CheckSubElementType(const InitializedEntity
&Entity
,
314 InitListExpr
*IList
, QualType ElemType
,
316 InitListExpr
*StructuredList
,
317 unsigned &StructuredIndex
,
318 bool DirectlyDesignated
= false);
319 void CheckComplexType(const InitializedEntity
&Entity
,
320 InitListExpr
*IList
, QualType DeclType
,
322 InitListExpr
*StructuredList
,
323 unsigned &StructuredIndex
);
324 void CheckScalarType(const InitializedEntity
&Entity
,
325 InitListExpr
*IList
, QualType DeclType
,
327 InitListExpr
*StructuredList
,
328 unsigned &StructuredIndex
);
329 void CheckReferenceType(const InitializedEntity
&Entity
,
330 InitListExpr
*IList
, QualType DeclType
,
332 InitListExpr
*StructuredList
,
333 unsigned &StructuredIndex
);
334 void CheckVectorType(const InitializedEntity
&Entity
,
335 InitListExpr
*IList
, QualType DeclType
, unsigned &Index
,
336 InitListExpr
*StructuredList
,
337 unsigned &StructuredIndex
);
338 void CheckStructUnionTypes(const InitializedEntity
&Entity
,
339 InitListExpr
*IList
, QualType DeclType
,
340 CXXRecordDecl::base_class_const_range Bases
,
341 RecordDecl::field_iterator Field
,
342 bool SubobjectIsDesignatorContext
, unsigned &Index
,
343 InitListExpr
*StructuredList
,
344 unsigned &StructuredIndex
,
345 bool TopLevelObject
= false);
346 void CheckArrayType(const InitializedEntity
&Entity
,
347 InitListExpr
*IList
, QualType
&DeclType
,
348 llvm::APSInt elementIndex
,
349 bool SubobjectIsDesignatorContext
, unsigned &Index
,
350 InitListExpr
*StructuredList
,
351 unsigned &StructuredIndex
);
352 bool CheckDesignatedInitializer(const InitializedEntity
&Entity
,
353 InitListExpr
*IList
, DesignatedInitExpr
*DIE
,
355 QualType
&CurrentObjectType
,
356 RecordDecl::field_iterator
*NextField
,
357 llvm::APSInt
*NextElementIndex
,
359 InitListExpr
*StructuredList
,
360 unsigned &StructuredIndex
,
361 bool FinishSubobjectInit
,
362 bool TopLevelObject
);
363 InitListExpr
*getStructuredSubobjectInit(InitListExpr
*IList
, unsigned Index
,
364 QualType CurrentObjectType
,
365 InitListExpr
*StructuredList
,
366 unsigned StructuredIndex
,
367 SourceRange InitRange
,
368 bool IsFullyOverwritten
= false);
369 void UpdateStructuredListElement(InitListExpr
*StructuredList
,
370 unsigned &StructuredIndex
,
372 InitListExpr
*createInitListExpr(QualType CurrentObjectType
,
373 SourceRange InitRange
,
374 unsigned ExpectedNumInits
);
375 int numArrayElements(QualType DeclType
);
376 int numStructUnionElements(QualType DeclType
);
377 static RecordDecl
*getRecordDecl(QualType DeclType
);
379 ExprResult
PerformEmptyInit(SourceLocation Loc
,
380 const InitializedEntity
&Entity
);
382 /// Diagnose that OldInit (or part thereof) has been overridden by NewInit.
383 void diagnoseInitOverride(Expr
*OldInit
, SourceRange NewInitRange
,
384 bool UnionOverride
= false,
385 bool FullyOverwritten
= true) {
386 // Overriding an initializer via a designator is valid with C99 designated
387 // initializers, but ill-formed with C++20 designated initializers.
389 SemaRef
.getLangOpts().CPlusPlus
390 ? (UnionOverride
? diag::ext_initializer_union_overrides
391 : diag::ext_initializer_overrides
)
392 : diag::warn_initializer_overrides
;
394 if (InOverloadResolution
&& SemaRef
.getLangOpts().CPlusPlus
) {
395 // In overload resolution, we have to strictly enforce the rules, and so
396 // don't allow any overriding of prior initializers. This matters for a
399 // union U { int a, b; };
400 // struct S { int a, b; };
403 // Here, f({.a = 1, .b = 2}) is required to call the struct overload. For
404 // consistency, we disallow all overriding of prior initializers in
405 // overload resolution, not only overriding of union members.
407 } else if (OldInit
->getType().isDestructedType() && !FullyOverwritten
) {
408 // If we'll be keeping around the old initializer but overwriting part of
409 // the object it initialized, and that object is not trivially
410 // destructible, this can leak. Don't allow that, not even as an
413 // FIXME: It might be reasonable to allow this in cases where the part of
414 // the initializer that we're overriding has trivial destruction.
415 DiagID
= diag::err_initializer_overrides_destructed
;
416 } else if (!OldInit
->getSourceRange().isValid()) {
417 // We need to check on source range validity because the previous
418 // initializer does not have to be an explicit initializer. e.g.,
420 // struct P { int a, b; };
421 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
423 // There is an overwrite taking place because the first braced initializer
424 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
426 // Such overwrites are harmless, so we don't diagnose them. (Note that in
427 // C++, this cannot be reached unless we've already seen and diagnosed a
428 // different conformance issue, such as a mixture of designated and
429 // non-designated initializers or a multi-level designator.)
434 SemaRef
.Diag(NewInitRange
.getBegin(), DiagID
)
435 << NewInitRange
<< FullyOverwritten
<< OldInit
->getType();
436 SemaRef
.Diag(OldInit
->getBeginLoc(), diag::note_previous_initializer
)
437 << (OldInit
->HasSideEffects(SemaRef
.Context
) && FullyOverwritten
)
438 << OldInit
->getSourceRange();
442 // Explanation on the "FillWithNoInit" mode:
444 // Assume we have the following definitions (Case#1):
445 // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
446 // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
448 // l.lp.x[1][0..1] should not be filled with implicit initializers because the
449 // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
451 // But if we have (Case#2):
452 // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
454 // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
455 // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
457 // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
458 // in the InitListExpr, the "holes" in Case#1 are filled not with empty
459 // initializers but with special "NoInitExpr" place holders, which tells the
460 // CodeGen not to generate any initializers for these parts.
461 void FillInEmptyInitForBase(unsigned Init
, const CXXBaseSpecifier
&Base
,
462 const InitializedEntity
&ParentEntity
,
463 InitListExpr
*ILE
, bool &RequiresSecondPass
,
464 bool FillWithNoInit
);
465 void FillInEmptyInitForField(unsigned Init
, FieldDecl
*Field
,
466 const InitializedEntity
&ParentEntity
,
467 InitListExpr
*ILE
, bool &RequiresSecondPass
,
468 bool FillWithNoInit
= false);
469 void FillInEmptyInitializations(const InitializedEntity
&Entity
,
470 InitListExpr
*ILE
, bool &RequiresSecondPass
,
471 InitListExpr
*OuterILE
, unsigned OuterIndex
,
472 bool FillWithNoInit
= false);
473 bool CheckFlexibleArrayInit(const InitializedEntity
&Entity
,
474 Expr
*InitExpr
, FieldDecl
*Field
,
475 bool TopLevelObject
);
476 void CheckEmptyInitializable(const InitializedEntity
&Entity
,
481 Sema
&S
, const InitializedEntity
&Entity
, InitListExpr
*IL
, QualType
&T
,
482 bool VerifyOnly
, bool TreatUnavailableAsInvalid
,
483 bool InOverloadResolution
= false,
484 SmallVectorImpl
<QualType
> *AggrDeductionCandidateParamTypes
= nullptr);
485 InitListChecker(Sema
&S
, const InitializedEntity
&Entity
, InitListExpr
*IL
,
487 SmallVectorImpl
<QualType
> &AggrDeductionCandidateParamTypes
)
488 : InitListChecker(S
, Entity
, IL
, T
, /*VerifyOnly=*/true,
489 /*TreatUnavailableAsInvalid=*/false,
490 /*InOverloadResolution=*/false,
491 &AggrDeductionCandidateParamTypes
){};
493 bool HadError() { return hadError
; }
495 // Retrieves the fully-structured initializer list used for
496 // semantic analysis and code generation.
497 InitListExpr
*getFullyStructuredList() const { return FullyStructuredList
; }
500 } // end anonymous namespace
502 ExprResult
InitListChecker::PerformEmptyInit(SourceLocation Loc
,
503 const InitializedEntity
&Entity
) {
504 InitializationKind Kind
= InitializationKind::CreateValue(Loc
, Loc
, Loc
,
506 MultiExprArg SubInit
;
508 InitListExpr
DummyInitList(SemaRef
.Context
, Loc
, std::nullopt
, Loc
);
510 // C++ [dcl.init.aggr]p7:
511 // If there are fewer initializer-clauses in the list than there are
512 // members in the aggregate, then each member not explicitly initialized
514 bool EmptyInitList
= SemaRef
.getLangOpts().CPlusPlus11
&&
515 Entity
.getType()->getBaseElementTypeUnsafe()->isRecordType();
518 // shall be initialized [...] from an empty initializer list.
520 // We apply the resolution of this DR to C++11 but not C++98, since C++98
521 // does not have useful semantics for initialization from an init list.
522 // We treat this as copy-initialization, because aggregate initialization
523 // always performs copy-initialization on its elements.
525 // Only do this if we're initializing a class type, to avoid filling in
526 // the initializer list where possible.
527 InitExpr
= VerifyOnly
529 : new (SemaRef
.Context
)
530 InitListExpr(SemaRef
.Context
, Loc
, std::nullopt
, Loc
);
531 InitExpr
->setType(SemaRef
.Context
.VoidTy
);
533 Kind
= InitializationKind::CreateCopy(Loc
, Loc
);
536 // shall be value-initialized.
539 InitializationSequence
InitSeq(SemaRef
, Entity
, Kind
, SubInit
);
540 // libstdc++4.6 marks the vector default constructor as explicit in
541 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
542 // stlport does so too. Look for std::__debug for libstdc++, and for
543 // std:: for stlport. This is effectively a compiler-side implementation of
545 if (!InitSeq
&& EmptyInitList
&& InitSeq
.getFailureKind() ==
546 InitializationSequence::FK_ExplicitConstructor
) {
547 OverloadCandidateSet::iterator Best
;
548 OverloadingResult O
=
549 InitSeq
.getFailedCandidateSet()
550 .BestViableFunction(SemaRef
, Kind
.getLocation(), Best
);
552 assert(O
== OR_Success
&& "Inconsistent overload resolution");
553 CXXConstructorDecl
*CtorDecl
= cast
<CXXConstructorDecl
>(Best
->Function
);
554 CXXRecordDecl
*R
= CtorDecl
->getParent();
556 if (CtorDecl
->getMinRequiredArguments() == 0 &&
557 CtorDecl
->isExplicit() && R
->getDeclName() &&
558 SemaRef
.SourceMgr
.isInSystemHeader(CtorDecl
->getLocation())) {
559 bool IsInStd
= false;
560 for (NamespaceDecl
*ND
= dyn_cast
<NamespaceDecl
>(R
->getDeclContext());
561 ND
&& !IsInStd
; ND
= dyn_cast
<NamespaceDecl
>(ND
->getParent())) {
562 if (SemaRef
.getStdNamespace()->InEnclosingNamespaceSetOf(ND
))
566 if (IsInStd
&& llvm::StringSwitch
<bool>(R
->getName())
567 .Cases("basic_string", "deque", "forward_list", true)
568 .Cases("list", "map", "multimap", "multiset", true)
569 .Cases("priority_queue", "queue", "set", "stack", true)
570 .Cases("unordered_map", "unordered_set", "vector", true)
572 InitSeq
.InitializeFrom(
574 InitializationKind::CreateValue(Loc
, Loc
, Loc
, true),
575 MultiExprArg(), /*TopLevelOfInitList=*/false,
576 TreatUnavailableAsInvalid
);
577 // Emit a warning for this. System header warnings aren't shown
578 // by default, but people working on system headers should see it.
580 SemaRef
.Diag(CtorDecl
->getLocation(),
581 diag::warn_invalid_initializer_from_system_header
);
582 if (Entity
.getKind() == InitializedEntity::EK_Member
)
583 SemaRef
.Diag(Entity
.getDecl()->getLocation(),
584 diag::note_used_in_initialization_here
);
585 else if (Entity
.getKind() == InitializedEntity::EK_ArrayElement
)
586 SemaRef
.Diag(Loc
, diag::note_used_in_initialization_here
);
593 InitSeq
.Diagnose(SemaRef
, Entity
, Kind
, SubInit
);
594 if (Entity
.getKind() == InitializedEntity::EK_Member
)
595 SemaRef
.Diag(Entity
.getDecl()->getLocation(),
596 diag::note_in_omitted_aggregate_initializer
)
597 << /*field*/1 << Entity
.getDecl();
598 else if (Entity
.getKind() == InitializedEntity::EK_ArrayElement
) {
599 bool IsTrailingArrayNewMember
=
600 Entity
.getParent() &&
601 Entity
.getParent()->isVariableLengthArrayNew();
602 SemaRef
.Diag(Loc
, diag::note_in_omitted_aggregate_initializer
)
603 << (IsTrailingArrayNewMember
? 2 : /*array element*/0)
604 << Entity
.getElementIndex();
611 return VerifyOnly
? ExprResult()
612 : InitSeq
.Perform(SemaRef
, Entity
, Kind
, SubInit
);
615 void InitListChecker::CheckEmptyInitializable(const InitializedEntity
&Entity
,
616 SourceLocation Loc
) {
617 // If we're building a fully-structured list, we'll check this at the end
618 // once we know which elements are actually initialized. Otherwise, we know
619 // that there are no designators so we can just check now.
620 if (FullyStructuredList
)
622 PerformEmptyInit(Loc
, Entity
);
625 void InitListChecker::FillInEmptyInitForBase(
626 unsigned Init
, const CXXBaseSpecifier
&Base
,
627 const InitializedEntity
&ParentEntity
, InitListExpr
*ILE
,
628 bool &RequiresSecondPass
, bool FillWithNoInit
) {
629 InitializedEntity BaseEntity
= InitializedEntity::InitializeBase(
630 SemaRef
.Context
, &Base
, false, &ParentEntity
);
632 if (Init
>= ILE
->getNumInits() || !ILE
->getInit(Init
)) {
633 ExprResult BaseInit
= FillWithNoInit
634 ? new (SemaRef
.Context
) NoInitExpr(Base
.getType())
635 : PerformEmptyInit(ILE
->getEndLoc(), BaseEntity
);
636 if (BaseInit
.isInvalid()) {
642 assert(Init
< ILE
->getNumInits() && "should have been expanded");
643 ILE
->setInit(Init
, BaseInit
.getAs
<Expr
>());
645 } else if (InitListExpr
*InnerILE
=
646 dyn_cast
<InitListExpr
>(ILE
->getInit(Init
))) {
647 FillInEmptyInitializations(BaseEntity
, InnerILE
, RequiresSecondPass
,
648 ILE
, Init
, FillWithNoInit
);
649 } else if (DesignatedInitUpdateExpr
*InnerDIUE
=
650 dyn_cast
<DesignatedInitUpdateExpr
>(ILE
->getInit(Init
))) {
651 FillInEmptyInitializations(BaseEntity
, InnerDIUE
->getUpdater(),
652 RequiresSecondPass
, ILE
, Init
,
653 /*FillWithNoInit =*/true);
657 void InitListChecker::FillInEmptyInitForField(unsigned Init
, FieldDecl
*Field
,
658 const InitializedEntity
&ParentEntity
,
660 bool &RequiresSecondPass
,
661 bool FillWithNoInit
) {
662 SourceLocation Loc
= ILE
->getEndLoc();
663 unsigned NumInits
= ILE
->getNumInits();
664 InitializedEntity MemberEntity
665 = InitializedEntity::InitializeMember(Field
, &ParentEntity
);
667 if (Init
>= NumInits
|| !ILE
->getInit(Init
)) {
668 if (const RecordType
*RType
= ILE
->getType()->getAs
<RecordType
>())
669 if (!RType
->getDecl()->isUnion())
670 assert((Init
< NumInits
|| VerifyOnly
) &&
671 "This ILE should have been expanded");
673 if (FillWithNoInit
) {
674 assert(!VerifyOnly
&& "should not fill with no-init in verify-only mode");
675 Expr
*Filler
= new (SemaRef
.Context
) NoInitExpr(Field
->getType());
677 ILE
->setInit(Init
, Filler
);
679 ILE
->updateInit(SemaRef
.Context
, Init
, Filler
);
682 // C++1y [dcl.init.aggr]p7:
683 // If there are fewer initializer-clauses in the list than there are
684 // members in the aggregate, then each member not explicitly initialized
685 // shall be initialized from its brace-or-equal-initializer [...]
686 if (Field
->hasInClassInitializer()) {
690 ExprResult DIE
= SemaRef
.BuildCXXDefaultInitExpr(Loc
, Field
);
691 if (DIE
.isInvalid()) {
695 SemaRef
.checkInitializerLifetime(MemberEntity
, DIE
.get());
697 ILE
->setInit(Init
, DIE
.get());
699 ILE
->updateInit(SemaRef
.Context
, Init
, DIE
.get());
700 RequiresSecondPass
= true;
705 if (Field
->getType()->isReferenceType()) {
707 // C++ [dcl.init.aggr]p9:
708 // If an incomplete or empty initializer-list leaves a
709 // member of reference type uninitialized, the program is
711 SemaRef
.Diag(Loc
, diag::err_init_reference_member_uninitialized
)
713 << (ILE
->isSyntacticForm() ? ILE
: ILE
->getSyntacticForm())
715 SemaRef
.Diag(Field
->getLocation(), diag::note_uninit_reference_member
);
721 ExprResult MemberInit
= PerformEmptyInit(Loc
, MemberEntity
);
722 if (MemberInit
.isInvalid()) {
727 if (hadError
|| VerifyOnly
) {
729 } else if (Init
< NumInits
) {
730 ILE
->setInit(Init
, MemberInit
.getAs
<Expr
>());
731 } else if (!isa
<ImplicitValueInitExpr
>(MemberInit
.get())) {
732 // Empty initialization requires a constructor call, so
733 // extend the initializer list to include the constructor
734 // call and make a note that we'll need to take another pass
735 // through the initializer list.
736 ILE
->updateInit(SemaRef
.Context
, Init
, MemberInit
.getAs
<Expr
>());
737 RequiresSecondPass
= true;
739 } else if (InitListExpr
*InnerILE
740 = dyn_cast
<InitListExpr
>(ILE
->getInit(Init
))) {
741 FillInEmptyInitializations(MemberEntity
, InnerILE
,
742 RequiresSecondPass
, ILE
, Init
, FillWithNoInit
);
743 } else if (DesignatedInitUpdateExpr
*InnerDIUE
=
744 dyn_cast
<DesignatedInitUpdateExpr
>(ILE
->getInit(Init
))) {
745 FillInEmptyInitializations(MemberEntity
, InnerDIUE
->getUpdater(),
746 RequiresSecondPass
, ILE
, Init
,
747 /*FillWithNoInit =*/true);
751 /// Recursively replaces NULL values within the given initializer list
752 /// with expressions that perform value-initialization of the
753 /// appropriate type, and finish off the InitListExpr formation.
755 InitListChecker::FillInEmptyInitializations(const InitializedEntity
&Entity
,
757 bool &RequiresSecondPass
,
758 InitListExpr
*OuterILE
,
760 bool FillWithNoInit
) {
761 assert((ILE
->getType() != SemaRef
.Context
.VoidTy
) &&
762 "Should not have void type");
764 // We don't need to do any checks when just filling NoInitExprs; that can't
766 if (FillWithNoInit
&& VerifyOnly
)
769 // If this is a nested initializer list, we might have changed its contents
770 // (and therefore some of its properties, such as instantiation-dependence)
771 // while filling it in. Inform the outer initializer list so that its state
772 // can be updated to match.
773 // FIXME: We should fully build the inner initializers before constructing
774 // the outer InitListExpr instead of mutating AST nodes after they have
775 // been used as subexpressions of other nodes.
776 struct UpdateOuterILEWithUpdatedInit
{
779 ~UpdateOuterILEWithUpdatedInit() {
781 Outer
->setInit(OuterIndex
, Outer
->getInit(OuterIndex
));
783 } UpdateOuterRAII
= {OuterILE
, OuterIndex
};
785 // A transparent ILE is not performing aggregate initialization and should
787 if (ILE
->isTransparent())
790 if (const RecordType
*RType
= ILE
->getType()->getAs
<RecordType
>()) {
791 const RecordDecl
*RDecl
= RType
->getDecl();
792 if (RDecl
->isUnion() && ILE
->getInitializedFieldInUnion())
793 FillInEmptyInitForField(0, ILE
->getInitializedFieldInUnion(),
794 Entity
, ILE
, RequiresSecondPass
, FillWithNoInit
);
795 else if (RDecl
->isUnion() && isa
<CXXRecordDecl
>(RDecl
) &&
796 cast
<CXXRecordDecl
>(RDecl
)->hasInClassInitializer()) {
797 for (auto *Field
: RDecl
->fields()) {
798 if (Field
->hasInClassInitializer()) {
799 FillInEmptyInitForField(0, Field
, Entity
, ILE
, RequiresSecondPass
,
805 // The fields beyond ILE->getNumInits() are default initialized, so in
806 // order to leave them uninitialized, the ILE is expanded and the extra
807 // fields are then filled with NoInitExpr.
808 unsigned NumElems
= numStructUnionElements(ILE
->getType());
809 if (!RDecl
->isUnion() && RDecl
->hasFlexibleArrayMember())
811 if (!VerifyOnly
&& ILE
->getNumInits() < NumElems
)
812 ILE
->resizeInits(SemaRef
.Context
, NumElems
);
816 if (auto *CXXRD
= dyn_cast
<CXXRecordDecl
>(RDecl
)) {
817 for (auto &Base
: CXXRD
->bases()) {
821 FillInEmptyInitForBase(Init
, Base
, Entity
, ILE
, RequiresSecondPass
,
827 for (auto *Field
: RDecl
->fields()) {
828 if (Field
->isUnnamedBitfield())
834 FillInEmptyInitForField(Init
, Field
, Entity
, ILE
, RequiresSecondPass
,
841 // Only look at the first initialization of a union.
842 if (RDecl
->isUnion())
850 QualType ElementType
;
852 InitializedEntity ElementEntity
= Entity
;
853 unsigned NumInits
= ILE
->getNumInits();
854 unsigned NumElements
= NumInits
;
855 if (const ArrayType
*AType
= SemaRef
.Context
.getAsArrayType(ILE
->getType())) {
856 ElementType
= AType
->getElementType();
857 if (const auto *CAType
= dyn_cast
<ConstantArrayType
>(AType
))
858 NumElements
= CAType
->getSize().getZExtValue();
859 // For an array new with an unknown bound, ask for one additional element
860 // in order to populate the array filler.
861 if (Entity
.isVariableLengthArrayNew())
863 ElementEntity
= InitializedEntity::InitializeElement(SemaRef
.Context
,
865 } else if (const VectorType
*VType
= ILE
->getType()->getAs
<VectorType
>()) {
866 ElementType
= VType
->getElementType();
867 NumElements
= VType
->getNumElements();
868 ElementEntity
= InitializedEntity::InitializeElement(SemaRef
.Context
,
871 ElementType
= ILE
->getType();
873 bool SkipEmptyInitChecks
= false;
874 for (unsigned Init
= 0; Init
!= NumElements
; ++Init
) {
878 if (ElementEntity
.getKind() == InitializedEntity::EK_ArrayElement
||
879 ElementEntity
.getKind() == InitializedEntity::EK_VectorElement
)
880 ElementEntity
.setElementIndex(Init
);
882 if (Init
>= NumInits
&& (ILE
->hasArrayFiller() || SkipEmptyInitChecks
))
885 Expr
*InitExpr
= (Init
< NumInits
? ILE
->getInit(Init
) : nullptr);
886 if (!InitExpr
&& Init
< NumInits
&& ILE
->hasArrayFiller())
887 ILE
->setInit(Init
, ILE
->getArrayFiller());
888 else if (!InitExpr
&& !ILE
->hasArrayFiller()) {
889 // In VerifyOnly mode, there's no point performing empty initialization
891 if (SkipEmptyInitChecks
)
894 Expr
*Filler
= nullptr;
897 Filler
= new (SemaRef
.Context
) NoInitExpr(ElementType
);
899 ExprResult ElementInit
=
900 PerformEmptyInit(ILE
->getEndLoc(), ElementEntity
);
901 if (ElementInit
.isInvalid()) {
906 Filler
= ElementInit
.getAs
<Expr
>();
911 } else if (VerifyOnly
) {
912 SkipEmptyInitChecks
= true;
913 } else if (Init
< NumInits
) {
914 // For arrays, just set the expression used for value-initialization
915 // of the "holes" in the array.
916 if (ElementEntity
.getKind() == InitializedEntity::EK_ArrayElement
)
917 ILE
->setArrayFiller(Filler
);
919 ILE
->setInit(Init
, Filler
);
921 // For arrays, just set the expression used for value-initialization
922 // of the rest of elements and exit.
923 if (ElementEntity
.getKind() == InitializedEntity::EK_ArrayElement
) {
924 ILE
->setArrayFiller(Filler
);
928 if (!isa
<ImplicitValueInitExpr
>(Filler
) && !isa
<NoInitExpr
>(Filler
)) {
929 // Empty initialization requires a constructor call, so
930 // extend the initializer list to include the constructor
931 // call and make a note that we'll need to take another pass
932 // through the initializer list.
933 ILE
->updateInit(SemaRef
.Context
, Init
, Filler
);
934 RequiresSecondPass
= true;
937 } else if (InitListExpr
*InnerILE
938 = dyn_cast_or_null
<InitListExpr
>(InitExpr
)) {
939 FillInEmptyInitializations(ElementEntity
, InnerILE
, RequiresSecondPass
,
940 ILE
, Init
, FillWithNoInit
);
941 } else if (DesignatedInitUpdateExpr
*InnerDIUE
=
942 dyn_cast_or_null
<DesignatedInitUpdateExpr
>(InitExpr
)) {
943 FillInEmptyInitializations(ElementEntity
, InnerDIUE
->getUpdater(),
944 RequiresSecondPass
, ILE
, Init
,
945 /*FillWithNoInit =*/true);
950 static bool hasAnyDesignatedInits(const InitListExpr
*IL
) {
951 for (const Stmt
*Init
: *IL
)
952 if (isa_and_nonnull
<DesignatedInitExpr
>(Init
))
957 InitListChecker::InitListChecker(
958 Sema
&S
, const InitializedEntity
&Entity
, InitListExpr
*IL
, QualType
&T
,
959 bool VerifyOnly
, bool TreatUnavailableAsInvalid
, bool InOverloadResolution
,
960 SmallVectorImpl
<QualType
> *AggrDeductionCandidateParamTypes
)
961 : SemaRef(S
), VerifyOnly(VerifyOnly
),
962 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid
),
963 InOverloadResolution(InOverloadResolution
),
964 AggrDeductionCandidateParamTypes(AggrDeductionCandidateParamTypes
) {
965 if (!VerifyOnly
|| hasAnyDesignatedInits(IL
)) {
966 FullyStructuredList
=
967 createInitListExpr(T
, IL
->getSourceRange(), IL
->getNumInits());
969 // FIXME: Check that IL isn't already the semantic form of some other
970 // InitListExpr. If it is, we'd create a broken AST.
972 FullyStructuredList
->setSyntacticForm(IL
);
975 CheckExplicitInitList(Entity
, IL
, T
, FullyStructuredList
,
976 /*TopLevelObject=*/true);
978 if (!hadError
&& !AggrDeductionCandidateParamTypes
&& FullyStructuredList
) {
979 bool RequiresSecondPass
= false;
980 FillInEmptyInitializations(Entity
, FullyStructuredList
, RequiresSecondPass
,
981 /*OuterILE=*/nullptr, /*OuterIndex=*/0);
982 if (RequiresSecondPass
&& !hadError
)
983 FillInEmptyInitializations(Entity
, FullyStructuredList
,
984 RequiresSecondPass
, nullptr, 0);
986 if (hadError
&& FullyStructuredList
)
987 FullyStructuredList
->markError();
990 int InitListChecker::numArrayElements(QualType DeclType
) {
991 // FIXME: use a proper constant
992 int maxElements
= 0x7FFFFFFF;
993 if (const ConstantArrayType
*CAT
=
994 SemaRef
.Context
.getAsConstantArrayType(DeclType
)) {
995 maxElements
= static_cast<int>(CAT
->getSize().getZExtValue());
1000 int InitListChecker::numStructUnionElements(QualType DeclType
) {
1001 RecordDecl
*structDecl
= DeclType
->castAs
<RecordType
>()->getDecl();
1002 int InitializableMembers
= 0;
1003 if (auto *CXXRD
= dyn_cast
<CXXRecordDecl
>(structDecl
))
1004 InitializableMembers
+= CXXRD
->getNumBases();
1005 for (const auto *Field
: structDecl
->fields())
1006 if (!Field
->isUnnamedBitfield())
1007 ++InitializableMembers
;
1009 if (structDecl
->isUnion())
1010 return std::min(InitializableMembers
, 1);
1011 return InitializableMembers
- structDecl
->hasFlexibleArrayMember();
1014 RecordDecl
*InitListChecker::getRecordDecl(QualType DeclType
) {
1015 if (const auto *RT
= DeclType
->getAs
<RecordType
>())
1016 return RT
->getDecl();
1017 if (const auto *Inject
= DeclType
->getAs
<InjectedClassNameType
>())
1018 return Inject
->getDecl();
1022 /// Determine whether Entity is an entity for which it is idiomatic to elide
1023 /// the braces in aggregate initialization.
1024 static bool isIdiomaticBraceElisionEntity(const InitializedEntity
&Entity
) {
1025 // Recursive initialization of the one and only field within an aggregate
1026 // class is considered idiomatic. This case arises in particular for
1027 // initialization of std::array, where the C++ standard suggests the idiom of
1029 // std::array<T, N> arr = {1, 2, 3};
1031 // (where std::array is an aggregate struct containing a single array field.
1033 if (!Entity
.getParent())
1036 // Allows elide brace initialization for aggregates with empty base.
1037 if (Entity
.getKind() == InitializedEntity::EK_Base
) {
1039 Entity
.getParent()->getType()->castAs
<RecordType
>()->getDecl();
1040 CXXRecordDecl
*CXXRD
= cast
<CXXRecordDecl
>(ParentRD
);
1041 return CXXRD
->getNumBases() == 1 && CXXRD
->field_empty();
1044 // Allow brace elision if the only subobject is a field.
1045 if (Entity
.getKind() == InitializedEntity::EK_Member
) {
1047 Entity
.getParent()->getType()->castAs
<RecordType
>()->getDecl();
1048 if (CXXRecordDecl
*CXXRD
= dyn_cast
<CXXRecordDecl
>(ParentRD
)) {
1049 if (CXXRD
->getNumBases()) {
1053 auto FieldIt
= ParentRD
->field_begin();
1054 assert(FieldIt
!= ParentRD
->field_end() &&
1055 "no fields but have initializer for member?");
1056 return ++FieldIt
== ParentRD
->field_end();
1062 /// Check whether the range of the initializer \p ParentIList from element
1063 /// \p Index onwards can be used to initialize an object of type \p T. Update
1064 /// \p Index to indicate how many elements of the list were consumed.
1066 /// This also fills in \p StructuredList, from element \p StructuredIndex
1067 /// onwards, with the fully-braced, desugared form of the initialization.
1068 void InitListChecker::CheckImplicitInitList(const InitializedEntity
&Entity
,
1069 InitListExpr
*ParentIList
,
1070 QualType T
, unsigned &Index
,
1071 InitListExpr
*StructuredList
,
1072 unsigned &StructuredIndex
) {
1073 int maxElements
= 0;
1075 if (T
->isArrayType())
1076 maxElements
= numArrayElements(T
);
1077 else if (T
->isRecordType())
1078 maxElements
= numStructUnionElements(T
);
1079 else if (T
->isVectorType())
1080 maxElements
= T
->castAs
<VectorType
>()->getNumElements();
1082 llvm_unreachable("CheckImplicitInitList(): Illegal type");
1084 if (maxElements
== 0) {
1086 SemaRef
.Diag(ParentIList
->getInit(Index
)->getBeginLoc(),
1087 diag::err_implicit_empty_initializer
);
1093 // Build a structured initializer list corresponding to this subobject.
1094 InitListExpr
*StructuredSubobjectInitList
= getStructuredSubobjectInit(
1095 ParentIList
, Index
, T
, StructuredList
, StructuredIndex
,
1096 SourceRange(ParentIList
->getInit(Index
)->getBeginLoc(),
1097 ParentIList
->getSourceRange().getEnd()));
1098 unsigned StructuredSubobjectInitIndex
= 0;
1100 // Check the element types and build the structural subobject.
1101 unsigned StartIndex
= Index
;
1102 CheckListElementTypes(Entity
, ParentIList
, T
,
1103 /*SubobjectIsDesignatorContext=*/false, Index
,
1104 StructuredSubobjectInitList
,
1105 StructuredSubobjectInitIndex
);
1107 if (StructuredSubobjectInitList
) {
1108 StructuredSubobjectInitList
->setType(T
);
1110 unsigned EndIndex
= (Index
== StartIndex
? StartIndex
: Index
- 1);
1111 // Update the structured sub-object initializer so that it's ending
1112 // range corresponds with the end of the last initializer it used.
1113 if (EndIndex
< ParentIList
->getNumInits() &&
1114 ParentIList
->getInit(EndIndex
)) {
1115 SourceLocation EndLoc
1116 = ParentIList
->getInit(EndIndex
)->getSourceRange().getEnd();
1117 StructuredSubobjectInitList
->setRBraceLoc(EndLoc
);
1120 // Complain about missing braces.
1121 if (!VerifyOnly
&& (T
->isArrayType() || T
->isRecordType()) &&
1122 !ParentIList
->isIdiomaticZeroInitializer(SemaRef
.getLangOpts()) &&
1123 !isIdiomaticBraceElisionEntity(Entity
)) {
1124 SemaRef
.Diag(StructuredSubobjectInitList
->getBeginLoc(),
1125 diag::warn_missing_braces
)
1126 << StructuredSubobjectInitList
->getSourceRange()
1127 << FixItHint::CreateInsertion(
1128 StructuredSubobjectInitList
->getBeginLoc(), "{")
1129 << FixItHint::CreateInsertion(
1130 SemaRef
.getLocForEndOfToken(
1131 StructuredSubobjectInitList
->getEndLoc()),
1135 // Warn if this type won't be an aggregate in future versions of C++.
1136 auto *CXXRD
= T
->getAsCXXRecordDecl();
1137 if (!VerifyOnly
&& CXXRD
&& CXXRD
->hasUserDeclaredConstructor()) {
1138 SemaRef
.Diag(StructuredSubobjectInitList
->getBeginLoc(),
1139 diag::warn_cxx20_compat_aggregate_init_with_ctors
)
1140 << StructuredSubobjectInitList
->getSourceRange() << T
;
1145 /// Warn that \p Entity was of scalar type and was initialized by a
1146 /// single-element braced initializer list.
1147 static void warnBracedScalarInit(Sema
&S
, const InitializedEntity
&Entity
,
1148 SourceRange Braces
) {
1149 // Don't warn during template instantiation. If the initialization was
1150 // non-dependent, we warned during the initial parse; otherwise, the
1151 // type might not be scalar in some uses of the template.
1152 if (S
.inTemplateInstantiation())
1155 unsigned DiagID
= 0;
1157 switch (Entity
.getKind()) {
1158 case InitializedEntity::EK_VectorElement
:
1159 case InitializedEntity::EK_ComplexElement
:
1160 case InitializedEntity::EK_ArrayElement
:
1161 case InitializedEntity::EK_Parameter
:
1162 case InitializedEntity::EK_Parameter_CF_Audited
:
1163 case InitializedEntity::EK_TemplateParameter
:
1164 case InitializedEntity::EK_Result
:
1165 case InitializedEntity::EK_ParenAggInitMember
:
1166 // Extra braces here are suspicious.
1167 DiagID
= diag::warn_braces_around_init
;
1170 case InitializedEntity::EK_Member
:
1171 // Warn on aggregate initialization but not on ctor init list or
1172 // default member initializer.
1173 if (Entity
.getParent())
1174 DiagID
= diag::warn_braces_around_init
;
1177 case InitializedEntity::EK_Variable
:
1178 case InitializedEntity::EK_LambdaCapture
:
1179 // No warning, might be direct-list-initialization.
1180 // FIXME: Should we warn for copy-list-initialization in these cases?
1183 case InitializedEntity::EK_New
:
1184 case InitializedEntity::EK_Temporary
:
1185 case InitializedEntity::EK_CompoundLiteralInit
:
1186 // No warning, braces are part of the syntax of the underlying construct.
1189 case InitializedEntity::EK_RelatedResult
:
1190 // No warning, we already warned when initializing the result.
1193 case InitializedEntity::EK_Exception
:
1194 case InitializedEntity::EK_Base
:
1195 case InitializedEntity::EK_Delegating
:
1196 case InitializedEntity::EK_BlockElement
:
1197 case InitializedEntity::EK_LambdaToBlockConversionBlockElement
:
1198 case InitializedEntity::EK_Binding
:
1199 case InitializedEntity::EK_StmtExprResult
:
1200 llvm_unreachable("unexpected braced scalar init");
1204 S
.Diag(Braces
.getBegin(), DiagID
)
1205 << Entity
.getType()->isSizelessBuiltinType() << Braces
1206 << FixItHint::CreateRemoval(Braces
.getBegin())
1207 << FixItHint::CreateRemoval(Braces
.getEnd());
1211 /// Check whether the initializer \p IList (that was written with explicit
1212 /// braces) can be used to initialize an object of type \p T.
1214 /// This also fills in \p StructuredList with the fully-braced, desugared
1215 /// form of the initialization.
1216 void InitListChecker::CheckExplicitInitList(const InitializedEntity
&Entity
,
1217 InitListExpr
*IList
, QualType
&T
,
1218 InitListExpr
*StructuredList
,
1219 bool TopLevelObject
) {
1220 unsigned Index
= 0, StructuredIndex
= 0;
1221 CheckListElementTypes(Entity
, IList
, T
, /*SubobjectIsDesignatorContext=*/true,
1222 Index
, StructuredList
, StructuredIndex
, TopLevelObject
);
1223 if (StructuredList
) {
1224 QualType ExprTy
= T
;
1225 if (!ExprTy
->isArrayType())
1226 ExprTy
= ExprTy
.getNonLValueExprType(SemaRef
.Context
);
1228 IList
->setType(ExprTy
);
1229 StructuredList
->setType(ExprTy
);
1234 // Don't complain for incomplete types, since we'll get an error elsewhere.
1235 if (Index
< IList
->getNumInits() && !T
->isIncompleteType()) {
1236 // We have leftover initializers
1237 bool ExtraInitsIsError
= SemaRef
.getLangOpts().CPlusPlus
||
1238 (SemaRef
.getLangOpts().OpenCL
&& T
->isVectorType());
1239 hadError
= ExtraInitsIsError
;
1242 } else if (StructuredIndex
== 1 &&
1243 IsStringInit(StructuredList
->getInit(0), T
, SemaRef
.Context
) ==
1247 ? diag::err_excess_initializers_in_char_array_initializer
1248 : diag::ext_excess_initializers_in_char_array_initializer
;
1249 SemaRef
.Diag(IList
->getInit(Index
)->getBeginLoc(), DK
)
1250 << IList
->getInit(Index
)->getSourceRange();
1251 } else if (T
->isSizelessBuiltinType()) {
1252 unsigned DK
= ExtraInitsIsError
1253 ? diag::err_excess_initializers_for_sizeless_type
1254 : diag::ext_excess_initializers_for_sizeless_type
;
1255 SemaRef
.Diag(IList
->getInit(Index
)->getBeginLoc(), DK
)
1256 << T
<< IList
->getInit(Index
)->getSourceRange();
1258 int initKind
= T
->isArrayType() ? 0 :
1259 T
->isVectorType() ? 1 :
1260 T
->isScalarType() ? 2 :
1261 T
->isUnionType() ? 3 :
1264 unsigned DK
= ExtraInitsIsError
? diag::err_excess_initializers
1265 : diag::ext_excess_initializers
;
1266 SemaRef
.Diag(IList
->getInit(Index
)->getBeginLoc(), DK
)
1267 << initKind
<< IList
->getInit(Index
)->getSourceRange();
1272 if (T
->isScalarType() && IList
->getNumInits() == 1 &&
1273 !isa
<InitListExpr
>(IList
->getInit(0)))
1274 warnBracedScalarInit(SemaRef
, Entity
, IList
->getSourceRange());
1276 // Warn if this is a class type that won't be an aggregate in future
1278 auto *CXXRD
= T
->getAsCXXRecordDecl();
1279 if (CXXRD
&& CXXRD
->hasUserDeclaredConstructor()) {
1280 // Don't warn if there's an equivalent default constructor that would be
1282 bool HasEquivCtor
= false;
1283 if (IList
->getNumInits() == 0) {
1284 auto *CD
= SemaRef
.LookupDefaultConstructor(CXXRD
);
1285 HasEquivCtor
= CD
&& !CD
->isDeleted();
1288 if (!HasEquivCtor
) {
1289 SemaRef
.Diag(IList
->getBeginLoc(),
1290 diag::warn_cxx20_compat_aggregate_init_with_ctors
)
1291 << IList
->getSourceRange() << T
;
1297 void InitListChecker::CheckListElementTypes(const InitializedEntity
&Entity
,
1298 InitListExpr
*IList
,
1300 bool SubobjectIsDesignatorContext
,
1302 InitListExpr
*StructuredList
,
1303 unsigned &StructuredIndex
,
1304 bool TopLevelObject
) {
1305 if (DeclType
->isAnyComplexType() && SubobjectIsDesignatorContext
) {
1306 // Explicitly braced initializer for complex type can be real+imaginary
1308 CheckComplexType(Entity
, IList
, DeclType
, Index
,
1309 StructuredList
, StructuredIndex
);
1310 } else if (DeclType
->isScalarType()) {
1311 CheckScalarType(Entity
, IList
, DeclType
, Index
,
1312 StructuredList
, StructuredIndex
);
1313 } else if (DeclType
->isVectorType()) {
1314 CheckVectorType(Entity
, IList
, DeclType
, Index
,
1315 StructuredList
, StructuredIndex
);
1316 } else if (const RecordDecl
*RD
= getRecordDecl(DeclType
)) {
1318 CXXRecordDecl::base_class_const_range(CXXRecordDecl::base_class_const_iterator(),
1319 CXXRecordDecl::base_class_const_iterator());
1320 if (DeclType
->isRecordType()) {
1321 assert(DeclType
->isAggregateType() &&
1322 "non-aggregate records should be handed in CheckSubElementType");
1323 if (auto *CXXRD
= dyn_cast
<CXXRecordDecl
>(RD
))
1324 Bases
= CXXRD
->bases();
1326 Bases
= cast
<CXXRecordDecl
>(RD
)->bases();
1328 CheckStructUnionTypes(Entity
, IList
, DeclType
, Bases
, RD
->field_begin(),
1329 SubobjectIsDesignatorContext
, Index
, StructuredList
,
1330 StructuredIndex
, TopLevelObject
);
1331 } else if (DeclType
->isArrayType()) {
1333 SemaRef
.Context
.getTypeSize(SemaRef
.Context
.getSizeType()),
1335 CheckArrayType(Entity
, IList
, DeclType
, Zero
,
1336 SubobjectIsDesignatorContext
, Index
,
1337 StructuredList
, StructuredIndex
);
1338 } else if (DeclType
->isVoidType() || DeclType
->isFunctionType()) {
1339 // This type is invalid, issue a diagnostic.
1342 SemaRef
.Diag(IList
->getBeginLoc(), diag::err_illegal_initializer_type
)
1345 } else if (DeclType
->isReferenceType()) {
1346 CheckReferenceType(Entity
, IList
, DeclType
, Index
,
1347 StructuredList
, StructuredIndex
);
1348 } else if (DeclType
->isObjCObjectType()) {
1350 SemaRef
.Diag(IList
->getBeginLoc(), diag::err_init_objc_class
) << DeclType
;
1352 } else if (DeclType
->isOCLIntelSubgroupAVCType() ||
1353 DeclType
->isSizelessBuiltinType()) {
1354 // Checks for scalar type are sufficient for these types too.
1355 CheckScalarType(Entity
, IList
, DeclType
, Index
, StructuredList
,
1357 } else if (DeclType
->isDependentType()) {
1358 // C++ [over.match.class.deduct]p1.5:
1359 // brace elision is not considered for any aggregate element that has a
1360 // dependent non-array type or an array type with a value-dependent bound
1362 assert(AggrDeductionCandidateParamTypes
);
1363 AggrDeductionCandidateParamTypes
->push_back(DeclType
);
1366 SemaRef
.Diag(IList
->getBeginLoc(), diag::err_illegal_initializer_type
)
1372 void InitListChecker::CheckSubElementType(const InitializedEntity
&Entity
,
1373 InitListExpr
*IList
,
1376 InitListExpr
*StructuredList
,
1377 unsigned &StructuredIndex
,
1378 bool DirectlyDesignated
) {
1379 Expr
*expr
= IList
->getInit(Index
);
1381 if (ElemType
->isReferenceType())
1382 return CheckReferenceType(Entity
, IList
, ElemType
, Index
,
1383 StructuredList
, StructuredIndex
);
1385 if (InitListExpr
*SubInitList
= dyn_cast
<InitListExpr
>(expr
)) {
1386 if (SubInitList
->getNumInits() == 1 &&
1387 IsStringInit(SubInitList
->getInit(0), ElemType
, SemaRef
.Context
) ==
1389 // FIXME: It would be more faithful and no less correct to include an
1390 // InitListExpr in the semantic form of the initializer list in this case.
1391 expr
= SubInitList
->getInit(0);
1393 // Nested aggregate initialization and C++ initialization are handled later.
1394 } else if (isa
<ImplicitValueInitExpr
>(expr
)) {
1395 // This happens during template instantiation when we see an InitListExpr
1396 // that we've already checked once.
1397 assert(SemaRef
.Context
.hasSameType(expr
->getType(), ElemType
) &&
1398 "found implicit initialization for the wrong type");
1399 UpdateStructuredListElement(StructuredList
, StructuredIndex
, expr
);
1404 if (SemaRef
.getLangOpts().CPlusPlus
|| isa
<InitListExpr
>(expr
)) {
1405 // C++ [dcl.init.aggr]p2:
1406 // Each member is copy-initialized from the corresponding
1407 // initializer-clause.
1409 // FIXME: Better EqualLoc?
1410 InitializationKind Kind
=
1411 InitializationKind::CreateCopy(expr
->getBeginLoc(), SourceLocation());
1413 // Vector elements can be initialized from other vectors in which case
1414 // we need initialization entity with a type of a vector (and not a vector
1415 // element!) initializing multiple vector elements.
1417 (ElemType
->isExtVectorType() && !Entity
.getType()->isExtVectorType())
1418 ? InitializedEntity::InitializeTemporary(ElemType
)
1421 if (TmpEntity
.getType()->isDependentType()) {
1422 // C++ [over.match.class.deduct]p1.5:
1423 // brace elision is not considered for any aggregate element that has a
1424 // dependent non-array type or an array type with a value-dependent
1426 assert(AggrDeductionCandidateParamTypes
);
1427 if (!isa_and_nonnull
<ConstantArrayType
>(
1428 SemaRef
.Context
.getAsArrayType(ElemType
))) {
1430 AggrDeductionCandidateParamTypes
->push_back(ElemType
);
1434 InitializationSequence
Seq(SemaRef
, TmpEntity
, Kind
, expr
,
1435 /*TopLevelOfInitList*/ true);
1436 // C++14 [dcl.init.aggr]p13:
1437 // If the assignment-expression can initialize a member, the member is
1438 // initialized. Otherwise [...] brace elision is assumed
1440 // Brace elision is never performed if the element is not an
1441 // assignment-expression.
1442 if (Seq
|| isa
<InitListExpr
>(expr
)) {
1444 ExprResult Result
= Seq
.Perform(SemaRef
, TmpEntity
, Kind
, expr
);
1445 if (Result
.isInvalid())
1448 UpdateStructuredListElement(StructuredList
, StructuredIndex
,
1449 Result
.getAs
<Expr
>());
1452 } else if (StructuredList
) {
1453 UpdateStructuredListElement(StructuredList
, StructuredIndex
,
1457 if (AggrDeductionCandidateParamTypes
)
1458 AggrDeductionCandidateParamTypes
->push_back(ElemType
);
1463 // Fall through for subaggregate initialization
1464 } else if (ElemType
->isScalarType() || ElemType
->isAtomicType()) {
1465 // FIXME: Need to handle atomic aggregate types with implicit init lists.
1466 return CheckScalarType(Entity
, IList
, ElemType
, Index
,
1467 StructuredList
, StructuredIndex
);
1468 } else if (const ArrayType
*arrayType
=
1469 SemaRef
.Context
.getAsArrayType(ElemType
)) {
1470 // arrayType can be incomplete if we're initializing a flexible
1471 // array member. There's nothing we can do with the completed
1472 // type here, though.
1474 if (IsStringInit(expr
, arrayType
, SemaRef
.Context
) == SIF_None
) {
1475 // FIXME: Should we do this checking in verify-only mode?
1477 CheckStringInit(expr
, ElemType
, arrayType
, SemaRef
);
1479 UpdateStructuredListElement(StructuredList
, StructuredIndex
, expr
);
1484 // Fall through for subaggregate initialization.
1487 assert((ElemType
->isRecordType() || ElemType
->isVectorType() ||
1488 ElemType
->isOpenCLSpecificType()) && "Unexpected type");
1492 // The initializer for a structure or union object that has
1493 // automatic storage duration shall be either an initializer
1494 // list as described below, or a single expression that has
1495 // compatible structure or union type. In the latter case, the
1496 // initial value of the object, including unnamed members, is
1497 // that of the expression.
1498 ExprResult ExprRes
= expr
;
1499 if (SemaRef
.CheckSingleAssignmentConstraints(
1500 ElemType
, ExprRes
, !VerifyOnly
) != Sema::Incompatible
) {
1501 if (ExprRes
.isInvalid())
1504 ExprRes
= SemaRef
.DefaultFunctionArrayLvalueConversion(ExprRes
.get());
1505 if (ExprRes
.isInvalid())
1508 UpdateStructuredListElement(StructuredList
, StructuredIndex
,
1509 ExprRes
.getAs
<Expr
>());
1514 // Fall through for subaggregate initialization
1517 // C++ [dcl.init.aggr]p12:
1519 // [...] Otherwise, if the member is itself a non-empty
1520 // subaggregate, brace elision is assumed and the initializer is
1521 // considered for the initialization of the first member of
1522 // the subaggregate.
1523 // OpenCL vector initializer is handled elsewhere.
1524 if ((!SemaRef
.getLangOpts().OpenCL
&& ElemType
->isVectorType()) ||
1525 ElemType
->isAggregateType()) {
1526 CheckImplicitInitList(Entity
, IList
, ElemType
, Index
, StructuredList
,
1530 // In C++20, brace elision is not permitted for a designated initializer.
1531 if (DirectlyDesignated
&& SemaRef
.getLangOpts().CPlusPlus
&& !hadError
) {
1532 if (InOverloadResolution
)
1535 SemaRef
.Diag(expr
->getBeginLoc(),
1536 diag::ext_designated_init_brace_elision
)
1537 << expr
->getSourceRange()
1538 << FixItHint::CreateInsertion(expr
->getBeginLoc(), "{")
1539 << FixItHint::CreateInsertion(
1540 SemaRef
.getLocForEndOfToken(expr
->getEndLoc()), "}");
1545 // We cannot initialize this element, so let PerformCopyInitialization
1546 // produce the appropriate diagnostic. We already checked that this
1547 // initialization will fail.
1549 SemaRef
.PerformCopyInitialization(Entity
, SourceLocation(), expr
,
1550 /*TopLevelOfInitList=*/true);
1552 assert(Copy
.isInvalid() &&
1553 "expected non-aggregate initialization to fail");
1561 void InitListChecker::CheckComplexType(const InitializedEntity
&Entity
,
1562 InitListExpr
*IList
, QualType DeclType
,
1564 InitListExpr
*StructuredList
,
1565 unsigned &StructuredIndex
) {
1566 assert(Index
== 0 && "Index in explicit init list must be zero");
1568 // As an extension, clang supports complex initializers, which initialize
1569 // a complex number component-wise. When an explicit initializer list for
1570 // a complex number contains two initializers, this extension kicks in:
1571 // it expects the initializer list to contain two elements convertible to
1572 // the element type of the complex type. The first element initializes
1573 // the real part, and the second element intitializes the imaginary part.
1575 if (IList
->getNumInits() < 2)
1576 return CheckScalarType(Entity
, IList
, DeclType
, Index
, StructuredList
,
1579 // This is an extension in C. (The builtin _Complex type does not exist
1580 // in the C++ standard.)
1581 if (!SemaRef
.getLangOpts().CPlusPlus
&& !VerifyOnly
)
1582 SemaRef
.Diag(IList
->getBeginLoc(), diag::ext_complex_component_init
)
1583 << IList
->getSourceRange();
1585 // Initialize the complex number.
1586 QualType elementType
= DeclType
->castAs
<ComplexType
>()->getElementType();
1587 InitializedEntity ElementEntity
=
1588 InitializedEntity::InitializeElement(SemaRef
.Context
, 0, Entity
);
1590 for (unsigned i
= 0; i
< 2; ++i
) {
1591 ElementEntity
.setElementIndex(Index
);
1592 CheckSubElementType(ElementEntity
, IList
, elementType
, Index
,
1593 StructuredList
, StructuredIndex
);
1597 void InitListChecker::CheckScalarType(const InitializedEntity
&Entity
,
1598 InitListExpr
*IList
, QualType DeclType
,
1600 InitListExpr
*StructuredList
,
1601 unsigned &StructuredIndex
) {
1602 if (Index
>= IList
->getNumInits()) {
1604 if (SemaRef
.getLangOpts().CPlusPlus
) {
1605 if (DeclType
->isSizelessBuiltinType())
1606 SemaRef
.Diag(IList
->getBeginLoc(),
1607 SemaRef
.getLangOpts().CPlusPlus11
1608 ? diag::warn_cxx98_compat_empty_sizeless_initializer
1609 : diag::err_empty_sizeless_initializer
)
1610 << DeclType
<< IList
->getSourceRange();
1612 SemaRef
.Diag(IList
->getBeginLoc(),
1613 SemaRef
.getLangOpts().CPlusPlus11
1614 ? diag::warn_cxx98_compat_empty_scalar_initializer
1615 : diag::err_empty_scalar_initializer
)
1616 << IList
->getSourceRange();
1620 SemaRef
.getLangOpts().CPlusPlus
&& !SemaRef
.getLangOpts().CPlusPlus11
;
1626 Expr
*expr
= IList
->getInit(Index
);
1627 if (InitListExpr
*SubIList
= dyn_cast
<InitListExpr
>(expr
)) {
1628 // FIXME: This is invalid, and accepting it causes overload resolution
1629 // to pick the wrong overload in some corner cases.
1631 SemaRef
.Diag(SubIList
->getBeginLoc(), diag::ext_many_braces_around_init
)
1632 << DeclType
->isSizelessBuiltinType() << SubIList
->getSourceRange();
1634 CheckScalarType(Entity
, SubIList
, DeclType
, Index
, StructuredList
,
1637 } else if (isa
<DesignatedInitExpr
>(expr
)) {
1639 SemaRef
.Diag(expr
->getBeginLoc(),
1640 diag::err_designator_for_scalar_or_sizeless_init
)
1641 << DeclType
->isSizelessBuiltinType() << DeclType
1642 << expr
->getSourceRange();
1651 if (SemaRef
.CanPerformCopyInitialization(Entity
, expr
))
1652 Result
= getDummyInit();
1654 Result
= ExprError();
1657 SemaRef
.PerformCopyInitialization(Entity
, expr
->getBeginLoc(), expr
,
1658 /*TopLevelOfInitList=*/true);
1661 Expr
*ResultExpr
= nullptr;
1663 if (Result
.isInvalid())
1664 hadError
= true; // types weren't compatible.
1666 ResultExpr
= Result
.getAs
<Expr
>();
1668 if (ResultExpr
!= expr
&& !VerifyOnly
) {
1669 // The type was promoted, update initializer list.
1670 // FIXME: Why are we updating the syntactic init list?
1671 IList
->setInit(Index
, ResultExpr
);
1674 UpdateStructuredListElement(StructuredList
, StructuredIndex
, ResultExpr
);
1676 if (AggrDeductionCandidateParamTypes
)
1677 AggrDeductionCandidateParamTypes
->push_back(DeclType
);
1680 void InitListChecker::CheckReferenceType(const InitializedEntity
&Entity
,
1681 InitListExpr
*IList
, QualType DeclType
,
1683 InitListExpr
*StructuredList
,
1684 unsigned &StructuredIndex
) {
1685 if (Index
>= IList
->getNumInits()) {
1686 // FIXME: It would be wonderful if we could point at the actual member. In
1687 // general, it would be useful to pass location information down the stack,
1688 // so that we know the location (or decl) of the "current object" being
1691 SemaRef
.Diag(IList
->getBeginLoc(),
1692 diag::err_init_reference_member_uninitialized
)
1693 << DeclType
<< IList
->getSourceRange();
1700 Expr
*expr
= IList
->getInit(Index
);
1701 if (isa
<InitListExpr
>(expr
) && !SemaRef
.getLangOpts().CPlusPlus11
) {
1703 SemaRef
.Diag(IList
->getBeginLoc(), diag::err_init_non_aggr_init_list
)
1704 << DeclType
<< IList
->getSourceRange();
1713 if (SemaRef
.CanPerformCopyInitialization(Entity
,expr
))
1714 Result
= getDummyInit();
1716 Result
= ExprError();
1719 SemaRef
.PerformCopyInitialization(Entity
, expr
->getBeginLoc(), expr
,
1720 /*TopLevelOfInitList=*/true);
1723 if (Result
.isInvalid())
1726 expr
= Result
.getAs
<Expr
>();
1727 // FIXME: Why are we updating the syntactic init list?
1728 if (!VerifyOnly
&& expr
)
1729 IList
->setInit(Index
, expr
);
1731 UpdateStructuredListElement(StructuredList
, StructuredIndex
, expr
);
1733 if (AggrDeductionCandidateParamTypes
)
1734 AggrDeductionCandidateParamTypes
->push_back(DeclType
);
1737 void InitListChecker::CheckVectorType(const InitializedEntity
&Entity
,
1738 InitListExpr
*IList
, QualType DeclType
,
1740 InitListExpr
*StructuredList
,
1741 unsigned &StructuredIndex
) {
1742 const VectorType
*VT
= DeclType
->castAs
<VectorType
>();
1743 unsigned maxElements
= VT
->getNumElements();
1744 unsigned numEltsInit
= 0;
1745 QualType elementType
= VT
->getElementType();
1747 if (Index
>= IList
->getNumInits()) {
1748 // Make sure the element type can be value-initialized.
1749 CheckEmptyInitializable(
1750 InitializedEntity::InitializeElement(SemaRef
.Context
, 0, Entity
),
1751 IList
->getEndLoc());
1755 if (!SemaRef
.getLangOpts().OpenCL
&& !SemaRef
.getLangOpts().HLSL
) {
1756 // If the initializing element is a vector, try to copy-initialize
1757 // instead of breaking it apart (which is doomed to failure anyway).
1758 Expr
*Init
= IList
->getInit(Index
);
1759 if (!isa
<InitListExpr
>(Init
) && Init
->getType()->isVectorType()) {
1762 if (SemaRef
.CanPerformCopyInitialization(Entity
, Init
))
1763 Result
= getDummyInit();
1765 Result
= ExprError();
1768 SemaRef
.PerformCopyInitialization(Entity
, Init
->getBeginLoc(), Init
,
1769 /*TopLevelOfInitList=*/true);
1772 Expr
*ResultExpr
= nullptr;
1773 if (Result
.isInvalid())
1774 hadError
= true; // types weren't compatible.
1776 ResultExpr
= Result
.getAs
<Expr
>();
1778 if (ResultExpr
!= Init
&& !VerifyOnly
) {
1779 // The type was promoted, update initializer list.
1780 // FIXME: Why are we updating the syntactic init list?
1781 IList
->setInit(Index
, ResultExpr
);
1784 UpdateStructuredListElement(StructuredList
, StructuredIndex
, ResultExpr
);
1786 if (AggrDeductionCandidateParamTypes
)
1787 AggrDeductionCandidateParamTypes
->push_back(elementType
);
1791 InitializedEntity ElementEntity
=
1792 InitializedEntity::InitializeElement(SemaRef
.Context
, 0, Entity
);
1794 for (unsigned i
= 0; i
< maxElements
; ++i
, ++numEltsInit
) {
1795 // Don't attempt to go past the end of the init list
1796 if (Index
>= IList
->getNumInits()) {
1797 CheckEmptyInitializable(ElementEntity
, IList
->getEndLoc());
1801 ElementEntity
.setElementIndex(Index
);
1802 CheckSubElementType(ElementEntity
, IList
, elementType
, Index
,
1803 StructuredList
, StructuredIndex
);
1809 bool isBigEndian
= SemaRef
.Context
.getTargetInfo().isBigEndian();
1810 const VectorType
*T
= Entity
.getType()->castAs
<VectorType
>();
1811 if (isBigEndian
&& (T
->getVectorKind() == VectorKind::Neon
||
1812 T
->getVectorKind() == VectorKind::NeonPoly
)) {
1813 // The ability to use vector initializer lists is a GNU vector extension
1814 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1815 // endian machines it works fine, however on big endian machines it
1816 // exhibits surprising behaviour:
1818 // uint32x2_t x = {42, 64};
1819 // return vget_lane_u32(x, 0); // Will return 64.
1821 // Because of this, explicitly call out that it is non-portable.
1823 SemaRef
.Diag(IList
->getBeginLoc(),
1824 diag::warn_neon_vector_initializer_non_portable
);
1826 const char *typeCode
;
1827 unsigned typeSize
= SemaRef
.Context
.getTypeSize(elementType
);
1829 if (elementType
->isFloatingType())
1831 else if (elementType
->isSignedIntegerType())
1833 else if (elementType
->isUnsignedIntegerType())
1836 llvm_unreachable("Invalid element type!");
1838 SemaRef
.Diag(IList
->getBeginLoc(),
1839 SemaRef
.Context
.getTypeSize(VT
) > 64
1840 ? diag::note_neon_vector_initializer_non_portable_q
1841 : diag::note_neon_vector_initializer_non_portable
)
1842 << typeCode
<< typeSize
;
1848 InitializedEntity ElementEntity
=
1849 InitializedEntity::InitializeElement(SemaRef
.Context
, 0, Entity
);
1851 // OpenCL and HLSL initializers allow vectors to be constructed from vectors.
1852 for (unsigned i
= 0; i
< maxElements
; ++i
) {
1853 // Don't attempt to go past the end of the init list
1854 if (Index
>= IList
->getNumInits())
1857 ElementEntity
.setElementIndex(Index
);
1859 QualType IType
= IList
->getInit(Index
)->getType();
1860 if (!IType
->isVectorType()) {
1861 CheckSubElementType(ElementEntity
, IList
, elementType
, Index
,
1862 StructuredList
, StructuredIndex
);
1866 const VectorType
*IVT
= IType
->castAs
<VectorType
>();
1867 unsigned numIElts
= IVT
->getNumElements();
1869 if (IType
->isExtVectorType())
1870 VecType
= SemaRef
.Context
.getExtVectorType(elementType
, numIElts
);
1872 VecType
= SemaRef
.Context
.getVectorType(elementType
, numIElts
,
1873 IVT
->getVectorKind());
1874 CheckSubElementType(ElementEntity
, IList
, VecType
, Index
,
1875 StructuredList
, StructuredIndex
);
1876 numEltsInit
+= numIElts
;
1880 // OpenCL and HLSL require all elements to be initialized.
1881 if (numEltsInit
!= maxElements
) {
1883 SemaRef
.Diag(IList
->getBeginLoc(),
1884 diag::err_vector_incorrect_num_initializers
)
1885 << (numEltsInit
< maxElements
) << maxElements
<< numEltsInit
;
1890 /// Check if the type of a class element has an accessible destructor, and marks
1891 /// it referenced. Returns true if we shouldn't form a reference to the
1894 /// Aggregate initialization requires a class element's destructor be
1895 /// accessible per 11.6.1 [dcl.init.aggr]:
1897 /// The destructor for each element of class type is potentially invoked
1898 /// (15.4 [class.dtor]) from the context where the aggregate initialization
1900 static bool checkDestructorReference(QualType ElementType
, SourceLocation Loc
,
1902 auto *CXXRD
= ElementType
->getAsCXXRecordDecl();
1906 CXXDestructorDecl
*Destructor
= SemaRef
.LookupDestructor(CXXRD
);
1907 SemaRef
.CheckDestructorAccess(Loc
, Destructor
,
1908 SemaRef
.PDiag(diag::err_access_dtor_temp
)
1910 SemaRef
.MarkFunctionReferenced(Loc
, Destructor
);
1911 return SemaRef
.DiagnoseUseOfDecl(Destructor
, Loc
);
1914 void InitListChecker::CheckArrayType(const InitializedEntity
&Entity
,
1915 InitListExpr
*IList
, QualType
&DeclType
,
1916 llvm::APSInt elementIndex
,
1917 bool SubobjectIsDesignatorContext
,
1919 InitListExpr
*StructuredList
,
1920 unsigned &StructuredIndex
) {
1921 const ArrayType
*arrayType
= SemaRef
.Context
.getAsArrayType(DeclType
);
1924 if (checkDestructorReference(arrayType
->getElementType(),
1925 IList
->getEndLoc(), SemaRef
)) {
1931 // Check for the special-case of initializing an array with a string.
1932 if (Index
< IList
->getNumInits()) {
1933 if (IsStringInit(IList
->getInit(Index
), arrayType
, SemaRef
.Context
) ==
1935 // We place the string literal directly into the resulting
1936 // initializer list. This is the only place where the structure
1937 // of the structured initializer list doesn't match exactly,
1938 // because doing so would involve allocating one character
1939 // constant for each string.
1940 // FIXME: Should we do these checks in verify-only mode too?
1942 CheckStringInit(IList
->getInit(Index
), DeclType
, arrayType
, SemaRef
);
1943 if (StructuredList
) {
1944 UpdateStructuredListElement(StructuredList
, StructuredIndex
,
1945 IList
->getInit(Index
));
1946 StructuredList
->resizeInits(SemaRef
.Context
, StructuredIndex
);
1949 if (AggrDeductionCandidateParamTypes
)
1950 AggrDeductionCandidateParamTypes
->push_back(DeclType
);
1954 if (const VariableArrayType
*VAT
= dyn_cast
<VariableArrayType
>(arrayType
)) {
1955 // Check for VLAs; in standard C it would be possible to check this
1956 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1957 // them in all sorts of strange places).
1958 bool HasErr
= IList
->getNumInits() != 0 || SemaRef
.getLangOpts().CPlusPlus
;
1960 // C23 6.7.10p4: An entity of variable length array type shall not be
1961 // initialized except by an empty initializer.
1963 // The C extension warnings are issued from ParseBraceInitializer() and
1964 // do not need to be issued here. However, we continue to issue an error
1965 // in the case there are initializers or we are compiling C++. We allow
1966 // use of VLAs in C++, but it's not clear we want to allow {} to zero
1967 // init a VLA in C++ in all cases (such as with non-trivial constructors).
1968 // FIXME: should we allow this construct in C++ when it makes sense to do
1971 SemaRef
.Diag(VAT
->getSizeExpr()->getBeginLoc(),
1972 diag::err_variable_object_no_init
)
1973 << VAT
->getSizeExpr()->getSourceRange();
1981 // We might know the maximum number of elements in advance.
1982 llvm::APSInt
maxElements(elementIndex
.getBitWidth(),
1983 elementIndex
.isUnsigned());
1984 bool maxElementsKnown
= false;
1985 if (const ConstantArrayType
*CAT
= dyn_cast
<ConstantArrayType
>(arrayType
)) {
1986 maxElements
= CAT
->getSize();
1987 elementIndex
= elementIndex
.extOrTrunc(maxElements
.getBitWidth());
1988 elementIndex
.setIsUnsigned(maxElements
.isUnsigned());
1989 maxElementsKnown
= true;
1992 QualType elementType
= arrayType
->getElementType();
1993 while (Index
< IList
->getNumInits()) {
1994 Expr
*Init
= IList
->getInit(Index
);
1995 if (DesignatedInitExpr
*DIE
= dyn_cast
<DesignatedInitExpr
>(Init
)) {
1996 // If we're not the subobject that matches up with the '{' for
1997 // the designator, we shouldn't be handling the
1998 // designator. Return immediately.
1999 if (!SubobjectIsDesignatorContext
)
2002 // Handle this designated initializer. elementIndex will be
2003 // updated to be the next array element we'll initialize.
2004 if (CheckDesignatedInitializer(Entity
, IList
, DIE
, 0,
2005 DeclType
, nullptr, &elementIndex
, Index
,
2006 StructuredList
, StructuredIndex
, true,
2012 if (elementIndex
.getBitWidth() > maxElements
.getBitWidth())
2013 maxElements
= maxElements
.extend(elementIndex
.getBitWidth());
2014 else if (elementIndex
.getBitWidth() < maxElements
.getBitWidth())
2015 elementIndex
= elementIndex
.extend(maxElements
.getBitWidth());
2016 elementIndex
.setIsUnsigned(maxElements
.isUnsigned());
2018 // If the array is of incomplete type, keep track of the number of
2019 // elements in the initializer.
2020 if (!maxElementsKnown
&& elementIndex
> maxElements
)
2021 maxElements
= elementIndex
;
2026 // If we know the maximum number of elements, and we've already
2027 // hit it, stop consuming elements in the initializer list.
2028 if (maxElementsKnown
&& elementIndex
== maxElements
)
2031 InitializedEntity ElementEntity
=
2032 InitializedEntity::InitializeElement(SemaRef
.Context
, StructuredIndex
,
2034 // Check this element.
2035 CheckSubElementType(ElementEntity
, IList
, elementType
, Index
,
2036 StructuredList
, StructuredIndex
);
2039 // If the array is of incomplete type, keep track of the number of
2040 // elements in the initializer.
2041 if (!maxElementsKnown
&& elementIndex
> maxElements
)
2042 maxElements
= elementIndex
;
2044 if (!hadError
&& DeclType
->isIncompleteArrayType() && !VerifyOnly
) {
2045 // If this is an incomplete array type, the actual type needs to
2046 // be calculated here.
2047 llvm::APSInt
Zero(maxElements
.getBitWidth(), maxElements
.isUnsigned());
2048 if (maxElements
== Zero
&& !Entity
.isVariableLengthArrayNew()) {
2049 // Sizing an array implicitly to zero is not allowed by ISO C,
2050 // but is supported by GNU.
2051 SemaRef
.Diag(IList
->getBeginLoc(), diag::ext_typecheck_zero_array_size
);
2054 DeclType
= SemaRef
.Context
.getConstantArrayType(
2055 elementType
, maxElements
, nullptr, ArraySizeModifier::Normal
, 0);
2058 // If there are any members of the array that get value-initialized, check
2059 // that is possible. That happens if we know the bound and don't have
2060 // enough elements, or if we're performing an array new with an unknown
2062 if ((maxElementsKnown
&& elementIndex
< maxElements
) ||
2063 Entity
.isVariableLengthArrayNew())
2064 CheckEmptyInitializable(
2065 InitializedEntity::InitializeElement(SemaRef
.Context
, 0, Entity
),
2066 IList
->getEndLoc());
2070 bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity
&Entity
,
2073 bool TopLevelObject
) {
2074 // Handle GNU flexible array initializers.
2075 unsigned FlexArrayDiag
;
2076 if (isa
<InitListExpr
>(InitExpr
) &&
2077 cast
<InitListExpr
>(InitExpr
)->getNumInits() == 0) {
2078 // Empty flexible array init always allowed as an extension
2079 FlexArrayDiag
= diag::ext_flexible_array_init
;
2080 } else if (!TopLevelObject
) {
2081 // Disallow flexible array init on non-top-level object
2082 FlexArrayDiag
= diag::err_flexible_array_init
;
2083 } else if (Entity
.getKind() != InitializedEntity::EK_Variable
) {
2084 // Disallow flexible array init on anything which is not a variable.
2085 FlexArrayDiag
= diag::err_flexible_array_init
;
2086 } else if (cast
<VarDecl
>(Entity
.getDecl())->hasLocalStorage()) {
2087 // Disallow flexible array init on local variables.
2088 FlexArrayDiag
= diag::err_flexible_array_init
;
2090 // Allow other cases.
2091 FlexArrayDiag
= diag::ext_flexible_array_init
;
2095 SemaRef
.Diag(InitExpr
->getBeginLoc(), FlexArrayDiag
)
2096 << InitExpr
->getBeginLoc();
2097 SemaRef
.Diag(Field
->getLocation(), diag::note_flexible_array_member
)
2101 return FlexArrayDiag
!= diag::ext_flexible_array_init
;
2104 void InitListChecker::CheckStructUnionTypes(
2105 const InitializedEntity
&Entity
, InitListExpr
*IList
, QualType DeclType
,
2106 CXXRecordDecl::base_class_const_range Bases
, RecordDecl::field_iterator Field
,
2107 bool SubobjectIsDesignatorContext
, unsigned &Index
,
2108 InitListExpr
*StructuredList
, unsigned &StructuredIndex
,
2109 bool TopLevelObject
) {
2110 const RecordDecl
*RD
= getRecordDecl(DeclType
);
2112 // If the record is invalid, some of it's members are invalid. To avoid
2113 // confusion, we forgo checking the initializer for the entire record.
2114 if (RD
->isInvalidDecl()) {
2115 // Assume it was supposed to consume a single initializer.
2121 if (RD
->isUnion() && IList
->getNumInits() == 0) {
2123 for (FieldDecl
*FD
: RD
->fields()) {
2124 QualType ET
= SemaRef
.Context
.getBaseElementType(FD
->getType());
2125 if (checkDestructorReference(ET
, IList
->getEndLoc(), SemaRef
)) {
2131 // If there's a default initializer, use it.
2132 if (isa
<CXXRecordDecl
>(RD
) &&
2133 cast
<CXXRecordDecl
>(RD
)->hasInClassInitializer()) {
2134 if (!StructuredList
)
2136 for (RecordDecl::field_iterator FieldEnd
= RD
->field_end();
2137 Field
!= FieldEnd
; ++Field
) {
2138 if (Field
->hasInClassInitializer()) {
2139 StructuredList
->setInitializedFieldInUnion(*Field
);
2140 // FIXME: Actually build a CXXDefaultInitExpr?
2146 // Value-initialize the first member of the union that isn't an unnamed
2148 for (RecordDecl::field_iterator FieldEnd
= RD
->field_end();
2149 Field
!= FieldEnd
; ++Field
) {
2150 if (!Field
->isUnnamedBitfield()) {
2151 CheckEmptyInitializable(
2152 InitializedEntity::InitializeMember(*Field
, &Entity
),
2153 IList
->getEndLoc());
2155 StructuredList
->setInitializedFieldInUnion(*Field
);
2162 bool InitializedSomething
= false;
2164 // If we have any base classes, they are initialized prior to the fields.
2165 for (auto I
= Bases
.begin(), E
= Bases
.end(); I
!= E
; ++I
) {
2167 Expr
*Init
= Index
< IList
->getNumInits() ? IList
->getInit(Index
) : nullptr;
2169 // Designated inits always initialize fields, so if we see one, all
2170 // remaining base classes have no explicit initializer.
2171 if (Init
&& isa
<DesignatedInitExpr
>(Init
))
2174 // C++ [over.match.class.deduct]p1.6:
2175 // each non-trailing aggregate element that is a pack expansion is assumed
2176 // to correspond to no elements of the initializer list, and (1.7) a
2177 // trailing aggregate element that is a pack expansion is assumed to
2178 // correspond to all remaining elements of the initializer list (if any).
2180 // C++ [over.match.class.deduct]p1.9:
2181 // ... except that additional parameter packs of the form P_j... are
2182 // inserted into the parameter list in their original aggregate element
2183 // position corresponding to each non-trailing aggregate element of
2184 // type P_j that was skipped because it was a parameter pack, and the
2185 // trailing sequence of parameters corresponding to a trailing
2186 // aggregate element that is a pack expansion (if any) is replaced
2187 // by a single parameter of the form T_n....
2188 if (AggrDeductionCandidateParamTypes
&& Base
.isPackExpansion()) {
2189 AggrDeductionCandidateParamTypes
->push_back(
2190 SemaRef
.Context
.getPackExpansionType(Base
.getType(), std::nullopt
));
2192 // Trailing pack expansion
2193 if (I
+ 1 == E
&& RD
->field_empty()) {
2194 if (Index
< IList
->getNumInits())
2195 Index
= IList
->getNumInits();
2202 SourceLocation InitLoc
= Init
? Init
->getBeginLoc() : IList
->getEndLoc();
2203 InitializedEntity BaseEntity
= InitializedEntity::InitializeBase(
2204 SemaRef
.Context
, &Base
, false, &Entity
);
2206 CheckSubElementType(BaseEntity
, IList
, Base
.getType(), Index
,
2207 StructuredList
, StructuredIndex
);
2208 InitializedSomething
= true;
2210 CheckEmptyInitializable(BaseEntity
, InitLoc
);
2214 if (checkDestructorReference(Base
.getType(), InitLoc
, SemaRef
)) {
2220 // If structDecl is a forward declaration, this loop won't do
2221 // anything except look at designated initializers; That's okay,
2222 // because an error should get printed out elsewhere. It might be
2223 // worthwhile to skip over the rest of the initializer, though.
2224 RecordDecl::field_iterator FieldEnd
= RD
->field_end();
2225 size_t NumRecordDecls
= llvm::count_if(RD
->decls(), [&](const Decl
*D
) {
2226 return isa
<FieldDecl
>(D
) || isa
<RecordDecl
>(D
);
2228 bool CheckForMissingFields
=
2229 !IList
->isIdiomaticZeroInitializer(SemaRef
.getLangOpts());
2230 bool HasDesignatedInit
= false;
2232 llvm::SmallPtrSet
<FieldDecl
*, 4> InitializedFields
;
2234 while (Index
< IList
->getNumInits()) {
2235 Expr
*Init
= IList
->getInit(Index
);
2236 SourceLocation InitLoc
= Init
->getBeginLoc();
2238 if (DesignatedInitExpr
*DIE
= dyn_cast
<DesignatedInitExpr
>(Init
)) {
2239 // If we're not the subobject that matches up with the '{' for
2240 // the designator, we shouldn't be handling the
2241 // designator. Return immediately.
2242 if (!SubobjectIsDesignatorContext
)
2245 HasDesignatedInit
= true;
2247 // Handle this designated initializer. Field will be updated to
2248 // the next field that we'll be initializing.
2249 bool DesignatedInitFailed
= CheckDesignatedInitializer(
2250 Entity
, IList
, DIE
, 0, DeclType
, &Field
, nullptr, Index
,
2251 StructuredList
, StructuredIndex
, true, TopLevelObject
);
2252 if (DesignatedInitFailed
)
2255 // Find the field named by the designated initializer.
2256 DesignatedInitExpr::Designator
*D
= DIE
->getDesignator(0);
2257 if (!VerifyOnly
&& D
->isFieldDesignator()) {
2258 FieldDecl
*F
= D
->getFieldDecl();
2259 InitializedFields
.insert(F
);
2260 if (!DesignatedInitFailed
) {
2261 QualType ET
= SemaRef
.Context
.getBaseElementType(F
->getType());
2262 if (checkDestructorReference(ET
, InitLoc
, SemaRef
)) {
2269 InitializedSomething
= true;
2271 // Disable check for missing fields when designators are used.
2272 // This matches gcc behaviour.
2273 if (!SemaRef
.getLangOpts().CPlusPlus
)
2274 CheckForMissingFields
= false;
2278 // Check if this is an initializer of forms:
2280 // struct foo f = {};
2281 // struct foo g = {0};
2283 // These are okay for randomized structures. [C99 6.7.8p19]
2285 // Also, if there is only one element in the structure, we allow something
2286 // like this, because it's really not randomized in the tranditional sense.
2288 // struct foo h = {bar};
2289 auto IsZeroInitializer
= [&](const Expr
*I
) {
2290 if (IList
->getNumInits() == 1) {
2291 if (NumRecordDecls
== 1)
2293 if (const auto *IL
= dyn_cast
<IntegerLiteral
>(I
))
2294 return IL
->getValue().isZero();
2299 // Don't allow non-designated initializers on randomized structures.
2300 if (RD
->isRandomized() && !IsZeroInitializer(Init
)) {
2302 SemaRef
.Diag(InitLoc
, diag::err_non_designated_init_used
);
2307 if (Field
== FieldEnd
) {
2308 // We've run out of fields. We're done.
2312 // We've already initialized a member of a union. We're done.
2313 if (InitializedSomething
&& RD
->isUnion())
2316 // If we've hit the flexible array member at the end, we're done.
2317 if (Field
->getType()->isIncompleteArrayType())
2320 if (Field
->isUnnamedBitfield()) {
2321 // Don't initialize unnamed bitfields, e.g. "int : 20;"
2326 // Make sure we can use this declaration.
2329 InvalidUse
= !SemaRef
.CanUseDecl(*Field
, TreatUnavailableAsInvalid
);
2331 InvalidUse
= SemaRef
.DiagnoseUseOfDecl(
2332 *Field
, IList
->getInit(Index
)->getBeginLoc());
2341 QualType ET
= SemaRef
.Context
.getBaseElementType(Field
->getType());
2342 if (checkDestructorReference(ET
, InitLoc
, SemaRef
)) {
2348 InitializedEntity MemberEntity
=
2349 InitializedEntity::InitializeMember(*Field
, &Entity
);
2350 CheckSubElementType(MemberEntity
, IList
, Field
->getType(), Index
,
2351 StructuredList
, StructuredIndex
);
2352 InitializedSomething
= true;
2353 InitializedFields
.insert(*Field
);
2355 if (RD
->isUnion() && StructuredList
) {
2356 // Initialize the first field within the union.
2357 StructuredList
->setInitializedFieldInUnion(*Field
);
2363 // Emit warnings for missing struct field initializers.
2364 if (!VerifyOnly
&& InitializedSomething
&& CheckForMissingFields
&&
2366 // It is possible we have one or more unnamed bitfields remaining.
2367 // Find first (if any) named field and emit warning.
2368 for (RecordDecl::field_iterator it
= HasDesignatedInit
? RD
->field_begin()
2370 end
= RD
->field_end();
2372 if (HasDesignatedInit
&& InitializedFields
.count(*it
))
2375 if (!it
->isUnnamedBitfield() && !it
->hasInClassInitializer() &&
2376 !it
->getType()->isIncompleteArrayType()) {
2377 SemaRef
.Diag(IList
->getSourceRange().getEnd(),
2378 diag::warn_missing_field_initializers
)
2385 // Check that any remaining fields can be value-initialized if we're not
2386 // building a structured list. (If we are, we'll check this later.)
2387 if (!StructuredList
&& Field
!= FieldEnd
&& !RD
->isUnion() &&
2388 !Field
->getType()->isIncompleteArrayType()) {
2389 for (; Field
!= FieldEnd
&& !hadError
; ++Field
) {
2390 if (!Field
->isUnnamedBitfield() && !Field
->hasInClassInitializer())
2391 CheckEmptyInitializable(
2392 InitializedEntity::InitializeMember(*Field
, &Entity
),
2393 IList
->getEndLoc());
2397 // Check that the types of the remaining fields have accessible destructors.
2399 // If the initializer expression has a designated initializer, check the
2400 // elements for which a designated initializer is not provided too.
2401 RecordDecl::field_iterator I
= HasDesignatedInit
? RD
->field_begin()
2403 for (RecordDecl::field_iterator E
= RD
->field_end(); I
!= E
; ++I
) {
2404 QualType ET
= SemaRef
.Context
.getBaseElementType(I
->getType());
2405 if (checkDestructorReference(ET
, IList
->getEndLoc(), SemaRef
)) {
2412 if (Field
== FieldEnd
|| !Field
->getType()->isIncompleteArrayType() ||
2413 Index
>= IList
->getNumInits())
2416 if (CheckFlexibleArrayInit(Entity
, IList
->getInit(Index
), *Field
,
2423 InitializedEntity MemberEntity
=
2424 InitializedEntity::InitializeMember(*Field
, &Entity
);
2426 if (isa
<InitListExpr
>(IList
->getInit(Index
)) ||
2427 AggrDeductionCandidateParamTypes
)
2428 CheckSubElementType(MemberEntity
, IList
, Field
->getType(), Index
,
2429 StructuredList
, StructuredIndex
);
2431 CheckImplicitInitList(MemberEntity
, IList
, Field
->getType(), Index
,
2432 StructuredList
, StructuredIndex
);
2435 /// Expand a field designator that refers to a member of an
2436 /// anonymous struct or union into a series of field designators that
2437 /// refers to the field within the appropriate subobject.
2439 static void ExpandAnonymousFieldDesignator(Sema
&SemaRef
,
2440 DesignatedInitExpr
*DIE
,
2442 IndirectFieldDecl
*IndirectField
) {
2443 typedef DesignatedInitExpr::Designator Designator
;
2445 // Build the replacement designators.
2446 SmallVector
<Designator
, 4> Replacements
;
2447 for (IndirectFieldDecl::chain_iterator PI
= IndirectField
->chain_begin(),
2448 PE
= IndirectField
->chain_end(); PI
!= PE
; ++PI
) {
2450 Replacements
.push_back(Designator::CreateFieldDesignator(
2451 (IdentifierInfo
*)nullptr, DIE
->getDesignator(DesigIdx
)->getDotLoc(),
2452 DIE
->getDesignator(DesigIdx
)->getFieldLoc()));
2454 Replacements
.push_back(Designator::CreateFieldDesignator(
2455 (IdentifierInfo
*)nullptr, SourceLocation(), SourceLocation()));
2456 assert(isa
<FieldDecl
>(*PI
));
2457 Replacements
.back().setFieldDecl(cast
<FieldDecl
>(*PI
));
2460 // Expand the current designator into the set of replacement
2461 // designators, so we have a full subobject path down to where the
2462 // member of the anonymous struct/union is actually stored.
2463 DIE
->ExpandDesignator(SemaRef
.Context
, DesigIdx
, &Replacements
[0],
2464 &Replacements
[0] + Replacements
.size());
2467 static DesignatedInitExpr
*CloneDesignatedInitExpr(Sema
&SemaRef
,
2468 DesignatedInitExpr
*DIE
) {
2469 unsigned NumIndexExprs
= DIE
->getNumSubExprs() - 1;
2470 SmallVector
<Expr
*, 4> IndexExprs(NumIndexExprs
);
2471 for (unsigned I
= 0; I
< NumIndexExprs
; ++I
)
2472 IndexExprs
[I
] = DIE
->getSubExpr(I
+ 1);
2473 return DesignatedInitExpr::Create(SemaRef
.Context
, DIE
->designators(),
2475 DIE
->getEqualOrColonLoc(),
2476 DIE
->usesGNUSyntax(), DIE
->getInit());
2481 // Callback to only accept typo corrections that are for field members of
2482 // the given struct or union.
2483 class FieldInitializerValidatorCCC final
: public CorrectionCandidateCallback
{
2485 explicit FieldInitializerValidatorCCC(const RecordDecl
*RD
)
2488 bool ValidateCandidate(const TypoCorrection
&candidate
) override
{
2489 FieldDecl
*FD
= candidate
.getCorrectionDeclAs
<FieldDecl
>();
2490 return FD
&& FD
->getDeclContext()->getRedeclContext()->Equals(Record
);
2493 std::unique_ptr
<CorrectionCandidateCallback
> clone() override
{
2494 return std::make_unique
<FieldInitializerValidatorCCC
>(*this);
2498 const RecordDecl
*Record
;
2501 } // end anonymous namespace
2503 /// Check the well-formedness of a C99 designated initializer.
2505 /// Determines whether the designated initializer @p DIE, which
2506 /// resides at the given @p Index within the initializer list @p
2507 /// IList, is well-formed for a current object of type @p DeclType
2508 /// (C99 6.7.8). The actual subobject that this designator refers to
2509 /// within the current subobject is returned in either
2510 /// @p NextField or @p NextElementIndex (whichever is appropriate).
2512 /// @param IList The initializer list in which this designated
2513 /// initializer occurs.
2515 /// @param DIE The designated initializer expression.
2517 /// @param DesigIdx The index of the current designator.
2519 /// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2520 /// into which the designation in @p DIE should refer.
2522 /// @param NextField If non-NULL and the first designator in @p DIE is
2523 /// a field, this will be set to the field declaration corresponding
2524 /// to the field named by the designator. On input, this is expected to be
2525 /// the next field that would be initialized in the absence of designation,
2526 /// if the complete object being initialized is a struct.
2528 /// @param NextElementIndex If non-NULL and the first designator in @p
2529 /// DIE is an array designator or GNU array-range designator, this
2530 /// will be set to the last index initialized by this designator.
2532 /// @param Index Index into @p IList where the designated initializer
2535 /// @param StructuredList The initializer list expression that
2536 /// describes all of the subobject initializers in the order they'll
2537 /// actually be initialized.
2539 /// @returns true if there was an error, false otherwise.
2541 InitListChecker::CheckDesignatedInitializer(const InitializedEntity
&Entity
,
2542 InitListExpr
*IList
,
2543 DesignatedInitExpr
*DIE
,
2545 QualType
&CurrentObjectType
,
2546 RecordDecl::field_iterator
*NextField
,
2547 llvm::APSInt
*NextElementIndex
,
2549 InitListExpr
*StructuredList
,
2550 unsigned &StructuredIndex
,
2551 bool FinishSubobjectInit
,
2552 bool TopLevelObject
) {
2553 if (DesigIdx
== DIE
->size()) {
2554 // C++20 designated initialization can result in direct-list-initialization
2555 // of the designated subobject. This is the only way that we can end up
2556 // performing direct initialization as part of aggregate initialization, so
2557 // it needs special handling.
2558 if (DIE
->isDirectInit()) {
2559 Expr
*Init
= DIE
->getInit();
2560 assert(isa
<InitListExpr
>(Init
) &&
2561 "designator result in direct non-list initialization?");
2562 InitializationKind Kind
= InitializationKind::CreateDirectList(
2563 DIE
->getBeginLoc(), Init
->getBeginLoc(), Init
->getEndLoc());
2564 InitializationSequence
Seq(SemaRef
, Entity
, Kind
, Init
,
2565 /*TopLevelOfInitList*/ true);
2566 if (StructuredList
) {
2567 ExprResult Result
= VerifyOnly
2569 : Seq
.Perform(SemaRef
, Entity
, Kind
, Init
);
2570 UpdateStructuredListElement(StructuredList
, StructuredIndex
,
2574 if (AggrDeductionCandidateParamTypes
)
2575 AggrDeductionCandidateParamTypes
->push_back(CurrentObjectType
);
2579 // Check the actual initialization for the designated object type.
2580 bool prevHadError
= hadError
;
2582 // Temporarily remove the designator expression from the
2583 // initializer list that the child calls see, so that we don't try
2584 // to re-process the designator.
2585 unsigned OldIndex
= Index
;
2586 IList
->setInit(OldIndex
, DIE
->getInit());
2588 CheckSubElementType(Entity
, IList
, CurrentObjectType
, Index
, StructuredList
,
2589 StructuredIndex
, /*DirectlyDesignated=*/true);
2591 // Restore the designated initializer expression in the syntactic
2592 // form of the initializer list.
2593 if (IList
->getInit(OldIndex
) != DIE
->getInit())
2594 DIE
->setInit(IList
->getInit(OldIndex
));
2595 IList
->setInit(OldIndex
, DIE
);
2597 return hadError
&& !prevHadError
;
2600 DesignatedInitExpr::Designator
*D
= DIE
->getDesignator(DesigIdx
);
2601 bool IsFirstDesignator
= (DesigIdx
== 0);
2602 if (IsFirstDesignator
? FullyStructuredList
: StructuredList
) {
2603 // Determine the structural initializer list that corresponds to the
2604 // current subobject.
2605 if (IsFirstDesignator
)
2606 StructuredList
= FullyStructuredList
;
2608 Expr
*ExistingInit
= StructuredIndex
< StructuredList
->getNumInits() ?
2609 StructuredList
->getInit(StructuredIndex
) : nullptr;
2610 if (!ExistingInit
&& StructuredList
->hasArrayFiller())
2611 ExistingInit
= StructuredList
->getArrayFiller();
2614 StructuredList
= getStructuredSubobjectInit(
2615 IList
, Index
, CurrentObjectType
, StructuredList
, StructuredIndex
,
2616 SourceRange(D
->getBeginLoc(), DIE
->getEndLoc()));
2617 else if (InitListExpr
*Result
= dyn_cast
<InitListExpr
>(ExistingInit
))
2618 StructuredList
= Result
;
2620 // We are creating an initializer list that initializes the
2621 // subobjects of the current object, but there was already an
2622 // initialization that completely initialized the current
2623 // subobject, e.g., by a compound literal:
2625 // struct X { int a, b; };
2626 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2628 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
2629 // designated initializer re-initializes only its current object
2631 diagnoseInitOverride(ExistingInit
,
2632 SourceRange(D
->getBeginLoc(), DIE
->getEndLoc()),
2633 /*UnionOverride=*/false,
2634 /*FullyOverwritten=*/false);
2637 if (DesignatedInitUpdateExpr
*E
=
2638 dyn_cast
<DesignatedInitUpdateExpr
>(ExistingInit
))
2639 StructuredList
= E
->getUpdater();
2641 DesignatedInitUpdateExpr
*DIUE
= new (SemaRef
.Context
)
2642 DesignatedInitUpdateExpr(SemaRef
.Context
, D
->getBeginLoc(),
2643 ExistingInit
, DIE
->getEndLoc());
2644 StructuredList
->updateInit(SemaRef
.Context
, StructuredIndex
, DIUE
);
2645 StructuredList
= DIUE
->getUpdater();
2648 // We don't need to track the structured representation of a
2649 // designated init update of an already-fully-initialized object in
2650 // verify-only mode. The only reason we would need the structure is
2651 // to determine where the uninitialized "holes" are, and in this
2652 // case, we know there aren't any and we can't introduce any.
2653 StructuredList
= nullptr;
2659 if (D
->isFieldDesignator()) {
2662 // If a designator has the form
2666 // then the current object (defined below) shall have
2667 // structure or union type and the identifier shall be the
2668 // name of a member of that type.
2669 RecordDecl
*RD
= getRecordDecl(CurrentObjectType
);
2671 SourceLocation Loc
= D
->getDotLoc();
2672 if (Loc
.isInvalid())
2673 Loc
= D
->getFieldLoc();
2675 SemaRef
.Diag(Loc
, diag::err_field_designator_non_aggr
)
2676 << SemaRef
.getLangOpts().CPlusPlus
<< CurrentObjectType
;
2681 FieldDecl
*KnownField
= D
->getFieldDecl();
2683 const IdentifierInfo
*FieldName
= D
->getFieldName();
2684 ValueDecl
*VD
= SemaRef
.tryLookupUnambiguousFieldDecl(RD
, FieldName
);
2685 if (auto *FD
= dyn_cast_if_present
<FieldDecl
>(VD
)) {
2687 } else if (auto *IFD
= dyn_cast_if_present
<IndirectFieldDecl
>(VD
)) {
2688 // In verify mode, don't modify the original.
2690 DIE
= CloneDesignatedInitExpr(SemaRef
, DIE
);
2691 ExpandAnonymousFieldDesignator(SemaRef
, DIE
, DesigIdx
, IFD
);
2692 D
= DIE
->getDesignator(DesigIdx
);
2693 KnownField
= cast
<FieldDecl
>(*IFD
->chain_begin());
2698 return true; // No typo correction when just trying this out.
2701 // We found a placeholder variable
2702 if (SemaRef
.DiagRedefinedPlaceholderFieldDecl(DIE
->getBeginLoc(), RD
,
2707 // Name lookup found something, but it wasn't a field.
2708 if (DeclContextLookupResult Lookup
= RD
->lookup(FieldName
);
2710 SemaRef
.Diag(D
->getFieldLoc(), diag::err_field_designator_nonfield
)
2712 SemaRef
.Diag(Lookup
.front()->getLocation(),
2713 diag::note_field_designator_found
);
2718 // Name lookup didn't find anything.
2719 // Determine whether this was a typo for another field name.
2720 FieldInitializerValidatorCCC
CCC(RD
);
2721 if (TypoCorrection Corrected
= SemaRef
.CorrectTypo(
2722 DeclarationNameInfo(FieldName
, D
->getFieldLoc()),
2723 Sema::LookupMemberName
, /*Scope=*/nullptr, /*SS=*/nullptr, CCC
,
2724 Sema::CTK_ErrorRecovery
, RD
)) {
2725 SemaRef
.diagnoseTypo(
2727 SemaRef
.PDiag(diag::err_field_designator_unknown_suggest
)
2728 << FieldName
<< CurrentObjectType
);
2729 KnownField
= Corrected
.getCorrectionDeclAs
<FieldDecl
>();
2732 // Typo correction didn't find anything.
2733 SourceLocation Loc
= D
->getFieldLoc();
2735 // The loc can be invalid with a "null" designator (i.e. an anonymous
2736 // union/struct). Do our best to approximate the location.
2737 if (Loc
.isInvalid())
2738 Loc
= IList
->getBeginLoc();
2740 SemaRef
.Diag(Loc
, diag::err_field_designator_unknown
)
2741 << FieldName
<< CurrentObjectType
<< DIE
->getSourceRange();
2748 unsigned NumBases
= 0;
2749 if (auto *CXXRD
= dyn_cast
<CXXRecordDecl
>(RD
))
2750 NumBases
= CXXRD
->getNumBases();
2752 unsigned FieldIndex
= NumBases
;
2754 for (auto *FI
: RD
->fields()) {
2755 if (FI
->isUnnamedBitfield())
2757 if (declaresSameEntity(KnownField
, FI
)) {
2764 RecordDecl::field_iterator Field
=
2765 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField
));
2767 // All of the fields of a union are located at the same place in
2768 // the initializer list.
2769 if (RD
->isUnion()) {
2771 if (StructuredList
) {
2772 FieldDecl
*CurrentField
= StructuredList
->getInitializedFieldInUnion();
2773 if (CurrentField
&& !declaresSameEntity(CurrentField
, *Field
)) {
2774 assert(StructuredList
->getNumInits() == 1
2775 && "A union should never have more than one initializer!");
2777 Expr
*ExistingInit
= StructuredList
->getInit(0);
2779 // We're about to throw away an initializer, emit warning.
2780 diagnoseInitOverride(
2781 ExistingInit
, SourceRange(D
->getBeginLoc(), DIE
->getEndLoc()),
2782 /*UnionOverride=*/true,
2783 /*FullyOverwritten=*/SemaRef
.getLangOpts().CPlusPlus
? false
2787 // remove existing initializer
2788 StructuredList
->resizeInits(SemaRef
.Context
, 0);
2789 StructuredList
->setInitializedFieldInUnion(nullptr);
2792 StructuredList
->setInitializedFieldInUnion(*Field
);
2796 // Make sure we can use this declaration.
2799 InvalidUse
= !SemaRef
.CanUseDecl(*Field
, TreatUnavailableAsInvalid
);
2801 InvalidUse
= SemaRef
.DiagnoseUseOfDecl(*Field
, D
->getFieldLoc());
2807 // C++20 [dcl.init.list]p3:
2808 // The ordered identifiers in the designators of the designated-
2809 // initializer-list shall form a subsequence of the ordered identifiers
2810 // in the direct non-static data members of T.
2812 // Note that this is not a condition on forming the aggregate
2813 // initialization, only on actually performing initialization,
2814 // so it is not checked in VerifyOnly mode.
2816 // FIXME: This is the only reordering diagnostic we produce, and it only
2817 // catches cases where we have a top-level field designator that jumps
2818 // backwards. This is the only such case that is reachable in an
2819 // otherwise-valid C++20 program, so is the only case that's required for
2820 // conformance, but for consistency, we should diagnose all the other
2821 // cases where a designator takes us backwards too.
2822 if (IsFirstDesignator
&& !VerifyOnly
&& SemaRef
.getLangOpts().CPlusPlus
&&
2824 (*NextField
== RD
->field_end() ||
2825 (*NextField
)->getFieldIndex() > Field
->getFieldIndex() + 1)) {
2826 // Find the field that we just initialized.
2827 FieldDecl
*PrevField
= nullptr;
2828 for (auto FI
= RD
->field_begin(); FI
!= RD
->field_end(); ++FI
) {
2829 if (FI
->isUnnamedBitfield())
2831 if (*NextField
!= RD
->field_end() &&
2832 declaresSameEntity(*FI
, **NextField
))
2838 PrevField
->getFieldIndex() > KnownField
->getFieldIndex()) {
2839 SemaRef
.Diag(DIE
->getInit()->getBeginLoc(),
2840 diag::ext_designated_init_reordered
)
2841 << KnownField
<< PrevField
<< DIE
->getSourceRange();
2843 unsigned OldIndex
= StructuredIndex
- 1;
2844 if (StructuredList
&& OldIndex
<= StructuredList
->getNumInits()) {
2845 if (Expr
*PrevInit
= StructuredList
->getInit(OldIndex
)) {
2846 SemaRef
.Diag(PrevInit
->getBeginLoc(),
2847 diag::note_previous_field_init
)
2848 << PrevField
<< PrevInit
->getSourceRange();
2855 // Update the designator with the field declaration.
2857 D
->setFieldDecl(*Field
);
2859 // Make sure that our non-designated initializer list has space
2860 // for a subobject corresponding to this field.
2861 if (StructuredList
&& FieldIndex
>= StructuredList
->getNumInits())
2862 StructuredList
->resizeInits(SemaRef
.Context
, FieldIndex
+ 1);
2864 // This designator names a flexible array member.
2865 if (Field
->getType()->isIncompleteArrayType()) {
2866 bool Invalid
= false;
2867 if ((DesigIdx
+ 1) != DIE
->size()) {
2868 // We can't designate an object within the flexible array
2869 // member (because GCC doesn't allow it).
2871 DesignatedInitExpr::Designator
*NextD
2872 = DIE
->getDesignator(DesigIdx
+ 1);
2873 SemaRef
.Diag(NextD
->getBeginLoc(),
2874 diag::err_designator_into_flexible_array_member
)
2875 << SourceRange(NextD
->getBeginLoc(), DIE
->getEndLoc());
2876 SemaRef
.Diag(Field
->getLocation(), diag::note_flexible_array_member
)
2882 if (!hadError
&& !isa
<InitListExpr
>(DIE
->getInit()) &&
2883 !isa
<StringLiteral
>(DIE
->getInit())) {
2884 // The initializer is not an initializer list.
2886 SemaRef
.Diag(DIE
->getInit()->getBeginLoc(),
2887 diag::err_flexible_array_init_needs_braces
)
2888 << DIE
->getInit()->getSourceRange();
2889 SemaRef
.Diag(Field
->getLocation(), diag::note_flexible_array_member
)
2895 // Check GNU flexible array initializer.
2896 if (!Invalid
&& CheckFlexibleArrayInit(Entity
, DIE
->getInit(), *Field
,
2905 // Initialize the array.
2906 bool prevHadError
= hadError
;
2907 unsigned newStructuredIndex
= FieldIndex
;
2908 unsigned OldIndex
= Index
;
2909 IList
->setInit(Index
, DIE
->getInit());
2911 InitializedEntity MemberEntity
=
2912 InitializedEntity::InitializeMember(*Field
, &Entity
);
2913 CheckSubElementType(MemberEntity
, IList
, Field
->getType(), Index
,
2914 StructuredList
, newStructuredIndex
);
2916 IList
->setInit(OldIndex
, DIE
);
2917 if (hadError
&& !prevHadError
) {
2922 StructuredIndex
= FieldIndex
;
2926 // Recurse to check later designated subobjects.
2927 QualType FieldType
= Field
->getType();
2928 unsigned newStructuredIndex
= FieldIndex
;
2930 InitializedEntity MemberEntity
=
2931 InitializedEntity::InitializeMember(*Field
, &Entity
);
2932 if (CheckDesignatedInitializer(MemberEntity
, IList
, DIE
, DesigIdx
+ 1,
2933 FieldType
, nullptr, nullptr, Index
,
2934 StructuredList
, newStructuredIndex
,
2935 FinishSubobjectInit
, false))
2939 // Find the position of the next field to be initialized in this
2944 // If this the first designator, our caller will continue checking
2945 // the rest of this struct/class/union subobject.
2946 if (IsFirstDesignator
) {
2947 if (Field
!= RD
->field_end() && Field
->isUnnamedBitfield())
2953 StructuredIndex
= FieldIndex
;
2957 if (!FinishSubobjectInit
)
2960 // We've already initialized something in the union; we're done.
2964 // Check the remaining fields within this class/struct/union subobject.
2965 bool prevHadError
= hadError
;
2968 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
2969 CXXRecordDecl::base_class_iterator());
2970 CheckStructUnionTypes(Entity
, IList
, CurrentObjectType
, NoBases
, Field
,
2971 false, Index
, StructuredList
, FieldIndex
);
2972 return hadError
&& !prevHadError
;
2977 // If a designator has the form
2979 // [ constant-expression ]
2981 // then the current object (defined below) shall have array
2982 // type and the expression shall be an integer constant
2983 // expression. If the array is of unknown size, any
2984 // nonnegative value is valid.
2986 // Additionally, cope with the GNU extension that permits
2987 // designators of the form
2989 // [ constant-expression ... constant-expression ]
2990 const ArrayType
*AT
= SemaRef
.Context
.getAsArrayType(CurrentObjectType
);
2993 SemaRef
.Diag(D
->getLBracketLoc(), diag::err_array_designator_non_array
)
2994 << CurrentObjectType
;
2999 Expr
*IndexExpr
= nullptr;
3000 llvm::APSInt DesignatedStartIndex
, DesignatedEndIndex
;
3001 if (D
->isArrayDesignator()) {
3002 IndexExpr
= DIE
->getArrayIndex(*D
);
3003 DesignatedStartIndex
= IndexExpr
->EvaluateKnownConstInt(SemaRef
.Context
);
3004 DesignatedEndIndex
= DesignatedStartIndex
;
3006 assert(D
->isArrayRangeDesignator() && "Need array-range designator");
3008 DesignatedStartIndex
=
3009 DIE
->getArrayRangeStart(*D
)->EvaluateKnownConstInt(SemaRef
.Context
);
3010 DesignatedEndIndex
=
3011 DIE
->getArrayRangeEnd(*D
)->EvaluateKnownConstInt(SemaRef
.Context
);
3012 IndexExpr
= DIE
->getArrayRangeEnd(*D
);
3014 // Codegen can't handle evaluating array range designators that have side
3015 // effects, because we replicate the AST value for each initialized element.
3016 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
3017 // elements with something that has a side effect, so codegen can emit an
3018 // "error unsupported" error instead of miscompiling the app.
3019 if (DesignatedStartIndex
.getZExtValue()!=DesignatedEndIndex
.getZExtValue()&&
3020 DIE
->getInit()->HasSideEffects(SemaRef
.Context
) && !VerifyOnly
)
3021 FullyStructuredList
->sawArrayRangeDesignator();
3024 if (isa
<ConstantArrayType
>(AT
)) {
3025 llvm::APSInt
MaxElements(cast
<ConstantArrayType
>(AT
)->getSize(), false);
3026 DesignatedStartIndex
3027 = DesignatedStartIndex
.extOrTrunc(MaxElements
.getBitWidth());
3028 DesignatedStartIndex
.setIsUnsigned(MaxElements
.isUnsigned());
3030 = DesignatedEndIndex
.extOrTrunc(MaxElements
.getBitWidth());
3031 DesignatedEndIndex
.setIsUnsigned(MaxElements
.isUnsigned());
3032 if (DesignatedEndIndex
>= MaxElements
) {
3034 SemaRef
.Diag(IndexExpr
->getBeginLoc(),
3035 diag::err_array_designator_too_large
)
3036 << toString(DesignatedEndIndex
, 10) << toString(MaxElements
, 10)
3037 << IndexExpr
->getSourceRange();
3042 unsigned DesignatedIndexBitWidth
=
3043 ConstantArrayType::getMaxSizeBits(SemaRef
.Context
);
3044 DesignatedStartIndex
=
3045 DesignatedStartIndex
.extOrTrunc(DesignatedIndexBitWidth
);
3046 DesignatedEndIndex
=
3047 DesignatedEndIndex
.extOrTrunc(DesignatedIndexBitWidth
);
3048 DesignatedStartIndex
.setIsUnsigned(true);
3049 DesignatedEndIndex
.setIsUnsigned(true);
3052 bool IsStringLiteralInitUpdate
=
3053 StructuredList
&& StructuredList
->isStringLiteralInit();
3054 if (IsStringLiteralInitUpdate
&& VerifyOnly
) {
3055 // We're just verifying an update to a string literal init. We don't need
3056 // to split the string up into individual characters to do that.
3057 StructuredList
= nullptr;
3058 } else if (IsStringLiteralInitUpdate
) {
3059 // We're modifying a string literal init; we have to decompose the string
3060 // so we can modify the individual characters.
3061 ASTContext
&Context
= SemaRef
.Context
;
3062 Expr
*SubExpr
= StructuredList
->getInit(0)->IgnoreParenImpCasts();
3064 // Compute the character type
3065 QualType CharTy
= AT
->getElementType();
3067 // Compute the type of the integer literals.
3068 QualType PromotedCharTy
= CharTy
;
3069 if (Context
.isPromotableIntegerType(CharTy
))
3070 PromotedCharTy
= Context
.getPromotedIntegerType(CharTy
);
3071 unsigned PromotedCharTyWidth
= Context
.getTypeSize(PromotedCharTy
);
3073 if (StringLiteral
*SL
= dyn_cast
<StringLiteral
>(SubExpr
)) {
3074 // Get the length of the string.
3075 uint64_t StrLen
= SL
->getLength();
3076 if (cast
<ConstantArrayType
>(AT
)->getSize().ult(StrLen
))
3077 StrLen
= cast
<ConstantArrayType
>(AT
)->getSize().getZExtValue();
3078 StructuredList
->resizeInits(Context
, StrLen
);
3080 // Build a literal for each character in the string, and put them into
3082 for (unsigned i
= 0, e
= StrLen
; i
!= e
; ++i
) {
3083 llvm::APInt
CodeUnit(PromotedCharTyWidth
, SL
->getCodeUnit(i
));
3084 Expr
*Init
= new (Context
) IntegerLiteral(
3085 Context
, CodeUnit
, PromotedCharTy
, SubExpr
->getExprLoc());
3086 if (CharTy
!= PromotedCharTy
)
3087 Init
= ImplicitCastExpr::Create(Context
, CharTy
, CK_IntegralCast
,
3088 Init
, nullptr, VK_PRValue
,
3089 FPOptionsOverride());
3090 StructuredList
->updateInit(Context
, i
, Init
);
3093 ObjCEncodeExpr
*E
= cast
<ObjCEncodeExpr
>(SubExpr
);
3095 Context
.getObjCEncodingForType(E
->getEncodedType(), Str
);
3097 // Get the length of the string.
3098 uint64_t StrLen
= Str
.size();
3099 if (cast
<ConstantArrayType
>(AT
)->getSize().ult(StrLen
))
3100 StrLen
= cast
<ConstantArrayType
>(AT
)->getSize().getZExtValue();
3101 StructuredList
->resizeInits(Context
, StrLen
);
3103 // Build a literal for each character in the string, and put them into
3105 for (unsigned i
= 0, e
= StrLen
; i
!= e
; ++i
) {
3106 llvm::APInt
CodeUnit(PromotedCharTyWidth
, Str
[i
]);
3107 Expr
*Init
= new (Context
) IntegerLiteral(
3108 Context
, CodeUnit
, PromotedCharTy
, SubExpr
->getExprLoc());
3109 if (CharTy
!= PromotedCharTy
)
3110 Init
= ImplicitCastExpr::Create(Context
, CharTy
, CK_IntegralCast
,
3111 Init
, nullptr, VK_PRValue
,
3112 FPOptionsOverride());
3113 StructuredList
->updateInit(Context
, i
, Init
);
3118 // Make sure that our non-designated initializer list has space
3119 // for a subobject corresponding to this array element.
3120 if (StructuredList
&&
3121 DesignatedEndIndex
.getZExtValue() >= StructuredList
->getNumInits())
3122 StructuredList
->resizeInits(SemaRef
.Context
,
3123 DesignatedEndIndex
.getZExtValue() + 1);
3125 // Repeatedly perform subobject initializations in the range
3126 // [DesignatedStartIndex, DesignatedEndIndex].
3128 // Move to the next designator
3129 unsigned ElementIndex
= DesignatedStartIndex
.getZExtValue();
3130 unsigned OldIndex
= Index
;
3132 InitializedEntity ElementEntity
=
3133 InitializedEntity::InitializeElement(SemaRef
.Context
, 0, Entity
);
3135 while (DesignatedStartIndex
<= DesignatedEndIndex
) {
3136 // Recurse to check later designated subobjects.
3137 QualType ElementType
= AT
->getElementType();
3140 ElementEntity
.setElementIndex(ElementIndex
);
3141 if (CheckDesignatedInitializer(
3142 ElementEntity
, IList
, DIE
, DesigIdx
+ 1, ElementType
, nullptr,
3143 nullptr, Index
, StructuredList
, ElementIndex
,
3144 FinishSubobjectInit
&& (DesignatedStartIndex
== DesignatedEndIndex
),
3148 // Move to the next index in the array that we'll be initializing.
3149 ++DesignatedStartIndex
;
3150 ElementIndex
= DesignatedStartIndex
.getZExtValue();
3153 // If this the first designator, our caller will continue checking
3154 // the rest of this array subobject.
3155 if (IsFirstDesignator
) {
3156 if (NextElementIndex
)
3157 *NextElementIndex
= DesignatedStartIndex
;
3158 StructuredIndex
= ElementIndex
;
3162 if (!FinishSubobjectInit
)
3165 // Check the remaining elements within this array subobject.
3166 bool prevHadError
= hadError
;
3167 CheckArrayType(Entity
, IList
, CurrentObjectType
, DesignatedStartIndex
,
3168 /*SubobjectIsDesignatorContext=*/false, Index
,
3169 StructuredList
, ElementIndex
);
3170 return hadError
&& !prevHadError
;
3173 // Get the structured initializer list for a subobject of type
3174 // @p CurrentObjectType.
3176 InitListChecker::getStructuredSubobjectInit(InitListExpr
*IList
, unsigned Index
,
3177 QualType CurrentObjectType
,
3178 InitListExpr
*StructuredList
,
3179 unsigned StructuredIndex
,
3180 SourceRange InitRange
,
3181 bool IsFullyOverwritten
) {
3182 if (!StructuredList
)
3185 Expr
*ExistingInit
= nullptr;
3186 if (StructuredIndex
< StructuredList
->getNumInits())
3187 ExistingInit
= StructuredList
->getInit(StructuredIndex
);
3189 if (InitListExpr
*Result
= dyn_cast_or_null
<InitListExpr
>(ExistingInit
))
3190 // There might have already been initializers for subobjects of the current
3191 // object, but a subsequent initializer list will overwrite the entirety
3192 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
3194 // struct P { char x[6]; };
3195 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
3197 // The first designated initializer is ignored, and l.x is just "f".
3198 if (!IsFullyOverwritten
)
3202 // We are creating an initializer list that initializes the
3203 // subobjects of the current object, but there was already an
3204 // initialization that completely initialized the current
3207 // struct X { int a, b; };
3208 // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 };
3210 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
3211 // designated initializer overwrites the [0].b initializer
3212 // from the prior initialization.
3214 // When the existing initializer is an expression rather than an
3215 // initializer list, we cannot decompose and update it in this way.
3218 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
3220 // This case is handled by CheckDesignatedInitializer.
3221 diagnoseInitOverride(ExistingInit
, InitRange
);
3224 unsigned ExpectedNumInits
= 0;
3225 if (Index
< IList
->getNumInits()) {
3226 if (auto *Init
= dyn_cast_or_null
<InitListExpr
>(IList
->getInit(Index
)))
3227 ExpectedNumInits
= Init
->getNumInits();
3229 ExpectedNumInits
= IList
->getNumInits() - Index
;
3232 InitListExpr
*Result
=
3233 createInitListExpr(CurrentObjectType
, InitRange
, ExpectedNumInits
);
3235 // Link this new initializer list into the structured initializer
3237 StructuredList
->updateInit(SemaRef
.Context
, StructuredIndex
, Result
);
3242 InitListChecker::createInitListExpr(QualType CurrentObjectType
,
3243 SourceRange InitRange
,
3244 unsigned ExpectedNumInits
) {
3245 InitListExpr
*Result
= new (SemaRef
.Context
) InitListExpr(
3246 SemaRef
.Context
, InitRange
.getBegin(), std::nullopt
, InitRange
.getEnd());
3248 QualType ResultType
= CurrentObjectType
;
3249 if (!ResultType
->isArrayType())
3250 ResultType
= ResultType
.getNonLValueExprType(SemaRef
.Context
);
3251 Result
->setType(ResultType
);
3253 // Pre-allocate storage for the structured initializer list.
3254 unsigned NumElements
= 0;
3256 if (const ArrayType
*AType
3257 = SemaRef
.Context
.getAsArrayType(CurrentObjectType
)) {
3258 if (const ConstantArrayType
*CAType
= dyn_cast
<ConstantArrayType
>(AType
)) {
3259 NumElements
= CAType
->getSize().getZExtValue();
3260 // Simple heuristic so that we don't allocate a very large
3261 // initializer with many empty entries at the end.
3262 if (NumElements
> ExpectedNumInits
)
3265 } else if (const VectorType
*VType
= CurrentObjectType
->getAs
<VectorType
>()) {
3266 NumElements
= VType
->getNumElements();
3267 } else if (CurrentObjectType
->isRecordType()) {
3268 NumElements
= numStructUnionElements(CurrentObjectType
);
3269 } else if (CurrentObjectType
->isDependentType()) {
3273 Result
->reserveInits(SemaRef
.Context
, NumElements
);
3278 /// Update the initializer at index @p StructuredIndex within the
3279 /// structured initializer list to the value @p expr.
3280 void InitListChecker::UpdateStructuredListElement(InitListExpr
*StructuredList
,
3281 unsigned &StructuredIndex
,
3283 // No structured initializer list to update
3284 if (!StructuredList
)
3287 if (Expr
*PrevInit
= StructuredList
->updateInit(SemaRef
.Context
,
3288 StructuredIndex
, expr
)) {
3289 // This initializer overwrites a previous initializer.
3290 // No need to diagnose when `expr` is nullptr because a more relevant
3291 // diagnostic has already been issued and this diagnostic is potentially
3294 diagnoseInitOverride(PrevInit
, expr
->getSourceRange());
3300 /// Determine whether we can perform aggregate initialization for the purposes
3301 /// of overload resolution.
3302 bool Sema::CanPerformAggregateInitializationForOverloadResolution(
3303 const InitializedEntity
&Entity
, InitListExpr
*From
) {
3304 QualType Type
= Entity
.getType();
3305 InitListChecker
Check(*this, Entity
, From
, Type
, /*VerifyOnly=*/true,
3306 /*TreatUnavailableAsInvalid=*/false,
3307 /*InOverloadResolution=*/true);
3308 return !Check
.HadError();
3311 /// Check that the given Index expression is a valid array designator
3312 /// value. This is essentially just a wrapper around
3313 /// VerifyIntegerConstantExpression that also checks for negative values
3314 /// and produces a reasonable diagnostic if there is a
3315 /// failure. Returns the index expression, possibly with an implicit cast
3316 /// added, on success. If everything went okay, Value will receive the
3317 /// value of the constant expression.
3319 CheckArrayDesignatorExpr(Sema
&S
, Expr
*Index
, llvm::APSInt
&Value
) {
3320 SourceLocation Loc
= Index
->getBeginLoc();
3322 // Make sure this is an integer constant expression.
3324 S
.VerifyIntegerConstantExpression(Index
, &Value
, Sema::AllowFold
);
3325 if (Result
.isInvalid())
3328 if (Value
.isSigned() && Value
.isNegative())
3329 return S
.Diag(Loc
, diag::err_array_designator_negative
)
3330 << toString(Value
, 10) << Index
->getSourceRange();
3332 Value
.setIsUnsigned(true);
3336 ExprResult
Sema::ActOnDesignatedInitializer(Designation
&Desig
,
3337 SourceLocation EqualOrColonLoc
,
3340 typedef DesignatedInitExpr::Designator ASTDesignator
;
3342 bool Invalid
= false;
3343 SmallVector
<ASTDesignator
, 32> Designators
;
3344 SmallVector
<Expr
*, 32> InitExpressions
;
3346 // Build designators and check array designator expressions.
3347 for (unsigned Idx
= 0; Idx
< Desig
.getNumDesignators(); ++Idx
) {
3348 const Designator
&D
= Desig
.getDesignator(Idx
);
3350 if (D
.isFieldDesignator()) {
3351 Designators
.push_back(ASTDesignator::CreateFieldDesignator(
3352 D
.getFieldDecl(), D
.getDotLoc(), D
.getFieldLoc()));
3353 } else if (D
.isArrayDesignator()) {
3354 Expr
*Index
= static_cast<Expr
*>(D
.getArrayIndex());
3355 llvm::APSInt IndexValue
;
3356 if (!Index
->isTypeDependent() && !Index
->isValueDependent())
3357 Index
= CheckArrayDesignatorExpr(*this, Index
, IndexValue
).get();
3361 Designators
.push_back(ASTDesignator::CreateArrayDesignator(
3362 InitExpressions
.size(), D
.getLBracketLoc(), D
.getRBracketLoc()));
3363 InitExpressions
.push_back(Index
);
3365 } else if (D
.isArrayRangeDesignator()) {
3366 Expr
*StartIndex
= static_cast<Expr
*>(D
.getArrayRangeStart());
3367 Expr
*EndIndex
= static_cast<Expr
*>(D
.getArrayRangeEnd());
3368 llvm::APSInt StartValue
;
3369 llvm::APSInt EndValue
;
3370 bool StartDependent
= StartIndex
->isTypeDependent() ||
3371 StartIndex
->isValueDependent();
3372 bool EndDependent
= EndIndex
->isTypeDependent() ||
3373 EndIndex
->isValueDependent();
3374 if (!StartDependent
)
3376 CheckArrayDesignatorExpr(*this, StartIndex
, StartValue
).get();
3378 EndIndex
= CheckArrayDesignatorExpr(*this, EndIndex
, EndValue
).get();
3380 if (!StartIndex
|| !EndIndex
)
3383 // Make sure we're comparing values with the same bit width.
3384 if (StartDependent
|| EndDependent
) {
3385 // Nothing to compute.
3386 } else if (StartValue
.getBitWidth() > EndValue
.getBitWidth())
3387 EndValue
= EndValue
.extend(StartValue
.getBitWidth());
3388 else if (StartValue
.getBitWidth() < EndValue
.getBitWidth())
3389 StartValue
= StartValue
.extend(EndValue
.getBitWidth());
3391 if (!StartDependent
&& !EndDependent
&& EndValue
< StartValue
) {
3392 Diag(D
.getEllipsisLoc(), diag::err_array_designator_empty_range
)
3393 << toString(StartValue
, 10) << toString(EndValue
, 10)
3394 << StartIndex
->getSourceRange() << EndIndex
->getSourceRange();
3397 Designators
.push_back(ASTDesignator::CreateArrayRangeDesignator(
3398 InitExpressions
.size(), D
.getLBracketLoc(), D
.getEllipsisLoc(),
3399 D
.getRBracketLoc()));
3400 InitExpressions
.push_back(StartIndex
);
3401 InitExpressions
.push_back(EndIndex
);
3407 if (Invalid
|| Init
.isInvalid())
3410 return DesignatedInitExpr::Create(Context
, Designators
, InitExpressions
,
3411 EqualOrColonLoc
, GNUSyntax
,
3412 Init
.getAs
<Expr
>());
3415 //===----------------------------------------------------------------------===//
3416 // Initialization entity
3417 //===----------------------------------------------------------------------===//
3419 InitializedEntity::InitializedEntity(ASTContext
&Context
, unsigned Index
,
3420 const InitializedEntity
&Parent
)
3421 : Parent(&Parent
), Index(Index
)
3423 if (const ArrayType
*AT
= Context
.getAsArrayType(Parent
.getType())) {
3424 Kind
= EK_ArrayElement
;
3425 Type
= AT
->getElementType();
3426 } else if (const VectorType
*VT
= Parent
.getType()->getAs
<VectorType
>()) {
3427 Kind
= EK_VectorElement
;
3428 Type
= VT
->getElementType();
3430 const ComplexType
*CT
= Parent
.getType()->getAs
<ComplexType
>();
3431 assert(CT
&& "Unexpected type");
3432 Kind
= EK_ComplexElement
;
3433 Type
= CT
->getElementType();
3438 InitializedEntity::InitializeBase(ASTContext
&Context
,
3439 const CXXBaseSpecifier
*Base
,
3440 bool IsInheritedVirtualBase
,
3441 const InitializedEntity
*Parent
) {
3442 InitializedEntity Result
;
3443 Result
.Kind
= EK_Base
;
3444 Result
.Parent
= Parent
;
3445 Result
.Base
= {Base
, IsInheritedVirtualBase
};
3446 Result
.Type
= Base
->getType();
3450 DeclarationName
InitializedEntity::getName() const {
3451 switch (getKind()) {
3453 case EK_Parameter_CF_Audited
: {
3454 ParmVarDecl
*D
= Parameter
.getPointer();
3455 return (D
? D
->getDeclName() : DeclarationName());
3460 case EK_ParenAggInitMember
:
3462 case EK_TemplateParameter
:
3463 return Variable
.VariableOrMember
->getDeclName();
3465 case EK_LambdaCapture
:
3466 return DeclarationName(Capture
.VarID
);
3469 case EK_StmtExprResult
:
3475 case EK_ArrayElement
:
3476 case EK_VectorElement
:
3477 case EK_ComplexElement
:
3478 case EK_BlockElement
:
3479 case EK_LambdaToBlockConversionBlockElement
:
3480 case EK_CompoundLiteralInit
:
3481 case EK_RelatedResult
:
3482 return DeclarationName();
3485 llvm_unreachable("Invalid EntityKind!");
3488 ValueDecl
*InitializedEntity::getDecl() const {
3489 switch (getKind()) {
3492 case EK_ParenAggInitMember
:
3494 case EK_TemplateParameter
:
3495 return Variable
.VariableOrMember
;
3498 case EK_Parameter_CF_Audited
:
3499 return Parameter
.getPointer();
3502 case EK_StmtExprResult
:
3508 case EK_ArrayElement
:
3509 case EK_VectorElement
:
3510 case EK_ComplexElement
:
3511 case EK_BlockElement
:
3512 case EK_LambdaToBlockConversionBlockElement
:
3513 case EK_LambdaCapture
:
3514 case EK_CompoundLiteralInit
:
3515 case EK_RelatedResult
:
3519 llvm_unreachable("Invalid EntityKind!");
3522 bool InitializedEntity::allowsNRVO() const {
3523 switch (getKind()) {
3526 return LocAndNRVO
.NRVO
;
3528 case EK_StmtExprResult
:
3531 case EK_Parameter_CF_Audited
:
3532 case EK_TemplateParameter
:
3534 case EK_ParenAggInitMember
:
3538 case EK_CompoundLiteralInit
:
3541 case EK_ArrayElement
:
3542 case EK_VectorElement
:
3543 case EK_ComplexElement
:
3544 case EK_BlockElement
:
3545 case EK_LambdaToBlockConversionBlockElement
:
3546 case EK_LambdaCapture
:
3547 case EK_RelatedResult
:
3554 unsigned InitializedEntity::dumpImpl(raw_ostream
&OS
) const {
3555 assert(getParent() != this);
3556 unsigned Depth
= getParent() ? getParent()->dumpImpl(OS
) : 0;
3557 for (unsigned I
= 0; I
!= Depth
; ++I
)
3560 switch (getKind()) {
3561 case EK_Variable
: OS
<< "Variable"; break;
3562 case EK_Parameter
: OS
<< "Parameter"; break;
3563 case EK_Parameter_CF_Audited
: OS
<< "CF audited function Parameter";
3565 case EK_TemplateParameter
: OS
<< "TemplateParameter"; break;
3566 case EK_Result
: OS
<< "Result"; break;
3567 case EK_StmtExprResult
: OS
<< "StmtExprResult"; break;
3568 case EK_Exception
: OS
<< "Exception"; break;
3570 case EK_ParenAggInitMember
:
3573 case EK_Binding
: OS
<< "Binding"; break;
3574 case EK_New
: OS
<< "New"; break;
3575 case EK_Temporary
: OS
<< "Temporary"; break;
3576 case EK_CompoundLiteralInit
: OS
<< "CompoundLiteral";break;
3577 case EK_RelatedResult
: OS
<< "RelatedResult"; break;
3578 case EK_Base
: OS
<< "Base"; break;
3579 case EK_Delegating
: OS
<< "Delegating"; break;
3580 case EK_ArrayElement
: OS
<< "ArrayElement " << Index
; break;
3581 case EK_VectorElement
: OS
<< "VectorElement " << Index
; break;
3582 case EK_ComplexElement
: OS
<< "ComplexElement " << Index
; break;
3583 case EK_BlockElement
: OS
<< "Block"; break;
3584 case EK_LambdaToBlockConversionBlockElement
:
3585 OS
<< "Block (lambda)";
3587 case EK_LambdaCapture
:
3588 OS
<< "LambdaCapture ";
3589 OS
<< DeclarationName(Capture
.VarID
);
3593 if (auto *D
= getDecl()) {
3595 D
->printQualifiedName(OS
);
3598 OS
<< " '" << getType() << "'\n";
3603 LLVM_DUMP_METHOD
void InitializedEntity::dump() const {
3604 dumpImpl(llvm::errs());
3607 //===----------------------------------------------------------------------===//
3608 // Initialization sequence
3609 //===----------------------------------------------------------------------===//
3611 void InitializationSequence::Step::Destroy() {
3613 case SK_ResolveAddressOfOverloadedFunction
:
3614 case SK_CastDerivedToBasePRValue
:
3615 case SK_CastDerivedToBaseXValue
:
3616 case SK_CastDerivedToBaseLValue
:
3617 case SK_BindReference
:
3618 case SK_BindReferenceToTemporary
:
3620 case SK_ExtraneousCopyToTemporary
:
3621 case SK_UserConversion
:
3622 case SK_QualificationConversionPRValue
:
3623 case SK_QualificationConversionXValue
:
3624 case SK_QualificationConversionLValue
:
3625 case SK_FunctionReferenceConversion
:
3626 case SK_AtomicConversion
:
3627 case SK_ListInitialization
:
3628 case SK_UnwrapInitList
:
3629 case SK_RewrapInitList
:
3630 case SK_ConstructorInitialization
:
3631 case SK_ConstructorInitializationFromList
:
3632 case SK_ZeroInitialization
:
3633 case SK_CAssignment
:
3635 case SK_ObjCObjectConversion
:
3636 case SK_ArrayLoopIndex
:
3637 case SK_ArrayLoopInit
:
3639 case SK_GNUArrayInit
:
3640 case SK_ParenthesizedArrayInit
:
3641 case SK_PassByIndirectCopyRestore
:
3642 case SK_PassByIndirectRestore
:
3643 case SK_ProduceObjCObject
:
3644 case SK_StdInitializerList
:
3645 case SK_StdInitializerListConstructorCall
:
3646 case SK_OCLSamplerInit
:
3647 case SK_OCLZeroOpaqueType
:
3648 case SK_ParenthesizedListInit
:
3651 case SK_ConversionSequence
:
3652 case SK_ConversionSequenceNoNarrowing
:
3657 bool InitializationSequence::isDirectReferenceBinding() const {
3658 // There can be some lvalue adjustments after the SK_BindReference step.
3659 for (const Step
&S
: llvm::reverse(Steps
)) {
3660 if (S
.Kind
== SK_BindReference
)
3662 if (S
.Kind
== SK_BindReferenceToTemporary
)
3668 bool InitializationSequence::isAmbiguous() const {
3672 switch (getFailureKind()) {
3673 case FK_TooManyInitsForReference
:
3674 case FK_ParenthesizedListInitForReference
:
3675 case FK_ArrayNeedsInitList
:
3676 case FK_ArrayNeedsInitListOrStringLiteral
:
3677 case FK_ArrayNeedsInitListOrWideStringLiteral
:
3678 case FK_NarrowStringIntoWideCharArray
:
3679 case FK_WideStringIntoCharArray
:
3680 case FK_IncompatWideStringIntoWideChar
:
3681 case FK_PlainStringIntoUTF8Char
:
3682 case FK_UTF8StringIntoPlainChar
:
3683 case FK_AddressOfOverloadFailed
: // FIXME: Could do better
3684 case FK_NonConstLValueReferenceBindingToTemporary
:
3685 case FK_NonConstLValueReferenceBindingToBitfield
:
3686 case FK_NonConstLValueReferenceBindingToVectorElement
:
3687 case FK_NonConstLValueReferenceBindingToMatrixElement
:
3688 case FK_NonConstLValueReferenceBindingToUnrelated
:
3689 case FK_RValueReferenceBindingToLValue
:
3690 case FK_ReferenceAddrspaceMismatchTemporary
:
3691 case FK_ReferenceInitDropsQualifiers
:
3692 case FK_ReferenceInitFailed
:
3693 case FK_ConversionFailed
:
3694 case FK_ConversionFromPropertyFailed
:
3695 case FK_TooManyInitsForScalar
:
3696 case FK_ParenthesizedListInitForScalar
:
3697 case FK_ReferenceBindingToInitList
:
3698 case FK_InitListBadDestinationType
:
3699 case FK_DefaultInitOfConst
:
3701 case FK_ArrayTypeMismatch
:
3702 case FK_NonConstantArrayInit
:
3703 case FK_ListInitializationFailed
:
3704 case FK_VariableLengthArrayHasInitializer
:
3705 case FK_PlaceholderType
:
3706 case FK_ExplicitConstructor
:
3707 case FK_AddressOfUnaddressableFunction
:
3708 case FK_ParenthesizedListInitFailed
:
3709 case FK_DesignatedInitForNonAggregate
:
3712 case FK_ReferenceInitOverloadFailed
:
3713 case FK_UserConversionOverloadFailed
:
3714 case FK_ConstructorOverloadFailed
:
3715 case FK_ListConstructorOverloadFailed
:
3716 return FailedOverloadResult
== OR_Ambiguous
;
3719 llvm_unreachable("Invalid EntityKind!");
3722 bool InitializationSequence::isConstructorInitialization() const {
3723 return !Steps
.empty() && Steps
.back().Kind
== SK_ConstructorInitialization
;
3727 InitializationSequence
3728 ::AddAddressOverloadResolutionStep(FunctionDecl
*Function
,
3729 DeclAccessPair Found
,
3730 bool HadMultipleCandidates
) {
3732 S
.Kind
= SK_ResolveAddressOfOverloadedFunction
;
3733 S
.Type
= Function
->getType();
3734 S
.Function
.HadMultipleCandidates
= HadMultipleCandidates
;
3735 S
.Function
.Function
= Function
;
3736 S
.Function
.FoundDecl
= Found
;
3740 void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType
,
3745 S
.Kind
= SK_CastDerivedToBasePRValue
;
3747 case VK_XValue
: S
.Kind
= SK_CastDerivedToBaseXValue
; break;
3748 case VK_LValue
: S
.Kind
= SK_CastDerivedToBaseLValue
; break;
3754 void InitializationSequence::AddReferenceBindingStep(QualType T
,
3755 bool BindingTemporary
) {
3757 S
.Kind
= BindingTemporary
? SK_BindReferenceToTemporary
: SK_BindReference
;
3762 void InitializationSequence::AddFinalCopy(QualType T
) {
3764 S
.Kind
= SK_FinalCopy
;
3769 void InitializationSequence::AddExtraneousCopyToTemporary(QualType T
) {
3771 S
.Kind
= SK_ExtraneousCopyToTemporary
;
3777 InitializationSequence::AddUserConversionStep(FunctionDecl
*Function
,
3778 DeclAccessPair FoundDecl
,
3780 bool HadMultipleCandidates
) {
3782 S
.Kind
= SK_UserConversion
;
3784 S
.Function
.HadMultipleCandidates
= HadMultipleCandidates
;
3785 S
.Function
.Function
= Function
;
3786 S
.Function
.FoundDecl
= FoundDecl
;
3790 void InitializationSequence::AddQualificationConversionStep(QualType Ty
,
3793 S
.Kind
= SK_QualificationConversionPRValue
; // work around a gcc warning
3796 S
.Kind
= SK_QualificationConversionPRValue
;
3799 S
.Kind
= SK_QualificationConversionXValue
;
3802 S
.Kind
= SK_QualificationConversionLValue
;
3809 void InitializationSequence::AddFunctionReferenceConversionStep(QualType Ty
) {
3811 S
.Kind
= SK_FunctionReferenceConversion
;
3816 void InitializationSequence::AddAtomicConversionStep(QualType Ty
) {
3818 S
.Kind
= SK_AtomicConversion
;
3823 void InitializationSequence::AddConversionSequenceStep(
3824 const ImplicitConversionSequence
&ICS
, QualType T
,
3825 bool TopLevelOfInitList
) {
3827 S
.Kind
= TopLevelOfInitList
? SK_ConversionSequenceNoNarrowing
3828 : SK_ConversionSequence
;
3830 S
.ICS
= new ImplicitConversionSequence(ICS
);
3834 void InitializationSequence::AddListInitializationStep(QualType T
) {
3836 S
.Kind
= SK_ListInitialization
;
3841 void InitializationSequence::AddConstructorInitializationStep(
3842 DeclAccessPair FoundDecl
, CXXConstructorDecl
*Constructor
, QualType T
,
3843 bool HadMultipleCandidates
, bool FromInitList
, bool AsInitList
) {
3845 S
.Kind
= FromInitList
? AsInitList
? SK_StdInitializerListConstructorCall
3846 : SK_ConstructorInitializationFromList
3847 : SK_ConstructorInitialization
;
3849 S
.Function
.HadMultipleCandidates
= HadMultipleCandidates
;
3850 S
.Function
.Function
= Constructor
;
3851 S
.Function
.FoundDecl
= FoundDecl
;
3855 void InitializationSequence::AddZeroInitializationStep(QualType T
) {
3857 S
.Kind
= SK_ZeroInitialization
;
3862 void InitializationSequence::AddCAssignmentStep(QualType T
) {
3864 S
.Kind
= SK_CAssignment
;
3869 void InitializationSequence::AddStringInitStep(QualType T
) {
3871 S
.Kind
= SK_StringInit
;
3876 void InitializationSequence::AddObjCObjectConversionStep(QualType T
) {
3878 S
.Kind
= SK_ObjCObjectConversion
;
3883 void InitializationSequence::AddArrayInitStep(QualType T
, bool IsGNUExtension
) {
3885 S
.Kind
= IsGNUExtension
? SK_GNUArrayInit
: SK_ArrayInit
;
3890 void InitializationSequence::AddArrayInitLoopStep(QualType T
, QualType EltT
) {
3892 S
.Kind
= SK_ArrayLoopIndex
;
3894 Steps
.insert(Steps
.begin(), S
);
3896 S
.Kind
= SK_ArrayLoopInit
;
3901 void InitializationSequence::AddParenthesizedArrayInitStep(QualType T
) {
3903 S
.Kind
= SK_ParenthesizedArrayInit
;
3908 void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type
,
3911 s
.Kind
= (shouldCopy
? SK_PassByIndirectCopyRestore
3912 : SK_PassByIndirectRestore
);
3917 void InitializationSequence::AddProduceObjCObjectStep(QualType T
) {
3919 S
.Kind
= SK_ProduceObjCObject
;
3924 void InitializationSequence::AddStdInitializerListConstructionStep(QualType T
) {
3926 S
.Kind
= SK_StdInitializerList
;
3931 void InitializationSequence::AddOCLSamplerInitStep(QualType T
) {
3933 S
.Kind
= SK_OCLSamplerInit
;
3938 void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T
) {
3940 S
.Kind
= SK_OCLZeroOpaqueType
;
3945 void InitializationSequence::AddParenthesizedListInitStep(QualType T
) {
3947 S
.Kind
= SK_ParenthesizedListInit
;
3952 void InitializationSequence::RewrapReferenceInitList(QualType T
,
3953 InitListExpr
*Syntactic
) {
3954 assert(Syntactic
->getNumInits() == 1 &&
3955 "Can only rewrap trivial init lists.");
3957 S
.Kind
= SK_UnwrapInitList
;
3958 S
.Type
= Syntactic
->getInit(0)->getType();
3959 Steps
.insert(Steps
.begin(), S
);
3961 S
.Kind
= SK_RewrapInitList
;
3963 S
.WrappingSyntacticList
= Syntactic
;
3967 void InitializationSequence::SetOverloadFailure(FailureKind Failure
,
3968 OverloadingResult Result
) {
3969 setSequenceKind(FailedSequence
);
3970 this->Failure
= Failure
;
3971 this->FailedOverloadResult
= Result
;
3974 //===----------------------------------------------------------------------===//
3975 // Attempt initialization
3976 //===----------------------------------------------------------------------===//
3978 /// Tries to add a zero initializer. Returns true if that worked.
3980 maybeRecoverWithZeroInitialization(Sema
&S
, InitializationSequence
&Sequence
,
3981 const InitializedEntity
&Entity
) {
3982 if (Entity
.getKind() != InitializedEntity::EK_Variable
)
3985 VarDecl
*VD
= cast
<VarDecl
>(Entity
.getDecl());
3986 if (VD
->getInit() || VD
->getEndLoc().isMacroID())
3989 QualType VariableTy
= VD
->getType().getCanonicalType();
3990 SourceLocation Loc
= S
.getLocForEndOfToken(VD
->getEndLoc());
3991 std::string Init
= S
.getFixItZeroInitializerForType(VariableTy
, Loc
);
3992 if (!Init
.empty()) {
3993 Sequence
.AddZeroInitializationStep(Entity
.getType());
3994 Sequence
.SetZeroInitializationFixit(Init
, Loc
);
4000 static void MaybeProduceObjCObject(Sema
&S
,
4001 InitializationSequence
&Sequence
,
4002 const InitializedEntity
&Entity
) {
4003 if (!S
.getLangOpts().ObjCAutoRefCount
) return;
4005 /// When initializing a parameter, produce the value if it's marked
4006 /// __attribute__((ns_consumed)).
4007 if (Entity
.isParameterKind()) {
4008 if (!Entity
.isParameterConsumed())
4011 assert(Entity
.getType()->isObjCRetainableType() &&
4012 "consuming an object of unretainable type?");
4013 Sequence
.AddProduceObjCObjectStep(Entity
.getType());
4015 /// When initializing a return value, if the return type is a
4016 /// retainable type, then returns need to immediately retain the
4017 /// object. If an autorelease is required, it will be done at the
4019 } else if (Entity
.getKind() == InitializedEntity::EK_Result
||
4020 Entity
.getKind() == InitializedEntity::EK_StmtExprResult
) {
4021 if (!Entity
.getType()->isObjCRetainableType())
4024 Sequence
.AddProduceObjCObjectStep(Entity
.getType());
4028 static void TryListInitialization(Sema
&S
,
4029 const InitializedEntity
&Entity
,
4030 const InitializationKind
&Kind
,
4031 InitListExpr
*InitList
,
4032 InitializationSequence
&Sequence
,
4033 bool TreatUnavailableAsInvalid
);
4035 /// When initializing from init list via constructor, handle
4036 /// initialization of an object of type std::initializer_list<T>.
4038 /// \return true if we have handled initialization of an object of type
4039 /// std::initializer_list<T>, false otherwise.
4040 static bool TryInitializerListConstruction(Sema
&S
,
4043 InitializationSequence
&Sequence
,
4044 bool TreatUnavailableAsInvalid
) {
4046 if (!S
.isStdInitializerList(DestType
, &E
))
4049 if (!S
.isCompleteType(List
->getExprLoc(), E
)) {
4050 Sequence
.setIncompleteTypeFailure(E
);
4054 // Try initializing a temporary array from the init list.
4055 QualType ArrayType
= S
.Context
.getConstantArrayType(
4057 llvm::APInt(S
.Context
.getTypeSize(S
.Context
.getSizeType()),
4058 List
->getNumInits()),
4059 nullptr, clang::ArraySizeModifier::Normal
, 0);
4060 InitializedEntity HiddenArray
=
4061 InitializedEntity::InitializeTemporary(ArrayType
);
4062 InitializationKind Kind
= InitializationKind::CreateDirectList(
4063 List
->getExprLoc(), List
->getBeginLoc(), List
->getEndLoc());
4064 TryListInitialization(S
, HiddenArray
, Kind
, List
, Sequence
,
4065 TreatUnavailableAsInvalid
);
4067 Sequence
.AddStdInitializerListConstructionStep(DestType
);
4071 /// Determine if the constructor has the signature of a copy or move
4072 /// constructor for the type T of the class in which it was found. That is,
4073 /// determine if its first parameter is of type T or reference to (possibly
4074 /// cv-qualified) T.
4075 static bool hasCopyOrMoveCtorParam(ASTContext
&Ctx
,
4076 const ConstructorInfo
&Info
) {
4077 if (Info
.Constructor
->getNumParams() == 0)
4081 Info
.Constructor
->getParamDecl(0)->getType().getNonReferenceType();
4083 Ctx
.getRecordType(cast
<CXXRecordDecl
>(Info
.FoundDecl
->getDeclContext()));
4085 return Ctx
.hasSameUnqualifiedType(ParmT
, ClassT
);
4088 static OverloadingResult
4089 ResolveConstructorOverload(Sema
&S
, SourceLocation DeclLoc
,
4091 OverloadCandidateSet
&CandidateSet
,
4093 DeclContext::lookup_result Ctors
,
4094 OverloadCandidateSet::iterator
&Best
,
4095 bool CopyInitializing
, bool AllowExplicit
,
4096 bool OnlyListConstructors
, bool IsListInit
,
4097 bool SecondStepOfCopyInit
= false) {
4098 CandidateSet
.clear(OverloadCandidateSet::CSK_InitByConstructor
);
4099 CandidateSet
.setDestAS(DestType
.getQualifiers().getAddressSpace());
4101 for (NamedDecl
*D
: Ctors
) {
4102 auto Info
= getConstructorInfo(D
);
4103 if (!Info
.Constructor
|| Info
.Constructor
->isInvalidDecl())
4106 if (OnlyListConstructors
&& !S
.isInitListConstructor(Info
.Constructor
))
4109 // C++11 [over.best.ics]p4:
4110 // ... and the constructor or user-defined conversion function is a
4112 // - 13.3.1.3, when the argument is the temporary in the second step
4113 // of a class copy-initialization, or
4114 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
4115 // - the second phase of 13.3.1.7 when the initializer list has exactly
4116 // one element that is itself an initializer list, and the target is
4117 // the first parameter of a constructor of class X, and the conversion
4118 // is to X or reference to (possibly cv-qualified X),
4119 // user-defined conversion sequences are not considered.
4120 bool SuppressUserConversions
=
4121 SecondStepOfCopyInit
||
4122 (IsListInit
&& Args
.size() == 1 && isa
<InitListExpr
>(Args
[0]) &&
4123 hasCopyOrMoveCtorParam(S
.Context
, Info
));
4125 if (Info
.ConstructorTmpl
)
4126 S
.AddTemplateOverloadCandidate(
4127 Info
.ConstructorTmpl
, Info
.FoundDecl
,
4128 /*ExplicitArgs*/ nullptr, Args
, CandidateSet
, SuppressUserConversions
,
4129 /*PartialOverloading=*/false, AllowExplicit
);
4131 // C++ [over.match.copy]p1:
4132 // - When initializing a temporary to be bound to the first parameter
4133 // of a constructor [for type T] that takes a reference to possibly
4134 // cv-qualified T as its first argument, called with a single
4135 // argument in the context of direct-initialization, explicit
4136 // conversion functions are also considered.
4137 // FIXME: What if a constructor template instantiates to such a signature?
4138 bool AllowExplicitConv
= AllowExplicit
&& !CopyInitializing
&&
4140 hasCopyOrMoveCtorParam(S
.Context
, Info
);
4141 S
.AddOverloadCandidate(Info
.Constructor
, Info
.FoundDecl
, Args
,
4142 CandidateSet
, SuppressUserConversions
,
4143 /*PartialOverloading=*/false, AllowExplicit
,
4148 // FIXME: Work around a bug in C++17 guaranteed copy elision.
4150 // When initializing an object of class type T by constructor
4151 // ([over.match.ctor]) or by list-initialization ([over.match.list])
4152 // from a single expression of class type U, conversion functions of
4153 // U that convert to the non-reference type cv T are candidates.
4154 // Explicit conversion functions are only candidates during
4155 // direct-initialization.
4157 // Note: SecondStepOfCopyInit is only ever true in this case when
4158 // evaluating whether to produce a C++98 compatibility warning.
4159 if (S
.getLangOpts().CPlusPlus17
&& Args
.size() == 1 &&
4160 !SecondStepOfCopyInit
) {
4161 Expr
*Initializer
= Args
[0];
4162 auto *SourceRD
= Initializer
->getType()->getAsCXXRecordDecl();
4163 if (SourceRD
&& S
.isCompleteType(DeclLoc
, Initializer
->getType())) {
4164 const auto &Conversions
= SourceRD
->getVisibleConversionFunctions();
4165 for (auto I
= Conversions
.begin(), E
= Conversions
.end(); I
!= E
; ++I
) {
4167 CXXRecordDecl
*ActingDC
= cast
<CXXRecordDecl
>(D
->getDeclContext());
4168 D
= D
->getUnderlyingDecl();
4170 FunctionTemplateDecl
*ConvTemplate
= dyn_cast
<FunctionTemplateDecl
>(D
);
4171 CXXConversionDecl
*Conv
;
4173 Conv
= cast
<CXXConversionDecl
>(ConvTemplate
->getTemplatedDecl());
4175 Conv
= cast
<CXXConversionDecl
>(D
);
4178 S
.AddTemplateConversionCandidate(
4179 ConvTemplate
, I
.getPair(), ActingDC
, Initializer
, DestType
,
4180 CandidateSet
, AllowExplicit
, AllowExplicit
,
4181 /*AllowResultConversion*/ false);
4183 S
.AddConversionCandidate(Conv
, I
.getPair(), ActingDC
, Initializer
,
4184 DestType
, CandidateSet
, AllowExplicit
,
4186 /*AllowResultConversion*/ false);
4191 // Perform overload resolution and return the result.
4192 return CandidateSet
.BestViableFunction(S
, DeclLoc
, Best
);
4195 /// Attempt initialization by constructor (C++ [dcl.init]), which
4196 /// enumerates the constructors of the initialized entity and performs overload
4197 /// resolution to select the best.
4198 /// \param DestType The destination class type.
4199 /// \param DestArrayType The destination type, which is either DestType or
4200 /// a (possibly multidimensional) array of DestType.
4201 /// \param IsListInit Is this list-initialization?
4202 /// \param IsInitListCopy Is this non-list-initialization resulting from a
4203 /// list-initialization from {x} where x is the same
4204 /// type as the entity?
4205 static void TryConstructorInitialization(Sema
&S
,
4206 const InitializedEntity
&Entity
,
4207 const InitializationKind
&Kind
,
4208 MultiExprArg Args
, QualType DestType
,
4209 QualType DestArrayType
,
4210 InitializationSequence
&Sequence
,
4211 bool IsListInit
= false,
4212 bool IsInitListCopy
= false) {
4213 assert(((!IsListInit
&& !IsInitListCopy
) ||
4214 (Args
.size() == 1 && isa
<InitListExpr
>(Args
[0]))) &&
4215 "IsListInit/IsInitListCopy must come with a single initializer list "
4218 (IsListInit
|| IsInitListCopy
) ? cast
<InitListExpr
>(Args
[0]) : nullptr;
4219 MultiExprArg UnwrappedArgs
=
4220 ILE
? MultiExprArg(ILE
->getInits(), ILE
->getNumInits()) : Args
;
4222 // The type we're constructing needs to be complete.
4223 if (!S
.isCompleteType(Kind
.getLocation(), DestType
)) {
4224 Sequence
.setIncompleteTypeFailure(DestType
);
4228 // C++17 [dcl.init]p17:
4229 // - If the initializer expression is a prvalue and the cv-unqualified
4230 // version of the source type is the same class as the class of the
4231 // destination, the initializer expression is used to initialize the
4232 // destination object.
4233 // Per DR (no number yet), this does not apply when initializing a base
4234 // class or delegating to another constructor from a mem-initializer.
4235 // ObjC++: Lambda captured by the block in the lambda to block conversion
4236 // should avoid copy elision.
4237 if (S
.getLangOpts().CPlusPlus17
&&
4238 Entity
.getKind() != InitializedEntity::EK_Base
&&
4239 Entity
.getKind() != InitializedEntity::EK_Delegating
&&
4241 InitializedEntity::EK_LambdaToBlockConversionBlockElement
&&
4242 UnwrappedArgs
.size() == 1 && UnwrappedArgs
[0]->isPRValue() &&
4243 S
.Context
.hasSameUnqualifiedType(UnwrappedArgs
[0]->getType(), DestType
)) {
4244 // Convert qualifications if necessary.
4245 Sequence
.AddQualificationConversionStep(DestType
, VK_PRValue
);
4247 Sequence
.RewrapReferenceInitList(DestType
, ILE
);
4251 const RecordType
*DestRecordType
= DestType
->getAs
<RecordType
>();
4252 assert(DestRecordType
&& "Constructor initialization requires record type");
4253 CXXRecordDecl
*DestRecordDecl
4254 = cast
<CXXRecordDecl
>(DestRecordType
->getDecl());
4256 // Build the candidate set directly in the initialization sequence
4257 // structure, so that it will persist if we fail.
4258 OverloadCandidateSet
&CandidateSet
= Sequence
.getFailedCandidateSet();
4260 // Determine whether we are allowed to call explicit constructors or
4261 // explicit conversion operators.
4262 bool AllowExplicit
= Kind
.AllowExplicit() || IsListInit
;
4263 bool CopyInitialization
= Kind
.getKind() == InitializationKind::IK_Copy
;
4265 // - Otherwise, if T is a class type, constructors are considered. The
4266 // applicable constructors are enumerated, and the best one is chosen
4267 // through overload resolution.
4268 DeclContext::lookup_result Ctors
= S
.LookupConstructors(DestRecordDecl
);
4270 OverloadingResult Result
= OR_No_Viable_Function
;
4271 OverloadCandidateSet::iterator Best
;
4272 bool AsInitializerList
= false;
4274 // C++11 [over.match.list]p1, per DR1467:
4275 // When objects of non-aggregate type T are list-initialized, such that
4276 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
4277 // according to the rules in this section, overload resolution selects
4278 // the constructor in two phases:
4280 // - Initially, the candidate functions are the initializer-list
4281 // constructors of the class T and the argument list consists of the
4282 // initializer list as a single argument.
4284 AsInitializerList
= true;
4286 // If the initializer list has no elements and T has a default constructor,
4287 // the first phase is omitted.
4288 if (!(UnwrappedArgs
.empty() && S
.LookupDefaultConstructor(DestRecordDecl
)))
4289 Result
= ResolveConstructorOverload(S
, Kind
.getLocation(), Args
,
4290 CandidateSet
, DestType
, Ctors
, Best
,
4291 CopyInitialization
, AllowExplicit
,
4292 /*OnlyListConstructors=*/true,
4296 // C++11 [over.match.list]p1:
4297 // - If no viable initializer-list constructor is found, overload resolution
4298 // is performed again, where the candidate functions are all the
4299 // constructors of the class T and the argument list consists of the
4300 // elements of the initializer list.
4301 if (Result
== OR_No_Viable_Function
) {
4302 AsInitializerList
= false;
4303 Result
= ResolveConstructorOverload(S
, Kind
.getLocation(), UnwrappedArgs
,
4304 CandidateSet
, DestType
, Ctors
, Best
,
4305 CopyInitialization
, AllowExplicit
,
4306 /*OnlyListConstructors=*/false,
4310 Sequence
.SetOverloadFailure(
4311 IsListInit
? InitializationSequence::FK_ListConstructorOverloadFailed
4312 : InitializationSequence::FK_ConstructorOverloadFailed
,
4315 if (Result
!= OR_Deleted
)
4319 bool HadMultipleCandidates
= (CandidateSet
.size() > 1);
4321 // In C++17, ResolveConstructorOverload can select a conversion function
4322 // instead of a constructor.
4323 if (auto *CD
= dyn_cast
<CXXConversionDecl
>(Best
->Function
)) {
4324 // Add the user-defined conversion step that calls the conversion function.
4325 QualType ConvType
= CD
->getConversionType();
4326 assert(S
.Context
.hasSameUnqualifiedType(ConvType
, DestType
) &&
4327 "should not have selected this conversion function");
4328 Sequence
.AddUserConversionStep(CD
, Best
->FoundDecl
, ConvType
,
4329 HadMultipleCandidates
);
4330 if (!S
.Context
.hasSameType(ConvType
, DestType
))
4331 Sequence
.AddQualificationConversionStep(DestType
, VK_PRValue
);
4333 Sequence
.RewrapReferenceInitList(Entity
.getType(), ILE
);
4337 CXXConstructorDecl
*CtorDecl
= cast
<CXXConstructorDecl
>(Best
->Function
);
4338 if (Result
!= OR_Deleted
) {
4339 // C++11 [dcl.init]p6:
4340 // If a program calls for the default initialization of an object
4341 // of a const-qualified type T, T shall be a class type with a
4342 // user-provided default constructor.
4343 // C++ core issue 253 proposal:
4344 // If the implicit default constructor initializes all subobjects, no
4345 // initializer should be required.
4346 // The 253 proposal is for example needed to process libstdc++ headers
4348 if (Kind
.getKind() == InitializationKind::IK_Default
&&
4349 Entity
.getType().isConstQualified()) {
4350 if (!CtorDecl
->getParent()->allowConstDefaultInit()) {
4351 if (!maybeRecoverWithZeroInitialization(S
, Sequence
, Entity
))
4352 Sequence
.SetFailed(InitializationSequence::FK_DefaultInitOfConst
);
4357 // C++11 [over.match.list]p1:
4358 // In copy-list-initialization, if an explicit constructor is chosen, the
4359 // initializer is ill-formed.
4360 if (IsListInit
&& !Kind
.AllowExplicit() && CtorDecl
->isExplicit()) {
4361 Sequence
.SetFailed(InitializationSequence::FK_ExplicitConstructor
);
4366 // [class.copy.elision]p3:
4367 // In some copy-initialization contexts, a two-stage overload resolution
4369 // If the first overload resolution selects a deleted function, we also
4370 // need the initialization sequence to decide whether to perform the second
4371 // overload resolution.
4372 // For deleted functions in other contexts, there is no need to get the
4373 // initialization sequence.
4374 if (Result
== OR_Deleted
&& Kind
.getKind() != InitializationKind::IK_Copy
)
4377 // Add the constructor initialization step. Any cv-qualification conversion is
4378 // subsumed by the initialization.
4379 Sequence
.AddConstructorInitializationStep(
4380 Best
->FoundDecl
, CtorDecl
, DestArrayType
, HadMultipleCandidates
,
4381 IsListInit
| IsInitListCopy
, AsInitializerList
);
4385 ResolveOverloadedFunctionForReferenceBinding(Sema
&S
,
4387 QualType
&SourceType
,
4388 QualType
&UnqualifiedSourceType
,
4389 QualType UnqualifiedTargetType
,
4390 InitializationSequence
&Sequence
) {
4391 if (S
.Context
.getCanonicalType(UnqualifiedSourceType
) ==
4392 S
.Context
.OverloadTy
) {
4393 DeclAccessPair Found
;
4394 bool HadMultipleCandidates
= false;
4395 if (FunctionDecl
*Fn
4396 = S
.ResolveAddressOfOverloadedFunction(Initializer
,
4397 UnqualifiedTargetType
,
4399 &HadMultipleCandidates
)) {
4400 Sequence
.AddAddressOverloadResolutionStep(Fn
, Found
,
4401 HadMultipleCandidates
);
4402 SourceType
= Fn
->getType();
4403 UnqualifiedSourceType
= SourceType
.getUnqualifiedType();
4404 } else if (!UnqualifiedTargetType
->isRecordType()) {
4405 Sequence
.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed
);
4412 static void TryReferenceInitializationCore(Sema
&S
,
4413 const InitializedEntity
&Entity
,
4414 const InitializationKind
&Kind
,
4416 QualType cv1T1
, QualType T1
,
4418 QualType cv2T2
, QualType T2
,
4420 InitializationSequence
&Sequence
);
4422 static void TryValueInitialization(Sema
&S
,
4423 const InitializedEntity
&Entity
,
4424 const InitializationKind
&Kind
,
4425 InitializationSequence
&Sequence
,
4426 InitListExpr
*InitList
= nullptr);
4428 /// Attempt list initialization of a reference.
4429 static void TryReferenceListInitialization(Sema
&S
,
4430 const InitializedEntity
&Entity
,
4431 const InitializationKind
&Kind
,
4432 InitListExpr
*InitList
,
4433 InitializationSequence
&Sequence
,
4434 bool TreatUnavailableAsInvalid
) {
4435 // First, catch C++03 where this isn't possible.
4436 if (!S
.getLangOpts().CPlusPlus11
) {
4437 Sequence
.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList
);
4440 // Can't reference initialize a compound literal.
4441 if (Entity
.getKind() == InitializedEntity::EK_CompoundLiteralInit
) {
4442 Sequence
.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList
);
4446 QualType DestType
= Entity
.getType();
4447 QualType cv1T1
= DestType
->castAs
<ReferenceType
>()->getPointeeType();
4449 QualType T1
= S
.Context
.getUnqualifiedArrayType(cv1T1
, T1Quals
);
4451 // Reference initialization via an initializer list works thus:
4452 // If the initializer list consists of a single element that is
4453 // reference-related to the referenced type, bind directly to that element
4454 // (possibly creating temporaries).
4455 // Otherwise, initialize a temporary with the initializer list and
4457 if (InitList
->getNumInits() == 1) {
4458 Expr
*Initializer
= InitList
->getInit(0);
4459 QualType cv2T2
= S
.getCompletedType(Initializer
);
4461 QualType T2
= S
.Context
.getUnqualifiedArrayType(cv2T2
, T2Quals
);
4463 // If this fails, creating a temporary wouldn't work either.
4464 if (ResolveOverloadedFunctionForReferenceBinding(S
, Initializer
, cv2T2
, T2
,
4468 SourceLocation DeclLoc
= Initializer
->getBeginLoc();
4469 Sema::ReferenceCompareResult RefRelationship
4470 = S
.CompareReferenceRelationship(DeclLoc
, cv1T1
, cv2T2
);
4471 if (RefRelationship
>= Sema::Ref_Related
) {
4472 // Try to bind the reference here.
4473 TryReferenceInitializationCore(S
, Entity
, Kind
, Initializer
, cv1T1
, T1
,
4474 T1Quals
, cv2T2
, T2
, T2Quals
, Sequence
);
4476 Sequence
.RewrapReferenceInitList(cv1T1
, InitList
);
4480 // Update the initializer if we've resolved an overloaded function.
4481 if (Sequence
.step_begin() != Sequence
.step_end())
4482 Sequence
.RewrapReferenceInitList(cv1T1
, InitList
);
4484 // Perform address space compatibility check.
4485 QualType cv1T1IgnoreAS
= cv1T1
;
4486 if (T1Quals
.hasAddressSpace()) {
4488 (void)S
.Context
.getUnqualifiedArrayType(InitList
->getType(), T2Quals
);
4489 if (!T1Quals
.isAddressSpaceSupersetOf(T2Quals
)) {
4491 InitializationSequence::FK_ReferenceInitDropsQualifiers
);
4494 // Ignore address space of reference type at this point and perform address
4495 // space conversion after the reference binding step.
4497 S
.Context
.getQualifiedType(T1
, T1Quals
.withoutAddressSpace());
4499 // Not reference-related. Create a temporary and bind to that.
4500 InitializedEntity TempEntity
=
4501 InitializedEntity::InitializeTemporary(cv1T1IgnoreAS
);
4503 TryListInitialization(S
, TempEntity
, Kind
, InitList
, Sequence
,
4504 TreatUnavailableAsInvalid
);
4506 if (DestType
->isRValueReferenceType() ||
4507 (T1Quals
.hasConst() && !T1Quals
.hasVolatile())) {
4508 if (S
.getLangOpts().CPlusPlus20
&&
4509 isa
<IncompleteArrayType
>(T1
->getUnqualifiedDesugaredType()) &&
4510 DestType
->isRValueReferenceType()) {
4511 // C++20 [dcl.init.list]p3.10:
4512 // List-initialization of an object or reference of type T is defined as
4514 // ..., unless T is “reference to array of unknown bound of U”, in which
4515 // case the type of the prvalue is the type of x in the declaration U
4516 // x[] H, where H is the initializer list.
4517 Sequence
.AddQualificationConversionStep(cv1T1
, clang::VK_PRValue
);
4519 Sequence
.AddReferenceBindingStep(cv1T1IgnoreAS
,
4520 /*BindingTemporary=*/true);
4521 if (T1Quals
.hasAddressSpace())
4522 Sequence
.AddQualificationConversionStep(
4523 cv1T1
, DestType
->isRValueReferenceType() ? VK_XValue
: VK_LValue
);
4526 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary
);
4530 /// Attempt list initialization (C++0x [dcl.init.list])
4531 static void TryListInitialization(Sema
&S
,
4532 const InitializedEntity
&Entity
,
4533 const InitializationKind
&Kind
,
4534 InitListExpr
*InitList
,
4535 InitializationSequence
&Sequence
,
4536 bool TreatUnavailableAsInvalid
) {
4537 QualType DestType
= Entity
.getType();
4539 // C++ doesn't allow scalar initialization with more than one argument.
4540 // But C99 complex numbers are scalars and it makes sense there.
4541 if (S
.getLangOpts().CPlusPlus
&& DestType
->isScalarType() &&
4542 !DestType
->isAnyComplexType() && InitList
->getNumInits() > 1) {
4543 Sequence
.SetFailed(InitializationSequence::FK_TooManyInitsForScalar
);
4546 if (DestType
->isReferenceType()) {
4547 TryReferenceListInitialization(S
, Entity
, Kind
, InitList
, Sequence
,
4548 TreatUnavailableAsInvalid
);
4552 if (DestType
->isRecordType() &&
4553 !S
.isCompleteType(InitList
->getBeginLoc(), DestType
)) {
4554 Sequence
.setIncompleteTypeFailure(DestType
);
4558 // C++20 [dcl.init.list]p3:
4559 // - If the braced-init-list contains a designated-initializer-list, T shall
4560 // be an aggregate class. [...] Aggregate initialization is performed.
4562 // We allow arrays here too in order to support array designators.
4564 // FIXME: This check should precede the handling of reference initialization.
4565 // We follow other compilers in allowing things like 'Aggr &&a = {.x = 1};'
4566 // as a tentative DR resolution.
4567 bool IsDesignatedInit
= InitList
->hasDesignatedInit();
4568 if (!DestType
->isAggregateType() && IsDesignatedInit
) {
4570 InitializationSequence::FK_DesignatedInitForNonAggregate
);
4574 // C++11 [dcl.init.list]p3, per DR1467:
4575 // - If T is a class type and the initializer list has a single element of
4576 // type cv U, where U is T or a class derived from T, the object is
4577 // initialized from that element (by copy-initialization for
4578 // copy-list-initialization, or by direct-initialization for
4579 // direct-list-initialization).
4580 // - Otherwise, if T is a character array and the initializer list has a
4581 // single element that is an appropriately-typed string literal
4582 // (8.5.2 [dcl.init.string]), initialization is performed as described
4584 // - Otherwise, if T is an aggregate, [...] (continue below).
4585 if (S
.getLangOpts().CPlusPlus11
&& InitList
->getNumInits() == 1 &&
4586 !IsDesignatedInit
) {
4587 if (DestType
->isRecordType()) {
4588 QualType InitType
= InitList
->getInit(0)->getType();
4589 if (S
.Context
.hasSameUnqualifiedType(InitType
, DestType
) ||
4590 S
.IsDerivedFrom(InitList
->getBeginLoc(), InitType
, DestType
)) {
4591 Expr
*InitListAsExpr
= InitList
;
4592 TryConstructorInitialization(S
, Entity
, Kind
, InitListAsExpr
, DestType
,
4594 /*InitListSyntax*/false,
4595 /*IsInitListCopy*/true);
4599 if (const ArrayType
*DestAT
= S
.Context
.getAsArrayType(DestType
)) {
4600 Expr
*SubInit
[1] = {InitList
->getInit(0)};
4601 if (!isa
<VariableArrayType
>(DestAT
) &&
4602 IsStringInit(SubInit
[0], DestAT
, S
.Context
) == SIF_None
) {
4603 InitializationKind SubKind
=
4604 Kind
.getKind() == InitializationKind::IK_DirectList
4605 ? InitializationKind::CreateDirect(Kind
.getLocation(),
4606 InitList
->getLBraceLoc(),
4607 InitList
->getRBraceLoc())
4609 Sequence
.InitializeFrom(S
, Entity
, SubKind
, SubInit
,
4610 /*TopLevelOfInitList*/ true,
4611 TreatUnavailableAsInvalid
);
4613 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4614 // the element is not an appropriately-typed string literal, in which
4615 // case we should proceed as in C++11 (below).
4617 Sequence
.RewrapReferenceInitList(Entity
.getType(), InitList
);
4624 // C++11 [dcl.init.list]p3:
4625 // - If T is an aggregate, aggregate initialization is performed.
4626 if ((DestType
->isRecordType() && !DestType
->isAggregateType()) ||
4627 (S
.getLangOpts().CPlusPlus11
&&
4628 S
.isStdInitializerList(DestType
, nullptr) && !IsDesignatedInit
)) {
4629 if (S
.getLangOpts().CPlusPlus11
) {
4630 // - Otherwise, if the initializer list has no elements and T is a
4631 // class type with a default constructor, the object is
4632 // value-initialized.
4633 if (InitList
->getNumInits() == 0) {
4634 CXXRecordDecl
*RD
= DestType
->getAsCXXRecordDecl();
4635 if (S
.LookupDefaultConstructor(RD
)) {
4636 TryValueInitialization(S
, Entity
, Kind
, Sequence
, InitList
);
4641 // - Otherwise, if T is a specialization of std::initializer_list<E>,
4642 // an initializer_list object constructed [...]
4643 if (TryInitializerListConstruction(S
, InitList
, DestType
, Sequence
,
4644 TreatUnavailableAsInvalid
))
4647 // - Otherwise, if T is a class type, constructors are considered.
4648 Expr
*InitListAsExpr
= InitList
;
4649 TryConstructorInitialization(S
, Entity
, Kind
, InitListAsExpr
, DestType
,
4650 DestType
, Sequence
, /*InitListSyntax*/true);
4652 Sequence
.SetFailed(InitializationSequence::FK_InitListBadDestinationType
);
4656 if (S
.getLangOpts().CPlusPlus
&& !DestType
->isAggregateType() &&
4657 InitList
->getNumInits() == 1) {
4658 Expr
*E
= InitList
->getInit(0);
4660 // - Otherwise, if T is an enumeration with a fixed underlying type,
4661 // the initializer-list has a single element v, and the initialization
4662 // is direct-list-initialization, the object is initialized with the
4663 // value T(v); if a narrowing conversion is required to convert v to
4664 // the underlying type of T, the program is ill-formed.
4665 auto *ET
= DestType
->getAs
<EnumType
>();
4666 if (S
.getLangOpts().CPlusPlus17
&&
4667 Kind
.getKind() == InitializationKind::IK_DirectList
&&
4668 ET
&& ET
->getDecl()->isFixed() &&
4669 !S
.Context
.hasSameUnqualifiedType(E
->getType(), DestType
) &&
4670 (E
->getType()->isIntegralOrUnscopedEnumerationType() ||
4671 E
->getType()->isFloatingType())) {
4672 // There are two ways that T(v) can work when T is an enumeration type.
4673 // If there is either an implicit conversion sequence from v to T or
4674 // a conversion function that can convert from v to T, then we use that.
4675 // Otherwise, if v is of integral, unscoped enumeration, or floating-point
4676 // type, it is converted to the enumeration type via its underlying type.
4677 // There is no overlap possible between these two cases (except when the
4678 // source value is already of the destination type), and the first
4679 // case is handled by the general case for single-element lists below.
4680 ImplicitConversionSequence ICS
;
4682 ICS
.Standard
.setAsIdentityConversion();
4683 if (!E
->isPRValue())
4684 ICS
.Standard
.First
= ICK_Lvalue_To_Rvalue
;
4685 // If E is of a floating-point type, then the conversion is ill-formed
4686 // due to narrowing, but go through the motions in order to produce the
4687 // right diagnostic.
4688 ICS
.Standard
.Second
= E
->getType()->isFloatingType()
4689 ? ICK_Floating_Integral
4690 : ICK_Integral_Conversion
;
4691 ICS
.Standard
.setFromType(E
->getType());
4692 ICS
.Standard
.setToType(0, E
->getType());
4693 ICS
.Standard
.setToType(1, DestType
);
4694 ICS
.Standard
.setToType(2, DestType
);
4695 Sequence
.AddConversionSequenceStep(ICS
, ICS
.Standard
.getToType(2),
4696 /*TopLevelOfInitList*/true);
4697 Sequence
.RewrapReferenceInitList(Entity
.getType(), InitList
);
4701 // - Otherwise, if the initializer list has a single element of type E
4702 // [...references are handled above...], the object or reference is
4703 // initialized from that element (by copy-initialization for
4704 // copy-list-initialization, or by direct-initialization for
4705 // direct-list-initialization); if a narrowing conversion is required
4706 // to convert the element to T, the program is ill-formed.
4708 // Per core-24034, this is direct-initialization if we were performing
4709 // direct-list-initialization and copy-initialization otherwise.
4710 // We can't use InitListChecker for this, because it always performs
4711 // copy-initialization. This only matters if we might use an 'explicit'
4712 // conversion operator, or for the special case conversion of nullptr_t to
4713 // bool, so we only need to handle those cases.
4715 // FIXME: Why not do this in all cases?
4716 Expr
*Init
= InitList
->getInit(0);
4717 if (Init
->getType()->isRecordType() ||
4718 (Init
->getType()->isNullPtrType() && DestType
->isBooleanType())) {
4719 InitializationKind SubKind
=
4720 Kind
.getKind() == InitializationKind::IK_DirectList
4721 ? InitializationKind::CreateDirect(Kind
.getLocation(),
4722 InitList
->getLBraceLoc(),
4723 InitList
->getRBraceLoc())
4725 Expr
*SubInit
[1] = { Init
};
4726 Sequence
.InitializeFrom(S
, Entity
, SubKind
, SubInit
,
4727 /*TopLevelOfInitList*/true,
4728 TreatUnavailableAsInvalid
);
4730 Sequence
.RewrapReferenceInitList(Entity
.getType(), InitList
);
4735 InitListChecker
CheckInitList(S
, Entity
, InitList
,
4736 DestType
, /*VerifyOnly=*/true, TreatUnavailableAsInvalid
);
4737 if (CheckInitList
.HadError()) {
4738 Sequence
.SetFailed(InitializationSequence::FK_ListInitializationFailed
);
4742 // Add the list initialization step with the built init list.
4743 Sequence
.AddListInitializationStep(DestType
);
4746 /// Try a reference initialization that involves calling a conversion
4748 static OverloadingResult
TryRefInitWithConversionFunction(
4749 Sema
&S
, const InitializedEntity
&Entity
, const InitializationKind
&Kind
,
4750 Expr
*Initializer
, bool AllowRValues
, bool IsLValueRef
,
4751 InitializationSequence
&Sequence
) {
4752 QualType DestType
= Entity
.getType();
4753 QualType cv1T1
= DestType
->castAs
<ReferenceType
>()->getPointeeType();
4754 QualType T1
= cv1T1
.getUnqualifiedType();
4755 QualType cv2T2
= Initializer
->getType();
4756 QualType T2
= cv2T2
.getUnqualifiedType();
4758 assert(!S
.CompareReferenceRelationship(Initializer
->getBeginLoc(), T1
, T2
) &&
4759 "Must have incompatible references when binding via conversion");
4761 // Build the candidate set directly in the initialization sequence
4762 // structure, so that it will persist if we fail.
4763 OverloadCandidateSet
&CandidateSet
= Sequence
.getFailedCandidateSet();
4764 CandidateSet
.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion
);
4766 // Determine whether we are allowed to call explicit conversion operators.
4767 // Note that none of [over.match.copy], [over.match.conv], nor
4768 // [over.match.ref] permit an explicit constructor to be chosen when
4769 // initializing a reference, not even for direct-initialization.
4770 bool AllowExplicitCtors
= false;
4771 bool AllowExplicitConvs
= Kind
.allowExplicitConversionFunctionsInRefBinding();
4773 const RecordType
*T1RecordType
= nullptr;
4774 if (AllowRValues
&& (T1RecordType
= T1
->getAs
<RecordType
>()) &&
4775 S
.isCompleteType(Kind
.getLocation(), T1
)) {
4776 // The type we're converting to is a class type. Enumerate its constructors
4777 // to see if there is a suitable conversion.
4778 CXXRecordDecl
*T1RecordDecl
= cast
<CXXRecordDecl
>(T1RecordType
->getDecl());
4780 for (NamedDecl
*D
: S
.LookupConstructors(T1RecordDecl
)) {
4781 auto Info
= getConstructorInfo(D
);
4782 if (!Info
.Constructor
)
4785 if (!Info
.Constructor
->isInvalidDecl() &&
4786 Info
.Constructor
->isConvertingConstructor(/*AllowExplicit*/true)) {
4787 if (Info
.ConstructorTmpl
)
4788 S
.AddTemplateOverloadCandidate(
4789 Info
.ConstructorTmpl
, Info
.FoundDecl
,
4790 /*ExplicitArgs*/ nullptr, Initializer
, CandidateSet
,
4791 /*SuppressUserConversions=*/true,
4792 /*PartialOverloading*/ false, AllowExplicitCtors
);
4794 S
.AddOverloadCandidate(
4795 Info
.Constructor
, Info
.FoundDecl
, Initializer
, CandidateSet
,
4796 /*SuppressUserConversions=*/true,
4797 /*PartialOverloading*/ false, AllowExplicitCtors
);
4801 if (T1RecordType
&& T1RecordType
->getDecl()->isInvalidDecl())
4802 return OR_No_Viable_Function
;
4804 const RecordType
*T2RecordType
= nullptr;
4805 if ((T2RecordType
= T2
->getAs
<RecordType
>()) &&
4806 S
.isCompleteType(Kind
.getLocation(), T2
)) {
4807 // The type we're converting from is a class type, enumerate its conversion
4809 CXXRecordDecl
*T2RecordDecl
= cast
<CXXRecordDecl
>(T2RecordType
->getDecl());
4811 const auto &Conversions
= T2RecordDecl
->getVisibleConversionFunctions();
4812 for (auto I
= Conversions
.begin(), E
= Conversions
.end(); I
!= E
; ++I
) {
4814 CXXRecordDecl
*ActingDC
= cast
<CXXRecordDecl
>(D
->getDeclContext());
4815 if (isa
<UsingShadowDecl
>(D
))
4816 D
= cast
<UsingShadowDecl
>(D
)->getTargetDecl();
4818 FunctionTemplateDecl
*ConvTemplate
= dyn_cast
<FunctionTemplateDecl
>(D
);
4819 CXXConversionDecl
*Conv
;
4821 Conv
= cast
<CXXConversionDecl
>(ConvTemplate
->getTemplatedDecl());
4823 Conv
= cast
<CXXConversionDecl
>(D
);
4825 // If the conversion function doesn't return a reference type,
4826 // it can't be considered for this conversion unless we're allowed to
4827 // consider rvalues.
4828 // FIXME: Do we need to make sure that we only consider conversion
4829 // candidates with reference-compatible results? That might be needed to
4831 if ((AllowRValues
||
4832 Conv
->getConversionType()->isLValueReferenceType())) {
4834 S
.AddTemplateConversionCandidate(
4835 ConvTemplate
, I
.getPair(), ActingDC
, Initializer
, DestType
,
4837 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs
);
4839 S
.AddConversionCandidate(
4840 Conv
, I
.getPair(), ActingDC
, Initializer
, DestType
, CandidateSet
,
4841 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs
);
4845 if (T2RecordType
&& T2RecordType
->getDecl()->isInvalidDecl())
4846 return OR_No_Viable_Function
;
4848 SourceLocation DeclLoc
= Initializer
->getBeginLoc();
4850 // Perform overload resolution. If it fails, return the failed result.
4851 OverloadCandidateSet::iterator Best
;
4852 if (OverloadingResult Result
4853 = CandidateSet
.BestViableFunction(S
, DeclLoc
, Best
))
4856 FunctionDecl
*Function
= Best
->Function
;
4857 // This is the overload that will be used for this initialization step if we
4858 // use this initialization. Mark it as referenced.
4859 Function
->setReferenced();
4861 // Compute the returned type and value kind of the conversion.
4863 if (isa
<CXXConversionDecl
>(Function
))
4864 cv3T3
= Function
->getReturnType();
4868 ExprValueKind VK
= VK_PRValue
;
4869 if (cv3T3
->isLValueReferenceType())
4871 else if (const auto *RRef
= cv3T3
->getAs
<RValueReferenceType
>())
4872 VK
= RRef
->getPointeeType()->isFunctionType() ? VK_LValue
: VK_XValue
;
4873 cv3T3
= cv3T3
.getNonLValueExprType(S
.Context
);
4875 // Add the user-defined conversion step.
4876 bool HadMultipleCandidates
= (CandidateSet
.size() > 1);
4877 Sequence
.AddUserConversionStep(Function
, Best
->FoundDecl
, cv3T3
,
4878 HadMultipleCandidates
);
4880 // Determine whether we'll need to perform derived-to-base adjustments or
4881 // other conversions.
4882 Sema::ReferenceConversions RefConv
;
4883 Sema::ReferenceCompareResult NewRefRelationship
=
4884 S
.CompareReferenceRelationship(DeclLoc
, T1
, cv3T3
, &RefConv
);
4886 // Add the final conversion sequence, if necessary.
4887 if (NewRefRelationship
== Sema::Ref_Incompatible
) {
4888 assert(!isa
<CXXConstructorDecl
>(Function
) &&
4889 "should not have conversion after constructor");
4891 ImplicitConversionSequence ICS
;
4893 ICS
.Standard
= Best
->FinalConversion
;
4894 Sequence
.AddConversionSequenceStep(ICS
, ICS
.Standard
.getToType(2));
4896 // Every implicit conversion results in a prvalue, except for a glvalue
4897 // derived-to-base conversion, which we handle below.
4898 cv3T3
= ICS
.Standard
.getToType(2);
4902 // If the converted initializer is a prvalue, its type T4 is adjusted to
4903 // type "cv1 T4" and the temporary materialization conversion is applied.
4905 // We adjust the cv-qualifications to match the reference regardless of
4906 // whether we have a prvalue so that the AST records the change. In this
4907 // case, T4 is "cv3 T3".
4908 QualType cv1T4
= S
.Context
.getQualifiedType(cv3T3
, cv1T1
.getQualifiers());
4909 if (cv1T4
.getQualifiers() != cv3T3
.getQualifiers())
4910 Sequence
.AddQualificationConversionStep(cv1T4
, VK
);
4911 Sequence
.AddReferenceBindingStep(cv1T4
, VK
== VK_PRValue
);
4912 VK
= IsLValueRef
? VK_LValue
: VK_XValue
;
4914 if (RefConv
& Sema::ReferenceConversions::DerivedToBase
)
4915 Sequence
.AddDerivedToBaseCastStep(cv1T1
, VK
);
4916 else if (RefConv
& Sema::ReferenceConversions::ObjC
)
4917 Sequence
.AddObjCObjectConversionStep(cv1T1
);
4918 else if (RefConv
& Sema::ReferenceConversions::Function
)
4919 Sequence
.AddFunctionReferenceConversionStep(cv1T1
);
4920 else if (RefConv
& Sema::ReferenceConversions::Qualification
) {
4921 if (!S
.Context
.hasSameType(cv1T4
, cv1T1
))
4922 Sequence
.AddQualificationConversionStep(cv1T1
, VK
);
4928 static void CheckCXX98CompatAccessibleCopy(Sema
&S
,
4929 const InitializedEntity
&Entity
,
4932 /// Attempt reference initialization (C++0x [dcl.init.ref])
4933 static void TryReferenceInitialization(Sema
&S
,
4934 const InitializedEntity
&Entity
,
4935 const InitializationKind
&Kind
,
4937 InitializationSequence
&Sequence
) {
4938 QualType DestType
= Entity
.getType();
4939 QualType cv1T1
= DestType
->castAs
<ReferenceType
>()->getPointeeType();
4941 QualType T1
= S
.Context
.getUnqualifiedArrayType(cv1T1
, T1Quals
);
4942 QualType cv2T2
= S
.getCompletedType(Initializer
);
4944 QualType T2
= S
.Context
.getUnqualifiedArrayType(cv2T2
, T2Quals
);
4946 // If the initializer is the address of an overloaded function, try
4947 // to resolve the overloaded function. If all goes well, T2 is the
4948 // type of the resulting function.
4949 if (ResolveOverloadedFunctionForReferenceBinding(S
, Initializer
, cv2T2
, T2
,
4953 // Delegate everything else to a subfunction.
4954 TryReferenceInitializationCore(S
, Entity
, Kind
, Initializer
, cv1T1
, T1
,
4955 T1Quals
, cv2T2
, T2
, T2Quals
, Sequence
);
4958 /// Determine whether an expression is a non-referenceable glvalue (one to
4959 /// which a reference can never bind). Attempting to bind a reference to
4960 /// such a glvalue will always create a temporary.
4961 static bool isNonReferenceableGLValue(Expr
*E
) {
4962 return E
->refersToBitField() || E
->refersToVectorElement() ||
4963 E
->refersToMatrixElement();
4966 /// Reference initialization without resolving overloaded functions.
4968 /// We also can get here in C if we call a builtin which is declared as
4969 /// a function with a parameter of reference type (such as __builtin_va_end()).
4970 static void TryReferenceInitializationCore(Sema
&S
,
4971 const InitializedEntity
&Entity
,
4972 const InitializationKind
&Kind
,
4974 QualType cv1T1
, QualType T1
,
4976 QualType cv2T2
, QualType T2
,
4978 InitializationSequence
&Sequence
) {
4979 QualType DestType
= Entity
.getType();
4980 SourceLocation DeclLoc
= Initializer
->getBeginLoc();
4982 // Compute some basic properties of the types and the initializer.
4983 bool isLValueRef
= DestType
->isLValueReferenceType();
4984 bool isRValueRef
= !isLValueRef
;
4985 Expr::Classification InitCategory
= Initializer
->Classify(S
.Context
);
4987 Sema::ReferenceConversions RefConv
;
4988 Sema::ReferenceCompareResult RefRelationship
=
4989 S
.CompareReferenceRelationship(DeclLoc
, cv1T1
, cv2T2
, &RefConv
);
4991 // C++0x [dcl.init.ref]p5:
4992 // A reference to type "cv1 T1" is initialized by an expression of type
4993 // "cv2 T2" as follows:
4995 // - If the reference is an lvalue reference and the initializer
4997 // Note the analogous bullet points for rvalue refs to functions. Because
4998 // there are no function rvalues in C++, rvalue refs to functions are treated
4999 // like lvalue refs.
5000 OverloadingResult ConvOvlResult
= OR_Success
;
5001 bool T1Function
= T1
->isFunctionType();
5002 if (isLValueRef
|| T1Function
) {
5003 if (InitCategory
.isLValue() && !isNonReferenceableGLValue(Initializer
) &&
5004 (RefRelationship
== Sema::Ref_Compatible
||
5005 (Kind
.isCStyleOrFunctionalCast() &&
5006 RefRelationship
== Sema::Ref_Related
))) {
5007 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
5008 // reference-compatible with "cv2 T2," or
5009 if (RefConv
& (Sema::ReferenceConversions::DerivedToBase
|
5010 Sema::ReferenceConversions::ObjC
)) {
5011 // If we're converting the pointee, add any qualifiers first;
5012 // these qualifiers must all be top-level, so just convert to "cv1 T2".
5013 if (RefConv
& (Sema::ReferenceConversions::Qualification
))
5014 Sequence
.AddQualificationConversionStep(
5015 S
.Context
.getQualifiedType(T2
, T1Quals
),
5016 Initializer
->getValueKind());
5017 if (RefConv
& Sema::ReferenceConversions::DerivedToBase
)
5018 Sequence
.AddDerivedToBaseCastStep(cv1T1
, VK_LValue
);
5020 Sequence
.AddObjCObjectConversionStep(cv1T1
);
5021 } else if (RefConv
& Sema::ReferenceConversions::Qualification
) {
5022 // Perform a (possibly multi-level) qualification conversion.
5023 Sequence
.AddQualificationConversionStep(cv1T1
,
5024 Initializer
->getValueKind());
5025 } else if (RefConv
& Sema::ReferenceConversions::Function
) {
5026 Sequence
.AddFunctionReferenceConversionStep(cv1T1
);
5029 // We only create a temporary here when binding a reference to a
5030 // bit-field or vector element. Those cases are't supposed to be
5031 // handled by this bullet, but the outcome is the same either way.
5032 Sequence
.AddReferenceBindingStep(cv1T1
, false);
5036 // - has a class type (i.e., T2 is a class type), where T1 is not
5037 // reference-related to T2, and can be implicitly converted to an
5038 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
5039 // with "cv3 T3" (this conversion is selected by enumerating the
5040 // applicable conversion functions (13.3.1.6) and choosing the best
5041 // one through overload resolution (13.3)),
5042 // If we have an rvalue ref to function type here, the rhs must be
5043 // an rvalue. DR1287 removed the "implicitly" here.
5044 if (RefRelationship
== Sema::Ref_Incompatible
&& T2
->isRecordType() &&
5045 (isLValueRef
|| InitCategory
.isRValue())) {
5046 if (S
.getLangOpts().CPlusPlus
) {
5047 // Try conversion functions only for C++.
5048 ConvOvlResult
= TryRefInitWithConversionFunction(
5049 S
, Entity
, Kind
, Initializer
, /*AllowRValues*/ isRValueRef
,
5050 /*IsLValueRef*/ isLValueRef
, Sequence
);
5051 if (ConvOvlResult
== OR_Success
)
5053 if (ConvOvlResult
!= OR_No_Viable_Function
)
5054 Sequence
.SetOverloadFailure(
5055 InitializationSequence::FK_ReferenceInitOverloadFailed
,
5058 ConvOvlResult
= OR_No_Viable_Function
;
5063 // - Otherwise, the reference shall be an lvalue reference to a
5064 // non-volatile const type (i.e., cv1 shall be const), or the reference
5065 // shall be an rvalue reference.
5066 // For address spaces, we interpret this to mean that an addr space
5067 // of a reference "cv1 T1" is a superset of addr space of "cv2 T2".
5068 if (isLValueRef
&& !(T1Quals
.hasConst() && !T1Quals
.hasVolatile() &&
5069 T1Quals
.isAddressSpaceSupersetOf(T2Quals
))) {
5070 if (S
.Context
.getCanonicalType(T2
) == S
.Context
.OverloadTy
)
5071 Sequence
.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed
);
5072 else if (ConvOvlResult
&& !Sequence
.getFailedCandidateSet().empty())
5073 Sequence
.SetOverloadFailure(
5074 InitializationSequence::FK_ReferenceInitOverloadFailed
,
5076 else if (!InitCategory
.isLValue())
5078 T1Quals
.isAddressSpaceSupersetOf(T2Quals
)
5079 ? InitializationSequence::
5080 FK_NonConstLValueReferenceBindingToTemporary
5081 : InitializationSequence::FK_ReferenceInitDropsQualifiers
);
5083 InitializationSequence::FailureKind FK
;
5084 switch (RefRelationship
) {
5085 case Sema::Ref_Compatible
:
5086 if (Initializer
->refersToBitField())
5087 FK
= InitializationSequence::
5088 FK_NonConstLValueReferenceBindingToBitfield
;
5089 else if (Initializer
->refersToVectorElement())
5090 FK
= InitializationSequence::
5091 FK_NonConstLValueReferenceBindingToVectorElement
;
5092 else if (Initializer
->refersToMatrixElement())
5093 FK
= InitializationSequence::
5094 FK_NonConstLValueReferenceBindingToMatrixElement
;
5096 llvm_unreachable("unexpected kind of compatible initializer");
5098 case Sema::Ref_Related
:
5099 FK
= InitializationSequence::FK_ReferenceInitDropsQualifiers
;
5101 case Sema::Ref_Incompatible
:
5102 FK
= InitializationSequence::
5103 FK_NonConstLValueReferenceBindingToUnrelated
;
5106 Sequence
.SetFailed(FK
);
5111 // - If the initializer expression
5113 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
5114 // [1z] rvalue (but not a bit-field) or
5115 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
5117 // Note: functions are handled above and below rather than here...
5119 (RefRelationship
== Sema::Ref_Compatible
||
5120 (Kind
.isCStyleOrFunctionalCast() &&
5121 RefRelationship
== Sema::Ref_Related
)) &&
5122 ((InitCategory
.isXValue() && !isNonReferenceableGLValue(Initializer
)) ||
5123 (InitCategory
.isPRValue() &&
5124 (S
.getLangOpts().CPlusPlus17
|| T2
->isRecordType() ||
5125 T2
->isArrayType())))) {
5126 ExprValueKind ValueKind
= InitCategory
.isXValue() ? VK_XValue
: VK_PRValue
;
5127 if (InitCategory
.isPRValue() && T2
->isRecordType()) {
5128 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
5129 // compiler the freedom to perform a copy here or bind to the
5130 // object, while C++0x requires that we bind directly to the
5131 // object. Hence, we always bind to the object without making an
5132 // extra copy. However, in C++03 requires that we check for the
5133 // presence of a suitable copy constructor:
5135 // The constructor that would be used to make the copy shall
5136 // be callable whether or not the copy is actually done.
5137 if (!S
.getLangOpts().CPlusPlus11
&& !S
.getLangOpts().MicrosoftExt
)
5138 Sequence
.AddExtraneousCopyToTemporary(cv2T2
);
5139 else if (S
.getLangOpts().CPlusPlus11
)
5140 CheckCXX98CompatAccessibleCopy(S
, Entity
, Initializer
);
5143 // C++1z [dcl.init.ref]/5.2.1.2:
5144 // If the converted initializer is a prvalue, its type T4 is adjusted
5145 // to type "cv1 T4" and the temporary materialization conversion is
5147 // Postpone address space conversions to after the temporary materialization
5148 // conversion to allow creating temporaries in the alloca address space.
5149 auto T1QualsIgnoreAS
= T1Quals
;
5150 auto T2QualsIgnoreAS
= T2Quals
;
5151 if (T1Quals
.getAddressSpace() != T2Quals
.getAddressSpace()) {
5152 T1QualsIgnoreAS
.removeAddressSpace();
5153 T2QualsIgnoreAS
.removeAddressSpace();
5155 QualType cv1T4
= S
.Context
.getQualifiedType(cv2T2
, T1QualsIgnoreAS
);
5156 if (T1QualsIgnoreAS
!= T2QualsIgnoreAS
)
5157 Sequence
.AddQualificationConversionStep(cv1T4
, ValueKind
);
5158 Sequence
.AddReferenceBindingStep(cv1T4
, ValueKind
== VK_PRValue
);
5159 ValueKind
= isLValueRef
? VK_LValue
: VK_XValue
;
5160 // Add addr space conversion if required.
5161 if (T1Quals
.getAddressSpace() != T2Quals
.getAddressSpace()) {
5162 auto T4Quals
= cv1T4
.getQualifiers();
5163 T4Quals
.addAddressSpace(T1Quals
.getAddressSpace());
5164 QualType cv1T4WithAS
= S
.Context
.getQualifiedType(T2
, T4Quals
);
5165 Sequence
.AddQualificationConversionStep(cv1T4WithAS
, ValueKind
);
5166 cv1T4
= cv1T4WithAS
;
5169 // In any case, the reference is bound to the resulting glvalue (or to
5170 // an appropriate base class subobject).
5171 if (RefConv
& Sema::ReferenceConversions::DerivedToBase
)
5172 Sequence
.AddDerivedToBaseCastStep(cv1T1
, ValueKind
);
5173 else if (RefConv
& Sema::ReferenceConversions::ObjC
)
5174 Sequence
.AddObjCObjectConversionStep(cv1T1
);
5175 else if (RefConv
& Sema::ReferenceConversions::Qualification
) {
5176 if (!S
.Context
.hasSameType(cv1T4
, cv1T1
))
5177 Sequence
.AddQualificationConversionStep(cv1T1
, ValueKind
);
5182 // - has a class type (i.e., T2 is a class type), where T1 is not
5183 // reference-related to T2, and can be implicitly converted to an
5184 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
5185 // where "cv1 T1" is reference-compatible with "cv3 T3",
5187 // DR1287 removes the "implicitly" here.
5188 if (T2
->isRecordType()) {
5189 if (RefRelationship
== Sema::Ref_Incompatible
) {
5190 ConvOvlResult
= TryRefInitWithConversionFunction(
5191 S
, Entity
, Kind
, Initializer
, /*AllowRValues*/ true,
5192 /*IsLValueRef*/ isLValueRef
, Sequence
);
5194 Sequence
.SetOverloadFailure(
5195 InitializationSequence::FK_ReferenceInitOverloadFailed
,
5201 if (RefRelationship
== Sema::Ref_Compatible
&&
5202 isRValueRef
&& InitCategory
.isLValue()) {
5204 InitializationSequence::FK_RValueReferenceBindingToLValue
);
5208 Sequence
.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers
);
5212 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
5213 // from the initializer expression using the rules for a non-reference
5214 // copy-initialization (8.5). The reference is then bound to the
5217 // Ignore address space of reference type at this point and perform address
5218 // space conversion after the reference binding step.
5219 QualType cv1T1IgnoreAS
=
5220 T1Quals
.hasAddressSpace()
5221 ? S
.Context
.getQualifiedType(T1
, T1Quals
.withoutAddressSpace())
5224 InitializedEntity TempEntity
=
5225 InitializedEntity::InitializeTemporary(cv1T1IgnoreAS
);
5227 // FIXME: Why do we use an implicit conversion here rather than trying
5228 // copy-initialization?
5229 ImplicitConversionSequence ICS
5230 = S
.TryImplicitConversion(Initializer
, TempEntity
.getType(),
5231 /*SuppressUserConversions=*/false,
5232 Sema::AllowedExplicit::None
,
5233 /*FIXME:InOverloadResolution=*/false,
5234 /*CStyle=*/Kind
.isCStyleOrFunctionalCast(),
5235 /*AllowObjCWritebackConversion=*/false);
5238 // FIXME: Use the conversion function set stored in ICS to turn
5239 // this into an overloading ambiguity diagnostic. However, we need
5240 // to keep that set as an OverloadCandidateSet rather than as some
5241 // other kind of set.
5242 if (ConvOvlResult
&& !Sequence
.getFailedCandidateSet().empty())
5243 Sequence
.SetOverloadFailure(
5244 InitializationSequence::FK_ReferenceInitOverloadFailed
,
5246 else if (S
.Context
.getCanonicalType(T2
) == S
.Context
.OverloadTy
)
5247 Sequence
.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed
);
5249 Sequence
.SetFailed(InitializationSequence::FK_ReferenceInitFailed
);
5252 Sequence
.AddConversionSequenceStep(ICS
, TempEntity
.getType());
5255 // [...] If T1 is reference-related to T2, cv1 must be the
5256 // same cv-qualification as, or greater cv-qualification
5257 // than, cv2; otherwise, the program is ill-formed.
5258 unsigned T1CVRQuals
= T1Quals
.getCVRQualifiers();
5259 unsigned T2CVRQuals
= T2Quals
.getCVRQualifiers();
5260 if (RefRelationship
== Sema::Ref_Related
&&
5261 ((T1CVRQuals
| T2CVRQuals
) != T1CVRQuals
||
5262 !T1Quals
.isAddressSpaceSupersetOf(T2Quals
))) {
5263 Sequence
.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers
);
5267 // [...] If T1 is reference-related to T2 and the reference is an rvalue
5268 // reference, the initializer expression shall not be an lvalue.
5269 if (RefRelationship
>= Sema::Ref_Related
&& !isLValueRef
&&
5270 InitCategory
.isLValue()) {
5272 InitializationSequence::FK_RValueReferenceBindingToLValue
);
5276 Sequence
.AddReferenceBindingStep(cv1T1IgnoreAS
, /*BindingTemporary=*/true);
5278 if (T1Quals
.hasAddressSpace()) {
5279 if (!Qualifiers::isAddressSpaceSupersetOf(T1Quals
.getAddressSpace(),
5282 InitializationSequence::FK_ReferenceAddrspaceMismatchTemporary
);
5285 Sequence
.AddQualificationConversionStep(cv1T1
, isLValueRef
? VK_LValue
5290 /// Attempt character array initialization from a string literal
5291 /// (C++ [dcl.init.string], C99 6.7.8).
5292 static void TryStringLiteralInitialization(Sema
&S
,
5293 const InitializedEntity
&Entity
,
5294 const InitializationKind
&Kind
,
5296 InitializationSequence
&Sequence
) {
5297 Sequence
.AddStringInitStep(Entity
.getType());
5300 /// Attempt value initialization (C++ [dcl.init]p7).
5301 static void TryValueInitialization(Sema
&S
,
5302 const InitializedEntity
&Entity
,
5303 const InitializationKind
&Kind
,
5304 InitializationSequence
&Sequence
,
5305 InitListExpr
*InitList
) {
5306 assert((!InitList
|| InitList
->getNumInits() == 0) &&
5307 "Shouldn't use value-init for non-empty init lists");
5309 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
5311 // To value-initialize an object of type T means:
5312 QualType T
= Entity
.getType();
5314 // -- if T is an array type, then each element is value-initialized;
5315 T
= S
.Context
.getBaseElementType(T
);
5317 if (const RecordType
*RT
= T
->getAs
<RecordType
>()) {
5318 if (CXXRecordDecl
*ClassDecl
= dyn_cast
<CXXRecordDecl
>(RT
->getDecl())) {
5319 bool NeedZeroInitialization
= true;
5321 // -- if T is a class type (clause 9) with a user-declared constructor
5322 // (12.1), then the default constructor for T is called (and the
5323 // initialization is ill-formed if T has no accessible default
5326 // -- if T is a class type (clause 9) with either no default constructor
5327 // (12.1 [class.ctor]) or a default constructor that is user-provided
5328 // or deleted, then the object is default-initialized;
5330 // Note that the C++11 rule is the same as the C++98 rule if there are no
5331 // defaulted or deleted constructors, so we just use it unconditionally.
5332 CXXConstructorDecl
*CD
= S
.LookupDefaultConstructor(ClassDecl
);
5333 if (!CD
|| !CD
->getCanonicalDecl()->isDefaulted() || CD
->isDeleted())
5334 NeedZeroInitialization
= false;
5336 // -- if T is a (possibly cv-qualified) non-union class type without a
5337 // user-provided or deleted default constructor, then the object is
5338 // zero-initialized and, if T has a non-trivial default constructor,
5339 // default-initialized;
5340 // The 'non-union' here was removed by DR1502. The 'non-trivial default
5341 // constructor' part was removed by DR1507.
5342 if (NeedZeroInitialization
)
5343 Sequence
.AddZeroInitializationStep(Entity
.getType());
5346 // -- if T is a non-union class type without a user-declared constructor,
5347 // then every non-static data member and base class component of T is
5348 // value-initialized;
5349 // [...] A program that calls for [...] value-initialization of an
5350 // entity of reference type is ill-formed.
5352 // C++11 doesn't need this handling, because value-initialization does not
5353 // occur recursively there, and the implicit default constructor is
5354 // defined as deleted in the problematic cases.
5355 if (!S
.getLangOpts().CPlusPlus11
&&
5356 ClassDecl
->hasUninitializedReferenceMember()) {
5357 Sequence
.SetFailed(InitializationSequence::FK_TooManyInitsForReference
);
5361 // If this is list-value-initialization, pass the empty init list on when
5362 // building the constructor call. This affects the semantics of a few
5363 // things (such as whether an explicit default constructor can be called).
5364 Expr
*InitListAsExpr
= InitList
;
5365 MultiExprArg
Args(&InitListAsExpr
, InitList
? 1 : 0);
5366 bool InitListSyntax
= InitList
;
5368 // FIXME: Instead of creating a CXXConstructExpr of array type here,
5369 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
5370 return TryConstructorInitialization(
5371 S
, Entity
, Kind
, Args
, T
, Entity
.getType(), Sequence
, InitListSyntax
);
5375 Sequence
.AddZeroInitializationStep(Entity
.getType());
5378 /// Attempt default initialization (C++ [dcl.init]p6).
5379 static void TryDefaultInitialization(Sema
&S
,
5380 const InitializedEntity
&Entity
,
5381 const InitializationKind
&Kind
,
5382 InitializationSequence
&Sequence
) {
5383 assert(Kind
.getKind() == InitializationKind::IK_Default
);
5385 // C++ [dcl.init]p6:
5386 // To default-initialize an object of type T means:
5387 // - if T is an array type, each element is default-initialized;
5388 QualType DestType
= S
.Context
.getBaseElementType(Entity
.getType());
5390 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
5391 // constructor for T is called (and the initialization is ill-formed if
5392 // T has no accessible default constructor);
5393 if (DestType
->isRecordType() && S
.getLangOpts().CPlusPlus
) {
5394 TryConstructorInitialization(S
, Entity
, Kind
, std::nullopt
, DestType
,
5395 Entity
.getType(), Sequence
);
5399 // - otherwise, no initialization is performed.
5401 // If a program calls for the default initialization of an object of
5402 // a const-qualified type T, T shall be a class type with a user-provided
5403 // default constructor.
5404 if (DestType
.isConstQualified() && S
.getLangOpts().CPlusPlus
) {
5405 if (!maybeRecoverWithZeroInitialization(S
, Sequence
, Entity
))
5406 Sequence
.SetFailed(InitializationSequence::FK_DefaultInitOfConst
);
5410 // If the destination type has a lifetime property, zero-initialize it.
5411 if (DestType
.getQualifiers().hasObjCLifetime()) {
5412 Sequence
.AddZeroInitializationStep(Entity
.getType());
5417 static void TryOrBuildParenListInitialization(
5418 Sema
&S
, const InitializedEntity
&Entity
, const InitializationKind
&Kind
,
5419 ArrayRef
<Expr
*> Args
, InitializationSequence
&Sequence
, bool VerifyOnly
,
5420 ExprResult
*Result
= nullptr) {
5421 unsigned EntityIndexToProcess
= 0;
5422 SmallVector
<Expr
*, 4> InitExprs
;
5423 QualType ResultType
;
5424 Expr
*ArrayFiller
= nullptr;
5425 FieldDecl
*InitializedFieldInUnion
= nullptr;
5427 auto HandleInitializedEntity
= [&](const InitializedEntity
&SubEntity
,
5428 const InitializationKind
&SubKind
,
5429 Expr
*Arg
, Expr
**InitExpr
= nullptr) {
5430 InitializationSequence IS
= [&]() {
5432 return InitializationSequence(S
, SubEntity
, SubKind
, Arg
);
5433 return InitializationSequence(S
, SubEntity
, SubKind
, std::nullopt
);
5439 IS
.Diagnose(S
, SubEntity
, SubKind
, Arg
);
5441 IS
.Diagnose(S
, SubEntity
, SubKind
, std::nullopt
);
5444 InitializationSequence::FK_ParenthesizedListInitFailed
);
5452 ER
= IS
.Perform(S
, SubEntity
, SubKind
, Arg
);
5454 ER
= IS
.Perform(S
, SubEntity
, SubKind
, std::nullopt
);
5456 *InitExpr
= ER
.get();
5458 InitExprs
.push_back(ER
.get());
5463 if (const ArrayType
*AT
=
5464 S
.getASTContext().getAsArrayType(Entity
.getType())) {
5465 SmallVector
<InitializedEntity
, 4> ElementEntities
;
5466 uint64_t ArrayLength
;
5467 // C++ [dcl.init]p16.5
5468 // if the destination type is an array, the object is initialized as
5469 // follows. Let x1, . . . , xk be the elements of the expression-list. If
5470 // the destination type is an array of unknown bound, it is defined as
5471 // having k elements.
5472 if (const ConstantArrayType
*CAT
=
5473 S
.getASTContext().getAsConstantArrayType(Entity
.getType())) {
5474 ArrayLength
= CAT
->getSize().getZExtValue();
5475 ResultType
= Entity
.getType();
5476 } else if (const VariableArrayType
*VAT
=
5477 S
.getASTContext().getAsVariableArrayType(Entity
.getType())) {
5478 // Braced-initialization of variable array types is not allowed, even if
5479 // the size is greater than or equal to the number of args, so we don't
5480 // allow them to be initialized via parenthesized aggregate initialization
5482 const Expr
*SE
= VAT
->getSizeExpr();
5483 S
.Diag(SE
->getBeginLoc(), diag::err_variable_object_no_init
)
5484 << SE
->getSourceRange();
5487 assert(isa
<IncompleteArrayType
>(Entity
.getType()));
5488 ArrayLength
= Args
.size();
5490 EntityIndexToProcess
= ArrayLength
;
5492 // ...the ith array element is copy-initialized with xi for each
5494 for (Expr
*E
: Args
) {
5495 InitializedEntity SubEntity
= InitializedEntity::InitializeElement(
5496 S
.getASTContext(), EntityIndexToProcess
, Entity
);
5497 InitializationKind SubKind
= InitializationKind::CreateForInit(
5498 E
->getExprLoc(), /*isDirectInit=*/false, E
);
5499 if (!HandleInitializedEntity(SubEntity
, SubKind
, E
))
5502 // ...and value-initialized for each k < i <= n;
5503 if (ArrayLength
> Args
.size()) {
5504 InitializedEntity SubEntity
= InitializedEntity::InitializeElement(
5505 S
.getASTContext(), Args
.size(), Entity
);
5506 InitializationKind SubKind
= InitializationKind::CreateValue(
5507 Kind
.getLocation(), Kind
.getLocation(), Kind
.getLocation(), true);
5508 if (!HandleInitializedEntity(SubEntity
, SubKind
, nullptr, &ArrayFiller
))
5512 if (ResultType
.isNull()) {
5513 ResultType
= S
.Context
.getConstantArrayType(
5514 AT
->getElementType(), llvm::APInt(/*numBits=*/32, ArrayLength
),
5515 /*SizeExpr=*/nullptr, ArraySizeModifier::Normal
, 0);
5517 } else if (auto *RT
= Entity
.getType()->getAs
<RecordType
>()) {
5518 bool IsUnion
= RT
->isUnionType();
5519 const CXXRecordDecl
*RD
= cast
<CXXRecordDecl
>(RT
->getDecl());
5522 for (const CXXBaseSpecifier
&Base
: RD
->bases()) {
5523 InitializedEntity SubEntity
= InitializedEntity::InitializeBase(
5524 S
.getASTContext(), &Base
, false, &Entity
);
5525 if (EntityIndexToProcess
< Args
.size()) {
5526 // C++ [dcl.init]p16.6.2.2.
5527 // ...the object is initialized is follows. Let e1, ..., en be the
5528 // elements of the aggregate([dcl.init.aggr]). Let x1, ..., xk be
5529 // the elements of the expression-list...The element ei is
5530 // copy-initialized with xi for 1 <= i <= k.
5531 Expr
*E
= Args
[EntityIndexToProcess
];
5532 InitializationKind SubKind
= InitializationKind::CreateForInit(
5533 E
->getExprLoc(), /*isDirectInit=*/false, E
);
5534 if (!HandleInitializedEntity(SubEntity
, SubKind
, E
))
5537 // We've processed all of the args, but there are still base classes
5538 // that have to be initialized.
5539 // C++ [dcl.init]p17.6.2.2
5540 // The remaining elements...otherwise are value initialzed
5541 InitializationKind SubKind
= InitializationKind::CreateValue(
5542 Kind
.getLocation(), Kind
.getLocation(), Kind
.getLocation(),
5543 /*IsImplicit=*/true);
5544 if (!HandleInitializedEntity(SubEntity
, SubKind
, nullptr))
5547 EntityIndexToProcess
++;
5551 for (FieldDecl
*FD
: RD
->fields()) {
5552 // Unnamed bitfields should not be initialized at all, either with an arg
5554 if (FD
->isUnnamedBitfield())
5557 InitializedEntity SubEntity
=
5558 InitializedEntity::InitializeMemberFromParenAggInit(FD
);
5560 if (EntityIndexToProcess
< Args
.size()) {
5561 // ...The element ei is copy-initialized with xi for 1 <= i <= k.
5562 Expr
*E
= Args
[EntityIndexToProcess
];
5564 // Incomplete array types indicate flexible array members. Do not allow
5565 // paren list initializations of structs with these members, as GCC
5567 if (FD
->getType()->isIncompleteArrayType()) {
5569 S
.Diag(E
->getBeginLoc(), diag::err_flexible_array_init
)
5570 << SourceRange(E
->getBeginLoc(), E
->getEndLoc());
5571 S
.Diag(FD
->getLocation(), diag::note_flexible_array_member
) << FD
;
5574 InitializationSequence::FK_ParenthesizedListInitFailed
);
5578 InitializationKind SubKind
= InitializationKind::CreateForInit(
5579 E
->getExprLoc(), /*isDirectInit=*/false, E
);
5580 if (!HandleInitializedEntity(SubEntity
, SubKind
, E
))
5583 // Unions should have only one initializer expression, so we bail out
5584 // after processing the first field. If there are more initializers then
5585 // it will be caught when we later check whether EntityIndexToProcess is
5586 // less than Args.size();
5588 InitializedFieldInUnion
= FD
;
5589 EntityIndexToProcess
= 1;
5593 // We've processed all of the args, but there are still members that
5594 // have to be initialized.
5595 if (FD
->hasInClassInitializer()) {
5597 // C++ [dcl.init]p16.6.2.2
5598 // The remaining elements are initialized with their default
5599 // member initializers, if any
5600 ExprResult DIE
= S
.BuildCXXDefaultInitExpr(
5601 Kind
.getParenOrBraceRange().getEnd(), FD
);
5602 if (DIE
.isInvalid())
5604 S
.checkInitializerLifetime(SubEntity
, DIE
.get());
5605 InitExprs
.push_back(DIE
.get());
5608 // C++ [dcl.init]p17.6.2.2
5609 // The remaining elements...otherwise are value initialzed
5610 if (FD
->getType()->isReferenceType()) {
5612 InitializationSequence::FK_ParenthesizedListInitFailed
);
5614 SourceRange SR
= Kind
.getParenOrBraceRange();
5615 S
.Diag(SR
.getEnd(), diag::err_init_reference_member_uninitialized
)
5616 << FD
->getType() << SR
;
5617 S
.Diag(FD
->getLocation(), diag::note_uninit_reference_member
);
5621 InitializationKind SubKind
= InitializationKind::CreateValue(
5622 Kind
.getLocation(), Kind
.getLocation(), Kind
.getLocation(), true);
5623 if (!HandleInitializedEntity(SubEntity
, SubKind
, nullptr))
5627 EntityIndexToProcess
++;
5629 ResultType
= Entity
.getType();
5632 // Not all of the args have been processed, so there must've been more args
5633 // than were required to initialize the element.
5634 if (EntityIndexToProcess
< Args
.size()) {
5635 Sequence
.SetFailed(InitializationSequence::FK_ParenthesizedListInitFailed
);
5637 QualType T
= Entity
.getType();
5638 int InitKind
= T
->isArrayType() ? 0 : T
->isUnionType() ? 3 : 4;
5639 SourceRange
ExcessInitSR(Args
[EntityIndexToProcess
]->getBeginLoc(),
5640 Args
.back()->getEndLoc());
5641 S
.Diag(Kind
.getLocation(), diag::err_excess_initializers
)
5642 << InitKind
<< ExcessInitSR
;
5648 Sequence
.setSequenceKind(InitializationSequence::NormalSequence
);
5649 Sequence
.AddParenthesizedListInitStep(Entity
.getType());
5650 } else if (Result
) {
5651 SourceRange SR
= Kind
.getParenOrBraceRange();
5652 auto *CPLIE
= CXXParenListInitExpr::Create(
5653 S
.getASTContext(), InitExprs
, ResultType
, Args
.size(),
5654 Kind
.getLocation(), SR
.getBegin(), SR
.getEnd());
5656 CPLIE
->setArrayFiller(ArrayFiller
);
5657 if (InitializedFieldInUnion
)
5658 CPLIE
->setInitializedFieldInUnion(InitializedFieldInUnion
);
5660 S
.Diag(Kind
.getLocation(),
5661 diag::warn_cxx17_compat_aggregate_init_paren_list
)
5662 << Kind
.getLocation() << SR
<< ResultType
;
5666 /// Attempt a user-defined conversion between two types (C++ [dcl.init]),
5667 /// which enumerates all conversion functions and performs overload resolution
5668 /// to select the best.
5669 static void TryUserDefinedConversion(Sema
&S
,
5671 const InitializationKind
&Kind
,
5673 InitializationSequence
&Sequence
,
5674 bool TopLevelOfInitList
) {
5675 assert(!DestType
->isReferenceType() && "References are handled elsewhere");
5676 QualType SourceType
= Initializer
->getType();
5677 assert((DestType
->isRecordType() || SourceType
->isRecordType()) &&
5678 "Must have a class type to perform a user-defined conversion");
5680 // Build the candidate set directly in the initialization sequence
5681 // structure, so that it will persist if we fail.
5682 OverloadCandidateSet
&CandidateSet
= Sequence
.getFailedCandidateSet();
5683 CandidateSet
.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion
);
5684 CandidateSet
.setDestAS(DestType
.getQualifiers().getAddressSpace());
5686 // Determine whether we are allowed to call explicit constructors or
5687 // explicit conversion operators.
5688 bool AllowExplicit
= Kind
.AllowExplicit();
5690 if (const RecordType
*DestRecordType
= DestType
->getAs
<RecordType
>()) {
5691 // The type we're converting to is a class type. Enumerate its constructors
5692 // to see if there is a suitable conversion.
5693 CXXRecordDecl
*DestRecordDecl
5694 = cast
<CXXRecordDecl
>(DestRecordType
->getDecl());
5696 // Try to complete the type we're converting to.
5697 if (S
.isCompleteType(Kind
.getLocation(), DestType
)) {
5698 for (NamedDecl
*D
: S
.LookupConstructors(DestRecordDecl
)) {
5699 auto Info
= getConstructorInfo(D
);
5700 if (!Info
.Constructor
)
5703 if (!Info
.Constructor
->isInvalidDecl() &&
5704 Info
.Constructor
->isConvertingConstructor(/*AllowExplicit*/true)) {
5705 if (Info
.ConstructorTmpl
)
5706 S
.AddTemplateOverloadCandidate(
5707 Info
.ConstructorTmpl
, Info
.FoundDecl
,
5708 /*ExplicitArgs*/ nullptr, Initializer
, CandidateSet
,
5709 /*SuppressUserConversions=*/true,
5710 /*PartialOverloading*/ false, AllowExplicit
);
5712 S
.AddOverloadCandidate(Info
.Constructor
, Info
.FoundDecl
,
5713 Initializer
, CandidateSet
,
5714 /*SuppressUserConversions=*/true,
5715 /*PartialOverloading*/ false, AllowExplicit
);
5721 SourceLocation DeclLoc
= Initializer
->getBeginLoc();
5723 if (const RecordType
*SourceRecordType
= SourceType
->getAs
<RecordType
>()) {
5724 // The type we're converting from is a class type, enumerate its conversion
5727 // We can only enumerate the conversion functions for a complete type; if
5728 // the type isn't complete, simply skip this step.
5729 if (S
.isCompleteType(DeclLoc
, SourceType
)) {
5730 CXXRecordDecl
*SourceRecordDecl
5731 = cast
<CXXRecordDecl
>(SourceRecordType
->getDecl());
5733 const auto &Conversions
=
5734 SourceRecordDecl
->getVisibleConversionFunctions();
5735 for (auto I
= Conversions
.begin(), E
= Conversions
.end(); I
!= E
; ++I
) {
5737 CXXRecordDecl
*ActingDC
= cast
<CXXRecordDecl
>(D
->getDeclContext());
5738 if (isa
<UsingShadowDecl
>(D
))
5739 D
= cast
<UsingShadowDecl
>(D
)->getTargetDecl();
5741 FunctionTemplateDecl
*ConvTemplate
= dyn_cast
<FunctionTemplateDecl
>(D
);
5742 CXXConversionDecl
*Conv
;
5744 Conv
= cast
<CXXConversionDecl
>(ConvTemplate
->getTemplatedDecl());
5746 Conv
= cast
<CXXConversionDecl
>(D
);
5749 S
.AddTemplateConversionCandidate(
5750 ConvTemplate
, I
.getPair(), ActingDC
, Initializer
, DestType
,
5751 CandidateSet
, AllowExplicit
, AllowExplicit
);
5753 S
.AddConversionCandidate(Conv
, I
.getPair(), ActingDC
, Initializer
,
5754 DestType
, CandidateSet
, AllowExplicit
,
5760 // Perform overload resolution. If it fails, return the failed result.
5761 OverloadCandidateSet::iterator Best
;
5762 if (OverloadingResult Result
5763 = CandidateSet
.BestViableFunction(S
, DeclLoc
, Best
)) {
5764 Sequence
.SetOverloadFailure(
5765 InitializationSequence::FK_UserConversionOverloadFailed
, Result
);
5767 // [class.copy.elision]p3:
5768 // In some copy-initialization contexts, a two-stage overload resolution
5770 // If the first overload resolution selects a deleted function, we also
5771 // need the initialization sequence to decide whether to perform the second
5772 // overload resolution.
5773 if (!(Result
== OR_Deleted
&&
5774 Kind
.getKind() == InitializationKind::IK_Copy
))
5778 FunctionDecl
*Function
= Best
->Function
;
5779 Function
->setReferenced();
5780 bool HadMultipleCandidates
= (CandidateSet
.size() > 1);
5782 if (isa
<CXXConstructorDecl
>(Function
)) {
5783 // Add the user-defined conversion step. Any cv-qualification conversion is
5784 // subsumed by the initialization. Per DR5, the created temporary is of the
5785 // cv-unqualified type of the destination.
5786 Sequence
.AddUserConversionStep(Function
, Best
->FoundDecl
,
5787 DestType
.getUnqualifiedType(),
5788 HadMultipleCandidates
);
5790 // C++14 and before:
5791 // - if the function is a constructor, the call initializes a temporary
5792 // of the cv-unqualified version of the destination type. The [...]
5793 // temporary [...] is then used to direct-initialize, according to the
5794 // rules above, the object that is the destination of the
5795 // copy-initialization.
5796 // Note that this just performs a simple object copy from the temporary.
5799 // - if the function is a constructor, the call is a prvalue of the
5800 // cv-unqualified version of the destination type whose return object
5801 // is initialized by the constructor. The call is used to
5802 // direct-initialize, according to the rules above, the object that
5803 // is the destination of the copy-initialization.
5804 // Therefore we need to do nothing further.
5806 // FIXME: Mark this copy as extraneous.
5807 if (!S
.getLangOpts().CPlusPlus17
)
5808 Sequence
.AddFinalCopy(DestType
);
5809 else if (DestType
.hasQualifiers())
5810 Sequence
.AddQualificationConversionStep(DestType
, VK_PRValue
);
5814 // Add the user-defined conversion step that calls the conversion function.
5815 QualType ConvType
= Function
->getCallResultType();
5816 Sequence
.AddUserConversionStep(Function
, Best
->FoundDecl
, ConvType
,
5817 HadMultipleCandidates
);
5819 if (ConvType
->getAs
<RecordType
>()) {
5820 // The call is used to direct-initialize [...] the object that is the
5821 // destination of the copy-initialization.
5823 // In C++17, this does not call a constructor if we enter /17.6.1:
5824 // - If the initializer expression is a prvalue and the cv-unqualified
5825 // version of the source type is the same as the class of the
5826 // destination [... do not make an extra copy]
5828 // FIXME: Mark this copy as extraneous.
5829 if (!S
.getLangOpts().CPlusPlus17
||
5830 Function
->getReturnType()->isReferenceType() ||
5831 !S
.Context
.hasSameUnqualifiedType(ConvType
, DestType
))
5832 Sequence
.AddFinalCopy(DestType
);
5833 else if (!S
.Context
.hasSameType(ConvType
, DestType
))
5834 Sequence
.AddQualificationConversionStep(DestType
, VK_PRValue
);
5838 // If the conversion following the call to the conversion function
5839 // is interesting, add it as a separate step.
5840 if (Best
->FinalConversion
.First
|| Best
->FinalConversion
.Second
||
5841 Best
->FinalConversion
.Third
) {
5842 ImplicitConversionSequence ICS
;
5844 ICS
.Standard
= Best
->FinalConversion
;
5845 Sequence
.AddConversionSequenceStep(ICS
, DestType
, TopLevelOfInitList
);
5849 /// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
5850 /// a function with a pointer return type contains a 'return false;' statement.
5851 /// In C++11, 'false' is not a null pointer, so this breaks the build of any
5852 /// code using that header.
5854 /// Work around this by treating 'return false;' as zero-initializing the result
5855 /// if it's used in a pointer-returning function in a system header.
5856 static bool isLibstdcxxPointerReturnFalseHack(Sema
&S
,
5857 const InitializedEntity
&Entity
,
5859 return S
.getLangOpts().CPlusPlus11
&&
5860 Entity
.getKind() == InitializedEntity::EK_Result
&&
5861 Entity
.getType()->isPointerType() &&
5862 isa
<CXXBoolLiteralExpr
>(Init
) &&
5863 !cast
<CXXBoolLiteralExpr
>(Init
)->getValue() &&
5864 S
.getSourceManager().isInSystemHeader(Init
->getExprLoc());
5867 /// The non-zero enum values here are indexes into diagnostic alternatives.
5868 enum InvalidICRKind
{ IIK_okay
, IIK_nonlocal
, IIK_nonscalar
};
5870 /// Determines whether this expression is an acceptable ICR source.
5871 static InvalidICRKind
isInvalidICRSource(ASTContext
&C
, Expr
*e
,
5872 bool isAddressOf
, bool &isWeakAccess
) {
5874 e
= e
->IgnoreParens();
5876 // Skip address-of nodes.
5877 if (UnaryOperator
*op
= dyn_cast
<UnaryOperator
>(e
)) {
5878 if (op
->getOpcode() == UO_AddrOf
)
5879 return isInvalidICRSource(C
, op
->getSubExpr(), /*addressof*/ true,
5882 // Skip certain casts.
5883 } else if (CastExpr
*ce
= dyn_cast
<CastExpr
>(e
)) {
5884 switch (ce
->getCastKind()) {
5887 case CK_LValueBitCast
:
5889 return isInvalidICRSource(C
, ce
->getSubExpr(), isAddressOf
, isWeakAccess
);
5891 case CK_ArrayToPointerDecay
:
5892 return IIK_nonscalar
;
5894 case CK_NullToPointer
:
5901 // If we have a declaration reference, it had better be a local variable.
5902 } else if (isa
<DeclRefExpr
>(e
)) {
5903 // set isWeakAccess to true, to mean that there will be an implicit
5904 // load which requires a cleanup.
5905 if (e
->getType().getObjCLifetime() == Qualifiers::OCL_Weak
)
5906 isWeakAccess
= true;
5908 if (!isAddressOf
) return IIK_nonlocal
;
5910 VarDecl
*var
= dyn_cast
<VarDecl
>(cast
<DeclRefExpr
>(e
)->getDecl());
5911 if (!var
) return IIK_nonlocal
;
5913 return (var
->hasLocalStorage() ? IIK_okay
: IIK_nonlocal
);
5915 // If we have a conditional operator, check both sides.
5916 } else if (ConditionalOperator
*cond
= dyn_cast
<ConditionalOperator
>(e
)) {
5917 if (InvalidICRKind iik
= isInvalidICRSource(C
, cond
->getLHS(), isAddressOf
,
5921 return isInvalidICRSource(C
, cond
->getRHS(), isAddressOf
, isWeakAccess
);
5923 // These are never scalar.
5924 } else if (isa
<ArraySubscriptExpr
>(e
)) {
5925 return IIK_nonscalar
;
5927 // Otherwise, it needs to be a null pointer constant.
5929 return (e
->isNullPointerConstant(C
, Expr::NPC_ValueDependentIsNull
)
5930 ? IIK_okay
: IIK_nonlocal
);
5933 return IIK_nonlocal
;
5936 /// Check whether the given expression is a valid operand for an
5937 /// indirect copy/restore.
5938 static void checkIndirectCopyRestoreSource(Sema
&S
, Expr
*src
) {
5939 assert(src
->isPRValue());
5940 bool isWeakAccess
= false;
5941 InvalidICRKind iik
= isInvalidICRSource(S
.Context
, src
, false, isWeakAccess
);
5942 // If isWeakAccess to true, there will be an implicit
5943 // load which requires a cleanup.
5944 if (S
.getLangOpts().ObjCAutoRefCount
&& isWeakAccess
)
5945 S
.Cleanup
.setExprNeedsCleanups(true);
5947 if (iik
== IIK_okay
) return;
5949 S
.Diag(src
->getExprLoc(), diag::err_arc_nonlocal_writeback
)
5950 << ((unsigned) iik
- 1) // shift index into diagnostic explanations
5951 << src
->getSourceRange();
5954 /// Determine whether we have compatible array types for the
5955 /// purposes of GNU by-copy array initialization.
5956 static bool hasCompatibleArrayTypes(ASTContext
&Context
, const ArrayType
*Dest
,
5957 const ArrayType
*Source
) {
5958 // If the source and destination array types are equivalent, we're
5960 if (Context
.hasSameType(QualType(Dest
, 0), QualType(Source
, 0)))
5963 // Make sure that the element types are the same.
5964 if (!Context
.hasSameType(Dest
->getElementType(), Source
->getElementType()))
5967 // The only mismatch we allow is when the destination is an
5968 // incomplete array type and the source is a constant array type.
5969 return Source
->isConstantArrayType() && Dest
->isIncompleteArrayType();
5972 static bool tryObjCWritebackConversion(Sema
&S
,
5973 InitializationSequence
&Sequence
,
5974 const InitializedEntity
&Entity
,
5975 Expr
*Initializer
) {
5976 bool ArrayDecay
= false;
5977 QualType ArgType
= Initializer
->getType();
5978 QualType ArgPointee
;
5979 if (const ArrayType
*ArgArrayType
= S
.Context
.getAsArrayType(ArgType
)) {
5981 ArgPointee
= ArgArrayType
->getElementType();
5982 ArgType
= S
.Context
.getPointerType(ArgPointee
);
5985 // Handle write-back conversion.
5986 QualType ConvertedArgType
;
5987 if (!S
.isObjCWritebackConversion(ArgType
, Entity
.getType(),
5991 // We should copy unless we're passing to an argument explicitly
5993 bool ShouldCopy
= true;
5994 if (ParmVarDecl
*param
= cast_or_null
<ParmVarDecl
>(Entity
.getDecl()))
5995 ShouldCopy
= (param
->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out
);
5997 // Do we need an lvalue conversion?
5998 if (ArrayDecay
|| Initializer
->isGLValue()) {
5999 ImplicitConversionSequence ICS
;
6001 ICS
.Standard
.setAsIdentityConversion();
6003 QualType ResultType
;
6005 ICS
.Standard
.First
= ICK_Array_To_Pointer
;
6006 ResultType
= S
.Context
.getPointerType(ArgPointee
);
6008 ICS
.Standard
.First
= ICK_Lvalue_To_Rvalue
;
6009 ResultType
= Initializer
->getType().getNonLValueExprType(S
.Context
);
6012 Sequence
.AddConversionSequenceStep(ICS
, ResultType
);
6015 Sequence
.AddPassByIndirectCopyRestoreStep(Entity
.getType(), ShouldCopy
);
6019 static bool TryOCLSamplerInitialization(Sema
&S
,
6020 InitializationSequence
&Sequence
,
6022 Expr
*Initializer
) {
6023 if (!S
.getLangOpts().OpenCL
|| !DestType
->isSamplerT() ||
6024 (!Initializer
->isIntegerConstantExpr(S
.Context
) &&
6025 !Initializer
->getType()->isSamplerT()))
6028 Sequence
.AddOCLSamplerInitStep(DestType
);
6032 static bool IsZeroInitializer(Expr
*Initializer
, Sema
&S
) {
6033 return Initializer
->isIntegerConstantExpr(S
.getASTContext()) &&
6034 (Initializer
->EvaluateKnownConstInt(S
.getASTContext()) == 0);
6037 static bool TryOCLZeroOpaqueTypeInitialization(Sema
&S
,
6038 InitializationSequence
&Sequence
,
6040 Expr
*Initializer
) {
6041 if (!S
.getLangOpts().OpenCL
)
6045 // OpenCL 1.2 spec, s6.12.10
6047 // The event argument can also be used to associate the
6048 // async_work_group_copy with a previous async copy allowing
6049 // an event to be shared by multiple async copies; otherwise
6050 // event should be zero.
6052 if (DestType
->isEventT() || DestType
->isQueueT()) {
6053 if (!IsZeroInitializer(Initializer
, S
))
6056 Sequence
.AddOCLZeroOpaqueTypeStep(DestType
);
6060 // We should allow zero initialization for all types defined in the
6061 // cl_intel_device_side_avc_motion_estimation extension, except
6062 // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t.
6063 if (S
.getOpenCLOptions().isAvailableOption(
6064 "cl_intel_device_side_avc_motion_estimation", S
.getLangOpts()) &&
6065 DestType
->isOCLIntelSubgroupAVCType()) {
6066 if (DestType
->isOCLIntelSubgroupAVCMcePayloadType() ||
6067 DestType
->isOCLIntelSubgroupAVCMceResultType())
6069 if (!IsZeroInitializer(Initializer
, S
))
6072 Sequence
.AddOCLZeroOpaqueTypeStep(DestType
);
6079 InitializationSequence::InitializationSequence(
6080 Sema
&S
, const InitializedEntity
&Entity
, const InitializationKind
&Kind
,
6081 MultiExprArg Args
, bool TopLevelOfInitList
, bool TreatUnavailableAsInvalid
)
6082 : FailedOverloadResult(OR_Success
),
6083 FailedCandidateSet(Kind
.getLocation(), OverloadCandidateSet::CSK_Normal
) {
6084 InitializeFrom(S
, Entity
, Kind
, Args
, TopLevelOfInitList
,
6085 TreatUnavailableAsInvalid
);
6088 /// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
6089 /// address of that function, this returns true. Otherwise, it returns false.
6090 static bool isExprAnUnaddressableFunction(Sema
&S
, const Expr
*E
) {
6091 auto *DRE
= dyn_cast
<DeclRefExpr
>(E
);
6092 if (!DRE
|| !isa
<FunctionDecl
>(DRE
->getDecl()))
6095 return !S
.checkAddressOfFunctionIsAvailable(
6096 cast
<FunctionDecl
>(DRE
->getDecl()));
6099 /// Determine whether we can perform an elementwise array copy for this kind
6101 static bool canPerformArrayCopy(const InitializedEntity
&Entity
) {
6102 switch (Entity
.getKind()) {
6103 case InitializedEntity::EK_LambdaCapture
:
6104 // C++ [expr.prim.lambda]p24:
6105 // For array members, the array elements are direct-initialized in
6106 // increasing subscript order.
6109 case InitializedEntity::EK_Variable
:
6110 // C++ [dcl.decomp]p1:
6111 // [...] each element is copy-initialized or direct-initialized from the
6112 // corresponding element of the assignment-expression [...]
6113 return isa
<DecompositionDecl
>(Entity
.getDecl());
6115 case InitializedEntity::EK_Member
:
6116 // C++ [class.copy.ctor]p14:
6117 // - if the member is an array, each element is direct-initialized with
6118 // the corresponding subobject of x
6119 return Entity
.isImplicitMemberInitializer();
6121 case InitializedEntity::EK_ArrayElement
:
6122 // All the above cases are intended to apply recursively, even though none
6123 // of them actually say that.
6124 if (auto *E
= Entity
.getParent())
6125 return canPerformArrayCopy(*E
);
6135 void InitializationSequence::InitializeFrom(Sema
&S
,
6136 const InitializedEntity
&Entity
,
6137 const InitializationKind
&Kind
,
6139 bool TopLevelOfInitList
,
6140 bool TreatUnavailableAsInvalid
) {
6141 ASTContext
&Context
= S
.Context
;
6143 // Eliminate non-overload placeholder types in the arguments. We
6144 // need to do this before checking whether types are dependent
6145 // because lowering a pseudo-object expression might well give us
6146 // something of dependent type.
6147 for (unsigned I
= 0, E
= Args
.size(); I
!= E
; ++I
)
6148 if (Args
[I
]->getType()->isNonOverloadPlaceholderType()) {
6149 // FIXME: should we be doing this here?
6150 ExprResult result
= S
.CheckPlaceholderExpr(Args
[I
]);
6151 if (result
.isInvalid()) {
6152 SetFailed(FK_PlaceholderType
);
6155 Args
[I
] = result
.get();
6158 // C++0x [dcl.init]p16:
6159 // The semantics of initializers are as follows. The destination type is
6160 // the type of the object or reference being initialized and the source
6161 // type is the type of the initializer expression. The source type is not
6162 // defined when the initializer is a braced-init-list or when it is a
6163 // parenthesized list of expressions.
6164 QualType DestType
= Entity
.getType();
6166 if (DestType
->isDependentType() ||
6167 Expr::hasAnyTypeDependentArguments(Args
)) {
6168 SequenceKind
= DependentSequence
;
6172 // Almost everything is a normal sequence.
6173 setSequenceKind(NormalSequence
);
6175 QualType SourceType
;
6176 Expr
*Initializer
= nullptr;
6177 if (Args
.size() == 1) {
6178 Initializer
= Args
[0];
6179 if (S
.getLangOpts().ObjC
) {
6180 if (S
.CheckObjCBridgeRelatedConversions(Initializer
->getBeginLoc(),
6181 DestType
, Initializer
->getType(),
6183 S
.CheckConversionToObjCLiteral(DestType
, Initializer
))
6184 Args
[0] = Initializer
;
6186 if (!isa
<InitListExpr
>(Initializer
))
6187 SourceType
= Initializer
->getType();
6190 // - If the initializer is a (non-parenthesized) braced-init-list, the
6191 // object is list-initialized (8.5.4).
6192 if (Kind
.getKind() != InitializationKind::IK_Direct
) {
6193 if (InitListExpr
*InitList
= dyn_cast_or_null
<InitListExpr
>(Initializer
)) {
6194 TryListInitialization(S
, Entity
, Kind
, InitList
, *this,
6195 TreatUnavailableAsInvalid
);
6200 // - If the destination type is a reference type, see 8.5.3.
6201 if (DestType
->isReferenceType()) {
6202 // C++0x [dcl.init.ref]p1:
6203 // A variable declared to be a T& or T&&, that is, "reference to type T"
6204 // (8.3.2), shall be initialized by an object, or function, of type T or
6205 // by an object that can be converted into a T.
6206 // (Therefore, multiple arguments are not permitted.)
6207 if (Args
.size() != 1)
6208 SetFailed(FK_TooManyInitsForReference
);
6209 // C++17 [dcl.init.ref]p5:
6210 // A reference [...] is initialized by an expression [...] as follows:
6211 // If the initializer is not an expression, presumably we should reject,
6212 // but the standard fails to actually say so.
6213 else if (isa
<InitListExpr
>(Args
[0]))
6214 SetFailed(FK_ParenthesizedListInitForReference
);
6216 TryReferenceInitialization(S
, Entity
, Kind
, Args
[0], *this);
6220 // - If the initializer is (), the object is value-initialized.
6221 if (Kind
.getKind() == InitializationKind::IK_Value
||
6222 (Kind
.getKind() == InitializationKind::IK_Direct
&& Args
.empty())) {
6223 TryValueInitialization(S
, Entity
, Kind
, *this);
6227 // Handle default initialization.
6228 if (Kind
.getKind() == InitializationKind::IK_Default
) {
6229 TryDefaultInitialization(S
, Entity
, Kind
, *this);
6233 // - If the destination type is an array of characters, an array of
6234 // char16_t, an array of char32_t, or an array of wchar_t, and the
6235 // initializer is a string literal, see 8.5.2.
6236 // - Otherwise, if the destination type is an array, the program is
6238 if (const ArrayType
*DestAT
= Context
.getAsArrayType(DestType
)) {
6239 if (Initializer
&& isa
<VariableArrayType
>(DestAT
)) {
6240 SetFailed(FK_VariableLengthArrayHasInitializer
);
6245 switch (IsStringInit(Initializer
, DestAT
, Context
)) {
6247 TryStringLiteralInitialization(S
, Entity
, Kind
, Initializer
, *this);
6249 case SIF_NarrowStringIntoWideChar
:
6250 SetFailed(FK_NarrowStringIntoWideCharArray
);
6252 case SIF_WideStringIntoChar
:
6253 SetFailed(FK_WideStringIntoCharArray
);
6255 case SIF_IncompatWideStringIntoWideChar
:
6256 SetFailed(FK_IncompatWideStringIntoWideChar
);
6258 case SIF_PlainStringIntoUTF8Char
:
6259 SetFailed(FK_PlainStringIntoUTF8Char
);
6261 case SIF_UTF8StringIntoPlainChar
:
6262 SetFailed(FK_UTF8StringIntoPlainChar
);
6269 // Some kinds of initialization permit an array to be initialized from
6270 // another array of the same type, and perform elementwise initialization.
6271 if (Initializer
&& isa
<ConstantArrayType
>(DestAT
) &&
6272 S
.Context
.hasSameUnqualifiedType(Initializer
->getType(),
6273 Entity
.getType()) &&
6274 canPerformArrayCopy(Entity
)) {
6275 // If source is a prvalue, use it directly.
6276 if (Initializer
->isPRValue()) {
6277 AddArrayInitStep(DestType
, /*IsGNUExtension*/false);
6281 // Emit element-at-a-time copy loop.
6282 InitializedEntity Element
=
6283 InitializedEntity::InitializeElement(S
.Context
, 0, Entity
);
6285 Context
.getAsArrayType(Initializer
->getType())->getElementType();
6286 OpaqueValueExpr
OVE(Initializer
->getExprLoc(), InitEltT
,
6287 Initializer
->getValueKind(),
6288 Initializer
->getObjectKind());
6289 Expr
*OVEAsExpr
= &OVE
;
6290 InitializeFrom(S
, Element
, Kind
, OVEAsExpr
, TopLevelOfInitList
,
6291 TreatUnavailableAsInvalid
);
6293 AddArrayInitLoopStep(Entity
.getType(), InitEltT
);
6297 // Note: as an GNU C extension, we allow initialization of an
6298 // array from a compound literal that creates an array of the same
6299 // type, so long as the initializer has no side effects.
6300 if (!S
.getLangOpts().CPlusPlus
&& Initializer
&&
6301 isa
<CompoundLiteralExpr
>(Initializer
->IgnoreParens()) &&
6302 Initializer
->getType()->isArrayType()) {
6303 const ArrayType
*SourceAT
6304 = Context
.getAsArrayType(Initializer
->getType());
6305 if (!hasCompatibleArrayTypes(S
.Context
, DestAT
, SourceAT
))
6306 SetFailed(FK_ArrayTypeMismatch
);
6307 else if (Initializer
->HasSideEffects(S
.Context
))
6308 SetFailed(FK_NonConstantArrayInit
);
6310 AddArrayInitStep(DestType
, /*IsGNUExtension*/true);
6313 // Note: as a GNU C++ extension, we allow list-initialization of a
6314 // class member of array type from a parenthesized initializer list.
6315 else if (S
.getLangOpts().CPlusPlus
&&
6316 Entity
.getKind() == InitializedEntity::EK_Member
&&
6317 Initializer
&& isa
<InitListExpr
>(Initializer
)) {
6318 TryListInitialization(S
, Entity
, Kind
, cast
<InitListExpr
>(Initializer
),
6319 *this, TreatUnavailableAsInvalid
);
6320 AddParenthesizedArrayInitStep(DestType
);
6321 } else if (S
.getLangOpts().CPlusPlus20
&& !TopLevelOfInitList
&&
6322 Kind
.getKind() == InitializationKind::IK_Direct
)
6323 TryOrBuildParenListInitialization(S
, Entity
, Kind
, Args
, *this,
6324 /*VerifyOnly=*/true);
6325 else if (DestAT
->getElementType()->isCharType())
6326 SetFailed(FK_ArrayNeedsInitListOrStringLiteral
);
6327 else if (IsWideCharCompatible(DestAT
->getElementType(), Context
))
6328 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral
);
6330 SetFailed(FK_ArrayNeedsInitList
);
6335 // Determine whether we should consider writeback conversions for
6337 bool allowObjCWritebackConversion
= S
.getLangOpts().ObjCAutoRefCount
&&
6338 Entity
.isParameterKind();
6340 if (TryOCLSamplerInitialization(S
, *this, DestType
, Initializer
))
6343 // We're at the end of the line for C: it's either a write-back conversion
6344 // or it's a C assignment. There's no need to check anything else.
6345 if (!S
.getLangOpts().CPlusPlus
) {
6346 assert(Initializer
&& "Initializer must be non-null");
6347 // If allowed, check whether this is an Objective-C writeback conversion.
6348 if (allowObjCWritebackConversion
&&
6349 tryObjCWritebackConversion(S
, *this, Entity
, Initializer
)) {
6353 if (TryOCLZeroOpaqueTypeInitialization(S
, *this, DestType
, Initializer
))
6356 // Handle initialization in C
6357 AddCAssignmentStep(DestType
);
6358 MaybeProduceObjCObject(S
, *this, Entity
);
6362 assert(S
.getLangOpts().CPlusPlus
);
6364 // - If the destination type is a (possibly cv-qualified) class type:
6365 if (DestType
->isRecordType()) {
6366 // - If the initialization is direct-initialization, or if it is
6367 // copy-initialization where the cv-unqualified version of the
6368 // source type is the same class as, or a derived class of, the
6369 // class of the destination, constructors are considered. [...]
6370 if (Kind
.getKind() == InitializationKind::IK_Direct
||
6371 (Kind
.getKind() == InitializationKind::IK_Copy
&&
6372 (Context
.hasSameUnqualifiedType(SourceType
, DestType
) ||
6373 (Initializer
&& S
.IsDerivedFrom(Initializer
->getBeginLoc(),
6374 SourceType
, DestType
))))) {
6375 TryConstructorInitialization(S
, Entity
, Kind
, Args
, DestType
, DestType
,
6378 // We fall back to the "no matching constructor" path if the
6379 // failed candidate set has functions other than the three default
6380 // constructors. For example, conversion function.
6381 if (const auto *RD
=
6382 dyn_cast
<CXXRecordDecl
>(DestType
->getAs
<RecordType
>()->getDecl());
6383 // In general, we should call isCompleteType for RD to check its
6384 // completeness, we don't call it here as it was already called in the
6385 // above TryConstructorInitialization.
6386 S
.getLangOpts().CPlusPlus20
&& RD
&& RD
->hasDefinition() &&
6387 RD
->isAggregate() && Failed() &&
6388 getFailureKind() == FK_ConstructorOverloadFailed
) {
6389 // Do not attempt paren list initialization if overload resolution
6390 // resolves to a deleted function .
6392 // We may reach this condition if we have a union wrapping a class with
6393 // a non-trivial copy or move constructor and we call one of those two
6394 // constructors. The union is an aggregate, but the matched constructor
6395 // is implicitly deleted, so we need to prevent aggregate initialization
6396 // (otherwise, it'll attempt aggregate initialization by initializing
6397 // the first element with a reference to the union).
6398 OverloadCandidateSet::iterator Best
;
6399 OverloadingResult OR
= getFailedCandidateSet().BestViableFunction(
6400 S
, Kind
.getLocation(), Best
);
6401 if (OR
!= OverloadingResult::OR_Deleted
) {
6402 // C++20 [dcl.init] 17.6.2.2:
6403 // - Otherwise, if no constructor is viable, the destination type is
6405 // aggregate class, and the initializer is a parenthesized
6407 TryOrBuildParenListInitialization(S
, Entity
, Kind
, Args
, *this,
6408 /*VerifyOnly=*/true);
6412 // - Otherwise (i.e., for the remaining copy-initialization cases),
6413 // user-defined conversion sequences that can convert from the
6414 // source type to the destination type or (when a conversion
6415 // function is used) to a derived class thereof are enumerated as
6416 // described in 13.3.1.4, and the best one is chosen through
6417 // overload resolution (13.3).
6418 assert(Initializer
&& "Initializer must be non-null");
6419 TryUserDefinedConversion(S
, DestType
, Kind
, Initializer
, *this,
6420 TopLevelOfInitList
);
6425 assert(Args
.size() >= 1 && "Zero-argument case handled above");
6427 // For HLSL ext vector types we allow list initialization behavior for C++
6428 // constructor syntax. This is accomplished by converting initialization
6429 // arguments an InitListExpr late.
6430 if (S
.getLangOpts().HLSL
&& DestType
->isExtVectorType() &&
6431 (SourceType
.isNull() ||
6432 !Context
.hasSameUnqualifiedType(SourceType
, DestType
))) {
6434 llvm::SmallVector
<Expr
*> InitArgs
;
6435 for (auto *Arg
: Args
) {
6436 if (Arg
->getType()->isExtVectorType()) {
6437 const auto *VTy
= Arg
->getType()->castAs
<ExtVectorType
>();
6438 unsigned Elm
= VTy
->getNumElements();
6439 for (unsigned Idx
= 0; Idx
< Elm
; ++Idx
) {
6440 InitArgs
.emplace_back(new (Context
) ArraySubscriptExpr(
6442 IntegerLiteral::Create(
6443 Context
, llvm::APInt(Context
.getIntWidth(Context
.IntTy
), Idx
),
6444 Context
.IntTy
, SourceLocation()),
6445 VTy
->getElementType(), Arg
->getValueKind(), Arg
->getObjectKind(),
6449 InitArgs
.emplace_back(Arg
);
6451 InitListExpr
*ILE
= new (Context
) InitListExpr(
6452 S
.getASTContext(), SourceLocation(), InitArgs
, SourceLocation());
6454 AddListInitializationStep(DestType
);
6458 // The remaining cases all need a source type.
6459 if (Args
.size() > 1) {
6460 SetFailed(FK_TooManyInitsForScalar
);
6462 } else if (isa
<InitListExpr
>(Args
[0])) {
6463 SetFailed(FK_ParenthesizedListInitForScalar
);
6467 // - Otherwise, if the source type is a (possibly cv-qualified) class
6468 // type, conversion functions are considered.
6469 if (!SourceType
.isNull() && SourceType
->isRecordType()) {
6470 assert(Initializer
&& "Initializer must be non-null");
6471 // For a conversion to _Atomic(T) from either T or a class type derived
6472 // from T, initialize the T object then convert to _Atomic type.
6473 bool NeedAtomicConversion
= false;
6474 if (const AtomicType
*Atomic
= DestType
->getAs
<AtomicType
>()) {
6475 if (Context
.hasSameUnqualifiedType(SourceType
, Atomic
->getValueType()) ||
6476 S
.IsDerivedFrom(Initializer
->getBeginLoc(), SourceType
,
6477 Atomic
->getValueType())) {
6478 DestType
= Atomic
->getValueType();
6479 NeedAtomicConversion
= true;
6483 TryUserDefinedConversion(S
, DestType
, Kind
, Initializer
, *this,
6484 TopLevelOfInitList
);
6485 MaybeProduceObjCObject(S
, *this, Entity
);
6486 if (!Failed() && NeedAtomicConversion
)
6487 AddAtomicConversionStep(Entity
.getType());
6491 // - Otherwise, if the initialization is direct-initialization, the source
6492 // type is std::nullptr_t, and the destination type is bool, the initial
6493 // value of the object being initialized is false.
6494 if (!SourceType
.isNull() && SourceType
->isNullPtrType() &&
6495 DestType
->isBooleanType() &&
6496 Kind
.getKind() == InitializationKind::IK_Direct
) {
6497 AddConversionSequenceStep(
6498 ImplicitConversionSequence::getNullptrToBool(SourceType
, DestType
,
6499 Initializer
->isGLValue()),
6504 // - Otherwise, the initial value of the object being initialized is the
6505 // (possibly converted) value of the initializer expression. Standard
6506 // conversions (Clause 4) will be used, if necessary, to convert the
6507 // initializer expression to the cv-unqualified version of the
6508 // destination type; no user-defined conversions are considered.
6510 ImplicitConversionSequence ICS
6511 = S
.TryImplicitConversion(Initializer
, DestType
,
6512 /*SuppressUserConversions*/true,
6513 Sema::AllowedExplicit::None
,
6514 /*InOverloadResolution*/ false,
6515 /*CStyle=*/Kind
.isCStyleOrFunctionalCast(),
6516 allowObjCWritebackConversion
);
6518 if (ICS
.isStandard() &&
6519 ICS
.Standard
.Second
== ICK_Writeback_Conversion
) {
6520 // Objective-C ARC writeback conversion.
6522 // We should copy unless we're passing to an argument explicitly
6524 bool ShouldCopy
= true;
6525 if (ParmVarDecl
*Param
= cast_or_null
<ParmVarDecl
>(Entity
.getDecl()))
6526 ShouldCopy
= (Param
->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out
);
6528 // If there was an lvalue adjustment, add it as a separate conversion.
6529 if (ICS
.Standard
.First
== ICK_Array_To_Pointer
||
6530 ICS
.Standard
.First
== ICK_Lvalue_To_Rvalue
) {
6531 ImplicitConversionSequence LvalueICS
;
6532 LvalueICS
.setStandard();
6533 LvalueICS
.Standard
.setAsIdentityConversion();
6534 LvalueICS
.Standard
.setAllToTypes(ICS
.Standard
.getToType(0));
6535 LvalueICS
.Standard
.First
= ICS
.Standard
.First
;
6536 AddConversionSequenceStep(LvalueICS
, ICS
.Standard
.getToType(0));
6539 AddPassByIndirectCopyRestoreStep(DestType
, ShouldCopy
);
6540 } else if (ICS
.isBad()) {
6542 if (isLibstdcxxPointerReturnFalseHack(S
, Entity
, Initializer
)) {
6543 AddZeroInitializationStep(Entity
.getType());
6544 } else if (Initializer
->getType() == Context
.OverloadTy
&&
6545 !S
.ResolveAddressOfOverloadedFunction(Initializer
, DestType
,
6547 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed
);
6548 else if (Initializer
->getType()->isFunctionType() &&
6549 isExprAnUnaddressableFunction(S
, Initializer
))
6550 SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction
);
6552 SetFailed(InitializationSequence::FK_ConversionFailed
);
6554 AddConversionSequenceStep(ICS
, DestType
, TopLevelOfInitList
);
6556 MaybeProduceObjCObject(S
, *this, Entity
);
6560 InitializationSequence::~InitializationSequence() {
6561 for (auto &S
: Steps
)
6565 //===----------------------------------------------------------------------===//
6566 // Perform initialization
6567 //===----------------------------------------------------------------------===//
6568 static Sema::AssignmentAction
6569 getAssignmentAction(const InitializedEntity
&Entity
, bool Diagnose
= false) {
6570 switch(Entity
.getKind()) {
6571 case InitializedEntity::EK_Variable
:
6572 case InitializedEntity::EK_New
:
6573 case InitializedEntity::EK_Exception
:
6574 case InitializedEntity::EK_Base
:
6575 case InitializedEntity::EK_Delegating
:
6576 return Sema::AA_Initializing
;
6578 case InitializedEntity::EK_Parameter
:
6579 if (Entity
.getDecl() &&
6580 isa
<ObjCMethodDecl
>(Entity
.getDecl()->getDeclContext()))
6581 return Sema::AA_Sending
;
6583 return Sema::AA_Passing
;
6585 case InitializedEntity::EK_Parameter_CF_Audited
:
6586 if (Entity
.getDecl() &&
6587 isa
<ObjCMethodDecl
>(Entity
.getDecl()->getDeclContext()))
6588 return Sema::AA_Sending
;
6590 return !Diagnose
? Sema::AA_Passing
: Sema::AA_Passing_CFAudited
;
6592 case InitializedEntity::EK_Result
:
6593 case InitializedEntity::EK_StmtExprResult
: // FIXME: Not quite right.
6594 return Sema::AA_Returning
;
6596 case InitializedEntity::EK_Temporary
:
6597 case InitializedEntity::EK_RelatedResult
:
6598 // FIXME: Can we tell apart casting vs. converting?
6599 return Sema::AA_Casting
;
6601 case InitializedEntity::EK_TemplateParameter
:
6602 // This is really initialization, but refer to it as conversion for
6603 // consistency with CheckConvertedConstantExpression.
6604 return Sema::AA_Converting
;
6606 case InitializedEntity::EK_Member
:
6607 case InitializedEntity::EK_ParenAggInitMember
:
6608 case InitializedEntity::EK_Binding
:
6609 case InitializedEntity::EK_ArrayElement
:
6610 case InitializedEntity::EK_VectorElement
:
6611 case InitializedEntity::EK_ComplexElement
:
6612 case InitializedEntity::EK_BlockElement
:
6613 case InitializedEntity::EK_LambdaToBlockConversionBlockElement
:
6614 case InitializedEntity::EK_LambdaCapture
:
6615 case InitializedEntity::EK_CompoundLiteralInit
:
6616 return Sema::AA_Initializing
;
6619 llvm_unreachable("Invalid EntityKind!");
6622 /// Whether we should bind a created object as a temporary when
6623 /// initializing the given entity.
6624 static bool shouldBindAsTemporary(const InitializedEntity
&Entity
) {
6625 switch (Entity
.getKind()) {
6626 case InitializedEntity::EK_ArrayElement
:
6627 case InitializedEntity::EK_Member
:
6628 case InitializedEntity::EK_ParenAggInitMember
:
6629 case InitializedEntity::EK_Result
:
6630 case InitializedEntity::EK_StmtExprResult
:
6631 case InitializedEntity::EK_New
:
6632 case InitializedEntity::EK_Variable
:
6633 case InitializedEntity::EK_Base
:
6634 case InitializedEntity::EK_Delegating
:
6635 case InitializedEntity::EK_VectorElement
:
6636 case InitializedEntity::EK_ComplexElement
:
6637 case InitializedEntity::EK_Exception
:
6638 case InitializedEntity::EK_BlockElement
:
6639 case InitializedEntity::EK_LambdaToBlockConversionBlockElement
:
6640 case InitializedEntity::EK_LambdaCapture
:
6641 case InitializedEntity::EK_CompoundLiteralInit
:
6642 case InitializedEntity::EK_TemplateParameter
:
6645 case InitializedEntity::EK_Parameter
:
6646 case InitializedEntity::EK_Parameter_CF_Audited
:
6647 case InitializedEntity::EK_Temporary
:
6648 case InitializedEntity::EK_RelatedResult
:
6649 case InitializedEntity::EK_Binding
:
6653 llvm_unreachable("missed an InitializedEntity kind?");
6656 /// Whether the given entity, when initialized with an object
6657 /// created for that initialization, requires destruction.
6658 static bool shouldDestroyEntity(const InitializedEntity
&Entity
) {
6659 switch (Entity
.getKind()) {
6660 case InitializedEntity::EK_Result
:
6661 case InitializedEntity::EK_StmtExprResult
:
6662 case InitializedEntity::EK_New
:
6663 case InitializedEntity::EK_Base
:
6664 case InitializedEntity::EK_Delegating
:
6665 case InitializedEntity::EK_VectorElement
:
6666 case InitializedEntity::EK_ComplexElement
:
6667 case InitializedEntity::EK_BlockElement
:
6668 case InitializedEntity::EK_LambdaToBlockConversionBlockElement
:
6669 case InitializedEntity::EK_LambdaCapture
:
6672 case InitializedEntity::EK_Member
:
6673 case InitializedEntity::EK_ParenAggInitMember
:
6674 case InitializedEntity::EK_Binding
:
6675 case InitializedEntity::EK_Variable
:
6676 case InitializedEntity::EK_Parameter
:
6677 case InitializedEntity::EK_Parameter_CF_Audited
:
6678 case InitializedEntity::EK_TemplateParameter
:
6679 case InitializedEntity::EK_Temporary
:
6680 case InitializedEntity::EK_ArrayElement
:
6681 case InitializedEntity::EK_Exception
:
6682 case InitializedEntity::EK_CompoundLiteralInit
:
6683 case InitializedEntity::EK_RelatedResult
:
6687 llvm_unreachable("missed an InitializedEntity kind?");
6690 /// Get the location at which initialization diagnostics should appear.
6691 static SourceLocation
getInitializationLoc(const InitializedEntity
&Entity
,
6692 Expr
*Initializer
) {
6693 switch (Entity
.getKind()) {
6694 case InitializedEntity::EK_Result
:
6695 case InitializedEntity::EK_StmtExprResult
:
6696 return Entity
.getReturnLoc();
6698 case InitializedEntity::EK_Exception
:
6699 return Entity
.getThrowLoc();
6701 case InitializedEntity::EK_Variable
:
6702 case InitializedEntity::EK_Binding
:
6703 return Entity
.getDecl()->getLocation();
6705 case InitializedEntity::EK_LambdaCapture
:
6706 return Entity
.getCaptureLoc();
6708 case InitializedEntity::EK_ArrayElement
:
6709 case InitializedEntity::EK_Member
:
6710 case InitializedEntity::EK_ParenAggInitMember
:
6711 case InitializedEntity::EK_Parameter
:
6712 case InitializedEntity::EK_Parameter_CF_Audited
:
6713 case InitializedEntity::EK_TemplateParameter
:
6714 case InitializedEntity::EK_Temporary
:
6715 case InitializedEntity::EK_New
:
6716 case InitializedEntity::EK_Base
:
6717 case InitializedEntity::EK_Delegating
:
6718 case InitializedEntity::EK_VectorElement
:
6719 case InitializedEntity::EK_ComplexElement
:
6720 case InitializedEntity::EK_BlockElement
:
6721 case InitializedEntity::EK_LambdaToBlockConversionBlockElement
:
6722 case InitializedEntity::EK_CompoundLiteralInit
:
6723 case InitializedEntity::EK_RelatedResult
:
6724 return Initializer
->getBeginLoc();
6726 llvm_unreachable("missed an InitializedEntity kind?");
6729 /// Make a (potentially elidable) temporary copy of the object
6730 /// provided by the given initializer by calling the appropriate copy
6733 /// \param S The Sema object used for type-checking.
6735 /// \param T The type of the temporary object, which must either be
6736 /// the type of the initializer expression or a superclass thereof.
6738 /// \param Entity The entity being initialized.
6740 /// \param CurInit The initializer expression.
6742 /// \param IsExtraneousCopy Whether this is an "extraneous" copy that
6743 /// is permitted in C++03 (but not C++0x) when binding a reference to
6746 /// \returns An expression that copies the initializer expression into
6747 /// a temporary object, or an error expression if a copy could not be
6749 static ExprResult
CopyObject(Sema
&S
,
6751 const InitializedEntity
&Entity
,
6753 bool IsExtraneousCopy
) {
6754 if (CurInit
.isInvalid())
6756 // Determine which class type we're copying to.
6757 Expr
*CurInitExpr
= (Expr
*)CurInit
.get();
6758 CXXRecordDecl
*Class
= nullptr;
6759 if (const RecordType
*Record
= T
->getAs
<RecordType
>())
6760 Class
= cast
<CXXRecordDecl
>(Record
->getDecl());
6764 SourceLocation Loc
= getInitializationLoc(Entity
, CurInit
.get());
6766 // Make sure that the type we are copying is complete.
6767 if (S
.RequireCompleteType(Loc
, T
, diag::err_temp_copy_incomplete
))
6770 // Perform overload resolution using the class's constructors. Per
6771 // C++11 [dcl.init]p16, second bullet for class types, this initialization
6772 // is direct-initialization.
6773 OverloadCandidateSet
CandidateSet(Loc
, OverloadCandidateSet::CSK_Normal
);
6774 DeclContext::lookup_result Ctors
= S
.LookupConstructors(Class
);
6776 OverloadCandidateSet::iterator Best
;
6777 switch (ResolveConstructorOverload(
6778 S
, Loc
, CurInitExpr
, CandidateSet
, T
, Ctors
, Best
,
6779 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
6780 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
6781 /*SecondStepOfCopyInit=*/true)) {
6785 case OR_No_Viable_Function
:
6786 CandidateSet
.NoteCandidates(
6787 PartialDiagnosticAt(
6788 Loc
, S
.PDiag(IsExtraneousCopy
&& !S
.isSFINAEContext()
6789 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
6790 : diag::err_temp_copy_no_viable
)
6791 << (int)Entity
.getKind() << CurInitExpr
->getType()
6792 << CurInitExpr
->getSourceRange()),
6793 S
, OCD_AllCandidates
, CurInitExpr
);
6794 if (!IsExtraneousCopy
|| S
.isSFINAEContext())
6799 CandidateSet
.NoteCandidates(
6800 PartialDiagnosticAt(Loc
, S
.PDiag(diag::err_temp_copy_ambiguous
)
6801 << (int)Entity
.getKind()
6802 << CurInitExpr
->getType()
6803 << CurInitExpr
->getSourceRange()),
6804 S
, OCD_AmbiguousCandidates
, CurInitExpr
);
6808 S
.Diag(Loc
, diag::err_temp_copy_deleted
)
6809 << (int)Entity
.getKind() << CurInitExpr
->getType()
6810 << CurInitExpr
->getSourceRange();
6811 S
.NoteDeletedFunction(Best
->Function
);
6815 bool HadMultipleCandidates
= CandidateSet
.size() > 1;
6817 CXXConstructorDecl
*Constructor
= cast
<CXXConstructorDecl
>(Best
->Function
);
6818 SmallVector
<Expr
*, 8> ConstructorArgs
;
6819 CurInit
.get(); // Ownership transferred into MultiExprArg, below.
6821 S
.CheckConstructorAccess(Loc
, Constructor
, Best
->FoundDecl
, Entity
,
6824 if (IsExtraneousCopy
) {
6825 // If this is a totally extraneous copy for C++03 reference
6826 // binding purposes, just return the original initialization
6827 // expression. We don't generate an (elided) copy operation here
6828 // because doing so would require us to pass down a flag to avoid
6829 // infinite recursion, where each step adds another extraneous,
6832 // Instantiate the default arguments of any extra parameters in
6833 // the selected copy constructor, as if we were going to create a
6834 // proper call to the copy constructor.
6835 for (unsigned I
= 1, N
= Constructor
->getNumParams(); I
!= N
; ++I
) {
6836 ParmVarDecl
*Parm
= Constructor
->getParamDecl(I
);
6837 if (S
.RequireCompleteType(Loc
, Parm
->getType(),
6838 diag::err_call_incomplete_argument
))
6841 // Build the default argument expression; we don't actually care
6842 // if this succeeds or not, because this routine will complain
6843 // if there was a problem.
6844 S
.BuildCXXDefaultArgExpr(Loc
, Constructor
, Parm
);
6850 // Determine the arguments required to actually perform the
6851 // constructor call (we might have derived-to-base conversions, or
6852 // the copy constructor may have default arguments).
6853 if (S
.CompleteConstructorCall(Constructor
, T
, CurInitExpr
, Loc
,
6857 // C++0x [class.copy]p32:
6858 // When certain criteria are met, an implementation is allowed to
6859 // omit the copy/move construction of a class object, even if the
6860 // copy/move constructor and/or destructor for the object have
6861 // side effects. [...]
6862 // - when a temporary class object that has not been bound to a
6863 // reference (12.2) would be copied/moved to a class object
6864 // with the same cv-unqualified type, the copy/move operation
6865 // can be omitted by constructing the temporary object
6866 // directly into the target of the omitted copy/move
6868 // Note that the other three bullets are handled elsewhere. Copy
6869 // elision for return statements and throw expressions are handled as part
6870 // of constructor initialization, while copy elision for exception handlers
6871 // is handled by the run-time.
6873 // FIXME: If the function parameter is not the same type as the temporary, we
6874 // should still be able to elide the copy, but we don't have a way to
6875 // represent in the AST how much should be elided in this case.
6877 CurInitExpr
->isTemporaryObject(S
.Context
, Class
) &&
6878 S
.Context
.hasSameUnqualifiedType(
6879 Best
->Function
->getParamDecl(0)->getType().getNonReferenceType(),
6880 CurInitExpr
->getType());
6882 // Actually perform the constructor call.
6883 CurInit
= S
.BuildCXXConstructExpr(Loc
, T
, Best
->FoundDecl
, Constructor
,
6886 HadMultipleCandidates
,
6888 /*StdInitListInit*/ false,
6890 CXXConstructExpr::CK_Complete
,
6893 // If we're supposed to bind temporaries, do so.
6894 if (!CurInit
.isInvalid() && shouldBindAsTemporary(Entity
))
6895 CurInit
= S
.MaybeBindToTemporary(CurInit
.getAs
<Expr
>());
6899 /// Check whether elidable copy construction for binding a reference to
6900 /// a temporary would have succeeded if we were building in C++98 mode, for
6902 static void CheckCXX98CompatAccessibleCopy(Sema
&S
,
6903 const InitializedEntity
&Entity
,
6904 Expr
*CurInitExpr
) {
6905 assert(S
.getLangOpts().CPlusPlus11
);
6907 const RecordType
*Record
= CurInitExpr
->getType()->getAs
<RecordType
>();
6911 SourceLocation Loc
= getInitializationLoc(Entity
, CurInitExpr
);
6912 if (S
.Diags
.isIgnored(diag::warn_cxx98_compat_temp_copy
, Loc
))
6915 // Find constructors which would have been considered.
6916 OverloadCandidateSet
CandidateSet(Loc
, OverloadCandidateSet::CSK_Normal
);
6917 DeclContext::lookup_result Ctors
=
6918 S
.LookupConstructors(cast
<CXXRecordDecl
>(Record
->getDecl()));
6920 // Perform overload resolution.
6921 OverloadCandidateSet::iterator Best
;
6922 OverloadingResult OR
= ResolveConstructorOverload(
6923 S
, Loc
, CurInitExpr
, CandidateSet
, CurInitExpr
->getType(), Ctors
, Best
,
6924 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
6925 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
6926 /*SecondStepOfCopyInit=*/true);
6928 PartialDiagnostic Diag
= S
.PDiag(diag::warn_cxx98_compat_temp_copy
)
6929 << OR
<< (int)Entity
.getKind() << CurInitExpr
->getType()
6930 << CurInitExpr
->getSourceRange();
6934 S
.CheckConstructorAccess(Loc
, cast
<CXXConstructorDecl
>(Best
->Function
),
6935 Best
->FoundDecl
, Entity
, Diag
);
6936 // FIXME: Check default arguments as far as that's possible.
6939 case OR_No_Viable_Function
:
6940 CandidateSet
.NoteCandidates(PartialDiagnosticAt(Loc
, Diag
), S
,
6941 OCD_AllCandidates
, CurInitExpr
);
6945 CandidateSet
.NoteCandidates(PartialDiagnosticAt(Loc
, Diag
), S
,
6946 OCD_AmbiguousCandidates
, CurInitExpr
);
6951 S
.NoteDeletedFunction(Best
->Function
);
6956 void InitializationSequence::PrintInitLocationNote(Sema
&S
,
6957 const InitializedEntity
&Entity
) {
6958 if (Entity
.isParamOrTemplateParamKind() && Entity
.getDecl()) {
6959 if (Entity
.getDecl()->getLocation().isInvalid())
6962 if (Entity
.getDecl()->getDeclName())
6963 S
.Diag(Entity
.getDecl()->getLocation(), diag::note_parameter_named_here
)
6964 << Entity
.getDecl()->getDeclName();
6966 S
.Diag(Entity
.getDecl()->getLocation(), diag::note_parameter_here
);
6968 else if (Entity
.getKind() == InitializedEntity::EK_RelatedResult
&&
6969 Entity
.getMethodDecl())
6970 S
.Diag(Entity
.getMethodDecl()->getLocation(),
6971 diag::note_method_return_type_change
)
6972 << Entity
.getMethodDecl()->getDeclName();
6975 /// Returns true if the parameters describe a constructor initialization of
6976 /// an explicit temporary object, e.g. "Point(x, y)".
6977 static bool isExplicitTemporary(const InitializedEntity
&Entity
,
6978 const InitializationKind
&Kind
,
6980 switch (Entity
.getKind()) {
6981 case InitializedEntity::EK_Temporary
:
6982 case InitializedEntity::EK_CompoundLiteralInit
:
6983 case InitializedEntity::EK_RelatedResult
:
6989 switch (Kind
.getKind()) {
6990 case InitializationKind::IK_DirectList
:
6992 // FIXME: Hack to work around cast weirdness.
6993 case InitializationKind::IK_Direct
:
6994 case InitializationKind::IK_Value
:
6995 return NumArgs
!= 1;
7002 PerformConstructorInitialization(Sema
&S
,
7003 const InitializedEntity
&Entity
,
7004 const InitializationKind
&Kind
,
7006 const InitializationSequence::Step
& Step
,
7007 bool &ConstructorInitRequiresZeroInit
,
7008 bool IsListInitialization
,
7009 bool IsStdInitListInitialization
,
7010 SourceLocation LBraceLoc
,
7011 SourceLocation RBraceLoc
) {
7012 unsigned NumArgs
= Args
.size();
7013 CXXConstructorDecl
*Constructor
7014 = cast
<CXXConstructorDecl
>(Step
.Function
.Function
);
7015 bool HadMultipleCandidates
= Step
.Function
.HadMultipleCandidates
;
7017 // Build a call to the selected constructor.
7018 SmallVector
<Expr
*, 8> ConstructorArgs
;
7019 SourceLocation Loc
= (Kind
.isCopyInit() && Kind
.getEqualLoc().isValid())
7020 ? Kind
.getEqualLoc()
7021 : Kind
.getLocation();
7023 if (Kind
.getKind() == InitializationKind::IK_Default
) {
7024 // Force even a trivial, implicit default constructor to be
7025 // semantically checked. We do this explicitly because we don't build
7026 // the definition for completely trivial constructors.
7027 assert(Constructor
->getParent() && "No parent class for constructor.");
7028 if (Constructor
->isDefaulted() && Constructor
->isDefaultConstructor() &&
7029 Constructor
->isTrivial() && !Constructor
->isUsed(false)) {
7030 S
.runWithSufficientStackSpace(Loc
, [&] {
7031 S
.DefineImplicitDefaultConstructor(Loc
, Constructor
);
7036 ExprResult
CurInit((Expr
*)nullptr);
7038 // C++ [over.match.copy]p1:
7039 // - When initializing a temporary to be bound to the first parameter
7040 // of a constructor that takes a reference to possibly cv-qualified
7041 // T as its first argument, called with a single argument in the
7042 // context of direct-initialization, explicit conversion functions
7043 // are also considered.
7044 bool AllowExplicitConv
=
7045 Kind
.AllowExplicit() && !Kind
.isCopyInit() && Args
.size() == 1 &&
7046 hasCopyOrMoveCtorParam(S
.Context
,
7047 getConstructorInfo(Step
.Function
.FoundDecl
));
7049 // Determine the arguments required to actually perform the constructor
7051 if (S
.CompleteConstructorCall(Constructor
, Step
.Type
, Args
, Loc
,
7052 ConstructorArgs
, AllowExplicitConv
,
7053 IsListInitialization
))
7056 if (isExplicitTemporary(Entity
, Kind
, NumArgs
)) {
7057 // An explicitly-constructed temporary, e.g., X(1, 2).
7058 if (S
.DiagnoseUseOfDecl(Step
.Function
.FoundDecl
, Loc
))
7061 TypeSourceInfo
*TSInfo
= Entity
.getTypeSourceInfo();
7063 TSInfo
= S
.Context
.getTrivialTypeSourceInfo(Entity
.getType(), Loc
);
7064 SourceRange ParenOrBraceRange
=
7065 (Kind
.getKind() == InitializationKind::IK_DirectList
)
7066 ? SourceRange(LBraceLoc
, RBraceLoc
)
7067 : Kind
.getParenOrBraceRange();
7069 CXXConstructorDecl
*CalleeDecl
= Constructor
;
7070 if (auto *Shadow
= dyn_cast
<ConstructorUsingShadowDecl
>(
7071 Step
.Function
.FoundDecl
.getDecl())) {
7072 CalleeDecl
= S
.findInheritingConstructor(Loc
, Constructor
, Shadow
);
7074 S
.MarkFunctionReferenced(Loc
, CalleeDecl
);
7076 CurInit
= S
.CheckForImmediateInvocation(
7077 CXXTemporaryObjectExpr::Create(
7078 S
.Context
, CalleeDecl
,
7079 Entity
.getType().getNonLValueExprType(S
.Context
), TSInfo
,
7080 ConstructorArgs
, ParenOrBraceRange
, HadMultipleCandidates
,
7081 IsListInitialization
, IsStdInitListInitialization
,
7082 ConstructorInitRequiresZeroInit
),
7085 CXXConstructExpr::ConstructionKind ConstructKind
=
7086 CXXConstructExpr::CK_Complete
;
7088 if (Entity
.getKind() == InitializedEntity::EK_Base
) {
7089 ConstructKind
= Entity
.getBaseSpecifier()->isVirtual() ?
7090 CXXConstructExpr::CK_VirtualBase
:
7091 CXXConstructExpr::CK_NonVirtualBase
;
7092 } else if (Entity
.getKind() == InitializedEntity::EK_Delegating
) {
7093 ConstructKind
= CXXConstructExpr::CK_Delegating
;
7096 // Only get the parenthesis or brace range if it is a list initialization or
7097 // direct construction.
7098 SourceRange ParenOrBraceRange
;
7099 if (IsListInitialization
)
7100 ParenOrBraceRange
= SourceRange(LBraceLoc
, RBraceLoc
);
7101 else if (Kind
.getKind() == InitializationKind::IK_Direct
)
7102 ParenOrBraceRange
= Kind
.getParenOrBraceRange();
7104 // If the entity allows NRVO, mark the construction as elidable
7106 if (Entity
.allowsNRVO())
7107 CurInit
= S
.BuildCXXConstructExpr(Loc
, Step
.Type
,
7108 Step
.Function
.FoundDecl
,
7109 Constructor
, /*Elidable=*/true,
7111 HadMultipleCandidates
,
7112 IsListInitialization
,
7113 IsStdInitListInitialization
,
7114 ConstructorInitRequiresZeroInit
,
7118 CurInit
= S
.BuildCXXConstructExpr(Loc
, Step
.Type
,
7119 Step
.Function
.FoundDecl
,
7122 HadMultipleCandidates
,
7123 IsListInitialization
,
7124 IsStdInitListInitialization
,
7125 ConstructorInitRequiresZeroInit
,
7129 if (CurInit
.isInvalid())
7132 // Only check access if all of that succeeded.
7133 S
.CheckConstructorAccess(Loc
, Constructor
, Step
.Function
.FoundDecl
, Entity
);
7134 if (S
.DiagnoseUseOfDecl(Step
.Function
.FoundDecl
, Loc
))
7137 if (const ArrayType
*AT
= S
.Context
.getAsArrayType(Entity
.getType()))
7138 if (checkDestructorReference(S
.Context
.getBaseElementType(AT
), Loc
, S
))
7141 if (shouldBindAsTemporary(Entity
))
7142 CurInit
= S
.MaybeBindToTemporary(CurInit
.get());
7149 /// The lifetime of a temporary bound to this entity ends at the end of the
7150 /// full-expression, and that's (probably) fine.
7153 /// The lifetime of a temporary bound to this entity is extended to the
7154 /// lifeitme of the entity itself.
7157 /// The lifetime of a temporary bound to this entity probably ends too soon,
7158 /// because the entity is allocated in a new-expression.
7161 /// The lifetime of a temporary bound to this entity ends too soon, because
7162 /// the entity is a return object.
7165 /// The lifetime of a temporary bound to this entity ends too soon, because
7166 /// the entity is the result of a statement expression.
7169 /// This is a mem-initializer: if it would extend a temporary (other than via
7170 /// a default member initializer), the program is ill-formed.
7173 using LifetimeResult
=
7174 llvm::PointerIntPair
<const InitializedEntity
*, 3, LifetimeKind
>;
7177 /// Determine the declaration which an initialized entity ultimately refers to,
7178 /// for the purpose of lifetime-extending a temporary bound to a reference in
7179 /// the initialization of \p Entity.
7180 static LifetimeResult
getEntityLifetime(
7181 const InitializedEntity
*Entity
,
7182 const InitializedEntity
*InitField
= nullptr) {
7183 // C++11 [class.temporary]p5:
7184 switch (Entity
->getKind()) {
7185 case InitializedEntity::EK_Variable
:
7186 // The temporary [...] persists for the lifetime of the reference
7187 return {Entity
, LK_Extended
};
7189 case InitializedEntity::EK_Member
:
7190 // For subobjects, we look at the complete object.
7191 if (Entity
->getParent())
7192 return getEntityLifetime(Entity
->getParent(), Entity
);
7195 // C++17 [class.base.init]p8:
7196 // A temporary expression bound to a reference member in a
7197 // mem-initializer is ill-formed.
7198 // C++17 [class.base.init]p11:
7199 // A temporary expression bound to a reference member from a
7200 // default member initializer is ill-formed.
7202 // The context of p11 and its example suggest that it's only the use of a
7203 // default member initializer from a constructor that makes the program
7204 // ill-formed, not its mere existence, and that it can even be used by
7205 // aggregate initialization.
7206 return {Entity
, Entity
->isDefaultMemberInitializer() ? LK_Extended
7207 : LK_MemInitializer
};
7209 case InitializedEntity::EK_Binding
:
7210 // Per [dcl.decomp]p3, the binding is treated as a variable of reference
7212 return {Entity
, LK_Extended
};
7214 case InitializedEntity::EK_Parameter
:
7215 case InitializedEntity::EK_Parameter_CF_Audited
:
7216 // -- A temporary bound to a reference parameter in a function call
7217 // persists until the completion of the full-expression containing
7219 return {nullptr, LK_FullExpression
};
7221 case InitializedEntity::EK_TemplateParameter
:
7222 // FIXME: This will always be ill-formed; should we eagerly diagnose it here?
7223 return {nullptr, LK_FullExpression
};
7225 case InitializedEntity::EK_Result
:
7226 // -- The lifetime of a temporary bound to the returned value in a
7227 // function return statement is not extended; the temporary is
7228 // destroyed at the end of the full-expression in the return statement.
7229 return {nullptr, LK_Return
};
7231 case InitializedEntity::EK_StmtExprResult
:
7232 // FIXME: Should we lifetime-extend through the result of a statement
7234 return {nullptr, LK_StmtExprResult
};
7236 case InitializedEntity::EK_New
:
7237 // -- A temporary bound to a reference in a new-initializer persists
7238 // until the completion of the full-expression containing the
7240 return {nullptr, LK_New
};
7242 case InitializedEntity::EK_Temporary
:
7243 case InitializedEntity::EK_CompoundLiteralInit
:
7244 case InitializedEntity::EK_RelatedResult
:
7245 // We don't yet know the storage duration of the surrounding temporary.
7246 // Assume it's got full-expression duration for now, it will patch up our
7247 // storage duration if that's not correct.
7248 return {nullptr, LK_FullExpression
};
7250 case InitializedEntity::EK_ArrayElement
:
7251 // For subobjects, we look at the complete object.
7252 return getEntityLifetime(Entity
->getParent(), InitField
);
7254 case InitializedEntity::EK_Base
:
7255 // For subobjects, we look at the complete object.
7256 if (Entity
->getParent())
7257 return getEntityLifetime(Entity
->getParent(), InitField
);
7258 return {InitField
, LK_MemInitializer
};
7260 case InitializedEntity::EK_Delegating
:
7261 // We can reach this case for aggregate initialization in a constructor:
7262 // struct A { int &&r; };
7263 // struct B : A { B() : A{0} {} };
7264 // In this case, use the outermost field decl as the context.
7265 return {InitField
, LK_MemInitializer
};
7267 case InitializedEntity::EK_BlockElement
:
7268 case InitializedEntity::EK_LambdaToBlockConversionBlockElement
:
7269 case InitializedEntity::EK_LambdaCapture
:
7270 case InitializedEntity::EK_VectorElement
:
7271 case InitializedEntity::EK_ComplexElement
:
7272 return {nullptr, LK_FullExpression
};
7274 case InitializedEntity::EK_Exception
:
7275 // FIXME: Can we diagnose lifetime problems with exceptions?
7276 return {nullptr, LK_FullExpression
};
7278 case InitializedEntity::EK_ParenAggInitMember
:
7279 // -- A temporary object bound to a reference element of an aggregate of
7280 // class type initialized from a parenthesized expression-list
7281 // [dcl.init, 9.3] persists until the completion of the full-expression
7282 // containing the expression-list.
7283 return {nullptr, LK_FullExpression
};
7286 llvm_unreachable("unknown entity kind");
7290 enum ReferenceKind
{
7291 /// Lifetime would be extended by a reference binding to a temporary.
7292 RK_ReferenceBinding
,
7293 /// Lifetime would be extended by a std::initializer_list object binding to
7294 /// its backing array.
7295 RK_StdInitializerList
,
7298 /// A temporary or local variable. This will be one of:
7299 /// * A MaterializeTemporaryExpr.
7300 /// * A DeclRefExpr whose declaration is a local.
7301 /// * An AddrLabelExpr.
7302 /// * A BlockExpr for a block with captures.
7303 using Local
= Expr
*;
7305 /// Expressions we stepped over when looking for the local state. Any steps
7306 /// that would inhibit lifetime extension or take us out of subexpressions of
7307 /// the initializer are included.
7308 struct IndirectLocalPathEntry
{
7322 const Decl
*D
= nullptr;
7323 const LambdaCapture
*Capture
;
7325 IndirectLocalPathEntry() {}
7326 IndirectLocalPathEntry(EntryKind K
, Expr
*E
) : Kind(K
), E(E
) {}
7327 IndirectLocalPathEntry(EntryKind K
, Expr
*E
, const Decl
*D
)
7328 : Kind(K
), E(E
), D(D
) {}
7329 IndirectLocalPathEntry(EntryKind K
, Expr
*E
, const LambdaCapture
*Capture
)
7330 : Kind(K
), E(E
), Capture(Capture
) {}
7333 using IndirectLocalPath
= llvm::SmallVectorImpl
<IndirectLocalPathEntry
>;
7335 struct RevertToOldSizeRAII
{
7336 IndirectLocalPath
&Path
;
7337 unsigned OldSize
= Path
.size();
7338 RevertToOldSizeRAII(IndirectLocalPath
&Path
) : Path(Path
) {}
7339 ~RevertToOldSizeRAII() { Path
.resize(OldSize
); }
7342 using LocalVisitor
= llvm::function_ref
<bool(IndirectLocalPath
&Path
, Local L
,
7346 static bool isVarOnPath(IndirectLocalPath
&Path
, VarDecl
*VD
) {
7348 if (E
.Kind
== IndirectLocalPathEntry::VarInit
&& E
.D
== VD
)
7353 static bool pathContainsInit(IndirectLocalPath
&Path
) {
7354 return llvm::any_of(Path
, [=](IndirectLocalPathEntry E
) {
7355 return E
.Kind
== IndirectLocalPathEntry::DefaultInit
||
7356 E
.Kind
== IndirectLocalPathEntry::VarInit
;
7360 static void visitLocalsRetainedByInitializer(IndirectLocalPath
&Path
,
7361 Expr
*Init
, LocalVisitor Visit
,
7362 bool RevisitSubinits
,
7363 bool EnableLifetimeWarnings
);
7365 static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath
&Path
,
7366 Expr
*Init
, ReferenceKind RK
,
7368 bool EnableLifetimeWarnings
);
7370 template <typename T
> static bool isRecordWithAttr(QualType Type
) {
7371 if (auto *RD
= Type
->getAsCXXRecordDecl())
7372 return RD
->hasAttr
<T
>();
7376 // Decl::isInStdNamespace will return false for iterators in some STL
7377 // implementations due to them being defined in a namespace outside of the std
7379 static bool isInStlNamespace(const Decl
*D
) {
7380 const DeclContext
*DC
= D
->getDeclContext();
7383 if (const auto *ND
= dyn_cast
<NamespaceDecl
>(DC
))
7384 if (const IdentifierInfo
*II
= ND
->getIdentifier()) {
7385 StringRef Name
= II
->getName();
7386 if (Name
.size() >= 2 && Name
.front() == '_' &&
7387 (Name
[1] == '_' || isUppercase(Name
[1])))
7391 return DC
->isStdNamespace();
7394 static bool shouldTrackImplicitObjectArg(const CXXMethodDecl
*Callee
) {
7395 if (auto *Conv
= dyn_cast_or_null
<CXXConversionDecl
>(Callee
))
7396 if (isRecordWithAttr
<PointerAttr
>(Conv
->getConversionType()))
7398 if (!isInStlNamespace(Callee
->getParent()))
7400 if (!isRecordWithAttr
<PointerAttr
>(
7401 Callee
->getFunctionObjectParameterType()) &&
7402 !isRecordWithAttr
<OwnerAttr
>(Callee
->getFunctionObjectParameterType()))
7404 if (Callee
->getReturnType()->isPointerType() ||
7405 isRecordWithAttr
<PointerAttr
>(Callee
->getReturnType())) {
7406 if (!Callee
->getIdentifier())
7408 return llvm::StringSwitch
<bool>(Callee
->getName())
7409 .Cases("begin", "rbegin", "cbegin", "crbegin", true)
7410 .Cases("end", "rend", "cend", "crend", true)
7411 .Cases("c_str", "data", "get", true)
7412 // Map and set types.
7413 .Cases("find", "equal_range", "lower_bound", "upper_bound", true)
7415 } else if (Callee
->getReturnType()->isReferenceType()) {
7416 if (!Callee
->getIdentifier()) {
7417 auto OO
= Callee
->getOverloadedOperator();
7418 return OO
== OverloadedOperatorKind::OO_Subscript
||
7419 OO
== OverloadedOperatorKind::OO_Star
;
7421 return llvm::StringSwitch
<bool>(Callee
->getName())
7422 .Cases("front", "back", "at", "top", "value", true)
7428 static bool shouldTrackFirstArgument(const FunctionDecl
*FD
) {
7429 if (!FD
->getIdentifier() || FD
->getNumParams() != 1)
7431 const auto *RD
= FD
->getParamDecl(0)->getType()->getPointeeCXXRecordDecl();
7432 if (!FD
->isInStdNamespace() || !RD
|| !RD
->isInStdNamespace())
7434 if (!isRecordWithAttr
<PointerAttr
>(QualType(RD
->getTypeForDecl(), 0)) &&
7435 !isRecordWithAttr
<OwnerAttr
>(QualType(RD
->getTypeForDecl(), 0)))
7437 if (FD
->getReturnType()->isPointerType() ||
7438 isRecordWithAttr
<PointerAttr
>(FD
->getReturnType())) {
7439 return llvm::StringSwitch
<bool>(FD
->getName())
7440 .Cases("begin", "rbegin", "cbegin", "crbegin", true)
7441 .Cases("end", "rend", "cend", "crend", true)
7444 } else if (FD
->getReturnType()->isReferenceType()) {
7445 return llvm::StringSwitch
<bool>(FD
->getName())
7446 .Cases("get", "any_cast", true)
7452 static void handleGslAnnotatedTypes(IndirectLocalPath
&Path
, Expr
*Call
,
7453 LocalVisitor Visit
) {
7454 auto VisitPointerArg
= [&](const Decl
*D
, Expr
*Arg
, bool Value
) {
7455 // We are not interested in the temporary base objects of gsl Pointers:
7456 // Temp().ptr; // Here ptr might not dangle.
7457 if (isa
<MemberExpr
>(Arg
->IgnoreImpCasts()))
7459 // Once we initialized a value with a reference, it can no longer dangle.
7461 for (const IndirectLocalPathEntry
&PE
: llvm::reverse(Path
)) {
7462 if (PE
.Kind
== IndirectLocalPathEntry::GslReferenceInit
)
7464 if (PE
.Kind
== IndirectLocalPathEntry::GslPointerInit
)
7469 Path
.push_back({Value
? IndirectLocalPathEntry::GslPointerInit
7470 : IndirectLocalPathEntry::GslReferenceInit
,
7472 if (Arg
->isGLValue())
7473 visitLocalsRetainedByReferenceBinding(Path
, Arg
, RK_ReferenceBinding
,
7475 /*EnableLifetimeWarnings=*/true);
7477 visitLocalsRetainedByInitializer(Path
, Arg
, Visit
, true,
7478 /*EnableLifetimeWarnings=*/true);
7482 if (auto *MCE
= dyn_cast
<CXXMemberCallExpr
>(Call
)) {
7483 const auto *MD
= cast_or_null
<CXXMethodDecl
>(MCE
->getDirectCallee());
7484 if (MD
&& shouldTrackImplicitObjectArg(MD
))
7485 VisitPointerArg(MD
, MCE
->getImplicitObjectArgument(),
7486 !MD
->getReturnType()->isReferenceType());
7488 } else if (auto *OCE
= dyn_cast
<CXXOperatorCallExpr
>(Call
)) {
7489 FunctionDecl
*Callee
= OCE
->getDirectCallee();
7490 if (Callee
&& Callee
->isCXXInstanceMember() &&
7491 shouldTrackImplicitObjectArg(cast
<CXXMethodDecl
>(Callee
)))
7492 VisitPointerArg(Callee
, OCE
->getArg(0),
7493 !Callee
->getReturnType()->isReferenceType());
7495 } else if (auto *CE
= dyn_cast
<CallExpr
>(Call
)) {
7496 FunctionDecl
*Callee
= CE
->getDirectCallee();
7497 if (Callee
&& shouldTrackFirstArgument(Callee
))
7498 VisitPointerArg(Callee
, CE
->getArg(0),
7499 !Callee
->getReturnType()->isReferenceType());
7503 if (auto *CCE
= dyn_cast
<CXXConstructExpr
>(Call
)) {
7504 const auto *Ctor
= CCE
->getConstructor();
7505 const CXXRecordDecl
*RD
= Ctor
->getParent();
7506 if (CCE
->getNumArgs() > 0 && RD
->hasAttr
<PointerAttr
>())
7507 VisitPointerArg(Ctor
->getParamDecl(0), CCE
->getArgs()[0], true);
7511 static bool implicitObjectParamIsLifetimeBound(const FunctionDecl
*FD
) {
7512 const TypeSourceInfo
*TSI
= FD
->getTypeSourceInfo();
7515 // Don't declare this variable in the second operand of the for-statement;
7516 // GCC miscompiles that by ending its lifetime before evaluating the
7517 // third operand. See gcc.gnu.org/PR86769.
7518 AttributedTypeLoc ATL
;
7519 for (TypeLoc TL
= TSI
->getTypeLoc();
7520 (ATL
= TL
.getAsAdjusted
<AttributedTypeLoc
>());
7521 TL
= ATL
.getModifiedLoc()) {
7522 if (ATL
.getAttrAs
<LifetimeBoundAttr
>())
7526 // Assume that all assignment operators with a "normal" return type return
7527 // *this, that is, an lvalue reference that is the same type as the implicit
7528 // object parameter (or the LHS for a non-member operator$=).
7529 OverloadedOperatorKind OO
= FD
->getDeclName().getCXXOverloadedOperator();
7530 if (OO
== OO_Equal
|| isCompoundAssignmentOperator(OO
)) {
7531 QualType RetT
= FD
->getReturnType();
7532 if (RetT
->isLValueReferenceType()) {
7533 ASTContext
&Ctx
= FD
->getASTContext();
7535 auto *MD
= dyn_cast
<CXXMethodDecl
>(FD
);
7536 if (MD
&& MD
->isCXXInstanceMember())
7537 LHST
= Ctx
.getLValueReferenceType(MD
->getFunctionObjectParameterType());
7539 LHST
= MD
->getParamDecl(0)->getType();
7540 if (Ctx
.hasSameType(RetT
, LHST
))
7548 static void visitLifetimeBoundArguments(IndirectLocalPath
&Path
, Expr
*Call
,
7549 LocalVisitor Visit
) {
7550 const FunctionDecl
*Callee
;
7551 ArrayRef
<Expr
*> Args
;
7553 if (auto *CE
= dyn_cast
<CallExpr
>(Call
)) {
7554 Callee
= CE
->getDirectCallee();
7555 Args
= llvm::ArrayRef(CE
->getArgs(), CE
->getNumArgs());
7557 auto *CCE
= cast
<CXXConstructExpr
>(Call
);
7558 Callee
= CCE
->getConstructor();
7559 Args
= llvm::ArrayRef(CCE
->getArgs(), CCE
->getNumArgs());
7564 Expr
*ObjectArg
= nullptr;
7565 if (isa
<CXXOperatorCallExpr
>(Call
) && Callee
->isCXXInstanceMember()) {
7566 ObjectArg
= Args
[0];
7567 Args
= Args
.slice(1);
7568 } else if (auto *MCE
= dyn_cast
<CXXMemberCallExpr
>(Call
)) {
7569 ObjectArg
= MCE
->getImplicitObjectArgument();
7572 auto VisitLifetimeBoundArg
= [&](const Decl
*D
, Expr
*Arg
) {
7573 Path
.push_back({IndirectLocalPathEntry::LifetimeBoundCall
, Arg
, D
});
7574 if (Arg
->isGLValue())
7575 visitLocalsRetainedByReferenceBinding(Path
, Arg
, RK_ReferenceBinding
,
7577 /*EnableLifetimeWarnings=*/false);
7579 visitLocalsRetainedByInitializer(Path
, Arg
, Visit
, true,
7580 /*EnableLifetimeWarnings=*/false);
7584 if (ObjectArg
&& implicitObjectParamIsLifetimeBound(Callee
))
7585 VisitLifetimeBoundArg(Callee
, ObjectArg
);
7587 for (unsigned I
= 0,
7588 N
= std::min
<unsigned>(Callee
->getNumParams(), Args
.size());
7590 if (Callee
->getParamDecl(I
)->hasAttr
<LifetimeBoundAttr
>())
7591 VisitLifetimeBoundArg(Callee
->getParamDecl(I
), Args
[I
]);
7595 /// Visit the locals that would be reachable through a reference bound to the
7596 /// glvalue expression \c Init.
7597 static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath
&Path
,
7598 Expr
*Init
, ReferenceKind RK
,
7600 bool EnableLifetimeWarnings
) {
7601 RevertToOldSizeRAII
RAII(Path
);
7603 // Walk past any constructs which we can lifetime-extend across.
7608 if (auto *FE
= dyn_cast
<FullExpr
>(Init
))
7609 Init
= FE
->getSubExpr();
7611 if (InitListExpr
*ILE
= dyn_cast
<InitListExpr
>(Init
)) {
7612 // If this is just redundant braces around an initializer, step over it.
7613 if (ILE
->isTransparent())
7614 Init
= ILE
->getInit(0);
7617 // Step over any subobject adjustments; we may have a materialized
7618 // temporary inside them.
7619 Init
= const_cast<Expr
*>(Init
->skipRValueSubobjectAdjustments());
7621 // Per current approach for DR1376, look through casts to reference type
7622 // when performing lifetime extension.
7623 if (CastExpr
*CE
= dyn_cast
<CastExpr
>(Init
))
7624 if (CE
->getSubExpr()->isGLValue())
7625 Init
= CE
->getSubExpr();
7627 // Per the current approach for DR1299, look through array element access
7628 // on array glvalues when performing lifetime extension.
7629 if (auto *ASE
= dyn_cast
<ArraySubscriptExpr
>(Init
)) {
7630 Init
= ASE
->getBase();
7631 auto *ICE
= dyn_cast
<ImplicitCastExpr
>(Init
);
7632 if (ICE
&& ICE
->getCastKind() == CK_ArrayToPointerDecay
)
7633 Init
= ICE
->getSubExpr();
7635 // We can't lifetime extend through this but we might still find some
7636 // retained temporaries.
7637 return visitLocalsRetainedByInitializer(Path
, Init
, Visit
, true,
7638 EnableLifetimeWarnings
);
7641 // Step into CXXDefaultInitExprs so we can diagnose cases where a
7642 // constructor inherits one as an implicit mem-initializer.
7643 if (auto *DIE
= dyn_cast
<CXXDefaultInitExpr
>(Init
)) {
7645 {IndirectLocalPathEntry::DefaultInit
, DIE
, DIE
->getField()});
7646 Init
= DIE
->getExpr();
7648 } while (Init
!= Old
);
7650 if (auto *MTE
= dyn_cast
<MaterializeTemporaryExpr
>(Init
)) {
7651 if (Visit(Path
, Local(MTE
), RK
))
7652 visitLocalsRetainedByInitializer(Path
, MTE
->getSubExpr(), Visit
, true,
7653 EnableLifetimeWarnings
);
7656 if (isa
<CallExpr
>(Init
)) {
7657 if (EnableLifetimeWarnings
)
7658 handleGslAnnotatedTypes(Path
, Init
, Visit
);
7659 return visitLifetimeBoundArguments(Path
, Init
, Visit
);
7662 switch (Init
->getStmtClass()) {
7663 case Stmt::DeclRefExprClass
: {
7664 // If we find the name of a local non-reference parameter, we could have a
7665 // lifetime problem.
7666 auto *DRE
= cast
<DeclRefExpr
>(Init
);
7667 auto *VD
= dyn_cast
<VarDecl
>(DRE
->getDecl());
7668 if (VD
&& VD
->hasLocalStorage() &&
7669 !DRE
->refersToEnclosingVariableOrCapture()) {
7670 if (!VD
->getType()->isReferenceType()) {
7671 Visit(Path
, Local(DRE
), RK
);
7672 } else if (isa
<ParmVarDecl
>(DRE
->getDecl())) {
7673 // The lifetime of a reference parameter is unknown; assume it's OK
7676 } else if (VD
->getInit() && !isVarOnPath(Path
, VD
)) {
7677 Path
.push_back({IndirectLocalPathEntry::VarInit
, DRE
, VD
});
7678 visitLocalsRetainedByReferenceBinding(Path
, VD
->getInit(),
7679 RK_ReferenceBinding
, Visit
,
7680 EnableLifetimeWarnings
);
7686 case Stmt::UnaryOperatorClass
: {
7687 // The only unary operator that make sense to handle here
7688 // is Deref. All others don't resolve to a "name." This includes
7689 // handling all sorts of rvalues passed to a unary operator.
7690 const UnaryOperator
*U
= cast
<UnaryOperator
>(Init
);
7691 if (U
->getOpcode() == UO_Deref
)
7692 visitLocalsRetainedByInitializer(Path
, U
->getSubExpr(), Visit
, true,
7693 EnableLifetimeWarnings
);
7697 case Stmt::OMPArraySectionExprClass
: {
7698 visitLocalsRetainedByInitializer(Path
,
7699 cast
<OMPArraySectionExpr
>(Init
)->getBase(),
7700 Visit
, true, EnableLifetimeWarnings
);
7704 case Stmt::ConditionalOperatorClass
:
7705 case Stmt::BinaryConditionalOperatorClass
: {
7706 auto *C
= cast
<AbstractConditionalOperator
>(Init
);
7707 if (!C
->getTrueExpr()->getType()->isVoidType())
7708 visitLocalsRetainedByReferenceBinding(Path
, C
->getTrueExpr(), RK
, Visit
,
7709 EnableLifetimeWarnings
);
7710 if (!C
->getFalseExpr()->getType()->isVoidType())
7711 visitLocalsRetainedByReferenceBinding(Path
, C
->getFalseExpr(), RK
, Visit
,
7712 EnableLifetimeWarnings
);
7716 // FIXME: Visit the left-hand side of an -> or ->*.
7723 /// Visit the locals that would be reachable through an object initialized by
7724 /// the prvalue expression \c Init.
7725 static void visitLocalsRetainedByInitializer(IndirectLocalPath
&Path
,
7726 Expr
*Init
, LocalVisitor Visit
,
7727 bool RevisitSubinits
,
7728 bool EnableLifetimeWarnings
) {
7729 RevertToOldSizeRAII
RAII(Path
);
7735 // Step into CXXDefaultInitExprs so we can diagnose cases where a
7736 // constructor inherits one as an implicit mem-initializer.
7737 if (auto *DIE
= dyn_cast
<CXXDefaultInitExpr
>(Init
)) {
7738 Path
.push_back({IndirectLocalPathEntry::DefaultInit
, DIE
, DIE
->getField()});
7739 Init
= DIE
->getExpr();
7742 if (auto *FE
= dyn_cast
<FullExpr
>(Init
))
7743 Init
= FE
->getSubExpr();
7745 // Dig out the expression which constructs the extended temporary.
7746 Init
= const_cast<Expr
*>(Init
->skipRValueSubobjectAdjustments());
7748 if (CXXBindTemporaryExpr
*BTE
= dyn_cast
<CXXBindTemporaryExpr
>(Init
))
7749 Init
= BTE
->getSubExpr();
7751 Init
= Init
->IgnoreParens();
7753 // Step over value-preserving rvalue casts.
7754 if (auto *CE
= dyn_cast
<CastExpr
>(Init
)) {
7755 switch (CE
->getCastKind()) {
7756 case CK_LValueToRValue
:
7757 // If we can match the lvalue to a const object, we can look at its
7759 Path
.push_back({IndirectLocalPathEntry::LValToRVal
, CE
});
7760 return visitLocalsRetainedByReferenceBinding(
7761 Path
, Init
, RK_ReferenceBinding
,
7762 [&](IndirectLocalPath
&Path
, Local L
, ReferenceKind RK
) -> bool {
7763 if (auto *DRE
= dyn_cast
<DeclRefExpr
>(L
)) {
7764 auto *VD
= dyn_cast
<VarDecl
>(DRE
->getDecl());
7765 if (VD
&& VD
->getType().isConstQualified() && VD
->getInit() &&
7766 !isVarOnPath(Path
, VD
)) {
7767 Path
.push_back({IndirectLocalPathEntry::VarInit
, DRE
, VD
});
7768 visitLocalsRetainedByInitializer(Path
, VD
->getInit(), Visit
, true,
7769 EnableLifetimeWarnings
);
7771 } else if (auto *MTE
= dyn_cast
<MaterializeTemporaryExpr
>(L
)) {
7772 if (MTE
->getType().isConstQualified())
7773 visitLocalsRetainedByInitializer(Path
, MTE
->getSubExpr(), Visit
,
7774 true, EnableLifetimeWarnings
);
7777 }, EnableLifetimeWarnings
);
7779 // We assume that objects can be retained by pointers cast to integers,
7780 // but not if the integer is cast to floating-point type or to _Complex.
7781 // We assume that casts to 'bool' do not preserve enough information to
7782 // retain a local object.
7785 case CK_BaseToDerived
:
7786 case CK_DerivedToBase
:
7787 case CK_UncheckedDerivedToBase
:
7790 case CK_UserDefinedConversion
:
7791 case CK_ConstructorConversion
:
7792 case CK_IntegralToPointer
:
7793 case CK_PointerToIntegral
:
7794 case CK_VectorSplat
:
7795 case CK_IntegralCast
:
7796 case CK_CPointerToObjCPointerCast
:
7797 case CK_BlockPointerToObjCPointerCast
:
7798 case CK_AnyPointerToBlockPointerCast
:
7799 case CK_AddressSpaceConversion
:
7802 case CK_ArrayToPointerDecay
:
7803 // Model array-to-pointer decay as taking the address of the array
7805 Path
.push_back({IndirectLocalPathEntry::AddressOf
, CE
});
7806 return visitLocalsRetainedByReferenceBinding(Path
, CE
->getSubExpr(),
7807 RK_ReferenceBinding
, Visit
,
7808 EnableLifetimeWarnings
);
7814 Init
= CE
->getSubExpr();
7816 } while (Old
!= Init
);
7818 // C++17 [dcl.init.list]p6:
7819 // initializing an initializer_list object from the array extends the
7820 // lifetime of the array exactly like binding a reference to a temporary.
7821 if (auto *ILE
= dyn_cast
<CXXStdInitializerListExpr
>(Init
))
7822 return visitLocalsRetainedByReferenceBinding(Path
, ILE
->getSubExpr(),
7823 RK_StdInitializerList
, Visit
,
7824 EnableLifetimeWarnings
);
7826 if (InitListExpr
*ILE
= dyn_cast
<InitListExpr
>(Init
)) {
7827 // We already visited the elements of this initializer list while
7828 // performing the initialization. Don't visit them again unless we've
7829 // changed the lifetime of the initialized entity.
7830 if (!RevisitSubinits
)
7833 if (ILE
->isTransparent())
7834 return visitLocalsRetainedByInitializer(Path
, ILE
->getInit(0), Visit
,
7836 EnableLifetimeWarnings
);
7838 if (ILE
->getType()->isArrayType()) {
7839 for (unsigned I
= 0, N
= ILE
->getNumInits(); I
!= N
; ++I
)
7840 visitLocalsRetainedByInitializer(Path
, ILE
->getInit(I
), Visit
,
7842 EnableLifetimeWarnings
);
7846 if (CXXRecordDecl
*RD
= ILE
->getType()->getAsCXXRecordDecl()) {
7847 assert(RD
->isAggregate() && "aggregate init on non-aggregate");
7849 // If we lifetime-extend a braced initializer which is initializing an
7850 // aggregate, and that aggregate contains reference members which are
7851 // bound to temporaries, those temporaries are also lifetime-extended.
7852 if (RD
->isUnion() && ILE
->getInitializedFieldInUnion() &&
7853 ILE
->getInitializedFieldInUnion()->getType()->isReferenceType())
7854 visitLocalsRetainedByReferenceBinding(Path
, ILE
->getInit(0),
7855 RK_ReferenceBinding
, Visit
,
7856 EnableLifetimeWarnings
);
7859 for (; Index
< RD
->getNumBases() && Index
< ILE
->getNumInits(); ++Index
)
7860 visitLocalsRetainedByInitializer(Path
, ILE
->getInit(Index
), Visit
,
7862 EnableLifetimeWarnings
);
7863 for (const auto *I
: RD
->fields()) {
7864 if (Index
>= ILE
->getNumInits())
7866 if (I
->isUnnamedBitfield())
7868 Expr
*SubInit
= ILE
->getInit(Index
);
7869 if (I
->getType()->isReferenceType())
7870 visitLocalsRetainedByReferenceBinding(Path
, SubInit
,
7871 RK_ReferenceBinding
, Visit
,
7872 EnableLifetimeWarnings
);
7874 // This might be either aggregate-initialization of a member or
7875 // initialization of a std::initializer_list object. Regardless,
7876 // we should recursively lifetime-extend that initializer.
7877 visitLocalsRetainedByInitializer(Path
, SubInit
, Visit
,
7879 EnableLifetimeWarnings
);
7887 // The lifetime of an init-capture is that of the closure object constructed
7888 // by a lambda-expression.
7889 if (auto *LE
= dyn_cast
<LambdaExpr
>(Init
)) {
7890 LambdaExpr::capture_iterator CapI
= LE
->capture_begin();
7891 for (Expr
*E
: LE
->capture_inits()) {
7892 assert(CapI
!= LE
->capture_end());
7893 const LambdaCapture
&Cap
= *CapI
++;
7896 if (Cap
.capturesVariable())
7897 Path
.push_back({IndirectLocalPathEntry::LambdaCaptureInit
, E
, &Cap
});
7899 visitLocalsRetainedByReferenceBinding(Path
, E
, RK_ReferenceBinding
,
7900 Visit
, EnableLifetimeWarnings
);
7902 visitLocalsRetainedByInitializer(Path
, E
, Visit
, true,
7903 EnableLifetimeWarnings
);
7904 if (Cap
.capturesVariable())
7909 // Assume that a copy or move from a temporary references the same objects
7910 // that the temporary does.
7911 if (auto *CCE
= dyn_cast
<CXXConstructExpr
>(Init
)) {
7912 if (CCE
->getConstructor()->isCopyOrMoveConstructor()) {
7913 if (auto *MTE
= dyn_cast
<MaterializeTemporaryExpr
>(CCE
->getArg(0))) {
7914 Expr
*Arg
= MTE
->getSubExpr();
7915 Path
.push_back({IndirectLocalPathEntry::TemporaryCopy
, Arg
,
7916 CCE
->getConstructor()});
7917 visitLocalsRetainedByInitializer(Path
, Arg
, Visit
, true,
7918 /*EnableLifetimeWarnings*/false);
7924 if (isa
<CallExpr
>(Init
) || isa
<CXXConstructExpr
>(Init
)) {
7925 if (EnableLifetimeWarnings
)
7926 handleGslAnnotatedTypes(Path
, Init
, Visit
);
7927 return visitLifetimeBoundArguments(Path
, Init
, Visit
);
7930 switch (Init
->getStmtClass()) {
7931 case Stmt::UnaryOperatorClass
: {
7932 auto *UO
= cast
<UnaryOperator
>(Init
);
7933 // If the initializer is the address of a local, we could have a lifetime
7935 if (UO
->getOpcode() == UO_AddrOf
) {
7936 // If this is &rvalue, then it's ill-formed and we have already diagnosed
7937 // it. Don't produce a redundant warning about the lifetime of the
7939 if (isa
<MaterializeTemporaryExpr
>(UO
->getSubExpr()))
7942 Path
.push_back({IndirectLocalPathEntry::AddressOf
, UO
});
7943 visitLocalsRetainedByReferenceBinding(Path
, UO
->getSubExpr(),
7944 RK_ReferenceBinding
, Visit
,
7945 EnableLifetimeWarnings
);
7950 case Stmt::BinaryOperatorClass
: {
7951 // Handle pointer arithmetic.
7952 auto *BO
= cast
<BinaryOperator
>(Init
);
7953 BinaryOperatorKind BOK
= BO
->getOpcode();
7954 if (!BO
->getType()->isPointerType() || (BOK
!= BO_Add
&& BOK
!= BO_Sub
))
7957 if (BO
->getLHS()->getType()->isPointerType())
7958 visitLocalsRetainedByInitializer(Path
, BO
->getLHS(), Visit
, true,
7959 EnableLifetimeWarnings
);
7960 else if (BO
->getRHS()->getType()->isPointerType())
7961 visitLocalsRetainedByInitializer(Path
, BO
->getRHS(), Visit
, true,
7962 EnableLifetimeWarnings
);
7966 case Stmt::ConditionalOperatorClass
:
7967 case Stmt::BinaryConditionalOperatorClass
: {
7968 auto *C
= cast
<AbstractConditionalOperator
>(Init
);
7969 // In C++, we can have a throw-expression operand, which has 'void' type
7970 // and isn't interesting from a lifetime perspective.
7971 if (!C
->getTrueExpr()->getType()->isVoidType())
7972 visitLocalsRetainedByInitializer(Path
, C
->getTrueExpr(), Visit
, true,
7973 EnableLifetimeWarnings
);
7974 if (!C
->getFalseExpr()->getType()->isVoidType())
7975 visitLocalsRetainedByInitializer(Path
, C
->getFalseExpr(), Visit
, true,
7976 EnableLifetimeWarnings
);
7980 case Stmt::BlockExprClass
:
7981 if (cast
<BlockExpr
>(Init
)->getBlockDecl()->hasCaptures()) {
7982 // This is a local block, whose lifetime is that of the function.
7983 Visit(Path
, Local(cast
<BlockExpr
>(Init
)), RK_ReferenceBinding
);
7987 case Stmt::AddrLabelExprClass
:
7988 // We want to warn if the address of a label would escape the function.
7989 Visit(Path
, Local(cast
<AddrLabelExpr
>(Init
)), RK_ReferenceBinding
);
7997 /// Whether a path to an object supports lifetime extension.
7998 enum PathLifetimeKind
{
7999 /// Lifetime-extend along this path.
8001 /// We should lifetime-extend, but we don't because (due to technical
8002 /// limitations) we can't. This happens for default member initializers,
8003 /// which we don't clone for every use, so we don't have a unique
8004 /// MaterializeTemporaryExpr to update.
8006 /// Do not lifetime extend along this path.
8010 /// Determine whether this is an indirect path to a temporary that we are
8011 /// supposed to lifetime-extend along.
8012 static PathLifetimeKind
8013 shouldLifetimeExtendThroughPath(const IndirectLocalPath
&Path
) {
8014 PathLifetimeKind Kind
= PathLifetimeKind::Extend
;
8015 for (auto Elem
: Path
) {
8016 if (Elem
.Kind
== IndirectLocalPathEntry::DefaultInit
)
8017 Kind
= PathLifetimeKind::ShouldExtend
;
8018 else if (Elem
.Kind
!= IndirectLocalPathEntry::LambdaCaptureInit
)
8019 return PathLifetimeKind::NoExtend
;
8024 /// Find the range for the first interesting entry in the path at or after I.
8025 static SourceRange
nextPathEntryRange(const IndirectLocalPath
&Path
, unsigned I
,
8027 for (unsigned N
= Path
.size(); I
!= N
; ++I
) {
8028 switch (Path
[I
].Kind
) {
8029 case IndirectLocalPathEntry::AddressOf
:
8030 case IndirectLocalPathEntry::LValToRVal
:
8031 case IndirectLocalPathEntry::LifetimeBoundCall
:
8032 case IndirectLocalPathEntry::TemporaryCopy
:
8033 case IndirectLocalPathEntry::GslReferenceInit
:
8034 case IndirectLocalPathEntry::GslPointerInit
:
8035 // These exist primarily to mark the path as not permitting or
8036 // supporting lifetime extension.
8039 case IndirectLocalPathEntry::VarInit
:
8040 if (cast
<VarDecl
>(Path
[I
].D
)->isImplicit())
8041 return SourceRange();
8043 case IndirectLocalPathEntry::DefaultInit
:
8044 return Path
[I
].E
->getSourceRange();
8046 case IndirectLocalPathEntry::LambdaCaptureInit
:
8047 if (!Path
[I
].Capture
->capturesVariable())
8049 return Path
[I
].E
->getSourceRange();
8052 return E
->getSourceRange();
8055 static bool pathOnlyInitializesGslPointer(IndirectLocalPath
&Path
) {
8056 for (const auto &It
: llvm::reverse(Path
)) {
8057 if (It
.Kind
== IndirectLocalPathEntry::VarInit
)
8059 if (It
.Kind
== IndirectLocalPathEntry::AddressOf
)
8061 if (It
.Kind
== IndirectLocalPathEntry::LifetimeBoundCall
)
8063 return It
.Kind
== IndirectLocalPathEntry::GslPointerInit
||
8064 It
.Kind
== IndirectLocalPathEntry::GslReferenceInit
;
8069 void Sema::checkInitializerLifetime(const InitializedEntity
&Entity
,
8071 LifetimeResult LR
= getEntityLifetime(&Entity
);
8072 LifetimeKind LK
= LR
.getInt();
8073 const InitializedEntity
*ExtendingEntity
= LR
.getPointer();
8075 // If this entity doesn't have an interesting lifetime, don't bother looking
8076 // for temporaries within its initializer.
8077 if (LK
== LK_FullExpression
)
8080 auto TemporaryVisitor
= [&](IndirectLocalPath
&Path
, Local L
,
8081 ReferenceKind RK
) -> bool {
8082 SourceRange DiagRange
= nextPathEntryRange(Path
, 0, L
);
8083 SourceLocation DiagLoc
= DiagRange
.getBegin();
8085 auto *MTE
= dyn_cast
<MaterializeTemporaryExpr
>(L
);
8087 bool IsGslPtrInitWithGslTempOwner
= false;
8088 bool IsLocalGslOwner
= false;
8089 if (pathOnlyInitializesGslPointer(Path
)) {
8090 if (isa
<DeclRefExpr
>(L
)) {
8091 // We do not want to follow the references when returning a pointer originating
8092 // from a local owner to avoid the following false positive:
8093 // int &p = *localUniquePtr;
8094 // someContainer.add(std::move(localUniquePtr));
8096 IsLocalGslOwner
= isRecordWithAttr
<OwnerAttr
>(L
->getType());
8097 if (pathContainsInit(Path
) || !IsLocalGslOwner
)
8100 IsGslPtrInitWithGslTempOwner
= MTE
&& !MTE
->getExtendingDecl() &&
8101 isRecordWithAttr
<OwnerAttr
>(MTE
->getType());
8102 // Skipping a chain of initializing gsl::Pointer annotated objects.
8103 // We are looking only for the final source to find out if it was
8104 // a local or temporary owner or the address of a local variable/param.
8105 if (!IsGslPtrInitWithGslTempOwner
)
8111 case LK_FullExpression
:
8112 llvm_unreachable("already handled this");
8116 // The initialized entity has lifetime beyond the full-expression,
8117 // and the local entity does too, so don't warn.
8119 // FIXME: We should consider warning if a static / thread storage
8120 // duration variable retains an automatic storage duration local.
8124 if (IsGslPtrInitWithGslTempOwner
&& DiagLoc
.isValid()) {
8125 Diag(DiagLoc
, diag::warn_dangling_lifetime_pointer
) << DiagRange
;
8129 switch (shouldLifetimeExtendThroughPath(Path
)) {
8130 case PathLifetimeKind::Extend
:
8131 // Update the storage duration of the materialized temporary.
8132 // FIXME: Rebuild the expression instead of mutating it.
8133 MTE
->setExtendingDecl(ExtendingEntity
->getDecl(),
8134 ExtendingEntity
->allocateManglingNumber());
8135 // Also visit the temporaries lifetime-extended by this initializer.
8138 case PathLifetimeKind::ShouldExtend
:
8139 // We're supposed to lifetime-extend the temporary along this path (per
8140 // the resolution of DR1815), but we don't support that yet.
8142 // FIXME: Properly handle this situation. Perhaps the easiest approach
8143 // would be to clone the initializer expression on each use that would
8144 // lifetime extend its temporaries.
8145 Diag(DiagLoc
, diag::warn_unsupported_lifetime_extension
)
8149 case PathLifetimeKind::NoExtend
:
8150 // If the path goes through the initialization of a variable or field,
8151 // it can't possibly reach a temporary created in this full-expression.
8152 // We will have already diagnosed any problems with the initializer.
8153 if (pathContainsInit(Path
))
8156 Diag(DiagLoc
, diag::warn_dangling_variable
)
8157 << RK
<< !Entity
.getParent()
8158 << ExtendingEntity
->getDecl()->isImplicit()
8159 << ExtendingEntity
->getDecl() << Init
->isGLValue() << DiagRange
;
8165 case LK_MemInitializer
: {
8166 if (isa
<MaterializeTemporaryExpr
>(L
)) {
8167 // Under C++ DR1696, if a mem-initializer (or a default member
8168 // initializer used by the absence of one) would lifetime-extend a
8169 // temporary, the program is ill-formed.
8170 if (auto *ExtendingDecl
=
8171 ExtendingEntity
? ExtendingEntity
->getDecl() : nullptr) {
8172 if (IsGslPtrInitWithGslTempOwner
) {
8173 Diag(DiagLoc
, diag::warn_dangling_lifetime_pointer_member
)
8174 << ExtendingDecl
<< DiagRange
;
8175 Diag(ExtendingDecl
->getLocation(),
8176 diag::note_ref_or_ptr_member_declared_here
)
8180 bool IsSubobjectMember
= ExtendingEntity
!= &Entity
;
8181 Diag(DiagLoc
, shouldLifetimeExtendThroughPath(Path
) !=
8182 PathLifetimeKind::NoExtend
8183 ? diag::err_dangling_member
8184 : diag::warn_dangling_member
)
8185 << ExtendingDecl
<< IsSubobjectMember
<< RK
<< DiagRange
;
8186 // Don't bother adding a note pointing to the field if we're inside
8187 // its default member initializer; our primary diagnostic points to
8188 // the same place in that case.
8190 Path
.back().Kind
!= IndirectLocalPathEntry::DefaultInit
) {
8191 Diag(ExtendingDecl
->getLocation(),
8192 diag::note_lifetime_extending_member_declared_here
)
8193 << RK
<< IsSubobjectMember
;
8196 // We have a mem-initializer but no particular field within it; this
8197 // is either a base class or a delegating initializer directly
8198 // initializing the base-class from something that doesn't live long
8201 // FIXME: Warn on this.
8205 // Paths via a default initializer can only occur during error recovery
8206 // (there's no other way that a default initializer can refer to a
8207 // local). Don't produce a bogus warning on those cases.
8208 if (pathContainsInit(Path
))
8211 // Suppress false positives for code like the one below:
8212 // Ctor(unique_ptr<T> up) : member(*up), member2(move(up)) {}
8213 if (IsLocalGslOwner
&& pathOnlyInitializesGslPointer(Path
))
8216 auto *DRE
= dyn_cast
<DeclRefExpr
>(L
);
8217 auto *VD
= DRE
? dyn_cast
<VarDecl
>(DRE
->getDecl()) : nullptr;
8219 // A member was initialized to a local block.
8220 // FIXME: Warn on this.
8225 ExtendingEntity
? ExtendingEntity
->getDecl() : nullptr) {
8226 bool IsPointer
= !Member
->getType()->isReferenceType();
8227 Diag(DiagLoc
, IsPointer
? diag::warn_init_ptr_member_to_parameter_addr
8228 : diag::warn_bind_ref_member_to_parameter
)
8229 << Member
<< VD
<< isa
<ParmVarDecl
>(VD
) << DiagRange
;
8230 Diag(Member
->getLocation(),
8231 diag::note_ref_or_ptr_member_declared_here
)
8232 << (unsigned)IsPointer
;
8239 if (isa
<MaterializeTemporaryExpr
>(L
)) {
8240 if (IsGslPtrInitWithGslTempOwner
)
8241 Diag(DiagLoc
, diag::warn_dangling_lifetime_pointer
) << DiagRange
;
8243 Diag(DiagLoc
, RK
== RK_ReferenceBinding
8244 ? diag::warn_new_dangling_reference
8245 : diag::warn_new_dangling_initializer_list
)
8246 << !Entity
.getParent() << DiagRange
;
8248 // We can't determine if the allocation outlives the local declaration.
8254 case LK_StmtExprResult
:
8255 if (auto *DRE
= dyn_cast
<DeclRefExpr
>(L
)) {
8256 // We can't determine if the local variable outlives the statement
8258 if (LK
== LK_StmtExprResult
)
8260 Diag(DiagLoc
, diag::warn_ret_stack_addr_ref
)
8261 << Entity
.getType()->isReferenceType() << DRE
->getDecl()
8262 << isa
<ParmVarDecl
>(DRE
->getDecl()) << DiagRange
;
8263 } else if (isa
<BlockExpr
>(L
)) {
8264 Diag(DiagLoc
, diag::err_ret_local_block
) << DiagRange
;
8265 } else if (isa
<AddrLabelExpr
>(L
)) {
8266 // Don't warn when returning a label from a statement expression.
8267 // Leaving the scope doesn't end its lifetime.
8268 if (LK
== LK_StmtExprResult
)
8270 Diag(DiagLoc
, diag::warn_ret_addr_label
) << DiagRange
;
8272 Diag(DiagLoc
, diag::warn_ret_local_temp_addr_ref
)
8273 << Entity
.getType()->isReferenceType() << DiagRange
;
8278 for (unsigned I
= 0; I
!= Path
.size(); ++I
) {
8279 auto Elem
= Path
[I
];
8281 switch (Elem
.Kind
) {
8282 case IndirectLocalPathEntry::AddressOf
:
8283 case IndirectLocalPathEntry::LValToRVal
:
8284 // These exist primarily to mark the path as not permitting or
8285 // supporting lifetime extension.
8288 case IndirectLocalPathEntry::LifetimeBoundCall
:
8289 case IndirectLocalPathEntry::TemporaryCopy
:
8290 case IndirectLocalPathEntry::GslPointerInit
:
8291 case IndirectLocalPathEntry::GslReferenceInit
:
8292 // FIXME: Consider adding a note for these.
8295 case IndirectLocalPathEntry::DefaultInit
: {
8296 auto *FD
= cast
<FieldDecl
>(Elem
.D
);
8297 Diag(FD
->getLocation(), diag::note_init_with_default_member_initializer
)
8298 << FD
<< nextPathEntryRange(Path
, I
+ 1, L
);
8302 case IndirectLocalPathEntry::VarInit
: {
8303 const VarDecl
*VD
= cast
<VarDecl
>(Elem
.D
);
8304 Diag(VD
->getLocation(), diag::note_local_var_initializer
)
8305 << VD
->getType()->isReferenceType()
8306 << VD
->isImplicit() << VD
->getDeclName()
8307 << nextPathEntryRange(Path
, I
+ 1, L
);
8311 case IndirectLocalPathEntry::LambdaCaptureInit
:
8312 if (!Elem
.Capture
->capturesVariable())
8314 // FIXME: We can't easily tell apart an init-capture from a nested
8315 // capture of an init-capture.
8316 const ValueDecl
*VD
= Elem
.Capture
->getCapturedVar();
8317 Diag(Elem
.Capture
->getLocation(), diag::note_lambda_capture_initializer
)
8318 << VD
<< VD
->isInitCapture() << Elem
.Capture
->isExplicit()
8319 << (Elem
.Capture
->getCaptureKind() == LCK_ByRef
) << VD
8320 << nextPathEntryRange(Path
, I
+ 1, L
);
8325 // We didn't lifetime-extend, so don't go any further; we don't need more
8326 // warnings or errors on inner temporaries within this one's initializer.
8330 bool EnableLifetimeWarnings
= !getDiagnostics().isIgnored(
8331 diag::warn_dangling_lifetime_pointer
, SourceLocation());
8332 llvm::SmallVector
<IndirectLocalPathEntry
, 8> Path
;
8333 if (Init
->isGLValue())
8334 visitLocalsRetainedByReferenceBinding(Path
, Init
, RK_ReferenceBinding
,
8336 EnableLifetimeWarnings
);
8338 visitLocalsRetainedByInitializer(Path
, Init
, TemporaryVisitor
, false,
8339 EnableLifetimeWarnings
);
8342 static void DiagnoseNarrowingInInitList(Sema
&S
,
8343 const ImplicitConversionSequence
&ICS
,
8344 QualType PreNarrowingType
,
8345 QualType EntityType
,
8346 const Expr
*PostInit
);
8348 /// Provide warnings when std::move is used on construction.
8349 static void CheckMoveOnConstruction(Sema
&S
, const Expr
*InitExpr
,
8350 bool IsReturnStmt
) {
8354 if (S
.inTemplateInstantiation())
8357 QualType DestType
= InitExpr
->getType();
8358 if (!DestType
->isRecordType())
8361 unsigned DiagID
= 0;
8363 const CXXConstructExpr
*CCE
=
8364 dyn_cast
<CXXConstructExpr
>(InitExpr
->IgnoreParens());
8365 if (!CCE
|| CCE
->getNumArgs() != 1)
8368 if (!CCE
->getConstructor()->isCopyOrMoveConstructor())
8371 InitExpr
= CCE
->getArg(0)->IgnoreImpCasts();
8374 // Find the std::move call and get the argument.
8375 const CallExpr
*CE
= dyn_cast
<CallExpr
>(InitExpr
->IgnoreParens());
8376 if (!CE
|| !CE
->isCallToStdMove())
8379 const Expr
*Arg
= CE
->getArg(0)->IgnoreImplicit();
8382 const DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(Arg
->IgnoreParenImpCasts());
8383 if (!DRE
|| DRE
->refersToEnclosingVariableOrCapture())
8386 const VarDecl
*VD
= dyn_cast
<VarDecl
>(DRE
->getDecl());
8387 if (!VD
|| !VD
->hasLocalStorage())
8390 // __block variables are not moved implicitly.
8391 if (VD
->hasAttr
<BlocksAttr
>())
8394 QualType SourceType
= VD
->getType();
8395 if (!SourceType
->isRecordType())
8398 if (!S
.Context
.hasSameUnqualifiedType(DestType
, SourceType
)) {
8402 // If we're returning a function parameter, copy elision
8404 if (isa
<ParmVarDecl
>(VD
))
8405 DiagID
= diag::warn_redundant_move_on_return
;
8407 DiagID
= diag::warn_pessimizing_move_on_return
;
8409 DiagID
= diag::warn_pessimizing_move_on_initialization
;
8410 const Expr
*ArgStripped
= Arg
->IgnoreImplicit()->IgnoreParens();
8411 if (!ArgStripped
->isPRValue() || !ArgStripped
->getType()->isRecordType())
8415 S
.Diag(CE
->getBeginLoc(), DiagID
);
8417 // Get all the locations for a fix-it. Don't emit the fix-it if any location
8418 // is within a macro.
8419 SourceLocation CallBegin
= CE
->getCallee()->getBeginLoc();
8420 if (CallBegin
.isMacroID())
8422 SourceLocation RParen
= CE
->getRParenLoc();
8423 if (RParen
.isMacroID())
8425 SourceLocation LParen
;
8426 SourceLocation ArgLoc
= Arg
->getBeginLoc();
8428 // Special testing for the argument location. Since the fix-it needs the
8429 // location right before the argument, the argument location can be in a
8430 // macro only if it is at the beginning of the macro.
8431 while (ArgLoc
.isMacroID() &&
8432 S
.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc
)) {
8433 ArgLoc
= S
.getSourceManager().getImmediateExpansionRange(ArgLoc
).getBegin();
8436 if (LParen
.isMacroID())
8439 LParen
= ArgLoc
.getLocWithOffset(-1);
8441 S
.Diag(CE
->getBeginLoc(), diag::note_remove_move
)
8442 << FixItHint::CreateRemoval(SourceRange(CallBegin
, LParen
))
8443 << FixItHint::CreateRemoval(SourceRange(RParen
, RParen
));
8446 static void CheckForNullPointerDereference(Sema
&S
, const Expr
*E
) {
8447 // Check to see if we are dereferencing a null pointer. If so, this is
8448 // undefined behavior, so warn about it. This only handles the pattern
8449 // "*null", which is a very syntactic check.
8450 if (const UnaryOperator
*UO
= dyn_cast
<UnaryOperator
>(E
->IgnoreParenCasts()))
8451 if (UO
->getOpcode() == UO_Deref
&&
8452 UO
->getSubExpr()->IgnoreParenCasts()->
8453 isNullPointerConstant(S
.Context
, Expr::NPC_ValueDependentIsNotNull
)) {
8454 S
.DiagRuntimeBehavior(UO
->getOperatorLoc(), UO
,
8455 S
.PDiag(diag::warn_binding_null_to_reference
)
8456 << UO
->getSubExpr()->getSourceRange());
8460 MaterializeTemporaryExpr
*
8461 Sema::CreateMaterializeTemporaryExpr(QualType T
, Expr
*Temporary
,
8462 bool BoundToLvalueReference
) {
8463 auto MTE
= new (Context
)
8464 MaterializeTemporaryExpr(T
, Temporary
, BoundToLvalueReference
);
8466 // Order an ExprWithCleanups for lifetime marks.
8468 // TODO: It'll be good to have a single place to check the access of the
8469 // destructor and generate ExprWithCleanups for various uses. Currently these
8470 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
8471 // but there may be a chance to merge them.
8472 Cleanup
.setExprNeedsCleanups(false);
8476 ExprResult
Sema::TemporaryMaterializationConversion(Expr
*E
) {
8477 // In C++98, we don't want to implicitly create an xvalue.
8478 // FIXME: This means that AST consumers need to deal with "prvalues" that
8479 // denote materialized temporaries. Maybe we should add another ValueKind
8480 // for "xvalue pretending to be a prvalue" for C++98 support.
8481 if (!E
->isPRValue() || !getLangOpts().CPlusPlus11
)
8484 // C++1z [conv.rval]/1: T shall be a complete type.
8485 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
8486 // If so, we should check for a non-abstract class type here too.
8487 QualType T
= E
->getType();
8488 if (RequireCompleteType(E
->getExprLoc(), T
, diag::err_incomplete_type
))
8491 return CreateMaterializeTemporaryExpr(E
->getType(), E
, false);
8494 ExprResult
Sema::PerformQualificationConversion(Expr
*E
, QualType Ty
,
8496 CheckedConversionKind CCK
) {
8498 CastKind CK
= CK_NoOp
;
8500 if (VK
== VK_PRValue
) {
8501 auto PointeeTy
= Ty
->getPointeeType();
8502 auto ExprPointeeTy
= E
->getType()->getPointeeType();
8503 if (!PointeeTy
.isNull() &&
8504 PointeeTy
.getAddressSpace() != ExprPointeeTy
.getAddressSpace())
8505 CK
= CK_AddressSpaceConversion
;
8506 } else if (Ty
.getAddressSpace() != E
->getType().getAddressSpace()) {
8507 CK
= CK_AddressSpaceConversion
;
8510 return ImpCastExprToType(E
, Ty
, CK
, VK
, /*BasePath=*/nullptr, CCK
);
8513 ExprResult
InitializationSequence::Perform(Sema
&S
,
8514 const InitializedEntity
&Entity
,
8515 const InitializationKind
&Kind
,
8517 QualType
*ResultType
) {
8519 Diagnose(S
, Entity
, Kind
, Args
);
8522 if (!ZeroInitializationFixit
.empty()) {
8523 const Decl
*D
= Entity
.getDecl();
8524 const auto *VD
= dyn_cast_or_null
<VarDecl
>(D
);
8525 QualType DestType
= Entity
.getType();
8527 // The initialization would have succeeded with this fixit. Since the fixit
8528 // is on the error, we need to build a valid AST in this case, so this isn't
8529 // handled in the Failed() branch above.
8530 if (!DestType
->isRecordType() && VD
&& VD
->isConstexpr()) {
8531 // Use a more useful diagnostic for constexpr variables.
8532 S
.Diag(Kind
.getLocation(), diag::err_constexpr_var_requires_const_init
)
8534 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc
,
8535 ZeroInitializationFixit
);
8537 unsigned DiagID
= diag::err_default_init_const
;
8538 if (S
.getLangOpts().MSVCCompat
&& D
&& D
->hasAttr
<SelectAnyAttr
>())
8539 DiagID
= diag::ext_default_init_const
;
8541 S
.Diag(Kind
.getLocation(), DiagID
)
8542 << DestType
<< (bool)DestType
->getAs
<RecordType
>()
8543 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc
,
8544 ZeroInitializationFixit
);
8548 if (getKind() == DependentSequence
) {
8549 // If the declaration is a non-dependent, incomplete array type
8550 // that has an initializer, then its type will be completed once
8551 // the initializer is instantiated.
8552 if (ResultType
&& !Entity
.getType()->isDependentType() &&
8554 QualType DeclType
= Entity
.getType();
8555 if (const IncompleteArrayType
*ArrayT
8556 = S
.Context
.getAsIncompleteArrayType(DeclType
)) {
8557 // FIXME: We don't currently have the ability to accurately
8558 // compute the length of an initializer list without
8559 // performing full type-checking of the initializer list
8560 // (since we have to determine where braces are implicitly
8561 // introduced and such). So, we fall back to making the array
8562 // type a dependently-sized array type with no specified
8564 if (isa
<InitListExpr
>((Expr
*)Args
[0])) {
8565 SourceRange Brackets
;
8567 // Scavange the location of the brackets from the entity, if we can.
8568 if (auto *DD
= dyn_cast_or_null
<DeclaratorDecl
>(Entity
.getDecl())) {
8569 if (TypeSourceInfo
*TInfo
= DD
->getTypeSourceInfo()) {
8570 TypeLoc TL
= TInfo
->getTypeLoc();
8571 if (IncompleteArrayTypeLoc ArrayLoc
=
8572 TL
.getAs
<IncompleteArrayTypeLoc
>())
8573 Brackets
= ArrayLoc
.getBracketsRange();
8578 = S
.Context
.getDependentSizedArrayType(ArrayT
->getElementType(),
8579 /*NumElts=*/nullptr,
8580 ArrayT
->getSizeModifier(),
8581 ArrayT
->getIndexTypeCVRQualifiers(),
8587 if (Kind
.getKind() == InitializationKind::IK_Direct
&&
8588 !Kind
.isExplicitCast()) {
8589 // Rebuild the ParenListExpr.
8590 SourceRange ParenRange
= Kind
.getParenOrBraceRange();
8591 return S
.ActOnParenListExpr(ParenRange
.getBegin(), ParenRange
.getEnd(),
8594 assert(Kind
.getKind() == InitializationKind::IK_Copy
||
8595 Kind
.isExplicitCast() ||
8596 Kind
.getKind() == InitializationKind::IK_DirectList
);
8597 return ExprResult(Args
[0]);
8600 // No steps means no initialization.
8602 return ExprResult((Expr
*)nullptr);
8604 if (S
.getLangOpts().CPlusPlus11
&& Entity
.getType()->isReferenceType() &&
8605 Args
.size() == 1 && isa
<InitListExpr
>(Args
[0]) &&
8606 !Entity
.isParamOrTemplateParamKind()) {
8607 // Produce a C++98 compatibility warning if we are initializing a reference
8608 // from an initializer list. For parameters, we produce a better warning
8610 Expr
*Init
= Args
[0];
8611 S
.Diag(Init
->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init
)
8612 << Init
->getSourceRange();
8615 if (S
.getLangOpts().MicrosoftExt
&& Args
.size() == 1 &&
8616 isa
<PredefinedExpr
>(Args
[0]) && Entity
.getType()->isArrayType()) {
8617 // Produce a Microsoft compatibility warning when initializing from a
8618 // predefined expression since MSVC treats predefined expressions as string
8620 Expr
*Init
= Args
[0];
8621 S
.Diag(Init
->getBeginLoc(), diag::ext_init_from_predefined
) << Init
;
8624 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
8625 QualType ETy
= Entity
.getType();
8626 bool HasGlobalAS
= ETy
.hasAddressSpace() &&
8627 ETy
.getAddressSpace() == LangAS::opencl_global
;
8629 if (S
.getLangOpts().OpenCLVersion
>= 200 &&
8630 ETy
->isAtomicType() && !HasGlobalAS
&&
8631 Entity
.getKind() == InitializedEntity::EK_Variable
&& Args
.size() > 0) {
8632 S
.Diag(Args
[0]->getBeginLoc(), diag::err_opencl_atomic_init
)
8634 << SourceRange(Entity
.getDecl()->getBeginLoc(), Args
[0]->getEndLoc());
8638 QualType DestType
= Entity
.getType().getNonReferenceType();
8639 // FIXME: Ugly hack around the fact that Entity.getType() is not
8640 // the same as Entity.getDecl()->getType() in cases involving type merging,
8641 // and we want latter when it makes sense.
8643 *ResultType
= Entity
.getDecl() ? Entity
.getDecl()->getType() :
8646 ExprResult
CurInit((Expr
*)nullptr);
8647 SmallVector
<Expr
*, 4> ArrayLoopCommonExprs
;
8649 // HLSL allows vector initialization to function like list initialization, but
8650 // use the syntax of a C++-like constructor.
8651 bool IsHLSLVectorInit
= S
.getLangOpts().HLSL
&& DestType
->isExtVectorType() &&
8652 isa
<InitListExpr
>(Args
[0]);
8653 (void)IsHLSLVectorInit
;
8655 // For initialization steps that start with a single initializer,
8656 // grab the only argument out the Args and place it into the "current"
8658 switch (Steps
.front().Kind
) {
8659 case SK_ResolveAddressOfOverloadedFunction
:
8660 case SK_CastDerivedToBasePRValue
:
8661 case SK_CastDerivedToBaseXValue
:
8662 case SK_CastDerivedToBaseLValue
:
8663 case SK_BindReference
:
8664 case SK_BindReferenceToTemporary
:
8666 case SK_ExtraneousCopyToTemporary
:
8667 case SK_UserConversion
:
8668 case SK_QualificationConversionLValue
:
8669 case SK_QualificationConversionXValue
:
8670 case SK_QualificationConversionPRValue
:
8671 case SK_FunctionReferenceConversion
:
8672 case SK_AtomicConversion
:
8673 case SK_ConversionSequence
:
8674 case SK_ConversionSequenceNoNarrowing
:
8675 case SK_ListInitialization
:
8676 case SK_UnwrapInitList
:
8677 case SK_RewrapInitList
:
8678 case SK_CAssignment
:
8680 case SK_ObjCObjectConversion
:
8681 case SK_ArrayLoopIndex
:
8682 case SK_ArrayLoopInit
:
8684 case SK_GNUArrayInit
:
8685 case SK_ParenthesizedArrayInit
:
8686 case SK_PassByIndirectCopyRestore
:
8687 case SK_PassByIndirectRestore
:
8688 case SK_ProduceObjCObject
:
8689 case SK_StdInitializerList
:
8690 case SK_OCLSamplerInit
:
8691 case SK_OCLZeroOpaqueType
: {
8692 assert(Args
.size() == 1 || IsHLSLVectorInit
);
8694 if (!CurInit
.get()) return ExprError();
8698 case SK_ConstructorInitialization
:
8699 case SK_ConstructorInitializationFromList
:
8700 case SK_StdInitializerListConstructorCall
:
8701 case SK_ZeroInitialization
:
8702 case SK_ParenthesizedListInit
:
8706 // Promote from an unevaluated context to an unevaluated list context in
8707 // C++11 list-initialization; we need to instantiate entities usable in
8708 // constant expressions here in order to perform narrowing checks =(
8709 EnterExpressionEvaluationContext
Evaluated(
8710 S
, EnterExpressionEvaluationContext::InitList
,
8711 CurInit
.get() && isa
<InitListExpr
>(CurInit
.get()));
8713 // C++ [class.abstract]p2:
8714 // no objects of an abstract class can be created except as subobjects
8715 // of a class derived from it
8716 auto checkAbstractType
= [&](QualType T
) -> bool {
8717 if (Entity
.getKind() == InitializedEntity::EK_Base
||
8718 Entity
.getKind() == InitializedEntity::EK_Delegating
)
8720 return S
.RequireNonAbstractType(Kind
.getLocation(), T
,
8721 diag::err_allocation_of_abstract_type
);
8724 // Walk through the computed steps for the initialization sequence,
8725 // performing the specified conversions along the way.
8726 bool ConstructorInitRequiresZeroInit
= false;
8727 for (step_iterator Step
= step_begin(), StepEnd
= step_end();
8728 Step
!= StepEnd
; ++Step
) {
8729 if (CurInit
.isInvalid())
8732 QualType SourceType
= CurInit
.get() ? CurInit
.get()->getType() : QualType();
8734 switch (Step
->Kind
) {
8735 case SK_ResolveAddressOfOverloadedFunction
:
8736 // Overload resolution determined which function invoke; update the
8737 // initializer to reflect that choice.
8738 S
.CheckAddressOfMemberAccess(CurInit
.get(), Step
->Function
.FoundDecl
);
8739 if (S
.DiagnoseUseOfDecl(Step
->Function
.FoundDecl
, Kind
.getLocation()))
8741 CurInit
= S
.FixOverloadedFunctionReference(CurInit
,
8742 Step
->Function
.FoundDecl
,
8743 Step
->Function
.Function
);
8744 // We might get back another placeholder expression if we resolved to a
8746 if (!CurInit
.isInvalid())
8747 CurInit
= S
.CheckPlaceholderExpr(CurInit
.get());
8750 case SK_CastDerivedToBasePRValue
:
8751 case SK_CastDerivedToBaseXValue
:
8752 case SK_CastDerivedToBaseLValue
: {
8753 // We have a derived-to-base cast that produces either an rvalue or an
8754 // lvalue. Perform that cast.
8756 CXXCastPath BasePath
;
8758 // Casts to inaccessible base classes are allowed with C-style casts.
8759 bool IgnoreBaseAccess
= Kind
.isCStyleOrFunctionalCast();
8760 if (S
.CheckDerivedToBaseConversion(
8761 SourceType
, Step
->Type
, CurInit
.get()->getBeginLoc(),
8762 CurInit
.get()->getSourceRange(), &BasePath
, IgnoreBaseAccess
))
8766 Step
->Kind
== SK_CastDerivedToBaseLValue
8768 : (Step
->Kind
== SK_CastDerivedToBaseXValue
? VK_XValue
8770 CurInit
= ImplicitCastExpr::Create(S
.Context
, Step
->Type
,
8771 CK_DerivedToBase
, CurInit
.get(),
8772 &BasePath
, VK
, FPOptionsOverride());
8776 case SK_BindReference
:
8777 // Reference binding does not have any corresponding ASTs.
8779 // Check exception specifications
8780 if (S
.CheckExceptionSpecCompatibility(CurInit
.get(), DestType
))
8783 // We don't check for e.g. function pointers here, since address
8784 // availability checks should only occur when the function first decays
8785 // into a pointer or reference.
8786 if (CurInit
.get()->getType()->isFunctionProtoType()) {
8787 if (auto *DRE
= dyn_cast
<DeclRefExpr
>(CurInit
.get()->IgnoreParens())) {
8788 if (auto *FD
= dyn_cast
<FunctionDecl
>(DRE
->getDecl())) {
8789 if (!S
.checkAddressOfFunctionIsAvailable(FD
, /*Complain=*/true,
8790 DRE
->getBeginLoc()))
8796 CheckForNullPointerDereference(S
, CurInit
.get());
8799 case SK_BindReferenceToTemporary
: {
8800 // Make sure the "temporary" is actually an rvalue.
8801 assert(CurInit
.get()->isPRValue() && "not a temporary");
8803 // Check exception specifications
8804 if (S
.CheckExceptionSpecCompatibility(CurInit
.get(), DestType
))
8807 QualType MTETy
= Step
->Type
;
8809 // When this is an incomplete array type (such as when this is
8810 // initializing an array of unknown bounds from an init list), use THAT
8811 // type instead so that we propagate the array bounds.
8812 if (MTETy
->isIncompleteArrayType() &&
8813 !CurInit
.get()->getType()->isIncompleteArrayType() &&
8814 S
.Context
.hasSameType(
8815 MTETy
->getPointeeOrArrayElementType(),
8816 CurInit
.get()->getType()->getPointeeOrArrayElementType()))
8817 MTETy
= CurInit
.get()->getType();
8819 // Materialize the temporary into memory.
8820 MaterializeTemporaryExpr
*MTE
= S
.CreateMaterializeTemporaryExpr(
8821 MTETy
, CurInit
.get(), Entity
.getType()->isLValueReferenceType());
8824 // If we're extending this temporary to automatic storage duration -- we
8825 // need to register its cleanup during the full-expression's cleanups.
8826 if (MTE
->getStorageDuration() == SD_Automatic
&&
8827 MTE
->getType().isDestructedType())
8828 S
.Cleanup
.setExprNeedsCleanups(true);
8833 if (checkAbstractType(Step
->Type
))
8836 // If the overall initialization is initializing a temporary, we already
8837 // bound our argument if it was necessary to do so. If not (if we're
8838 // ultimately initializing a non-temporary), our argument needs to be
8839 // bound since it's initializing a function parameter.
8840 // FIXME: This is a mess. Rationalize temporary destruction.
8841 if (!shouldBindAsTemporary(Entity
))
8842 CurInit
= S
.MaybeBindToTemporary(CurInit
.get());
8843 CurInit
= CopyObject(S
, Step
->Type
, Entity
, CurInit
,
8844 /*IsExtraneousCopy=*/false);
8847 case SK_ExtraneousCopyToTemporary
:
8848 CurInit
= CopyObject(S
, Step
->Type
, Entity
, CurInit
,
8849 /*IsExtraneousCopy=*/true);
8852 case SK_UserConversion
: {
8853 // We have a user-defined conversion that invokes either a constructor
8854 // or a conversion function.
8856 FunctionDecl
*Fn
= Step
->Function
.Function
;
8857 DeclAccessPair FoundFn
= Step
->Function
.FoundDecl
;
8858 bool HadMultipleCandidates
= Step
->Function
.HadMultipleCandidates
;
8859 bool CreatedObject
= false;
8860 if (CXXConstructorDecl
*Constructor
= dyn_cast
<CXXConstructorDecl
>(Fn
)) {
8861 // Build a call to the selected constructor.
8862 SmallVector
<Expr
*, 8> ConstructorArgs
;
8863 SourceLocation Loc
= CurInit
.get()->getBeginLoc();
8865 // Determine the arguments required to actually perform the constructor
8867 Expr
*Arg
= CurInit
.get();
8868 if (S
.CompleteConstructorCall(Constructor
, Step
->Type
,
8869 MultiExprArg(&Arg
, 1), Loc
,
8873 // Build an expression that constructs a temporary.
8874 CurInit
= S
.BuildCXXConstructExpr(Loc
, Step
->Type
,
8875 FoundFn
, Constructor
,
8877 HadMultipleCandidates
,
8879 /*StdInitListInit*/ false,
8881 CXXConstructExpr::CK_Complete
,
8883 if (CurInit
.isInvalid())
8886 S
.CheckConstructorAccess(Kind
.getLocation(), Constructor
, FoundFn
,
8888 if (S
.DiagnoseUseOfDecl(FoundFn
, Kind
.getLocation()))
8891 CastKind
= CK_ConstructorConversion
;
8892 CreatedObject
= true;
8894 // Build a call to the conversion function.
8895 CXXConversionDecl
*Conversion
= cast
<CXXConversionDecl
>(Fn
);
8896 S
.CheckMemberOperatorAccess(Kind
.getLocation(), CurInit
.get(), nullptr,
8898 if (S
.DiagnoseUseOfDecl(FoundFn
, Kind
.getLocation()))
8901 CurInit
= S
.BuildCXXMemberCallExpr(CurInit
.get(), FoundFn
, Conversion
,
8902 HadMultipleCandidates
);
8903 if (CurInit
.isInvalid())
8906 CastKind
= CK_UserDefinedConversion
;
8907 CreatedObject
= Conversion
->getReturnType()->isRecordType();
8910 if (CreatedObject
&& checkAbstractType(CurInit
.get()->getType()))
8913 CurInit
= ImplicitCastExpr::Create(
8914 S
.Context
, CurInit
.get()->getType(), CastKind
, CurInit
.get(), nullptr,
8915 CurInit
.get()->getValueKind(), S
.CurFPFeatureOverrides());
8917 if (shouldBindAsTemporary(Entity
))
8918 // The overall entity is temporary, so this expression should be
8919 // destroyed at the end of its full-expression.
8920 CurInit
= S
.MaybeBindToTemporary(CurInit
.getAs
<Expr
>());
8921 else if (CreatedObject
&& shouldDestroyEntity(Entity
)) {
8922 // The object outlasts the full-expression, but we need to prepare for
8923 // a destructor being run on it.
8924 // FIXME: It makes no sense to do this here. This should happen
8925 // regardless of how we initialized the entity.
8926 QualType T
= CurInit
.get()->getType();
8927 if (const RecordType
*Record
= T
->getAs
<RecordType
>()) {
8928 CXXDestructorDecl
*Destructor
8929 = S
.LookupDestructor(cast
<CXXRecordDecl
>(Record
->getDecl()));
8930 S
.CheckDestructorAccess(CurInit
.get()->getBeginLoc(), Destructor
,
8931 S
.PDiag(diag::err_access_dtor_temp
) << T
);
8932 S
.MarkFunctionReferenced(CurInit
.get()->getBeginLoc(), Destructor
);
8933 if (S
.DiagnoseUseOfDecl(Destructor
, CurInit
.get()->getBeginLoc()))
8940 case SK_QualificationConversionLValue
:
8941 case SK_QualificationConversionXValue
:
8942 case SK_QualificationConversionPRValue
: {
8943 // Perform a qualification conversion; these can never go wrong.
8945 Step
->Kind
== SK_QualificationConversionLValue
8947 : (Step
->Kind
== SK_QualificationConversionXValue
? VK_XValue
8949 CurInit
= S
.PerformQualificationConversion(CurInit
.get(), Step
->Type
, VK
);
8953 case SK_FunctionReferenceConversion
:
8954 assert(CurInit
.get()->isLValue() &&
8955 "function reference should be lvalue");
8957 S
.ImpCastExprToType(CurInit
.get(), Step
->Type
, CK_NoOp
, VK_LValue
);
8960 case SK_AtomicConversion
: {
8961 assert(CurInit
.get()->isPRValue() && "cannot convert glvalue to atomic");
8962 CurInit
= S
.ImpCastExprToType(CurInit
.get(), Step
->Type
,
8963 CK_NonAtomicToAtomic
, VK_PRValue
);
8967 case SK_ConversionSequence
:
8968 case SK_ConversionSequenceNoNarrowing
: {
8969 if (const auto *FromPtrType
=
8970 CurInit
.get()->getType()->getAs
<PointerType
>()) {
8971 if (const auto *ToPtrType
= Step
->Type
->getAs
<PointerType
>()) {
8972 if (FromPtrType
->getPointeeType()->hasAttr(attr::NoDeref
) &&
8973 !ToPtrType
->getPointeeType()->hasAttr(attr::NoDeref
)) {
8974 // Do not check static casts here because they are checked earlier
8975 // in Sema::ActOnCXXNamedCast()
8976 if (!Kind
.isStaticCast()) {
8977 S
.Diag(CurInit
.get()->getExprLoc(),
8978 diag::warn_noderef_to_dereferenceable_pointer
)
8979 << CurInit
.get()->getSourceRange();
8985 Sema::CheckedConversionKind CCK
8986 = Kind
.isCStyleCast()? Sema::CCK_CStyleCast
8987 : Kind
.isFunctionalCast()? Sema::CCK_FunctionalCast
8988 : Kind
.isExplicitCast()? Sema::CCK_OtherCast
8989 : Sema::CCK_ImplicitConversion
;
8990 ExprResult CurInitExprRes
=
8991 S
.PerformImplicitConversion(CurInit
.get(), Step
->Type
, *Step
->ICS
,
8992 getAssignmentAction(Entity
), CCK
);
8993 if (CurInitExprRes
.isInvalid())
8996 S
.DiscardMisalignedMemberAddress(Step
->Type
.getTypePtr(), CurInit
.get());
8998 CurInit
= CurInitExprRes
;
9000 if (Step
->Kind
== SK_ConversionSequenceNoNarrowing
&&
9001 S
.getLangOpts().CPlusPlus
)
9002 DiagnoseNarrowingInInitList(S
, *Step
->ICS
, SourceType
, Entity
.getType(),
9008 case SK_ListInitialization
: {
9009 if (checkAbstractType(Step
->Type
))
9012 InitListExpr
*InitList
= cast
<InitListExpr
>(CurInit
.get());
9013 // If we're not initializing the top-level entity, we need to create an
9014 // InitializeTemporary entity for our target type.
9015 QualType Ty
= Step
->Type
;
9016 bool IsTemporary
= !S
.Context
.hasSameType(Entity
.getType(), Ty
);
9017 InitializedEntity TempEntity
= InitializedEntity::InitializeTemporary(Ty
);
9018 InitializedEntity InitEntity
= IsTemporary
? TempEntity
: Entity
;
9019 InitListChecker
PerformInitList(S
, InitEntity
,
9020 InitList
, Ty
, /*VerifyOnly=*/false,
9021 /*TreatUnavailableAsInvalid=*/false);
9022 if (PerformInitList
.HadError())
9025 // Hack: We must update *ResultType if available in order to set the
9026 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
9027 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
9029 ResultType
->getNonReferenceType()->isIncompleteArrayType()) {
9030 if ((*ResultType
)->isRValueReferenceType())
9031 Ty
= S
.Context
.getRValueReferenceType(Ty
);
9032 else if ((*ResultType
)->isLValueReferenceType())
9033 Ty
= S
.Context
.getLValueReferenceType(Ty
,
9034 (*ResultType
)->castAs
<LValueReferenceType
>()->isSpelledAsLValue());
9038 InitListExpr
*StructuredInitList
=
9039 PerformInitList
.getFullyStructuredList();
9041 CurInit
= shouldBindAsTemporary(InitEntity
)
9042 ? S
.MaybeBindToTemporary(StructuredInitList
)
9043 : StructuredInitList
;
9047 case SK_ConstructorInitializationFromList
: {
9048 if (checkAbstractType(Step
->Type
))
9051 // When an initializer list is passed for a parameter of type "reference
9052 // to object", we don't get an EK_Temporary entity, but instead an
9053 // EK_Parameter entity with reference type.
9054 // FIXME: This is a hack. What we really should do is create a user
9055 // conversion step for this case, but this makes it considerably more
9056 // complicated. For now, this will do.
9057 InitializedEntity TempEntity
= InitializedEntity::InitializeTemporary(
9058 Entity
.getType().getNonReferenceType());
9059 bool UseTemporary
= Entity
.getType()->isReferenceType();
9060 assert(Args
.size() == 1 && "expected a single argument for list init");
9061 InitListExpr
*InitList
= cast
<InitListExpr
>(Args
[0]);
9062 S
.Diag(InitList
->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init
)
9063 << InitList
->getSourceRange();
9064 MultiExprArg
Arg(InitList
->getInits(), InitList
->getNumInits());
9065 CurInit
= PerformConstructorInitialization(S
, UseTemporary
? TempEntity
:
9068 ConstructorInitRequiresZeroInit
,
9069 /*IsListInitialization*/true,
9070 /*IsStdInitListInit*/false,
9071 InitList
->getLBraceLoc(),
9072 InitList
->getRBraceLoc());
9076 case SK_UnwrapInitList
:
9077 CurInit
= cast
<InitListExpr
>(CurInit
.get())->getInit(0);
9080 case SK_RewrapInitList
: {
9081 Expr
*E
= CurInit
.get();
9082 InitListExpr
*Syntactic
= Step
->WrappingSyntacticList
;
9083 InitListExpr
*ILE
= new (S
.Context
) InitListExpr(S
.Context
,
9084 Syntactic
->getLBraceLoc(), E
, Syntactic
->getRBraceLoc());
9085 ILE
->setSyntacticForm(Syntactic
);
9086 ILE
->setType(E
->getType());
9087 ILE
->setValueKind(E
->getValueKind());
9092 case SK_ConstructorInitialization
:
9093 case SK_StdInitializerListConstructorCall
: {
9094 if (checkAbstractType(Step
->Type
))
9097 // When an initializer list is passed for a parameter of type "reference
9098 // to object", we don't get an EK_Temporary entity, but instead an
9099 // EK_Parameter entity with reference type.
9100 // FIXME: This is a hack. What we really should do is create a user
9101 // conversion step for this case, but this makes it considerably more
9102 // complicated. For now, this will do.
9103 InitializedEntity TempEntity
= InitializedEntity::InitializeTemporary(
9104 Entity
.getType().getNonReferenceType());
9105 bool UseTemporary
= Entity
.getType()->isReferenceType();
9106 bool IsStdInitListInit
=
9107 Step
->Kind
== SK_StdInitializerListConstructorCall
;
9108 Expr
*Source
= CurInit
.get();
9109 SourceRange Range
= Kind
.hasParenOrBraceRange()
9110 ? Kind
.getParenOrBraceRange()
9112 CurInit
= PerformConstructorInitialization(
9113 S
, UseTemporary
? TempEntity
: Entity
, Kind
,
9114 Source
? MultiExprArg(Source
) : Args
, *Step
,
9115 ConstructorInitRequiresZeroInit
,
9116 /*IsListInitialization*/ IsStdInitListInit
,
9117 /*IsStdInitListInitialization*/ IsStdInitListInit
,
9118 /*LBraceLoc*/ Range
.getBegin(),
9119 /*RBraceLoc*/ Range
.getEnd());
9123 case SK_ZeroInitialization
: {
9124 step_iterator NextStep
= Step
;
9126 if (NextStep
!= StepEnd
&&
9127 (NextStep
->Kind
== SK_ConstructorInitialization
||
9128 NextStep
->Kind
== SK_ConstructorInitializationFromList
)) {
9129 // The need for zero-initialization is recorded directly into
9130 // the call to the object's constructor within the next step.
9131 ConstructorInitRequiresZeroInit
= true;
9132 } else if (Kind
.getKind() == InitializationKind::IK_Value
&&
9133 S
.getLangOpts().CPlusPlus
&&
9134 !Kind
.isImplicitValueInit()) {
9135 TypeSourceInfo
*TSInfo
= Entity
.getTypeSourceInfo();
9137 TSInfo
= S
.Context
.getTrivialTypeSourceInfo(Step
->Type
,
9138 Kind
.getRange().getBegin());
9140 CurInit
= new (S
.Context
) CXXScalarValueInitExpr(
9141 Entity
.getType().getNonLValueExprType(S
.Context
), TSInfo
,
9142 Kind
.getRange().getEnd());
9144 CurInit
= new (S
.Context
) ImplicitValueInitExpr(Step
->Type
);
9149 case SK_CAssignment
: {
9150 QualType SourceType
= CurInit
.get()->getType();
9152 // Save off the initial CurInit in case we need to emit a diagnostic
9153 ExprResult InitialCurInit
= CurInit
;
9154 ExprResult Result
= CurInit
;
9155 Sema::AssignConvertType ConvTy
=
9156 S
.CheckSingleAssignmentConstraints(Step
->Type
, Result
, true,
9157 Entity
.getKind() == InitializedEntity::EK_Parameter_CF_Audited
);
9158 if (Result
.isInvalid())
9162 // If this is a call, allow conversion to a transparent union.
9163 ExprResult CurInitExprRes
= CurInit
;
9164 if (ConvTy
!= Sema::Compatible
&&
9165 Entity
.isParameterKind() &&
9166 S
.CheckTransparentUnionArgumentConstraints(Step
->Type
, CurInitExprRes
)
9167 == Sema::Compatible
)
9168 ConvTy
= Sema::Compatible
;
9169 if (CurInitExprRes
.isInvalid())
9171 CurInit
= CurInitExprRes
;
9174 if (S
.DiagnoseAssignmentResult(ConvTy
, Kind
.getLocation(),
9175 Step
->Type
, SourceType
,
9176 InitialCurInit
.get(),
9177 getAssignmentAction(Entity
, true),
9179 PrintInitLocationNote(S
, Entity
);
9181 } else if (Complained
)
9182 PrintInitLocationNote(S
, Entity
);
9186 case SK_StringInit
: {
9187 QualType Ty
= Step
->Type
;
9188 bool UpdateType
= ResultType
&& Entity
.getType()->isIncompleteArrayType();
9189 CheckStringInit(CurInit
.get(), UpdateType
? *ResultType
: Ty
,
9190 S
.Context
.getAsArrayType(Ty
), S
);
9194 case SK_ObjCObjectConversion
:
9195 CurInit
= S
.ImpCastExprToType(CurInit
.get(), Step
->Type
,
9196 CK_ObjCObjectLValueCast
,
9197 CurInit
.get()->getValueKind());
9200 case SK_ArrayLoopIndex
: {
9201 Expr
*Cur
= CurInit
.get();
9202 Expr
*BaseExpr
= new (S
.Context
)
9203 OpaqueValueExpr(Cur
->getExprLoc(), Cur
->getType(),
9204 Cur
->getValueKind(), Cur
->getObjectKind(), Cur
);
9206 new (S
.Context
) ArrayInitIndexExpr(S
.Context
.getSizeType());
9207 CurInit
= S
.CreateBuiltinArraySubscriptExpr(
9208 BaseExpr
, Kind
.getLocation(), IndexExpr
, Kind
.getLocation());
9209 ArrayLoopCommonExprs
.push_back(BaseExpr
);
9213 case SK_ArrayLoopInit
: {
9214 assert(!ArrayLoopCommonExprs
.empty() &&
9215 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
9216 Expr
*Common
= ArrayLoopCommonExprs
.pop_back_val();
9217 CurInit
= new (S
.Context
) ArrayInitLoopExpr(Step
->Type
, Common
,
9222 case SK_GNUArrayInit
:
9223 // Okay: we checked everything before creating this step. Note that
9224 // this is a GNU extension.
9225 S
.Diag(Kind
.getLocation(), diag::ext_array_init_copy
)
9226 << Step
->Type
<< CurInit
.get()->getType()
9227 << CurInit
.get()->getSourceRange();
9228 updateGNUCompoundLiteralRValue(CurInit
.get());
9231 // If the destination type is an incomplete array type, update the
9232 // type accordingly.
9234 if (const IncompleteArrayType
*IncompleteDest
9235 = S
.Context
.getAsIncompleteArrayType(Step
->Type
)) {
9236 if (const ConstantArrayType
*ConstantSource
9237 = S
.Context
.getAsConstantArrayType(CurInit
.get()->getType())) {
9238 *ResultType
= S
.Context
.getConstantArrayType(
9239 IncompleteDest
->getElementType(), ConstantSource
->getSize(),
9240 ConstantSource
->getSizeExpr(), ArraySizeModifier::Normal
, 0);
9246 case SK_ParenthesizedArrayInit
:
9247 // Okay: we checked everything before creating this step. Note that
9248 // this is a GNU extension.
9249 S
.Diag(Kind
.getLocation(), diag::ext_array_init_parens
)
9250 << CurInit
.get()->getSourceRange();
9253 case SK_PassByIndirectCopyRestore
:
9254 case SK_PassByIndirectRestore
:
9255 checkIndirectCopyRestoreSource(S
, CurInit
.get());
9256 CurInit
= new (S
.Context
) ObjCIndirectCopyRestoreExpr(
9257 CurInit
.get(), Step
->Type
,
9258 Step
->Kind
== SK_PassByIndirectCopyRestore
);
9261 case SK_ProduceObjCObject
:
9262 CurInit
= ImplicitCastExpr::Create(
9263 S
.Context
, Step
->Type
, CK_ARCProduceObject
, CurInit
.get(), nullptr,
9264 VK_PRValue
, FPOptionsOverride());
9267 case SK_StdInitializerList
: {
9268 S
.Diag(CurInit
.get()->getExprLoc(),
9269 diag::warn_cxx98_compat_initializer_list_init
)
9270 << CurInit
.get()->getSourceRange();
9272 // Materialize the temporary into memory.
9273 MaterializeTemporaryExpr
*MTE
= S
.CreateMaterializeTemporaryExpr(
9274 CurInit
.get()->getType(), CurInit
.get(),
9275 /*BoundToLvalueReference=*/false);
9277 // Wrap it in a construction of a std::initializer_list<T>.
9278 CurInit
= new (S
.Context
) CXXStdInitializerListExpr(Step
->Type
, MTE
);
9280 // Bind the result, in case the library has given initializer_list a
9281 // non-trivial destructor.
9282 if (shouldBindAsTemporary(Entity
))
9283 CurInit
= S
.MaybeBindToTemporary(CurInit
.get());
9287 case SK_OCLSamplerInit
: {
9288 // Sampler initialization have 5 cases:
9289 // 1. function argument passing
9290 // 1a. argument is a file-scope variable
9291 // 1b. argument is a function-scope variable
9292 // 1c. argument is one of caller function's parameters
9293 // 2. variable initialization
9294 // 2a. initializing a file-scope variable
9295 // 2b. initializing a function-scope variable
9297 // For file-scope variables, since they cannot be initialized by function
9298 // call of __translate_sampler_initializer in LLVM IR, their references
9299 // need to be replaced by a cast from their literal initializers to
9300 // sampler type. Since sampler variables can only be used in function
9301 // calls as arguments, we only need to replace them when handling the
9302 // argument passing.
9303 assert(Step
->Type
->isSamplerT() &&
9304 "Sampler initialization on non-sampler type.");
9305 Expr
*Init
= CurInit
.get()->IgnoreParens();
9306 QualType SourceType
= Init
->getType();
9308 if (Entity
.isParameterKind()) {
9309 if (!SourceType
->isSamplerT() && !SourceType
->isIntegerType()) {
9310 S
.Diag(Kind
.getLocation(), diag::err_sampler_argument_required
)
9313 } else if (const DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(Init
)) {
9314 auto Var
= cast
<VarDecl
>(DRE
->getDecl());
9316 // No cast from integer to sampler is needed.
9317 if (!Var
->hasGlobalStorage()) {
9318 CurInit
= ImplicitCastExpr::Create(
9319 S
.Context
, Step
->Type
, CK_LValueToRValue
, Init
,
9320 /*BasePath=*/nullptr, VK_PRValue
, FPOptionsOverride());
9324 // For function call with a file-scope sampler variable as argument,
9325 // get the integer literal.
9326 // Do not diagnose if the file-scope variable does not have initializer
9327 // since this has already been diagnosed when parsing the variable
9329 if (!Var
->getInit() || !isa
<ImplicitCastExpr
>(Var
->getInit()))
9331 Init
= cast
<ImplicitCastExpr
>(const_cast<Expr
*>(
9332 Var
->getInit()))->getSubExpr();
9333 SourceType
= Init
->getType();
9337 // Check initializer is 32 bit integer constant.
9338 // If the initializer is taken from global variable, do not diagnose since
9339 // this has already been done when parsing the variable declaration.
9340 if (!Init
->isConstantInitializer(S
.Context
, false))
9343 if (!SourceType
->isIntegerType() ||
9344 32 != S
.Context
.getIntWidth(SourceType
)) {
9345 S
.Diag(Kind
.getLocation(), diag::err_sampler_initializer_not_integer
)
9350 Expr::EvalResult EVResult
;
9351 Init
->EvaluateAsInt(EVResult
, S
.Context
);
9352 llvm::APSInt Result
= EVResult
.Val
.getInt();
9353 const uint64_t SamplerValue
= Result
.getLimitedValue();
9354 // 32-bit value of sampler's initializer is interpreted as
9355 // bit-field with the following structure:
9356 // |unspecified|Filter|Addressing Mode| Normalized Coords|
9357 // |31 6|5 4|3 1| 0|
9358 // This structure corresponds to enum values of sampler properties
9359 // defined in SPIR spec v1.2 and also opencl-c.h
9360 unsigned AddressingMode
= (0x0E & SamplerValue
) >> 1;
9361 unsigned FilterMode
= (0x30 & SamplerValue
) >> 4;
9362 if (FilterMode
!= 1 && FilterMode
!= 2 &&
9363 !S
.getOpenCLOptions().isAvailableOption(
9364 "cl_intel_device_side_avc_motion_estimation", S
.getLangOpts()))
9365 S
.Diag(Kind
.getLocation(),
9366 diag::warn_sampler_initializer_invalid_bits
)
9368 if (AddressingMode
> 4)
9369 S
.Diag(Kind
.getLocation(),
9370 diag::warn_sampler_initializer_invalid_bits
)
9371 << "Addressing Mode";
9374 // Cases 1a, 2a and 2b
9375 // Insert cast from integer to sampler.
9376 CurInit
= S
.ImpCastExprToType(Init
, S
.Context
.OCLSamplerTy
,
9377 CK_IntToOCLSampler
);
9380 case SK_OCLZeroOpaqueType
: {
9381 assert((Step
->Type
->isEventT() || Step
->Type
->isQueueT() ||
9382 Step
->Type
->isOCLIntelSubgroupAVCType()) &&
9383 "Wrong type for initialization of OpenCL opaque type.");
9385 CurInit
= S
.ImpCastExprToType(CurInit
.get(), Step
->Type
,
9386 CK_ZeroToOCLOpaqueType
,
9387 CurInit
.get()->getValueKind());
9390 case SK_ParenthesizedListInit
: {
9392 TryOrBuildParenListInitialization(S
, Entity
, Kind
, Args
, *this,
9393 /*VerifyOnly=*/false, &CurInit
);
9394 if (CurInit
.get() && ResultType
)
9395 *ResultType
= CurInit
.get()->getType();
9396 if (shouldBindAsTemporary(Entity
))
9397 CurInit
= S
.MaybeBindToTemporary(CurInit
.get());
9403 Expr
*Init
= CurInit
.get();
9407 // Check whether the initializer has a shorter lifetime than the initialized
9408 // entity, and if not, either lifetime-extend or warn as appropriate.
9409 S
.checkInitializerLifetime(Entity
, Init
);
9411 // Diagnose non-fatal problems with the completed initialization.
9412 if (InitializedEntity::EntityKind EK
= Entity
.getKind();
9413 (EK
== InitializedEntity::EK_Member
||
9414 EK
== InitializedEntity::EK_ParenAggInitMember
) &&
9415 cast
<FieldDecl
>(Entity
.getDecl())->isBitField())
9416 S
.CheckBitFieldInitialization(Kind
.getLocation(),
9417 cast
<FieldDecl
>(Entity
.getDecl()), Init
);
9419 // Check for std::move on construction.
9420 CheckMoveOnConstruction(S
, Init
,
9421 Entity
.getKind() == InitializedEntity::EK_Result
);
9426 /// Somewhere within T there is an uninitialized reference subobject.
9427 /// Dig it out and diagnose it.
9428 static bool DiagnoseUninitializedReference(Sema
&S
, SourceLocation Loc
,
9430 if (T
->isReferenceType()) {
9431 S
.Diag(Loc
, diag::err_reference_without_init
)
9432 << T
.getNonReferenceType();
9436 CXXRecordDecl
*RD
= T
->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
9437 if (!RD
|| !RD
->hasUninitializedReferenceMember())
9440 for (const auto *FI
: RD
->fields()) {
9441 if (FI
->isUnnamedBitfield())
9444 if (DiagnoseUninitializedReference(S
, FI
->getLocation(), FI
->getType())) {
9445 S
.Diag(Loc
, diag::note_value_initialization_here
) << RD
;
9450 for (const auto &BI
: RD
->bases()) {
9451 if (DiagnoseUninitializedReference(S
, BI
.getBeginLoc(), BI
.getType())) {
9452 S
.Diag(Loc
, diag::note_value_initialization_here
) << RD
;
9461 //===----------------------------------------------------------------------===//
9462 // Diagnose initialization failures
9463 //===----------------------------------------------------------------------===//
9465 /// Emit notes associated with an initialization that failed due to a
9466 /// "simple" conversion failure.
9467 static void emitBadConversionNotes(Sema
&S
, const InitializedEntity
&entity
,
9469 QualType destType
= entity
.getType();
9470 if (destType
.getNonReferenceType()->isObjCObjectPointerType() &&
9471 op
->getType()->isObjCObjectPointerType()) {
9473 // Emit a possible note about the conversion failing because the
9474 // operand is a message send with a related result type.
9475 S
.EmitRelatedResultTypeNote(op
);
9477 // Emit a possible note about a return failing because we're
9478 // expecting a related result type.
9479 if (entity
.getKind() == InitializedEntity::EK_Result
)
9480 S
.EmitRelatedResultTypeNoteForReturn(destType
);
9482 QualType fromType
= op
->getType();
9483 QualType fromPointeeType
= fromType
.getCanonicalType()->getPointeeType();
9484 QualType destPointeeType
= destType
.getCanonicalType()->getPointeeType();
9485 auto *fromDecl
= fromType
->getPointeeCXXRecordDecl();
9486 auto *destDecl
= destType
->getPointeeCXXRecordDecl();
9487 if (fromDecl
&& destDecl
&& fromDecl
->getDeclKind() == Decl::CXXRecord
&&
9488 destDecl
->getDeclKind() == Decl::CXXRecord
&&
9489 !fromDecl
->isInvalidDecl() && !destDecl
->isInvalidDecl() &&
9490 !fromDecl
->hasDefinition() &&
9491 destPointeeType
.getQualifiers().compatiblyIncludes(
9492 fromPointeeType
.getQualifiers()))
9493 S
.Diag(fromDecl
->getLocation(), diag::note_forward_class_conversion
)
9494 << S
.getASTContext().getTagDeclType(fromDecl
)
9495 << S
.getASTContext().getTagDeclType(destDecl
);
9498 static void diagnoseListInit(Sema
&S
, const InitializedEntity
&Entity
,
9499 InitListExpr
*InitList
) {
9500 QualType DestType
= Entity
.getType();
9503 if (S
.getLangOpts().CPlusPlus11
&& S
.isStdInitializerList(DestType
, &E
)) {
9504 QualType ArrayType
= S
.Context
.getConstantArrayType(
9506 llvm::APInt(S
.Context
.getTypeSize(S
.Context
.getSizeType()),
9507 InitList
->getNumInits()),
9508 nullptr, clang::ArraySizeModifier::Normal
, 0);
9509 InitializedEntity HiddenArray
=
9510 InitializedEntity::InitializeTemporary(ArrayType
);
9511 return diagnoseListInit(S
, HiddenArray
, InitList
);
9514 if (DestType
->isReferenceType()) {
9515 // A list-initialization failure for a reference means that we tried to
9516 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
9517 // inner initialization failed.
9518 QualType T
= DestType
->castAs
<ReferenceType
>()->getPointeeType();
9519 diagnoseListInit(S
, InitializedEntity::InitializeTemporary(T
), InitList
);
9520 SourceLocation Loc
= InitList
->getBeginLoc();
9521 if (auto *D
= Entity
.getDecl())
9522 Loc
= D
->getLocation();
9523 S
.Diag(Loc
, diag::note_in_reference_temporary_list_initializer
) << T
;
9527 InitListChecker
DiagnoseInitList(S
, Entity
, InitList
, DestType
,
9528 /*VerifyOnly=*/false,
9529 /*TreatUnavailableAsInvalid=*/false);
9530 assert(DiagnoseInitList
.HadError() &&
9531 "Inconsistent init list check result.");
9534 bool InitializationSequence::Diagnose(Sema
&S
,
9535 const InitializedEntity
&Entity
,
9536 const InitializationKind
&Kind
,
9537 ArrayRef
<Expr
*> Args
) {
9541 // When we want to diagnose only one element of a braced-init-list,
9542 // we need to factor it out.
9544 if (Args
.size() == 1) {
9545 auto *List
= dyn_cast
<InitListExpr
>(Args
[0]);
9546 if (List
&& List
->getNumInits() == 1)
9547 OnlyArg
= List
->getInit(0);
9554 QualType DestType
= Entity
.getType();
9556 case FK_TooManyInitsForReference
:
9557 // FIXME: Customize for the initialized entity?
9559 // Dig out the reference subobject which is uninitialized and diagnose it.
9560 // If this is value-initialization, this could be nested some way within
9562 assert(Kind
.getKind() == InitializationKind::IK_Value
||
9563 DestType
->isReferenceType());
9565 DiagnoseUninitializedReference(S
, Kind
.getLocation(), DestType
);
9566 assert(Diagnosed
&& "couldn't find uninitialized reference to diagnose");
9568 } else // FIXME: diagnostic below could be better!
9569 S
.Diag(Kind
.getLocation(), diag::err_reference_has_multiple_inits
)
9570 << SourceRange(Args
.front()->getBeginLoc(), Args
.back()->getEndLoc());
9572 case FK_ParenthesizedListInitForReference
:
9573 S
.Diag(Kind
.getLocation(), diag::err_list_init_in_parens
)
9574 << 1 << Entity
.getType() << Args
[0]->getSourceRange();
9577 case FK_ArrayNeedsInitList
:
9578 S
.Diag(Kind
.getLocation(), diag::err_array_init_not_init_list
) << 0;
9580 case FK_ArrayNeedsInitListOrStringLiteral
:
9581 S
.Diag(Kind
.getLocation(), diag::err_array_init_not_init_list
) << 1;
9583 case FK_ArrayNeedsInitListOrWideStringLiteral
:
9584 S
.Diag(Kind
.getLocation(), diag::err_array_init_not_init_list
) << 2;
9586 case FK_NarrowStringIntoWideCharArray
:
9587 S
.Diag(Kind
.getLocation(), diag::err_array_init_narrow_string_into_wchar
);
9589 case FK_WideStringIntoCharArray
:
9590 S
.Diag(Kind
.getLocation(), diag::err_array_init_wide_string_into_char
);
9592 case FK_IncompatWideStringIntoWideChar
:
9593 S
.Diag(Kind
.getLocation(),
9594 diag::err_array_init_incompat_wide_string_into_wchar
);
9596 case FK_PlainStringIntoUTF8Char
:
9597 S
.Diag(Kind
.getLocation(),
9598 diag::err_array_init_plain_string_into_char8_t
);
9599 S
.Diag(Args
.front()->getBeginLoc(),
9600 diag::note_array_init_plain_string_into_char8_t
)
9601 << FixItHint::CreateInsertion(Args
.front()->getBeginLoc(), "u8");
9603 case FK_UTF8StringIntoPlainChar
:
9604 S
.Diag(Kind
.getLocation(), diag::err_array_init_utf8_string_into_char
)
9605 << DestType
->isSignedIntegerType() << S
.getLangOpts().CPlusPlus20
;
9607 case FK_ArrayTypeMismatch
:
9608 case FK_NonConstantArrayInit
:
9609 S
.Diag(Kind
.getLocation(),
9610 (Failure
== FK_ArrayTypeMismatch
9611 ? diag::err_array_init_different_type
9612 : diag::err_array_init_non_constant_array
))
9613 << DestType
.getNonReferenceType()
9614 << OnlyArg
->getType()
9615 << Args
[0]->getSourceRange();
9618 case FK_VariableLengthArrayHasInitializer
:
9619 S
.Diag(Kind
.getLocation(), diag::err_variable_object_no_init
)
9620 << Args
[0]->getSourceRange();
9623 case FK_AddressOfOverloadFailed
: {
9624 DeclAccessPair Found
;
9625 S
.ResolveAddressOfOverloadedFunction(OnlyArg
,
9626 DestType
.getNonReferenceType(),
9632 case FK_AddressOfUnaddressableFunction
: {
9633 auto *FD
= cast
<FunctionDecl
>(cast
<DeclRefExpr
>(OnlyArg
)->getDecl());
9634 S
.checkAddressOfFunctionIsAvailable(FD
, /*Complain=*/true,
9635 OnlyArg
->getBeginLoc());
9639 case FK_ReferenceInitOverloadFailed
:
9640 case FK_UserConversionOverloadFailed
:
9641 switch (FailedOverloadResult
) {
9644 FailedCandidateSet
.NoteCandidates(
9645 PartialDiagnosticAt(
9647 Failure
== FK_UserConversionOverloadFailed
9648 ? (S
.PDiag(diag::err_typecheck_ambiguous_condition
)
9649 << OnlyArg
->getType() << DestType
9650 << Args
[0]->getSourceRange())
9651 : (S
.PDiag(diag::err_ref_init_ambiguous
)
9652 << DestType
<< OnlyArg
->getType()
9653 << Args
[0]->getSourceRange())),
9654 S
, OCD_AmbiguousCandidates
, Args
);
9657 case OR_No_Viable_Function
: {
9658 auto Cands
= FailedCandidateSet
.CompleteCandidates(S
, OCD_AllCandidates
, Args
);
9659 if (!S
.RequireCompleteType(Kind
.getLocation(),
9660 DestType
.getNonReferenceType(),
9661 diag::err_typecheck_nonviable_condition_incomplete
,
9662 OnlyArg
->getType(), Args
[0]->getSourceRange()))
9663 S
.Diag(Kind
.getLocation(), diag::err_typecheck_nonviable_condition
)
9664 << (Entity
.getKind() == InitializedEntity::EK_Result
)
9665 << OnlyArg
->getType() << Args
[0]->getSourceRange()
9666 << DestType
.getNonReferenceType();
9668 FailedCandidateSet
.NoteCandidates(S
, Args
, Cands
);
9672 S
.Diag(Kind
.getLocation(), diag::err_typecheck_deleted_function
)
9673 << OnlyArg
->getType() << DestType
.getNonReferenceType()
9674 << Args
[0]->getSourceRange();
9675 OverloadCandidateSet::iterator Best
;
9676 OverloadingResult Ovl
9677 = FailedCandidateSet
.BestViableFunction(S
, Kind
.getLocation(), Best
);
9678 if (Ovl
== OR_Deleted
) {
9679 S
.NoteDeletedFunction(Best
->Function
);
9681 llvm_unreachable("Inconsistent overload resolution?");
9687 llvm_unreachable("Conversion did not fail!");
9691 case FK_NonConstLValueReferenceBindingToTemporary
:
9692 if (isa
<InitListExpr
>(Args
[0])) {
9693 S
.Diag(Kind
.getLocation(),
9694 diag::err_lvalue_reference_bind_to_initlist
)
9695 << DestType
.getNonReferenceType().isVolatileQualified()
9696 << DestType
.getNonReferenceType()
9697 << Args
[0]->getSourceRange();
9702 case FK_NonConstLValueReferenceBindingToUnrelated
:
9703 S
.Diag(Kind
.getLocation(),
9704 Failure
== FK_NonConstLValueReferenceBindingToTemporary
9705 ? diag::err_lvalue_reference_bind_to_temporary
9706 : diag::err_lvalue_reference_bind_to_unrelated
)
9707 << DestType
.getNonReferenceType().isVolatileQualified()
9708 << DestType
.getNonReferenceType()
9709 << OnlyArg
->getType()
9710 << Args
[0]->getSourceRange();
9713 case FK_NonConstLValueReferenceBindingToBitfield
: {
9714 // We don't necessarily have an unambiguous source bit-field.
9715 FieldDecl
*BitField
= Args
[0]->getSourceBitField();
9716 S
.Diag(Kind
.getLocation(), diag::err_reference_bind_to_bitfield
)
9717 << DestType
.isVolatileQualified()
9718 << (BitField
? BitField
->getDeclName() : DeclarationName())
9719 << (BitField
!= nullptr)
9720 << Args
[0]->getSourceRange();
9722 S
.Diag(BitField
->getLocation(), diag::note_bitfield_decl
);
9726 case FK_NonConstLValueReferenceBindingToVectorElement
:
9727 S
.Diag(Kind
.getLocation(), diag::err_reference_bind_to_vector_element
)
9728 << DestType
.isVolatileQualified()
9729 << Args
[0]->getSourceRange();
9732 case FK_NonConstLValueReferenceBindingToMatrixElement
:
9733 S
.Diag(Kind
.getLocation(), diag::err_reference_bind_to_matrix_element
)
9734 << DestType
.isVolatileQualified() << Args
[0]->getSourceRange();
9737 case FK_RValueReferenceBindingToLValue
:
9738 S
.Diag(Kind
.getLocation(), diag::err_lvalue_to_rvalue_ref
)
9739 << DestType
.getNonReferenceType() << OnlyArg
->getType()
9740 << Args
[0]->getSourceRange();
9743 case FK_ReferenceAddrspaceMismatchTemporary
:
9744 S
.Diag(Kind
.getLocation(), diag::err_reference_bind_temporary_addrspace
)
9745 << DestType
<< Args
[0]->getSourceRange();
9748 case FK_ReferenceInitDropsQualifiers
: {
9749 QualType SourceType
= OnlyArg
->getType();
9750 QualType NonRefType
= DestType
.getNonReferenceType();
9751 Qualifiers DroppedQualifiers
=
9752 SourceType
.getQualifiers() - NonRefType
.getQualifiers();
9754 if (!NonRefType
.getQualifiers().isAddressSpaceSupersetOf(
9755 SourceType
.getQualifiers()))
9756 S
.Diag(Kind
.getLocation(), diag::err_reference_bind_drops_quals
)
9757 << NonRefType
<< SourceType
<< 1 /*addr space*/
9758 << Args
[0]->getSourceRange();
9759 else if (DroppedQualifiers
.hasQualifiers())
9760 S
.Diag(Kind
.getLocation(), diag::err_reference_bind_drops_quals
)
9761 << NonRefType
<< SourceType
<< 0 /*cv quals*/
9762 << Qualifiers::fromCVRMask(DroppedQualifiers
.getCVRQualifiers())
9763 << DroppedQualifiers
.getCVRQualifiers() << Args
[0]->getSourceRange();
9765 // FIXME: Consider decomposing the type and explaining which qualifiers
9766 // were dropped where, or on which level a 'const' is missing, etc.
9767 S
.Diag(Kind
.getLocation(), diag::err_reference_bind_drops_quals
)
9768 << NonRefType
<< SourceType
<< 2 /*incompatible quals*/
9769 << Args
[0]->getSourceRange();
9773 case FK_ReferenceInitFailed
:
9774 S
.Diag(Kind
.getLocation(), diag::err_reference_bind_failed
)
9775 << DestType
.getNonReferenceType()
9776 << DestType
.getNonReferenceType()->isIncompleteType()
9777 << OnlyArg
->isLValue()
9778 << OnlyArg
->getType()
9779 << Args
[0]->getSourceRange();
9780 emitBadConversionNotes(S
, Entity
, Args
[0]);
9783 case FK_ConversionFailed
: {
9784 QualType FromType
= OnlyArg
->getType();
9785 PartialDiagnostic PDiag
= S
.PDiag(diag::err_init_conversion_failed
)
9786 << (int)Entity
.getKind()
9788 << OnlyArg
->isLValue()
9790 << Args
[0]->getSourceRange();
9791 S
.HandleFunctionTypeMismatch(PDiag
, FromType
, DestType
);
9792 S
.Diag(Kind
.getLocation(), PDiag
);
9793 emitBadConversionNotes(S
, Entity
, Args
[0]);
9797 case FK_ConversionFromPropertyFailed
:
9798 // No-op. This error has already been reported.
9801 case FK_TooManyInitsForScalar
: {
9804 auto *InitList
= dyn_cast
<InitListExpr
>(Args
[0]);
9805 if (InitList
&& InitList
->getNumInits() >= 1) {
9806 R
= SourceRange(InitList
->getInit(0)->getEndLoc(), InitList
->getEndLoc());
9808 assert(Args
.size() > 1 && "Expected multiple initializers!");
9809 R
= SourceRange(Args
.front()->getEndLoc(), Args
.back()->getEndLoc());
9812 R
.setBegin(S
.getLocForEndOfToken(R
.getBegin()));
9813 if (Kind
.isCStyleOrFunctionalCast())
9814 S
.Diag(Kind
.getLocation(), diag::err_builtin_func_cast_more_than_one_arg
)
9817 S
.Diag(Kind
.getLocation(), diag::err_excess_initializers
)
9818 << /*scalar=*/2 << R
;
9822 case FK_ParenthesizedListInitForScalar
:
9823 S
.Diag(Kind
.getLocation(), diag::err_list_init_in_parens
)
9824 << 0 << Entity
.getType() << Args
[0]->getSourceRange();
9827 case FK_ReferenceBindingToInitList
:
9828 S
.Diag(Kind
.getLocation(), diag::err_reference_bind_init_list
)
9829 << DestType
.getNonReferenceType() << Args
[0]->getSourceRange();
9832 case FK_InitListBadDestinationType
:
9833 S
.Diag(Kind
.getLocation(), diag::err_init_list_bad_dest_type
)
9834 << (DestType
->isRecordType()) << DestType
<< Args
[0]->getSourceRange();
9837 case FK_ListConstructorOverloadFailed
:
9838 case FK_ConstructorOverloadFailed
: {
9839 SourceRange ArgsRange
;
9842 SourceRange(Args
.front()->getBeginLoc(), Args
.back()->getEndLoc());
9844 if (Failure
== FK_ListConstructorOverloadFailed
) {
9845 assert(Args
.size() == 1 &&
9846 "List construction from other than 1 argument.");
9847 InitListExpr
*InitList
= cast
<InitListExpr
>(Args
[0]);
9848 Args
= MultiExprArg(InitList
->getInits(), InitList
->getNumInits());
9851 // FIXME: Using "DestType" for the entity we're printing is probably
9853 switch (FailedOverloadResult
) {
9855 FailedCandidateSet
.NoteCandidates(
9856 PartialDiagnosticAt(Kind
.getLocation(),
9857 S
.PDiag(diag::err_ovl_ambiguous_init
)
9858 << DestType
<< ArgsRange
),
9859 S
, OCD_AmbiguousCandidates
, Args
);
9862 case OR_No_Viable_Function
:
9863 if (Kind
.getKind() == InitializationKind::IK_Default
&&
9864 (Entity
.getKind() == InitializedEntity::EK_Base
||
9865 Entity
.getKind() == InitializedEntity::EK_Member
||
9866 Entity
.getKind() == InitializedEntity::EK_ParenAggInitMember
) &&
9867 isa
<CXXConstructorDecl
>(S
.CurContext
)) {
9868 // This is implicit default initialization of a member or
9869 // base within a constructor. If no viable function was
9870 // found, notify the user that they need to explicitly
9871 // initialize this base/member.
9872 CXXConstructorDecl
*Constructor
9873 = cast
<CXXConstructorDecl
>(S
.CurContext
);
9874 const CXXRecordDecl
*InheritedFrom
= nullptr;
9875 if (auto Inherited
= Constructor
->getInheritedConstructor())
9876 InheritedFrom
= Inherited
.getShadowDecl()->getNominatedBaseClass();
9877 if (Entity
.getKind() == InitializedEntity::EK_Base
) {
9878 S
.Diag(Kind
.getLocation(), diag::err_missing_default_ctor
)
9879 << (InheritedFrom
? 2 : Constructor
->isImplicit() ? 1 : 0)
9880 << S
.Context
.getTypeDeclType(Constructor
->getParent())
9885 RecordDecl
*BaseDecl
9886 = Entity
.getBaseSpecifier()->getType()->castAs
<RecordType
>()
9888 S
.Diag(BaseDecl
->getLocation(), diag::note_previous_decl
)
9889 << S
.Context
.getTagDeclType(BaseDecl
);
9891 S
.Diag(Kind
.getLocation(), diag::err_missing_default_ctor
)
9892 << (InheritedFrom
? 2 : Constructor
->isImplicit() ? 1 : 0)
9893 << S
.Context
.getTypeDeclType(Constructor
->getParent())
9897 S
.Diag(Entity
.getDecl()->getLocation(),
9898 diag::note_member_declared_at
);
9900 if (const RecordType
*Record
9901 = Entity
.getType()->getAs
<RecordType
>())
9902 S
.Diag(Record
->getDecl()->getLocation(),
9903 diag::note_previous_decl
)
9904 << S
.Context
.getTagDeclType(Record
->getDecl());
9909 FailedCandidateSet
.NoteCandidates(
9910 PartialDiagnosticAt(
9912 S
.PDiag(diag::err_ovl_no_viable_function_in_init
)
9913 << DestType
<< ArgsRange
),
9914 S
, OCD_AllCandidates
, Args
);
9918 OverloadCandidateSet::iterator Best
;
9919 OverloadingResult Ovl
9920 = FailedCandidateSet
.BestViableFunction(S
, Kind
.getLocation(), Best
);
9921 if (Ovl
!= OR_Deleted
) {
9922 S
.Diag(Kind
.getLocation(), diag::err_ovl_deleted_init
)
9923 << DestType
<< ArgsRange
;
9924 llvm_unreachable("Inconsistent overload resolution?");
9928 // If this is a defaulted or implicitly-declared function, then
9929 // it was implicitly deleted. Make it clear that the deletion was
9931 if (S
.isImplicitlyDeleted(Best
->Function
))
9932 S
.Diag(Kind
.getLocation(), diag::err_ovl_deleted_special_init
)
9933 << S
.getSpecialMember(cast
<CXXMethodDecl
>(Best
->Function
))
9934 << DestType
<< ArgsRange
;
9936 S
.Diag(Kind
.getLocation(), diag::err_ovl_deleted_init
)
9937 << DestType
<< ArgsRange
;
9939 S
.NoteDeletedFunction(Best
->Function
);
9944 llvm_unreachable("Conversion did not fail!");
9949 case FK_DefaultInitOfConst
:
9950 if (Entity
.getKind() == InitializedEntity::EK_Member
&&
9951 isa
<CXXConstructorDecl
>(S
.CurContext
)) {
9952 // This is implicit default-initialization of a const member in
9953 // a constructor. Complain that it needs to be explicitly
9955 CXXConstructorDecl
*Constructor
= cast
<CXXConstructorDecl
>(S
.CurContext
);
9956 S
.Diag(Kind
.getLocation(), diag::err_uninitialized_member_in_ctor
)
9957 << (Constructor
->getInheritedConstructor() ? 2 :
9958 Constructor
->isImplicit() ? 1 : 0)
9959 << S
.Context
.getTypeDeclType(Constructor
->getParent())
9961 << Entity
.getName();
9962 S
.Diag(Entity
.getDecl()->getLocation(), diag::note_previous_decl
)
9963 << Entity
.getName();
9964 } else if (const auto *VD
= dyn_cast_if_present
<VarDecl
>(Entity
.getDecl());
9965 VD
&& VD
->isConstexpr()) {
9966 S
.Diag(Kind
.getLocation(), diag::err_constexpr_var_requires_const_init
)
9969 S
.Diag(Kind
.getLocation(), diag::err_default_init_const
)
9970 << DestType
<< (bool)DestType
->getAs
<RecordType
>();
9975 S
.RequireCompleteType(Kind
.getLocation(), FailedIncompleteType
,
9976 diag::err_init_incomplete_type
);
9979 case FK_ListInitializationFailed
: {
9980 // Run the init list checker again to emit diagnostics.
9981 InitListExpr
*InitList
= cast
<InitListExpr
>(Args
[0]);
9982 diagnoseListInit(S
, Entity
, InitList
);
9986 case FK_PlaceholderType
: {
9987 // FIXME: Already diagnosed!
9991 case FK_ExplicitConstructor
: {
9992 S
.Diag(Kind
.getLocation(), diag::err_selected_explicit_constructor
)
9993 << Args
[0]->getSourceRange();
9994 OverloadCandidateSet::iterator Best
;
9995 OverloadingResult Ovl
9996 = FailedCandidateSet
.BestViableFunction(S
, Kind
.getLocation(), Best
);
9998 assert(Ovl
== OR_Success
&& "Inconsistent overload resolution");
9999 CXXConstructorDecl
*CtorDecl
= cast
<CXXConstructorDecl
>(Best
->Function
);
10000 S
.Diag(CtorDecl
->getLocation(),
10001 diag::note_explicit_ctor_deduction_guide_here
) << false;
10005 case FK_ParenthesizedListInitFailed
:
10006 TryOrBuildParenListInitialization(S
, Entity
, Kind
, Args
, *this,
10007 /*VerifyOnly=*/false);
10010 case FK_DesignatedInitForNonAggregate
:
10011 InitListExpr
*InitList
= cast
<InitListExpr
>(Args
[0]);
10012 S
.Diag(Kind
.getLocation(), diag::err_designated_init_for_non_aggregate
)
10013 << Entity
.getType() << InitList
->getSourceRange();
10017 PrintInitLocationNote(S
, Entity
);
10021 void InitializationSequence::dump(raw_ostream
&OS
) const {
10022 switch (SequenceKind
) {
10023 case FailedSequence
: {
10024 OS
<< "Failed sequence: ";
10026 case FK_TooManyInitsForReference
:
10027 OS
<< "too many initializers for reference";
10030 case FK_ParenthesizedListInitForReference
:
10031 OS
<< "parenthesized list init for reference";
10034 case FK_ArrayNeedsInitList
:
10035 OS
<< "array requires initializer list";
10038 case FK_AddressOfUnaddressableFunction
:
10039 OS
<< "address of unaddressable function was taken";
10042 case FK_ArrayNeedsInitListOrStringLiteral
:
10043 OS
<< "array requires initializer list or string literal";
10046 case FK_ArrayNeedsInitListOrWideStringLiteral
:
10047 OS
<< "array requires initializer list or wide string literal";
10050 case FK_NarrowStringIntoWideCharArray
:
10051 OS
<< "narrow string into wide char array";
10054 case FK_WideStringIntoCharArray
:
10055 OS
<< "wide string into char array";
10058 case FK_IncompatWideStringIntoWideChar
:
10059 OS
<< "incompatible wide string into wide char array";
10062 case FK_PlainStringIntoUTF8Char
:
10063 OS
<< "plain string literal into char8_t array";
10066 case FK_UTF8StringIntoPlainChar
:
10067 OS
<< "u8 string literal into char array";
10070 case FK_ArrayTypeMismatch
:
10071 OS
<< "array type mismatch";
10074 case FK_NonConstantArrayInit
:
10075 OS
<< "non-constant array initializer";
10078 case FK_AddressOfOverloadFailed
:
10079 OS
<< "address of overloaded function failed";
10082 case FK_ReferenceInitOverloadFailed
:
10083 OS
<< "overload resolution for reference initialization failed";
10086 case FK_NonConstLValueReferenceBindingToTemporary
:
10087 OS
<< "non-const lvalue reference bound to temporary";
10090 case FK_NonConstLValueReferenceBindingToBitfield
:
10091 OS
<< "non-const lvalue reference bound to bit-field";
10094 case FK_NonConstLValueReferenceBindingToVectorElement
:
10095 OS
<< "non-const lvalue reference bound to vector element";
10098 case FK_NonConstLValueReferenceBindingToMatrixElement
:
10099 OS
<< "non-const lvalue reference bound to matrix element";
10102 case FK_NonConstLValueReferenceBindingToUnrelated
:
10103 OS
<< "non-const lvalue reference bound to unrelated type";
10106 case FK_RValueReferenceBindingToLValue
:
10107 OS
<< "rvalue reference bound to an lvalue";
10110 case FK_ReferenceInitDropsQualifiers
:
10111 OS
<< "reference initialization drops qualifiers";
10114 case FK_ReferenceAddrspaceMismatchTemporary
:
10115 OS
<< "reference with mismatching address space bound to temporary";
10118 case FK_ReferenceInitFailed
:
10119 OS
<< "reference initialization failed";
10122 case FK_ConversionFailed
:
10123 OS
<< "conversion failed";
10126 case FK_ConversionFromPropertyFailed
:
10127 OS
<< "conversion from property failed";
10130 case FK_TooManyInitsForScalar
:
10131 OS
<< "too many initializers for scalar";
10134 case FK_ParenthesizedListInitForScalar
:
10135 OS
<< "parenthesized list init for reference";
10138 case FK_ReferenceBindingToInitList
:
10139 OS
<< "referencing binding to initializer list";
10142 case FK_InitListBadDestinationType
:
10143 OS
<< "initializer list for non-aggregate, non-scalar type";
10146 case FK_UserConversionOverloadFailed
:
10147 OS
<< "overloading failed for user-defined conversion";
10150 case FK_ConstructorOverloadFailed
:
10151 OS
<< "constructor overloading failed";
10154 case FK_DefaultInitOfConst
:
10155 OS
<< "default initialization of a const variable";
10158 case FK_Incomplete
:
10159 OS
<< "initialization of incomplete type";
10162 case FK_ListInitializationFailed
:
10163 OS
<< "list initialization checker failure";
10166 case FK_VariableLengthArrayHasInitializer
:
10167 OS
<< "variable length array has an initializer";
10170 case FK_PlaceholderType
:
10171 OS
<< "initializer expression isn't contextually valid";
10174 case FK_ListConstructorOverloadFailed
:
10175 OS
<< "list constructor overloading failed";
10178 case FK_ExplicitConstructor
:
10179 OS
<< "list copy initialization chose explicit constructor";
10182 case FK_ParenthesizedListInitFailed
:
10183 OS
<< "parenthesized list initialization failed";
10186 case FK_DesignatedInitForNonAggregate
:
10187 OS
<< "designated initializer for non-aggregate type";
10194 case DependentSequence
:
10195 OS
<< "Dependent sequence\n";
10198 case NormalSequence
:
10199 OS
<< "Normal sequence: ";
10203 for (step_iterator S
= step_begin(), SEnd
= step_end(); S
!= SEnd
; ++S
) {
10204 if (S
!= step_begin()) {
10209 case SK_ResolveAddressOfOverloadedFunction
:
10210 OS
<< "resolve address of overloaded function";
10213 case SK_CastDerivedToBasePRValue
:
10214 OS
<< "derived-to-base (prvalue)";
10217 case SK_CastDerivedToBaseXValue
:
10218 OS
<< "derived-to-base (xvalue)";
10221 case SK_CastDerivedToBaseLValue
:
10222 OS
<< "derived-to-base (lvalue)";
10225 case SK_BindReference
:
10226 OS
<< "bind reference to lvalue";
10229 case SK_BindReferenceToTemporary
:
10230 OS
<< "bind reference to a temporary";
10234 OS
<< "final copy in class direct-initialization";
10237 case SK_ExtraneousCopyToTemporary
:
10238 OS
<< "extraneous C++03 copy to temporary";
10241 case SK_UserConversion
:
10242 OS
<< "user-defined conversion via " << *S
->Function
.Function
;
10245 case SK_QualificationConversionPRValue
:
10246 OS
<< "qualification conversion (prvalue)";
10249 case SK_QualificationConversionXValue
:
10250 OS
<< "qualification conversion (xvalue)";
10253 case SK_QualificationConversionLValue
:
10254 OS
<< "qualification conversion (lvalue)";
10257 case SK_FunctionReferenceConversion
:
10258 OS
<< "function reference conversion";
10261 case SK_AtomicConversion
:
10262 OS
<< "non-atomic-to-atomic conversion";
10265 case SK_ConversionSequence
:
10266 OS
<< "implicit conversion sequence (";
10267 S
->ICS
->dump(); // FIXME: use OS
10271 case SK_ConversionSequenceNoNarrowing
:
10272 OS
<< "implicit conversion sequence with narrowing prohibited (";
10273 S
->ICS
->dump(); // FIXME: use OS
10277 case SK_ListInitialization
:
10278 OS
<< "list aggregate initialization";
10281 case SK_UnwrapInitList
:
10282 OS
<< "unwrap reference initializer list";
10285 case SK_RewrapInitList
:
10286 OS
<< "rewrap reference initializer list";
10289 case SK_ConstructorInitialization
:
10290 OS
<< "constructor initialization";
10293 case SK_ConstructorInitializationFromList
:
10294 OS
<< "list initialization via constructor";
10297 case SK_ZeroInitialization
:
10298 OS
<< "zero initialization";
10301 case SK_CAssignment
:
10302 OS
<< "C assignment";
10305 case SK_StringInit
:
10306 OS
<< "string initialization";
10309 case SK_ObjCObjectConversion
:
10310 OS
<< "Objective-C object conversion";
10313 case SK_ArrayLoopIndex
:
10314 OS
<< "indexing for array initialization loop";
10317 case SK_ArrayLoopInit
:
10318 OS
<< "array initialization loop";
10322 OS
<< "array initialization";
10325 case SK_GNUArrayInit
:
10326 OS
<< "array initialization (GNU extension)";
10329 case SK_ParenthesizedArrayInit
:
10330 OS
<< "parenthesized array initialization";
10333 case SK_PassByIndirectCopyRestore
:
10334 OS
<< "pass by indirect copy and restore";
10337 case SK_PassByIndirectRestore
:
10338 OS
<< "pass by indirect restore";
10341 case SK_ProduceObjCObject
:
10342 OS
<< "Objective-C object retension";
10345 case SK_StdInitializerList
:
10346 OS
<< "std::initializer_list from initializer list";
10349 case SK_StdInitializerListConstructorCall
:
10350 OS
<< "list initialization from std::initializer_list";
10353 case SK_OCLSamplerInit
:
10354 OS
<< "OpenCL sampler_t from integer constant";
10357 case SK_OCLZeroOpaqueType
:
10358 OS
<< "OpenCL opaque type from zero";
10360 case SK_ParenthesizedListInit
:
10361 OS
<< "initialization from a parenthesized list of values";
10365 OS
<< " [" << S
->Type
<< ']';
10371 void InitializationSequence::dump() const {
10372 dump(llvm::errs());
10375 static bool NarrowingErrs(const LangOptions
&L
) {
10376 return L
.CPlusPlus11
&&
10377 (!L
.MicrosoftExt
|| L
.isCompatibleWithMSVC(LangOptions::MSVC2015
));
10380 static void DiagnoseNarrowingInInitList(Sema
&S
,
10381 const ImplicitConversionSequence
&ICS
,
10382 QualType PreNarrowingType
,
10383 QualType EntityType
,
10384 const Expr
*PostInit
) {
10385 const StandardConversionSequence
*SCS
= nullptr;
10386 switch (ICS
.getKind()) {
10387 case ImplicitConversionSequence::StandardConversion
:
10388 SCS
= &ICS
.Standard
;
10390 case ImplicitConversionSequence::UserDefinedConversion
:
10391 SCS
= &ICS
.UserDefined
.After
;
10393 case ImplicitConversionSequence::AmbiguousConversion
:
10394 case ImplicitConversionSequence::StaticObjectArgumentConversion
:
10395 case ImplicitConversionSequence::EllipsisConversion
:
10396 case ImplicitConversionSequence::BadConversion
:
10400 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
10401 APValue ConstantValue
;
10402 QualType ConstantType
;
10403 switch (SCS
->getNarrowingKind(S
.Context
, PostInit
, ConstantValue
,
10405 case NK_Not_Narrowing
:
10406 case NK_Dependent_Narrowing
:
10407 // No narrowing occurred.
10410 case NK_Type_Narrowing
:
10411 // This was a floating-to-integer conversion, which is always considered a
10412 // narrowing conversion even if the value is a constant and can be
10413 // represented exactly as an integer.
10414 S
.Diag(PostInit
->getBeginLoc(), NarrowingErrs(S
.getLangOpts())
10415 ? diag::ext_init_list_type_narrowing
10416 : diag::warn_init_list_type_narrowing
)
10417 << PostInit
->getSourceRange()
10418 << PreNarrowingType
.getLocalUnqualifiedType()
10419 << EntityType
.getLocalUnqualifiedType();
10422 case NK_Constant_Narrowing
:
10423 // A constant value was narrowed.
10424 S
.Diag(PostInit
->getBeginLoc(),
10425 NarrowingErrs(S
.getLangOpts())
10426 ? diag::ext_init_list_constant_narrowing
10427 : diag::warn_init_list_constant_narrowing
)
10428 << PostInit
->getSourceRange()
10429 << ConstantValue
.getAsString(S
.getASTContext(), ConstantType
)
10430 << EntityType
.getLocalUnqualifiedType();
10433 case NK_Variable_Narrowing
:
10434 // A variable's value may have been narrowed.
10435 S
.Diag(PostInit
->getBeginLoc(),
10436 NarrowingErrs(S
.getLangOpts())
10437 ? diag::ext_init_list_variable_narrowing
10438 : diag::warn_init_list_variable_narrowing
)
10439 << PostInit
->getSourceRange()
10440 << PreNarrowingType
.getLocalUnqualifiedType()
10441 << EntityType
.getLocalUnqualifiedType();
10445 SmallString
<128> StaticCast
;
10446 llvm::raw_svector_ostream
OS(StaticCast
);
10447 OS
<< "static_cast<";
10448 if (const TypedefType
*TT
= EntityType
->getAs
<TypedefType
>()) {
10449 // It's important to use the typedef's name if there is one so that the
10450 // fixit doesn't break code using types like int64_t.
10452 // FIXME: This will break if the typedef requires qualification. But
10453 // getQualifiedNameAsString() includes non-machine-parsable components.
10454 OS
<< *TT
->getDecl();
10455 } else if (const BuiltinType
*BT
= EntityType
->getAs
<BuiltinType
>())
10456 OS
<< BT
->getName(S
.getLangOpts());
10458 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
10459 // with a broken cast.
10463 S
.Diag(PostInit
->getBeginLoc(), diag::note_init_list_narrowing_silence
)
10464 << PostInit
->getSourceRange()
10465 << FixItHint::CreateInsertion(PostInit
->getBeginLoc(), OS
.str())
10466 << FixItHint::CreateInsertion(
10467 S
.getLocForEndOfToken(PostInit
->getEndLoc()), ")");
10470 //===----------------------------------------------------------------------===//
10471 // Initialization helper functions
10472 //===----------------------------------------------------------------------===//
10474 Sema::CanPerformCopyInitialization(const InitializedEntity
&Entity
,
10476 if (Init
.isInvalid())
10479 Expr
*InitE
= Init
.get();
10480 assert(InitE
&& "No initialization expression");
10482 InitializationKind Kind
=
10483 InitializationKind::CreateCopy(InitE
->getBeginLoc(), SourceLocation());
10484 InitializationSequence
Seq(*this, Entity
, Kind
, InitE
);
10485 return !Seq
.Failed();
10489 Sema::PerformCopyInitialization(const InitializedEntity
&Entity
,
10490 SourceLocation EqualLoc
,
10492 bool TopLevelOfInitList
,
10493 bool AllowExplicit
) {
10494 if (Init
.isInvalid())
10495 return ExprError();
10497 Expr
*InitE
= Init
.get();
10498 assert(InitE
&& "No initialization expression?");
10500 if (EqualLoc
.isInvalid())
10501 EqualLoc
= InitE
->getBeginLoc();
10503 InitializationKind Kind
= InitializationKind::CreateCopy(
10504 InitE
->getBeginLoc(), EqualLoc
, AllowExplicit
);
10505 InitializationSequence
Seq(*this, Entity
, Kind
, InitE
, TopLevelOfInitList
);
10507 // Prevent infinite recursion when performing parameter copy-initialization.
10508 const bool ShouldTrackCopy
=
10509 Entity
.isParameterKind() && Seq
.isConstructorInitialization();
10510 if (ShouldTrackCopy
) {
10511 if (llvm::is_contained(CurrentParameterCopyTypes
, Entity
.getType())) {
10512 Seq
.SetOverloadFailure(
10513 InitializationSequence::FK_ConstructorOverloadFailed
,
10514 OR_No_Viable_Function
);
10516 // Try to give a meaningful diagnostic note for the problematic
10518 const auto LastStep
= Seq
.step_end() - 1;
10519 assert(LastStep
->Kind
==
10520 InitializationSequence::SK_ConstructorInitialization
);
10521 const FunctionDecl
*Function
= LastStep
->Function
.Function
;
10523 llvm::find_if(Seq
.getFailedCandidateSet(),
10524 [Function
](const OverloadCandidate
&Candidate
) -> bool {
10525 return Candidate
.Viable
&&
10526 Candidate
.Function
== Function
&&
10527 Candidate
.Conversions
.size() > 0;
10529 if (Candidate
!= Seq
.getFailedCandidateSet().end() &&
10530 Function
->getNumParams() > 0) {
10531 Candidate
->Viable
= false;
10532 Candidate
->FailureKind
= ovl_fail_bad_conversion
;
10533 Candidate
->Conversions
[0].setBad(BadConversionSequence::no_conversion
,
10535 Function
->getParamDecl(0)->getType());
10538 CurrentParameterCopyTypes
.push_back(Entity
.getType());
10541 ExprResult Result
= Seq
.Perform(*this, Entity
, Kind
, InitE
);
10543 if (ShouldTrackCopy
)
10544 CurrentParameterCopyTypes
.pop_back();
10549 /// Determine whether RD is, or is derived from, a specialization of CTD.
10550 static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl
*RD
,
10551 ClassTemplateDecl
*CTD
) {
10552 auto NotSpecialization
= [&] (const CXXRecordDecl
*Candidate
) {
10553 auto *CTSD
= dyn_cast
<ClassTemplateSpecializationDecl
>(Candidate
);
10554 return !CTSD
|| !declaresSameEntity(CTSD
->getSpecializedTemplate(), CTD
);
10556 return !(NotSpecialization(RD
) && RD
->forallBases(NotSpecialization
));
10559 QualType
Sema::DeduceTemplateSpecializationFromInitializer(
10560 TypeSourceInfo
*TSInfo
, const InitializedEntity
&Entity
,
10561 const InitializationKind
&Kind
, MultiExprArg Inits
, ParenListExpr
*PL
) {
10562 auto *DeducedTST
= dyn_cast
<DeducedTemplateSpecializationType
>(
10563 TSInfo
->getType()->getContainedDeducedType());
10564 assert(DeducedTST
&& "not a deduced template specialization type");
10566 auto TemplateName
= DeducedTST
->getTemplateName();
10567 if (TemplateName
.isDependent())
10568 return SubstAutoTypeDependent(TSInfo
->getType());
10570 // We can only perform deduction for class templates.
10572 dyn_cast_or_null
<ClassTemplateDecl
>(TemplateName
.getAsTemplateDecl());
10574 Diag(Kind
.getLocation(),
10575 diag::err_deduced_non_class_template_specialization_type
)
10576 << (int)getTemplateNameKindForDiagnostics(TemplateName
) << TemplateName
;
10577 if (auto *TD
= TemplateName
.getAsTemplateDecl())
10578 Diag(TD
->getLocation(), diag::note_template_decl_here
);
10582 // Can't deduce from dependent arguments.
10583 if (Expr::hasAnyTypeDependentArguments(Inits
)) {
10584 Diag(TSInfo
->getTypeLoc().getBeginLoc(),
10585 diag::warn_cxx14_compat_class_template_argument_deduction
)
10586 << TSInfo
->getTypeLoc().getSourceRange() << 0;
10587 return SubstAutoTypeDependent(TSInfo
->getType());
10590 // FIXME: Perform "exact type" matching first, per CWG discussion?
10591 // Or implement this via an implied 'T(T) -> T' deduction guide?
10593 // FIXME: Do we need/want a std::initializer_list<T> special case?
10595 // Look up deduction guides, including those synthesized from constructors.
10597 // C++1z [over.match.class.deduct]p1:
10598 // A set of functions and function templates is formed comprising:
10599 // - For each constructor of the class template designated by the
10600 // template-name, a function template [...]
10601 // - For each deduction-guide, a function or function template [...]
10602 DeclarationNameInfo
NameInfo(
10603 Context
.DeclarationNames
.getCXXDeductionGuideName(Template
),
10604 TSInfo
->getTypeLoc().getEndLoc());
10605 LookupResult
Guides(*this, NameInfo
, LookupOrdinaryName
);
10606 LookupQualifiedName(Guides
, Template
->getDeclContext());
10608 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
10609 // clear on this, but they're not found by name so access does not apply.
10610 Guides
.suppressDiagnostics();
10612 // Figure out if this is list-initialization.
10613 InitListExpr
*ListInit
=
10614 (Inits
.size() == 1 && Kind
.getKind() != InitializationKind::IK_Direct
)
10615 ? dyn_cast
<InitListExpr
>(Inits
[0])
10618 // C++1z [over.match.class.deduct]p1:
10619 // Initialization and overload resolution are performed as described in
10620 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
10621 // (as appropriate for the type of initialization performed) for an object
10622 // of a hypothetical class type, where the selected functions and function
10623 // templates are considered to be the constructors of that class type
10625 // Since we know we're initializing a class type of a type unrelated to that
10626 // of the initializer, this reduces to something fairly reasonable.
10627 OverloadCandidateSet
Candidates(Kind
.getLocation(),
10628 OverloadCandidateSet::CSK_Normal
);
10629 OverloadCandidateSet::iterator Best
;
10631 bool AllowExplicit
= !Kind
.isCopyInit() || ListInit
;
10633 // Return true is the candidate is added successfully, false otherwise.
10634 auto addDeductionCandidate
= [&](FunctionTemplateDecl
*TD
,
10635 CXXDeductionGuideDecl
*GD
,
10636 DeclAccessPair FoundDecl
,
10637 bool OnlyListConstructors
,
10638 bool AllowAggregateDeductionCandidate
) {
10639 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
10640 // For copy-initialization, the candidate functions are all the
10641 // converting constructors (12.3.1) of that class.
10642 // C++ [over.match.copy]p1: (non-list copy-initialization from class)
10643 // The converting constructors of T are candidate functions.
10644 if (!AllowExplicit
) {
10645 // Overload resolution checks whether the deduction guide is declared
10646 // explicit for us.
10648 // When looking for a converting constructor, deduction guides that
10649 // could never be called with one argument are not interesting to
10651 if (GD
->getMinRequiredArguments() > 1 ||
10652 (GD
->getNumParams() == 0 && !GD
->isVariadic()))
10656 // C++ [over.match.list]p1.1: (first phase list initialization)
10657 // Initially, the candidate functions are the initializer-list
10658 // constructors of the class T
10659 if (OnlyListConstructors
&& !isInitListConstructor(GD
))
10662 if (!AllowAggregateDeductionCandidate
&&
10663 GD
->getDeductionCandidateKind() == DeductionCandidate::Aggregate
)
10666 // C++ [over.match.list]p1.2: (second phase list initialization)
10667 // the candidate functions are all the constructors of the class T
10668 // C++ [over.match.ctor]p1: (all other cases)
10669 // the candidate functions are all the constructors of the class of
10670 // the object being initialized
10672 // C++ [over.best.ics]p4:
10673 // When [...] the constructor [...] is a candidate by
10674 // - [over.match.copy] (in all cases)
10675 // FIXME: The "second phase of [over.match.list] case can also
10676 // theoretically happen here, but it's not clear whether we can
10677 // ever have a parameter of the right type.
10678 bool SuppressUserConversions
= Kind
.isCopyInit();
10681 SmallVector
<Expr
*, 8> TmpInits
;
10682 for (Expr
*E
: Inits
)
10683 if (auto *DI
= dyn_cast
<DesignatedInitExpr
>(E
))
10684 TmpInits
.push_back(DI
->getInit());
10686 TmpInits
.push_back(E
);
10687 AddTemplateOverloadCandidate(
10688 TD
, FoundDecl
, /*ExplicitArgs=*/nullptr, TmpInits
, Candidates
,
10689 SuppressUserConversions
,
10690 /*PartialOverloading=*/false, AllowExplicit
, ADLCallKind::NotADL
,
10691 /*PO=*/{}, AllowAggregateDeductionCandidate
);
10693 AddOverloadCandidate(GD
, FoundDecl
, Inits
, Candidates
,
10694 SuppressUserConversions
,
10695 /*PartialOverloading=*/false, AllowExplicit
);
10699 bool FoundDeductionGuide
= false;
10701 auto TryToResolveOverload
=
10702 [&](bool OnlyListConstructors
) -> OverloadingResult
{
10703 Candidates
.clear(OverloadCandidateSet::CSK_Normal
);
10704 bool HasAnyDeductionGuide
= false;
10706 auto SynthesizeAggrGuide
= [&](InitListExpr
*ListInit
) {
10707 auto *RD
= cast
<CXXRecordDecl
>(Template
->getTemplatedDecl());
10708 if (!(RD
->getDefinition() && RD
->isAggregate()))
10710 QualType Ty
= Context
.getRecordType(RD
);
10711 SmallVector
<QualType
, 8> ElementTypes
;
10713 InitListChecker
CheckInitList(*this, Entity
, ListInit
, Ty
, ElementTypes
);
10714 if (!CheckInitList
.HadError()) {
10715 // C++ [over.match.class.deduct]p1.8:
10716 // if e_i is of array type and x_i is a braced-init-list, T_i is an
10717 // rvalue reference to the declared type of e_i and
10718 // C++ [over.match.class.deduct]p1.9:
10719 // if e_i is of array type and x_i is a bstring-literal, T_i is an
10720 // lvalue reference to the const-qualified declared type of e_i and
10721 // C++ [over.match.class.deduct]p1.10:
10722 // otherwise, T_i is the declared type of e_i
10723 for (int I
= 0, E
= ListInit
->getNumInits();
10724 I
< E
&& !isa
<PackExpansionType
>(ElementTypes
[I
]); ++I
)
10725 if (ElementTypes
[I
]->isArrayType()) {
10726 if (isa
<InitListExpr
>(ListInit
->getInit(I
)))
10727 ElementTypes
[I
] = Context
.getRValueReferenceType(ElementTypes
[I
]);
10728 else if (isa
<StringLiteral
>(
10729 ListInit
->getInit(I
)->IgnoreParenImpCasts()))
10731 Context
.getLValueReferenceType(ElementTypes
[I
].withConst());
10734 llvm::FoldingSetNodeID ID
;
10735 ID
.AddPointer(Template
);
10736 for (auto &T
: ElementTypes
)
10737 T
.getCanonicalType().Profile(ID
);
10738 unsigned Hash
= ID
.ComputeHash();
10739 if (AggregateDeductionCandidates
.count(Hash
) == 0) {
10740 if (FunctionTemplateDecl
*TD
=
10741 DeclareImplicitDeductionGuideFromInitList(
10742 Template
, ElementTypes
,
10743 TSInfo
->getTypeLoc().getEndLoc())) {
10744 auto *GD
= cast
<CXXDeductionGuideDecl
>(TD
->getTemplatedDecl());
10745 GD
->setDeductionCandidateKind(DeductionCandidate::Aggregate
);
10746 AggregateDeductionCandidates
[Hash
] = GD
;
10747 addDeductionCandidate(TD
, GD
, DeclAccessPair::make(TD
, AS_public
),
10748 OnlyListConstructors
,
10749 /*AllowAggregateDeductionCandidate=*/true);
10752 CXXDeductionGuideDecl
*GD
= AggregateDeductionCandidates
[Hash
];
10753 FunctionTemplateDecl
*TD
= GD
->getDescribedFunctionTemplate();
10754 assert(TD
&& "aggregate deduction candidate is function template");
10755 addDeductionCandidate(TD
, GD
, DeclAccessPair::make(TD
, AS_public
),
10756 OnlyListConstructors
,
10757 /*AllowAggregateDeductionCandidate=*/true);
10759 HasAnyDeductionGuide
= true;
10763 for (auto I
= Guides
.begin(), E
= Guides
.end(); I
!= E
; ++I
) {
10764 NamedDecl
*D
= (*I
)->getUnderlyingDecl();
10765 if (D
->isInvalidDecl())
10768 auto *TD
= dyn_cast
<FunctionTemplateDecl
>(D
);
10769 auto *GD
= dyn_cast_if_present
<CXXDeductionGuideDecl
>(
10770 TD
? TD
->getTemplatedDecl() : dyn_cast
<FunctionDecl
>(D
));
10774 if (!GD
->isImplicit())
10775 HasAnyDeductionGuide
= true;
10777 addDeductionCandidate(TD
, GD
, I
.getPair(), OnlyListConstructors
,
10778 /*AllowAggregateDeductionCandidate=*/false);
10781 // C++ [over.match.class.deduct]p1.4:
10782 // if C is defined and its definition satisfies the conditions for an
10783 // aggregate class ([dcl.init.aggr]) with the assumption that any
10784 // dependent base class has no virtual functions and no virtual base
10785 // classes, and the initializer is a non-empty braced-init-list or
10786 // parenthesized expression-list, and there are no deduction-guides for
10787 // C, the set contains an additional function template, called the
10788 // aggregate deduction candidate, defined as follows.
10789 if (getLangOpts().CPlusPlus20
&& !HasAnyDeductionGuide
) {
10790 if (ListInit
&& ListInit
->getNumInits()) {
10791 SynthesizeAggrGuide(ListInit
);
10792 } else if (PL
&& PL
->getNumExprs()) {
10793 InitListExpr
TempListInit(getASTContext(), PL
->getLParenLoc(),
10794 PL
->exprs(), PL
->getRParenLoc());
10795 SynthesizeAggrGuide(&TempListInit
);
10799 FoundDeductionGuide
= FoundDeductionGuide
|| HasAnyDeductionGuide
;
10801 return Candidates
.BestViableFunction(*this, Kind
.getLocation(), Best
);
10804 OverloadingResult Result
= OR_No_Viable_Function
;
10806 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
10807 // try initializer-list constructors.
10809 bool TryListConstructors
= true;
10811 // Try list constructors unless the list is empty and the class has one or
10812 // more default constructors, in which case those constructors win.
10813 if (!ListInit
->getNumInits()) {
10814 for (NamedDecl
*D
: Guides
) {
10815 auto *FD
= dyn_cast
<FunctionDecl
>(D
->getUnderlyingDecl());
10816 if (FD
&& FD
->getMinRequiredArguments() == 0) {
10817 TryListConstructors
= false;
10821 } else if (ListInit
->getNumInits() == 1) {
10822 // C++ [over.match.class.deduct]:
10823 // As an exception, the first phase in [over.match.list] (considering
10824 // initializer-list constructors) is omitted if the initializer list
10825 // consists of a single expression of type cv U, where U is a
10826 // specialization of C or a class derived from a specialization of C.
10827 Expr
*E
= ListInit
->getInit(0);
10828 auto *RD
= E
->getType()->getAsCXXRecordDecl();
10829 if (!isa
<InitListExpr
>(E
) && RD
&&
10830 isCompleteType(Kind
.getLocation(), E
->getType()) &&
10831 isOrIsDerivedFromSpecializationOf(RD
, Template
))
10832 TryListConstructors
= false;
10835 if (TryListConstructors
)
10836 Result
= TryToResolveOverload(/*OnlyListConstructor*/true);
10837 // Then unwrap the initializer list and try again considering all
10839 Inits
= MultiExprArg(ListInit
->getInits(), ListInit
->getNumInits());
10842 // If list-initialization fails, or if we're doing any other kind of
10843 // initialization, we (eventually) consider constructors.
10844 if (Result
== OR_No_Viable_Function
)
10845 Result
= TryToResolveOverload(/*OnlyListConstructor*/false);
10849 // FIXME: For list-initialization candidates, it'd usually be better to
10850 // list why they were not viable when given the initializer list itself as
10852 Candidates
.NoteCandidates(
10853 PartialDiagnosticAt(
10854 Kind
.getLocation(),
10855 PDiag(diag::err_deduced_class_template_ctor_ambiguous
)
10857 *this, OCD_AmbiguousCandidates
, Inits
);
10860 case OR_No_Viable_Function
: {
10861 CXXRecordDecl
*Primary
=
10862 cast
<ClassTemplateDecl
>(Template
)->getTemplatedDecl();
10864 isCompleteType(Kind
.getLocation(), Context
.getTypeDeclType(Primary
));
10865 Candidates
.NoteCandidates(
10866 PartialDiagnosticAt(
10867 Kind
.getLocation(),
10868 PDiag(Complete
? diag::err_deduced_class_template_ctor_no_viable
10869 : diag::err_deduced_class_template_incomplete
)
10870 << TemplateName
<< !Guides
.empty()),
10871 *this, OCD_AllCandidates
, Inits
);
10876 Diag(Kind
.getLocation(), diag::err_deduced_class_template_deleted
)
10878 NoteDeletedFunction(Best
->Function
);
10883 // C++ [over.match.list]p1:
10884 // In copy-list-initialization, if an explicit constructor is chosen, the
10885 // initialization is ill-formed.
10886 if (Kind
.isCopyInit() && ListInit
&&
10887 cast
<CXXDeductionGuideDecl
>(Best
->Function
)->isExplicit()) {
10888 bool IsDeductionGuide
= !Best
->Function
->isImplicit();
10889 Diag(Kind
.getLocation(), diag::err_deduced_class_template_explicit
)
10890 << TemplateName
<< IsDeductionGuide
;
10891 Diag(Best
->Function
->getLocation(),
10892 diag::note_explicit_ctor_deduction_guide_here
)
10893 << IsDeductionGuide
;
10897 // Make sure we didn't select an unusable deduction guide, and mark it
10899 DiagnoseUseOfDecl(Best
->FoundDecl
, Kind
.getLocation());
10900 MarkFunctionReferenced(Kind
.getLocation(), Best
->Function
);
10904 // C++ [dcl.type.class.deduct]p1:
10905 // The placeholder is replaced by the return type of the function selected
10906 // by overload resolution for class template deduction.
10907 QualType DeducedType
=
10908 SubstAutoType(TSInfo
->getType(), Best
->Function
->getReturnType());
10909 Diag(TSInfo
->getTypeLoc().getBeginLoc(),
10910 diag::warn_cxx14_compat_class_template_argument_deduction
)
10911 << TSInfo
->getTypeLoc().getSourceRange() << 1 << DeducedType
;
10913 // Warn if CTAD was used on a type that does not have any user-defined
10914 // deduction guides.
10915 if (!FoundDeductionGuide
) {
10916 Diag(TSInfo
->getTypeLoc().getBeginLoc(),
10917 diag::warn_ctad_maybe_unsupported
)
10919 Diag(Template
->getLocation(), diag::note_suppress_ctad_maybe_unsupported
);
10922 return DeducedType
;