Bug Summary

File:clang/lib/Sema/SemaInit.cpp
Warning:line 5307, column 48
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -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 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-11/lib/clang/11.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-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/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-11/lib/clang/11.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-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaInit.cpp

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