Bug Summary

File:clang/lib/Sema/SemaInit.cpp
Warning:line 5946, 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 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include -I /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/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/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/llvm-12/lib/clang/12.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-12~++20200806111125+5446ec85070/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070=. -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 -o /tmp/scan-build-2020-08-06-171148-17323-1 -x c++ /build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/Sema/SemaInit.cpp

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