Bug Summary

File:build/source/clang/lib/Sema/SemaInit.cpp
Warning:line 2918, column 7
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SemaInit.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm -resource-dir /usr/lib/llvm-17/lib/clang/17 -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Sema -I /build/source/clang/lib/Sema -I /build/source/clang/include -I tools/clang/include -I include -I /build/source/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-17/lib/clang/17/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -source-date-epoch 1680807975 -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2023-04-06-205148-16299-1 -x c++ /build/source/clang/lib/Sema/SemaInit.cpp
1//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for initializers.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/ASTContext.h"
14#include "clang/AST/DeclObjC.h"
15#include "clang/AST/ExprCXX.h"
16#include "clang/AST/ExprObjC.h"
17#include "clang/AST/ExprOpenMP.h"
18#include "clang/AST/TypeLoc.h"
19#include "clang/Basic/CharInfo.h"
20#include "clang/Basic/SourceManager.h"
21#include "clang/Basic/TargetInfo.h"
22#include "clang/Sema/Designator.h"
23#include "clang/Sema/Initialization.h"
24#include "clang/Sema/Lookup.h"
25#include "clang/Sema/SemaInternal.h"
26#include "llvm/ADT/APInt.h"
27#include "llvm/ADT/PointerIntPair.h"
28#include "llvm/ADT/SmallString.h"
29#include "llvm/Support/ErrorHandling.h"
30#include "llvm/Support/raw_ostream.h"
31
32using namespace clang;
33
34//===----------------------------------------------------------------------===//
35// Sema Initialization Checking
36//===----------------------------------------------------------------------===//
37
38/// Check whether T is compatible with a wide character type (wchar_t,
39/// char16_t or char32_t).
40static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
41 if (Context.typesAreCompatible(Context.getWideCharType(), T))
42 return true;
43 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
44 return Context.typesAreCompatible(Context.Char16Ty, T) ||
45 Context.typesAreCompatible(Context.Char32Ty, T);
46 }
47 return false;
48}
49
50enum StringInitFailureKind {
51 SIF_None,
52 SIF_NarrowStringIntoWideChar,
53 SIF_WideStringIntoChar,
54 SIF_IncompatWideStringIntoWideChar,
55 SIF_UTF8StringIntoPlainChar,
56 SIF_PlainStringIntoUTF8Char,
57 SIF_Other
58};
59
60/// Check whether the array of type AT can be initialized by the Init
61/// expression by means of string initialization. Returns SIF_None if so,
62/// otherwise returns a StringInitFailureKind that describes why the
63/// initialization would not work.
64static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
65 ASTContext &Context) {
66 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
67 return SIF_Other;
68
69 // See if this is a string literal or @encode.
70 Init = Init->IgnoreParens();
71
72 // Handle @encode, which is a narrow string.
73 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
74 return SIF_None;
75
76 // Otherwise we can only handle string literals.
77 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
78 if (!SL)
79 return SIF_Other;
80
81 const QualType ElemTy =
82 Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
83
84 auto IsCharOrUnsignedChar = [](const QualType &T) {
85 const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr());
86 return BT && BT->isCharType() && BT->getKind() != BuiltinType::SChar;
87 };
88
89 switch (SL->getKind()) {
90 case StringLiteral::UTF8:
91 // char8_t array can be initialized with a UTF-8 string.
92 // - C++20 [dcl.init.string] (DR)
93 // Additionally, an array of char or unsigned char may be initialized
94 // by a UTF-8 string literal.
95 if (ElemTy->isChar8Type() ||
96 (Context.getLangOpts().Char8 &&
97 IsCharOrUnsignedChar(ElemTy.getCanonicalType())))
98 return SIF_None;
99 [[fallthrough]];
100 case StringLiteral::Ordinary:
101 // char array can be initialized with a narrow string.
102 // Only allow char x[] = "foo"; not char x[] = L"foo";
103 if (ElemTy->isCharType())
104 return (SL->getKind() == StringLiteral::UTF8 &&
105 Context.getLangOpts().Char8)
106 ? SIF_UTF8StringIntoPlainChar
107 : SIF_None;
108 if (ElemTy->isChar8Type())
109 return SIF_PlainStringIntoUTF8Char;
110 if (IsWideCharCompatible(ElemTy, Context))
111 return SIF_NarrowStringIntoWideChar;
112 return SIF_Other;
113 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
114 // "An array with element type compatible with a qualified or unqualified
115 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
116 // string literal with the corresponding encoding prefix (L, u, or U,
117 // respectively), optionally enclosed in braces.
118 case StringLiteral::UTF16:
119 if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
120 return SIF_None;
121 if (ElemTy->isCharType() || ElemTy->isChar8Type())
122 return SIF_WideStringIntoChar;
123 if (IsWideCharCompatible(ElemTy, Context))
124 return SIF_IncompatWideStringIntoWideChar;
125 return SIF_Other;
126 case StringLiteral::UTF32:
127 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
128 return SIF_None;
129 if (ElemTy->isCharType() || ElemTy->isChar8Type())
130 return SIF_WideStringIntoChar;
131 if (IsWideCharCompatible(ElemTy, Context))
132 return SIF_IncompatWideStringIntoWideChar;
133 return SIF_Other;
134 case StringLiteral::Wide:
135 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
136 return SIF_None;
137 if (ElemTy->isCharType() || ElemTy->isChar8Type())
138 return SIF_WideStringIntoChar;
139 if (IsWideCharCompatible(ElemTy, Context))
140 return SIF_IncompatWideStringIntoWideChar;
141 return SIF_Other;
142 }
143
144 llvm_unreachable("missed a StringLiteral kind?")::llvm::llvm_unreachable_internal("missed a StringLiteral kind?"
, "clang/lib/Sema/SemaInit.cpp", 144)
;
145}
146
147static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
148 ASTContext &Context) {
149 const ArrayType *arrayType = Context.getAsArrayType(declType);
150 if (!arrayType)
151 return SIF_Other;
152 return IsStringInit(init, arrayType, Context);
153}
154
155bool Sema::IsStringInit(Expr *Init, const ArrayType *AT) {
156 return ::IsStringInit(Init, AT, Context) == SIF_None;
157}
158
159/// Update the type of a string literal, including any surrounding parentheses,
160/// to match the type of the object which it is initializing.
161static void updateStringLiteralType(Expr *E, QualType Ty) {
162 while (true) {
163 E->setType(Ty);
164 E->setValueKind(VK_PRValue);
165 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E)) {
166 break;
167 } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
168 E = PE->getSubExpr();
169 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
170 assert(UO->getOpcode() == UO_Extension)(static_cast <bool> (UO->getOpcode() == UO_Extension
) ? void (0) : __assert_fail ("UO->getOpcode() == UO_Extension"
, "clang/lib/Sema/SemaInit.cpp", 170, __extension__ __PRETTY_FUNCTION__
))
;
171 E = UO->getSubExpr();
172 } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) {
173 E = GSE->getResultExpr();
174 } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) {
175 E = CE->getChosenSubExpr();
176 } else {
177 llvm_unreachable("unexpected expr in string literal init")::llvm::llvm_unreachable_internal("unexpected expr in string literal init"
, "clang/lib/Sema/SemaInit.cpp", 177)
;
178 }
179 }
180}
181
182/// Fix a compound literal initializing an array so it's correctly marked
183/// as an rvalue.
184static void updateGNUCompoundLiteralRValue(Expr *E) {
185 while (true) {
186 E->setValueKind(VK_PRValue);
187 if (isa<CompoundLiteralExpr>(E)) {
188 break;
189 } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
190 E = PE->getSubExpr();
191 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
192 assert(UO->getOpcode() == UO_Extension)(static_cast <bool> (UO->getOpcode() == UO_Extension
) ? void (0) : __assert_fail ("UO->getOpcode() == UO_Extension"
, "clang/lib/Sema/SemaInit.cpp", 192, __extension__ __PRETTY_FUNCTION__
))
;
193 E = UO->getSubExpr();
194 } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) {
195 E = GSE->getResultExpr();
196 } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) {
197 E = CE->getChosenSubExpr();
198 } else {
199 llvm_unreachable("unexpected expr in array compound literal init")::llvm::llvm_unreachable_internal("unexpected expr in array compound literal init"
, "clang/lib/Sema/SemaInit.cpp", 199)
;
200 }
201 }
202}
203
204static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
205 Sema &S) {
206 // Get the length of the string as parsed.
207 auto *ConstantArrayTy =
208 cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
209 uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
210
211 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
212 // C99 6.7.8p14. We have an array of character type with unknown size
213 // being initialized to a string literal.
214 llvm::APInt ConstVal(32, StrLength);
215 // Return a new array type (C99 6.7.8p22).
216 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
217 ConstVal, nullptr,
218 ArrayType::Normal, 0);
219 updateStringLiteralType(Str, DeclT);
220 return;
221 }
222
223 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
224
225 // We have an array of character type with known size. However,
226 // the size may be smaller or larger than the string we are initializing.
227 // FIXME: Avoid truncation for 64-bit length strings.
228 if (S.getLangOpts().CPlusPlus) {
229 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
230 // For Pascal strings it's OK to strip off the terminating null character,
231 // so the example below is valid:
232 //
233 // unsigned char a[2] = "\pa";
234 if (SL->isPascal())
235 StrLength--;
236 }
237
238 // [dcl.init.string]p2
239 if (StrLength > CAT->getSize().getZExtValue())
240 S.Diag(Str->getBeginLoc(),
241 diag::err_initializer_string_for_char_array_too_long)
242 << CAT->getSize().getZExtValue() << StrLength
243 << Str->getSourceRange();
244 } else {
245 // C99 6.7.8p14.
246 if (StrLength-1 > CAT->getSize().getZExtValue())
247 S.Diag(Str->getBeginLoc(),
248 diag::ext_initializer_string_for_char_array_too_long)
249 << Str->getSourceRange();
250 }
251
252 // Set the type to the actual size that we are initializing. If we have
253 // something like:
254 // char x[1] = "foo";
255 // then this will set the string literal's type to char[1].
256 updateStringLiteralType(Str, DeclT);
257}
258
259//===----------------------------------------------------------------------===//
260// Semantic checking for initializer lists.
261//===----------------------------------------------------------------------===//
262
263namespace {
264
265/// Semantic checking for initializer lists.
266///
267/// The InitListChecker class contains a set of routines that each
268/// handle the initialization of a certain kind of entity, e.g.,
269/// arrays, vectors, struct/union types, scalars, etc. The
270/// InitListChecker itself performs a recursive walk of the subobject
271/// structure of the type to be initialized, while stepping through
272/// the initializer list one element at a time. The IList and Index
273/// parameters to each of the Check* routines contain the active
274/// (syntactic) initializer list and the index into that initializer
275/// list that represents the current initializer. Each routine is
276/// responsible for moving that Index forward as it consumes elements.
277///
278/// Each Check* routine also has a StructuredList/StructuredIndex
279/// arguments, which contains the current "structured" (semantic)
280/// initializer list and the index into that initializer list where we
281/// are copying initializers as we map them over to the semantic
282/// list. Once we have completed our recursive walk of the subobject
283/// structure, we will have constructed a full semantic initializer
284/// list.
285///
286/// C99 designators cause changes in the initializer list traversal,
287/// because they make the initialization "jump" into a specific
288/// subobject and then continue the initialization from that
289/// point. CheckDesignatedInitializer() recursively steps into the
290/// designated subobject and manages backing out the recursion to
291/// initialize the subobjects after the one designated.
292///
293/// If an initializer list contains any designators, we build a placeholder
294/// structured list even in 'verify only' mode, so that we can track which
295/// elements need 'empty' initializtion.
296class InitListChecker {
297 Sema &SemaRef;
298 bool hadError = false;
299 bool VerifyOnly; // No diagnostics.
300 bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
301 bool InOverloadResolution;
302 InitListExpr *FullyStructuredList = nullptr;
303 NoInitExpr *DummyExpr = nullptr;
304
305 NoInitExpr *getDummyInit() {
306 if (!DummyExpr)
307 DummyExpr = new (SemaRef.Context) NoInitExpr(SemaRef.Context.VoidTy);
308 return DummyExpr;
309 }
310
311 void CheckImplicitInitList(const InitializedEntity &Entity,
312 InitListExpr *ParentIList, QualType T,
313 unsigned &Index, InitListExpr *StructuredList,
314 unsigned &StructuredIndex);
315 void CheckExplicitInitList(const InitializedEntity &Entity,
316 InitListExpr *IList, QualType &T,
317 InitListExpr *StructuredList,
318 bool TopLevelObject = false);
319 void CheckListElementTypes(const InitializedEntity &Entity,
320 InitListExpr *IList, QualType &DeclType,
321 bool SubobjectIsDesignatorContext,
322 unsigned &Index,
323 InitListExpr *StructuredList,
324 unsigned &StructuredIndex,
325 bool TopLevelObject = false);
326 void CheckSubElementType(const InitializedEntity &Entity,
327 InitListExpr *IList, QualType ElemType,
328 unsigned &Index,
329 InitListExpr *StructuredList,
330 unsigned &StructuredIndex,
331 bool DirectlyDesignated = false);
332 void CheckComplexType(const InitializedEntity &Entity,
333 InitListExpr *IList, QualType DeclType,
334 unsigned &Index,
335 InitListExpr *StructuredList,
336 unsigned &StructuredIndex);
337 void CheckScalarType(const InitializedEntity &Entity,
338 InitListExpr *IList, QualType DeclType,
339 unsigned &Index,
340 InitListExpr *StructuredList,
341 unsigned &StructuredIndex);
342 void CheckReferenceType(const InitializedEntity &Entity,
343 InitListExpr *IList, QualType DeclType,
344 unsigned &Index,
345 InitListExpr *StructuredList,
346 unsigned &StructuredIndex);
347 void CheckVectorType(const InitializedEntity &Entity,
348 InitListExpr *IList, QualType DeclType, unsigned &Index,
349 InitListExpr *StructuredList,
350 unsigned &StructuredIndex);
351 void CheckStructUnionTypes(const InitializedEntity &Entity,
352 InitListExpr *IList, QualType DeclType,
353 CXXRecordDecl::base_class_range Bases,
354 RecordDecl::field_iterator Field,
355 bool SubobjectIsDesignatorContext, unsigned &Index,
356 InitListExpr *StructuredList,
357 unsigned &StructuredIndex,
358 bool TopLevelObject = false);
359 void CheckArrayType(const InitializedEntity &Entity,
360 InitListExpr *IList, QualType &DeclType,
361 llvm::APSInt elementIndex,
362 bool SubobjectIsDesignatorContext, unsigned &Index,
363 InitListExpr *StructuredList,
364 unsigned &StructuredIndex);
365 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
366 InitListExpr *IList, DesignatedInitExpr *DIE,
367 unsigned DesigIdx,
368 QualType &CurrentObjectType,
369 RecordDecl::field_iterator *NextField,
370 llvm::APSInt *NextElementIndex,
371 unsigned &Index,
372 InitListExpr *StructuredList,
373 unsigned &StructuredIndex,
374 bool FinishSubobjectInit,
375 bool TopLevelObject);
376 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
377 QualType CurrentObjectType,
378 InitListExpr *StructuredList,
379 unsigned StructuredIndex,
380 SourceRange InitRange,
381 bool IsFullyOverwritten = false);
382 void UpdateStructuredListElement(InitListExpr *StructuredList,
383 unsigned &StructuredIndex,
384 Expr *expr);
385 InitListExpr *createInitListExpr(QualType CurrentObjectType,
386 SourceRange InitRange,
387 unsigned ExpectedNumInits);
388 int numArrayElements(QualType DeclType);
389 int numStructUnionElements(QualType DeclType);
390
391 ExprResult PerformEmptyInit(SourceLocation Loc,
392 const InitializedEntity &Entity);
393
394 /// Diagnose that OldInit (or part thereof) has been overridden by NewInit.
395 void diagnoseInitOverride(Expr *OldInit, SourceRange NewInitRange,
396 bool FullyOverwritten = true) {
397 // Overriding an initializer via a designator is valid with C99 designated
398 // initializers, but ill-formed with C++20 designated initializers.
399 unsigned DiagID = SemaRef.getLangOpts().CPlusPlus
400 ? diag::ext_initializer_overrides
401 : diag::warn_initializer_overrides;
402
403 if (InOverloadResolution && SemaRef.getLangOpts().CPlusPlus) {
404 // In overload resolution, we have to strictly enforce the rules, and so
405 // don't allow any overriding of prior initializers. This matters for a
406 // case such as:
407 //
408 // union U { int a, b; };
409 // struct S { int a, b; };
410 // void f(U), f(S);
411 //
412 // Here, f({.a = 1, .b = 2}) is required to call the struct overload. For
413 // consistency, we disallow all overriding of prior initializers in
414 // overload resolution, not only overriding of union members.
415 hadError = true;
416 } else if (OldInit->getType().isDestructedType() && !FullyOverwritten) {
417 // If we'll be keeping around the old initializer but overwriting part of
418 // the object it initialized, and that object is not trivially
419 // destructible, this can leak. Don't allow that, not even as an
420 // extension.
421 //
422 // FIXME: It might be reasonable to allow this in cases where the part of
423 // the initializer that we're overriding has trivial destruction.
424 DiagID = diag::err_initializer_overrides_destructed;
425 } else if (!OldInit->getSourceRange().isValid()) {
426 // We need to check on source range validity because the previous
427 // initializer does not have to be an explicit initializer. e.g.,
428 //
429 // struct P { int a, b; };
430 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
431 //
432 // There is an overwrite taking place because the first braced initializer
433 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
434 //
435 // Such overwrites are harmless, so we don't diagnose them. (Note that in
436 // C++, this cannot be reached unless we've already seen and diagnosed a
437 // different conformance issue, such as a mixture of designated and
438 // non-designated initializers or a multi-level designator.)
439 return;
440 }
441
442 if (!VerifyOnly) {
443 SemaRef.Diag(NewInitRange.getBegin(), DiagID)
444 << NewInitRange << FullyOverwritten << OldInit->getType();
445 SemaRef.Diag(OldInit->getBeginLoc(), diag::note_previous_initializer)
446 << (OldInit->HasSideEffects(SemaRef.Context) && FullyOverwritten)
447 << OldInit->getSourceRange();
448 }
449 }
450
451 // Explanation on the "FillWithNoInit" mode:
452 //
453 // Assume we have the following definitions (Case#1):
454 // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
455 // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
456 //
457 // l.lp.x[1][0..1] should not be filled with implicit initializers because the
458 // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
459 //
460 // But if we have (Case#2):
461 // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
462 //
463 // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
464 // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
465 //
466 // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
467 // in the InitListExpr, the "holes" in Case#1 are filled not with empty
468 // initializers but with special "NoInitExpr" place holders, which tells the
469 // CodeGen not to generate any initializers for these parts.
470 void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
471 const InitializedEntity &ParentEntity,
472 InitListExpr *ILE, bool &RequiresSecondPass,
473 bool FillWithNoInit);
474 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
475 const InitializedEntity &ParentEntity,
476 InitListExpr *ILE, bool &RequiresSecondPass,
477 bool FillWithNoInit = false);
478 void FillInEmptyInitializations(const InitializedEntity &Entity,
479 InitListExpr *ILE, bool &RequiresSecondPass,
480 InitListExpr *OuterILE, unsigned OuterIndex,
481 bool FillWithNoInit = false);
482 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
483 Expr *InitExpr, FieldDecl *Field,
484 bool TopLevelObject);
485 void CheckEmptyInitializable(const InitializedEntity &Entity,
486 SourceLocation Loc);
487
488public:
489 InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL,
490 QualType &T, bool VerifyOnly, bool TreatUnavailableAsInvalid,
491 bool InOverloadResolution = false);
492 bool HadError() { return hadError; }
493
494 // Retrieves the fully-structured initializer list used for
495 // semantic analysis and code generation.
496 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
497};
498
499} // end anonymous namespace
500
501ExprResult InitListChecker::PerformEmptyInit(SourceLocation Loc,
502 const InitializedEntity &Entity) {
503 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
504 true);
505 MultiExprArg SubInit;
506 Expr *InitExpr;
507 InitListExpr DummyInitList(SemaRef.Context, Loc, std::nullopt, Loc);
508
509 // C++ [dcl.init.aggr]p7:
510 // If there are fewer initializer-clauses in the list than there are
511 // members in the aggregate, then each member not explicitly initialized
512 // ...
513 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
514 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
515 if (EmptyInitList) {
516 // C++1y / DR1070:
517 // shall be initialized [...] from an empty initializer list.
518 //
519 // We apply the resolution of this DR to C++11 but not C++98, since C++98
520 // does not have useful semantics for initialization from an init list.
521 // We treat this as copy-initialization, because aggregate initialization
522 // always performs copy-initialization on its elements.
523 //
524 // Only do this if we're initializing a class type, to avoid filling in
525 // the initializer list where possible.
526 InitExpr = VerifyOnly
527 ? &DummyInitList
528 : new (SemaRef.Context)
529 InitListExpr(SemaRef.Context, Loc, std::nullopt, Loc);
530 InitExpr->setType(SemaRef.Context.VoidTy);
531 SubInit = InitExpr;
532 Kind = InitializationKind::CreateCopy(Loc, Loc);
533 } else {
534 // C++03:
535 // shall be value-initialized.
536 }
537
538 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
539 // libstdc++4.6 marks the vector default constructor as explicit in
540 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
541 // stlport does so too. Look for std::__debug for libstdc++, and for
542 // std:: for stlport. This is effectively a compiler-side implementation of
543 // LWG2193.
544 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
545 InitializationSequence::FK_ExplicitConstructor) {
546 OverloadCandidateSet::iterator Best;
547 OverloadingResult O =
548 InitSeq.getFailedCandidateSet()
549 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
550 (void)O;
551 assert(O == OR_Success && "Inconsistent overload resolution")(static_cast <bool> (O == OR_Success && "Inconsistent overload resolution"
) ? void (0) : __assert_fail ("O == OR_Success && \"Inconsistent overload resolution\""
, "clang/lib/Sema/SemaInit.cpp", 551, __extension__ __PRETTY_FUNCTION__
))
;
552 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
553 CXXRecordDecl *R = CtorDecl->getParent();
554
555 if (CtorDecl->getMinRequiredArguments() == 0 &&
556 CtorDecl->isExplicit() && R->getDeclName() &&
557 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
558 bool IsInStd = false;
559 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
560 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
561 if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
562 IsInStd = true;
563 }
564
565 if (IsInStd && llvm::StringSwitch<bool>(R->getName())
566 .Cases("basic_string", "deque", "forward_list", true)
567 .Cases("list", "map", "multimap", "multiset", true)
568 .Cases("priority_queue", "queue", "set", "stack", true)
569 .Cases("unordered_map", "unordered_set", "vector", true)
570 .Default(false)) {
571 InitSeq.InitializeFrom(
572 SemaRef, Entity,
573 InitializationKind::CreateValue(Loc, Loc, Loc, true),
574 MultiExprArg(), /*TopLevelOfInitList=*/false,
575 TreatUnavailableAsInvalid);
576 // Emit a warning for this. System header warnings aren't shown
577 // by default, but people working on system headers should see it.
578 if (!VerifyOnly) {
579 SemaRef.Diag(CtorDecl->getLocation(),
580 diag::warn_invalid_initializer_from_system_header);
581 if (Entity.getKind() == InitializedEntity::EK_Member)
582 SemaRef.Diag(Entity.getDecl()->getLocation(),
583 diag::note_used_in_initialization_here);
584 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
585 SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
586 }
587 }
588 }
589 }
590 if (!InitSeq) {
591 if (!VerifyOnly) {
592 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
593 if (Entity.getKind() == InitializedEntity::EK_Member)
594 SemaRef.Diag(Entity.getDecl()->getLocation(),
595 diag::note_in_omitted_aggregate_initializer)
596 << /*field*/1 << Entity.getDecl();
597 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
598 bool IsTrailingArrayNewMember =
599 Entity.getParent() &&
600 Entity.getParent()->isVariableLengthArrayNew();
601 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
602 << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
603 << Entity.getElementIndex();
604 }
605 }
606 hadError = true;
607 return ExprError();
608 }
609
610 return VerifyOnly ? ExprResult()
611 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
612}
613
614void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
615 SourceLocation Loc) {
616 // If we're building a fully-structured list, we'll check this at the end
617 // once we know which elements are actually initialized. Otherwise, we know
618 // that there are no designators so we can just check now.
619 if (FullyStructuredList)
620 return;
621 PerformEmptyInit(Loc, Entity);
622}
623
624void InitListChecker::FillInEmptyInitForBase(
625 unsigned Init, const CXXBaseSpecifier &Base,
626 const InitializedEntity &ParentEntity, InitListExpr *ILE,
627 bool &RequiresSecondPass, bool FillWithNoInit) {
628 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
629 SemaRef.Context, &Base, false, &ParentEntity);
630
631 if (Init >= ILE->getNumInits() || !ILE->getInit(Init)) {
632 ExprResult BaseInit = FillWithNoInit
633 ? new (SemaRef.Context) NoInitExpr(Base.getType())
634 : PerformEmptyInit(ILE->getEndLoc(), BaseEntity);
635 if (BaseInit.isInvalid()) {
636 hadError = true;
637 return;
638 }
639
640 if (!VerifyOnly) {
641 assert(Init < ILE->getNumInits() && "should have been expanded")(static_cast <bool> (Init < ILE->getNumInits() &&
"should have been expanded") ? void (0) : __assert_fail ("Init < ILE->getNumInits() && \"should have been expanded\""
, "clang/lib/Sema/SemaInit.cpp", 641, __extension__ __PRETTY_FUNCTION__
))
;
642 ILE->setInit(Init, BaseInit.getAs<Expr>());
643 }
644 } else if (InitListExpr *InnerILE =
645 dyn_cast<InitListExpr>(ILE->getInit(Init))) {
646 FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,
647 ILE, Init, FillWithNoInit);
648 } else if (DesignatedInitUpdateExpr *InnerDIUE =
649 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
650 FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
651 RequiresSecondPass, ILE, Init,
652 /*FillWithNoInit =*/true);
653 }
654}
655
656void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
657 const InitializedEntity &ParentEntity,
658 InitListExpr *ILE,
659 bool &RequiresSecondPass,
660 bool FillWithNoInit) {
661 SourceLocation Loc = ILE->getEndLoc();
662 unsigned NumInits = ILE->getNumInits();
663 InitializedEntity MemberEntity
664 = InitializedEntity::InitializeMember(Field, &ParentEntity);
665
666 if (Init >= NumInits || !ILE->getInit(Init)) {
667 if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
668 if (!RType->getDecl()->isUnion())
669 assert((Init < NumInits || VerifyOnly) &&(static_cast <bool> ((Init < NumInits || VerifyOnly)
&& "This ILE should have been expanded") ? void (0) :
__assert_fail ("(Init < NumInits || VerifyOnly) && \"This ILE should have been expanded\""
, "clang/lib/Sema/SemaInit.cpp", 670, __extension__ __PRETTY_FUNCTION__
))
670 "This ILE should have been expanded")(static_cast <bool> ((Init < NumInits || VerifyOnly)
&& "This ILE should have been expanded") ? void (0) :
__assert_fail ("(Init < NumInits || VerifyOnly) && \"This ILE should have been expanded\""
, "clang/lib/Sema/SemaInit.cpp", 670, __extension__ __PRETTY_FUNCTION__
))
;
671
672 if (FillWithNoInit) {
673 assert(!VerifyOnly && "should not fill with no-init in verify-only mode")(static_cast <bool> (!VerifyOnly && "should not fill with no-init in verify-only mode"
) ? void (0) : __assert_fail ("!VerifyOnly && \"should not fill with no-init in verify-only mode\""
, "clang/lib/Sema/SemaInit.cpp", 673, __extension__ __PRETTY_FUNCTION__
))
;
674 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
675 if (Init < NumInits)
676 ILE->setInit(Init, Filler);
677 else
678 ILE->updateInit(SemaRef.Context, Init, Filler);
679 return;
680 }
681 // C++1y [dcl.init.aggr]p7:
682 // If there are fewer initializer-clauses in the list than there are
683 // members in the aggregate, then each member not explicitly initialized
684 // shall be initialized from its brace-or-equal-initializer [...]
685 if (Field->hasInClassInitializer()) {
686 if (VerifyOnly)
687 return;
688
689 ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
690 if (DIE.isInvalid()) {
691 hadError = true;
692 return;
693 }
694 SemaRef.checkInitializerLifetime(MemberEntity, DIE.get());
695 if (Init < NumInits)
696 ILE->setInit(Init, DIE.get());
697 else {
698 ILE->updateInit(SemaRef.Context, Init, DIE.get());
699 RequiresSecondPass = true;
700 }
701 return;
702 }
703
704 if (Field->getType()->isReferenceType()) {
705 if (!VerifyOnly) {
706 // C++ [dcl.init.aggr]p9:
707 // If an incomplete or empty initializer-list leaves a
708 // member of reference type uninitialized, the program is
709 // ill-formed.
710 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
711 << Field->getType()
712 << (ILE->isSyntacticForm() ? ILE : ILE->getSyntacticForm())
713 ->getSourceRange();
714 SemaRef.Diag(Field->getLocation(), diag::note_uninit_reference_member);
715 }
716 hadError = true;
717 return;
718 }
719
720 ExprResult MemberInit = PerformEmptyInit(Loc, MemberEntity);
721 if (MemberInit.isInvalid()) {
722 hadError = true;
723 return;
724 }
725
726 if (hadError || VerifyOnly) {
727 // Do nothing
728 } else if (Init < NumInits) {
729 ILE->setInit(Init, MemberInit.getAs<Expr>());
730 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
731 // Empty initialization requires a constructor call, so
732 // extend the initializer list to include the constructor
733 // call and make a note that we'll need to take another pass
734 // through the initializer list.
735 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
736 RequiresSecondPass = true;
737 }
738 } else if (InitListExpr *InnerILE
739 = dyn_cast<InitListExpr>(ILE->getInit(Init))) {
740 FillInEmptyInitializations(MemberEntity, InnerILE,
741 RequiresSecondPass, ILE, Init, FillWithNoInit);
742 } else if (DesignatedInitUpdateExpr *InnerDIUE =
743 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
744 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
745 RequiresSecondPass, ILE, Init,
746 /*FillWithNoInit =*/true);
747 }
748}
749
750/// Recursively replaces NULL values within the given initializer list
751/// with expressions that perform value-initialization of the
752/// appropriate type, and finish off the InitListExpr formation.
753void
754InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
755 InitListExpr *ILE,
756 bool &RequiresSecondPass,
757 InitListExpr *OuterILE,
758 unsigned OuterIndex,
759 bool FillWithNoInit) {
760 assert((ILE->getType() != SemaRef.Context.VoidTy) &&(static_cast <bool> ((ILE->getType() != SemaRef.Context
.VoidTy) && "Should not have void type") ? void (0) :
__assert_fail ("(ILE->getType() != SemaRef.Context.VoidTy) && \"Should not have void type\""
, "clang/lib/Sema/SemaInit.cpp", 761, __extension__ __PRETTY_FUNCTION__
))
761 "Should not have void type")(static_cast <bool> ((ILE->getType() != SemaRef.Context
.VoidTy) && "Should not have void type") ? void (0) :
__assert_fail ("(ILE->getType() != SemaRef.Context.VoidTy) && \"Should not have void type\""
, "clang/lib/Sema/SemaInit.cpp", 761, __extension__ __PRETTY_FUNCTION__
))
;
762
763 // We don't need to do any checks when just filling NoInitExprs; that can't
764 // fail.
765 if (FillWithNoInit && VerifyOnly)
766 return;
767
768 // If this is a nested initializer list, we might have changed its contents
769 // (and therefore some of its properties, such as instantiation-dependence)
770 // while filling it in. Inform the outer initializer list so that its state
771 // can be updated to match.
772 // FIXME: We should fully build the inner initializers before constructing
773 // the outer InitListExpr instead of mutating AST nodes after they have
774 // been used as subexpressions of other nodes.
775 struct UpdateOuterILEWithUpdatedInit {
776 InitListExpr *Outer;
777 unsigned OuterIndex;
778 ~UpdateOuterILEWithUpdatedInit() {
779 if (Outer)
780 Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
781 }
782 } UpdateOuterRAII = {OuterILE, OuterIndex};
783
784 // A transparent ILE is not performing aggregate initialization and should
785 // not be filled in.
786 if (ILE->isTransparent())
787 return;
788
789 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
790 const RecordDecl *RDecl = RType->getDecl();
791 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
792 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
793 Entity, ILE, RequiresSecondPass, FillWithNoInit);
794 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
795 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
796 for (auto *Field : RDecl->fields()) {
797 if (Field->hasInClassInitializer()) {
798 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
799 FillWithNoInit);
800 break;
801 }
802 }
803 } else {
804 // The fields beyond ILE->getNumInits() are default initialized, so in
805 // order to leave them uninitialized, the ILE is expanded and the extra
806 // fields are then filled with NoInitExpr.
807 unsigned NumElems = numStructUnionElements(ILE->getType());
808 if (RDecl->hasFlexibleArrayMember())
809 ++NumElems;
810 if (!VerifyOnly && ILE->getNumInits() < NumElems)
811 ILE->resizeInits(SemaRef.Context, NumElems);
812
813 unsigned Init = 0;
814
815 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
816 for (auto &Base : CXXRD->bases()) {
817 if (hadError)
818 return;
819
820 FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
821 FillWithNoInit);
822 ++Init;
823 }
824 }
825
826 for (auto *Field : RDecl->fields()) {
827 if (Field->isUnnamedBitfield())
828 continue;
829
830 if (hadError)
831 return;
832
833 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
834 FillWithNoInit);
835 if (hadError)
836 return;
837
838 ++Init;
839
840 // Only look at the first initialization of a union.
841 if (RDecl->isUnion())
842 break;
843 }
844 }
845
846 return;
847 }
848
849 QualType ElementType;
850
851 InitializedEntity ElementEntity = Entity;
852 unsigned NumInits = ILE->getNumInits();
853 unsigned NumElements = NumInits;
854 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
855 ElementType = AType->getElementType();
856 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
857 NumElements = CAType->getSize().getZExtValue();
858 // For an array new with an unknown bound, ask for one additional element
859 // in order to populate the array filler.
860 if (Entity.isVariableLengthArrayNew())
861 ++NumElements;
862 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
863 0, Entity);
864 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
865 ElementType = VType->getElementType();
866 NumElements = VType->getNumElements();
867 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
868 0, Entity);
869 } else
870 ElementType = ILE->getType();
871
872 bool SkipEmptyInitChecks = false;
873 for (unsigned Init = 0; Init != NumElements; ++Init) {
874 if (hadError)
875 return;
876
877 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
878 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
879 ElementEntity.setElementIndex(Init);
880
881 if (Init >= NumInits && (ILE->hasArrayFiller() || SkipEmptyInitChecks))
882 return;
883
884 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
885 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
886 ILE->setInit(Init, ILE->getArrayFiller());
887 else if (!InitExpr && !ILE->hasArrayFiller()) {
888 // In VerifyOnly mode, there's no point performing empty initialization
889 // more than once.
890 if (SkipEmptyInitChecks)
891 continue;
892
893 Expr *Filler = nullptr;
894
895 if (FillWithNoInit)
896 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
897 else {
898 ExprResult ElementInit =
899 PerformEmptyInit(ILE->getEndLoc(), ElementEntity);
900 if (ElementInit.isInvalid()) {
901 hadError = true;
902 return;
903 }
904
905 Filler = ElementInit.getAs<Expr>();
906 }
907
908 if (hadError) {
909 // Do nothing
910 } else if (VerifyOnly) {
911 SkipEmptyInitChecks = true;
912 } else if (Init < NumInits) {
913 // For arrays, just set the expression used for value-initialization
914 // of the "holes" in the array.
915 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
916 ILE->setArrayFiller(Filler);
917 else
918 ILE->setInit(Init, Filler);
919 } else {
920 // For arrays, just set the expression used for value-initialization
921 // of the rest of elements and exit.
922 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
923 ILE->setArrayFiller(Filler);
924 return;
925 }
926
927 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
928 // Empty initialization requires a constructor call, so
929 // extend the initializer list to include the constructor
930 // call and make a note that we'll need to take another pass
931 // through the initializer list.
932 ILE->updateInit(SemaRef.Context, Init, Filler);
933 RequiresSecondPass = true;
934 }
935 }
936 } else if (InitListExpr *InnerILE
937 = dyn_cast_or_null<InitListExpr>(InitExpr)) {
938 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
939 ILE, Init, FillWithNoInit);
940 } else if (DesignatedInitUpdateExpr *InnerDIUE =
941 dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr)) {
942 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
943 RequiresSecondPass, ILE, Init,
944 /*FillWithNoInit =*/true);
945 }
946 }
947}
948
949static bool hasAnyDesignatedInits(const InitListExpr *IL) {
950 for (const Stmt *Init : *IL)
951 if (Init && isa<DesignatedInitExpr>(Init))
952 return true;
953 return false;
954}
955
956InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
957 InitListExpr *IL, QualType &T, bool VerifyOnly,
958 bool TreatUnavailableAsInvalid,
959 bool InOverloadResolution)
960 : SemaRef(S), VerifyOnly(VerifyOnly),
961 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid),
962 InOverloadResolution(InOverloadResolution) {
963 if (!VerifyOnly || hasAnyDesignatedInits(IL)) {
964 FullyStructuredList =
965 createInitListExpr(T, IL->getSourceRange(), IL->getNumInits());
966
967 // FIXME: Check that IL isn't already the semantic form of some other
968 // InitListExpr. If it is, we'd create a broken AST.
969 if (!VerifyOnly)
970 FullyStructuredList->setSyntacticForm(IL);
971 }
972
973 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
974 /*TopLevelObject=*/true);
975
976 if (!hadError && FullyStructuredList) {
977 bool RequiresSecondPass = false;
978 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
979 /*OuterILE=*/nullptr, /*OuterIndex=*/0);
980 if (RequiresSecondPass && !hadError)
981 FillInEmptyInitializations(Entity, FullyStructuredList,
982 RequiresSecondPass, nullptr, 0);
983 }
984 if (hadError && FullyStructuredList)
985 FullyStructuredList->markError();
986}
987
988int InitListChecker::numArrayElements(QualType DeclType) {
989 // FIXME: use a proper constant
990 int maxElements = 0x7FFFFFFF;
991 if (const ConstantArrayType *CAT =
992 SemaRef.Context.getAsConstantArrayType(DeclType)) {
993 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
994 }
995 return maxElements;
996}
997
998int InitListChecker::numStructUnionElements(QualType DeclType) {
999 RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl();
1000 int InitializableMembers = 0;
1001 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
1002 InitializableMembers += CXXRD->getNumBases();
1003 for (const auto *Field : structDecl->fields())
1004 if (!Field->isUnnamedBitfield())
1005 ++InitializableMembers;
1006
1007 if (structDecl->isUnion())
1008 return std::min(InitializableMembers, 1);
1009 return InitializableMembers - structDecl->hasFlexibleArrayMember();
1010}
1011
1012/// Determine whether Entity is an entity for which it is idiomatic to elide
1013/// the braces in aggregate initialization.
1014static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) {
1015 // Recursive initialization of the one and only field within an aggregate
1016 // class is considered idiomatic. This case arises in particular for
1017 // initialization of std::array, where the C++ standard suggests the idiom of
1018 //
1019 // std::array<T, N> arr = {1, 2, 3};
1020 //
1021 // (where std::array is an aggregate struct containing a single array field.
1022
1023 if (!Entity.getParent())
1024 return false;
1025
1026 // Allows elide brace initialization for aggregates with empty base.
1027 if (Entity.getKind() == InitializedEntity::EK_Base) {
1028 auto *ParentRD =
1029 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1030 CXXRecordDecl *CXXRD = cast<CXXRecordDecl>(ParentRD);
1031 return CXXRD->getNumBases() == 1 && CXXRD->field_empty();
1032 }
1033
1034 // Allow brace elision if the only subobject is a field.
1035 if (Entity.getKind() == InitializedEntity::EK_Member) {
1036 auto *ParentRD =
1037 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1038 if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD)) {
1039 if (CXXRD->getNumBases()) {
1040 return false;
1041 }
1042 }
1043 auto FieldIt = ParentRD->field_begin();
1044 assert(FieldIt != ParentRD->field_end() &&(static_cast <bool> (FieldIt != ParentRD->field_end(
) && "no fields but have initializer for member?") ? void
(0) : __assert_fail ("FieldIt != ParentRD->field_end() && \"no fields but have initializer for member?\""
, "clang/lib/Sema/SemaInit.cpp", 1045, __extension__ __PRETTY_FUNCTION__
))
1045 "no fields but have initializer for member?")(static_cast <bool> (FieldIt != ParentRD->field_end(
) && "no fields but have initializer for member?") ? void
(0) : __assert_fail ("FieldIt != ParentRD->field_end() && \"no fields but have initializer for member?\""
, "clang/lib/Sema/SemaInit.cpp", 1045, __extension__ __PRETTY_FUNCTION__
))
;
1046 return ++FieldIt == ParentRD->field_end();
1047 }
1048
1049 return false;
1050}
1051
1052/// Check whether the range of the initializer \p ParentIList from element
1053/// \p Index onwards can be used to initialize an object of type \p T. Update
1054/// \p Index to indicate how many elements of the list were consumed.
1055///
1056/// This also fills in \p StructuredList, from element \p StructuredIndex
1057/// onwards, with the fully-braced, desugared form of the initialization.
1058void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
1059 InitListExpr *ParentIList,
1060 QualType T, unsigned &Index,
1061 InitListExpr *StructuredList,
1062 unsigned &StructuredIndex) {
1063 int maxElements = 0;
1064
1065 if (T->isArrayType())
1066 maxElements = numArrayElements(T);
1067 else if (T->isRecordType())
1068 maxElements = numStructUnionElements(T);
1069 else if (T->isVectorType())
1070 maxElements = T->castAs<VectorType>()->getNumElements();
1071 else
1072 llvm_unreachable("CheckImplicitInitList(): Illegal type")::llvm::llvm_unreachable_internal("CheckImplicitInitList(): Illegal type"
, "clang/lib/Sema/SemaInit.cpp", 1072)
;
1073
1074 if (maxElements == 0) {
1075 if (!VerifyOnly)
1076 SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(),
1077 diag::err_implicit_empty_initializer);
1078 ++Index;
1079 hadError = true;
1080 return;
1081 }
1082
1083 // Build a structured initializer list corresponding to this subobject.
1084 InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(
1085 ParentIList, Index, T, StructuredList, StructuredIndex,
1086 SourceRange(ParentIList->getInit(Index)->getBeginLoc(),
1087 ParentIList->getSourceRange().getEnd()));
1088 unsigned StructuredSubobjectInitIndex = 0;
1089
1090 // Check the element types and build the structural subobject.
1091 unsigned StartIndex = Index;
1092 CheckListElementTypes(Entity, ParentIList, T,
1093 /*SubobjectIsDesignatorContext=*/false, Index,
1094 StructuredSubobjectInitList,
1095 StructuredSubobjectInitIndex);
1096
1097 if (StructuredSubobjectInitList) {
1098 StructuredSubobjectInitList->setType(T);
1099
1100 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
1101 // Update the structured sub-object initializer so that it's ending
1102 // range corresponds with the end of the last initializer it used.
1103 if (EndIndex < ParentIList->getNumInits() &&
1104 ParentIList->getInit(EndIndex)) {
1105 SourceLocation EndLoc
1106 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
1107 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
1108 }
1109
1110 // Complain about missing braces.
1111 if (!VerifyOnly && (T->isArrayType() || T->isRecordType()) &&
1112 !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
1113 !isIdiomaticBraceElisionEntity(Entity)) {
1114 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1115 diag::warn_missing_braces)
1116 << StructuredSubobjectInitList->getSourceRange()
1117 << FixItHint::CreateInsertion(
1118 StructuredSubobjectInitList->getBeginLoc(), "{")
1119 << FixItHint::CreateInsertion(
1120 SemaRef.getLocForEndOfToken(
1121 StructuredSubobjectInitList->getEndLoc()),
1122 "}");
1123 }
1124
1125 // Warn if this type won't be an aggregate in future versions of C++.
1126 auto *CXXRD = T->getAsCXXRecordDecl();
1127 if (!VerifyOnly && CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1128 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1129 diag::warn_cxx20_compat_aggregate_init_with_ctors)
1130 << StructuredSubobjectInitList->getSourceRange() << T;
1131 }
1132 }
1133}
1134
1135/// Warn that \p Entity was of scalar type and was initialized by a
1136/// single-element braced initializer list.
1137static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
1138 SourceRange Braces) {
1139 // Don't warn during template instantiation. If the initialization was
1140 // non-dependent, we warned during the initial parse; otherwise, the
1141 // type might not be scalar in some uses of the template.
1142 if (S.inTemplateInstantiation())
1143 return;
1144
1145 unsigned DiagID = 0;
1146
1147 switch (Entity.getKind()) {
1148 case InitializedEntity::EK_VectorElement:
1149 case InitializedEntity::EK_ComplexElement:
1150 case InitializedEntity::EK_ArrayElement:
1151 case InitializedEntity::EK_Parameter:
1152 case InitializedEntity::EK_Parameter_CF_Audited:
1153 case InitializedEntity::EK_TemplateParameter:
1154 case InitializedEntity::EK_Result:
1155 // Extra braces here are suspicious.
1156 DiagID = diag::warn_braces_around_init;
1157 break;
1158
1159 case InitializedEntity::EK_Member:
1160 // Warn on aggregate initialization but not on ctor init list or
1161 // default member initializer.
1162 if (Entity.getParent())
1163 DiagID = diag::warn_braces_around_init;
1164 break;
1165
1166 case InitializedEntity::EK_Variable:
1167 case InitializedEntity::EK_LambdaCapture:
1168 // No warning, might be direct-list-initialization.
1169 // FIXME: Should we warn for copy-list-initialization in these cases?
1170 break;
1171
1172 case InitializedEntity::EK_New:
1173 case InitializedEntity::EK_Temporary:
1174 case InitializedEntity::EK_CompoundLiteralInit:
1175 // No warning, braces are part of the syntax of the underlying construct.
1176 break;
1177
1178 case InitializedEntity::EK_RelatedResult:
1179 // No warning, we already warned when initializing the result.
1180 break;
1181
1182 case InitializedEntity::EK_Exception:
1183 case InitializedEntity::EK_Base:
1184 case InitializedEntity::EK_Delegating:
1185 case InitializedEntity::EK_BlockElement:
1186 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
1187 case InitializedEntity::EK_Binding:
1188 case InitializedEntity::EK_StmtExprResult:
1189 llvm_unreachable("unexpected braced scalar init")::llvm::llvm_unreachable_internal("unexpected braced scalar init"
, "clang/lib/Sema/SemaInit.cpp", 1189)
;
1190 }
1191
1192 if (DiagID) {
1193 S.Diag(Braces.getBegin(), DiagID)
1194 << Entity.getType()->isSizelessBuiltinType() << Braces
1195 << FixItHint::CreateRemoval(Braces.getBegin())
1196 << FixItHint::CreateRemoval(Braces.getEnd());
1197 }
1198}
1199
1200/// Check whether the initializer \p IList (that was written with explicit
1201/// braces) can be used to initialize an object of type \p T.
1202///
1203/// This also fills in \p StructuredList with the fully-braced, desugared
1204/// form of the initialization.
1205void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
1206 InitListExpr *IList, QualType &T,
1207 InitListExpr *StructuredList,
1208 bool TopLevelObject) {
1209 unsigned Index = 0, StructuredIndex = 0;
1210 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
1211 Index, StructuredList, StructuredIndex, TopLevelObject);
1212 if (StructuredList) {
1213 QualType ExprTy = T;
1214 if (!ExprTy->isArrayType())
1215 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
1216 if (!VerifyOnly)
1217 IList->setType(ExprTy);
1218 StructuredList->setType(ExprTy);
1219 }
1220 if (hadError)
1221 return;
1222
1223 // Don't complain for incomplete types, since we'll get an error elsewhere.
1224 if (Index < IList->getNumInits() && !T->isIncompleteType()) {
1225 // We have leftover initializers
1226 bool ExtraInitsIsError = SemaRef.getLangOpts().CPlusPlus ||
1227 (SemaRef.getLangOpts().OpenCL && T->isVectorType());
1228 hadError = ExtraInitsIsError;
1229 if (VerifyOnly) {
1230 return;
1231 } else if (StructuredIndex == 1 &&
1232 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1233 SIF_None) {
1234 unsigned DK =
1235 ExtraInitsIsError
1236 ? diag::err_excess_initializers_in_char_array_initializer
1237 : diag::ext_excess_initializers_in_char_array_initializer;
1238 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1239 << IList->getInit(Index)->getSourceRange();
1240 } else if (T->isSizelessBuiltinType()) {
1241 unsigned DK = ExtraInitsIsError
1242 ? diag::err_excess_initializers_for_sizeless_type
1243 : diag::ext_excess_initializers_for_sizeless_type;
1244 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1245 << T << IList->getInit(Index)->getSourceRange();
1246 } else {
1247 int initKind = T->isArrayType() ? 0 :
1248 T->isVectorType() ? 1 :
1249 T->isScalarType() ? 2 :
1250 T->isUnionType() ? 3 :
1251 4;
1252
1253 unsigned DK = ExtraInitsIsError ? diag::err_excess_initializers
1254 : diag::ext_excess_initializers;
1255 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1256 << initKind << IList->getInit(Index)->getSourceRange();
1257 }
1258 }
1259
1260 if (!VerifyOnly) {
1261 if (T->isScalarType() && IList->getNumInits() == 1 &&
1262 !isa<InitListExpr>(IList->getInit(0)))
1263 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
1264
1265 // Warn if this is a class type that won't be an aggregate in future
1266 // versions of C++.
1267 auto *CXXRD = T->getAsCXXRecordDecl();
1268 if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1269 // Don't warn if there's an equivalent default constructor that would be
1270 // used instead.
1271 bool HasEquivCtor = false;
1272 if (IList->getNumInits() == 0) {
1273 auto *CD = SemaRef.LookupDefaultConstructor(CXXRD);
1274 HasEquivCtor = CD && !CD->isDeleted();
1275 }
1276
1277 if (!HasEquivCtor) {
1278 SemaRef.Diag(IList->getBeginLoc(),
1279 diag::warn_cxx20_compat_aggregate_init_with_ctors)
1280 << IList->getSourceRange() << T;
1281 }
1282 }
1283 }
1284}
1285
1286void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
1287 InitListExpr *IList,
1288 QualType &DeclType,
1289 bool SubobjectIsDesignatorContext,
1290 unsigned &Index,
1291 InitListExpr *StructuredList,
1292 unsigned &StructuredIndex,
1293 bool TopLevelObject) {
1294 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1295 // Explicitly braced initializer for complex type can be real+imaginary
1296 // parts.
1297 CheckComplexType(Entity, IList, DeclType, Index,
1298 StructuredList, StructuredIndex);
1299 } else if (DeclType->isScalarType()) {
1300 CheckScalarType(Entity, IList, DeclType, Index,
1301 StructuredList, StructuredIndex);
1302 } else if (DeclType->isVectorType()) {
1303 CheckVectorType(Entity, IList, DeclType, Index,
1304 StructuredList, StructuredIndex);
1305 } else if (DeclType->isRecordType()) {
1306 assert(DeclType->isAggregateType() &&(static_cast <bool> (DeclType->isAggregateType() &&
"non-aggregate records should be handed in CheckSubElementType"
) ? void (0) : __assert_fail ("DeclType->isAggregateType() && \"non-aggregate records should be handed in CheckSubElementType\""
, "clang/lib/Sema/SemaInit.cpp", 1307, __extension__ __PRETTY_FUNCTION__
))
1307 "non-aggregate records should be handed in CheckSubElementType")(static_cast <bool> (DeclType->isAggregateType() &&
"non-aggregate records should be handed in CheckSubElementType"
) ? void (0) : __assert_fail ("DeclType->isAggregateType() && \"non-aggregate records should be handed in CheckSubElementType\""
, "clang/lib/Sema/SemaInit.cpp", 1307, __extension__ __PRETTY_FUNCTION__
))
;
1308 RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl();
1309 auto Bases =
1310 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
1311 CXXRecordDecl::base_class_iterator());
1312 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1313 Bases = CXXRD->bases();
1314 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1315 SubobjectIsDesignatorContext, Index, StructuredList,
1316 StructuredIndex, TopLevelObject);
1317 } else if (DeclType->isArrayType()) {
1318 llvm::APSInt Zero(
1319 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1320 false);
1321 CheckArrayType(Entity, IList, DeclType, Zero,
1322 SubobjectIsDesignatorContext, Index,
1323 StructuredList, StructuredIndex);
1324 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1325 // This type is invalid, issue a diagnostic.
1326 ++Index;
1327 if (!VerifyOnly)
1328 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1329 << DeclType;
1330 hadError = true;
1331 } else if (DeclType->isReferenceType()) {
1332 CheckReferenceType(Entity, IList, DeclType, Index,
1333 StructuredList, StructuredIndex);
1334 } else if (DeclType->isObjCObjectType()) {
1335 if (!VerifyOnly)
1336 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType;
1337 hadError = true;
1338 } else if (DeclType->isOCLIntelSubgroupAVCType() ||
1339 DeclType->isSizelessBuiltinType()) {
1340 // Checks for scalar type are sufficient for these types too.
1341 CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1342 StructuredIndex);
1343 } else {
1344 if (!VerifyOnly)
1345 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1346 << DeclType;
1347 hadError = true;
1348 }
1349}
1350
1351void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
1352 InitListExpr *IList,
1353 QualType ElemType,
1354 unsigned &Index,
1355 InitListExpr *StructuredList,
1356 unsigned &StructuredIndex,
1357 bool DirectlyDesignated) {
1358 Expr *expr = IList->getInit(Index);
1359
1360 if (ElemType->isReferenceType())
1361 return CheckReferenceType(Entity, IList, ElemType, Index,
1362 StructuredList, StructuredIndex);
1363
1364 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
1365 if (SubInitList->getNumInits() == 1 &&
1366 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1367 SIF_None) {
1368 // FIXME: It would be more faithful and no less correct to include an
1369 // InitListExpr in the semantic form of the initializer list in this case.
1370 expr = SubInitList->getInit(0);
1371 }
1372 // Nested aggregate initialization and C++ initialization are handled later.
1373 } else if (isa<ImplicitValueInitExpr>(expr)) {
1374 // This happens during template instantiation when we see an InitListExpr
1375 // that we've already checked once.
1376 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&(static_cast <bool> (SemaRef.Context.hasSameType(expr->
getType(), ElemType) && "found implicit initialization for the wrong type"
) ? void (0) : __assert_fail ("SemaRef.Context.hasSameType(expr->getType(), ElemType) && \"found implicit initialization for the wrong type\""
, "clang/lib/Sema/SemaInit.cpp", 1377, __extension__ __PRETTY_FUNCTION__
))
1377 "found implicit initialization for the wrong type")(static_cast <bool> (SemaRef.Context.hasSameType(expr->
getType(), ElemType) && "found implicit initialization for the wrong type"
) ? void (0) : __assert_fail ("SemaRef.Context.hasSameType(expr->getType(), ElemType) && \"found implicit initialization for the wrong type\""
, "clang/lib/Sema/SemaInit.cpp", 1377, __extension__ __PRETTY_FUNCTION__
))
;
1378 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1379 ++Index;
1380 return;
1381 }
1382
1383 if (SemaRef.getLangOpts().CPlusPlus || isa<InitListExpr>(expr)) {
1384 // C++ [dcl.init.aggr]p2:
1385 // Each member is copy-initialized from the corresponding
1386 // initializer-clause.
1387
1388 // FIXME: Better EqualLoc?
1389 InitializationKind Kind =
1390 InitializationKind::CreateCopy(expr->getBeginLoc(), SourceLocation());
1391
1392 // Vector elements can be initialized from other vectors in which case
1393 // we need initialization entity with a type of a vector (and not a vector
1394 // element!) initializing multiple vector elements.
1395 auto TmpEntity =
1396 (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType())
1397 ? InitializedEntity::InitializeTemporary(ElemType)
1398 : Entity;
1399
1400 InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr,
1401 /*TopLevelOfInitList*/ true);
1402
1403 // C++14 [dcl.init.aggr]p13:
1404 // If the assignment-expression can initialize a member, the member is
1405 // initialized. Otherwise [...] brace elision is assumed
1406 //
1407 // Brace elision is never performed if the element is not an
1408 // assignment-expression.
1409 if (Seq || isa<InitListExpr>(expr)) {
1410 if (!VerifyOnly) {
1411 ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr);
1412 if (Result.isInvalid())
1413 hadError = true;
1414
1415 UpdateStructuredListElement(StructuredList, StructuredIndex,
1416 Result.getAs<Expr>());
1417 } else if (!Seq) {
1418 hadError = true;
1419 } else if (StructuredList) {
1420 UpdateStructuredListElement(StructuredList, StructuredIndex,
1421 getDummyInit());
1422 }
1423 ++Index;
1424 return;
1425 }
1426
1427 // Fall through for subaggregate initialization
1428 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1429 // FIXME: Need to handle atomic aggregate types with implicit init lists.
1430 return CheckScalarType(Entity, IList, ElemType, Index,
1431 StructuredList, StructuredIndex);
1432 } else if (const ArrayType *arrayType =
1433 SemaRef.Context.getAsArrayType(ElemType)) {
1434 // arrayType can be incomplete if we're initializing a flexible
1435 // array member. There's nothing we can do with the completed
1436 // type here, though.
1437
1438 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
1439 // FIXME: Should we do this checking in verify-only mode?
1440 if (!VerifyOnly)
1441 CheckStringInit(expr, ElemType, arrayType, SemaRef);
1442 if (StructuredList)
1443 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1444 ++Index;
1445 return;
1446 }
1447
1448 // Fall through for subaggregate initialization.
1449
1450 } else {
1451 assert((ElemType->isRecordType() || ElemType->isVectorType() ||(static_cast <bool> ((ElemType->isRecordType() || ElemType
->isVectorType() || ElemType->isOpenCLSpecificType()) &&
"Unexpected type") ? void (0) : __assert_fail ("(ElemType->isRecordType() || ElemType->isVectorType() || ElemType->isOpenCLSpecificType()) && \"Unexpected type\""
, "clang/lib/Sema/SemaInit.cpp", 1452, __extension__ __PRETTY_FUNCTION__
))
1452 ElemType->isOpenCLSpecificType()) && "Unexpected type")(static_cast <bool> ((ElemType->isRecordType() || ElemType
->isVectorType() || ElemType->isOpenCLSpecificType()) &&
"Unexpected type") ? void (0) : __assert_fail ("(ElemType->isRecordType() || ElemType->isVectorType() || ElemType->isOpenCLSpecificType()) && \"Unexpected type\""
, "clang/lib/Sema/SemaInit.cpp", 1452, __extension__ __PRETTY_FUNCTION__
))
;
1453
1454 // C99 6.7.8p13:
1455 //
1456 // The initializer for a structure or union object that has
1457 // automatic storage duration shall be either an initializer
1458 // list as described below, or a single expression that has
1459 // compatible structure or union type. In the latter case, the
1460 // initial value of the object, including unnamed members, is
1461 // that of the expression.
1462 ExprResult ExprRes = expr;
1463 if (SemaRef.CheckSingleAssignmentConstraints(
1464 ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
1465 if (ExprRes.isInvalid())
1466 hadError = true;
1467 else {
1468 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
1469 if (ExprRes.isInvalid())
1470 hadError = true;
1471 }
1472 UpdateStructuredListElement(StructuredList, StructuredIndex,
1473 ExprRes.getAs<Expr>());
1474 ++Index;
1475 return;
1476 }
1477 ExprRes.get();
1478 // Fall through for subaggregate initialization
1479 }
1480
1481 // C++ [dcl.init.aggr]p12:
1482 //
1483 // [...] Otherwise, if the member is itself a non-empty
1484 // subaggregate, brace elision is assumed and the initializer is
1485 // considered for the initialization of the first member of
1486 // the subaggregate.
1487 // OpenCL vector initializer is handled elsewhere.
1488 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1489 ElemType->isAggregateType()) {
1490 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1491 StructuredIndex);
1492 ++StructuredIndex;
1493
1494 // In C++20, brace elision is not permitted for a designated initializer.
1495 if (DirectlyDesignated && SemaRef.getLangOpts().CPlusPlus && !hadError) {
1496 if (InOverloadResolution)
1497 hadError = true;
1498 if (!VerifyOnly) {
1499 SemaRef.Diag(expr->getBeginLoc(),
1500 diag::ext_designated_init_brace_elision)
1501 << expr->getSourceRange()
1502 << FixItHint::CreateInsertion(expr->getBeginLoc(), "{")
1503 << FixItHint::CreateInsertion(
1504 SemaRef.getLocForEndOfToken(expr->getEndLoc()), "}");
1505 }
1506 }
1507 } else {
1508 if (!VerifyOnly) {
1509 // We cannot initialize this element, so let PerformCopyInitialization
1510 // produce the appropriate diagnostic. We already checked that this
1511 // initialization will fail.
1512 ExprResult Copy =
1513 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
1514 /*TopLevelOfInitList=*/true);
1515 (void)Copy;
1516 assert(Copy.isInvalid() &&(static_cast <bool> (Copy.isInvalid() && "expected non-aggregate initialization to fail"
) ? void (0) : __assert_fail ("Copy.isInvalid() && \"expected non-aggregate initialization to fail\""
, "clang/lib/Sema/SemaInit.cpp", 1517, __extension__ __PRETTY_FUNCTION__
))
1517 "expected non-aggregate initialization to fail")(static_cast <bool> (Copy.isInvalid() && "expected non-aggregate initialization to fail"
) ? void (0) : __assert_fail ("Copy.isInvalid() && \"expected non-aggregate initialization to fail\""
, "clang/lib/Sema/SemaInit.cpp", 1517, __extension__ __PRETTY_FUNCTION__
))
;
1518 }
1519 hadError = true;
1520 ++Index;
1521 ++StructuredIndex;
1522 }
1523}
1524
1525void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1526 InitListExpr *IList, QualType DeclType,
1527 unsigned &Index,
1528 InitListExpr *StructuredList,
1529 unsigned &StructuredIndex) {
1530 assert(Index == 0 && "Index in explicit init list must be zero")(static_cast <bool> (Index == 0 && "Index in explicit init list must be zero"
) ? void (0) : __assert_fail ("Index == 0 && \"Index in explicit init list must be zero\""
, "clang/lib/Sema/SemaInit.cpp", 1530, __extension__ __PRETTY_FUNCTION__
))
;
1531
1532 // As an extension, clang supports complex initializers, which initialize
1533 // a complex number component-wise. When an explicit initializer list for
1534 // a complex number contains two initializers, this extension kicks in:
1535 // it expects the initializer list to contain two elements convertible to
1536 // the element type of the complex type. The first element initializes
1537 // the real part, and the second element intitializes the imaginary part.
1538
1539 if (IList->getNumInits() < 2)
1540 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1541 StructuredIndex);
1542
1543 // This is an extension in C. (The builtin _Complex type does not exist
1544 // in the C++ standard.)
1545 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
1546 SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init)
1547 << IList->getSourceRange();
1548
1549 // Initialize the complex number.
1550 QualType elementType = DeclType->castAs<ComplexType>()->getElementType();
1551 InitializedEntity ElementEntity =
1552 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1553
1554 for (unsigned i = 0; i < 2; ++i) {
1555 ElementEntity.setElementIndex(Index);
1556 CheckSubElementType(ElementEntity, IList, elementType, Index,
1557 StructuredList, StructuredIndex);
1558 }
1559}
1560
1561void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
1562 InitListExpr *IList, QualType DeclType,
1563 unsigned &Index,
1564 InitListExpr *StructuredList,
1565 unsigned &StructuredIndex) {
1566 if (Index >= IList->getNumInits()) {
1567 if (!VerifyOnly) {
1568 if (SemaRef.getLangOpts().CPlusPlus) {
1569 if (DeclType->isSizelessBuiltinType())
1570 SemaRef.Diag(IList->getBeginLoc(),
1571 SemaRef.getLangOpts().CPlusPlus11
1572 ? diag::warn_cxx98_compat_empty_sizeless_initializer
1573 : diag::err_empty_sizeless_initializer)
1574 << DeclType << IList->getSourceRange();
1575 else
1576 SemaRef.Diag(IList->getBeginLoc(),
1577 SemaRef.getLangOpts().CPlusPlus11
1578 ? diag::warn_cxx98_compat_empty_scalar_initializer
1579 : diag::err_empty_scalar_initializer)
1580 << IList->getSourceRange();
1581 }
1582 }
1583 hadError =
1584 SemaRef.getLangOpts().CPlusPlus && !SemaRef.getLangOpts().CPlusPlus11;
1585 ++Index;
1586 ++StructuredIndex;
1587 return;
1588 }
1589
1590 Expr *expr = IList->getInit(Index);
1591 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
1592 // FIXME: This is invalid, and accepting it causes overload resolution
1593 // to pick the wrong overload in some corner cases.
1594 if (!VerifyOnly)
1595 SemaRef.Diag(SubIList->getBeginLoc(), diag::ext_many_braces_around_init)
1596 << DeclType->isSizelessBuiltinType() << SubIList->getSourceRange();
1597
1598 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1599 StructuredIndex);
1600 return;
1601 } else if (isa<DesignatedInitExpr>(expr)) {
1602 if (!VerifyOnly)
1603 SemaRef.Diag(expr->getBeginLoc(),
1604 diag::err_designator_for_scalar_or_sizeless_init)
1605 << DeclType->isSizelessBuiltinType() << DeclType
1606 << expr->getSourceRange();
1607 hadError = true;
1608 ++Index;
1609 ++StructuredIndex;
1610 return;
1611 }
1612
1613 ExprResult Result;
1614 if (VerifyOnly) {
1615 if (SemaRef.CanPerformCopyInitialization(Entity, expr))
1616 Result = getDummyInit();
1617 else
1618 Result = ExprError();
1619 } else {
1620 Result =
1621 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1622 /*TopLevelOfInitList=*/true);
1623 }
1624
1625 Expr *ResultExpr = nullptr;
1626
1627 if (Result.isInvalid())
1628 hadError = true; // types weren't compatible.
1629 else {
1630 ResultExpr = Result.getAs<Expr>();
1631
1632 if (ResultExpr != expr && !VerifyOnly) {
1633 // The type was promoted, update initializer list.
1634 // FIXME: Why are we updating the syntactic init list?
1635 IList->setInit(Index, ResultExpr);
1636 }
1637 }
1638 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1639 ++Index;
1640}
1641
1642void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1643 InitListExpr *IList, QualType DeclType,
1644 unsigned &Index,
1645 InitListExpr *StructuredList,
1646 unsigned &StructuredIndex) {
1647 if (Index >= IList->getNumInits()) {
1648 // FIXME: It would be wonderful if we could point at the actual member. In
1649 // general, it would be useful to pass location information down the stack,
1650 // so that we know the location (or decl) of the "current object" being
1651 // initialized.
1652 if (!VerifyOnly)
1653 SemaRef.Diag(IList->getBeginLoc(),
1654 diag::err_init_reference_member_uninitialized)
1655 << DeclType << IList->getSourceRange();
1656 hadError = true;
1657 ++Index;
1658 ++StructuredIndex;
1659 return;
1660 }
1661
1662 Expr *expr = IList->getInit(Index);
1663 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1664 if (!VerifyOnly)
1665 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list)
1666 << DeclType << IList->getSourceRange();
1667 hadError = true;
1668 ++Index;
1669 ++StructuredIndex;
1670 return;
1671 }
1672
1673 ExprResult Result;
1674 if (VerifyOnly) {
1675 if (SemaRef.CanPerformCopyInitialization(Entity,expr))
1676 Result = getDummyInit();
1677 else
1678 Result = ExprError();
1679 } else {
1680 Result =
1681 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1682 /*TopLevelOfInitList=*/true);
1683 }
1684
1685 if (Result.isInvalid())
1686 hadError = true;
1687
1688 expr = Result.getAs<Expr>();
1689 // FIXME: Why are we updating the syntactic init list?
1690 if (!VerifyOnly && expr)
1691 IList->setInit(Index, expr);
1692
1693 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1694 ++Index;
1695}
1696
1697void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1698 InitListExpr *IList, QualType DeclType,
1699 unsigned &Index,
1700 InitListExpr *StructuredList,
1701 unsigned &StructuredIndex) {
1702 const VectorType *VT = DeclType->castAs<VectorType>();
1703 unsigned maxElements = VT->getNumElements();
1704 unsigned numEltsInit = 0;
1705 QualType elementType = VT->getElementType();
1706
1707 if (Index >= IList->getNumInits()) {
1708 // Make sure the element type can be value-initialized.
1709 CheckEmptyInitializable(
1710 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1711 IList->getEndLoc());
1712 return;
1713 }
1714
1715 if (!SemaRef.getLangOpts().OpenCL && !SemaRef.getLangOpts().HLSL ) {
1716 // If the initializing element is a vector, try to copy-initialize
1717 // instead of breaking it apart (which is doomed to failure anyway).
1718 Expr *Init = IList->getInit(Index);
1719 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1720 ExprResult Result;
1721 if (VerifyOnly) {
1722 if (SemaRef.CanPerformCopyInitialization(Entity, Init))
1723 Result = getDummyInit();
1724 else
1725 Result = ExprError();
1726 } else {
1727 Result =
1728 SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init,
1729 /*TopLevelOfInitList=*/true);
1730 }
1731
1732 Expr *ResultExpr = nullptr;
1733 if (Result.isInvalid())
1734 hadError = true; // types weren't compatible.
1735 else {
1736 ResultExpr = Result.getAs<Expr>();
1737
1738 if (ResultExpr != Init && !VerifyOnly) {
1739 // The type was promoted, update initializer list.
1740 // FIXME: Why are we updating the syntactic init list?
1741 IList->setInit(Index, ResultExpr);
1742 }
1743 }
1744 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1745 ++Index;
1746 return;
1747 }
1748
1749 InitializedEntity ElementEntity =
1750 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1751
1752 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1753 // Don't attempt to go past the end of the init list
1754 if (Index >= IList->getNumInits()) {
1755 CheckEmptyInitializable(ElementEntity, IList->getEndLoc());
1756 break;
1757 }
1758
1759 ElementEntity.setElementIndex(Index);
1760 CheckSubElementType(ElementEntity, IList, elementType, Index,
1761 StructuredList, StructuredIndex);
1762 }
1763
1764 if (VerifyOnly)
1765 return;
1766
1767 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1768 const VectorType *T = Entity.getType()->castAs<VectorType>();
1769 if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1770 T->getVectorKind() == VectorType::NeonPolyVector)) {
1771 // The ability to use vector initializer lists is a GNU vector extension
1772 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1773 // endian machines it works fine, however on big endian machines it
1774 // exhibits surprising behaviour:
1775 //
1776 // uint32x2_t x = {42, 64};
1777 // return vget_lane_u32(x, 0); // Will return 64.
1778 //
1779 // Because of this, explicitly call out that it is non-portable.
1780 //
1781 SemaRef.Diag(IList->getBeginLoc(),
1782 diag::warn_neon_vector_initializer_non_portable);
1783
1784 const char *typeCode;
1785 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1786
1787 if (elementType->isFloatingType())
1788 typeCode = "f";
1789 else if (elementType->isSignedIntegerType())
1790 typeCode = "s";
1791 else if (elementType->isUnsignedIntegerType())
1792 typeCode = "u";
1793 else
1794 llvm_unreachable("Invalid element type!")::llvm::llvm_unreachable_internal("Invalid element type!", "clang/lib/Sema/SemaInit.cpp"
, 1794)
;
1795
1796 SemaRef.Diag(IList->getBeginLoc(),
1797 SemaRef.Context.getTypeSize(VT) > 64
1798 ? diag::note_neon_vector_initializer_non_portable_q
1799 : diag::note_neon_vector_initializer_non_portable)
1800 << typeCode << typeSize;
1801 }
1802
1803 return;
1804 }
1805
1806 InitializedEntity ElementEntity =
1807 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1808
1809 // OpenCL and HLSL initializers allow vectors to be constructed from vectors.
1810 for (unsigned i = 0; i < maxElements; ++i) {
1811 // Don't attempt to go past the end of the init list
1812 if (Index >= IList->getNumInits())
1813 break;
1814
1815 ElementEntity.setElementIndex(Index);
1816
1817 QualType IType = IList->getInit(Index)->getType();
1818 if (!IType->isVectorType()) {
1819 CheckSubElementType(ElementEntity, IList, elementType, Index,
1820 StructuredList, StructuredIndex);
1821 ++numEltsInit;
1822 } else {
1823 QualType VecType;
1824 const VectorType *IVT = IType->castAs<VectorType>();
1825 unsigned numIElts = IVT->getNumElements();
1826
1827 if (IType->isExtVectorType())
1828 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1829 else
1830 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
1831 IVT->getVectorKind());
1832 CheckSubElementType(ElementEntity, IList, VecType, Index,
1833 StructuredList, StructuredIndex);
1834 numEltsInit += numIElts;
1835 }
1836 }
1837
1838 // OpenCL and HLSL require all elements to be initialized.
1839 if (numEltsInit != maxElements) {
1840 if (!VerifyOnly)
1841 SemaRef.Diag(IList->getBeginLoc(),
1842 diag::err_vector_incorrect_num_initializers)
1843 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1844 hadError = true;
1845 }
1846}
1847
1848/// Check if the type of a class element has an accessible destructor, and marks
1849/// it referenced. Returns true if we shouldn't form a reference to the
1850/// destructor.
1851///
1852/// Aggregate initialization requires a class element's destructor be
1853/// accessible per 11.6.1 [dcl.init.aggr]:
1854///
1855/// The destructor for each element of class type is potentially invoked
1856/// (15.4 [class.dtor]) from the context where the aggregate initialization
1857/// occurs.
1858static bool checkDestructorReference(QualType ElementType, SourceLocation Loc,
1859 Sema &SemaRef) {
1860 auto *CXXRD = ElementType->getAsCXXRecordDecl();
1861 if (!CXXRD)
1862 return false;
1863
1864 CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(CXXRD);
1865 SemaRef.CheckDestructorAccess(Loc, Destructor,
1866 SemaRef.PDiag(diag::err_access_dtor_temp)
1867 << ElementType);
1868 SemaRef.MarkFunctionReferenced(Loc, Destructor);
1869 return SemaRef.DiagnoseUseOfDecl(Destructor, Loc);
1870}
1871
1872void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
1873 InitListExpr *IList, QualType &DeclType,
1874 llvm::APSInt elementIndex,
1875 bool SubobjectIsDesignatorContext,
1876 unsigned &Index,
1877 InitListExpr *StructuredList,
1878 unsigned &StructuredIndex) {
1879 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1880
1881 if (!VerifyOnly) {
1882 if (checkDestructorReference(arrayType->getElementType(),
1883 IList->getEndLoc(), SemaRef)) {
1884 hadError = true;
1885 return;
1886 }
1887 }
1888
1889 // Check for the special-case of initializing an array with a string.
1890 if (Index < IList->getNumInits()) {
1891 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1892 SIF_None) {
1893 // We place the string literal directly into the resulting
1894 // initializer list. This is the only place where the structure
1895 // of the structured initializer list doesn't match exactly,
1896 // because doing so would involve allocating one character
1897 // constant for each string.
1898 // FIXME: Should we do these checks in verify-only mode too?
1899 if (!VerifyOnly)
1900 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1901 if (StructuredList) {
1902 UpdateStructuredListElement(StructuredList, StructuredIndex,
1903 IList->getInit(Index));
1904 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1905 }
1906 ++Index;
1907 return;
1908 }
1909 }
1910 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
1911 // Check for VLAs; in standard C it would be possible to check this
1912 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1913 // them in all sorts of strange places).
1914 bool HasErr = IList->getNumInits() != 0 || SemaRef.getLangOpts().CPlusPlus;
1915 if (!VerifyOnly) {
1916 // C2x 6.7.9p4: An entity of variable length array type shall not be
1917 // initialized except by an empty initializer.
1918 //
1919 // The C extension warnings are issued from ParseBraceInitializer() and
1920 // do not need to be issued here. However, we continue to issue an error
1921 // in the case there are initializers or we are compiling C++. We allow
1922 // use of VLAs in C++, but it's not clear we want to allow {} to zero
1923 // init a VLA in C++ in all cases (such as with non-trivial constructors).
1924 // FIXME: should we allow this construct in C++ when it makes sense to do
1925 // so?
1926 if (HasErr)
1927 SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),
1928 diag::err_variable_object_no_init)
1929 << VAT->getSizeExpr()->getSourceRange();
1930 }
1931 hadError = HasErr;
1932 ++Index;
1933 ++StructuredIndex;
1934 return;
1935 }
1936
1937 // We might know the maximum number of elements in advance.
1938 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1939 elementIndex.isUnsigned());
1940 bool maxElementsKnown = false;
1941 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
1942 maxElements = CAT->getSize();
1943 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
1944 elementIndex.setIsUnsigned(maxElements.isUnsigned());
1945 maxElementsKnown = true;
1946 }
1947
1948 QualType elementType = arrayType->getElementType();
1949 while (Index < IList->getNumInits()) {
1950 Expr *Init = IList->getInit(Index);
1951 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1952 // If we're not the subobject that matches up with the '{' for
1953 // the designator, we shouldn't be handling the
1954 // designator. Return immediately.
1955 if (!SubobjectIsDesignatorContext)
1956 return;
1957
1958 // Handle this designated initializer. elementIndex will be
1959 // updated to be the next array element we'll initialize.
1960 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1961 DeclType, nullptr, &elementIndex, Index,
1962 StructuredList, StructuredIndex, true,
1963 false)) {
1964 hadError = true;
1965 continue;
1966 }
1967
1968 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1969 maxElements = maxElements.extend(elementIndex.getBitWidth());
1970 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1971 elementIndex = elementIndex.extend(maxElements.getBitWidth());
1972 elementIndex.setIsUnsigned(maxElements.isUnsigned());
1973
1974 // If the array is of incomplete type, keep track of the number of
1975 // elements in the initializer.
1976 if (!maxElementsKnown && elementIndex > maxElements)
1977 maxElements = elementIndex;
1978
1979 continue;
1980 }
1981
1982 // If we know the maximum number of elements, and we've already
1983 // hit it, stop consuming elements in the initializer list.
1984 if (maxElementsKnown && elementIndex == maxElements)
1985 break;
1986
1987 InitializedEntity ElementEntity =
1988 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
1989 Entity);
1990 // Check this element.
1991 CheckSubElementType(ElementEntity, IList, elementType, Index,
1992 StructuredList, StructuredIndex);
1993 ++elementIndex;
1994
1995 // If the array is of incomplete type, keep track of the number of
1996 // elements in the initializer.
1997 if (!maxElementsKnown && elementIndex > maxElements)
1998 maxElements = elementIndex;
1999 }
2000 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
2001 // If this is an incomplete array type, the actual type needs to
2002 // be calculated here.
2003 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
2004 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
2005 // Sizing an array implicitly to zero is not allowed by ISO C,
2006 // but is supported by GNU.
2007 SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
2008 }
2009
2010 DeclType = SemaRef.Context.getConstantArrayType(
2011 elementType, maxElements, nullptr, ArrayType::Normal, 0);
2012 }
2013 if (!hadError) {
2014 // If there are any members of the array that get value-initialized, check
2015 // that is possible. That happens if we know the bound and don't have
2016 // enough elements, or if we're performing an array new with an unknown
2017 // bound.
2018 if ((maxElementsKnown && elementIndex < maxElements) ||
2019 Entity.isVariableLengthArrayNew())
2020 CheckEmptyInitializable(
2021 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
2022 IList->getEndLoc());
2023 }
2024}
2025
2026bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
2027 Expr *InitExpr,
2028 FieldDecl *Field,
2029 bool TopLevelObject) {
2030 // Handle GNU flexible array initializers.
2031 unsigned FlexArrayDiag;
2032 if (isa<InitListExpr>(InitExpr) &&
2033 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
2034 // Empty flexible array init always allowed as an extension
2035 FlexArrayDiag = diag::ext_flexible_array_init;
2036 } else if (!TopLevelObject) {
2037 // Disallow flexible array init on non-top-level object
2038 FlexArrayDiag = diag::err_flexible_array_init;
2039 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
2040 // Disallow flexible array init on anything which is not a variable.
2041 FlexArrayDiag = diag::err_flexible_array_init;
2042 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
2043 // Disallow flexible array init on local variables.
2044 FlexArrayDiag = diag::err_flexible_array_init;
2045 } else {
2046 // Allow other cases.
2047 FlexArrayDiag = diag::ext_flexible_array_init;
2048 }
2049
2050 if (!VerifyOnly) {
2051 SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
2052 << InitExpr->getBeginLoc();
2053 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2054 << Field;
2055 }
2056
2057 return FlexArrayDiag != diag::ext_flexible_array_init;
2058}
2059
2060void InitListChecker::CheckStructUnionTypes(
2061 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
2062 CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field,
2063 bool SubobjectIsDesignatorContext, unsigned &Index,
2064 InitListExpr *StructuredList, unsigned &StructuredIndex,
2065 bool TopLevelObject) {
2066 RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl();
2067
2068 // If the record is invalid, some of it's members are invalid. To avoid
2069 // confusion, we forgo checking the initializer for the entire record.
2070 if (structDecl->isInvalidDecl()) {
2071 // Assume it was supposed to consume a single initializer.
2072 ++Index;
2073 hadError = true;
2074 return;
2075 }
2076
2077 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
2078 RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl();
2079
2080 if (!VerifyOnly)
2081 for (FieldDecl *FD : RD->fields()) {
2082 QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
2083 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2084 hadError = true;
2085 return;
2086 }
2087 }
2088
2089 // If there's a default initializer, use it.
2090 if (isa<CXXRecordDecl>(RD) &&
2091 cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
2092 if (!StructuredList)
2093 return;
2094 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2095 Field != FieldEnd; ++Field) {
2096 if (Field->hasInClassInitializer()) {
2097 StructuredList->setInitializedFieldInUnion(*Field);
2098 // FIXME: Actually build a CXXDefaultInitExpr?
2099 return;
2100 }
2101 }
2102 }
2103
2104 // Value-initialize the first member of the union that isn't an unnamed
2105 // bitfield.
2106 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2107 Field != FieldEnd; ++Field) {
2108 if (!Field->isUnnamedBitfield()) {
2109 CheckEmptyInitializable(
2110 InitializedEntity::InitializeMember(*Field, &Entity),
2111 IList->getEndLoc());
2112 if (StructuredList)
2113 StructuredList->setInitializedFieldInUnion(*Field);
2114 break;
2115 }
2116 }
2117 return;
2118 }
2119
2120 bool InitializedSomething = false;
2121
2122 // If we have any base classes, they are initialized prior to the fields.
2123 for (auto &Base : Bases) {
2124 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
2125
2126 // Designated inits always initialize fields, so if we see one, all
2127 // remaining base classes have no explicit initializer.
2128 if (Init && isa<DesignatedInitExpr>(Init))
2129 Init = nullptr;
2130
2131 SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
2132 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
2133 SemaRef.Context, &Base, false, &Entity);
2134 if (Init) {
2135 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
2136 StructuredList, StructuredIndex);
2137 InitializedSomething = true;
2138 } else {
2139 CheckEmptyInitializable(BaseEntity, InitLoc);
2140 }
2141
2142 if (!VerifyOnly)
2143 if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) {
2144 hadError = true;
2145 return;
2146 }
2147 }
2148
2149 // If structDecl is a forward declaration, this loop won't do
2150 // anything except look at designated initializers; That's okay,
2151 // because an error should get printed out elsewhere. It might be
2152 // worthwhile to skip over the rest of the initializer, though.
2153 RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl();
2154 RecordDecl::field_iterator FieldEnd = RD->field_end();
2155 size_t NumRecordDecls = llvm::count_if(RD->decls(), [&](const Decl *D) {
2156 return isa<FieldDecl>(D) || isa<RecordDecl>(D);
2157 });
2158 bool CheckForMissingFields =
2159 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
2160 bool HasDesignatedInit = false;
2161
2162 while (Index < IList->getNumInits()) {
2163 Expr *Init = IList->getInit(Index);
2164 SourceLocation InitLoc = Init->getBeginLoc();
2165
2166 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2167 // If we're not the subobject that matches up with the '{' for
2168 // the designator, we shouldn't be handling the
2169 // designator. Return immediately.
2170 if (!SubobjectIsDesignatorContext)
2171 return;
2172
2173 HasDesignatedInit = true;
2174
2175 // Handle this designated initializer. Field will be updated to
2176 // the next field that we'll be initializing.
2177 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
2178 DeclType, &Field, nullptr, Index,
2179 StructuredList, StructuredIndex,
2180 true, TopLevelObject))
2181 hadError = true;
2182 else if (!VerifyOnly) {
2183 // Find the field named by the designated initializer.
2184 RecordDecl::field_iterator F = RD->field_begin();
2185 while (std::next(F) != Field)
2186 ++F;
2187 QualType ET = SemaRef.Context.getBaseElementType(F->getType());
2188 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2189 hadError = true;
2190 return;
2191 }
2192 }
2193
2194 InitializedSomething = true;
2195
2196 // Disable check for missing fields when designators are used.
2197 // This matches gcc behaviour.
2198 CheckForMissingFields = false;
2199 continue;
2200 }
2201
2202 // Check if this is an initializer of forms:
2203 //
2204 // struct foo f = {};
2205 // struct foo g = {0};
2206 //
2207 // These are okay for randomized structures. [C99 6.7.8p19]
2208 //
2209 // Also, if there is only one element in the structure, we allow something
2210 // like this, because it's really not randomized in the tranditional sense.
2211 //
2212 // struct foo h = {bar};
2213 auto IsZeroInitializer = [&](const Expr *I) {
2214 if (IList->getNumInits() == 1) {
2215 if (NumRecordDecls == 1)
2216 return true;
2217 if (const auto *IL = dyn_cast<IntegerLiteral>(I))
2218 return IL->getValue().isZero();
2219 }
2220 return false;
2221 };
2222
2223 // Don't allow non-designated initializers on randomized structures.
2224 if (RD->isRandomized() && !IsZeroInitializer(Init)) {
2225 if (!VerifyOnly)
2226 SemaRef.Diag(InitLoc, diag::err_non_designated_init_used);
2227 hadError = true;
2228 break;
2229 }
2230
2231 if (Field == FieldEnd) {
2232 // We've run out of fields. We're done.
2233 break;
2234 }
2235
2236 // We've already initialized a member of a union. We're done.
2237 if (InitializedSomething && DeclType->isUnionType())
2238 break;
2239
2240 // If we've hit the flexible array member at the end, we're done.
2241 if (Field->getType()->isIncompleteArrayType())
2242 break;
2243
2244 if (Field->isUnnamedBitfield()) {
2245 // Don't initialize unnamed bitfields, e.g. "int : 20;"
2246 ++Field;
2247 continue;
2248 }
2249
2250 // Make sure we can use this declaration.
2251 bool InvalidUse;
2252 if (VerifyOnly)
2253 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2254 else
2255 InvalidUse = SemaRef.DiagnoseUseOfDecl(
2256 *Field, IList->getInit(Index)->getBeginLoc());
2257 if (InvalidUse) {
2258 ++Index;
2259 ++Field;
2260 hadError = true;
2261 continue;
2262 }
2263
2264 if (!VerifyOnly) {
2265 QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
2266 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2267 hadError = true;
2268 return;
2269 }
2270 }
2271
2272 InitializedEntity MemberEntity =
2273 InitializedEntity::InitializeMember(*Field, &Entity);
2274 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2275 StructuredList, StructuredIndex);
2276 InitializedSomething = true;
2277
2278 if (DeclType->isUnionType() && StructuredList) {
2279 // Initialize the first field within the union.
2280 StructuredList->setInitializedFieldInUnion(*Field);
2281 }
2282
2283 ++Field;
2284 }
2285
2286 // Emit warnings for missing struct field initializers.
2287 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
2288 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
2289 !DeclType->isUnionType()) {
2290 // It is possible we have one or more unnamed bitfields remaining.
2291 // Find first (if any) named field and emit warning.
2292 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
2293 it != end; ++it) {
2294 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
2295 SemaRef.Diag(IList->getSourceRange().getEnd(),
2296 diag::warn_missing_field_initializers) << *it;
2297 break;
2298 }
2299 }
2300 }
2301
2302 // Check that any remaining fields can be value-initialized if we're not
2303 // building a structured list. (If we are, we'll check this later.)
2304 if (!StructuredList && Field != FieldEnd && !DeclType->isUnionType() &&
2305 !Field->getType()->isIncompleteArrayType()) {
2306 for (; Field != FieldEnd && !hadError; ++Field) {
2307 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
2308 CheckEmptyInitializable(
2309 InitializedEntity::InitializeMember(*Field, &Entity),
2310 IList->getEndLoc());
2311 }
2312 }
2313
2314 // Check that the types of the remaining fields have accessible destructors.
2315 if (!VerifyOnly) {
2316 // If the initializer expression has a designated initializer, check the
2317 // elements for which a designated initializer is not provided too.
2318 RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
2319 : Field;
2320 for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
2321 QualType ET = SemaRef.Context.getBaseElementType(I->getType());
2322 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2323 hadError = true;
2324 return;
2325 }
2326 }
2327 }
2328
2329 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
2330 Index >= IList->getNumInits())
2331 return;
2332
2333 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
2334 TopLevelObject)) {
2335 hadError = true;
2336 ++Index;
2337 return;
2338 }
2339
2340 InitializedEntity MemberEntity =
2341 InitializedEntity::InitializeMember(*Field, &Entity);
2342
2343 if (isa<InitListExpr>(IList->getInit(Index)))
2344 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2345 StructuredList, StructuredIndex);
2346 else
2347 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
2348 StructuredList, StructuredIndex);
2349}
2350
2351/// Expand a field designator that refers to a member of an
2352/// anonymous struct or union into a series of field designators that
2353/// refers to the field within the appropriate subobject.
2354///
2355static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
2356 DesignatedInitExpr *DIE,
2357 unsigned DesigIdx,
2358 IndirectFieldDecl *IndirectField) {
2359 typedef DesignatedInitExpr::Designator Designator;
2360
2361 // Build the replacement designators.
2362 SmallVector<Designator, 4> Replacements;
2363 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2364 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2365 if (PI + 1 == PE)
2366 Replacements.push_back(Designator::CreateFieldDesignator(
2367 (IdentifierInfo *)nullptr, DIE->getDesignator(DesigIdx)->getDotLoc(),
2368 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2369 else
2370 Replacements.push_back(Designator::CreateFieldDesignator(
2371 (IdentifierInfo *)nullptr, SourceLocation(), SourceLocation()));
2372 assert(isa<FieldDecl>(*PI))(static_cast <bool> (isa<FieldDecl>(*PI)) ? void (
0) : __assert_fail ("isa<FieldDecl>(*PI)", "clang/lib/Sema/SemaInit.cpp"
, 2372, __extension__ __PRETTY_FUNCTION__))
;
2373 Replacements.back().setField(cast<FieldDecl>(*PI));
2374 }
2375
2376 // Expand the current designator into the set of replacement
2377 // designators, so we have a full subobject path down to where the
2378 // member of the anonymous struct/union is actually stored.
2379 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
2380 &Replacements[0] + Replacements.size());
2381}
2382
2383static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
2384 DesignatedInitExpr *DIE) {
2385 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2386 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2387 for (unsigned I = 0; I < NumIndexExprs; ++I)
2388 IndexExprs[I] = DIE->getSubExpr(I + 1);
2389 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2390 IndexExprs,
2391 DIE->getEqualOrColonLoc(),
2392 DIE->usesGNUSyntax(), DIE->getInit());
2393}
2394
2395namespace {
2396
2397// Callback to only accept typo corrections that are for field members of
2398// the given struct or union.
2399class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {
2400 public:
2401 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
2402 : Record(RD) {}
2403
2404 bool ValidateCandidate(const TypoCorrection &candidate) override {
2405 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2406 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2407 }
2408
2409 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2410 return std::make_unique<FieldInitializerValidatorCCC>(*this);
2411 }
2412
2413 private:
2414 RecordDecl *Record;
2415};
2416
2417} // end anonymous namespace
2418
2419/// Check the well-formedness of a C99 designated initializer.
2420///
2421/// Determines whether the designated initializer @p DIE, which
2422/// resides at the given @p Index within the initializer list @p
2423/// IList, is well-formed for a current object of type @p DeclType
2424/// (C99 6.7.8). The actual subobject that this designator refers to
2425/// within the current subobject is returned in either
2426/// @p NextField or @p NextElementIndex (whichever is appropriate).
2427///
2428/// @param IList The initializer list in which this designated
2429/// initializer occurs.
2430///
2431/// @param DIE The designated initializer expression.
2432///
2433/// @param DesigIdx The index of the current designator.
2434///
2435/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2436/// into which the designation in @p DIE should refer.
2437///
2438/// @param NextField If non-NULL and the first designator in @p DIE is
2439/// a field, this will be set to the field declaration corresponding
2440/// to the field named by the designator. On input, this is expected to be
2441/// the next field that would be initialized in the absence of designation,
2442/// if the complete object being initialized is a struct.
2443///
2444/// @param NextElementIndex If non-NULL and the first designator in @p
2445/// DIE is an array designator or GNU array-range designator, this
2446/// will be set to the last index initialized by this designator.
2447///
2448/// @param Index Index into @p IList where the designated initializer
2449/// @p DIE occurs.
2450///
2451/// @param StructuredList The initializer list expression that
2452/// describes all of the subobject initializers in the order they'll
2453/// actually be initialized.
2454///
2455/// @returns true if there was an error, false otherwise.
2456bool
2457InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2458 InitListExpr *IList,
2459 DesignatedInitExpr *DIE,
2460 unsigned DesigIdx,
2461 QualType &CurrentObjectType,
2462 RecordDecl::field_iterator *NextField,
2463 llvm::APSInt *NextElementIndex,
2464 unsigned &Index,
2465 InitListExpr *StructuredList,
2466 unsigned &StructuredIndex,
2467 bool FinishSubobjectInit,
2468 bool TopLevelObject) {
2469 if (DesigIdx == DIE->size()) {
1
Assuming the condition is false
2
Taking false branch
2470 // C++20 designated initialization can result in direct-list-initialization
2471 // of the designated subobject. This is the only way that we can end up
2472 // performing direct initialization as part of aggregate initialization, so
2473 // it needs special handling.
2474 if (DIE->isDirectInit()) {
2475 Expr *Init = DIE->getInit();
2476 assert(isa<InitListExpr>(Init) &&(static_cast <bool> (isa<InitListExpr>(Init) &&
"designator result in direct non-list initialization?") ? void
(0) : __assert_fail ("isa<InitListExpr>(Init) && \"designator result in direct non-list initialization?\""
, "clang/lib/Sema/SemaInit.cpp", 2477, __extension__ __PRETTY_FUNCTION__
))
2477 "designator result in direct non-list initialization?")(static_cast <bool> (isa<InitListExpr>(Init) &&
"designator result in direct non-list initialization?") ? void
(0) : __assert_fail ("isa<InitListExpr>(Init) && \"designator result in direct non-list initialization?\""
, "clang/lib/Sema/SemaInit.cpp", 2477, __extension__ __PRETTY_FUNCTION__
))
;
2478 InitializationKind Kind = InitializationKind::CreateDirectList(
2479 DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc());
2480 InitializationSequence Seq(SemaRef, Entity, Kind, Init,
2481 /*TopLevelOfInitList*/ true);
2482 if (StructuredList) {
2483 ExprResult Result = VerifyOnly
2484 ? getDummyInit()
2485 : Seq.Perform(SemaRef, Entity, Kind, Init);
2486 UpdateStructuredListElement(StructuredList, StructuredIndex,
2487 Result.get());
2488 }
2489 ++Index;
2490 return !Seq;
2491 }
2492
2493 // Check the actual initialization for the designated object type.
2494 bool prevHadError = hadError;
2495
2496 // Temporarily remove the designator expression from the
2497 // initializer list that the child calls see, so that we don't try
2498 // to re-process the designator.
2499 unsigned OldIndex = Index;
2500 IList->setInit(OldIndex, DIE->getInit());
2501
2502 CheckSubElementType(Entity, IList, CurrentObjectType, Index, StructuredList,
2503 StructuredIndex, /*DirectlyDesignated=*/true);
2504
2505 // Restore the designated initializer expression in the syntactic
2506 // form of the initializer list.
2507 if (IList->getInit(OldIndex) != DIE->getInit())
2508 DIE->setInit(IList->getInit(OldIndex));
2509 IList->setInit(OldIndex, DIE);
2510
2511 return hadError && !prevHadError;
2512 }
2513
2514 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
2515 bool IsFirstDesignator = (DesigIdx == 0);
3
Assuming 'DesigIdx' is equal to 0
2516 if (IsFirstDesignator
3.1
'IsFirstDesignator' is true
? FullyStructuredList : StructuredList
) {
4
'?' condition is true
5
Assuming pointer value is null
6
Taking false branch
2517 // Determine the structural initializer list that corresponds to the
2518 // current subobject.
2519 if (IsFirstDesignator)
2520 StructuredList = FullyStructuredList;
2521 else {
2522 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2523 StructuredList->getInit(StructuredIndex) : nullptr;
2524 if (!ExistingInit && StructuredList->hasArrayFiller())
2525 ExistingInit = StructuredList->getArrayFiller();
2526
2527 if (!ExistingInit)
2528 StructuredList = getStructuredSubobjectInit(
2529 IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
2530 SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
2531 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2532 StructuredList = Result;
2533 else {
2534 // We are creating an initializer list that initializes the
2535 // subobjects of the current object, but there was already an
2536 // initialization that completely initialized the current
2537 // subobject, e.g., by a compound literal:
2538 //
2539 // struct X { int a, b; };
2540 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2541 //
2542 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
2543 // designated initializer re-initializes only its current object
2544 // subobject [0].b.
2545 diagnoseInitOverride(ExistingInit,
2546 SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2547 /*FullyOverwritten=*/false);
2548
2549 if (!VerifyOnly) {
2550 if (DesignatedInitUpdateExpr *E =
2551 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2552 StructuredList = E->getUpdater();
2553 else {
2554 DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
2555 DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(),
2556 ExistingInit, DIE->getEndLoc());
2557 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2558 StructuredList = DIUE->getUpdater();
2559 }
2560 } else {
2561 // We don't need to track the structured representation of a
2562 // designated init update of an already-fully-initialized object in
2563 // verify-only mode. The only reason we would need the structure is
2564 // to determine where the uninitialized "holes" are, and in this
2565 // case, we know there aren't any and we can't introduce any.
2566 StructuredList = nullptr;
2567 }
2568 }
2569 }
2570 }
2571
2572 if (D->isFieldDesignator()) {
7
Taking false branch
2573 // C99 6.7.8p7:
2574 //
2575 // If a designator has the form
2576 //
2577 // . identifier
2578 //
2579 // then the current object (defined below) shall have
2580 // structure or union type and the identifier shall be the
2581 // name of a member of that type.
2582 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
2583 if (!RT) {
2584 SourceLocation Loc = D->getDotLoc();
2585 if (Loc.isInvalid())
2586 Loc = D->getFieldLoc();
2587 if (!VerifyOnly)
2588 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
2589 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2590 ++Index;
2591 return true;
2592 }
2593
2594 FieldDecl *KnownField = D->getField();
2595 if (!KnownField) {
2596 const IdentifierInfo *FieldName = D->getFieldName();
2597 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
2598 for (NamedDecl *ND : Lookup) {
2599 if (auto *FD = dyn_cast<FieldDecl>(ND)) {
2600 KnownField = FD;
2601 break;
2602 }
2603 if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
2604 // In verify mode, don't modify the original.
2605 if (VerifyOnly)
2606 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2607 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
2608 D = DIE->getDesignator(DesigIdx);
2609 KnownField = cast<FieldDecl>(*IFD->chain_begin());
2610 break;
2611 }
2612 }
2613 if (!KnownField) {
2614 if (VerifyOnly) {
2615 ++Index;
2616 return true; // No typo correction when just trying this out.
2617 }
2618
2619 // Name lookup found something, but it wasn't a field.
2620 if (!Lookup.empty()) {
2621 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2622 << FieldName;
2623 SemaRef.Diag(Lookup.front()->getLocation(),
2624 diag::note_field_designator_found);
2625 ++Index;
2626 return true;
2627 }
2628
2629 // Name lookup didn't find anything.
2630 // Determine whether this was a typo for another field name.
2631 FieldInitializerValidatorCCC CCC(RT->getDecl());
2632 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2633 DeclarationNameInfo(FieldName, D->getFieldLoc()),
2634 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC,
2635 Sema::CTK_ErrorRecovery, RT->getDecl())) {
2636 SemaRef.diagnoseTypo(
2637 Corrected,
2638 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
2639 << FieldName << CurrentObjectType);
2640 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
2641 hadError = true;
2642 } else {
2643 // Typo correction didn't find anything.
2644 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
2645 << FieldName << CurrentObjectType;
2646 ++Index;
2647 return true;
2648 }
2649 }
2650 }
2651
2652 unsigned NumBases = 0;
2653 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2654 NumBases = CXXRD->getNumBases();
2655
2656 unsigned FieldIndex = NumBases;
2657
2658 for (auto *FI : RT->getDecl()->fields()) {
2659 if (FI->isUnnamedBitfield())
2660 continue;
2661 if (declaresSameEntity(KnownField, FI)) {
2662 KnownField = FI;
2663 break;
2664 }
2665 ++FieldIndex;
2666 }
2667
2668 RecordDecl::field_iterator Field =
2669 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
2670
2671 // All of the fields of a union are located at the same place in
2672 // the initializer list.
2673 if (RT->getDecl()->isUnion()) {
2674 FieldIndex = 0;
2675 if (StructuredList) {
2676 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
2677 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
2678 assert(StructuredList->getNumInits() == 1(static_cast <bool> (StructuredList->getNumInits() ==
1 && "A union should never have more than one initializer!"
) ? void (0) : __assert_fail ("StructuredList->getNumInits() == 1 && \"A union should never have more than one initializer!\""
, "clang/lib/Sema/SemaInit.cpp", 2679, __extension__ __PRETTY_FUNCTION__
))
2679 && "A union should never have more than one initializer!")(static_cast <bool> (StructuredList->getNumInits() ==
1 && "A union should never have more than one initializer!"
) ? void (0) : __assert_fail ("StructuredList->getNumInits() == 1 && \"A union should never have more than one initializer!\""
, "clang/lib/Sema/SemaInit.cpp", 2679, __extension__ __PRETTY_FUNCTION__
))
;
2680
2681 Expr *ExistingInit = StructuredList->getInit(0);
2682 if (ExistingInit) {
2683 // We're about to throw away an initializer, emit warning.
2684 diagnoseInitOverride(
2685 ExistingInit, SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
2686 }
2687
2688 // remove existing initializer
2689 StructuredList->resizeInits(SemaRef.Context, 0);
2690 StructuredList->setInitializedFieldInUnion(nullptr);
2691 }
2692
2693 StructuredList->setInitializedFieldInUnion(*Field);
2694 }
2695 }
2696
2697 // Make sure we can use this declaration.
2698 bool InvalidUse;
2699 if (VerifyOnly)
2700 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2701 else
2702 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
2703 if (InvalidUse) {
2704 ++Index;
2705 return true;
2706 }
2707
2708 // C++20 [dcl.init.list]p3:
2709 // The ordered identifiers in the designators of the designated-
2710 // initializer-list shall form a subsequence of the ordered identifiers
2711 // in the direct non-static data members of T.
2712 //
2713 // Note that this is not a condition on forming the aggregate
2714 // initialization, only on actually performing initialization,
2715 // so it is not checked in VerifyOnly mode.
2716 //
2717 // FIXME: This is the only reordering diagnostic we produce, and it only
2718 // catches cases where we have a top-level field designator that jumps
2719 // backwards. This is the only such case that is reachable in an
2720 // otherwise-valid C++20 program, so is the only case that's required for
2721 // conformance, but for consistency, we should diagnose all the other
2722 // cases where a designator takes us backwards too.
2723 if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus &&
2724 NextField &&
2725 (*NextField == RT->getDecl()->field_end() ||
2726 (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) {
2727 // Find the field that we just initialized.
2728 FieldDecl *PrevField = nullptr;
2729 for (auto FI = RT->getDecl()->field_begin();
2730 FI != RT->getDecl()->field_end(); ++FI) {
2731 if (FI->isUnnamedBitfield())
2732 continue;
2733 if (*NextField != RT->getDecl()->field_end() &&
2734 declaresSameEntity(*FI, **NextField))
2735 break;
2736 PrevField = *FI;
2737 }
2738
2739 if (PrevField &&
2740 PrevField->getFieldIndex() > KnownField->getFieldIndex()) {
2741 SemaRef.Diag(DIE->getBeginLoc(), diag::ext_designated_init_reordered)
2742 << KnownField << PrevField << DIE->getSourceRange();
2743
2744 unsigned OldIndex = NumBases + PrevField->getFieldIndex();
2745 if (StructuredList && OldIndex <= StructuredList->getNumInits()) {
2746 if (Expr *PrevInit = StructuredList->getInit(OldIndex)) {
2747 SemaRef.Diag(PrevInit->getBeginLoc(),
2748 diag::note_previous_field_init)
2749 << PrevField << PrevInit->getSourceRange();
2750 }
2751 }
2752 }
2753 }
2754
2755
2756 // Update the designator with the field declaration.
2757 if (!VerifyOnly)
2758 D->setField(*Field);
2759
2760 // Make sure that our non-designated initializer list has space
2761 // for a subobject corresponding to this field.
2762 if (StructuredList && FieldIndex >= StructuredList->getNumInits())
2763 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2764
2765 // This designator names a flexible array member.
2766 if (Field->getType()->isIncompleteArrayType()) {
2767 bool Invalid = false;
2768 if ((DesigIdx + 1) != DIE->size()) {
2769 // We can't designate an object within the flexible array
2770 // member (because GCC doesn't allow it).
2771 if (!VerifyOnly) {
2772 DesignatedInitExpr::Designator *NextD
2773 = DIE->getDesignator(DesigIdx + 1);
2774 SemaRef.Diag(NextD->getBeginLoc(),
2775 diag::err_designator_into_flexible_array_member)
2776 << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
2777 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2778 << *Field;
2779 }
2780 Invalid = true;
2781 }
2782
2783 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2784 !isa<StringLiteral>(DIE->getInit())) {
2785 // The initializer is not an initializer list.
2786 if (!VerifyOnly) {
2787 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
2788 diag::err_flexible_array_init_needs_braces)
2789 << DIE->getInit()->getSourceRange();
2790 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2791 << *Field;
2792 }
2793 Invalid = true;
2794 }
2795
2796 // Check GNU flexible array initializer.
2797 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
2798 TopLevelObject))
2799 Invalid = true;
2800
2801 if (Invalid) {
2802 ++Index;
2803 return true;
2804 }
2805
2806 // Initialize the array.
2807 bool prevHadError = hadError;
2808 unsigned newStructuredIndex = FieldIndex;
2809 unsigned OldIndex = Index;
2810 IList->setInit(Index, DIE->getInit());
2811
2812 InitializedEntity MemberEntity =
2813 InitializedEntity::InitializeMember(*Field, &Entity);
2814 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2815 StructuredList, newStructuredIndex);
2816
2817 IList->setInit(OldIndex, DIE);
2818 if (hadError && !prevHadError) {
2819 ++Field;
2820 ++FieldIndex;
2821 if (NextField)
2822 *NextField = Field;
2823 StructuredIndex = FieldIndex;
2824 return true;
2825 }
2826 } else {
2827 // Recurse to check later designated subobjects.
2828 QualType FieldType = Field->getType();
2829 unsigned newStructuredIndex = FieldIndex;
2830
2831 InitializedEntity MemberEntity =
2832 InitializedEntity::InitializeMember(*Field, &Entity);
2833 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
2834 FieldType, nullptr, nullptr, Index,
2835 StructuredList, newStructuredIndex,
2836 FinishSubobjectInit, false))
2837 return true;
2838 }
2839
2840 // Find the position of the next field to be initialized in this
2841 // subobject.
2842 ++Field;
2843 ++FieldIndex;
2844
2845 // If this the first designator, our caller will continue checking
2846 // the rest of this struct/class/union subobject.
2847 if (IsFirstDesignator) {
2848 if (NextField)
2849 *NextField = Field;
2850 StructuredIndex = FieldIndex;
2851 return false;
2852 }
2853
2854 if (!FinishSubobjectInit)
2855 return false;
2856
2857 // We've already initialized something in the union; we're done.
2858 if (RT->getDecl()->isUnion())
2859 return hadError;
2860
2861 // Check the remaining fields within this class/struct/union subobject.
2862 bool prevHadError = hadError;
2863
2864 auto NoBases =
2865 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
2866 CXXRecordDecl::base_class_iterator());
2867 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
2868 false, Index, StructuredList, FieldIndex);
2869 return hadError && !prevHadError;
2870 }
2871
2872 // C99 6.7.8p6:
2873 //
2874 // If a designator has the form
2875 //
2876 // [ constant-expression ]
2877 //
2878 // then the current object (defined below) shall have array
2879 // type and the expression shall be an integer constant
2880 // expression. If the array is of unknown size, any
2881 // nonnegative value is valid.
2882 //
2883 // Additionally, cope with the GNU extension that permits
2884 // designators of the form
2885 //
2886 // [ constant-expression ... constant-expression ]
2887 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
2888 if (!AT) {
8
Assuming 'AT' is non-null
9
Taking false branch
2889 if (!VerifyOnly)
2890 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2891 << CurrentObjectType;
2892 ++Index;
2893 return true;
2894 }
2895
2896 Expr *IndexExpr = nullptr;
2897 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2898 if (D->isArrayDesignator()) {
2899 IndexExpr = DIE->getArrayIndex(*D);
2900 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
2901 DesignatedEndIndex = DesignatedStartIndex;
2902 } else {
2903 assert(D->isArrayRangeDesignator() && "Need array-range designator")(static_cast <bool> (D->isArrayRangeDesignator() &&
"Need array-range designator") ? void (0) : __assert_fail ("D->isArrayRangeDesignator() && \"Need array-range designator\""
, "clang/lib/Sema/SemaInit.cpp", 2903, __extension__ __PRETTY_FUNCTION__
))
;
10
Taking false branch
11
'?' condition is true
2904
2905 DesignatedStartIndex =
2906 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
2907 DesignatedEndIndex =
2908 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
2909 IndexExpr = DIE->getArrayRangeEnd(*D);
2910
2911 // Codegen can't handle evaluating array range designators that have side
2912 // effects, because we replicate the AST value for each initialized element.
2913 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2914 // elements with something that has a side effect, so codegen can emit an
2915 // "error unsupported" error instead of miscompiling the app.
2916 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
12
Assuming the condition is true
15
Taking true branch
2917 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
13
Assuming the condition is true
14
Assuming field 'VerifyOnly' is false
2918 FullyStructuredList->sawArrayRangeDesignator();
16
Called C++ object pointer is null
2919 }
2920
2921 if (isa<ConstantArrayType>(AT)) {
2922 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
2923 DesignatedStartIndex
2924 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
2925 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
2926 DesignatedEndIndex
2927 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
2928 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2929 if (DesignatedEndIndex >= MaxElements) {
2930 if (!VerifyOnly)
2931 SemaRef.Diag(IndexExpr->getBeginLoc(),
2932 diag::err_array_designator_too_large)
2933 << toString(DesignatedEndIndex, 10) << toString(MaxElements, 10)
2934 << IndexExpr->getSourceRange();
2935 ++Index;
2936 return true;
2937 }
2938 } else {
2939 unsigned DesignatedIndexBitWidth =
2940 ConstantArrayType::getMaxSizeBits(SemaRef.Context);
2941 DesignatedStartIndex =
2942 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
2943 DesignatedEndIndex =
2944 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
2945 DesignatedStartIndex.setIsUnsigned(true);
2946 DesignatedEndIndex.setIsUnsigned(true);
2947 }
2948
2949 bool IsStringLiteralInitUpdate =
2950 StructuredList && StructuredList->isStringLiteralInit();
2951 if (IsStringLiteralInitUpdate && VerifyOnly) {
2952 // We're just verifying an update to a string literal init. We don't need
2953 // to split the string up into individual characters to do that.
2954 StructuredList = nullptr;
2955 } else if (IsStringLiteralInitUpdate) {
2956 // We're modifying a string literal init; we have to decompose the string
2957 // so we can modify the individual characters.
2958 ASTContext &Context = SemaRef.Context;
2959 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParenImpCasts();
2960
2961 // Compute the character type
2962 QualType CharTy = AT->getElementType();
2963
2964 // Compute the type of the integer literals.
2965 QualType PromotedCharTy = CharTy;
2966 if (Context.isPromotableIntegerType(CharTy))
2967 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2968 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2969
2970 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2971 // Get the length of the string.
2972 uint64_t StrLen = SL->getLength();
2973 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2974 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2975 StructuredList->resizeInits(Context, StrLen);
2976
2977 // Build a literal for each character in the string, and put them into
2978 // the init list.
2979 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2980 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2981 Expr *Init = new (Context) IntegerLiteral(
2982 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2983 if (CharTy != PromotedCharTy)
2984 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2985 Init, nullptr, VK_PRValue,
2986 FPOptionsOverride());
2987 StructuredList->updateInit(Context, i, Init);
2988 }
2989 } else {
2990 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2991 std::string Str;
2992 Context.getObjCEncodingForType(E->getEncodedType(), Str);
2993
2994 // Get the length of the string.
2995 uint64_t StrLen = Str.size();
2996 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2997 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2998 StructuredList->resizeInits(Context, StrLen);
2999
3000 // Build a literal for each character in the string, and put them into
3001 // the init list.
3002 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3003 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
3004 Expr *Init = new (Context) IntegerLiteral(
3005 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3006 if (CharTy != PromotedCharTy)
3007 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3008 Init, nullptr, VK_PRValue,
3009 FPOptionsOverride());
3010 StructuredList->updateInit(Context, i, Init);
3011 }
3012 }
3013 }
3014
3015 // Make sure that our non-designated initializer list has space
3016 // for a subobject corresponding to this array element.
3017 if (StructuredList &&
3018 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
3019 StructuredList->resizeInits(SemaRef.Context,
3020 DesignatedEndIndex.getZExtValue() + 1);
3021
3022 // Repeatedly perform subobject initializations in the range
3023 // [DesignatedStartIndex, DesignatedEndIndex].
3024
3025 // Move to the next designator
3026 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
3027 unsigned OldIndex = Index;
3028
3029 InitializedEntity ElementEntity =
3030 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
3031
3032 while (DesignatedStartIndex <= DesignatedEndIndex) {
3033 // Recurse to check later designated subobjects.
3034 QualType ElementType = AT->getElementType();
3035 Index = OldIndex;
3036
3037 ElementEntity.setElementIndex(ElementIndex);
3038 if (CheckDesignatedInitializer(
3039 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
3040 nullptr, Index, StructuredList, ElementIndex,
3041 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
3042 false))
3043 return true;
3044
3045 // Move to the next index in the array that we'll be initializing.
3046 ++DesignatedStartIndex;
3047 ElementIndex = DesignatedStartIndex.getZExtValue();
3048 }
3049
3050 // If this the first designator, our caller will continue checking
3051 // the rest of this array subobject.
3052 if (IsFirstDesignator) {
3053 if (NextElementIndex)
3054 *NextElementIndex = DesignatedStartIndex;
3055 StructuredIndex = ElementIndex;
3056 return false;
3057 }
3058
3059 if (!FinishSubobjectInit)
3060 return false;
3061
3062 // Check the remaining elements within this array subobject.
3063 bool prevHadError = hadError;
3064 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
3065 /*SubobjectIsDesignatorContext=*/false, Index,
3066 StructuredList, ElementIndex);
3067 return hadError && !prevHadError;
3068}
3069
3070// Get the structured initializer list for a subobject of type
3071// @p CurrentObjectType.
3072InitListExpr *
3073InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
3074 QualType CurrentObjectType,
3075 InitListExpr *StructuredList,
3076 unsigned StructuredIndex,
3077 SourceRange InitRange,
3078 bool IsFullyOverwritten) {
3079 if (!StructuredList)
3080 return nullptr;
3081
3082 Expr *ExistingInit = nullptr;
3083 if (StructuredIndex < StructuredList->getNumInits())
3084 ExistingInit = StructuredList->getInit(StructuredIndex);
3085
3086 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
3087 // There might have already been initializers for subobjects of the current
3088 // object, but a subsequent initializer list will overwrite the entirety
3089 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
3090 //
3091 // struct P { char x[6]; };
3092 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
3093 //
3094 // The first designated initializer is ignored, and l.x is just "f".
3095 if (!IsFullyOverwritten)
3096 return Result;
3097
3098 if (ExistingInit) {
3099 // We are creating an initializer list that initializes the
3100 // subobjects of the current object, but there was already an
3101 // initialization that completely initialized the current
3102 // subobject:
3103 //
3104 // struct X { int a, b; };
3105 // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 };
3106 //
3107 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
3108 // designated initializer overwrites the [0].b initializer
3109 // from the prior initialization.
3110 //
3111 // When the existing initializer is an expression rather than an
3112 // initializer list, we cannot decompose and update it in this way.
3113 // For example:
3114 //
3115 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
3116 //
3117 // This case is handled by CheckDesignatedInitializer.
3118 diagnoseInitOverride(ExistingInit, InitRange);
3119 }
3120
3121 unsigned ExpectedNumInits = 0;
3122 if (Index < IList->getNumInits()) {
3123 if (auto *Init = dyn_cast_or_null<InitListExpr>(IList->getInit(Index)))
3124 ExpectedNumInits = Init->getNumInits();
3125 else
3126 ExpectedNumInits = IList->getNumInits() - Index;
3127 }
3128
3129 InitListExpr *Result =
3130 createInitListExpr(CurrentObjectType, InitRange, ExpectedNumInits);
3131
3132 // Link this new initializer list into the structured initializer
3133 // lists.
3134 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
3135 return Result;
3136}
3137
3138InitListExpr *
3139InitListChecker::createInitListExpr(QualType CurrentObjectType,
3140 SourceRange InitRange,
3141 unsigned ExpectedNumInits) {
3142 InitListExpr *Result = new (SemaRef.Context) InitListExpr(
3143 SemaRef.Context, InitRange.getBegin(), std::nullopt, InitRange.getEnd());
3144
3145 QualType ResultType = CurrentObjectType;
3146 if (!ResultType->isArrayType())
3147 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
3148 Result->setType(ResultType);
3149
3150 // Pre-allocate storage for the structured initializer list.
3151 unsigned NumElements = 0;
3152
3153 if (const ArrayType *AType
3154 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
3155 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
3156 NumElements = CAType->getSize().getZExtValue();
3157 // Simple heuristic so that we don't allocate a very large
3158 // initializer with many empty entries at the end.
3159 if (NumElements > ExpectedNumInits)
3160 NumElements = 0;
3161 }
3162 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) {
3163 NumElements = VType->getNumElements();
3164 } else if (CurrentObjectType->isRecordType()) {
3165 NumElements = numStructUnionElements(CurrentObjectType);
3166 }
3167
3168 Result->reserveInits(SemaRef.Context, NumElements);
3169
3170 return Result;
3171}
3172
3173/// Update the initializer at index @p StructuredIndex within the
3174/// structured initializer list to the value @p expr.
3175void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
3176 unsigned &StructuredIndex,
3177 Expr *expr) {
3178 // No structured initializer list to update
3179 if (!StructuredList)
3180 return;
3181
3182 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
3183 StructuredIndex, expr)) {
3184 // This initializer overwrites a previous initializer.
3185 // No need to diagnose when `expr` is nullptr because a more relevant
3186 // diagnostic has already been issued and this diagnostic is potentially
3187 // noise.
3188 if (expr)
3189 diagnoseInitOverride(PrevInit, expr->getSourceRange());
3190 }
3191
3192 ++StructuredIndex;
3193}
3194
3195/// Determine whether we can perform aggregate initialization for the purposes
3196/// of overload resolution.
3197bool Sema::CanPerformAggregateInitializationForOverloadResolution(
3198 const InitializedEntity &Entity, InitListExpr *From) {
3199 QualType Type = Entity.getType();
3200 InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true,
3201 /*TreatUnavailableAsInvalid=*/false,
3202 /*InOverloadResolution=*/true);
3203 return !Check.HadError();
3204}
3205
3206/// Check that the given Index expression is a valid array designator
3207/// value. This is essentially just a wrapper around
3208/// VerifyIntegerConstantExpression that also checks for negative values
3209/// and produces a reasonable diagnostic if there is a
3210/// failure. Returns the index expression, possibly with an implicit cast
3211/// added, on success. If everything went okay, Value will receive the
3212/// value of the constant expression.
3213static ExprResult
3214CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
3215 SourceLocation Loc = Index->getBeginLoc();
3216
3217 // Make sure this is an integer constant expression.
3218 ExprResult Result =
3219 S.VerifyIntegerConstantExpression(Index, &Value, Sema::AllowFold);
3220 if (Result.isInvalid())
3221 return Result;
3222
3223 if (Value.isSigned() && Value.isNegative())
3224 return S.Diag(Loc, diag::err_array_designator_negative)
3225 << toString(Value, 10) << Index->getSourceRange();
3226
3227 Value.setIsUnsigned(true);
3228 return Result;
3229}
3230
3231ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
3232 SourceLocation EqualOrColonLoc,
3233 bool GNUSyntax,
3234 ExprResult Init) {
3235 typedef DesignatedInitExpr::Designator ASTDesignator;
3236
3237 bool Invalid = false;
3238 SmallVector<ASTDesignator, 32> Designators;
3239 SmallVector<Expr *, 32> InitExpressions;
3240
3241 // Build designators and check array designator expressions.
3242 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
3243 const Designator &D = Desig.getDesignator(Idx);
3244
3245 if (D.isFieldDesignator()) {
3246 Designators.push_back(ASTDesignator::CreateFieldDesignator(
3247 D.getField(), D.getDotLoc(), D.getFieldLoc()));
3248 } else if (D.isArrayDesignator()) {
3249 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
3250 llvm::APSInt IndexValue;
3251 if (!Index->isTypeDependent() && !Index->isValueDependent())
3252 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
3253 if (!Index)
3254 Invalid = true;
3255 else {
3256 Designators.push_back(ASTDesignator::CreateArrayDesignator(
3257 InitExpressions.size(), D.getLBracketLoc(), D.getRBracketLoc()));
3258 InitExpressions.push_back(Index);
3259 }
3260 } else if (D.isArrayRangeDesignator()) {
3261 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
3262 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
3263 llvm::APSInt StartValue;
3264 llvm::APSInt EndValue;
3265 bool StartDependent = StartIndex->isTypeDependent() ||
3266 StartIndex->isValueDependent();
3267 bool EndDependent = EndIndex->isTypeDependent() ||
3268 EndIndex->isValueDependent();
3269 if (!StartDependent)
3270 StartIndex =
3271 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
3272 if (!EndDependent)
3273 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
3274
3275 if (!StartIndex || !EndIndex)
3276 Invalid = true;
3277 else {
3278 // Make sure we're comparing values with the same bit width.
3279 if (StartDependent || EndDependent) {
3280 // Nothing to compute.
3281 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
3282 EndValue = EndValue.extend(StartValue.getBitWidth());
3283 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
3284 StartValue = StartValue.extend(EndValue.getBitWidth());
3285
3286 if (!StartDependent && !EndDependent && EndValue < StartValue) {
3287 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
3288 << toString(StartValue, 10) << toString(EndValue, 10)
3289 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
3290 Invalid = true;
3291 } else {
3292 Designators.push_back(ASTDesignator::CreateArrayRangeDesignator(
3293 InitExpressions.size(), D.getLBracketLoc(), D.getEllipsisLoc(),
3294 D.getRBracketLoc()));
3295 InitExpressions.push_back(StartIndex);
3296 InitExpressions.push_back(EndIndex);
3297 }
3298 }
3299 }
3300 }
3301
3302 if (Invalid || Init.isInvalid())
3303 return ExprError();
3304
3305 return DesignatedInitExpr::Create(Context, Designators, InitExpressions,
3306 EqualOrColonLoc, GNUSyntax,
3307 Init.getAs<Expr>());
3308}
3309
3310//===----------------------------------------------------------------------===//
3311// Initialization entity
3312//===----------------------------------------------------------------------===//
3313
3314InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
3315 const InitializedEntity &Parent)
3316 : Parent(&Parent), Index(Index)
3317{
3318 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
3319 Kind = EK_ArrayElement;
3320 Type = AT->getElementType();
3321 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
3322 Kind = EK_VectorElement;
3323 Type = VT->getElementType();
3324 } else {
3325 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
3326 assert(CT && "Unexpected type")(static_cast <bool> (CT && "Unexpected type") ?
void (0) : __assert_fail ("CT && \"Unexpected type\""
, "clang/lib/Sema/SemaInit.cpp", 3326, __extension__ __PRETTY_FUNCTION__
))
;
3327 Kind = EK_ComplexElement;
3328 Type = CT->getElementType();
3329 }
3330}
3331
3332InitializedEntity
3333InitializedEntity::InitializeBase(ASTContext &Context,
3334 const CXXBaseSpecifier *Base,
3335 bool IsInheritedVirtualBase,
3336 const InitializedEntity *Parent) {
3337 InitializedEntity Result;
3338 Result.Kind = EK_Base;
3339 Result.Parent = Parent;
3340 Result.Base = {Base, IsInheritedVirtualBase};
3341 Result.Type = Base->getType();
3342 return Result;
3343}
3344
3345DeclarationName InitializedEntity::getName() const {
3346 switch (getKind()) {
3347 case EK_Parameter:
3348 case EK_Parameter_CF_Audited: {
3349 ParmVarDecl *D = Parameter.getPointer();
3350 return (D ? D->getDeclName() : DeclarationName());
3351 }
3352
3353 case EK_Variable:
3354 case EK_Member:
3355 case EK_Binding:
3356 case EK_TemplateParameter:
3357 return Variable.VariableOrMember->getDeclName();
3358
3359 case EK_LambdaCapture:
3360 return DeclarationName(Capture.VarID);
3361
3362 case EK_Result:
3363 case EK_StmtExprResult:
3364 case EK_Exception:
3365 case EK_New:
3366 case EK_Temporary:
3367 case EK_Base:
3368 case EK_Delegating:
3369 case EK_ArrayElement:
3370 case EK_VectorElement:
3371 case EK_ComplexElement:
3372 case EK_BlockElement:
3373 case EK_LambdaToBlockConversionBlockElement:
3374 case EK_CompoundLiteralInit:
3375 case EK_RelatedResult:
3376 return DeclarationName();
3377 }
3378
3379 llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "clang/lib/Sema/SemaInit.cpp"
, 3379)
;
3380}
3381
3382ValueDecl *InitializedEntity::getDecl() const {
3383 switch (getKind()) {
3384 case EK_Variable:
3385 case EK_Member:
3386 case EK_Binding:
3387 case EK_TemplateParameter:
3388 return Variable.VariableOrMember;
3389
3390 case EK_Parameter:
3391 case EK_Parameter_CF_Audited:
3392 return Parameter.getPointer();
3393
3394 case EK_Result:
3395 case EK_StmtExprResult:
3396 case EK_Exception:
3397 case EK_New:
3398 case EK_Temporary:
3399 case EK_Base:
3400 case EK_Delegating:
3401 case EK_ArrayElement:
3402 case EK_VectorElement:
3403 case EK_ComplexElement:
3404 case EK_BlockElement:
3405 case EK_LambdaToBlockConversionBlockElement:
3406 case EK_LambdaCapture:
3407 case EK_CompoundLiteralInit:
3408 case EK_RelatedResult:
3409 return nullptr;
3410 }
3411
3412 llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "clang/lib/Sema/SemaInit.cpp"
, 3412)
;
3413}
3414
3415bool InitializedEntity::allowsNRVO() const {
3416 switch (getKind()) {
3417 case EK_Result:
3418 case EK_Exception:
3419 return LocAndNRVO.NRVO;
3420
3421 case EK_StmtExprResult:
3422 case EK_Variable:
3423 case EK_Parameter:
3424 case EK_Parameter_CF_Audited:
3425 case EK_TemplateParameter:
3426 case EK_Member:
3427 case EK_Binding:
3428 case EK_New:
3429 case EK_Temporary:
3430 case EK_CompoundLiteralInit:
3431 case EK_Base:
3432 case EK_Delegating:
3433 case EK_ArrayElement:
3434 case EK_VectorElement:
3435 case EK_ComplexElement:
3436 case EK_BlockElement:
3437 case EK_LambdaToBlockConversionBlockElement:
3438 case EK_LambdaCapture:
3439 case EK_RelatedResult:
3440 break;
3441 }
3442
3443 return false;
3444}
3445
3446unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
3447 assert(getParent() != this)(static_cast <bool> (getParent() != this) ? void (0) : __assert_fail
("getParent() != this", "clang/lib/Sema/SemaInit.cpp", 3447,
__extension__ __PRETTY_FUNCTION__))
;
3448 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3449 for (unsigned I = 0; I != Depth; ++I)
3450 OS << "`-";
3451
3452 switch (getKind()) {
3453 case EK_Variable: OS << "Variable"; break;
3454 case EK_Parameter: OS << "Parameter"; break;
3455 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3456 break;
3457 case EK_TemplateParameter: OS << "TemplateParameter"; break;
3458 case EK_Result: OS << "Result"; break;
3459 case EK_StmtExprResult: OS << "StmtExprResult"; break;
3460 case EK_Exception: OS << "Exception"; break;
3461 case EK_Member: OS << "Member"; break;
3462 case EK_Binding: OS << "Binding"; break;
3463 case EK_New: OS << "New"; break;
3464 case EK_Temporary: OS << "Temporary"; break;
3465 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
3466 case EK_RelatedResult: OS << "RelatedResult"; break;
3467 case EK_Base: OS << "Base"; break;
3468 case EK_Delegating: OS << "Delegating"; break;
3469 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3470 case EK_VectorElement: OS << "VectorElement " << Index; break;
3471 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3472 case EK_BlockElement: OS << "Block"; break;
3473 case EK_LambdaToBlockConversionBlockElement:
3474 OS << "Block (lambda)";
3475 break;
3476 case EK_LambdaCapture:
3477 OS << "LambdaCapture ";
3478 OS << DeclarationName(Capture.VarID);
3479 break;
3480 }
3481
3482 if (auto *D = getDecl()) {
3483 OS << " ";
3484 D->printQualifiedName(OS);
3485 }
3486
3487 OS << " '" << getType() << "'\n";
3488
3489 return Depth + 1;
3490}
3491
3492LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void InitializedEntity::dump() const {
3493 dumpImpl(llvm::errs());
3494}
3495
3496//===----------------------------------------------------------------------===//
3497// Initialization sequence
3498//===----------------------------------------------------------------------===//
3499
3500void InitializationSequence::Step::Destroy() {
3501 switch (Kind) {
3502 case SK_ResolveAddressOfOverloadedFunction:
3503 case SK_CastDerivedToBasePRValue:
3504 case SK_CastDerivedToBaseXValue:
3505 case SK_CastDerivedToBaseLValue:
3506 case SK_BindReference:
3507 case SK_BindReferenceToTemporary:
3508 case SK_FinalCopy:
3509 case SK_ExtraneousCopyToTemporary:
3510 case SK_UserConversion:
3511 case SK_QualificationConversionPRValue:
3512 case SK_QualificationConversionXValue:
3513 case SK_QualificationConversionLValue:
3514 case SK_FunctionReferenceConversion:
3515 case SK_AtomicConversion:
3516 case SK_ListInitialization:
3517 case SK_UnwrapInitList:
3518 case SK_RewrapInitList:
3519 case SK_ConstructorInitialization:
3520 case SK_ConstructorInitializationFromList:
3521 case SK_ZeroInitialization:
3522 case SK_CAssignment:
3523 case SK_StringInit:
3524 case SK_ObjCObjectConversion:
3525 case SK_ArrayLoopIndex:
3526 case SK_ArrayLoopInit:
3527 case SK_ArrayInit:
3528 case SK_GNUArrayInit:
3529 case SK_ParenthesizedArrayInit:
3530 case SK_PassByIndirectCopyRestore:
3531 case SK_PassByIndirectRestore:
3532 case SK_ProduceObjCObject:
3533 case SK_StdInitializerList:
3534 case SK_StdInitializerListConstructorCall:
3535 case SK_OCLSamplerInit:
3536 case SK_OCLZeroOpaqueType:
3537 case SK_ParenthesizedListInit:
3538 break;
3539
3540 case SK_ConversionSequence:
3541 case SK_ConversionSequenceNoNarrowing:
3542 delete ICS;
3543 }
3544}
3545
3546bool InitializationSequence::isDirectReferenceBinding() const {
3547 // There can be some lvalue adjustments after the SK_BindReference step.
3548 for (const Step &S : llvm::reverse(Steps)) {
3549 if (S.Kind == SK_BindReference)
3550 return true;
3551 if (S.Kind == SK_BindReferenceToTemporary)
3552 return false;
3553 }
3554 return false;
3555}
3556
3557bool InitializationSequence::isAmbiguous() const {
3558 if (!Failed())
3559 return false;
3560
3561 switch (getFailureKind()) {
3562 case FK_TooManyInitsForReference:
3563 case FK_ParenthesizedListInitForReference:
3564 case FK_ArrayNeedsInitList:
3565 case FK_ArrayNeedsInitListOrStringLiteral:
3566 case FK_ArrayNeedsInitListOrWideStringLiteral:
3567 case FK_NarrowStringIntoWideCharArray:
3568 case FK_WideStringIntoCharArray:
3569 case FK_IncompatWideStringIntoWideChar:
3570 case FK_PlainStringIntoUTF8Char:
3571 case FK_UTF8StringIntoPlainChar:
3572 case FK_AddressOfOverloadFailed: // FIXME: Could do better
3573 case FK_NonConstLValueReferenceBindingToTemporary:
3574 case FK_NonConstLValueReferenceBindingToBitfield:
3575 case FK_NonConstLValueReferenceBindingToVectorElement:
3576 case FK_NonConstLValueReferenceBindingToMatrixElement:
3577 case FK_NonConstLValueReferenceBindingToUnrelated:
3578 case FK_RValueReferenceBindingToLValue:
3579 case FK_ReferenceAddrspaceMismatchTemporary:
3580 case FK_ReferenceInitDropsQualifiers:
3581 case FK_ReferenceInitFailed:
3582 case FK_ConversionFailed:
3583 case FK_ConversionFromPropertyFailed:
3584 case FK_TooManyInitsForScalar:
3585 case FK_ParenthesizedListInitForScalar:
3586 case FK_ReferenceBindingToInitList:
3587 case FK_InitListBadDestinationType:
3588 case FK_DefaultInitOfConst:
3589 case FK_Incomplete:
3590 case FK_ArrayTypeMismatch:
3591 case FK_NonConstantArrayInit:
3592 case FK_ListInitializationFailed:
3593 case FK_VariableLengthArrayHasInitializer:
3594 case FK_PlaceholderType:
3595 case FK_ExplicitConstructor:
3596 case FK_AddressOfUnaddressableFunction:
3597 case FK_ParenthesizedListInitFailed:
3598 return false;
3599
3600 case FK_ReferenceInitOverloadFailed:
3601 case FK_UserConversionOverloadFailed:
3602 case FK_ConstructorOverloadFailed:
3603 case FK_ListConstructorOverloadFailed:
3604 return FailedOverloadResult == OR_Ambiguous;
3605 }
3606
3607 llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "clang/lib/Sema/SemaInit.cpp"
, 3607)
;
3608}
3609
3610bool InitializationSequence::isConstructorInitialization() const {
3611 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3612}
3613
3614void
3615InitializationSequence
3616::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3617 DeclAccessPair Found,
3618 bool HadMultipleCandidates) {
3619 Step S;
3620 S.Kind = SK_ResolveAddressOfOverloadedFunction;
3621 S.Type = Function->getType();
3622 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3623 S.Function.Function = Function;
3624 S.Function.FoundDecl = Found;
3625 Steps.push_back(S);
3626}
3627
3628void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
3629 ExprValueKind VK) {
3630 Step S;
3631 switch (VK) {
3632 case VK_PRValue:
3633 S.Kind = SK_CastDerivedToBasePRValue;
3634 break;
3635 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3636 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
3637 }
3638 S.Type = BaseType;
3639 Steps.push_back(S);
3640}
3641
3642void InitializationSequence::AddReferenceBindingStep(QualType T,
3643 bool BindingTemporary) {
3644 Step S;
3645 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3646 S.Type = T;
3647 Steps.push_back(S);
3648}
3649
3650void InitializationSequence::AddFinalCopy(QualType T) {
3651 Step S;
3652 S.Kind = SK_FinalCopy;
3653 S.Type = T;
3654 Steps.push_back(S);
3655}
3656
3657void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
3658 Step S;
3659 S.Kind = SK_ExtraneousCopyToTemporary;
3660 S.Type = T;
3661 Steps.push_back(S);
3662}
3663
3664void
3665InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
3666 DeclAccessPair FoundDecl,
3667 QualType T,
3668 bool HadMultipleCandidates) {
3669 Step S;
3670 S.Kind = SK_UserConversion;
3671 S.Type = T;
3672 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3673 S.Function.Function = Function;
3674 S.Function.FoundDecl = FoundDecl;
3675 Steps.push_back(S);
3676}
3677
3678void InitializationSequence::AddQualificationConversionStep(QualType Ty,
3679 ExprValueKind VK) {
3680 Step S;
3681 S.Kind = SK_QualificationConversionPRValue; // work around a gcc warning
3682 switch (VK) {
3683 case VK_PRValue:
3684 S.Kind = SK_QualificationConversionPRValue;
3685 break;
3686 case VK_XValue:
3687 S.Kind = SK_QualificationConversionXValue;
3688 break;
3689 case VK_LValue:
3690 S.Kind = SK_QualificationConversionLValue;
3691 break;
3692 }
3693 S.Type = Ty;
3694 Steps.push_back(S);
3695}
3696
3697void InitializationSequence::AddFunctionReferenceConversionStep(QualType Ty) {
3698 Step S;
3699 S.Kind = SK_FunctionReferenceConversion;
3700 S.Type = Ty;
3701 Steps.push_back(S);
3702}
3703
3704void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
3705 Step S;
3706 S.Kind = SK_AtomicConversion;
3707 S.Type = Ty;
3708 Steps.push_back(S);
3709}
3710
3711void InitializationSequence::AddConversionSequenceStep(
3712 const ImplicitConversionSequence &ICS, QualType T,
3713 bool TopLevelOfInitList) {
3714 Step S;
3715 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3716 : SK_ConversionSequence;
3717 S.Type = T;
3718 S.ICS = new ImplicitConversionSequence(ICS);
3719 Steps.push_back(S);
3720}
3721
3722void InitializationSequence::AddListInitializationStep(QualType T) {
3723 Step S;
3724 S.Kind = SK_ListInitialization;
3725 S.Type = T;
3726 Steps.push_back(S);
3727}
3728
3729void InitializationSequence::AddConstructorInitializationStep(
3730 DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3731 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
3732 Step S;
3733 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
3734 : SK_ConstructorInitializationFromList
3735 : SK_ConstructorInitialization;
3736 S.Type = T;
3737 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3738 S.Function.Function = Constructor;
3739 S.Function.FoundDecl = FoundDecl;
3740 Steps.push_back(S);
3741}
3742
3743void InitializationSequence::AddZeroInitializationStep(QualType T) {
3744 Step S;
3745 S.Kind = SK_ZeroInitialization;
3746 S.Type = T;
3747 Steps.push_back(S);
3748}
3749
3750void InitializationSequence::AddCAssignmentStep(QualType T) {
3751 Step S;
3752 S.Kind = SK_CAssignment;
3753 S.Type = T;
3754 Steps.push_back(S);
3755}
3756
3757void InitializationSequence::AddStringInitStep(QualType T) {
3758 Step S;
3759 S.Kind = SK_StringInit;
3760 S.Type = T;
3761 Steps.push_back(S);
3762}
3763
3764void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
3765 Step S;
3766 S.Kind = SK_ObjCObjectConversion;
3767 S.Type = T;
3768 Steps.push_back(S);
3769}
3770
3771void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) {
3772 Step S;
3773 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
3774 S.Type = T;
3775 Steps.push_back(S);
3776}
3777
3778void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) {
3779 Step S;
3780 S.Kind = SK_ArrayLoopIndex;
3781 S.Type = EltT;
3782 Steps.insert(Steps.begin(), S);
3783
3784 S.Kind = SK_ArrayLoopInit;
3785 S.Type = T;
3786 Steps.push_back(S);
3787}
3788
3789void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
3790 Step S;
3791 S.Kind = SK_ParenthesizedArrayInit;
3792 S.Type = T;
3793 Steps.push_back(S);
3794}
3795
3796void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
3797 bool shouldCopy) {
3798 Step s;
3799 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3800 : SK_PassByIndirectRestore);
3801 s.Type = type;
3802 Steps.push_back(s);
3803}
3804
3805void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3806 Step S;
3807 S.Kind = SK_ProduceObjCObject;
3808 S.Type = T;
3809 Steps.push_back(S);
3810}
3811
3812void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3813 Step S;
3814 S.Kind = SK_StdInitializerList;
3815 S.Type = T;
3816 Steps.push_back(S);
3817}
3818
3819void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3820 Step S;
3821 S.Kind = SK_OCLSamplerInit;
3822 S.Type = T;
3823 Steps.push_back(S);
3824}
3825
3826void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T) {
3827 Step S;
3828 S.Kind = SK_OCLZeroOpaqueType;
3829 S.Type = T;
3830 Steps.push_back(S);
3831}
3832
3833void InitializationSequence::AddParenthesizedListInitStep(QualType T) {
3834 Step S;
3835 S.Kind = SK_ParenthesizedListInit;
3836 S.Type = T;
3837 Steps.push_back(S);
3838}
3839
3840void InitializationSequence::RewrapReferenceInitList(QualType T,
3841 InitListExpr *Syntactic) {
3842 assert(Syntactic->getNumInits() == 1 &&(static_cast <bool> (Syntactic->getNumInits() == 1 &&
"Can only rewrap trivial init lists.") ? void (0) : __assert_fail
("Syntactic->getNumInits() == 1 && \"Can only rewrap trivial init lists.\""
, "clang/lib/Sema/SemaInit.cpp", 3843, __extension__ __PRETTY_FUNCTION__
))
3843 "Can only rewrap trivial init lists.")(static_cast <bool> (Syntactic->getNumInits() == 1 &&
"Can only rewrap trivial init lists.") ? void (0) : __assert_fail
("Syntactic->getNumInits() == 1 && \"Can only rewrap trivial init lists.\""
, "clang/lib/Sema/SemaInit.cpp", 3843, __extension__ __PRETTY_FUNCTION__
))
;
3844 Step S;
3845 S.Kind = SK_UnwrapInitList;
3846 S.Type = Syntactic->getInit(0)->getType();
3847 Steps.insert(Steps.begin(), S);
3848
3849 S.Kind = SK_RewrapInitList;
3850 S.Type = T;
3851 S.WrappingSyntacticList = Syntactic;
3852 Steps.push_back(S);
3853}
3854
3855void InitializationSequence::SetOverloadFailure(FailureKind Failure,
3856 OverloadingResult Result) {
3857 setSequenceKind(FailedSequence);
3858 this->Failure = Failure;
3859 this->FailedOverloadResult = Result;
3860}
3861
3862//===----------------------------------------------------------------------===//
3863// Attempt initialization
3864//===----------------------------------------------------------------------===//
3865
3866/// Tries to add a zero initializer. Returns true if that worked.
3867static bool
3868maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
3869 const InitializedEntity &Entity) {
3870 if (Entity.getKind() != InitializedEntity::EK_Variable)
3871 return false;
3872
3873 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
3874 if (VD->getInit() || VD->getEndLoc().isMacroID())
3875 return false;
3876
3877 QualType VariableTy = VD->getType().getCanonicalType();
3878 SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc());
3879 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
3880 if (!Init.empty()) {
3881 Sequence.AddZeroInitializationStep(Entity.getType());
3882 Sequence.SetZeroInitializationFixit(Init, Loc);
3883 return true;
3884 }
3885 return false;
3886}
3887
3888static void MaybeProduceObjCObject(Sema &S,
3889 InitializationSequence &Sequence,
3890 const InitializedEntity &Entity) {
3891 if (!S.getLangOpts().ObjCAutoRefCount) return;
3892
3893 /// When initializing a parameter, produce the value if it's marked
3894 /// __attribute__((ns_consumed)).
3895 if (Entity.isParameterKind()) {
3896 if (!Entity.isParameterConsumed())
3897 return;
3898
3899 assert(Entity.getType()->isObjCRetainableType() &&(static_cast <bool> (Entity.getType()->isObjCRetainableType
() && "consuming an object of unretainable type?") ? void
(0) : __assert_fail ("Entity.getType()->isObjCRetainableType() && \"consuming an object of unretainable type?\""
, "clang/lib/Sema/SemaInit.cpp", 3900, __extension__ __PRETTY_FUNCTION__
))
3900 "consuming an object of unretainable type?")(static_cast <bool> (Entity.getType()->isObjCRetainableType
() && "consuming an object of unretainable type?") ? void
(0) : __assert_fail ("Entity.getType()->isObjCRetainableType() && \"consuming an object of unretainable type?\""
, "clang/lib/Sema/SemaInit.cpp", 3900, __extension__ __PRETTY_FUNCTION__
))
;
3901 Sequence.AddProduceObjCObjectStep(Entity.getType());
3902
3903 /// When initializing a return value, if the return type is a
3904 /// retainable type, then returns need to immediately retain the
3905 /// object. If an autorelease is required, it will be done at the
3906 /// last instant.
3907 } else if (Entity.getKind() == InitializedEntity::EK_Result ||
3908 Entity.getKind() == InitializedEntity::EK_StmtExprResult) {
3909 if (!Entity.getType()->isObjCRetainableType())
3910 return;
3911
3912 Sequence.AddProduceObjCObjectStep(Entity.getType());
3913 }
3914}
3915
3916static void TryListInitialization(Sema &S,
3917 const InitializedEntity &Entity,
3918 const InitializationKind &Kind,
3919 InitListExpr *InitList,
3920 InitializationSequence &Sequence,
3921 bool TreatUnavailableAsInvalid);
3922
3923/// When initializing from init list via constructor, handle
3924/// initialization of an object of type std::initializer_list<T>.
3925///
3926/// \return true if we have handled initialization of an object of type
3927/// std::initializer_list<T>, false otherwise.
3928static bool TryInitializerListConstruction(Sema &S,
3929 InitListExpr *List,
3930 QualType DestType,
3931 InitializationSequence &Sequence,
3932 bool TreatUnavailableAsInvalid) {
3933 QualType E;
3934 if (!S.isStdInitializerList(DestType, &E))
3935 return false;
3936
3937 if (!S.isCompleteType(List->getExprLoc(), E)) {
3938 Sequence.setIncompleteTypeFailure(E);
3939 return true;
3940 }
3941
3942 // Try initializing a temporary array from the init list.
3943 QualType ArrayType = S.Context.getConstantArrayType(
3944 E.withConst(),
3945 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3946 List->getNumInits()),
3947 nullptr, clang::ArrayType::Normal, 0);
3948 InitializedEntity HiddenArray =
3949 InitializedEntity::InitializeTemporary(ArrayType);
3950 InitializationKind Kind = InitializationKind::CreateDirectList(
3951 List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
3952 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
3953 TreatUnavailableAsInvalid);
3954 if (Sequence)
3955 Sequence.AddStdInitializerListConstructionStep(DestType);
3956 return true;
3957}
3958
3959/// Determine if the constructor has the signature of a copy or move
3960/// constructor for the type T of the class in which it was found. That is,
3961/// determine if its first parameter is of type T or reference to (possibly
3962/// cv-qualified) T.
3963static bool hasCopyOrMoveCtorParam(ASTContext &Ctx,
3964 const ConstructorInfo &Info) {
3965 if (Info.Constructor->getNumParams() == 0)
3966 return false;
3967
3968 QualType ParmT =
3969 Info.Constructor->getParamDecl(0)->getType().getNonReferenceType();
3970 QualType ClassT =
3971 Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
3972
3973 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
3974}
3975
3976static OverloadingResult
3977ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
3978 MultiExprArg Args,
3979 OverloadCandidateSet &CandidateSet,
3980 QualType DestType,
3981 DeclContext::lookup_result Ctors,
3982 OverloadCandidateSet::iterator &Best,
3983 bool CopyInitializing, bool AllowExplicit,
3984 bool OnlyListConstructors, bool IsListInit,
3985 bool SecondStepOfCopyInit = false) {
3986 CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor);
3987 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
3988
3989 for (NamedDecl *D : Ctors) {
3990 auto Info = getConstructorInfo(D);
3991 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
3992 continue;
3993
3994 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
3995 continue;
3996
3997 // C++11 [over.best.ics]p4:
3998 // ... and the constructor or user-defined conversion function is a
3999 // candidate by
4000 // - 13.3.1.3, when the argument is the temporary in the second step
4001 // of a class copy-initialization, or
4002 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
4003 // - the second phase of 13.3.1.7 when the initializer list has exactly
4004 // one element that is itself an initializer list, and the target is
4005 // the first parameter of a constructor of class X, and the conversion
4006 // is to X or reference to (possibly cv-qualified X),
4007 // user-defined conversion sequences are not considered.
4008 bool SuppressUserConversions =
4009 SecondStepOfCopyInit ||
4010 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
4011 hasCopyOrMoveCtorParam(S.Context, Info));
4012
4013 if (Info.ConstructorTmpl)
4014 S.AddTemplateOverloadCandidate(
4015 Info.ConstructorTmpl, Info.FoundDecl,
4016 /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions,
4017 /*PartialOverloading=*/false, AllowExplicit);
4018 else {
4019 // C++ [over.match.copy]p1:
4020 // - When initializing a temporary to be bound to the first parameter
4021 // of a constructor [for type T] that takes a reference to possibly
4022 // cv-qualified T as its first argument, called with a single
4023 // argument in the context of direct-initialization, explicit
4024 // conversion functions are also considered.
4025 // FIXME: What if a constructor template instantiates to such a signature?
4026 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
4027 Args.size() == 1 &&
4028 hasCopyOrMoveCtorParam(S.Context, Info);
4029 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
4030 CandidateSet, SuppressUserConversions,
4031 /*PartialOverloading=*/false, AllowExplicit,
4032 AllowExplicitConv);
4033 }
4034 }
4035
4036 // FIXME: Work around a bug in C++17 guaranteed copy elision.
4037 //
4038 // When initializing an object of class type T by constructor
4039 // ([over.match.ctor]) or by list-initialization ([over.match.list])
4040 // from a single expression of class type U, conversion functions of
4041 // U that convert to the non-reference type cv T are candidates.
4042 // Explicit conversion functions are only candidates during
4043 // direct-initialization.
4044 //
4045 // Note: SecondStepOfCopyInit is only ever true in this case when
4046 // evaluating whether to produce a C++98 compatibility warning.
4047 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
4048 !SecondStepOfCopyInit) {
4049 Expr *Initializer = Args[0];
4050 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
4051 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
4052 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
4053 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4054 NamedDecl *D = *I;
4055 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4056 D = D->getUnderlyingDecl();
4057
4058 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4059 CXXConversionDecl *Conv;
4060 if (ConvTemplate)
4061 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4062 else
4063 Conv = cast<CXXConversionDecl>(D);
4064
4065 if (ConvTemplate)
4066 S.AddTemplateConversionCandidate(
4067 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4068 CandidateSet, AllowExplicit, AllowExplicit,
4069 /*AllowResultConversion*/ false);
4070 else
4071 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
4072 DestType, CandidateSet, AllowExplicit,
4073 AllowExplicit,
4074 /*AllowResultConversion*/ false);
4075 }
4076 }
4077 }
4078
4079 // Perform overload resolution and return the result.
4080 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
4081}
4082
4083/// Attempt initialization by constructor (C++ [dcl.init]), which
4084/// enumerates the constructors of the initialized entity and performs overload
4085/// resolution to select the best.
4086/// \param DestType The destination class type.
4087/// \param DestArrayType The destination type, which is either DestType or
4088/// a (possibly multidimensional) array of DestType.
4089/// \param IsListInit Is this list-initialization?
4090/// \param IsInitListCopy Is this non-list-initialization resulting from a
4091/// list-initialization from {x} where x is the same
4092/// type as the entity?
4093static void TryConstructorInitialization(Sema &S,
4094 const InitializedEntity &Entity,
4095 const InitializationKind &Kind,
4096 MultiExprArg Args, QualType DestType,
4097 QualType DestArrayType,
4098 InitializationSequence &Sequence,
4099 bool IsListInit = false,
4100 bool IsInitListCopy = false) {
4101 assert(((!IsListInit && !IsInitListCopy) ||(static_cast <bool> (((!IsListInit && !IsInitListCopy
) || (Args.size() == 1 && isa<InitListExpr>(Args
[0]))) && "IsListInit/IsInitListCopy must come with a single initializer list "
"argument.") ? void (0) : __assert_fail ("((!IsListInit && !IsInitListCopy) || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && \"IsListInit/IsInitListCopy must come with a single initializer list \" \"argument.\""
, "clang/lib/Sema/SemaInit.cpp", 4104, __extension__ __PRETTY_FUNCTION__
))
4102 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&(static_cast <bool> (((!IsListInit && !IsInitListCopy
) || (Args.size() == 1 && isa<InitListExpr>(Args
[0]))) && "IsListInit/IsInitListCopy must come with a single initializer list "
"argument.") ? void (0) : __assert_fail ("((!IsListInit && !IsInitListCopy) || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && \"IsListInit/IsInitListCopy must come with a single initializer list \" \"argument.\""
, "clang/lib/Sema/SemaInit.cpp", 4104, __extension__ __PRETTY_FUNCTION__
))
4103 "IsListInit/IsInitListCopy must come with a single initializer list "(static_cast <bool> (((!IsListInit && !IsInitListCopy
) || (Args.size() == 1 && isa<InitListExpr>(Args
[0]))) && "IsListInit/IsInitListCopy must come with a single initializer list "
"argument.") ? void (0) : __assert_fail ("((!IsListInit && !IsInitListCopy) || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && \"IsListInit/IsInitListCopy must come with a single initializer list \" \"argument.\""
, "clang/lib/Sema/SemaInit.cpp", 4104, __extension__ __PRETTY_FUNCTION__
))
4104 "argument.")(static_cast <bool> (((!IsListInit && !IsInitListCopy
) || (Args.size() == 1 && isa<InitListExpr>(Args
[0]))) && "IsListInit/IsInitListCopy must come with a single initializer list "
"argument.") ? void (0) : __assert_fail ("((!IsListInit && !IsInitListCopy) || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && \"IsListInit/IsInitListCopy must come with a single initializer list \" \"argument.\""
, "clang/lib/Sema/SemaInit.cpp", 4104, __extension__ __PRETTY_FUNCTION__
))
;
4105 InitListExpr *ILE =
4106 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
4107 MultiExprArg UnwrappedArgs =
4108 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
4109
4110 // The type we're constructing needs to be complete.
4111 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
4112 Sequence.setIncompleteTypeFailure(DestType);
4113 return;
4114 }
4115
4116 // C++17 [dcl.init]p17:
4117 // - If the initializer expression is a prvalue and the cv-unqualified
4118 // version of the source type is the same class as the class of the
4119 // destination, the initializer expression is used to initialize the
4120 // destination object.
4121 // Per DR (no number yet), this does not apply when initializing a base
4122 // class or delegating to another constructor from a mem-initializer.
4123 // ObjC++: Lambda captured by the block in the lambda to block conversion
4124 // should avoid copy elision.
4125 if (S.getLangOpts().CPlusPlus17 &&
4126 Entity.getKind() != InitializedEntity::EK_Base &&
4127 Entity.getKind() != InitializedEntity::EK_Delegating &&
4128 Entity.getKind() !=
4129 InitializedEntity::EK_LambdaToBlockConversionBlockElement &&
4130 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() &&
4131 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
4132 // Convert qualifications if necessary.
4133 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4134 if (ILE)
4135 Sequence.RewrapReferenceInitList(DestType, ILE);
4136 return;
4137 }
4138
4139 const RecordType *DestRecordType = DestType->getAs<RecordType>();
4140 assert(DestRecordType && "Constructor initialization requires record type")(static_cast <bool> (DestRecordType && "Constructor initialization requires record type"
) ? void (0) : __assert_fail ("DestRecordType && \"Constructor initialization requires record type\""
, "clang/lib/Sema/SemaInit.cpp", 4140, __extension__ __PRETTY_FUNCTION__
))
;
4141 CXXRecordDecl *DestRecordDecl
4142 = cast<CXXRecordDecl>(DestRecordType->getDecl());
4143
4144 // Build the candidate set directly in the initialization sequence
4145 // structure, so that it will persist if we fail.
4146 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4147
4148 // Determine whether we are allowed to call explicit constructors or
4149 // explicit conversion operators.
4150 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
4151 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
4152
4153 // - Otherwise, if T is a class type, constructors are considered. The
4154 // applicable constructors are enumerated, and the best one is chosen
4155 // through overload resolution.
4156 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
4157
4158 OverloadingResult Result = OR_No_Viable_Function;
4159 OverloadCandidateSet::iterator Best;
4160 bool AsInitializerList = false;
4161
4162 // C++11 [over.match.list]p1, per DR1467:
4163 // When objects of non-aggregate type T are list-initialized, such that
4164 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
4165 // according to the rules in this section, overload resolution selects
4166 // the constructor in two phases:
4167 //
4168 // - Initially, the candidate functions are the initializer-list
4169 // constructors of the class T and the argument list consists of the
4170 // initializer list as a single argument.
4171 if (IsListInit) {
4172 AsInitializerList = true;
4173
4174 // If the initializer list has no elements and T has a default constructor,
4175 // the first phase is omitted.
4176 if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(DestRecordDecl)))
4177 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
4178 CandidateSet, DestType, Ctors, Best,
4179 CopyInitialization, AllowExplicit,
4180 /*OnlyListConstructors=*/true,
4181 IsListInit);
4182 }
4183
4184 // C++11 [over.match.list]p1:
4185 // - If no viable initializer-list constructor is found, overload resolution
4186 // is performed again, where the candidate functions are all the
4187 // constructors of the class T and the argument list consists of the
4188 // elements of the initializer list.
4189 if (Result == OR_No_Viable_Function) {
4190 AsInitializerList = false;
4191 Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs,
4192 CandidateSet, DestType, Ctors, Best,
4193 CopyInitialization, AllowExplicit,
4194 /*OnlyListConstructors=*/false,
4195 IsListInit);
4196 }
4197 if (Result) {
4198 Sequence.SetOverloadFailure(
4199 IsListInit ? InitializationSequence::FK_ListConstructorOverloadFailed
4200 : InitializationSequence::FK_ConstructorOverloadFailed,
4201 Result);
4202
4203 if (Result != OR_Deleted)
4204 return;
4205 }
4206
4207 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4208
4209 // In C++17, ResolveConstructorOverload can select a conversion function
4210 // instead of a constructor.
4211 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
4212 // Add the user-defined conversion step that calls the conversion function.
4213 QualType ConvType = CD->getConversionType();
4214 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&(static_cast <bool> (S.Context.hasSameUnqualifiedType(ConvType
, DestType) && "should not have selected this conversion function"
) ? void (0) : __assert_fail ("S.Context.hasSameUnqualifiedType(ConvType, DestType) && \"should not have selected this conversion function\""
, "clang/lib/Sema/SemaInit.cpp", 4215, __extension__ __PRETTY_FUNCTION__
))
4215 "should not have selected this conversion function")(static_cast <bool> (S.Context.hasSameUnqualifiedType(ConvType
, DestType) && "should not have selected this conversion function"
) ? void (0) : __assert_fail ("S.Context.hasSameUnqualifiedType(ConvType, DestType) && \"should not have selected this conversion function\""
, "clang/lib/Sema/SemaInit.cpp", 4215, __extension__ __PRETTY_FUNCTION__
))
;
4216 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
4217 HadMultipleCandidates);
4218 if (!S.Context.hasSameType(ConvType, DestType))
4219 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4220 if (IsListInit)
4221 Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
4222 return;
4223 }
4224
4225 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
4226 if (Result != OR_Deleted) {
4227 // C++11 [dcl.init]p6:
4228 // If a program calls for the default initialization of an object
4229 // of a const-qualified type T, T shall be a class type with a
4230 // user-provided default constructor.
4231 // C++ core issue 253 proposal:
4232 // If the implicit default constructor initializes all subobjects, no
4233 // initializer should be required.
4234 // The 253 proposal is for example needed to process libstdc++ headers
4235 // in 5.x.
4236 if (Kind.getKind() == InitializationKind::IK_Default &&
4237 Entity.getType().isConstQualified()) {
4238 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
4239 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4240 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
4241 return;
4242 }
4243 }
4244
4245 // C++11 [over.match.list]p1:
4246 // In copy-list-initialization, if an explicit constructor is chosen, the
4247 // initializer is ill-formed.
4248 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
4249 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
4250 return;
4251 }
4252 }
4253
4254 // [class.copy.elision]p3:
4255 // In some copy-initialization contexts, a two-stage overload resolution
4256 // is performed.
4257 // If the first overload resolution selects a deleted function, we also
4258 // need the initialization sequence to decide whether to perform the second
4259 // overload resolution.
4260 // For deleted functions in other contexts, there is no need to get the
4261 // initialization sequence.
4262 if (Result == OR_Deleted && Kind.getKind() != InitializationKind::IK_Copy)
4263 return;
4264
4265 // Add the constructor initialization step. Any cv-qualification conversion is
4266 // subsumed by the initialization.
4267 Sequence.AddConstructorInitializationStep(
4268 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
4269 IsListInit | IsInitListCopy, AsInitializerList);
4270}
4271
4272static bool
4273ResolveOverloadedFunctionForReferenceBinding(Sema &S,
4274 Expr *Initializer,
4275 QualType &SourceType,
4276 QualType &UnqualifiedSourceType,
4277 QualType UnqualifiedTargetType,
4278 InitializationSequence &Sequence) {
4279 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
4280 S.Context.OverloadTy) {
4281 DeclAccessPair Found;
4282 bool HadMultipleCandidates = false;
4283 if (FunctionDecl *Fn
4284 = S.ResolveAddressOfOverloadedFunction(Initializer,
4285 UnqualifiedTargetType,
4286 false, Found,
4287 &HadMultipleCandidates)) {
4288 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
4289 HadMultipleCandidates);
4290 SourceType = Fn->getType();
4291 UnqualifiedSourceType = SourceType.getUnqualifiedType();
4292 } else if (!UnqualifiedTargetType->isRecordType()) {
4293 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4294 return true;
4295 }
4296 }
4297 return false;
4298}
4299
4300static void TryReferenceInitializationCore(Sema &S,
4301 const InitializedEntity &Entity,
4302 const InitializationKind &Kind,
4303 Expr *Initializer,
4304 QualType cv1T1, QualType T1,
4305 Qualifiers T1Quals,
4306 QualType cv2T2, QualType T2,
4307 Qualifiers T2Quals,
4308 InitializationSequence &Sequence);
4309
4310static void TryValueInitialization(Sema &S,
4311 const InitializedEntity &Entity,
4312 const InitializationKind &Kind,
4313 InitializationSequence &Sequence,
4314 InitListExpr *InitList = nullptr);
4315
4316/// Attempt list initialization of a reference.
4317static void TryReferenceListInitialization(Sema &S,
4318 const InitializedEntity &Entity,
4319 const InitializationKind &Kind,
4320 InitListExpr *InitList,
4321 InitializationSequence &Sequence,
4322 bool TreatUnavailableAsInvalid) {
4323 // First, catch C++03 where this isn't possible.
4324 if (!S.getLangOpts().CPlusPlus11) {
4325 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4326 return;
4327 }
4328 // Can't reference initialize a compound literal.
4329 if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
4330 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4331 return;
4332 }
4333
4334 QualType DestType = Entity.getType();
4335 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4336 Qualifiers T1Quals;
4337 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4338
4339 // Reference initialization via an initializer list works thus:
4340 // If the initializer list consists of a single element that is
4341 // reference-related to the referenced type, bind directly to that element
4342 // (possibly creating temporaries).
4343 // Otherwise, initialize a temporary with the initializer list and
4344 // bind to that.
4345 if (InitList->getNumInits() == 1) {
4346 Expr *Initializer = InitList->getInit(0);
4347 QualType cv2T2 = S.getCompletedType(Initializer);
4348 Qualifiers T2Quals;
4349 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4350
4351 // If this fails, creating a temporary wouldn't work either.
4352 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4353 T1, Sequence))
4354 return;
4355
4356 SourceLocation DeclLoc = Initializer->getBeginLoc();
4357 Sema::ReferenceCompareResult RefRelationship
4358 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2);
4359 if (RefRelationship >= Sema::Ref_Related) {
4360 // Try to bind the reference here.
4361 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4362 T1Quals, cv2T2, T2, T2Quals, Sequence);
4363 if (Sequence)
4364 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4365 return;
4366 }
4367
4368 // Update the initializer if we've resolved an overloaded function.
4369 if (Sequence.step_begin() != Sequence.step_end())
4370 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4371 }
4372 // Perform address space compatibility check.
4373 QualType cv1T1IgnoreAS = cv1T1;
4374 if (T1Quals.hasAddressSpace()) {
4375 Qualifiers T2Quals;
4376 (void)S.Context.getUnqualifiedArrayType(InitList->getType(), T2Quals);
4377 if (!T1Quals.isAddressSpaceSupersetOf(T2Quals)) {
4378 Sequence.SetFailed(
4379 InitializationSequence::FK_ReferenceInitDropsQualifiers);
4380 return;
4381 }
4382 // Ignore address space of reference type at this point and perform address
4383 // space conversion after the reference binding step.
4384 cv1T1IgnoreAS =
4385 S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace());
4386 }
4387 // Not reference-related. Create a temporary and bind to that.
4388 InitializedEntity TempEntity =
4389 InitializedEntity::InitializeTemporary(cv1T1IgnoreAS);
4390
4391 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
4392 TreatUnavailableAsInvalid);
4393 if (Sequence) {
4394 if (DestType->isRValueReferenceType() ||
4395 (T1Quals.hasConst() && !T1Quals.hasVolatile())) {
4396 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS,
4397 /*BindingTemporary=*/true);
4398 if (T1Quals.hasAddressSpace())
4399 Sequence.AddQualificationConversionStep(
4400 cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue);
4401 } else
4402 Sequence.SetFailed(
4403 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
4404 }
4405}
4406
4407/// Attempt list initialization (C++0x [dcl.init.list])
4408static void TryListInitialization(Sema &S,
4409 const InitializedEntity &Entity,
4410 const InitializationKind &Kind,
4411 InitListExpr *InitList,
4412 InitializationSequence &Sequence,
4413 bool TreatUnavailableAsInvalid) {
4414 QualType DestType = Entity.getType();
4415
4416 // C++ doesn't allow scalar initialization with more than one argument.
4417 // But C99 complex numbers are scalars and it makes sense there.
4418 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
4419 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
4420 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
4421 return;
4422 }
4423 if (DestType->isReferenceType()) {
4424 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
4425 TreatUnavailableAsInvalid);
4426 return;
4427 }
4428
4429 if (DestType->isRecordType() &&
4430 !S.isCompleteType(InitList->getBeginLoc(), DestType)) {
4431 Sequence.setIncompleteTypeFailure(DestType);
4432 return;
4433 }
4434
4435 // C++11 [dcl.init.list]p3, per DR1467:
4436 // - If T is a class type and the initializer list has a single element of
4437 // type cv U, where U is T or a class derived from T, the object is
4438 // initialized from that element (by copy-initialization for
4439 // copy-list-initialization, or by direct-initialization for
4440 // direct-list-initialization).
4441 // - Otherwise, if T is a character array and the initializer list has a
4442 // single element that is an appropriately-typed string literal
4443 // (8.5.2 [dcl.init.string]), initialization is performed as described
4444 // in that section.
4445 // - Otherwise, if T is an aggregate, [...] (continue below).
4446 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) {
4447 if (DestType->isRecordType()) {
4448 QualType InitType = InitList->getInit(0)->getType();
4449 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
4450 S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {
4451 Expr *InitListAsExpr = InitList;
4452 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4453 DestType, Sequence,
4454 /*InitListSyntax*/false,
4455 /*IsInitListCopy*/true);
4456 return;
4457 }
4458 }
4459 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
4460 Expr *SubInit[1] = {InitList->getInit(0)};
4461 if (!isa<VariableArrayType>(DestAT) &&
4462 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
4463 InitializationKind SubKind =
4464 Kind.getKind() == InitializationKind::IK_DirectList
4465 ? InitializationKind::CreateDirect(Kind.getLocation(),
4466 InitList->getLBraceLoc(),
4467 InitList->getRBraceLoc())
4468 : Kind;
4469 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4470 /*TopLevelOfInitList*/ true,
4471 TreatUnavailableAsInvalid);
4472
4473 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4474 // the element is not an appropriately-typed string literal, in which
4475 // case we should proceed as in C++11 (below).
4476 if (Sequence) {
4477 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4478 return;
4479 }
4480 }
4481 }
4482 }
4483
4484 // C++11 [dcl.init.list]p3:
4485 // - If T is an aggregate, aggregate initialization is performed.
4486 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
4487 (S.getLangOpts().CPlusPlus11 &&
4488 S.isStdInitializerList(DestType, nullptr))) {
4489 if (S.getLangOpts().CPlusPlus11) {
4490 // - Otherwise, if the initializer list has no elements and T is a
4491 // class type with a default constructor, the object is
4492 // value-initialized.
4493 if (InitList->getNumInits() == 0) {
4494 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4495 if (S.LookupDefaultConstructor(RD)) {
4496 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
4497 return;
4498 }
4499 }
4500
4501 // - Otherwise, if T is a specialization of std::initializer_list<E>,
4502 // an initializer_list object constructed [...]
4503 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
4504 TreatUnavailableAsInvalid))
4505 return;
4506
4507 // - Otherwise, if T is a class type, constructors are considered.
4508 Expr *InitListAsExpr = InitList;
4509 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4510 DestType, Sequence, /*InitListSyntax*/true);
4511 } else
4512 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
4513 return;
4514 }
4515
4516 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
4517 InitList->getNumInits() == 1) {
4518 Expr *E = InitList->getInit(0);
4519
4520 // - Otherwise, if T is an enumeration with a fixed underlying type,
4521 // the initializer-list has a single element v, and the initialization
4522 // is direct-list-initialization, the object is initialized with the
4523 // value T(v); if a narrowing conversion is required to convert v to
4524 // the underlying type of T, the program is ill-formed.
4525 auto *ET = DestType->getAs<EnumType>();
4526 if (S.getLangOpts().CPlusPlus17 &&
4527 Kind.getKind() == InitializationKind::IK_DirectList &&
4528 ET && ET->getDecl()->isFixed() &&
4529 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
4530 (E->getType()->isIntegralOrUnscopedEnumerationType() ||
4531 E->getType()->isFloatingType())) {
4532 // There are two ways that T(v) can work when T is an enumeration type.
4533 // If there is either an implicit conversion sequence from v to T or
4534 // a conversion function that can convert from v to T, then we use that.
4535 // Otherwise, if v is of integral, unscoped enumeration, or floating-point
4536 // type, it is converted to the enumeration type via its underlying type.
4537 // There is no overlap possible between these two cases (except when the
4538 // source value is already of the destination type), and the first
4539 // case is handled by the general case for single-element lists below.
4540 ImplicitConversionSequence ICS;
4541 ICS.setStandard();
4542 ICS.Standard.setAsIdentityConversion();
4543 if (!E->isPRValue())
4544 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4545 // If E is of a floating-point type, then the conversion is ill-formed
4546 // due to narrowing, but go through the motions in order to produce the
4547 // right diagnostic.
4548 ICS.Standard.Second = E->getType()->isFloatingType()
4549 ? ICK_Floating_Integral
4550 : ICK_Integral_Conversion;
4551 ICS.Standard.setFromType(E->getType());
4552 ICS.Standard.setToType(0, E->getType());
4553 ICS.Standard.setToType(1, DestType);
4554 ICS.Standard.setToType(2, DestType);
4555 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
4556 /*TopLevelOfInitList*/true);
4557 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4558 return;
4559 }
4560
4561 // - Otherwise, if the initializer list has a single element of type E
4562 // [...references are handled above...], the object or reference is
4563 // initialized from that element (by copy-initialization for
4564 // copy-list-initialization, or by direct-initialization for
4565 // direct-list-initialization); if a narrowing conversion is required
4566 // to convert the element to T, the program is ill-formed.
4567 //
4568 // Per core-24034, this is direct-initialization if we were performing
4569 // direct-list-initialization and copy-initialization otherwise.
4570 // We can't use InitListChecker for this, because it always performs
4571 // copy-initialization. This only matters if we might use an 'explicit'
4572 // conversion operator, or for the special case conversion of nullptr_t to
4573 // bool, so we only need to handle those cases.
4574 //
4575 // FIXME: Why not do this in all cases?
4576 Expr *Init = InitList->getInit(0);
4577 if (Init->getType()->isRecordType() ||
4578 (Init->getType()->isNullPtrType() && DestType->isBooleanType())) {
4579 InitializationKind SubKind =
4580 Kind.getKind() == InitializationKind::IK_DirectList
4581 ? InitializationKind::CreateDirect(Kind.getLocation(),
4582 InitList->getLBraceLoc(),
4583 InitList->getRBraceLoc())
4584 : Kind;
4585 Expr *SubInit[1] = { Init };
4586 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4587 /*TopLevelOfInitList*/true,
4588 TreatUnavailableAsInvalid);
4589 if (Sequence)
4590 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4591 return;
4592 }
4593 }
4594
4595 InitListChecker CheckInitList(S, Entity, InitList,
4596 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
4597 if (CheckInitList.HadError()) {
4598 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
4599 return;
4600 }
4601
4602 // Add the list initialization step with the built init list.
4603 Sequence.AddListInitializationStep(DestType);
4604}
4605
4606/// Try a reference initialization that involves calling a conversion
4607/// function.
4608static OverloadingResult TryRefInitWithConversionFunction(
4609 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4610 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
4611 InitializationSequence &Sequence) {
4612 QualType DestType = Entity.getType();
4613 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4614 QualType T1 = cv1T1.getUnqualifiedType();
4615 QualType cv2T2 = Initializer->getType();
4616 QualType T2 = cv2T2.getUnqualifiedType();
4617
4618 assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) &&(static_cast <bool> (!S.CompareReferenceRelationship(Initializer
->getBeginLoc(), T1, T2) && "Must have incompatible references when binding via conversion"
) ? void (0) : __assert_fail ("!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) && \"Must have incompatible references when binding via conversion\""
, "clang/lib/Sema/SemaInit.cpp", 4619, __extension__ __PRETTY_FUNCTION__
))
4619 "Must have incompatible references when binding via conversion")(static_cast <bool> (!S.CompareReferenceRelationship(Initializer
->getBeginLoc(), T1, T2) && "Must have incompatible references when binding via conversion"
) ? void (0) : __assert_fail ("!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) && \"Must have incompatible references when binding via conversion\""
, "clang/lib/Sema/SemaInit.cpp", 4619, __extension__ __PRETTY_FUNCTION__
))
;
4620
4621 // Build the candidate set directly in the initialization sequence
4622 // structure, so that it will persist if we fail.
4623 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4624 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4625
4626 // Determine whether we are allowed to call explicit conversion operators.
4627 // Note that none of [over.match.copy], [over.match.conv], nor
4628 // [over.match.ref] permit an explicit constructor to be chosen when
4629 // initializing a reference, not even for direct-initialization.
4630 bool AllowExplicitCtors = false;
4631 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
4632
4633 const RecordType *T1RecordType = nullptr;
4634 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
4635 S.isCompleteType(Kind.getLocation(), T1)) {
4636 // The type we're converting to is a class type. Enumerate its constructors
4637 // to see if there is a suitable conversion.
4638 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
4639
4640 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
4641 auto Info = getConstructorInfo(D);
4642 if (!Info.Constructor)
4643 continue;
4644
4645 if (!Info.Constructor->isInvalidDecl() &&
4646 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
4647 if (Info.ConstructorTmpl)
4648 S.AddTemplateOverloadCandidate(
4649 Info.ConstructorTmpl, Info.FoundDecl,
4650 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
4651 /*SuppressUserConversions=*/true,
4652 /*PartialOverloading*/ false, AllowExplicitCtors);
4653 else
4654 S.AddOverloadCandidate(
4655 Info.Constructor, Info.FoundDecl, Initializer, CandidateSet,
4656 /*SuppressUserConversions=*/true,
4657 /*PartialOverloading*/ false, AllowExplicitCtors);
4658 }
4659 }
4660 }
4661 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
4662 return OR_No_Viable_Function;
4663
4664 const RecordType *T2RecordType = nullptr;
4665 if ((T2RecordType = T2->getAs<RecordType>()) &&
4666 S.isCompleteType(Kind.getLocation(), T2)) {
4667 // The type we're converting from is a class type, enumerate its conversion
4668 // functions.
4669 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4670
4671 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4672 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4673 NamedDecl *D = *I;
4674 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4675 if (isa<UsingShadowDecl>(D))
4676 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4677
4678 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4679 CXXConversionDecl *Conv;
4680 if (ConvTemplate)
4681 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4682 else
4683 Conv = cast<CXXConversionDecl>(D);
4684
4685 // If the conversion function doesn't return a reference type,
4686 // it can't be considered for this conversion unless we're allowed to
4687 // consider rvalues.
4688 // FIXME: Do we need to make sure that we only consider conversion
4689 // candidates with reference-compatible results? That might be needed to
4690 // break recursion.
4691 if ((AllowRValues ||
4692 Conv->getConversionType()->isLValueReferenceType())) {
4693 if (ConvTemplate)
4694 S.AddTemplateConversionCandidate(
4695 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4696 CandidateSet,
4697 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
4698 else
4699 S.AddConversionCandidate(
4700 Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet,
4701 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
4702 }
4703 }
4704 }
4705 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4706 return OR_No_Viable_Function;
4707
4708 SourceLocation DeclLoc = Initializer->getBeginLoc();
4709
4710 // Perform overload resolution. If it fails, return the failed result.
4711 OverloadCandidateSet::iterator Best;
4712 if (OverloadingResult Result
4713 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
4714 return Result;
4715
4716 FunctionDecl *Function = Best->Function;
4717 // This is the overload that will be used for this initialization step if we
4718 // use this initialization. Mark it as referenced.
4719 Function->setReferenced();
4720
4721 // Compute the returned type and value kind of the conversion.
4722 QualType cv3T3;
4723 if (isa<CXXConversionDecl>(Function))
4724 cv3T3 = Function->getReturnType();
4725 else
4726 cv3T3 = T1;
4727
4728 ExprValueKind VK = VK_PRValue;
4729 if (cv3T3->isLValueReferenceType())
4730 VK = VK_LValue;
4731 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
4732 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
4733 cv3T3 = cv3T3.getNonLValueExprType(S.Context);
4734
4735 // Add the user-defined conversion step.
4736 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4737 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
4738 HadMultipleCandidates);
4739
4740 // Determine whether we'll need to perform derived-to-base adjustments or
4741 // other conversions.
4742 Sema::ReferenceConversions RefConv;
4743 Sema::ReferenceCompareResult NewRefRelationship =
4744 S.CompareReferenceRelationship(DeclLoc, T1, cv3T3, &RefConv);
4745
4746 // Add the final conversion sequence, if necessary.
4747 if (NewRefRelationship == Sema::Ref_Incompatible) {
4748 assert(!isa<CXXConstructorDecl>(Function) &&(static_cast <bool> (!isa<CXXConstructorDecl>(Function
) && "should not have conversion after constructor") ?
void (0) : __assert_fail ("!isa<CXXConstructorDecl>(Function) && \"should not have conversion after constructor\""
, "clang/lib/Sema/SemaInit.cpp", 4749, __extension__ __PRETTY_FUNCTION__
))
4749 "should not have conversion after constructor")(static_cast <bool> (!isa<CXXConstructorDecl>(Function
) && "should not have conversion after constructor") ?
void (0) : __assert_fail ("!isa<CXXConstructorDecl>(Function) && \"should not have conversion after constructor\""
, "clang/lib/Sema/SemaInit.cpp", 4749, __extension__ __PRETTY_FUNCTION__
))
;
4750
4751 ImplicitConversionSequence ICS;
4752 ICS.setStandard();
4753 ICS.Standard = Best->FinalConversion;
4754 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
4755
4756 // Every implicit conversion results in a prvalue, except for a glvalue
4757 // derived-to-base conversion, which we handle below.
4758 cv3T3 = ICS.Standard.getToType(2);
4759 VK = VK_PRValue;
4760 }
4761
4762 // If the converted initializer is a prvalue, its type T4 is adjusted to
4763 // type "cv1 T4" and the temporary materialization conversion is applied.
4764 //
4765 // We adjust the cv-qualifications to match the reference regardless of
4766 // whether we have a prvalue so that the AST records the change. In this
4767 // case, T4 is "cv3 T3".
4768 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
4769 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
4770 Sequence.AddQualificationConversionStep(cv1T4, VK);
4771 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_PRValue);
4772 VK = IsLValueRef ? VK_LValue : VK_XValue;
4773
4774 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
4775 Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
4776 else if (RefConv & Sema::ReferenceConversions::ObjC)
4777 Sequence.AddObjCObjectConversionStep(cv1T1);
4778 else if (RefConv & Sema::ReferenceConversions::Function)
4779 Sequence.AddFunctionReferenceConversionStep(cv1T1);
4780 else if (RefConv & Sema::ReferenceConversions::Qualification) {
4781 if (!S.Context.hasSameType(cv1T4, cv1T1))
4782 Sequence.AddQualificationConversionStep(cv1T1, VK);
4783 }
4784
4785 return OR_Success;
4786}
4787
4788static void CheckCXX98CompatAccessibleCopy(Sema &S,
4789 const InitializedEntity &Entity,
4790 Expr *CurInitExpr);
4791
4792/// Attempt reference initialization (C++0x [dcl.init.ref])
4793static void TryReferenceInitialization(Sema &S,
4794 const InitializedEntity &Entity,
4795 const InitializationKind &Kind,
4796 Expr *Initializer,
4797 InitializationSequence &Sequence) {
4798 QualType DestType = Entity.getType();
4799 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4800 Qualifiers T1Quals;
4801 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4802 QualType cv2T2 = S.getCompletedType(Initializer);
4803 Qualifiers T2Quals;
4804 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4805
4806 // If the initializer is the address of an overloaded function, try
4807 // to resolve the overloaded function. If all goes well, T2 is the
4808 // type of the resulting function.
4809 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4810 T1, Sequence))
4811 return;
4812
4813 // Delegate everything else to a subfunction.
4814 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4815 T1Quals, cv2T2, T2, T2Quals, Sequence);
4816}
4817
4818/// Determine whether an expression is a non-referenceable glvalue (one to
4819/// which a reference can never bind). Attempting to bind a reference to
4820/// such a glvalue will always create a temporary.
4821static bool isNonReferenceableGLValue(Expr *E) {
4822 return E->refersToBitField() || E->refersToVectorElement() ||
4823 E->refersToMatrixElement();
4824}
4825
4826/// Reference initialization without resolving overloaded functions.
4827///
4828/// We also can get here in C if we call a builtin which is declared as
4829/// a function with a parameter of reference type (such as __builtin_va_end()).
4830static void TryReferenceInitializationCore(Sema &S,
4831 const InitializedEntity &Entity,
4832 const InitializationKind &Kind,
4833 Expr *Initializer,
4834 QualType cv1T1, QualType T1,
4835 Qualifiers T1Quals,
4836 QualType cv2T2, QualType T2,
4837 Qualifiers T2Quals,
4838 InitializationSequence &Sequence) {
4839 QualType DestType = Entity.getType();
4840 SourceLocation DeclLoc = Initializer->getBeginLoc();
4841
4842 // Compute some basic properties of the types and the initializer.
4843 bool isLValueRef = DestType->isLValueReferenceType();
4844 bool isRValueRef = !isLValueRef;
4845 Expr::Classification InitCategory = Initializer->Classify(S.Context);
4846
4847 Sema::ReferenceConversions RefConv;
4848 Sema::ReferenceCompareResult RefRelationship =
4849 S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, &RefConv);
4850
4851 // C++0x [dcl.init.ref]p5:
4852 // A reference to type "cv1 T1" is initialized by an expression of type
4853 // "cv2 T2" as follows:
4854 //
4855 // - If the reference is an lvalue reference and the initializer
4856 // expression
4857 // Note the analogous bullet points for rvalue refs to functions. Because
4858 // there are no function rvalues in C++, rvalue refs to functions are treated
4859 // like lvalue refs.
4860 OverloadingResult ConvOvlResult = OR_Success;
4861 bool T1Function = T1->isFunctionType();
4862 if (isLValueRef || T1Function) {
4863 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
4864 (RefRelationship == Sema::Ref_Compatible ||
4865 (Kind.isCStyleOrFunctionalCast() &&
4866 RefRelationship == Sema::Ref_Related))) {
4867 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
4868 // reference-compatible with "cv2 T2," or
4869 if (RefConv & (Sema::ReferenceConversions::DerivedToBase |
4870 Sema::ReferenceConversions::ObjC)) {
4871 // If we're converting the pointee, add any qualifiers first;
4872 // these qualifiers must all be top-level, so just convert to "cv1 T2".
4873 if (RefConv & (Sema::ReferenceConversions::Qualification))
4874 Sequence.AddQualificationConversionStep(
4875 S.Context.getQualifiedType(T2, T1Quals),
4876 Initializer->getValueKind());
4877 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
4878 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
4879 else
4880 Sequence.AddObjCObjectConversionStep(cv1T1);
4881 } else if (RefConv & Sema::ReferenceConversions::Qualification) {
4882 // Perform a (possibly multi-level) qualification conversion.
4883 Sequence.AddQualificationConversionStep(cv1T1,
4884 Initializer->getValueKind());
4885 } else if (RefConv & Sema::ReferenceConversions::Function) {
4886 Sequence.AddFunctionReferenceConversionStep(cv1T1);
4887 }
4888
4889 // We only create a temporary here when binding a reference to a
4890 // bit-field or vector element. Those cases are't supposed to be
4891 // handled by this bullet, but the outcome is the same either way.
4892 Sequence.AddReferenceBindingStep(cv1T1, false);
4893 return;
4894 }
4895
4896 // - has a class type (i.e., T2 is a class type), where T1 is not
4897 // reference-related to T2, and can be implicitly converted to an
4898 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
4899 // with "cv3 T3" (this conversion is selected by enumerating the
4900 // applicable conversion functions (13.3.1.6) and choosing the best
4901 // one through overload resolution (13.3)),
4902 // If we have an rvalue ref to function type here, the rhs must be
4903 // an rvalue. DR1287 removed the "implicitly" here.
4904 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
4905 (isLValueRef || InitCategory.isRValue())) {
4906 if (S.getLangOpts().CPlusPlus) {
4907 // Try conversion functions only for C++.
4908 ConvOvlResult = TryRefInitWithConversionFunction(
4909 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
4910 /*IsLValueRef*/ isLValueRef, Sequence);
4911 if (ConvOvlResult == OR_Success)
4912 return;
4913 if (ConvOvlResult != OR_No_Viable_Function)
4914 Sequence.SetOverloadFailure(
4915 InitializationSequence::FK_ReferenceInitOverloadFailed,
4916 ConvOvlResult);
4917 } else {
4918 ConvOvlResult = OR_No_Viable_Function;
4919 }
4920 }
4921 }
4922
4923 // - Otherwise, the reference shall be an lvalue reference to a
4924 // non-volatile const type (i.e., cv1 shall be const), or the reference
4925 // shall be an rvalue reference.
4926 // For address spaces, we interpret this to mean that an addr space
4927 // of a reference "cv1 T1" is a superset of addr space of "cv2 T2".
4928 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile() &&
4929 T1Quals.isAddressSpaceSupersetOf(T2Quals))) {
4930 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4931 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4932 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4933 Sequence.SetOverloadFailure(
4934 InitializationSequence::FK_ReferenceInitOverloadFailed,
4935 ConvOvlResult);
4936 else if (!InitCategory.isLValue())
4937 Sequence.SetFailed(
4938 T1Quals.isAddressSpaceSupersetOf(T2Quals)
4939 ? InitializationSequence::
4940 FK_NonConstLValueReferenceBindingToTemporary
4941 : InitializationSequence::FK_ReferenceInitDropsQualifiers);
4942 else {
4943 InitializationSequence::FailureKind FK;
4944 switch (RefRelationship) {
4945 case Sema::Ref_Compatible:
4946 if (Initializer->refersToBitField())
4947 FK = InitializationSequence::
4948 FK_NonConstLValueReferenceBindingToBitfield;
4949 else if (Initializer->refersToVectorElement())
4950 FK = InitializationSequence::
4951 FK_NonConstLValueReferenceBindingToVectorElement;
4952 else if (Initializer->refersToMatrixElement())
4953 FK = InitializationSequence::
4954 FK_NonConstLValueReferenceBindingToMatrixElement;
4955 else
4956 llvm_unreachable("unexpected kind of compatible initializer")::llvm::llvm_unreachable_internal("unexpected kind of compatible initializer"
, "clang/lib/Sema/SemaInit.cpp", 4956)
;
4957 break;
4958 case Sema::Ref_Related:
4959 FK = InitializationSequence::FK_ReferenceInitDropsQualifiers;
4960 break;
4961 case Sema::Ref_Incompatible:
4962 FK = InitializationSequence::
4963 FK_NonConstLValueReferenceBindingToUnrelated;
4964 break;
4965 }
4966 Sequence.SetFailed(FK);
4967 }
4968 return;
4969 }
4970
4971 // - If the initializer expression
4972 // - is an
4973 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
4974 // [1z] rvalue (but not a bit-field) or
4975 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
4976 //
4977 // Note: functions are handled above and below rather than here...
4978 if (!T1Function &&
4979 (RefRelationship == Sema::Ref_Compatible ||
4980 (Kind.isCStyleOrFunctionalCast() &&
4981 RefRelationship == Sema::Ref_Related)) &&
4982 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
4983 (InitCategory.isPRValue() &&
4984 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
4985 T2->isArrayType())))) {
4986 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_PRValue;
4987 if (InitCategory.isPRValue() && T2->isRecordType()) {
4988 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
4989 // compiler the freedom to perform a copy here or bind to the
4990 // object, while C++0x requires that we bind directly to the
4991 // object. Hence, we always bind to the object without making an
4992 // extra copy. However, in C++03 requires that we check for the
4993 // presence of a suitable copy constructor:
4994 //
4995 // The constructor that would be used to make the copy shall
4996 // be callable whether or not the copy is actually done.
4997 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
4998 Sequence.AddExtraneousCopyToTemporary(cv2T2);
4999 else if (S.getLangOpts().CPlusPlus11)
5000 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
5001 }
5002
5003 // C++1z [dcl.init.ref]/5.2.1.2:
5004 // If the converted initializer is a prvalue, its type T4 is adjusted
5005 // to type "cv1 T4" and the temporary materialization conversion is
5006 // applied.
5007 // Postpone address space conversions to after the temporary materialization
5008 // conversion to allow creating temporaries in the alloca address space.
5009 auto T1QualsIgnoreAS = T1Quals;
5010 auto T2QualsIgnoreAS = T2Quals;
5011 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5012 T1QualsIgnoreAS.removeAddressSpace();
5013 T2QualsIgnoreAS.removeAddressSpace();
5014 }
5015 QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1QualsIgnoreAS);
5016 if (T1QualsIgnoreAS != T2QualsIgnoreAS)
5017 Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
5018 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_PRValue);
5019 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
5020 // Add addr space conversion if required.
5021 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5022 auto T4Quals = cv1T4.getQualifiers();
5023 T4Quals.addAddressSpace(T1Quals.getAddressSpace());
5024 QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals);
5025 Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind);
5026 cv1T4 = cv1T4WithAS;
5027 }
5028
5029 // In any case, the reference is bound to the resulting glvalue (or to
5030 // an appropriate base class subobject).
5031 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5032 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
5033 else if (RefConv & Sema::ReferenceConversions::ObjC)
5034 Sequence.AddObjCObjectConversionStep(cv1T1);
5035 else if (RefConv & Sema::ReferenceConversions::Qualification) {
5036 if (!S.Context.hasSameType(cv1T4, cv1T1))
5037 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
5038 }
5039 return;
5040 }
5041
5042 // - has a class type (i.e., T2 is a class type), where T1 is not
5043 // reference-related to T2, and can be implicitly converted to an
5044 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
5045 // where "cv1 T1" is reference-compatible with "cv3 T3",
5046 //
5047 // DR1287 removes the "implicitly" here.
5048 if (T2->isRecordType()) {
5049 if (RefRelationship == Sema::Ref_Incompatible) {
5050 ConvOvlResult = TryRefInitWithConversionFunction(
5051 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
5052 /*IsLValueRef*/ isLValueRef, Sequence);
5053 if (ConvOvlResult)
5054 Sequence.SetOverloadFailure(
5055 InitializationSequence::FK_ReferenceInitOverloadFailed,
5056 ConvOvlResult);
5057
5058 return;
5059 }
5060
5061 if (RefRelationship == Sema::Ref_Compatible &&
5062 isRValueRef && InitCategory.isLValue()) {
5063 Sequence.SetFailed(
5064 InitializationSequence::FK_RValueReferenceBindingToLValue);
5065 return;
5066 }
5067
5068 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
5069 return;
5070 }
5071
5072 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
5073 // from the initializer expression using the rules for a non-reference
5074 // copy-initialization (8.5). The reference is then bound to the
5075 // temporary. [...]
5076
5077 // Ignore address space of reference type at this point and perform address
5078 // space conversion after the reference binding step.
5079 QualType cv1T1IgnoreAS =
5080 T1Quals.hasAddressSpace()
5081 ? S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace())
5082 : cv1T1;
5083
5084 InitializedEntity TempEntity =
5085 InitializedEntity::InitializeTemporary(cv1T1IgnoreAS);
5086
5087 // FIXME: Why do we use an implicit conversion here rather than trying
5088 // copy-initialization?
5089 ImplicitConversionSequence ICS
5090 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
5091 /*SuppressUserConversions=*/false,
5092 Sema::AllowedExplicit::None,
5093 /*FIXME:InOverloadResolution=*/false,
5094 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5095 /*AllowObjCWritebackConversion=*/false);
5096
5097 if (ICS.isBad()) {
5098 // FIXME: Use the conversion function set stored in ICS to turn
5099 // this into an overloading ambiguity diagnostic. However, we need
5100 // to keep that set as an OverloadCandidateSet rather than as some
5101 // other kind of set.
5102 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5103 Sequence.SetOverloadFailure(
5104 InitializationSequence::FK_ReferenceInitOverloadFailed,
5105 ConvOvlResult);
5106 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
5107 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
5108 else
5109 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
5110 return;
5111 } else {
5112 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
5113 }
5114
5115 // [...] If T1 is reference-related to T2, cv1 must be the
5116 // same cv-qualification as, or greater cv-qualification
5117 // than, cv2; otherwise, the program is ill-formed.
5118 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
5119 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
5120 if (RefRelationship == Sema::Ref_Related &&
5121 ((T1CVRQuals | T2CVRQuals) != T1CVRQuals ||
5122 !T1Quals.isAddressSpaceSupersetOf(T2Quals))) {
5123 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
5124 return;
5125 }
5126
5127 // [...] If T1 is reference-related to T2 and the reference is an rvalue
5128 // reference, the initializer expression shall not be an lvalue.
5129 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
5130 InitCategory.isLValue()) {
5131 Sequence.SetFailed(
5132 InitializationSequence::FK_RValueReferenceBindingToLValue);
5133 return;
5134 }
5135
5136 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true);
5137
5138 if (T1Quals.hasAddressSpace()) {
5139 if (!Qualifiers::isAddressSpaceSupersetOf(T1Quals.getAddressSpace(),
5140 LangAS::Default)) {
5141 Sequence.SetFailed(
5142 InitializationSequence::FK_ReferenceAddrspaceMismatchTemporary);
5143 return;
5144 }
5145 Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue
5146 : VK_XValue);
5147 }
5148}
5149
5150/// Attempt character array initialization from a string literal
5151/// (C++ [dcl.init.string], C99 6.7.8).
5152static void TryStringLiteralInitialization(Sema &S,
5153 const InitializedEntity &Entity,
5154 const InitializationKind &Kind,
5155 Expr *Initializer,
5156 InitializationSequence &Sequence) {
5157 Sequence.AddStringInitStep(Entity.getType());
5158}
5159
5160/// Attempt value initialization (C++ [dcl.init]p7).
5161static void TryValueInitialization(Sema &S,
5162 const InitializedEntity &Entity,
5163 const InitializationKind &Kind,
5164 InitializationSequence &Sequence,
5165 InitListExpr *InitList) {
5166 assert((!InitList || InitList->getNumInits() == 0) &&(static_cast <bool> ((!InitList || InitList->getNumInits
() == 0) && "Shouldn't use value-init for non-empty init lists"
) ? void (0) : __assert_fail ("(!InitList || InitList->getNumInits() == 0) && \"Shouldn't use value-init for non-empty init lists\""
, "clang/lib/Sema/SemaInit.cpp", 5167, __extension__ __PRETTY_FUNCTION__
))
5167 "Shouldn't use value-init for non-empty init lists")(static_cast <bool> ((!InitList || InitList->getNumInits
() == 0) && "Shouldn't use value-init for non-empty init lists"
) ? void (0) : __assert_fail ("(!InitList || InitList->getNumInits() == 0) && \"Shouldn't use value-init for non-empty init lists\""
, "clang/lib/Sema/SemaInit.cpp", 5167, __extension__ __PRETTY_FUNCTION__
))
;
5168
5169 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
5170 //
5171 // To value-initialize an object of type T means:
5172 QualType T = Entity.getType();
5173
5174 // -- if T is an array type, then each element is value-initialized;
5175 T = S.Context.getBaseElementType(T);
5176
5177 if (const RecordType *RT = T->getAs<RecordType>()) {
5178 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
5179 bool NeedZeroInitialization = true;
5180 // C++98:
5181 // -- if T is a class type (clause 9) with a user-declared constructor
5182 // (12.1), then the default constructor for T is called (and the
5183 // initialization is ill-formed if T has no accessible default
5184 // constructor);
5185 // C++11:
5186 // -- if T is a class type (clause 9) with either no default constructor
5187 // (12.1 [class.ctor]) or a default constructor that is user-provided
5188 // or deleted, then the object is default-initialized;
5189 //
5190 // Note that the C++11 rule is the same as the C++98 rule if there are no
5191 // defaulted or deleted constructors, so we just use it unconditionally.
5192 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
5193 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
5194 NeedZeroInitialization = false;
5195
5196 // -- if T is a (possibly cv-qualified) non-union class type without a
5197 // user-provided or deleted default constructor, then the object is
5198 // zero-initialized and, if T has a non-trivial default constructor,
5199 // default-initialized;
5200 // The 'non-union' here was removed by DR1502. The 'non-trivial default
5201 // constructor' part was removed by DR1507.
5202 if (NeedZeroInitialization)
5203 Sequence.AddZeroInitializationStep(Entity.getType());
5204
5205 // C++03:
5206 // -- if T is a non-union class type without a user-declared constructor,
5207 // then every non-static data member and base class component of T is
5208 // value-initialized;
5209 // [...] A program that calls for [...] value-initialization of an
5210 // entity of reference type is ill-formed.
5211 //
5212 // C++11 doesn't need this handling, because value-initialization does not
5213 // occur recursively there, and the implicit default constructor is
5214 // defined as deleted in the problematic cases.
5215 if (!S.getLangOpts().CPlusPlus11 &&
5216 ClassDecl->hasUninitializedReferenceMember()) {
5217 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
5218 return;
5219 }
5220
5221 // If this is list-value-initialization, pass the empty init list on when
5222 // building the constructor call. This affects the semantics of a few
5223 // things (such as whether an explicit default constructor can be called).
5224 Expr *InitListAsExpr = InitList;
5225 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
5226 bool InitListSyntax = InitList;
5227
5228 // FIXME: Instead of creating a CXXConstructExpr of array type here,
5229 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
5230 return TryConstructorInitialization(
5231 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
5232 }
5233 }
5234
5235 Sequence.AddZeroInitializationStep(Entity.getType());
5236}
5237
5238/// Attempt default initialization (C++ [dcl.init]p6).
5239static void TryDefaultInitialization(Sema &S,
5240 const InitializedEntity &Entity,
5241 const InitializationKind &Kind,
5242 InitializationSequence &Sequence) {
5243 assert(Kind.getKind() == InitializationKind::IK_Default)(static_cast <bool> (Kind.getKind() == InitializationKind
::IK_Default) ? void (0) : __assert_fail ("Kind.getKind() == InitializationKind::IK_Default"
, "clang/lib/Sema/SemaInit.cpp", 5243, __extension__ __PRETTY_FUNCTION__
))
;
5244
5245 // C++ [dcl.init]p6:
5246 // To default-initialize an object of type T means:
5247 // - if T is an array type, each element is default-initialized;
5248 QualType DestType = S.Context.getBaseElementType(Entity.getType());
5249
5250 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
5251 // constructor for T is called (and the initialization is ill-formed if
5252 // T has no accessible default constructor);
5253 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
5254 TryConstructorInitialization(S, Entity, Kind, std::nullopt, DestType,
5255 Entity.getType(), Sequence);
5256 return;
5257 }
5258
5259 // - otherwise, no initialization is performed.
5260
5261 // If a program calls for the default initialization of an object of
5262 // a const-qualified type T, T shall be a class type with a user-provided
5263 // default constructor.
5264 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
5265 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
5266 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
5267 return;
5268 }
5269
5270 // If the destination type has a lifetime property, zero-initialize it.
5271 if (DestType.getQualifiers().hasObjCLifetime()) {
5272 Sequence.AddZeroInitializationStep(Entity.getType());
5273 return;
5274 }
5275}
5276
5277static void TryOrBuildParenListInitialization(
5278 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
5279 ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly,
5280 ExprResult *Result = nullptr) {
5281 unsigned ArgIndexToProcess = 0;
5282 SmallVector<Expr *, 4> InitExprs;
5283 QualType ResultType;
5284 Expr *ArrayFiller = nullptr;
5285 FieldDecl *InitializedFieldInUnion = nullptr;
5286
5287 // Process entities (i.e. array members, base classes, or class fields) by
5288 // adding an initialization expression to InitExprs for each entity to
5289 // initialize.
5290 auto ProcessEntities = [&](auto Range) -> bool {
5291 bool IsUnionType = Entity.getType()->isUnionType();
5292 for (InitializedEntity SubEntity : Range) {
5293 // Unions should only have one initializer expression.
5294 // If there are more initializers than it will be caught when we check
5295 // whether Index equals Args.size().
5296 if (ArgIndexToProcess == 1 && IsUnionType)
5297 return true;
5298
5299 bool IsMember = SubEntity.getKind() == InitializedEntity::EK_Member;
5300
5301 // Unnamed bitfields should not be initialized at all, either with an arg
5302 // or by default.
5303 if (IsMember && cast<FieldDecl>(SubEntity.getDecl())->isUnnamedBitfield())
5304 continue;
5305
5306 if (ArgIndexToProcess < Args.size()) {
5307 // There are still expressions in Args that haven't been processed.
5308 // Let's match them to the current entity to initialize.
5309 Expr *E = Args[ArgIndexToProcess++];
5310
5311 // Incomplete array types indicate flexible array members. Do not allow
5312 // paren list initializations of structs with these members, as GCC
5313 // doesn't either.
5314 if (IsMember) {
5315 auto *FD = cast<FieldDecl>(SubEntity.getDecl());
5316 if (FD->getType()->isIncompleteArrayType()) {
5317 if (!VerifyOnly) {
5318 S.Diag(E->getBeginLoc(), diag::err_flexible_array_init)
5319 << SourceRange(E->getBeginLoc(), E->getEndLoc());
5320 S.Diag(FD->getLocation(), diag::note_flexible_array_member) << FD;
5321 }
5322 Sequence.SetFailed(
5323 InitializationSequence::FK_ParenthesizedListInitFailed);
5324 return false;
5325 }
5326 }
5327
5328 InitializationKind SubKind = InitializationKind::CreateForInit(
5329 E->getExprLoc(), /*isDirectInit=*/false, E);
5330 InitializationSequence SubSeq(S, SubEntity, SubKind, E);
5331
5332 if (SubSeq.Failed()) {
5333 if (!VerifyOnly)
5334 SubSeq.Diagnose(S, SubEntity, SubKind, E);
5335 else
5336 Sequence.SetFailed(
5337 InitializationSequence::FK_ParenthesizedListInitFailed);
5338
5339 return false;
5340 }
5341 if (!VerifyOnly) {
5342 ExprResult ER = SubSeq.Perform(S, SubEntity, SubKind, E);
5343 InitExprs.push_back(ER.get());
5344 if (IsMember && IsUnionType)
5345 InitializedFieldInUnion = cast<FieldDecl>(SubEntity.getDecl());
5346 }
5347 } else {
5348 // We've processed all of the args, but there are still entities that
5349 // have to be initialized.
5350 if (IsMember) {
5351 // C++ [dcl.init]p17.6.2.2
5352 // The remaining elements are initialized with their default member
5353 // initializers, if any
5354 auto *FD = cast<FieldDecl>(SubEntity.getDecl());
5355 if (Expr *ICE = FD->getInClassInitializer(); ICE && !VerifyOnly) {
5356 ExprResult DIE = S.BuildCXXDefaultInitExpr(FD->getLocation(), FD);
5357 if (DIE.isInvalid())
5358 return false;
5359 S.checkInitializerLifetime(SubEntity, DIE.get());
5360 InitExprs.push_back(DIE.get());
5361 continue;
5362 };
5363 }
5364 // Remaining class elements without default member initializers and
5365 // array elements are value initialized:
5366 //
5367 // C++ [dcl.init]p17.6.2.2
5368 // The remaining elements...otherwise are value initialzed
5369 //
5370 // C++ [dcl.init]p17.5
5371 // if the destination type is an array, the object is initialized as
5372 // . follows. Let x1, . . . , xk be the elements of the expression-list
5373 // ...Let n denote the array size...the ith array element is...value-
5374 // initialized for each k < i <= n.
5375 InitializationKind SubKind = InitializationKind::CreateValue(
5376 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
5377 InitializationSequence SubSeq(S, SubEntity, SubKind, std::nullopt);
5378 if (SubSeq.Failed()) {
5379 if (!VerifyOnly)
5380 SubSeq.Diagnose(S, SubEntity, SubKind, std::nullopt);
5381 return false;
5382 }
5383 if (!VerifyOnly) {
5384 ExprResult ER = SubSeq.Perform(S, SubEntity, SubKind, std::nullopt);
5385 if (SubEntity.getKind() == InitializedEntity::EK_ArrayElement) {
5386 ArrayFiller = ER.get();
5387 return true;
5388 }
5389 InitExprs.push_back(ER.get());
5390 }
5391 }
5392 }
5393 return true;
5394 };
5395
5396 if (const ArrayType *AT =
5397 S.getASTContext().getAsArrayType(Entity.getType())) {
5398
5399 SmallVector<InitializedEntity, 4> ElementEntities;
5400 uint64_t ArrayLength;
5401 // C++ [dcl.init]p17.5
5402 // if the destination type is an array, the object is initialized as
5403 // follows. Let x1, . . . , xk be the elements of the expression-list. If
5404 // the destination type is an array of unknown bound, it is define as
5405 // having k elements.
5406 if (const ConstantArrayType *CAT =
5407 S.getASTContext().getAsConstantArrayType(Entity.getType()))
5408 ArrayLength = CAT->getSize().getZExtValue();
5409 else
5410 ArrayLength = Args.size();
5411
5412 if (ArrayLength >= Args.size()) {
5413 for (uint64_t I = 0; I < ArrayLength; ++I)
5414 ElementEntities.push_back(
5415 InitializedEntity::InitializeElement(S.getASTContext(), I, Entity));
5416
5417 if (!ProcessEntities(ElementEntities))
5418 return;
5419
5420 ResultType = S.Context.getConstantArrayType(
5421 AT->getElementType(), llvm::APInt(/*numBits=*/32, ArrayLength),
5422 nullptr, ArrayType::Normal, 0);
5423 }
5424 } else if (auto *RT = Entity.getType()->getAs<RecordType>()) {
5425 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
5426
5427 auto BaseRange = map_range(RD->bases(), [&S](auto &base) {
5428 return InitializedEntity::InitializeBase(S.getASTContext(), &base, false);
5429 });
5430 auto FieldRange = map_range(RD->fields(), [](auto *field) {
5431 return InitializedEntity::InitializeMember(field);
5432 });
5433
5434 if (!ProcessEntities(BaseRange))
5435 return;
5436
5437 if (!ProcessEntities(FieldRange))
5438 return;
5439
5440 ResultType = Entity.getType();
5441 }
5442
5443 // Not all of the args have been processed, so there must've been more args
5444 // than were required to initialize the element.
5445 if (ArgIndexToProcess < Args.size()) {
5446 Sequence.SetFailed(InitializationSequence::FK_ParenthesizedListInitFailed);
5447 if (!VerifyOnly) {
5448 QualType T = Entity.getType();
5449 int InitKind = T->isArrayType() ? 0 : T->isUnionType() ? 3 : 4;
5450 SourceRange ExcessInitSR(Args[ArgIndexToProcess]->getBeginLoc(),
5451 Args.back()->getEndLoc());
5452 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5453 << InitKind << ExcessInitSR;
5454 }
5455 return;
5456 }
5457
5458 if (VerifyOnly) {
5459 Sequence.setSequenceKind(InitializationSequence::NormalSequence);
5460 Sequence.AddParenthesizedListInitStep(Entity.getType());
5461 } else if (Result) {
5462 SourceRange SR = Kind.getParenOrBraceRange();
5463 auto *CPLIE = CXXParenListInitExpr::Create(
5464 S.getASTContext(), InitExprs, ResultType, Args.size(),
5465 Kind.getLocation(), SR.getBegin(), SR.getEnd());
5466 if (ArrayFiller)
5467 CPLIE->setArrayFiller(ArrayFiller);
5468 if (InitializedFieldInUnion)
5469 CPLIE->setInitializedFieldInUnion(InitializedFieldInUnion);
5470 *Result = CPLIE;
5471 S.Diag(Kind.getLocation(),
5472 diag::warn_cxx17_compat_aggregate_init_paren_list)
5473 << Kind.getLocation() << SR << ResultType;
5474 }
5475
5476 return;
5477}
5478
5479/// Attempt a user-defined conversion between two types (C++ [dcl.init]),
5480/// which enumerates all conversion functions and performs overload resolution
5481/// to select the best.
5482static void TryUserDefinedConversion(Sema &S,
5483 QualType DestType,
5484 const InitializationKind &Kind,
5485 Expr *Initializer,
5486 InitializationSequence &Sequence,
5487 bool TopLevelOfInitList) {
5488 assert(!DestType->isReferenceType() && "References are handled elsewhere")(static_cast <bool> (!DestType->isReferenceType() &&
"References are handled elsewhere") ? void (0) : __assert_fail
("!DestType->isReferenceType() && \"References are handled elsewhere\""
, "clang/lib/Sema/SemaInit.cpp", 5488, __extension__ __PRETTY_FUNCTION__
))
;
5489 QualType SourceType = Initializer->getType();
5490 assert((DestType->isRecordType() || SourceType->isRecordType()) &&(static_cast <bool> ((DestType->isRecordType() || SourceType
->isRecordType()) && "Must have a class type to perform a user-defined conversion"
) ? void (0) : __assert_fail ("(DestType->isRecordType() || SourceType->isRecordType()) && \"Must have a class type to perform a user-defined conversion\""
, "clang/lib/Sema/SemaInit.cpp", 5491, __extension__ __PRETTY_FUNCTION__
))
5491 "Must have a class type to perform a user-defined conversion")(static_cast <bool> ((DestType->isRecordType() || SourceType
->isRecordType()) && "Must have a class type to perform a user-defined conversion"
) ? void (0) : __assert_fail ("(DestType->isRecordType() || SourceType->isRecordType()) && \"Must have a class type to perform a user-defined conversion\""
, "clang/lib/Sema/SemaInit.cpp", 5491, __extension__ __PRETTY_FUNCTION__
))
;
5492
5493 // Build the candidate set directly in the initialization sequence
5494 // structure, so that it will persist if we fail.
5495 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
5496 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
5497 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
5498
5499 // Determine whether we are allowed to call explicit constructors or
5500 // explicit conversion operators.
5501 bool AllowExplicit = Kind.AllowExplicit();
5502
5503 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
5504 // The type we're converting to is a class type. Enumerate its constructors
5505 // to see if there is a suitable conversion.
5506 CXXRecordDecl *DestRecordDecl
5507 = cast<CXXRecordDecl>(DestRecordType->getDecl());
5508
5509 // Try to complete the type we're converting to.
5510 if (S.isCompleteType(Kind.getLocation(), DestType)) {
5511 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
5512 auto Info = getConstructorInfo(D);
5513 if (!Info.Constructor)
5514 continue;
5515
5516 if (!Info.Constructor->isInvalidDecl() &&
5517 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
5518 if (Info.ConstructorTmpl)
5519 S.AddTemplateOverloadCandidate(
5520 Info.ConstructorTmpl, Info.FoundDecl,
5521 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
5522 /*SuppressUserConversions=*/true,
5523 /*PartialOverloading*/ false, AllowExplicit);
5524 else
5525 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
5526 Initializer, CandidateSet,
5527 /*SuppressUserConversions=*/true,
5528 /*PartialOverloading*/ false, AllowExplicit);
5529 }
5530 }
5531 }
5532 }
5533
5534 SourceLocation DeclLoc = Initializer->getBeginLoc();
5535
5536 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
5537 // The type we're converting from is a class type, enumerate its conversion
5538 // functions.
5539
5540 // We can only enumerate the conversion functions for a complete type; if
5541 // the type isn't complete, simply skip this step.
5542 if (S.isCompleteType(DeclLoc, SourceType)) {
5543 CXXRecordDecl *SourceRecordDecl
5544 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
5545
5546 const auto &Conversions =
5547 SourceRecordDecl->getVisibleConversionFunctions();
5548 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5549 NamedDecl *D = *I;
5550 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
5551 if (isa<UsingShadowDecl>(D))
5552 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5553
5554 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5555 CXXConversionDecl *Conv;
5556 if (ConvTemplate)
5557 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5558 else
5559 Conv = cast<CXXConversionDecl>(D);
5560
5561 if (ConvTemplate)
5562 S.AddTemplateConversionCandidate(
5563 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
5564 CandidateSet, AllowExplicit, AllowExplicit);
5565 else
5566 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
5567 DestType, CandidateSet, AllowExplicit,
5568 AllowExplicit);
5569 }
5570 }
5571 }
5572
5573 // Perform overload resolution. If it fails, return the failed result.
5574 OverloadCandidateSet::iterator Best;
5575 if (OverloadingResult Result
5576 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5577 Sequence.SetOverloadFailure(
5578 InitializationSequence::FK_UserConversionOverloadFailed, Result);
5579
5580 // [class.copy.elision]p3:
5581 // In some copy-initialization contexts, a two-stage overload resolution
5582 // is performed.
5583 // If the first overload resolution selects a deleted function, we also
5584 // need the initialization sequence to decide whether to perform the second
5585 // overload resolution.
5586 if (!(Result == OR_Deleted &&
5587 Kind.getKind() == InitializationKind::IK_Copy))
5588 return;
5589 }
5590
5591 FunctionDecl *Function = Best->Function;
5592 Function->setReferenced();
5593 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5594
5595 if (isa<CXXConstructorDecl>(Function)) {
5596 // Add the user-defined conversion step. Any cv-qualification conversion is
5597 // subsumed by the initialization. Per DR5, the created temporary is of the
5598 // cv-unqualified type of the destination.
5599 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
5600 DestType.getUnqualifiedType(),
5601 HadMultipleCandidates);
5602
5603 // C++14 and before:
5604 // - if the function is a constructor, the call initializes a temporary
5605 // of the cv-unqualified version of the destination type. The [...]
5606 // temporary [...] is then used to direct-initialize, according to the
5607 // rules above, the object that is the destination of the
5608 // copy-initialization.
5609 // Note that this just performs a simple object copy from the temporary.
5610 //
5611 // C++17:
5612 // - if the function is a constructor, the call is a prvalue of the
5613 // cv-unqualified version of the destination type whose return object
5614 // is initialized by the constructor. The call is used to
5615 // direct-initialize, according to the rules above, the object that
5616 // is the destination of the copy-initialization.
5617 // Therefore we need to do nothing further.
5618 //
5619 // FIXME: Mark this copy as extraneous.
5620 if (!S.getLangOpts().CPlusPlus17)
5621 Sequence.AddFinalCopy(DestType);
5622 else if (DestType.hasQualifiers())
5623 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
5624 return;
5625 }
5626
5627 // Add the user-defined conversion step that calls the conversion function.
5628 QualType ConvType = Function->getCallResultType();
5629 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
5630 HadMultipleCandidates);
5631
5632 if (ConvType->getAs<RecordType>()) {
5633 // The call is used to direct-initialize [...] the object that is the
5634 // destination of the copy-initialization.
5635 //
5636 // In C++17, this does not call a constructor if we enter /17.6.1:
5637 // - If the initializer expression is a prvalue and the cv-unqualified
5638 // version of the source type is the same as the class of the
5639 // destination [... do not make an extra copy]
5640 //
5641 // FIXME: Mark this copy as extraneous.
5642 if (!S.getLangOpts().CPlusPlus17 ||
5643 Function->getReturnType()->isReferenceType() ||
5644 !S.Context.hasSameUnqualifiedType(ConvType, DestType))
5645 Sequence.AddFinalCopy(DestType);
5646 else if (!S.Context.hasSameType(ConvType, DestType))
5647 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
5648 return;
5649 }
5650
5651 // If the conversion following the call to the conversion function
5652 // is interesting, add it as a separate step.
5653 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
5654 Best->FinalConversion.Third) {
5655 ImplicitConversionSequence ICS;
5656 ICS.setStandard();
5657 ICS.Standard = Best->FinalConversion;
5658 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
5659 }
5660}
5661
5662/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
5663/// a function with a pointer return type contains a 'return false;' statement.
5664/// In C++11, 'false' is not a null pointer, so this breaks the build of any
5665/// code using that header.
5666///
5667/// Work around this by treating 'return false;' as zero-initializing the result
5668/// if it's used in a pointer-returning function in a system header.
5669static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
5670 const InitializedEntity &Entity,
5671 const Expr *Init) {
5672 return S.getLangOpts().CPlusPlus11 &&
5673 Entity.getKind() == InitializedEntity::EK_Result &&
5674 Entity.getType()->isPointerType() &&
5675 isa<CXXBoolLiteralExpr>(Init) &&
5676 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
5677 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
5678}
5679
5680/// The non-zero enum values here are indexes into diagnostic alternatives.
5681enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
5682
5683/// Determines whether this expression is an acceptable ICR source.
5684static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
5685 bool isAddressOf, bool &isWeakAccess) {
5686 // Skip parens.
5687 e = e->IgnoreParens();
5688
5689 // Skip address-of nodes.
5690 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
5691 if (op->getOpcode() == UO_AddrOf)
5692 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
5693 isWeakAccess);
5694
5695 // Skip certain casts.
5696 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
5697 switch (ce->getCastKind()) {
5698 case CK_Dependent:
5699 case CK_BitCast:
5700 case CK_LValueBitCast:
5701 case CK_NoOp:
5702 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
5703
5704 case CK_ArrayToPointerDecay:
5705 return IIK_nonscalar;
5706
5707 case CK_NullToPointer:
5708 return IIK_okay;
5709
5710 default:
5711 break;
5712 }
5713
5714 // If we have a declaration reference, it had better be a local variable.
5715 } else if (isa<DeclRefExpr>(e)) {
5716 // set isWeakAccess to true, to mean that there will be an implicit
5717 // load which requires a cleanup.
5718 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
5719 isWeakAccess = true;
5720
5721 if (!isAddressOf) return IIK_nonlocal;
5722
5723 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
5724 if (!var) return IIK_nonlocal;
5725
5726 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
5727
5728 // If we have a conditional operator, check both sides.
5729 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
5730 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
5731 isWeakAccess))
5732 return iik;
5733
5734 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
5735
5736 // These are never scalar.
5737 } else if (isa<ArraySubscriptExpr>(e)) {
5738 return IIK_nonscalar;
5739
5740 // Otherwise, it needs to be a null pointer constant.
5741 } else {
5742 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
5743 ? IIK_okay : IIK_nonlocal);
5744 }
5745
5746 return IIK_nonlocal;
5747}
5748
5749/// Check whether the given expression is a valid operand for an
5750/// indirect copy/restore.
5751static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
5752 assert(src->isPRValue())(static_cast <bool> (src->isPRValue()) ? void (0) : __assert_fail
("src->isPRValue()", "clang/lib/Sema/SemaInit.cpp", 5752,
__extension__ __PRETTY_FUNCTION__))
;
5753 bool isWeakAccess = false;
5754 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
5755 // If isWeakAccess to true, there will be an implicit
5756 // load which requires a cleanup.
5757 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
5758 S.Cleanup.setExprNeedsCleanups(true);
5759
5760 if (iik == IIK_okay) return;
5761
5762 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
5763 << ((unsigned) iik - 1) // shift index into diagnostic explanations
5764 << src->getSourceRange();
5765}
5766
5767/// Determine whether we have compatible array types for the
5768/// purposes of GNU by-copy array initialization.
5769static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
5770 const ArrayType *Source) {
5771 // If the source and destination array types are equivalent, we're
5772 // done.
5773 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
5774 return true;
5775
5776 // Make sure that the element types are the same.
5777 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
5778 return false;
5779
5780 // The only mismatch we allow is when the destination is an
5781 // incomplete array type and the source is a constant array type.
5782 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
5783}
5784
5785static bool tryObjCWritebackConversion(Sema &S,
5786 InitializationSequence &Sequence,
5787 const InitializedEntity &Entity,
5788 Expr *Initializer) {
5789 bool ArrayDecay = false;
5790 QualType ArgType = Initializer->getType();
5791 QualType ArgPointee;
5792 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
5793 ArrayDecay = true;
5794 ArgPointee = ArgArrayType->getElementType();
5795 ArgType = S.Context.getPointerType(ArgPointee);
5796 }
5797
5798 // Handle write-back conversion.
5799 QualType ConvertedArgType;
5800 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
5801 ConvertedArgType))
5802 return false;
5803
5804 // We should copy unless we're passing to an argument explicitly
5805 // marked 'out'.
5806 bool ShouldCopy = true;
5807 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5808 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5809
5810 // Do we need an lvalue conversion?
5811 if (ArrayDecay || Initializer->isGLValue()) {
5812 ImplicitConversionSequence ICS;
5813 ICS.setStandard();
5814 ICS.Standard.setAsIdentityConversion();
5815
5816 QualType ResultType;
5817 if (ArrayDecay) {
5818 ICS.Standard.First = ICK_Array_To_Pointer;
5819 ResultType = S.Context.getPointerType(ArgPointee);
5820 } else {
5821 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
5822 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
5823 }
5824
5825 Sequence.AddConversionSequenceStep(ICS, ResultType);
5826 }
5827
5828 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
5829 return true;
5830}
5831
5832static bool TryOCLSamplerInitialization(Sema &S,
5833 InitializationSequence &Sequence,
5834 QualType DestType,
5835 Expr *Initializer) {
5836 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
5837 (!Initializer->isIntegerConstantExpr(S.Context) &&
5838 !Initializer->getType()->isSamplerT()))
5839 return false;
5840
5841 Sequence.AddOCLSamplerInitStep(DestType);
5842 return true;
5843}
5844
5845static bool IsZeroInitializer(Expr *Initializer, Sema &S) {
5846 return Initializer->isIntegerConstantExpr(S.getASTContext()) &&
5847 (Initializer->EvaluateKnownConstInt(S.getASTContext()) == 0);
5848}
5849
5850static bool TryOCLZeroOpaqueTypeInitialization(Sema &S,
5851 InitializationSequence &Sequence,
5852 QualType DestType,
5853 Expr *Initializer) {
5854 if (!S.getLangOpts().OpenCL)
5855 return false;
5856
5857 //
5858 // OpenCL 1.2 spec, s6.12.10
5859 //
5860 // The event argument can also be used to associate the
5861 // async_work_group_copy with a previous async copy allowing
5862 // an event to be shared by multiple async copies; otherwise
5863 // event should be zero.
5864 //
5865 if (DestType->isEventT() || DestType->isQueueT()) {
5866 if (!IsZeroInitializer(Initializer, S))
5867 return false;
5868
5869 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
5870 return true;
5871 }
5872
5873 // We should allow zero initialization for all types defined in the
5874 // cl_intel_device_side_avc_motion_estimation extension, except
5875 // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t.
5876 if (S.getOpenCLOptions().isAvailableOption(
5877 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()) &&
5878 DestType->isOCLIntelSubgroupAVCType()) {
5879 if (DestType->isOCLIntelSubgroupAVCMcePayloadType() ||
5880 DestType->isOCLIntelSubgroupAVCMceResultType())
5881 return false;
5882 if (!IsZeroInitializer(Initializer, S))
5883 return false;
5884
5885 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
5886 return true;
5887 }
5888
5889 return false;
5890}
5891
5892InitializationSequence::InitializationSequence(
5893 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
5894 MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid)
5895 : FailedOverloadResult(OR_Success),
5896 FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
5897 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
5898 TreatUnavailableAsInvalid);
5899}
5900
5901/// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
5902/// address of that function, this returns true. Otherwise, it returns false.
5903static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
5904 auto *DRE = dyn_cast<DeclRefExpr>(E);
5905 if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
5906 return false;
5907
5908 return !S.checkAddressOfFunctionIsAvailable(
5909 cast<FunctionDecl>(DRE->getDecl()));
5910}
5911
5912/// Determine whether we can perform an elementwise array copy for this kind
5913/// of entity.
5914static bool canPerformArrayCopy(const InitializedEntity &Entity) {
5915 switch (Entity.getKind()) {
5916 case InitializedEntity::EK_LambdaCapture:
5917 // C++ [expr.prim.lambda]p24:
5918 // For arra