Bug Summary

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