Bug Summary

File:clang/lib/Sema/SemaInit.cpp
Warning:line 6015, column 16
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 -disable-llvm-verifier -discard-value-names -main-file-name SemaInit.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -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 -fhalf-no-semantic-interposition -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/build-llvm/tools/clang/lib/Sema -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D CLANG_ROUND_TRIP_CC1_ARGS=ON -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../x86_64-linux-gnu/include -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -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-2021-04-05-202135-9119-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaInit.cpp

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