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 "CheckExprLifetime.h" |
14 | #include "clang/AST/ASTContext.h" |
15 | #include "clang/AST/DeclObjC.h" |
16 | #include "clang/AST/Expr.h" |
17 | #include "clang/AST/ExprCXX.h" |
18 | #include "clang/AST/ExprObjC.h" |
19 | #include "clang/AST/IgnoreExpr.h" |
20 | #include "clang/AST/TypeLoc.h" |
21 | #include "clang/Basic/SourceManager.h" |
22 | #include "clang/Basic/Specifiers.h" |
23 | #include "clang/Basic/TargetInfo.h" |
24 | #include "clang/Lex/Preprocessor.h" |
25 | #include "clang/Sema/Designator.h" |
26 | #include "clang/Sema/EnterExpressionEvaluationContext.h" |
27 | #include "clang/Sema/Initialization.h" |
28 | #include "clang/Sema/Lookup.h" |
29 | #include "clang/Sema/Ownership.h" |
30 | #include "clang/Sema/SemaHLSL.h" |
31 | #include "clang/Sema/SemaObjC.h" |
32 | #include "llvm/ADT/APInt.h" |
33 | #include "llvm/ADT/FoldingSet.h" |
34 | #include "llvm/ADT/PointerIntPair.h" |
35 | #include "llvm/ADT/SmallVector.h" |
36 | #include "llvm/ADT/StringExtras.h" |
37 | #include "llvm/Support/ErrorHandling.h" |
38 | #include "llvm/Support/raw_ostream.h" |
39 | |
40 | using namespace clang; |
41 | |
42 | //===----------------------------------------------------------------------===// |
43 | // Sema Initialization Checking |
44 | //===----------------------------------------------------------------------===// |
45 | |
46 | /// Check whether T is compatible with a wide character type (wchar_t, |
47 | /// char16_t or char32_t). |
48 | static bool IsWideCharCompatible(QualType T, ASTContext &Context) { |
49 | if (Context.typesAreCompatible(T1: Context.getWideCharType(), T2: T)) |
50 | return true; |
51 | if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) { |
52 | return Context.typesAreCompatible(T1: Context.Char16Ty, T2: T) || |
53 | Context.typesAreCompatible(T1: Context.Char32Ty, T2: T); |
54 | } |
55 | return false; |
56 | } |
57 | |
58 | enum StringInitFailureKind { |
59 | SIF_None, |
60 | SIF_NarrowStringIntoWideChar, |
61 | SIF_WideStringIntoChar, |
62 | SIF_IncompatWideStringIntoWideChar, |
63 | SIF_UTF8StringIntoPlainChar, |
64 | SIF_PlainStringIntoUTF8Char, |
65 | SIF_Other |
66 | }; |
67 | |
68 | /// Check whether the array of type AT can be initialized by the Init |
69 | /// expression by means of string initialization. Returns SIF_None if so, |
70 | /// otherwise returns a StringInitFailureKind that describes why the |
71 | /// initialization would not work. |
72 | static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT, |
73 | ASTContext &Context) { |
74 | if (!isa<ConstantArrayType>(Val: AT) && !isa<IncompleteArrayType>(Val: AT)) |
75 | return SIF_Other; |
76 | |
77 | // See if this is a string literal or @encode. |
78 | Init = Init->IgnoreParens(); |
79 | |
80 | // Handle @encode, which is a narrow string. |
81 | if (isa<ObjCEncodeExpr>(Val: Init) && AT->getElementType()->isCharType()) |
82 | return SIF_None; |
83 | |
84 | // Otherwise we can only handle string literals. |
85 | StringLiteral *SL = dyn_cast<StringLiteral>(Val: Init); |
86 | if (!SL) |
87 | return SIF_Other; |
88 | |
89 | const QualType ElemTy = |
90 | Context.getCanonicalType(T: AT->getElementType()).getUnqualifiedType(); |
91 | |
92 | auto IsCharOrUnsignedChar = [](const QualType &T) { |
93 | const BuiltinType *BT = dyn_cast<BuiltinType>(Val: T.getTypePtr()); |
94 | return BT && BT->isCharType() && BT->getKind() != BuiltinType::SChar; |
95 | }; |
96 | |
97 | switch (SL->getKind()) { |
98 | case StringLiteralKind::UTF8: |
99 | // char8_t array can be initialized with a UTF-8 string. |
100 | // - C++20 [dcl.init.string] (DR) |
101 | // Additionally, an array of char or unsigned char may be initialized |
102 | // by a UTF-8 string literal. |
103 | if (ElemTy->isChar8Type() || |
104 | (Context.getLangOpts().Char8 && |
105 | IsCharOrUnsignedChar(ElemTy.getCanonicalType()))) |
106 | return SIF_None; |
107 | [[fallthrough]]; |
108 | case StringLiteralKind::Ordinary: |
109 | case StringLiteralKind::Binary: |
110 | // char array can be initialized with a narrow string. |
111 | // Only allow char x[] = "foo"; not char x[] = L"foo"; |
112 | if (ElemTy->isCharType()) |
113 | return (SL->getKind() == StringLiteralKind::UTF8 && |
114 | Context.getLangOpts().Char8) |
115 | ? SIF_UTF8StringIntoPlainChar |
116 | : SIF_None; |
117 | if (ElemTy->isChar8Type()) |
118 | return SIF_PlainStringIntoUTF8Char; |
119 | if (IsWideCharCompatible(T: ElemTy, Context)) |
120 | return SIF_NarrowStringIntoWideChar; |
121 | return SIF_Other; |
122 | // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15: |
123 | // "An array with element type compatible with a qualified or unqualified |
124 | // version of wchar_t, char16_t, or char32_t may be initialized by a wide |
125 | // string literal with the corresponding encoding prefix (L, u, or U, |
126 | // respectively), optionally enclosed in braces. |
127 | case StringLiteralKind::UTF16: |
128 | if (Context.typesAreCompatible(T1: Context.Char16Ty, T2: ElemTy)) |
129 | return SIF_None; |
130 | if (ElemTy->isCharType() || ElemTy->isChar8Type()) |
131 | return SIF_WideStringIntoChar; |
132 | if (IsWideCharCompatible(T: ElemTy, Context)) |
133 | return SIF_IncompatWideStringIntoWideChar; |
134 | return SIF_Other; |
135 | case StringLiteralKind::UTF32: |
136 | if (Context.typesAreCompatible(T1: Context.Char32Ty, T2: ElemTy)) |
137 | return SIF_None; |
138 | if (ElemTy->isCharType() || ElemTy->isChar8Type()) |
139 | return SIF_WideStringIntoChar; |
140 | if (IsWideCharCompatible(T: ElemTy, Context)) |
141 | return SIF_IncompatWideStringIntoWideChar; |
142 | return SIF_Other; |
143 | case StringLiteralKind::Wide: |
144 | if (Context.typesAreCompatible(T1: Context.getWideCharType(), T2: ElemTy)) |
145 | return SIF_None; |
146 | if (ElemTy->isCharType() || ElemTy->isChar8Type()) |
147 | return SIF_WideStringIntoChar; |
148 | if (IsWideCharCompatible(T: ElemTy, Context)) |
149 | return SIF_IncompatWideStringIntoWideChar; |
150 | return SIF_Other; |
151 | case StringLiteralKind::Unevaluated: |
152 | assert(false && "Unevaluated string literal in initialization" ); |
153 | break; |
154 | } |
155 | |
156 | llvm_unreachable("missed a StringLiteral kind?" ); |
157 | } |
158 | |
159 | static StringInitFailureKind IsStringInit(Expr *init, QualType declType, |
160 | ASTContext &Context) { |
161 | const ArrayType *arrayType = Context.getAsArrayType(T: declType); |
162 | if (!arrayType) |
163 | return SIF_Other; |
164 | return IsStringInit(Init: init, AT: arrayType, Context); |
165 | } |
166 | |
167 | bool Sema::IsStringInit(Expr *Init, const ArrayType *AT) { |
168 | return ::IsStringInit(Init, AT, Context) == SIF_None; |
169 | } |
170 | |
171 | /// Update the type of a string literal, including any surrounding parentheses, |
172 | /// to match the type of the object which it is initializing. |
173 | static void updateStringLiteralType(Expr *E, QualType Ty) { |
174 | while (true) { |
175 | E->setType(Ty); |
176 | E->setValueKind(VK_PRValue); |
177 | if (isa<StringLiteral>(Val: E) || isa<ObjCEncodeExpr>(Val: E)) |
178 | break; |
179 | E = IgnoreParensSingleStep(E); |
180 | } |
181 | } |
182 | |
183 | /// Fix a compound literal initializing an array so it's correctly marked |
184 | /// as an rvalue. |
185 | static void updateGNUCompoundLiteralRValue(Expr *E) { |
186 | while (true) { |
187 | E->setValueKind(VK_PRValue); |
188 | if (isa<CompoundLiteralExpr>(Val: E)) |
189 | break; |
190 | E = IgnoreParensSingleStep(E); |
191 | } |
192 | } |
193 | |
194 | static bool initializingConstexprVariable(const InitializedEntity &Entity) { |
195 | Decl *D = Entity.getDecl(); |
196 | const InitializedEntity *Parent = &Entity; |
197 | |
198 | while (Parent) { |
199 | D = Parent->getDecl(); |
200 | Parent = Parent->getParent(); |
201 | } |
202 | |
203 | if (const auto *VD = dyn_cast_if_present<VarDecl>(Val: D); VD && VD->isConstexpr()) |
204 | return true; |
205 | |
206 | return false; |
207 | } |
208 | |
209 | static void CheckC23ConstexprInitStringLiteral(const StringLiteral *SE, |
210 | Sema &SemaRef, QualType &TT); |
211 | |
212 | static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT, |
213 | Sema &S, const InitializedEntity &Entity, |
214 | bool CheckC23ConstexprInit = false) { |
215 | // Get the length of the string as parsed. |
216 | auto *ConstantArrayTy = |
217 | cast<ConstantArrayType>(Val: Str->getType()->getAsArrayTypeUnsafe()); |
218 | uint64_t StrLength = ConstantArrayTy->getZExtSize(); |
219 | |
220 | if (CheckC23ConstexprInit) |
221 | if (const StringLiteral *SL = dyn_cast<StringLiteral>(Val: Str->IgnoreParens())) |
222 | CheckC23ConstexprInitStringLiteral(SE: SL, SemaRef&: S, TT&: DeclT); |
223 | |
224 | if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(Val: AT)) { |
225 | // C99 6.7.8p14. We have an array of character type with unknown size |
226 | // being initialized to a string literal. |
227 | llvm::APInt ConstVal(32, StrLength); |
228 | // Return a new array type (C99 6.7.8p22). |
229 | DeclT = S.Context.getConstantArrayType( |
230 | EltTy: IAT->getElementType(), ArySize: ConstVal, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0); |
231 | updateStringLiteralType(E: Str, Ty: DeclT); |
232 | return; |
233 | } |
234 | |
235 | const ConstantArrayType *CAT = cast<ConstantArrayType>(Val: AT); |
236 | uint64_t ArrayLen = CAT->getZExtSize(); |
237 | |
238 | // We have an array of character type with known size. However, |
239 | // the size may be smaller or larger than the string we are initializing. |
240 | // FIXME: Avoid truncation for 64-bit length strings. |
241 | if (S.getLangOpts().CPlusPlus) { |
242 | if (StringLiteral *SL = dyn_cast<StringLiteral>(Val: Str->IgnoreParens())) { |
243 | // For Pascal strings it's OK to strip off the terminating null character, |
244 | // so the example below is valid: |
245 | // |
246 | // unsigned char a[2] = "\pa"; |
247 | if (SL->isPascal()) |
248 | StrLength--; |
249 | } |
250 | |
251 | // [dcl.init.string]p2 |
252 | if (StrLength > ArrayLen) |
253 | S.Diag(Loc: Str->getBeginLoc(), |
254 | DiagID: diag::err_initializer_string_for_char_array_too_long) |
255 | << ArrayLen << StrLength << Str->getSourceRange(); |
256 | } else { |
257 | // C99 6.7.8p14. |
258 | if (StrLength - 1 > ArrayLen) |
259 | S.Diag(Loc: Str->getBeginLoc(), |
260 | DiagID: diag::ext_initializer_string_for_char_array_too_long) |
261 | << Str->getSourceRange(); |
262 | else if (StrLength - 1 == ArrayLen) { |
263 | // In C, if the string literal is null-terminated explicitly, e.g., `char |
264 | // a[4] = "ABC\0"`, there should be no warning: |
265 | const auto *SL = dyn_cast<StringLiteral>(Val: Str->IgnoreParens()); |
266 | bool IsSLSafe = SL && SL->getLength() > 0 && |
267 | SL->getCodeUnit(i: SL->getLength() - 1) == 0; |
268 | |
269 | if (!IsSLSafe) { |
270 | // If the entity being initialized has the nonstring attribute, then |
271 | // silence the "missing nonstring" diagnostic. If there's no entity, |
272 | // check whether we're initializing an array of arrays; if so, walk the |
273 | // parents to find an entity. |
274 | auto FindCorrectEntity = |
275 | [](const InitializedEntity *Entity) -> const ValueDecl * { |
276 | while (Entity) { |
277 | if (const ValueDecl *VD = Entity->getDecl()) |
278 | return VD; |
279 | if (!Entity->getType()->isArrayType()) |
280 | return nullptr; |
281 | Entity = Entity->getParent(); |
282 | } |
283 | |
284 | return nullptr; |
285 | }; |
286 | if (const ValueDecl *D = FindCorrectEntity(&Entity); |
287 | !D || !D->hasAttr<NonStringAttr>()) |
288 | S.Diag( |
289 | Loc: Str->getBeginLoc(), |
290 | DiagID: diag:: |
291 | warn_initializer_string_for_char_array_too_long_no_nonstring) |
292 | << ArrayLen << StrLength << Str->getSourceRange(); |
293 | } |
294 | // Always emit the C++ compatibility diagnostic. |
295 | S.Diag(Loc: Str->getBeginLoc(), |
296 | DiagID: diag::warn_initializer_string_for_char_array_too_long_for_cpp) |
297 | << ArrayLen << StrLength << Str->getSourceRange(); |
298 | } |
299 | } |
300 | |
301 | // Set the type to the actual size that we are initializing. If we have |
302 | // something like: |
303 | // char x[1] = "foo"; |
304 | // then this will set the string literal's type to char[1]. |
305 | updateStringLiteralType(E: Str, Ty: DeclT); |
306 | } |
307 | |
308 | void emitUninitializedExplicitInitFields(Sema &S, const RecordDecl *R) { |
309 | for (const FieldDecl *Field : R->fields()) { |
310 | if (Field->hasAttr<ExplicitInitAttr>()) |
311 | S.Diag(Loc: Field->getLocation(), DiagID: diag::note_entity_declared_at) << Field; |
312 | } |
313 | } |
314 | |
315 | //===----------------------------------------------------------------------===// |
316 | // Semantic checking for initializer lists. |
317 | //===----------------------------------------------------------------------===// |
318 | |
319 | namespace { |
320 | |
321 | /// Semantic checking for initializer lists. |
322 | /// |
323 | /// The InitListChecker class contains a set of routines that each |
324 | /// handle the initialization of a certain kind of entity, e.g., |
325 | /// arrays, vectors, struct/union types, scalars, etc. The |
326 | /// InitListChecker itself performs a recursive walk of the subobject |
327 | /// structure of the type to be initialized, while stepping through |
328 | /// the initializer list one element at a time. The IList and Index |
329 | /// parameters to each of the Check* routines contain the active |
330 | /// (syntactic) initializer list and the index into that initializer |
331 | /// list that represents the current initializer. Each routine is |
332 | /// responsible for moving that Index forward as it consumes elements. |
333 | /// |
334 | /// Each Check* routine also has a StructuredList/StructuredIndex |
335 | /// arguments, which contains the current "structured" (semantic) |
336 | /// initializer list and the index into that initializer list where we |
337 | /// are copying initializers as we map them over to the semantic |
338 | /// list. Once we have completed our recursive walk of the subobject |
339 | /// structure, we will have constructed a full semantic initializer |
340 | /// list. |
341 | /// |
342 | /// C99 designators cause changes in the initializer list traversal, |
343 | /// because they make the initialization "jump" into a specific |
344 | /// subobject and then continue the initialization from that |
345 | /// point. CheckDesignatedInitializer() recursively steps into the |
346 | /// designated subobject and manages backing out the recursion to |
347 | /// initialize the subobjects after the one designated. |
348 | /// |
349 | /// If an initializer list contains any designators, we build a placeholder |
350 | /// structured list even in 'verify only' mode, so that we can track which |
351 | /// elements need 'empty' initializtion. |
352 | class InitListChecker { |
353 | Sema &SemaRef; |
354 | bool hadError = false; |
355 | bool VerifyOnly; // No diagnostics. |
356 | bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode. |
357 | bool InOverloadResolution; |
358 | InitListExpr *FullyStructuredList = nullptr; |
359 | NoInitExpr *DummyExpr = nullptr; |
360 | SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr; |
361 | EmbedExpr *CurEmbed = nullptr; // Save current embed we're processing. |
362 | unsigned CurEmbedIndex = 0; |
363 | |
364 | NoInitExpr *getDummyInit() { |
365 | if (!DummyExpr) |
366 | DummyExpr = new (SemaRef.Context) NoInitExpr(SemaRef.Context.VoidTy); |
367 | return DummyExpr; |
368 | } |
369 | |
370 | void CheckImplicitInitList(const InitializedEntity &Entity, |
371 | InitListExpr *ParentIList, QualType T, |
372 | unsigned &Index, InitListExpr *StructuredList, |
373 | unsigned &StructuredIndex); |
374 | void CheckExplicitInitList(const InitializedEntity &Entity, |
375 | InitListExpr *IList, QualType &T, |
376 | InitListExpr *StructuredList, |
377 | bool TopLevelObject = false); |
378 | void CheckListElementTypes(const InitializedEntity &Entity, |
379 | InitListExpr *IList, QualType &DeclType, |
380 | bool SubobjectIsDesignatorContext, |
381 | unsigned &Index, |
382 | InitListExpr *StructuredList, |
383 | unsigned &StructuredIndex, |
384 | bool TopLevelObject = false); |
385 | void CheckSubElementType(const InitializedEntity &Entity, |
386 | InitListExpr *IList, QualType ElemType, |
387 | unsigned &Index, |
388 | InitListExpr *StructuredList, |
389 | unsigned &StructuredIndex, |
390 | bool DirectlyDesignated = false); |
391 | void CheckComplexType(const InitializedEntity &Entity, |
392 | InitListExpr *IList, QualType DeclType, |
393 | unsigned &Index, |
394 | InitListExpr *StructuredList, |
395 | unsigned &StructuredIndex); |
396 | void CheckScalarType(const InitializedEntity &Entity, |
397 | InitListExpr *IList, QualType DeclType, |
398 | unsigned &Index, |
399 | InitListExpr *StructuredList, |
400 | unsigned &StructuredIndex); |
401 | void CheckReferenceType(const InitializedEntity &Entity, |
402 | InitListExpr *IList, QualType DeclType, |
403 | unsigned &Index, |
404 | InitListExpr *StructuredList, |
405 | unsigned &StructuredIndex); |
406 | void CheckVectorType(const InitializedEntity &Entity, |
407 | InitListExpr *IList, QualType DeclType, unsigned &Index, |
408 | InitListExpr *StructuredList, |
409 | unsigned &StructuredIndex); |
410 | void CheckStructUnionTypes(const InitializedEntity &Entity, |
411 | InitListExpr *IList, QualType DeclType, |
412 | CXXRecordDecl::base_class_const_range Bases, |
413 | RecordDecl::field_iterator Field, |
414 | bool SubobjectIsDesignatorContext, unsigned &Index, |
415 | InitListExpr *StructuredList, |
416 | unsigned &StructuredIndex, |
417 | bool TopLevelObject = false); |
418 | void CheckArrayType(const InitializedEntity &Entity, |
419 | InitListExpr *IList, QualType &DeclType, |
420 | llvm::APSInt elementIndex, |
421 | bool SubobjectIsDesignatorContext, unsigned &Index, |
422 | InitListExpr *StructuredList, |
423 | unsigned &StructuredIndex); |
424 | bool CheckDesignatedInitializer(const InitializedEntity &Entity, |
425 | InitListExpr *IList, DesignatedInitExpr *DIE, |
426 | unsigned DesigIdx, |
427 | QualType &CurrentObjectType, |
428 | RecordDecl::field_iterator *NextField, |
429 | llvm::APSInt *NextElementIndex, |
430 | unsigned &Index, |
431 | InitListExpr *StructuredList, |
432 | unsigned &StructuredIndex, |
433 | bool FinishSubobjectInit, |
434 | bool TopLevelObject); |
435 | InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, |
436 | QualType CurrentObjectType, |
437 | InitListExpr *StructuredList, |
438 | unsigned StructuredIndex, |
439 | SourceRange InitRange, |
440 | bool IsFullyOverwritten = false); |
441 | void UpdateStructuredListElement(InitListExpr *StructuredList, |
442 | unsigned &StructuredIndex, |
443 | Expr *expr); |
444 | InitListExpr *createInitListExpr(QualType CurrentObjectType, |
445 | SourceRange InitRange, |
446 | unsigned ExpectedNumInits); |
447 | int numArrayElements(QualType DeclType); |
448 | int numStructUnionElements(QualType DeclType); |
449 | static RecordDecl *getRecordDecl(QualType DeclType); |
450 | |
451 | ExprResult PerformEmptyInit(SourceLocation Loc, |
452 | const InitializedEntity &Entity); |
453 | |
454 | /// Diagnose that OldInit (or part thereof) has been overridden by NewInit. |
455 | void diagnoseInitOverride(Expr *OldInit, SourceRange NewInitRange, |
456 | bool UnionOverride = false, |
457 | bool FullyOverwritten = true) { |
458 | // Overriding an initializer via a designator is valid with C99 designated |
459 | // initializers, but ill-formed with C++20 designated initializers. |
460 | unsigned DiagID = |
461 | SemaRef.getLangOpts().CPlusPlus |
462 | ? (UnionOverride ? diag::ext_initializer_union_overrides |
463 | : diag::ext_initializer_overrides) |
464 | : diag::warn_initializer_overrides; |
465 | |
466 | if (InOverloadResolution && SemaRef.getLangOpts().CPlusPlus) { |
467 | // In overload resolution, we have to strictly enforce the rules, and so |
468 | // don't allow any overriding of prior initializers. This matters for a |
469 | // case such as: |
470 | // |
471 | // union U { int a, b; }; |
472 | // struct S { int a, b; }; |
473 | // void f(U), f(S); |
474 | // |
475 | // Here, f({.a = 1, .b = 2}) is required to call the struct overload. For |
476 | // consistency, we disallow all overriding of prior initializers in |
477 | // overload resolution, not only overriding of union members. |
478 | hadError = true; |
479 | } else if (OldInit->getType().isDestructedType() && !FullyOverwritten) { |
480 | // If we'll be keeping around the old initializer but overwriting part of |
481 | // the object it initialized, and that object is not trivially |
482 | // destructible, this can leak. Don't allow that, not even as an |
483 | // extension. |
484 | // |
485 | // FIXME: It might be reasonable to allow this in cases where the part of |
486 | // the initializer that we're overriding has trivial destruction. |
487 | DiagID = diag::err_initializer_overrides_destructed; |
488 | } else if (!OldInit->getSourceRange().isValid()) { |
489 | // We need to check on source range validity because the previous |
490 | // initializer does not have to be an explicit initializer. e.g., |
491 | // |
492 | // struct P { int a, b; }; |
493 | // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 }; |
494 | // |
495 | // There is an overwrite taking place because the first braced initializer |
496 | // list "{ .a = 2 }" already provides value for .p.b (which is zero). |
497 | // |
498 | // Such overwrites are harmless, so we don't diagnose them. (Note that in |
499 | // C++, this cannot be reached unless we've already seen and diagnosed a |
500 | // different conformance issue, such as a mixture of designated and |
501 | // non-designated initializers or a multi-level designator.) |
502 | return; |
503 | } |
504 | |
505 | if (!VerifyOnly) { |
506 | SemaRef.Diag(Loc: NewInitRange.getBegin(), DiagID) |
507 | << NewInitRange << FullyOverwritten << OldInit->getType(); |
508 | SemaRef.Diag(Loc: OldInit->getBeginLoc(), DiagID: diag::note_previous_initializer) |
509 | << (OldInit->HasSideEffects(Ctx: SemaRef.Context) && FullyOverwritten) |
510 | << OldInit->getSourceRange(); |
511 | } |
512 | } |
513 | |
514 | // Explanation on the "FillWithNoInit" mode: |
515 | // |
516 | // Assume we have the following definitions (Case#1): |
517 | // struct P { char x[6][6]; } xp = { .x[1] = "bar" }; |
518 | // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' }; |
519 | // |
520 | // l.lp.x[1][0..1] should not be filled with implicit initializers because the |
521 | // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf". |
522 | // |
523 | // But if we have (Case#2): |
524 | // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } }; |
525 | // |
526 | // l.lp.x[1][0..1] are implicitly initialized and do not use values from the |
527 | // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0". |
528 | // |
529 | // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes" |
530 | // in the InitListExpr, the "holes" in Case#1 are filled not with empty |
531 | // initializers but with special "NoInitExpr" place holders, which tells the |
532 | // CodeGen not to generate any initializers for these parts. |
533 | void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base, |
534 | const InitializedEntity &ParentEntity, |
535 | InitListExpr *ILE, bool &RequiresSecondPass, |
536 | bool FillWithNoInit); |
537 | void FillInEmptyInitForField(unsigned Init, FieldDecl *Field, |
538 | const InitializedEntity &ParentEntity, |
539 | InitListExpr *ILE, bool &RequiresSecondPass, |
540 | bool FillWithNoInit = false); |
541 | void FillInEmptyInitializations(const InitializedEntity &Entity, |
542 | InitListExpr *ILE, bool &RequiresSecondPass, |
543 | InitListExpr *OuterILE, unsigned OuterIndex, |
544 | bool FillWithNoInit = false); |
545 | bool CheckFlexibleArrayInit(const InitializedEntity &Entity, |
546 | Expr *InitExpr, FieldDecl *Field, |
547 | bool TopLevelObject); |
548 | void CheckEmptyInitializable(const InitializedEntity &Entity, |
549 | SourceLocation Loc); |
550 | |
551 | Expr *HandleEmbed(EmbedExpr *Embed, const InitializedEntity &Entity) { |
552 | Expr *Result = nullptr; |
553 | // Undrestand which part of embed we'd like to reference. |
554 | if (!CurEmbed) { |
555 | CurEmbed = Embed; |
556 | CurEmbedIndex = 0; |
557 | } |
558 | // Reference just one if we're initializing a single scalar. |
559 | uint64_t ElsCount = 1; |
560 | // Otherwise try to fill whole array with embed data. |
561 | if (Entity.getKind() == InitializedEntity::EK_ArrayElement) { |
562 | unsigned ArrIndex = Entity.getElementIndex(); |
563 | auto *AType = |
564 | SemaRef.Context.getAsArrayType(T: Entity.getParent()->getType()); |
565 | assert(AType && "expected array type when initializing array" ); |
566 | ElsCount = Embed->getDataElementCount(); |
567 | if (const auto *CAType = dyn_cast<ConstantArrayType>(Val: AType)) |
568 | ElsCount = std::min(a: CAType->getSize().getZExtValue() - ArrIndex, |
569 | b: ElsCount - CurEmbedIndex); |
570 | if (ElsCount == Embed->getDataElementCount()) { |
571 | CurEmbed = nullptr; |
572 | CurEmbedIndex = 0; |
573 | return Embed; |
574 | } |
575 | } |
576 | |
577 | Result = new (SemaRef.Context) |
578 | EmbedExpr(SemaRef.Context, Embed->getLocation(), Embed->getData(), |
579 | CurEmbedIndex, ElsCount); |
580 | CurEmbedIndex += ElsCount; |
581 | if (CurEmbedIndex >= Embed->getDataElementCount()) { |
582 | CurEmbed = nullptr; |
583 | CurEmbedIndex = 0; |
584 | } |
585 | return Result; |
586 | } |
587 | |
588 | public: |
589 | InitListChecker( |
590 | Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T, |
591 | bool VerifyOnly, bool TreatUnavailableAsInvalid, |
592 | bool InOverloadResolution = false, |
593 | SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr); |
594 | InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL, |
595 | QualType &T, |
596 | SmallVectorImpl<QualType> &AggrDeductionCandidateParamTypes) |
597 | : InitListChecker(S, Entity, IL, T, /*VerifyOnly=*/true, |
598 | /*TreatUnavailableAsInvalid=*/false, |
599 | /*InOverloadResolution=*/false, |
600 | &AggrDeductionCandidateParamTypes) {} |
601 | |
602 | bool HadError() { return hadError; } |
603 | |
604 | // Retrieves the fully-structured initializer list used for |
605 | // semantic analysis and code generation. |
606 | InitListExpr *getFullyStructuredList() const { return FullyStructuredList; } |
607 | }; |
608 | |
609 | } // end anonymous namespace |
610 | |
611 | ExprResult InitListChecker::PerformEmptyInit(SourceLocation Loc, |
612 | const InitializedEntity &Entity) { |
613 | InitializationKind Kind = InitializationKind::CreateValue(InitLoc: Loc, LParenLoc: Loc, RParenLoc: Loc, |
614 | isImplicit: true); |
615 | MultiExprArg SubInit; |
616 | Expr *InitExpr; |
617 | InitListExpr DummyInitList(SemaRef.Context, Loc, {}, Loc); |
618 | |
619 | // C++ [dcl.init.aggr]p7: |
620 | // If there are fewer initializer-clauses in the list than there are |
621 | // members in the aggregate, then each member not explicitly initialized |
622 | // ... |
623 | bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 && |
624 | Entity.getType()->getBaseElementTypeUnsafe()->isRecordType(); |
625 | if (EmptyInitList) { |
626 | // C++1y / DR1070: |
627 | // shall be initialized [...] from an empty initializer list. |
628 | // |
629 | // We apply the resolution of this DR to C++11 but not C++98, since C++98 |
630 | // does not have useful semantics for initialization from an init list. |
631 | // We treat this as copy-initialization, because aggregate initialization |
632 | // always performs copy-initialization on its elements. |
633 | // |
634 | // Only do this if we're initializing a class type, to avoid filling in |
635 | // the initializer list where possible. |
636 | InitExpr = VerifyOnly ? &DummyInitList |
637 | : new (SemaRef.Context) |
638 | InitListExpr(SemaRef.Context, Loc, {}, Loc); |
639 | InitExpr->setType(SemaRef.Context.VoidTy); |
640 | SubInit = InitExpr; |
641 | Kind = InitializationKind::CreateCopy(InitLoc: Loc, EqualLoc: Loc); |
642 | } else { |
643 | // C++03: |
644 | // shall be value-initialized. |
645 | } |
646 | |
647 | InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit); |
648 | // HACK: libstdc++ prior to 4.9 marks the vector default constructor |
649 | // as explicit in _GLIBCXX_DEBUG mode, so recover using the C++03 logic |
650 | // in that case. stlport does so too. |
651 | // Look for std::__debug for libstdc++, and for std:: for stlport. |
652 | // This is effectively a compiler-side implementation of LWG2193. |
653 | if (!InitSeq && EmptyInitList && |
654 | InitSeq.getFailureKind() == |
655 | InitializationSequence::FK_ExplicitConstructor && |
656 | SemaRef.getPreprocessor().NeedsStdLibCxxWorkaroundBefore(FixedVersion: 2014'04'22)) { |
657 | OverloadCandidateSet::iterator Best; |
658 | OverloadingResult O = |
659 | InitSeq.getFailedCandidateSet() |
660 | .BestViableFunction(S&: SemaRef, Loc: Kind.getLocation(), Best); |
661 | (void)O; |
662 | assert(O == OR_Success && "Inconsistent overload resolution" ); |
663 | CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Val: Best->Function); |
664 | CXXRecordDecl *R = CtorDecl->getParent(); |
665 | |
666 | if (CtorDecl->getMinRequiredArguments() == 0 && |
667 | CtorDecl->isExplicit() && R->getDeclName() && |
668 | SemaRef.SourceMgr.isInSystemHeader(Loc: CtorDecl->getLocation())) { |
669 | bool IsInStd = false; |
670 | for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Val: R->getDeclContext()); |
671 | ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(Val: ND->getParent())) { |
672 | if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(NS: ND)) |
673 | IsInStd = true; |
674 | } |
675 | |
676 | if (IsInStd && llvm::StringSwitch<bool>(R->getName()) |
677 | .Cases(S0: "basic_string" , S1: "deque" , S2: "forward_list" , Value: true) |
678 | .Cases(S0: "list" , S1: "map" , S2: "multimap" , S3: "multiset" , Value: true) |
679 | .Cases(S0: "priority_queue" , S1: "queue" , S2: "set" , S3: "stack" , Value: true) |
680 | .Cases(S0: "unordered_map" , S1: "unordered_set" , S2: "vector" , Value: true) |
681 | .Default(Value: false)) { |
682 | InitSeq.InitializeFrom( |
683 | S&: SemaRef, Entity, |
684 | Kind: InitializationKind::CreateValue(InitLoc: Loc, LParenLoc: Loc, RParenLoc: Loc, isImplicit: true), |
685 | Args: MultiExprArg(), /*TopLevelOfInitList=*/false, |
686 | TreatUnavailableAsInvalid); |
687 | // Emit a warning for this. System header warnings aren't shown |
688 | // by default, but people working on system headers should see it. |
689 | if (!VerifyOnly) { |
690 | SemaRef.Diag(Loc: CtorDecl->getLocation(), |
691 | DiagID: diag::warn_invalid_initializer_from_system_header); |
692 | if (Entity.getKind() == InitializedEntity::EK_Member) |
693 | SemaRef.Diag(Loc: Entity.getDecl()->getLocation(), |
694 | DiagID: diag::note_used_in_initialization_here); |
695 | else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) |
696 | SemaRef.Diag(Loc, DiagID: diag::note_used_in_initialization_here); |
697 | } |
698 | } |
699 | } |
700 | } |
701 | if (!InitSeq) { |
702 | if (!VerifyOnly) { |
703 | InitSeq.Diagnose(S&: SemaRef, Entity, Kind, Args: SubInit); |
704 | if (Entity.getKind() == InitializedEntity::EK_Member) |
705 | SemaRef.Diag(Loc: Entity.getDecl()->getLocation(), |
706 | DiagID: diag::note_in_omitted_aggregate_initializer) |
707 | << /*field*/1 << Entity.getDecl(); |
708 | else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) { |
709 | bool IsTrailingArrayNewMember = |
710 | Entity.getParent() && |
711 | Entity.getParent()->isVariableLengthArrayNew(); |
712 | SemaRef.Diag(Loc, DiagID: diag::note_in_omitted_aggregate_initializer) |
713 | << (IsTrailingArrayNewMember ? 2 : /*array element*/0) |
714 | << Entity.getElementIndex(); |
715 | } |
716 | } |
717 | hadError = true; |
718 | return ExprError(); |
719 | } |
720 | |
721 | return VerifyOnly ? ExprResult() |
722 | : InitSeq.Perform(S&: SemaRef, Entity, Kind, Args: SubInit); |
723 | } |
724 | |
725 | void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity, |
726 | SourceLocation Loc) { |
727 | // If we're building a fully-structured list, we'll check this at the end |
728 | // once we know which elements are actually initialized. Otherwise, we know |
729 | // that there are no designators so we can just check now. |
730 | if (FullyStructuredList) |
731 | return; |
732 | PerformEmptyInit(Loc, Entity); |
733 | } |
734 | |
735 | void InitListChecker::FillInEmptyInitForBase( |
736 | unsigned Init, const CXXBaseSpecifier &Base, |
737 | const InitializedEntity &ParentEntity, InitListExpr *ILE, |
738 | bool &RequiresSecondPass, bool FillWithNoInit) { |
739 | InitializedEntity BaseEntity = InitializedEntity::InitializeBase( |
740 | Context&: SemaRef.Context, Base: &Base, IsInheritedVirtualBase: false, Parent: &ParentEntity); |
741 | |
742 | if (Init >= ILE->getNumInits() || !ILE->getInit(Init)) { |
743 | ExprResult BaseInit = FillWithNoInit |
744 | ? new (SemaRef.Context) NoInitExpr(Base.getType()) |
745 | : PerformEmptyInit(Loc: ILE->getEndLoc(), Entity: BaseEntity); |
746 | if (BaseInit.isInvalid()) { |
747 | hadError = true; |
748 | return; |
749 | } |
750 | |
751 | if (!VerifyOnly) { |
752 | assert(Init < ILE->getNumInits() && "should have been expanded" ); |
753 | ILE->setInit(Init, expr: BaseInit.getAs<Expr>()); |
754 | } |
755 | } else if (InitListExpr *InnerILE = |
756 | dyn_cast<InitListExpr>(Val: ILE->getInit(Init))) { |
757 | FillInEmptyInitializations(Entity: BaseEntity, ILE: InnerILE, RequiresSecondPass, |
758 | OuterILE: ILE, OuterIndex: Init, FillWithNoInit); |
759 | } else if (DesignatedInitUpdateExpr *InnerDIUE = |
760 | dyn_cast<DesignatedInitUpdateExpr>(Val: ILE->getInit(Init))) { |
761 | FillInEmptyInitializations(Entity: BaseEntity, ILE: InnerDIUE->getUpdater(), |
762 | RequiresSecondPass, OuterILE: ILE, OuterIndex: Init, |
763 | /*FillWithNoInit =*/true); |
764 | } |
765 | } |
766 | |
767 | void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field, |
768 | const InitializedEntity &ParentEntity, |
769 | InitListExpr *ILE, |
770 | bool &RequiresSecondPass, |
771 | bool FillWithNoInit) { |
772 | SourceLocation Loc = ILE->getEndLoc(); |
773 | unsigned NumInits = ILE->getNumInits(); |
774 | InitializedEntity MemberEntity |
775 | = InitializedEntity::InitializeMember(Member: Field, Parent: &ParentEntity); |
776 | |
777 | if (Init >= NumInits || !ILE->getInit(Init)) { |
778 | if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) |
779 | if (!RType->getDecl()->isUnion()) |
780 | assert((Init < NumInits || VerifyOnly) && |
781 | "This ILE should have been expanded" ); |
782 | |
783 | if (FillWithNoInit) { |
784 | assert(!VerifyOnly && "should not fill with no-init in verify-only mode" ); |
785 | Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType()); |
786 | if (Init < NumInits) |
787 | ILE->setInit(Init, expr: Filler); |
788 | else |
789 | ILE->updateInit(C: SemaRef.Context, Init, expr: Filler); |
790 | return; |
791 | } |
792 | |
793 | if (!VerifyOnly && Field->hasAttr<ExplicitInitAttr>()) { |
794 | SemaRef.Diag(Loc: ILE->getExprLoc(), DiagID: diag::warn_field_requires_explicit_init) |
795 | << /* Var-in-Record */ 0 << Field; |
796 | SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_entity_declared_at) |
797 | << Field; |
798 | } |
799 | |
800 | // C++1y [dcl.init.aggr]p7: |
801 | // If there are fewer initializer-clauses in the list than there are |
802 | // members in the aggregate, then each member not explicitly initialized |
803 | // shall be initialized from its brace-or-equal-initializer [...] |
804 | if (Field->hasInClassInitializer()) { |
805 | if (VerifyOnly) |
806 | return; |
807 | |
808 | ExprResult DIE; |
809 | { |
810 | // Enter a default initializer rebuild context, then we can support |
811 | // lifetime extension of temporary created by aggregate initialization |
812 | // using a default member initializer. |
813 | // CWG1815 (https://wg21.link/CWG1815). |
814 | EnterExpressionEvaluationContext RebuildDefaultInit( |
815 | SemaRef, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); |
816 | SemaRef.currentEvaluationContext().RebuildDefaultArgOrDefaultInit = |
817 | true; |
818 | SemaRef.currentEvaluationContext().DelayedDefaultInitializationContext = |
819 | SemaRef.parentEvaluationContext() |
820 | .DelayedDefaultInitializationContext; |
821 | SemaRef.currentEvaluationContext().InLifetimeExtendingContext = |
822 | SemaRef.parentEvaluationContext().InLifetimeExtendingContext; |
823 | DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field); |
824 | } |
825 | if (DIE.isInvalid()) { |
826 | hadError = true; |
827 | return; |
828 | } |
829 | SemaRef.checkInitializerLifetime(Entity: MemberEntity, Init: DIE.get()); |
830 | if (Init < NumInits) |
831 | ILE->setInit(Init, expr: DIE.get()); |
832 | else { |
833 | ILE->updateInit(C: SemaRef.Context, Init, expr: DIE.get()); |
834 | RequiresSecondPass = true; |
835 | } |
836 | return; |
837 | } |
838 | |
839 | if (Field->getType()->isReferenceType()) { |
840 | if (!VerifyOnly) { |
841 | // C++ [dcl.init.aggr]p9: |
842 | // If an incomplete or empty initializer-list leaves a |
843 | // member of reference type uninitialized, the program is |
844 | // ill-formed. |
845 | SemaRef.Diag(Loc, DiagID: diag::err_init_reference_member_uninitialized) |
846 | << Field->getType() |
847 | << (ILE->isSyntacticForm() ? ILE : ILE->getSyntacticForm()) |
848 | ->getSourceRange(); |
849 | SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_uninit_reference_member); |
850 | } |
851 | hadError = true; |
852 | return; |
853 | } |
854 | |
855 | ExprResult MemberInit = PerformEmptyInit(Loc, Entity: MemberEntity); |
856 | if (MemberInit.isInvalid()) { |
857 | hadError = true; |
858 | return; |
859 | } |
860 | |
861 | if (hadError || VerifyOnly) { |
862 | // Do nothing |
863 | } else if (Init < NumInits) { |
864 | ILE->setInit(Init, expr: MemberInit.getAs<Expr>()); |
865 | } else if (!isa<ImplicitValueInitExpr>(Val: MemberInit.get())) { |
866 | // Empty initialization requires a constructor call, so |
867 | // extend the initializer list to include the constructor |
868 | // call and make a note that we'll need to take another pass |
869 | // through the initializer list. |
870 | ILE->updateInit(C: SemaRef.Context, Init, expr: MemberInit.getAs<Expr>()); |
871 | RequiresSecondPass = true; |
872 | } |
873 | } else if (InitListExpr *InnerILE |
874 | = dyn_cast<InitListExpr>(Val: ILE->getInit(Init))) { |
875 | FillInEmptyInitializations(Entity: MemberEntity, ILE: InnerILE, |
876 | RequiresSecondPass, OuterILE: ILE, OuterIndex: Init, FillWithNoInit); |
877 | } else if (DesignatedInitUpdateExpr *InnerDIUE = |
878 | dyn_cast<DesignatedInitUpdateExpr>(Val: ILE->getInit(Init))) { |
879 | FillInEmptyInitializations(Entity: MemberEntity, ILE: InnerDIUE->getUpdater(), |
880 | RequiresSecondPass, OuterILE: ILE, OuterIndex: Init, |
881 | /*FillWithNoInit =*/true); |
882 | } |
883 | } |
884 | |
885 | /// Recursively replaces NULL values within the given initializer list |
886 | /// with expressions that perform value-initialization of the |
887 | /// appropriate type, and finish off the InitListExpr formation. |
888 | void |
889 | InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity, |
890 | InitListExpr *ILE, |
891 | bool &RequiresSecondPass, |
892 | InitListExpr *OuterILE, |
893 | unsigned OuterIndex, |
894 | bool FillWithNoInit) { |
895 | assert((ILE->getType() != SemaRef.Context.VoidTy) && |
896 | "Should not have void type" ); |
897 | |
898 | // We don't need to do any checks when just filling NoInitExprs; that can't |
899 | // fail. |
900 | if (FillWithNoInit && VerifyOnly) |
901 | return; |
902 | |
903 | // If this is a nested initializer list, we might have changed its contents |
904 | // (and therefore some of its properties, such as instantiation-dependence) |
905 | // while filling it in. Inform the outer initializer list so that its state |
906 | // can be updated to match. |
907 | // FIXME: We should fully build the inner initializers before constructing |
908 | // the outer InitListExpr instead of mutating AST nodes after they have |
909 | // been used as subexpressions of other nodes. |
910 | struct UpdateOuterILEWithUpdatedInit { |
911 | InitListExpr *Outer; |
912 | unsigned OuterIndex; |
913 | ~UpdateOuterILEWithUpdatedInit() { |
914 | if (Outer) |
915 | Outer->setInit(Init: OuterIndex, expr: Outer->getInit(Init: OuterIndex)); |
916 | } |
917 | } UpdateOuterRAII = {.Outer: OuterILE, .OuterIndex: OuterIndex}; |
918 | |
919 | // A transparent ILE is not performing aggregate initialization and should |
920 | // not be filled in. |
921 | if (ILE->isTransparent()) |
922 | return; |
923 | |
924 | if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) { |
925 | const RecordDecl *RDecl = RType->getDecl(); |
926 | if (RDecl->isUnion() && ILE->getInitializedFieldInUnion()) { |
927 | FillInEmptyInitForField(Init: 0, Field: ILE->getInitializedFieldInUnion(), ParentEntity: Entity, ILE, |
928 | RequiresSecondPass, FillWithNoInit); |
929 | } else { |
930 | assert((!RDecl->isUnion() || !isa<CXXRecordDecl>(RDecl) || |
931 | !cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) && |
932 | "We should have computed initialized fields already" ); |
933 | // The fields beyond ILE->getNumInits() are default initialized, so in |
934 | // order to leave them uninitialized, the ILE is expanded and the extra |
935 | // fields are then filled with NoInitExpr. |
936 | unsigned NumElems = numStructUnionElements(DeclType: ILE->getType()); |
937 | if (!RDecl->isUnion() && RDecl->hasFlexibleArrayMember()) |
938 | ++NumElems; |
939 | if (!VerifyOnly && ILE->getNumInits() < NumElems) |
940 | ILE->resizeInits(Context: SemaRef.Context, NumInits: NumElems); |
941 | |
942 | unsigned Init = 0; |
943 | |
944 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RDecl)) { |
945 | for (auto &Base : CXXRD->bases()) { |
946 | if (hadError) |
947 | return; |
948 | |
949 | FillInEmptyInitForBase(Init, Base, ParentEntity: Entity, ILE, RequiresSecondPass, |
950 | FillWithNoInit); |
951 | ++Init; |
952 | } |
953 | } |
954 | |
955 | for (auto *Field : RDecl->fields()) { |
956 | if (Field->isUnnamedBitField()) |
957 | continue; |
958 | |
959 | if (hadError) |
960 | return; |
961 | |
962 | FillInEmptyInitForField(Init, Field, ParentEntity: Entity, ILE, RequiresSecondPass, |
963 | FillWithNoInit); |
964 | if (hadError) |
965 | return; |
966 | |
967 | ++Init; |
968 | |
969 | // Only look at the first initialization of a union. |
970 | if (RDecl->isUnion()) |
971 | break; |
972 | } |
973 | } |
974 | |
975 | return; |
976 | } |
977 | |
978 | QualType ElementType; |
979 | |
980 | InitializedEntity ElementEntity = Entity; |
981 | unsigned NumInits = ILE->getNumInits(); |
982 | uint64_t NumElements = NumInits; |
983 | if (const ArrayType *AType = SemaRef.Context.getAsArrayType(T: ILE->getType())) { |
984 | ElementType = AType->getElementType(); |
985 | if (const auto *CAType = dyn_cast<ConstantArrayType>(Val: AType)) |
986 | NumElements = CAType->getZExtSize(); |
987 | // For an array new with an unknown bound, ask for one additional element |
988 | // in order to populate the array filler. |
989 | if (Entity.isVariableLengthArrayNew()) |
990 | ++NumElements; |
991 | ElementEntity = InitializedEntity::InitializeElement(Context&: SemaRef.Context, |
992 | Index: 0, Parent: Entity); |
993 | } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) { |
994 | ElementType = VType->getElementType(); |
995 | NumElements = VType->getNumElements(); |
996 | ElementEntity = InitializedEntity::InitializeElement(Context&: SemaRef.Context, |
997 | Index: 0, Parent: Entity); |
998 | } else |
999 | ElementType = ILE->getType(); |
1000 | |
1001 | bool SkipEmptyInitChecks = false; |
1002 | for (uint64_t Init = 0; Init != NumElements; ++Init) { |
1003 | if (hadError) |
1004 | return; |
1005 | |
1006 | if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement || |
1007 | ElementEntity.getKind() == InitializedEntity::EK_VectorElement) |
1008 | ElementEntity.setElementIndex(Init); |
1009 | |
1010 | if (Init >= NumInits && (ILE->hasArrayFiller() || SkipEmptyInitChecks)) |
1011 | return; |
1012 | |
1013 | Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr); |
1014 | if (!InitExpr && Init < NumInits && ILE->hasArrayFiller()) |
1015 | ILE->setInit(Init, expr: ILE->getArrayFiller()); |
1016 | else if (!InitExpr && !ILE->hasArrayFiller()) { |
1017 | // In VerifyOnly mode, there's no point performing empty initialization |
1018 | // more than once. |
1019 | if (SkipEmptyInitChecks) |
1020 | continue; |
1021 | |
1022 | Expr *Filler = nullptr; |
1023 | |
1024 | if (FillWithNoInit) |
1025 | Filler = new (SemaRef.Context) NoInitExpr(ElementType); |
1026 | else { |
1027 | ExprResult ElementInit = |
1028 | PerformEmptyInit(Loc: ILE->getEndLoc(), Entity: ElementEntity); |
1029 | if (ElementInit.isInvalid()) { |
1030 | hadError = true; |
1031 | return; |
1032 | } |
1033 | |
1034 | Filler = ElementInit.getAs<Expr>(); |
1035 | } |
1036 | |
1037 | if (hadError) { |
1038 | // Do nothing |
1039 | } else if (VerifyOnly) { |
1040 | SkipEmptyInitChecks = true; |
1041 | } else if (Init < NumInits) { |
1042 | // For arrays, just set the expression used for value-initialization |
1043 | // of the "holes" in the array. |
1044 | if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) |
1045 | ILE->setArrayFiller(Filler); |
1046 | else |
1047 | ILE->setInit(Init, expr: Filler); |
1048 | } else { |
1049 | // For arrays, just set the expression used for value-initialization |
1050 | // of the rest of elements and exit. |
1051 | if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) { |
1052 | ILE->setArrayFiller(Filler); |
1053 | return; |
1054 | } |
1055 | |
1056 | if (!isa<ImplicitValueInitExpr>(Val: Filler) && !isa<NoInitExpr>(Val: Filler)) { |
1057 | // Empty initialization requires a constructor call, so |
1058 | // extend the initializer list to include the constructor |
1059 | // call and make a note that we'll need to take another pass |
1060 | // through the initializer list. |
1061 | ILE->updateInit(C: SemaRef.Context, Init, expr: Filler); |
1062 | RequiresSecondPass = true; |
1063 | } |
1064 | } |
1065 | } else if (InitListExpr *InnerILE |
1066 | = dyn_cast_or_null<InitListExpr>(Val: InitExpr)) { |
1067 | FillInEmptyInitializations(Entity: ElementEntity, ILE: InnerILE, RequiresSecondPass, |
1068 | OuterILE: ILE, OuterIndex: Init, FillWithNoInit); |
1069 | } else if (DesignatedInitUpdateExpr *InnerDIUE = |
1070 | dyn_cast_or_null<DesignatedInitUpdateExpr>(Val: InitExpr)) { |
1071 | FillInEmptyInitializations(Entity: ElementEntity, ILE: InnerDIUE->getUpdater(), |
1072 | RequiresSecondPass, OuterILE: ILE, OuterIndex: Init, |
1073 | /*FillWithNoInit =*/true); |
1074 | } |
1075 | } |
1076 | } |
1077 | |
1078 | static bool hasAnyDesignatedInits(const InitListExpr *IL) { |
1079 | for (const Stmt *Init : *IL) |
1080 | if (isa_and_nonnull<DesignatedInitExpr>(Val: Init)) |
1081 | return true; |
1082 | return false; |
1083 | } |
1084 | |
1085 | InitListChecker::InitListChecker( |
1086 | Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T, |
1087 | bool VerifyOnly, bool TreatUnavailableAsInvalid, bool InOverloadResolution, |
1088 | SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes) |
1089 | : SemaRef(S), VerifyOnly(VerifyOnly), |
1090 | TreatUnavailableAsInvalid(TreatUnavailableAsInvalid), |
1091 | InOverloadResolution(InOverloadResolution), |
1092 | AggrDeductionCandidateParamTypes(AggrDeductionCandidateParamTypes) { |
1093 | if (!VerifyOnly || hasAnyDesignatedInits(IL)) { |
1094 | FullyStructuredList = |
1095 | createInitListExpr(CurrentObjectType: T, InitRange: IL->getSourceRange(), ExpectedNumInits: IL->getNumInits()); |
1096 | |
1097 | // FIXME: Check that IL isn't already the semantic form of some other |
1098 | // InitListExpr. If it is, we'd create a broken AST. |
1099 | if (!VerifyOnly) |
1100 | FullyStructuredList->setSyntacticForm(IL); |
1101 | } |
1102 | |
1103 | CheckExplicitInitList(Entity, IList: IL, T, StructuredList: FullyStructuredList, |
1104 | /*TopLevelObject=*/true); |
1105 | |
1106 | if (!hadError && !AggrDeductionCandidateParamTypes && FullyStructuredList) { |
1107 | bool RequiresSecondPass = false; |
1108 | FillInEmptyInitializations(Entity, ILE: FullyStructuredList, RequiresSecondPass, |
1109 | /*OuterILE=*/nullptr, /*OuterIndex=*/0); |
1110 | if (RequiresSecondPass && !hadError) |
1111 | FillInEmptyInitializations(Entity, ILE: FullyStructuredList, |
1112 | RequiresSecondPass, OuterILE: nullptr, OuterIndex: 0); |
1113 | } |
1114 | if (hadError && FullyStructuredList) |
1115 | FullyStructuredList->markError(); |
1116 | } |
1117 | |
1118 | int InitListChecker::numArrayElements(QualType DeclType) { |
1119 | // FIXME: use a proper constant |
1120 | int maxElements = 0x7FFFFFFF; |
1121 | if (const ConstantArrayType *CAT = |
1122 | SemaRef.Context.getAsConstantArrayType(T: DeclType)) { |
1123 | maxElements = static_cast<int>(CAT->getZExtSize()); |
1124 | } |
1125 | return maxElements; |
1126 | } |
1127 | |
1128 | int InitListChecker::numStructUnionElements(QualType DeclType) { |
1129 | RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl(); |
1130 | int InitializableMembers = 0; |
1131 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: structDecl)) |
1132 | InitializableMembers += CXXRD->getNumBases(); |
1133 | for (const auto *Field : structDecl->fields()) |
1134 | if (!Field->isUnnamedBitField()) |
1135 | ++InitializableMembers; |
1136 | |
1137 | if (structDecl->isUnion()) |
1138 | return std::min(a: InitializableMembers, b: 1); |
1139 | return InitializableMembers - structDecl->hasFlexibleArrayMember(); |
1140 | } |
1141 | |
1142 | RecordDecl *InitListChecker::getRecordDecl(QualType DeclType) { |
1143 | if (const auto *RT = DeclType->getAs<RecordType>()) |
1144 | return RT->getDecl(); |
1145 | if (const auto *Inject = DeclType->getAs<InjectedClassNameType>()) |
1146 | return Inject->getDecl(); |
1147 | return nullptr; |
1148 | } |
1149 | |
1150 | /// Determine whether Entity is an entity for which it is idiomatic to elide |
1151 | /// the braces in aggregate initialization. |
1152 | static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) { |
1153 | // Recursive initialization of the one and only field within an aggregate |
1154 | // class is considered idiomatic. This case arises in particular for |
1155 | // initialization of std::array, where the C++ standard suggests the idiom of |
1156 | // |
1157 | // std::array<T, N> arr = {1, 2, 3}; |
1158 | // |
1159 | // (where std::array is an aggregate struct containing a single array field. |
1160 | |
1161 | if (!Entity.getParent()) |
1162 | return false; |
1163 | |
1164 | // Allows elide brace initialization for aggregates with empty base. |
1165 | if (Entity.getKind() == InitializedEntity::EK_Base) { |
1166 | auto *ParentRD = |
1167 | Entity.getParent()->getType()->castAs<RecordType>()->getDecl(); |
1168 | CXXRecordDecl *CXXRD = cast<CXXRecordDecl>(Val: ParentRD); |
1169 | return CXXRD->getNumBases() == 1 && CXXRD->field_empty(); |
1170 | } |
1171 | |
1172 | // Allow brace elision if the only subobject is a field. |
1173 | if (Entity.getKind() == InitializedEntity::EK_Member) { |
1174 | auto *ParentRD = |
1175 | Entity.getParent()->getType()->castAs<RecordType>()->getDecl(); |
1176 | if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(Val: ParentRD)) { |
1177 | if (CXXRD->getNumBases()) { |
1178 | return false; |
1179 | } |
1180 | } |
1181 | auto FieldIt = ParentRD->field_begin(); |
1182 | assert(FieldIt != ParentRD->field_end() && |
1183 | "no fields but have initializer for member?" ); |
1184 | return ++FieldIt == ParentRD->field_end(); |
1185 | } |
1186 | |
1187 | return false; |
1188 | } |
1189 | |
1190 | /// Check whether the range of the initializer \p ParentIList from element |
1191 | /// \p Index onwards can be used to initialize an object of type \p T. Update |
1192 | /// \p Index to indicate how many elements of the list were consumed. |
1193 | /// |
1194 | /// This also fills in \p StructuredList, from element \p StructuredIndex |
1195 | /// onwards, with the fully-braced, desugared form of the initialization. |
1196 | void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity, |
1197 | InitListExpr *ParentIList, |
1198 | QualType T, unsigned &Index, |
1199 | InitListExpr *StructuredList, |
1200 | unsigned &StructuredIndex) { |
1201 | int maxElements = 0; |
1202 | |
1203 | if (T->isArrayType()) |
1204 | maxElements = numArrayElements(DeclType: T); |
1205 | else if (T->isRecordType()) |
1206 | maxElements = numStructUnionElements(DeclType: T); |
1207 | else if (T->isVectorType()) |
1208 | maxElements = T->castAs<VectorType>()->getNumElements(); |
1209 | else |
1210 | llvm_unreachable("CheckImplicitInitList(): Illegal type" ); |
1211 | |
1212 | if (maxElements == 0) { |
1213 | if (!VerifyOnly) |
1214 | SemaRef.Diag(Loc: ParentIList->getInit(Init: Index)->getBeginLoc(), |
1215 | DiagID: diag::err_implicit_empty_initializer); |
1216 | ++Index; |
1217 | hadError = true; |
1218 | return; |
1219 | } |
1220 | |
1221 | // Build a structured initializer list corresponding to this subobject. |
1222 | InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit( |
1223 | IList: ParentIList, Index, CurrentObjectType: T, StructuredList, StructuredIndex, |
1224 | InitRange: SourceRange(ParentIList->getInit(Init: Index)->getBeginLoc(), |
1225 | ParentIList->getSourceRange().getEnd())); |
1226 | unsigned StructuredSubobjectInitIndex = 0; |
1227 | |
1228 | // Check the element types and build the structural subobject. |
1229 | unsigned StartIndex = Index; |
1230 | CheckListElementTypes(Entity, IList: ParentIList, DeclType&: T, |
1231 | /*SubobjectIsDesignatorContext=*/false, Index, |
1232 | StructuredList: StructuredSubobjectInitList, |
1233 | StructuredIndex&: StructuredSubobjectInitIndex); |
1234 | |
1235 | if (StructuredSubobjectInitList) { |
1236 | StructuredSubobjectInitList->setType(T); |
1237 | |
1238 | unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1); |
1239 | // Update the structured sub-object initializer so that it's ending |
1240 | // range corresponds with the end of the last initializer it used. |
1241 | if (EndIndex < ParentIList->getNumInits() && |
1242 | ParentIList->getInit(Init: EndIndex)) { |
1243 | SourceLocation EndLoc |
1244 | = ParentIList->getInit(Init: EndIndex)->getSourceRange().getEnd(); |
1245 | StructuredSubobjectInitList->setRBraceLoc(EndLoc); |
1246 | } |
1247 | |
1248 | // Complain about missing braces. |
1249 | if (!VerifyOnly && (T->isArrayType() || T->isRecordType()) && |
1250 | !ParentIList->isIdiomaticZeroInitializer(LangOpts: SemaRef.getLangOpts()) && |
1251 | !isIdiomaticBraceElisionEntity(Entity)) { |
1252 | SemaRef.Diag(Loc: StructuredSubobjectInitList->getBeginLoc(), |
1253 | DiagID: diag::warn_missing_braces) |
1254 | << StructuredSubobjectInitList->getSourceRange() |
1255 | << FixItHint::CreateInsertion( |
1256 | InsertionLoc: StructuredSubobjectInitList->getBeginLoc(), Code: "{" ) |
1257 | << FixItHint::CreateInsertion( |
1258 | InsertionLoc: SemaRef.getLocForEndOfToken( |
1259 | Loc: StructuredSubobjectInitList->getEndLoc()), |
1260 | Code: "}" ); |
1261 | } |
1262 | |
1263 | // Warn if this type won't be an aggregate in future versions of C++. |
1264 | auto *CXXRD = T->getAsCXXRecordDecl(); |
1265 | if (!VerifyOnly && CXXRD && CXXRD->hasUserDeclaredConstructor()) { |
1266 | SemaRef.Diag(Loc: StructuredSubobjectInitList->getBeginLoc(), |
1267 | DiagID: diag::warn_cxx20_compat_aggregate_init_with_ctors) |
1268 | << StructuredSubobjectInitList->getSourceRange() << T; |
1269 | } |
1270 | } |
1271 | } |
1272 | |
1273 | /// Warn that \p Entity was of scalar type and was initialized by a |
1274 | /// single-element braced initializer list. |
1275 | static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity, |
1276 | SourceRange Braces) { |
1277 | // Don't warn during template instantiation. If the initialization was |
1278 | // non-dependent, we warned during the initial parse; otherwise, the |
1279 | // type might not be scalar in some uses of the template. |
1280 | if (S.inTemplateInstantiation()) |
1281 | return; |
1282 | |
1283 | unsigned DiagID = 0; |
1284 | |
1285 | switch (Entity.getKind()) { |
1286 | case InitializedEntity::EK_VectorElement: |
1287 | case InitializedEntity::EK_ComplexElement: |
1288 | case InitializedEntity::EK_ArrayElement: |
1289 | case InitializedEntity::EK_Parameter: |
1290 | case InitializedEntity::EK_Parameter_CF_Audited: |
1291 | case InitializedEntity::EK_TemplateParameter: |
1292 | case InitializedEntity::EK_Result: |
1293 | case InitializedEntity::EK_ParenAggInitMember: |
1294 | // Extra braces here are suspicious. |
1295 | DiagID = diag::warn_braces_around_init; |
1296 | break; |
1297 | |
1298 | case InitializedEntity::EK_Member: |
1299 | // Warn on aggregate initialization but not on ctor init list or |
1300 | // default member initializer. |
1301 | if (Entity.getParent()) |
1302 | DiagID = diag::warn_braces_around_init; |
1303 | break; |
1304 | |
1305 | case InitializedEntity::EK_Variable: |
1306 | case InitializedEntity::EK_LambdaCapture: |
1307 | // No warning, might be direct-list-initialization. |
1308 | // FIXME: Should we warn for copy-list-initialization in these cases? |
1309 | break; |
1310 | |
1311 | case InitializedEntity::EK_New: |
1312 | case InitializedEntity::EK_Temporary: |
1313 | case InitializedEntity::EK_CompoundLiteralInit: |
1314 | // No warning, braces are part of the syntax of the underlying construct. |
1315 | break; |
1316 | |
1317 | case InitializedEntity::EK_RelatedResult: |
1318 | // No warning, we already warned when initializing the result. |
1319 | break; |
1320 | |
1321 | case InitializedEntity::EK_Exception: |
1322 | case InitializedEntity::EK_Base: |
1323 | case InitializedEntity::EK_Delegating: |
1324 | case InitializedEntity::EK_BlockElement: |
1325 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: |
1326 | case InitializedEntity::EK_Binding: |
1327 | case InitializedEntity::EK_StmtExprResult: |
1328 | llvm_unreachable("unexpected braced scalar init" ); |
1329 | } |
1330 | |
1331 | if (DiagID) { |
1332 | S.Diag(Loc: Braces.getBegin(), DiagID) |
1333 | << Entity.getType()->isSizelessBuiltinType() << Braces |
1334 | << FixItHint::CreateRemoval(RemoveRange: Braces.getBegin()) |
1335 | << FixItHint::CreateRemoval(RemoveRange: Braces.getEnd()); |
1336 | } |
1337 | } |
1338 | |
1339 | /// Check whether the initializer \p IList (that was written with explicit |
1340 | /// braces) can be used to initialize an object of type \p T. |
1341 | /// |
1342 | /// This also fills in \p StructuredList with the fully-braced, desugared |
1343 | /// form of the initialization. |
1344 | void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity, |
1345 | InitListExpr *IList, QualType &T, |
1346 | InitListExpr *StructuredList, |
1347 | bool TopLevelObject) { |
1348 | unsigned Index = 0, StructuredIndex = 0; |
1349 | CheckListElementTypes(Entity, IList, DeclType&: T, /*SubobjectIsDesignatorContext=*/true, |
1350 | Index, StructuredList, StructuredIndex, TopLevelObject); |
1351 | if (StructuredList) { |
1352 | QualType ExprTy = T; |
1353 | if (!ExprTy->isArrayType()) |
1354 | ExprTy = ExprTy.getNonLValueExprType(Context: SemaRef.Context); |
1355 | if (!VerifyOnly) |
1356 | IList->setType(ExprTy); |
1357 | StructuredList->setType(ExprTy); |
1358 | } |
1359 | if (hadError) |
1360 | return; |
1361 | |
1362 | // Don't complain for incomplete types, since we'll get an error elsewhere. |
1363 | if ((Index < IList->getNumInits() || CurEmbed) && !T->isIncompleteType()) { |
1364 | // We have leftover initializers |
1365 | bool = SemaRef.getLangOpts().CPlusPlus || |
1366 | (SemaRef.getLangOpts().OpenCL && T->isVectorType()); |
1367 | hadError = ExtraInitsIsError; |
1368 | if (VerifyOnly) { |
1369 | return; |
1370 | } else if (StructuredIndex == 1 && |
1371 | IsStringInit(init: StructuredList->getInit(Init: 0), declType: T, Context&: SemaRef.Context) == |
1372 | SIF_None) { |
1373 | unsigned DK = |
1374 | ExtraInitsIsError |
1375 | ? diag::err_excess_initializers_in_char_array_initializer |
1376 | : diag::ext_excess_initializers_in_char_array_initializer; |
1377 | SemaRef.Diag(Loc: IList->getInit(Init: Index)->getBeginLoc(), DiagID: DK) |
1378 | << IList->getInit(Init: Index)->getSourceRange(); |
1379 | } else if (T->isSizelessBuiltinType()) { |
1380 | unsigned DK = ExtraInitsIsError |
1381 | ? diag::err_excess_initializers_for_sizeless_type |
1382 | : diag::ext_excess_initializers_for_sizeless_type; |
1383 | SemaRef.Diag(Loc: IList->getInit(Init: Index)->getBeginLoc(), DiagID: DK) |
1384 | << T << IList->getInit(Init: Index)->getSourceRange(); |
1385 | } else { |
1386 | int initKind = T->isArrayType() ? 0 : |
1387 | T->isVectorType() ? 1 : |
1388 | T->isScalarType() ? 2 : |
1389 | T->isUnionType() ? 3 : |
1390 | 4; |
1391 | |
1392 | unsigned DK = ExtraInitsIsError ? diag::err_excess_initializers |
1393 | : diag::ext_excess_initializers; |
1394 | SemaRef.Diag(Loc: IList->getInit(Init: Index)->getBeginLoc(), DiagID: DK) |
1395 | << initKind << IList->getInit(Init: Index)->getSourceRange(); |
1396 | } |
1397 | } |
1398 | |
1399 | if (!VerifyOnly) { |
1400 | if (T->isScalarType() && IList->getNumInits() == 1 && |
1401 | !isa<InitListExpr>(Val: IList->getInit(Init: 0))) |
1402 | warnBracedScalarInit(S&: SemaRef, Entity, Braces: IList->getSourceRange()); |
1403 | |
1404 | // Warn if this is a class type that won't be an aggregate in future |
1405 | // versions of C++. |
1406 | auto *CXXRD = T->getAsCXXRecordDecl(); |
1407 | if (CXXRD && CXXRD->hasUserDeclaredConstructor()) { |
1408 | // Don't warn if there's an equivalent default constructor that would be |
1409 | // used instead. |
1410 | bool HasEquivCtor = false; |
1411 | if (IList->getNumInits() == 0) { |
1412 | auto *CD = SemaRef.LookupDefaultConstructor(Class: CXXRD); |
1413 | HasEquivCtor = CD && !CD->isDeleted(); |
1414 | } |
1415 | |
1416 | if (!HasEquivCtor) { |
1417 | SemaRef.Diag(Loc: IList->getBeginLoc(), |
1418 | DiagID: diag::warn_cxx20_compat_aggregate_init_with_ctors) |
1419 | << IList->getSourceRange() << T; |
1420 | } |
1421 | } |
1422 | } |
1423 | } |
1424 | |
1425 | void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity, |
1426 | InitListExpr *IList, |
1427 | QualType &DeclType, |
1428 | bool SubobjectIsDesignatorContext, |
1429 | unsigned &Index, |
1430 | InitListExpr *StructuredList, |
1431 | unsigned &StructuredIndex, |
1432 | bool TopLevelObject) { |
1433 | if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) { |
1434 | // Explicitly braced initializer for complex type can be real+imaginary |
1435 | // parts. |
1436 | CheckComplexType(Entity, IList, DeclType, Index, |
1437 | StructuredList, StructuredIndex); |
1438 | } else if (DeclType->isScalarType()) { |
1439 | CheckScalarType(Entity, IList, DeclType, Index, |
1440 | StructuredList, StructuredIndex); |
1441 | } else if (DeclType->isVectorType()) { |
1442 | CheckVectorType(Entity, IList, DeclType, Index, |
1443 | StructuredList, StructuredIndex); |
1444 | } else if (const RecordDecl *RD = getRecordDecl(DeclType)) { |
1445 | auto Bases = |
1446 | CXXRecordDecl::base_class_const_range(CXXRecordDecl::base_class_const_iterator(), |
1447 | CXXRecordDecl::base_class_const_iterator()); |
1448 | if (DeclType->isRecordType()) { |
1449 | assert(DeclType->isAggregateType() && |
1450 | "non-aggregate records should be handed in CheckSubElementType" ); |
1451 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) |
1452 | Bases = CXXRD->bases(); |
1453 | } else { |
1454 | Bases = cast<CXXRecordDecl>(Val: RD)->bases(); |
1455 | } |
1456 | CheckStructUnionTypes(Entity, IList, DeclType, Bases, Field: RD->field_begin(), |
1457 | SubobjectIsDesignatorContext, Index, StructuredList, |
1458 | StructuredIndex, TopLevelObject); |
1459 | } else if (DeclType->isArrayType()) { |
1460 | llvm::APSInt Zero( |
1461 | SemaRef.Context.getTypeSize(T: SemaRef.Context.getSizeType()), |
1462 | false); |
1463 | CheckArrayType(Entity, IList, DeclType, elementIndex: Zero, |
1464 | SubobjectIsDesignatorContext, Index, |
1465 | StructuredList, StructuredIndex); |
1466 | } else if (DeclType->isVoidType() || DeclType->isFunctionType()) { |
1467 | // This type is invalid, issue a diagnostic. |
1468 | ++Index; |
1469 | if (!VerifyOnly) |
1470 | SemaRef.Diag(Loc: IList->getBeginLoc(), DiagID: diag::err_illegal_initializer_type) |
1471 | << DeclType; |
1472 | hadError = true; |
1473 | } else if (DeclType->isReferenceType()) { |
1474 | CheckReferenceType(Entity, IList, DeclType, Index, |
1475 | StructuredList, StructuredIndex); |
1476 | } else if (DeclType->isObjCObjectType()) { |
1477 | if (!VerifyOnly) |
1478 | SemaRef.Diag(Loc: IList->getBeginLoc(), DiagID: diag::err_init_objc_class) << DeclType; |
1479 | hadError = true; |
1480 | } else if (DeclType->isOCLIntelSubgroupAVCType() || |
1481 | DeclType->isSizelessBuiltinType()) { |
1482 | // Checks for scalar type are sufficient for these types too. |
1483 | CheckScalarType(Entity, IList, DeclType, Index, StructuredList, |
1484 | StructuredIndex); |
1485 | } else if (DeclType->isDependentType()) { |
1486 | // C++ [over.match.class.deduct]p1.5: |
1487 | // brace elision is not considered for any aggregate element that has a |
1488 | // dependent non-array type or an array type with a value-dependent bound |
1489 | ++Index; |
1490 | assert(AggrDeductionCandidateParamTypes); |
1491 | AggrDeductionCandidateParamTypes->push_back(Elt: DeclType); |
1492 | } else { |
1493 | if (!VerifyOnly) |
1494 | SemaRef.Diag(Loc: IList->getBeginLoc(), DiagID: diag::err_illegal_initializer_type) |
1495 | << DeclType; |
1496 | hadError = true; |
1497 | } |
1498 | } |
1499 | |
1500 | void InitListChecker::CheckSubElementType(const InitializedEntity &Entity, |
1501 | InitListExpr *IList, |
1502 | QualType ElemType, |
1503 | unsigned &Index, |
1504 | InitListExpr *StructuredList, |
1505 | unsigned &StructuredIndex, |
1506 | bool DirectlyDesignated) { |
1507 | Expr *expr = IList->getInit(Init: Index); |
1508 | |
1509 | if (ElemType->isReferenceType()) |
1510 | return CheckReferenceType(Entity, IList, DeclType: ElemType, Index, |
1511 | StructuredList, StructuredIndex); |
1512 | |
1513 | if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(Val: expr)) { |
1514 | if (SubInitList->getNumInits() == 1 && |
1515 | IsStringInit(init: SubInitList->getInit(Init: 0), declType: ElemType, Context&: SemaRef.Context) == |
1516 | SIF_None) { |
1517 | // FIXME: It would be more faithful and no less correct to include an |
1518 | // InitListExpr in the semantic form of the initializer list in this case. |
1519 | expr = SubInitList->getInit(Init: 0); |
1520 | } |
1521 | // Nested aggregate initialization and C++ initialization are handled later. |
1522 | } else if (isa<ImplicitValueInitExpr>(Val: expr)) { |
1523 | // This happens during template instantiation when we see an InitListExpr |
1524 | // that we've already checked once. |
1525 | assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) && |
1526 | "found implicit initialization for the wrong type" ); |
1527 | UpdateStructuredListElement(StructuredList, StructuredIndex, expr); |
1528 | ++Index; |
1529 | return; |
1530 | } |
1531 | |
1532 | if (SemaRef.getLangOpts().CPlusPlus || isa<InitListExpr>(Val: expr)) { |
1533 | // C++ [dcl.init.aggr]p2: |
1534 | // Each member is copy-initialized from the corresponding |
1535 | // initializer-clause. |
1536 | |
1537 | // FIXME: Better EqualLoc? |
1538 | InitializationKind Kind = |
1539 | InitializationKind::CreateCopy(InitLoc: expr->getBeginLoc(), EqualLoc: SourceLocation()); |
1540 | |
1541 | // Vector elements can be initialized from other vectors in which case |
1542 | // we need initialization entity with a type of a vector (and not a vector |
1543 | // element!) initializing multiple vector elements. |
1544 | auto TmpEntity = |
1545 | (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType()) |
1546 | ? InitializedEntity::InitializeTemporary(Type: ElemType) |
1547 | : Entity; |
1548 | |
1549 | if (TmpEntity.getType()->isDependentType()) { |
1550 | // C++ [over.match.class.deduct]p1.5: |
1551 | // brace elision is not considered for any aggregate element that has a |
1552 | // dependent non-array type or an array type with a value-dependent |
1553 | // bound |
1554 | assert(AggrDeductionCandidateParamTypes); |
1555 | |
1556 | // In the presence of a braced-init-list within the initializer, we should |
1557 | // not perform brace-elision, even if brace elision would otherwise be |
1558 | // applicable. For example, given: |
1559 | // |
1560 | // template <class T> struct Foo { |
1561 | // T t[2]; |
1562 | // }; |
1563 | // |
1564 | // Foo t = {{1, 2}}; |
1565 | // |
1566 | // we don't want the (T, T) but rather (T [2]) in terms of the initializer |
1567 | // {{1, 2}}. |
1568 | if (isa<InitListExpr, DesignatedInitExpr>(Val: expr) || |
1569 | !isa_and_present<ConstantArrayType>( |
1570 | Val: SemaRef.Context.getAsArrayType(T: ElemType))) { |
1571 | ++Index; |
1572 | AggrDeductionCandidateParamTypes->push_back(Elt: ElemType); |
1573 | return; |
1574 | } |
1575 | } else { |
1576 | InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr, |
1577 | /*TopLevelOfInitList*/ true); |
1578 | // C++14 [dcl.init.aggr]p13: |
1579 | // If the assignment-expression can initialize a member, the member is |
1580 | // initialized. Otherwise [...] brace elision is assumed |
1581 | // |
1582 | // Brace elision is never performed if the element is not an |
1583 | // assignment-expression. |
1584 | if (Seq || isa<InitListExpr>(Val: expr)) { |
1585 | if (auto *Embed = dyn_cast<EmbedExpr>(Val: expr)) { |
1586 | expr = HandleEmbed(Embed, Entity); |
1587 | } |
1588 | if (!VerifyOnly) { |
1589 | ExprResult Result = Seq.Perform(S&: SemaRef, Entity: TmpEntity, Kind, Args: expr); |
1590 | if (Result.isInvalid()) |
1591 | hadError = true; |
1592 | |
1593 | UpdateStructuredListElement(StructuredList, StructuredIndex, |
1594 | expr: Result.getAs<Expr>()); |
1595 | } else if (!Seq) { |
1596 | hadError = true; |
1597 | } else if (StructuredList) { |
1598 | UpdateStructuredListElement(StructuredList, StructuredIndex, |
1599 | expr: getDummyInit()); |
1600 | } |
1601 | if (!CurEmbed) |
1602 | ++Index; |
1603 | if (AggrDeductionCandidateParamTypes) |
1604 | AggrDeductionCandidateParamTypes->push_back(Elt: ElemType); |
1605 | return; |
1606 | } |
1607 | } |
1608 | |
1609 | // Fall through for subaggregate initialization |
1610 | } else if (ElemType->isScalarType() || ElemType->isAtomicType()) { |
1611 | // FIXME: Need to handle atomic aggregate types with implicit init lists. |
1612 | return CheckScalarType(Entity, IList, DeclType: ElemType, Index, |
1613 | StructuredList, StructuredIndex); |
1614 | } else if (const ArrayType *arrayType = |
1615 | SemaRef.Context.getAsArrayType(T: ElemType)) { |
1616 | // arrayType can be incomplete if we're initializing a flexible |
1617 | // array member. There's nothing we can do with the completed |
1618 | // type here, though. |
1619 | |
1620 | if (IsStringInit(Init: expr, AT: arrayType, Context&: SemaRef.Context) == SIF_None) { |
1621 | // FIXME: Should we do this checking in verify-only mode? |
1622 | if (!VerifyOnly) |
1623 | CheckStringInit(Str: expr, DeclT&: ElemType, AT: arrayType, S&: SemaRef, Entity, |
1624 | CheckC23ConstexprInit: SemaRef.getLangOpts().C23 && |
1625 | initializingConstexprVariable(Entity)); |
1626 | if (StructuredList) |
1627 | UpdateStructuredListElement(StructuredList, StructuredIndex, expr); |
1628 | ++Index; |
1629 | return; |
1630 | } |
1631 | |
1632 | // Fall through for subaggregate initialization. |
1633 | |
1634 | } else { |
1635 | assert((ElemType->isRecordType() || ElemType->isVectorType() || |
1636 | ElemType->isOpenCLSpecificType() || ElemType->isMFloat8Type()) && |
1637 | "Unexpected type" ); |
1638 | |
1639 | // C99 6.7.8p13: |
1640 | // |
1641 | // The initializer for a structure or union object that has |
1642 | // automatic storage duration shall be either an initializer |
1643 | // list as described below, or a single expression that has |
1644 | // compatible structure or union type. In the latter case, the |
1645 | // initial value of the object, including unnamed members, is |
1646 | // that of the expression. |
1647 | ExprResult ExprRes = expr; |
1648 | if (SemaRef.CheckSingleAssignmentConstraints(LHSType: ElemType, RHS&: ExprRes, |
1649 | Diagnose: !VerifyOnly) != |
1650 | AssignConvertType::Incompatible) { |
1651 | if (ExprRes.isInvalid()) |
1652 | hadError = true; |
1653 | else { |
1654 | ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(E: ExprRes.get()); |
1655 | if (ExprRes.isInvalid()) |
1656 | hadError = true; |
1657 | } |
1658 | UpdateStructuredListElement(StructuredList, StructuredIndex, |
1659 | expr: ExprRes.getAs<Expr>()); |
1660 | ++Index; |
1661 | return; |
1662 | } |
1663 | ExprRes.get(); |
1664 | // Fall through for subaggregate initialization |
1665 | } |
1666 | |
1667 | // C++ [dcl.init.aggr]p12: |
1668 | // |
1669 | // [...] Otherwise, if the member is itself a non-empty |
1670 | // subaggregate, brace elision is assumed and the initializer is |
1671 | // considered for the initialization of the first member of |
1672 | // the subaggregate. |
1673 | // OpenCL vector initializer is handled elsewhere. |
1674 | if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) || |
1675 | ElemType->isAggregateType()) { |
1676 | CheckImplicitInitList(Entity, ParentIList: IList, T: ElemType, Index, StructuredList, |
1677 | StructuredIndex); |
1678 | ++StructuredIndex; |
1679 | |
1680 | // In C++20, brace elision is not permitted for a designated initializer. |
1681 | if (DirectlyDesignated && SemaRef.getLangOpts().CPlusPlus && !hadError) { |
1682 | if (InOverloadResolution) |
1683 | hadError = true; |
1684 | if (!VerifyOnly) { |
1685 | SemaRef.Diag(Loc: expr->getBeginLoc(), |
1686 | DiagID: diag::ext_designated_init_brace_elision) |
1687 | << expr->getSourceRange() |
1688 | << FixItHint::CreateInsertion(InsertionLoc: expr->getBeginLoc(), Code: "{" ) |
1689 | << FixItHint::CreateInsertion( |
1690 | InsertionLoc: SemaRef.getLocForEndOfToken(Loc: expr->getEndLoc()), Code: "}" ); |
1691 | } |
1692 | } |
1693 | } else { |
1694 | if (!VerifyOnly) { |
1695 | // We cannot initialize this element, so let PerformCopyInitialization |
1696 | // produce the appropriate diagnostic. We already checked that this |
1697 | // initialization will fail. |
1698 | ExprResult Copy = |
1699 | SemaRef.PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: expr, |
1700 | /*TopLevelOfInitList=*/true); |
1701 | (void)Copy; |
1702 | assert(Copy.isInvalid() && |
1703 | "expected non-aggregate initialization to fail" ); |
1704 | } |
1705 | hadError = true; |
1706 | ++Index; |
1707 | ++StructuredIndex; |
1708 | } |
1709 | } |
1710 | |
1711 | void InitListChecker::CheckComplexType(const InitializedEntity &Entity, |
1712 | InitListExpr *IList, QualType DeclType, |
1713 | unsigned &Index, |
1714 | InitListExpr *StructuredList, |
1715 | unsigned &StructuredIndex) { |
1716 | assert(Index == 0 && "Index in explicit init list must be zero" ); |
1717 | |
1718 | // As an extension, clang supports complex initializers, which initialize |
1719 | // a complex number component-wise. When an explicit initializer list for |
1720 | // a complex number contains two initializers, this extension kicks in: |
1721 | // it expects the initializer list to contain two elements convertible to |
1722 | // the element type of the complex type. The first element initializes |
1723 | // the real part, and the second element intitializes the imaginary part. |
1724 | |
1725 | if (IList->getNumInits() < 2) |
1726 | return CheckScalarType(Entity, IList, DeclType, Index, StructuredList, |
1727 | StructuredIndex); |
1728 | |
1729 | // This is an extension in C. (The builtin _Complex type does not exist |
1730 | // in the C++ standard.) |
1731 | if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly) |
1732 | SemaRef.Diag(Loc: IList->getBeginLoc(), DiagID: diag::ext_complex_component_init) |
1733 | << IList->getSourceRange(); |
1734 | |
1735 | // Initialize the complex number. |
1736 | QualType elementType = DeclType->castAs<ComplexType>()->getElementType(); |
1737 | InitializedEntity ElementEntity = |
1738 | InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity); |
1739 | |
1740 | for (unsigned i = 0; i < 2; ++i) { |
1741 | ElementEntity.setElementIndex(Index); |
1742 | CheckSubElementType(Entity: ElementEntity, IList, ElemType: elementType, Index, |
1743 | StructuredList, StructuredIndex); |
1744 | } |
1745 | } |
1746 | |
1747 | void InitListChecker::CheckScalarType(const InitializedEntity &Entity, |
1748 | InitListExpr *IList, QualType DeclType, |
1749 | unsigned &Index, |
1750 | InitListExpr *StructuredList, |
1751 | unsigned &StructuredIndex) { |
1752 | if (Index >= IList->getNumInits()) { |
1753 | if (!VerifyOnly) { |
1754 | if (SemaRef.getLangOpts().CPlusPlus) { |
1755 | if (DeclType->isSizelessBuiltinType()) |
1756 | SemaRef.Diag(Loc: IList->getBeginLoc(), |
1757 | DiagID: SemaRef.getLangOpts().CPlusPlus11 |
1758 | ? diag::warn_cxx98_compat_empty_sizeless_initializer |
1759 | : diag::err_empty_sizeless_initializer) |
1760 | << DeclType << IList->getSourceRange(); |
1761 | else |
1762 | SemaRef.Diag(Loc: IList->getBeginLoc(), |
1763 | DiagID: SemaRef.getLangOpts().CPlusPlus11 |
1764 | ? diag::warn_cxx98_compat_empty_scalar_initializer |
1765 | : diag::err_empty_scalar_initializer) |
1766 | << IList->getSourceRange(); |
1767 | } |
1768 | } |
1769 | hadError = |
1770 | SemaRef.getLangOpts().CPlusPlus && !SemaRef.getLangOpts().CPlusPlus11; |
1771 | ++Index; |
1772 | ++StructuredIndex; |
1773 | return; |
1774 | } |
1775 | |
1776 | Expr *expr = IList->getInit(Init: Index); |
1777 | if (InitListExpr *SubIList = dyn_cast<InitListExpr>(Val: expr)) { |
1778 | // FIXME: This is invalid, and accepting it causes overload resolution |
1779 | // to pick the wrong overload in some corner cases. |
1780 | if (!VerifyOnly) |
1781 | SemaRef.Diag(Loc: SubIList->getBeginLoc(), DiagID: diag::ext_many_braces_around_init) |
1782 | << DeclType->isSizelessBuiltinType() << SubIList->getSourceRange(); |
1783 | |
1784 | CheckScalarType(Entity, IList: SubIList, DeclType, Index, StructuredList, |
1785 | StructuredIndex); |
1786 | return; |
1787 | } else if (isa<DesignatedInitExpr>(Val: expr)) { |
1788 | if (!VerifyOnly) |
1789 | SemaRef.Diag(Loc: expr->getBeginLoc(), |
1790 | DiagID: diag::err_designator_for_scalar_or_sizeless_init) |
1791 | << DeclType->isSizelessBuiltinType() << DeclType |
1792 | << expr->getSourceRange(); |
1793 | hadError = true; |
1794 | ++Index; |
1795 | ++StructuredIndex; |
1796 | return; |
1797 | } else if (auto *Embed = dyn_cast<EmbedExpr>(Val: expr)) { |
1798 | expr = HandleEmbed(Embed, Entity); |
1799 | } |
1800 | |
1801 | ExprResult Result; |
1802 | if (VerifyOnly) { |
1803 | if (SemaRef.CanPerformCopyInitialization(Entity, Init: expr)) |
1804 | Result = getDummyInit(); |
1805 | else |
1806 | Result = ExprError(); |
1807 | } else { |
1808 | Result = |
1809 | SemaRef.PerformCopyInitialization(Entity, EqualLoc: expr->getBeginLoc(), Init: expr, |
1810 | /*TopLevelOfInitList=*/true); |
1811 | } |
1812 | |
1813 | Expr *ResultExpr = nullptr; |
1814 | |
1815 | if (Result.isInvalid()) |
1816 | hadError = true; // types weren't compatible. |
1817 | else { |
1818 | ResultExpr = Result.getAs<Expr>(); |
1819 | |
1820 | if (ResultExpr != expr && !VerifyOnly && !CurEmbed) { |
1821 | // The type was promoted, update initializer list. |
1822 | // FIXME: Why are we updating the syntactic init list? |
1823 | IList->setInit(Init: Index, expr: ResultExpr); |
1824 | } |
1825 | } |
1826 | |
1827 | UpdateStructuredListElement(StructuredList, StructuredIndex, expr: ResultExpr); |
1828 | if (!CurEmbed) |
1829 | ++Index; |
1830 | if (AggrDeductionCandidateParamTypes) |
1831 | AggrDeductionCandidateParamTypes->push_back(Elt: DeclType); |
1832 | } |
1833 | |
1834 | void InitListChecker::CheckReferenceType(const InitializedEntity &Entity, |
1835 | InitListExpr *IList, QualType DeclType, |
1836 | unsigned &Index, |
1837 | InitListExpr *StructuredList, |
1838 | unsigned &StructuredIndex) { |
1839 | if (Index >= IList->getNumInits()) { |
1840 | // FIXME: It would be wonderful if we could point at the actual member. In |
1841 | // general, it would be useful to pass location information down the stack, |
1842 | // so that we know the location (or decl) of the "current object" being |
1843 | // initialized. |
1844 | if (!VerifyOnly) |
1845 | SemaRef.Diag(Loc: IList->getBeginLoc(), |
1846 | DiagID: diag::err_init_reference_member_uninitialized) |
1847 | << DeclType << IList->getSourceRange(); |
1848 | hadError = true; |
1849 | ++Index; |
1850 | ++StructuredIndex; |
1851 | return; |
1852 | } |
1853 | |
1854 | Expr *expr = IList->getInit(Init: Index); |
1855 | if (isa<InitListExpr>(Val: expr) && !SemaRef.getLangOpts().CPlusPlus11) { |
1856 | if (!VerifyOnly) |
1857 | SemaRef.Diag(Loc: IList->getBeginLoc(), DiagID: diag::err_init_non_aggr_init_list) |
1858 | << DeclType << IList->getSourceRange(); |
1859 | hadError = true; |
1860 | ++Index; |
1861 | ++StructuredIndex; |
1862 | return; |
1863 | } |
1864 | |
1865 | ExprResult Result; |
1866 | if (VerifyOnly) { |
1867 | if (SemaRef.CanPerformCopyInitialization(Entity,Init: expr)) |
1868 | Result = getDummyInit(); |
1869 | else |
1870 | Result = ExprError(); |
1871 | } else { |
1872 | Result = |
1873 | SemaRef.PerformCopyInitialization(Entity, EqualLoc: expr->getBeginLoc(), Init: expr, |
1874 | /*TopLevelOfInitList=*/true); |
1875 | } |
1876 | |
1877 | if (Result.isInvalid()) |
1878 | hadError = true; |
1879 | |
1880 | expr = Result.getAs<Expr>(); |
1881 | // FIXME: Why are we updating the syntactic init list? |
1882 | if (!VerifyOnly && expr) |
1883 | IList->setInit(Init: Index, expr); |
1884 | |
1885 | UpdateStructuredListElement(StructuredList, StructuredIndex, expr); |
1886 | ++Index; |
1887 | if (AggrDeductionCandidateParamTypes) |
1888 | AggrDeductionCandidateParamTypes->push_back(Elt: DeclType); |
1889 | } |
1890 | |
1891 | void InitListChecker::CheckVectorType(const InitializedEntity &Entity, |
1892 | InitListExpr *IList, QualType DeclType, |
1893 | unsigned &Index, |
1894 | InitListExpr *StructuredList, |
1895 | unsigned &StructuredIndex) { |
1896 | const VectorType *VT = DeclType->castAs<VectorType>(); |
1897 | unsigned maxElements = VT->getNumElements(); |
1898 | unsigned numEltsInit = 0; |
1899 | QualType elementType = VT->getElementType(); |
1900 | |
1901 | if (Index >= IList->getNumInits()) { |
1902 | // Make sure the element type can be value-initialized. |
1903 | CheckEmptyInitializable( |
1904 | Entity: InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity), |
1905 | Loc: IList->getEndLoc()); |
1906 | return; |
1907 | } |
1908 | |
1909 | if (!SemaRef.getLangOpts().OpenCL && !SemaRef.getLangOpts().HLSL ) { |
1910 | // If the initializing element is a vector, try to copy-initialize |
1911 | // instead of breaking it apart (which is doomed to failure anyway). |
1912 | Expr *Init = IList->getInit(Init: Index); |
1913 | if (!isa<InitListExpr>(Val: Init) && Init->getType()->isVectorType()) { |
1914 | ExprResult Result; |
1915 | if (VerifyOnly) { |
1916 | if (SemaRef.CanPerformCopyInitialization(Entity, Init)) |
1917 | Result = getDummyInit(); |
1918 | else |
1919 | Result = ExprError(); |
1920 | } else { |
1921 | Result = |
1922 | SemaRef.PerformCopyInitialization(Entity, EqualLoc: Init->getBeginLoc(), Init, |
1923 | /*TopLevelOfInitList=*/true); |
1924 | } |
1925 | |
1926 | Expr *ResultExpr = nullptr; |
1927 | if (Result.isInvalid()) |
1928 | hadError = true; // types weren't compatible. |
1929 | else { |
1930 | ResultExpr = Result.getAs<Expr>(); |
1931 | |
1932 | if (ResultExpr != Init && !VerifyOnly) { |
1933 | // The type was promoted, update initializer list. |
1934 | // FIXME: Why are we updating the syntactic init list? |
1935 | IList->setInit(Init: Index, expr: ResultExpr); |
1936 | } |
1937 | } |
1938 | UpdateStructuredListElement(StructuredList, StructuredIndex, expr: ResultExpr); |
1939 | ++Index; |
1940 | if (AggrDeductionCandidateParamTypes) |
1941 | AggrDeductionCandidateParamTypes->push_back(Elt: elementType); |
1942 | return; |
1943 | } |
1944 | |
1945 | InitializedEntity ElementEntity = |
1946 | InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity); |
1947 | |
1948 | for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) { |
1949 | // Don't attempt to go past the end of the init list |
1950 | if (Index >= IList->getNumInits()) { |
1951 | CheckEmptyInitializable(Entity: ElementEntity, Loc: IList->getEndLoc()); |
1952 | break; |
1953 | } |
1954 | |
1955 | ElementEntity.setElementIndex(Index); |
1956 | CheckSubElementType(Entity: ElementEntity, IList, ElemType: elementType, Index, |
1957 | StructuredList, StructuredIndex); |
1958 | } |
1959 | |
1960 | if (VerifyOnly) |
1961 | return; |
1962 | |
1963 | bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian(); |
1964 | const VectorType *T = Entity.getType()->castAs<VectorType>(); |
1965 | if (isBigEndian && (T->getVectorKind() == VectorKind::Neon || |
1966 | T->getVectorKind() == VectorKind::NeonPoly)) { |
1967 | // The ability to use vector initializer lists is a GNU vector extension |
1968 | // and is unrelated to the NEON intrinsics in arm_neon.h. On little |
1969 | // endian machines it works fine, however on big endian machines it |
1970 | // exhibits surprising behaviour: |
1971 | // |
1972 | // uint32x2_t x = {42, 64}; |
1973 | // return vget_lane_u32(x, 0); // Will return 64. |
1974 | // |
1975 | // Because of this, explicitly call out that it is non-portable. |
1976 | // |
1977 | SemaRef.Diag(Loc: IList->getBeginLoc(), |
1978 | DiagID: diag::warn_neon_vector_initializer_non_portable); |
1979 | |
1980 | const char *typeCode; |
1981 | unsigned typeSize = SemaRef.Context.getTypeSize(T: elementType); |
1982 | |
1983 | if (elementType->isFloatingType()) |
1984 | typeCode = "f" ; |
1985 | else if (elementType->isSignedIntegerType()) |
1986 | typeCode = "s" ; |
1987 | else if (elementType->isUnsignedIntegerType()) |
1988 | typeCode = "u" ; |
1989 | else if (elementType->isMFloat8Type()) |
1990 | typeCode = "mf" ; |
1991 | else |
1992 | llvm_unreachable("Invalid element type!" ); |
1993 | |
1994 | SemaRef.Diag(Loc: IList->getBeginLoc(), |
1995 | DiagID: SemaRef.Context.getTypeSize(T: VT) > 64 |
1996 | ? diag::note_neon_vector_initializer_non_portable_q |
1997 | : diag::note_neon_vector_initializer_non_portable) |
1998 | << typeCode << typeSize; |
1999 | } |
2000 | |
2001 | return; |
2002 | } |
2003 | |
2004 | InitializedEntity ElementEntity = |
2005 | InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity); |
2006 | |
2007 | // OpenCL and HLSL initializers allow vectors to be constructed from vectors. |
2008 | for (unsigned i = 0; i < maxElements; ++i) { |
2009 | // Don't attempt to go past the end of the init list |
2010 | if (Index >= IList->getNumInits()) |
2011 | break; |
2012 | |
2013 | ElementEntity.setElementIndex(Index); |
2014 | |
2015 | QualType IType = IList->getInit(Init: Index)->getType(); |
2016 | if (!IType->isVectorType()) { |
2017 | CheckSubElementType(Entity: ElementEntity, IList, ElemType: elementType, Index, |
2018 | StructuredList, StructuredIndex); |
2019 | ++numEltsInit; |
2020 | } else { |
2021 | QualType VecType; |
2022 | const VectorType *IVT = IType->castAs<VectorType>(); |
2023 | unsigned numIElts = IVT->getNumElements(); |
2024 | |
2025 | if (IType->isExtVectorType()) |
2026 | VecType = SemaRef.Context.getExtVectorType(VectorType: elementType, NumElts: numIElts); |
2027 | else |
2028 | VecType = SemaRef.Context.getVectorType(VectorType: elementType, NumElts: numIElts, |
2029 | VecKind: IVT->getVectorKind()); |
2030 | CheckSubElementType(Entity: ElementEntity, IList, ElemType: VecType, Index, |
2031 | StructuredList, StructuredIndex); |
2032 | numEltsInit += numIElts; |
2033 | } |
2034 | } |
2035 | |
2036 | // OpenCL and HLSL require all elements to be initialized. |
2037 | if (numEltsInit != maxElements) { |
2038 | if (!VerifyOnly) |
2039 | SemaRef.Diag(Loc: IList->getBeginLoc(), |
2040 | DiagID: diag::err_vector_incorrect_num_elements) |
2041 | << (numEltsInit < maxElements) << maxElements << numEltsInit |
2042 | << /*initialization*/ 0; |
2043 | hadError = true; |
2044 | } |
2045 | } |
2046 | |
2047 | /// Check if the type of a class element has an accessible destructor, and marks |
2048 | /// it referenced. Returns true if we shouldn't form a reference to the |
2049 | /// destructor. |
2050 | /// |
2051 | /// Aggregate initialization requires a class element's destructor be |
2052 | /// accessible per 11.6.1 [dcl.init.aggr]: |
2053 | /// |
2054 | /// The destructor for each element of class type is potentially invoked |
2055 | /// (15.4 [class.dtor]) from the context where the aggregate initialization |
2056 | /// occurs. |
2057 | static bool checkDestructorReference(QualType ElementType, SourceLocation Loc, |
2058 | Sema &SemaRef) { |
2059 | auto *CXXRD = ElementType->getAsCXXRecordDecl(); |
2060 | if (!CXXRD) |
2061 | return false; |
2062 | |
2063 | CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Class: CXXRD); |
2064 | if (!Destructor) |
2065 | return false; |
2066 | |
2067 | SemaRef.CheckDestructorAccess(Loc, Dtor: Destructor, |
2068 | PDiag: SemaRef.PDiag(DiagID: diag::err_access_dtor_temp) |
2069 | << ElementType); |
2070 | SemaRef.MarkFunctionReferenced(Loc, Func: Destructor); |
2071 | return SemaRef.DiagnoseUseOfDecl(D: Destructor, Locs: Loc); |
2072 | } |
2073 | |
2074 | static bool |
2075 | canInitializeArrayWithEmbedDataString(ArrayRef<Expr *> ExprList, |
2076 | const InitializedEntity &Entity, |
2077 | ASTContext &Context) { |
2078 | QualType InitType = Entity.getType(); |
2079 | const InitializedEntity *Parent = &Entity; |
2080 | |
2081 | while (Parent) { |
2082 | InitType = Parent->getType(); |
2083 | Parent = Parent->getParent(); |
2084 | } |
2085 | |
2086 | // Only one initializer, it's an embed and the types match; |
2087 | EmbedExpr *EE = |
2088 | ExprList.size() == 1 |
2089 | ? dyn_cast_if_present<EmbedExpr>(Val: ExprList[0]->IgnoreParens()) |
2090 | : nullptr; |
2091 | if (!EE) |
2092 | return false; |
2093 | |
2094 | if (InitType->isArrayType()) { |
2095 | const ArrayType *InitArrayType = InitType->getAsArrayTypeUnsafe(); |
2096 | StringLiteral *SL = EE->getDataStringLiteral(); |
2097 | return IsStringInit(Init: SL, AT: InitArrayType, Context) == SIF_None; |
2098 | } |
2099 | return false; |
2100 | } |
2101 | |
2102 | void InitListChecker::CheckArrayType(const InitializedEntity &Entity, |
2103 | InitListExpr *IList, QualType &DeclType, |
2104 | llvm::APSInt elementIndex, |
2105 | bool SubobjectIsDesignatorContext, |
2106 | unsigned &Index, |
2107 | InitListExpr *StructuredList, |
2108 | unsigned &StructuredIndex) { |
2109 | const ArrayType *arrayType = SemaRef.Context.getAsArrayType(T: DeclType); |
2110 | |
2111 | if (!VerifyOnly) { |
2112 | if (checkDestructorReference(ElementType: arrayType->getElementType(), |
2113 | Loc: IList->getEndLoc(), SemaRef)) { |
2114 | hadError = true; |
2115 | return; |
2116 | } |
2117 | } |
2118 | |
2119 | if (canInitializeArrayWithEmbedDataString(ExprList: IList->inits(), Entity, |
2120 | Context&: SemaRef.Context)) { |
2121 | EmbedExpr *Embed = cast<EmbedExpr>(Val: IList->inits()[0]); |
2122 | IList->setInit(Init: 0, expr: Embed->getDataStringLiteral()); |
2123 | } |
2124 | |
2125 | // Check for the special-case of initializing an array with a string. |
2126 | if (Index < IList->getNumInits()) { |
2127 | if (IsStringInit(Init: IList->getInit(Init: Index), AT: arrayType, Context&: SemaRef.Context) == |
2128 | SIF_None) { |
2129 | // We place the string literal directly into the resulting |
2130 | // initializer list. This is the only place where the structure |
2131 | // of the structured initializer list doesn't match exactly, |
2132 | // because doing so would involve allocating one character |
2133 | // constant for each string. |
2134 | // FIXME: Should we do these checks in verify-only mode too? |
2135 | if (!VerifyOnly) |
2136 | CheckStringInit( |
2137 | Str: IList->getInit(Init: Index), DeclT&: DeclType, AT: arrayType, S&: SemaRef, Entity, |
2138 | CheckC23ConstexprInit: SemaRef.getLangOpts().C23 && initializingConstexprVariable(Entity)); |
2139 | if (StructuredList) { |
2140 | UpdateStructuredListElement(StructuredList, StructuredIndex, |
2141 | expr: IList->getInit(Init: Index)); |
2142 | StructuredList->resizeInits(Context: SemaRef.Context, NumInits: StructuredIndex); |
2143 | } |
2144 | ++Index; |
2145 | if (AggrDeductionCandidateParamTypes) |
2146 | AggrDeductionCandidateParamTypes->push_back(Elt: DeclType); |
2147 | return; |
2148 | } |
2149 | } |
2150 | if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Val: arrayType)) { |
2151 | // Check for VLAs; in standard C it would be possible to check this |
2152 | // earlier, but I don't know where clang accepts VLAs (gcc accepts |
2153 | // them in all sorts of strange places). |
2154 | bool HasErr = IList->getNumInits() != 0 || SemaRef.getLangOpts().CPlusPlus; |
2155 | if (!VerifyOnly) { |
2156 | // C23 6.7.10p4: An entity of variable length array type shall not be |
2157 | // initialized except by an empty initializer. |
2158 | // |
2159 | // The C extension warnings are issued from ParseBraceInitializer() and |
2160 | // do not need to be issued here. However, we continue to issue an error |
2161 | // in the case there are initializers or we are compiling C++. We allow |
2162 | // use of VLAs in C++, but it's not clear we want to allow {} to zero |
2163 | // init a VLA in C++ in all cases (such as with non-trivial constructors). |
2164 | // FIXME: should we allow this construct in C++ when it makes sense to do |
2165 | // so? |
2166 | if (HasErr) |
2167 | SemaRef.Diag(Loc: VAT->getSizeExpr()->getBeginLoc(), |
2168 | DiagID: diag::err_variable_object_no_init) |
2169 | << VAT->getSizeExpr()->getSourceRange(); |
2170 | } |
2171 | hadError = HasErr; |
2172 | ++Index; |
2173 | ++StructuredIndex; |
2174 | return; |
2175 | } |
2176 | |
2177 | // We might know the maximum number of elements in advance. |
2178 | llvm::APSInt maxElements(elementIndex.getBitWidth(), |
2179 | elementIndex.isUnsigned()); |
2180 | bool maxElementsKnown = false; |
2181 | if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Val: arrayType)) { |
2182 | maxElements = CAT->getSize(); |
2183 | elementIndex = elementIndex.extOrTrunc(width: maxElements.getBitWidth()); |
2184 | elementIndex.setIsUnsigned(maxElements.isUnsigned()); |
2185 | maxElementsKnown = true; |
2186 | } |
2187 | |
2188 | QualType elementType = arrayType->getElementType(); |
2189 | while (Index < IList->getNumInits()) { |
2190 | Expr *Init = IList->getInit(Init: Index); |
2191 | if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Val: Init)) { |
2192 | // If we're not the subobject that matches up with the '{' for |
2193 | // the designator, we shouldn't be handling the |
2194 | // designator. Return immediately. |
2195 | if (!SubobjectIsDesignatorContext) |
2196 | return; |
2197 | |
2198 | // Handle this designated initializer. elementIndex will be |
2199 | // updated to be the next array element we'll initialize. |
2200 | if (CheckDesignatedInitializer(Entity, IList, DIE, DesigIdx: 0, |
2201 | CurrentObjectType&: DeclType, NextField: nullptr, NextElementIndex: &elementIndex, Index, |
2202 | StructuredList, StructuredIndex, FinishSubobjectInit: true, |
2203 | TopLevelObject: false)) { |
2204 | hadError = true; |
2205 | continue; |
2206 | } |
2207 | |
2208 | if (elementIndex.getBitWidth() > maxElements.getBitWidth()) |
2209 | maxElements = maxElements.extend(width: elementIndex.getBitWidth()); |
2210 | else if (elementIndex.getBitWidth() < maxElements.getBitWidth()) |
2211 | elementIndex = elementIndex.extend(width: maxElements.getBitWidth()); |
2212 | elementIndex.setIsUnsigned(maxElements.isUnsigned()); |
2213 | |
2214 | // If the array is of incomplete type, keep track of the number of |
2215 | // elements in the initializer. |
2216 | if (!maxElementsKnown && elementIndex > maxElements) |
2217 | maxElements = elementIndex; |
2218 | |
2219 | continue; |
2220 | } |
2221 | |
2222 | // If we know the maximum number of elements, and we've already |
2223 | // hit it, stop consuming elements in the initializer list. |
2224 | if (maxElementsKnown && elementIndex == maxElements) |
2225 | break; |
2226 | |
2227 | InitializedEntity ElementEntity = InitializedEntity::InitializeElement( |
2228 | Context&: SemaRef.Context, Index: StructuredIndex, Parent: Entity); |
2229 | ElementEntity.setElementIndex(elementIndex.getExtValue()); |
2230 | |
2231 | unsigned EmbedElementIndexBeforeInit = CurEmbedIndex; |
2232 | // Check this element. |
2233 | CheckSubElementType(Entity: ElementEntity, IList, ElemType: elementType, Index, |
2234 | StructuredList, StructuredIndex); |
2235 | ++elementIndex; |
2236 | if ((CurEmbed || isa<EmbedExpr>(Val: Init)) && elementType->isScalarType()) { |
2237 | if (CurEmbed) { |
2238 | elementIndex = |
2239 | elementIndex + CurEmbedIndex - EmbedElementIndexBeforeInit - 1; |
2240 | } else { |
2241 | auto Embed = cast<EmbedExpr>(Val: Init); |
2242 | elementIndex = elementIndex + Embed->getDataElementCount() - |
2243 | EmbedElementIndexBeforeInit - 1; |
2244 | } |
2245 | } |
2246 | |
2247 | // If the array is of incomplete type, keep track of the number of |
2248 | // elements in the initializer. |
2249 | if (!maxElementsKnown && elementIndex > maxElements) |
2250 | maxElements = elementIndex; |
2251 | } |
2252 | if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) { |
2253 | // If this is an incomplete array type, the actual type needs to |
2254 | // be calculated here. |
2255 | llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned()); |
2256 | if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) { |
2257 | // Sizing an array implicitly to zero is not allowed by ISO C, |
2258 | // but is supported by GNU. |
2259 | SemaRef.Diag(Loc: IList->getBeginLoc(), DiagID: diag::ext_typecheck_zero_array_size); |
2260 | } |
2261 | |
2262 | DeclType = SemaRef.Context.getConstantArrayType( |
2263 | EltTy: elementType, ArySize: maxElements, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0); |
2264 | } |
2265 | if (!hadError) { |
2266 | // If there are any members of the array that get value-initialized, check |
2267 | // that is possible. That happens if we know the bound and don't have |
2268 | // enough elements, or if we're performing an array new with an unknown |
2269 | // bound. |
2270 | if ((maxElementsKnown && elementIndex < maxElements) || |
2271 | Entity.isVariableLengthArrayNew()) |
2272 | CheckEmptyInitializable( |
2273 | Entity: InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity), |
2274 | Loc: IList->getEndLoc()); |
2275 | } |
2276 | } |
2277 | |
2278 | bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity, |
2279 | Expr *InitExpr, |
2280 | FieldDecl *Field, |
2281 | bool TopLevelObject) { |
2282 | // Handle GNU flexible array initializers. |
2283 | unsigned FlexArrayDiag; |
2284 | if (isa<InitListExpr>(Val: InitExpr) && |
2285 | cast<InitListExpr>(Val: InitExpr)->getNumInits() == 0) { |
2286 | // Empty flexible array init always allowed as an extension |
2287 | FlexArrayDiag = diag::ext_flexible_array_init; |
2288 | } else if (!TopLevelObject) { |
2289 | // Disallow flexible array init on non-top-level object |
2290 | FlexArrayDiag = diag::err_flexible_array_init; |
2291 | } else if (Entity.getKind() != InitializedEntity::EK_Variable) { |
2292 | // Disallow flexible array init on anything which is not a variable. |
2293 | FlexArrayDiag = diag::err_flexible_array_init; |
2294 | } else if (cast<VarDecl>(Val: Entity.getDecl())->hasLocalStorage()) { |
2295 | // Disallow flexible array init on local variables. |
2296 | FlexArrayDiag = diag::err_flexible_array_init; |
2297 | } else { |
2298 | // Allow other cases. |
2299 | FlexArrayDiag = diag::ext_flexible_array_init; |
2300 | } |
2301 | |
2302 | if (!VerifyOnly) { |
2303 | SemaRef.Diag(Loc: InitExpr->getBeginLoc(), DiagID: FlexArrayDiag) |
2304 | << InitExpr->getBeginLoc(); |
2305 | SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_flexible_array_member) |
2306 | << Field; |
2307 | } |
2308 | |
2309 | return FlexArrayDiag != diag::ext_flexible_array_init; |
2310 | } |
2311 | |
2312 | static bool isInitializedStructuredList(const InitListExpr *StructuredList) { |
2313 | return StructuredList && StructuredList->getNumInits() == 1U; |
2314 | } |
2315 | |
2316 | void InitListChecker::CheckStructUnionTypes( |
2317 | const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType, |
2318 | CXXRecordDecl::base_class_const_range Bases, RecordDecl::field_iterator Field, |
2319 | bool SubobjectIsDesignatorContext, unsigned &Index, |
2320 | InitListExpr *StructuredList, unsigned &StructuredIndex, |
2321 | bool TopLevelObject) { |
2322 | const RecordDecl *RD = getRecordDecl(DeclType); |
2323 | |
2324 | // If the record is invalid, some of it's members are invalid. To avoid |
2325 | // confusion, we forgo checking the initializer for the entire record. |
2326 | if (RD->isInvalidDecl()) { |
2327 | // Assume it was supposed to consume a single initializer. |
2328 | ++Index; |
2329 | hadError = true; |
2330 | return; |
2331 | } |
2332 | |
2333 | if (RD->isUnion() && IList->getNumInits() == 0) { |
2334 | if (!VerifyOnly) |
2335 | for (FieldDecl *FD : RD->fields()) { |
2336 | QualType ET = SemaRef.Context.getBaseElementType(QT: FD->getType()); |
2337 | if (checkDestructorReference(ElementType: ET, Loc: IList->getEndLoc(), SemaRef)) { |
2338 | hadError = true; |
2339 | return; |
2340 | } |
2341 | } |
2342 | |
2343 | // If there's a default initializer, use it. |
2344 | if (isa<CXXRecordDecl>(Val: RD) && |
2345 | cast<CXXRecordDecl>(Val: RD)->hasInClassInitializer()) { |
2346 | if (!StructuredList) |
2347 | return; |
2348 | for (RecordDecl::field_iterator FieldEnd = RD->field_end(); |
2349 | Field != FieldEnd; ++Field) { |
2350 | if (Field->hasInClassInitializer() || |
2351 | (Field->isAnonymousStructOrUnion() && |
2352 | Field->getType()->getAsCXXRecordDecl()->hasInClassInitializer())) { |
2353 | StructuredList->setInitializedFieldInUnion(*Field); |
2354 | // FIXME: Actually build a CXXDefaultInitExpr? |
2355 | return; |
2356 | } |
2357 | } |
2358 | llvm_unreachable("Couldn't find in-class initializer" ); |
2359 | } |
2360 | |
2361 | // Value-initialize the first member of the union that isn't an unnamed |
2362 | // bitfield. |
2363 | for (RecordDecl::field_iterator FieldEnd = RD->field_end(); |
2364 | Field != FieldEnd; ++Field) { |
2365 | if (!Field->isUnnamedBitField()) { |
2366 | CheckEmptyInitializable( |
2367 | Entity: InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity), |
2368 | Loc: IList->getEndLoc()); |
2369 | if (StructuredList) |
2370 | StructuredList->setInitializedFieldInUnion(*Field); |
2371 | break; |
2372 | } |
2373 | } |
2374 | return; |
2375 | } |
2376 | |
2377 | bool InitializedSomething = false; |
2378 | |
2379 | // If we have any base classes, they are initialized prior to the fields. |
2380 | for (auto I = Bases.begin(), E = Bases.end(); I != E; ++I) { |
2381 | auto &Base = *I; |
2382 | Expr *Init = Index < IList->getNumInits() ? IList->getInit(Init: Index) : nullptr; |
2383 | |
2384 | // Designated inits always initialize fields, so if we see one, all |
2385 | // remaining base classes have no explicit initializer. |
2386 | if (isa_and_nonnull<DesignatedInitExpr>(Val: Init)) |
2387 | Init = nullptr; |
2388 | |
2389 | // C++ [over.match.class.deduct]p1.6: |
2390 | // each non-trailing aggregate element that is a pack expansion is assumed |
2391 | // to correspond to no elements of the initializer list, and (1.7) a |
2392 | // trailing aggregate element that is a pack expansion is assumed to |
2393 | // correspond to all remaining elements of the initializer list (if any). |
2394 | |
2395 | // C++ [over.match.class.deduct]p1.9: |
2396 | // ... except that additional parameter packs of the form P_j... are |
2397 | // inserted into the parameter list in their original aggregate element |
2398 | // position corresponding to each non-trailing aggregate element of |
2399 | // type P_j that was skipped because it was a parameter pack, and the |
2400 | // trailing sequence of parameters corresponding to a trailing |
2401 | // aggregate element that is a pack expansion (if any) is replaced |
2402 | // by a single parameter of the form T_n.... |
2403 | if (AggrDeductionCandidateParamTypes && Base.isPackExpansion()) { |
2404 | AggrDeductionCandidateParamTypes->push_back( |
2405 | Elt: SemaRef.Context.getPackExpansionType(Pattern: Base.getType(), NumExpansions: std::nullopt)); |
2406 | |
2407 | // Trailing pack expansion |
2408 | if (I + 1 == E && RD->field_empty()) { |
2409 | if (Index < IList->getNumInits()) |
2410 | Index = IList->getNumInits(); |
2411 | return; |
2412 | } |
2413 | |
2414 | continue; |
2415 | } |
2416 | |
2417 | SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc(); |
2418 | InitializedEntity BaseEntity = InitializedEntity::InitializeBase( |
2419 | Context&: SemaRef.Context, Base: &Base, IsInheritedVirtualBase: false, Parent: &Entity); |
2420 | if (Init) { |
2421 | CheckSubElementType(Entity: BaseEntity, IList, ElemType: Base.getType(), Index, |
2422 | StructuredList, StructuredIndex); |
2423 | InitializedSomething = true; |
2424 | } else { |
2425 | CheckEmptyInitializable(Entity: BaseEntity, Loc: InitLoc); |
2426 | } |
2427 | |
2428 | if (!VerifyOnly) |
2429 | if (checkDestructorReference(ElementType: Base.getType(), Loc: InitLoc, SemaRef)) { |
2430 | hadError = true; |
2431 | return; |
2432 | } |
2433 | } |
2434 | |
2435 | // If structDecl is a forward declaration, this loop won't do |
2436 | // anything except look at designated initializers; That's okay, |
2437 | // because an error should get printed out elsewhere. It might be |
2438 | // worthwhile to skip over the rest of the initializer, though. |
2439 | RecordDecl::field_iterator FieldEnd = RD->field_end(); |
2440 | size_t NumRecordDecls = llvm::count_if(Range: RD->decls(), P: [&](const Decl *D) { |
2441 | return isa<FieldDecl>(Val: D) || isa<RecordDecl>(Val: D); |
2442 | }); |
2443 | bool HasDesignatedInit = false; |
2444 | |
2445 | llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields; |
2446 | |
2447 | while (Index < IList->getNumInits()) { |
2448 | Expr *Init = IList->getInit(Init: Index); |
2449 | SourceLocation InitLoc = Init->getBeginLoc(); |
2450 | |
2451 | if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Val: Init)) { |
2452 | // If we're not the subobject that matches up with the '{' for |
2453 | // the designator, we shouldn't be handling the |
2454 | // designator. Return immediately. |
2455 | if (!SubobjectIsDesignatorContext) |
2456 | return; |
2457 | |
2458 | HasDesignatedInit = true; |
2459 | |
2460 | // Handle this designated initializer. Field will be updated to |
2461 | // the next field that we'll be initializing. |
2462 | bool DesignatedInitFailed = CheckDesignatedInitializer( |
2463 | Entity, IList, DIE, DesigIdx: 0, CurrentObjectType&: DeclType, NextField: &Field, NextElementIndex: nullptr, Index, |
2464 | StructuredList, StructuredIndex, FinishSubobjectInit: true, TopLevelObject); |
2465 | if (DesignatedInitFailed) |
2466 | hadError = true; |
2467 | |
2468 | // Find the field named by the designated initializer. |
2469 | DesignatedInitExpr::Designator *D = DIE->getDesignator(Idx: 0); |
2470 | if (!VerifyOnly && D->isFieldDesignator()) { |
2471 | FieldDecl *F = D->getFieldDecl(); |
2472 | InitializedFields.insert(Ptr: F); |
2473 | if (!DesignatedInitFailed) { |
2474 | QualType ET = SemaRef.Context.getBaseElementType(QT: F->getType()); |
2475 | if (checkDestructorReference(ElementType: ET, Loc: InitLoc, SemaRef)) { |
2476 | hadError = true; |
2477 | return; |
2478 | } |
2479 | } |
2480 | } |
2481 | |
2482 | InitializedSomething = true; |
2483 | continue; |
2484 | } |
2485 | |
2486 | // Check if this is an initializer of forms: |
2487 | // |
2488 | // struct foo f = {}; |
2489 | // struct foo g = {0}; |
2490 | // |
2491 | // These are okay for randomized structures. [C99 6.7.8p19] |
2492 | // |
2493 | // Also, if there is only one element in the structure, we allow something |
2494 | // like this, because it's really not randomized in the traditional sense. |
2495 | // |
2496 | // struct foo h = {bar}; |
2497 | auto IsZeroInitializer = [&](const Expr *I) { |
2498 | if (IList->getNumInits() == 1) { |
2499 | if (NumRecordDecls == 1) |
2500 | return true; |
2501 | if (const auto *IL = dyn_cast<IntegerLiteral>(Val: I)) |
2502 | return IL->getValue().isZero(); |
2503 | } |
2504 | return false; |
2505 | }; |
2506 | |
2507 | // Don't allow non-designated initializers on randomized structures. |
2508 | if (RD->isRandomized() && !IsZeroInitializer(Init)) { |
2509 | if (!VerifyOnly) |
2510 | SemaRef.Diag(Loc: InitLoc, DiagID: diag::err_non_designated_init_used); |
2511 | hadError = true; |
2512 | break; |
2513 | } |
2514 | |
2515 | if (Field == FieldEnd) { |
2516 | // We've run out of fields. We're done. |
2517 | break; |
2518 | } |
2519 | |
2520 | // We've already initialized a member of a union. We can stop entirely. |
2521 | if (InitializedSomething && RD->isUnion()) |
2522 | return; |
2523 | |
2524 | // Stop if we've hit a flexible array member. |
2525 | if (Field->getType()->isIncompleteArrayType()) |
2526 | break; |
2527 | |
2528 | if (Field->isUnnamedBitField()) { |
2529 | // Don't initialize unnamed bitfields, e.g. "int : 20;" |
2530 | ++Field; |
2531 | continue; |
2532 | } |
2533 | |
2534 | // Make sure we can use this declaration. |
2535 | bool InvalidUse; |
2536 | if (VerifyOnly) |
2537 | InvalidUse = !SemaRef.CanUseDecl(D: *Field, TreatUnavailableAsInvalid); |
2538 | else |
2539 | InvalidUse = SemaRef.DiagnoseUseOfDecl( |
2540 | D: *Field, Locs: IList->getInit(Init: Index)->getBeginLoc()); |
2541 | if (InvalidUse) { |
2542 | ++Index; |
2543 | ++Field; |
2544 | hadError = true; |
2545 | continue; |
2546 | } |
2547 | |
2548 | if (!VerifyOnly) { |
2549 | QualType ET = SemaRef.Context.getBaseElementType(QT: Field->getType()); |
2550 | if (checkDestructorReference(ElementType: ET, Loc: InitLoc, SemaRef)) { |
2551 | hadError = true; |
2552 | return; |
2553 | } |
2554 | } |
2555 | |
2556 | InitializedEntity MemberEntity = |
2557 | InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity); |
2558 | CheckSubElementType(Entity: MemberEntity, IList, ElemType: Field->getType(), Index, |
2559 | StructuredList, StructuredIndex); |
2560 | InitializedSomething = true; |
2561 | InitializedFields.insert(Ptr: *Field); |
2562 | if (RD->isUnion() && isInitializedStructuredList(StructuredList)) { |
2563 | // Initialize the first field within the union. |
2564 | StructuredList->setInitializedFieldInUnion(*Field); |
2565 | } |
2566 | |
2567 | ++Field; |
2568 | } |
2569 | |
2570 | // Emit warnings for missing struct field initializers. |
2571 | // This check is disabled for designated initializers in C. |
2572 | // This matches gcc behaviour. |
2573 | bool IsCDesignatedInitializer = |
2574 | HasDesignatedInit && !SemaRef.getLangOpts().CPlusPlus; |
2575 | if (!VerifyOnly && InitializedSomething && !RD->isUnion() && |
2576 | !IList->isIdiomaticZeroInitializer(LangOpts: SemaRef.getLangOpts()) && |
2577 | !IsCDesignatedInitializer) { |
2578 | // It is possible we have one or more unnamed bitfields remaining. |
2579 | // Find first (if any) named field and emit warning. |
2580 | for (RecordDecl::field_iterator it = HasDesignatedInit ? RD->field_begin() |
2581 | : Field, |
2582 | end = RD->field_end(); |
2583 | it != end; ++it) { |
2584 | if (HasDesignatedInit && InitializedFields.count(Ptr: *it)) |
2585 | continue; |
2586 | |
2587 | if (!it->isUnnamedBitField() && !it->hasInClassInitializer() && |
2588 | !it->getType()->isIncompleteArrayType()) { |
2589 | auto Diag = HasDesignatedInit |
2590 | ? diag::warn_missing_designated_field_initializers |
2591 | : diag::warn_missing_field_initializers; |
2592 | SemaRef.Diag(Loc: IList->getSourceRange().getEnd(), DiagID: Diag) << *it; |
2593 | break; |
2594 | } |
2595 | } |
2596 | } |
2597 | |
2598 | // Check that any remaining fields can be value-initialized if we're not |
2599 | // building a structured list. (If we are, we'll check this later.) |
2600 | if (!StructuredList && Field != FieldEnd && !RD->isUnion() && |
2601 | !Field->getType()->isIncompleteArrayType()) { |
2602 | for (; Field != FieldEnd && !hadError; ++Field) { |
2603 | if (!Field->isUnnamedBitField() && !Field->hasInClassInitializer()) |
2604 | CheckEmptyInitializable( |
2605 | Entity: InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity), |
2606 | Loc: IList->getEndLoc()); |
2607 | } |
2608 | } |
2609 | |
2610 | // Check that the types of the remaining fields have accessible destructors. |
2611 | if (!VerifyOnly) { |
2612 | // If the initializer expression has a designated initializer, check the |
2613 | // elements for which a designated initializer is not provided too. |
2614 | RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin() |
2615 | : Field; |
2616 | for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) { |
2617 | QualType ET = SemaRef.Context.getBaseElementType(QT: I->getType()); |
2618 | if (checkDestructorReference(ElementType: ET, Loc: IList->getEndLoc(), SemaRef)) { |
2619 | hadError = true; |
2620 | return; |
2621 | } |
2622 | } |
2623 | } |
2624 | |
2625 | if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() || |
2626 | Index >= IList->getNumInits()) |
2627 | return; |
2628 | |
2629 | if (CheckFlexibleArrayInit(Entity, InitExpr: IList->getInit(Init: Index), Field: *Field, |
2630 | TopLevelObject)) { |
2631 | hadError = true; |
2632 | ++Index; |
2633 | return; |
2634 | } |
2635 | |
2636 | InitializedEntity MemberEntity = |
2637 | InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity); |
2638 | |
2639 | if (isa<InitListExpr>(Val: IList->getInit(Init: Index)) || |
2640 | AggrDeductionCandidateParamTypes) |
2641 | CheckSubElementType(Entity: MemberEntity, IList, ElemType: Field->getType(), Index, |
2642 | StructuredList, StructuredIndex); |
2643 | else |
2644 | CheckImplicitInitList(Entity: MemberEntity, ParentIList: IList, T: Field->getType(), Index, |
2645 | StructuredList, StructuredIndex); |
2646 | |
2647 | if (RD->isUnion() && isInitializedStructuredList(StructuredList)) { |
2648 | // Initialize the first field within the union. |
2649 | StructuredList->setInitializedFieldInUnion(*Field); |
2650 | } |
2651 | } |
2652 | |
2653 | /// Expand a field designator that refers to a member of an |
2654 | /// anonymous struct or union into a series of field designators that |
2655 | /// refers to the field within the appropriate subobject. |
2656 | /// |
2657 | static void ExpandAnonymousFieldDesignator(Sema &SemaRef, |
2658 | DesignatedInitExpr *DIE, |
2659 | unsigned DesigIdx, |
2660 | IndirectFieldDecl *IndirectField) { |
2661 | typedef DesignatedInitExpr::Designator Designator; |
2662 | |
2663 | // Build the replacement designators. |
2664 | SmallVector<Designator, 4> Replacements; |
2665 | for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(), |
2666 | PE = IndirectField->chain_end(); PI != PE; ++PI) { |
2667 | if (PI + 1 == PE) |
2668 | Replacements.push_back(Elt: Designator::CreateFieldDesignator( |
2669 | FieldName: (IdentifierInfo *)nullptr, DotLoc: DIE->getDesignator(Idx: DesigIdx)->getDotLoc(), |
2670 | FieldLoc: DIE->getDesignator(Idx: DesigIdx)->getFieldLoc())); |
2671 | else |
2672 | Replacements.push_back(Elt: Designator::CreateFieldDesignator( |
2673 | FieldName: (IdentifierInfo *)nullptr, DotLoc: SourceLocation(), FieldLoc: SourceLocation())); |
2674 | assert(isa<FieldDecl>(*PI)); |
2675 | Replacements.back().setFieldDecl(cast<FieldDecl>(Val: *PI)); |
2676 | } |
2677 | |
2678 | // Expand the current designator into the set of replacement |
2679 | // designators, so we have a full subobject path down to where the |
2680 | // member of the anonymous struct/union is actually stored. |
2681 | DIE->ExpandDesignator(C: SemaRef.Context, Idx: DesigIdx, First: &Replacements[0], |
2682 | Last: &Replacements[0] + Replacements.size()); |
2683 | } |
2684 | |
2685 | static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef, |
2686 | DesignatedInitExpr *DIE) { |
2687 | unsigned NumIndexExprs = DIE->getNumSubExprs() - 1; |
2688 | SmallVector<Expr*, 4> IndexExprs(NumIndexExprs); |
2689 | for (unsigned I = 0; I < NumIndexExprs; ++I) |
2690 | IndexExprs[I] = DIE->getSubExpr(Idx: I + 1); |
2691 | return DesignatedInitExpr::Create(C: SemaRef.Context, Designators: DIE->designators(), |
2692 | IndexExprs, |
2693 | EqualOrColonLoc: DIE->getEqualOrColonLoc(), |
2694 | GNUSyntax: DIE->usesGNUSyntax(), Init: DIE->getInit()); |
2695 | } |
2696 | |
2697 | namespace { |
2698 | |
2699 | // Callback to only accept typo corrections that are for field members of |
2700 | // the given struct or union. |
2701 | class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback { |
2702 | public: |
2703 | explicit FieldInitializerValidatorCCC(const RecordDecl *RD) |
2704 | : Record(RD) {} |
2705 | |
2706 | bool ValidateCandidate(const TypoCorrection &candidate) override { |
2707 | FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>(); |
2708 | return FD && FD->getDeclContext()->getRedeclContext()->Equals(DC: Record); |
2709 | } |
2710 | |
2711 | std::unique_ptr<CorrectionCandidateCallback> clone() override { |
2712 | return std::make_unique<FieldInitializerValidatorCCC>(args&: *this); |
2713 | } |
2714 | |
2715 | private: |
2716 | const RecordDecl *Record; |
2717 | }; |
2718 | |
2719 | } // end anonymous namespace |
2720 | |
2721 | /// Check the well-formedness of a C99 designated initializer. |
2722 | /// |
2723 | /// Determines whether the designated initializer @p DIE, which |
2724 | /// resides at the given @p Index within the initializer list @p |
2725 | /// IList, is well-formed for a current object of type @p DeclType |
2726 | /// (C99 6.7.8). The actual subobject that this designator refers to |
2727 | /// within the current subobject is returned in either |
2728 | /// @p NextField or @p NextElementIndex (whichever is appropriate). |
2729 | /// |
2730 | /// @param IList The initializer list in which this designated |
2731 | /// initializer occurs. |
2732 | /// |
2733 | /// @param DIE The designated initializer expression. |
2734 | /// |
2735 | /// @param DesigIdx The index of the current designator. |
2736 | /// |
2737 | /// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17), |
2738 | /// into which the designation in @p DIE should refer. |
2739 | /// |
2740 | /// @param NextField If non-NULL and the first designator in @p DIE is |
2741 | /// a field, this will be set to the field declaration corresponding |
2742 | /// to the field named by the designator. On input, this is expected to be |
2743 | /// the next field that would be initialized in the absence of designation, |
2744 | /// if the complete object being initialized is a struct. |
2745 | /// |
2746 | /// @param NextElementIndex If non-NULL and the first designator in @p |
2747 | /// DIE is an array designator or GNU array-range designator, this |
2748 | /// will be set to the last index initialized by this designator. |
2749 | /// |
2750 | /// @param Index Index into @p IList where the designated initializer |
2751 | /// @p DIE occurs. |
2752 | /// |
2753 | /// @param StructuredList The initializer list expression that |
2754 | /// describes all of the subobject initializers in the order they'll |
2755 | /// actually be initialized. |
2756 | /// |
2757 | /// @returns true if there was an error, false otherwise. |
2758 | bool |
2759 | InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity, |
2760 | InitListExpr *IList, |
2761 | DesignatedInitExpr *DIE, |
2762 | unsigned DesigIdx, |
2763 | QualType &CurrentObjectType, |
2764 | RecordDecl::field_iterator *NextField, |
2765 | llvm::APSInt *NextElementIndex, |
2766 | unsigned &Index, |
2767 | InitListExpr *StructuredList, |
2768 | unsigned &StructuredIndex, |
2769 | bool FinishSubobjectInit, |
2770 | bool TopLevelObject) { |
2771 | if (DesigIdx == DIE->size()) { |
2772 | // C++20 designated initialization can result in direct-list-initialization |
2773 | // of the designated subobject. This is the only way that we can end up |
2774 | // performing direct initialization as part of aggregate initialization, so |
2775 | // it needs special handling. |
2776 | if (DIE->isDirectInit()) { |
2777 | Expr *Init = DIE->getInit(); |
2778 | assert(isa<InitListExpr>(Init) && |
2779 | "designator result in direct non-list initialization?" ); |
2780 | InitializationKind Kind = InitializationKind::CreateDirectList( |
2781 | InitLoc: DIE->getBeginLoc(), LBraceLoc: Init->getBeginLoc(), RBraceLoc: Init->getEndLoc()); |
2782 | InitializationSequence Seq(SemaRef, Entity, Kind, Init, |
2783 | /*TopLevelOfInitList*/ true); |
2784 | if (StructuredList) { |
2785 | ExprResult Result = VerifyOnly |
2786 | ? getDummyInit() |
2787 | : Seq.Perform(S&: SemaRef, Entity, Kind, Args: Init); |
2788 | UpdateStructuredListElement(StructuredList, StructuredIndex, |
2789 | expr: Result.get()); |
2790 | } |
2791 | ++Index; |
2792 | if (AggrDeductionCandidateParamTypes) |
2793 | AggrDeductionCandidateParamTypes->push_back(Elt: CurrentObjectType); |
2794 | return !Seq; |
2795 | } |
2796 | |
2797 | // Check the actual initialization for the designated object type. |
2798 | bool prevHadError = hadError; |
2799 | |
2800 | // Temporarily remove the designator expression from the |
2801 | // initializer list that the child calls see, so that we don't try |
2802 | // to re-process the designator. |
2803 | unsigned OldIndex = Index; |
2804 | auto *OldDIE = |
2805 | dyn_cast_if_present<DesignatedInitExpr>(Val: IList->getInit(Init: OldIndex)); |
2806 | if (!OldDIE) |
2807 | OldDIE = DIE; |
2808 | IList->setInit(Init: OldIndex, expr: OldDIE->getInit()); |
2809 | |
2810 | CheckSubElementType(Entity, IList, ElemType: CurrentObjectType, Index, StructuredList, |
2811 | StructuredIndex, /*DirectlyDesignated=*/true); |
2812 | |
2813 | // Restore the designated initializer expression in the syntactic |
2814 | // form of the initializer list. |
2815 | if (IList->getInit(Init: OldIndex) != OldDIE->getInit()) |
2816 | OldDIE->setInit(IList->getInit(Init: OldIndex)); |
2817 | IList->setInit(Init: OldIndex, expr: OldDIE); |
2818 | |
2819 | return hadError && !prevHadError; |
2820 | } |
2821 | |
2822 | DesignatedInitExpr::Designator *D = DIE->getDesignator(Idx: DesigIdx); |
2823 | bool IsFirstDesignator = (DesigIdx == 0); |
2824 | if (IsFirstDesignator ? FullyStructuredList : StructuredList) { |
2825 | // Determine the structural initializer list that corresponds to the |
2826 | // current subobject. |
2827 | if (IsFirstDesignator) |
2828 | StructuredList = FullyStructuredList; |
2829 | else { |
2830 | Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ? |
2831 | StructuredList->getInit(Init: StructuredIndex) : nullptr; |
2832 | if (!ExistingInit && StructuredList->hasArrayFiller()) |
2833 | ExistingInit = StructuredList->getArrayFiller(); |
2834 | |
2835 | if (!ExistingInit) |
2836 | StructuredList = getStructuredSubobjectInit( |
2837 | IList, Index, CurrentObjectType, StructuredList, StructuredIndex, |
2838 | InitRange: SourceRange(D->getBeginLoc(), DIE->getEndLoc())); |
2839 | else if (InitListExpr *Result = dyn_cast<InitListExpr>(Val: ExistingInit)) |
2840 | StructuredList = Result; |
2841 | else { |
2842 | // We are creating an initializer list that initializes the |
2843 | // subobjects of the current object, but there was already an |
2844 | // initialization that completely initialized the current |
2845 | // subobject, e.g., by a compound literal: |
2846 | // |
2847 | // struct X { int a, b; }; |
2848 | // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 }; |
2849 | // |
2850 | // Here, xs[0].a == 1 and xs[0].b == 3, since the second, |
2851 | // designated initializer re-initializes only its current object |
2852 | // subobject [0].b. |
2853 | diagnoseInitOverride(OldInit: ExistingInit, |
2854 | NewInitRange: SourceRange(D->getBeginLoc(), DIE->getEndLoc()), |
2855 | /*UnionOverride=*/false, |
2856 | /*FullyOverwritten=*/false); |
2857 | |
2858 | if (!VerifyOnly) { |
2859 | if (DesignatedInitUpdateExpr *E = |
2860 | dyn_cast<DesignatedInitUpdateExpr>(Val: ExistingInit)) |
2861 | StructuredList = E->getUpdater(); |
2862 | else { |
2863 | DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context) |
2864 | DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(), |
2865 | ExistingInit, DIE->getEndLoc()); |
2866 | StructuredList->updateInit(C: SemaRef.Context, Init: StructuredIndex, expr: DIUE); |
2867 | StructuredList = DIUE->getUpdater(); |
2868 | } |
2869 | } else { |
2870 | // We don't need to track the structured representation of a |
2871 | // designated init update of an already-fully-initialized object in |
2872 | // verify-only mode. The only reason we would need the structure is |
2873 | // to determine where the uninitialized "holes" are, and in this |
2874 | // case, we know there aren't any and we can't introduce any. |
2875 | StructuredList = nullptr; |
2876 | } |
2877 | } |
2878 | } |
2879 | } |
2880 | |
2881 | if (D->isFieldDesignator()) { |
2882 | // C99 6.7.8p7: |
2883 | // |
2884 | // If a designator has the form |
2885 | // |
2886 | // . identifier |
2887 | // |
2888 | // then the current object (defined below) shall have |
2889 | // structure or union type and the identifier shall be the |
2890 | // name of a member of that type. |
2891 | RecordDecl *RD = getRecordDecl(DeclType: CurrentObjectType); |
2892 | if (!RD) { |
2893 | SourceLocation Loc = D->getDotLoc(); |
2894 | if (Loc.isInvalid()) |
2895 | Loc = D->getFieldLoc(); |
2896 | if (!VerifyOnly) |
2897 | SemaRef.Diag(Loc, DiagID: diag::err_field_designator_non_aggr) |
2898 | << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType; |
2899 | ++Index; |
2900 | return true; |
2901 | } |
2902 | |
2903 | FieldDecl *KnownField = D->getFieldDecl(); |
2904 | if (!KnownField) { |
2905 | const IdentifierInfo *FieldName = D->getFieldName(); |
2906 | ValueDecl *VD = SemaRef.tryLookupUnambiguousFieldDecl(ClassDecl: RD, MemberOrBase: FieldName); |
2907 | if (auto *FD = dyn_cast_if_present<FieldDecl>(Val: VD)) { |
2908 | KnownField = FD; |
2909 | } else if (auto *IFD = dyn_cast_if_present<IndirectFieldDecl>(Val: VD)) { |
2910 | // In verify mode, don't modify the original. |
2911 | if (VerifyOnly) |
2912 | DIE = CloneDesignatedInitExpr(SemaRef, DIE); |
2913 | ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IndirectField: IFD); |
2914 | D = DIE->getDesignator(Idx: DesigIdx); |
2915 | KnownField = cast<FieldDecl>(Val: *IFD->chain_begin()); |
2916 | } |
2917 | if (!KnownField) { |
2918 | if (VerifyOnly) { |
2919 | ++Index; |
2920 | return true; // No typo correction when just trying this out. |
2921 | } |
2922 | |
2923 | // We found a placeholder variable |
2924 | if (SemaRef.DiagRedefinedPlaceholderFieldDecl(Loc: DIE->getBeginLoc(), ClassDecl: RD, |
2925 | Name: FieldName)) { |
2926 | ++Index; |
2927 | return true; |
2928 | } |
2929 | // Name lookup found something, but it wasn't a field. |
2930 | if (DeclContextLookupResult Lookup = RD->lookup(Name: FieldName); |
2931 | !Lookup.empty()) { |
2932 | SemaRef.Diag(Loc: D->getFieldLoc(), DiagID: diag::err_field_designator_nonfield) |
2933 | << FieldName; |
2934 | SemaRef.Diag(Loc: Lookup.front()->getLocation(), |
2935 | DiagID: diag::note_field_designator_found); |
2936 | ++Index; |
2937 | return true; |
2938 | } |
2939 | |
2940 | // Name lookup didn't find anything. |
2941 | // Determine whether this was a typo for another field name. |
2942 | FieldInitializerValidatorCCC CCC(RD); |
2943 | if (TypoCorrection Corrected = SemaRef.CorrectTypo( |
2944 | Typo: DeclarationNameInfo(FieldName, D->getFieldLoc()), |
2945 | LookupKind: Sema::LookupMemberName, /*Scope=*/S: nullptr, /*SS=*/nullptr, CCC, |
2946 | Mode: CorrectTypoKind::ErrorRecovery, MemberContext: RD)) { |
2947 | SemaRef.diagnoseTypo( |
2948 | Correction: Corrected, |
2949 | TypoDiag: SemaRef.PDiag(DiagID: diag::err_field_designator_unknown_suggest) |
2950 | << FieldName << CurrentObjectType); |
2951 | KnownField = Corrected.getCorrectionDeclAs<FieldDecl>(); |
2952 | hadError = true; |
2953 | } else { |
2954 | // Typo correction didn't find anything. |
2955 | SourceLocation Loc = D->getFieldLoc(); |
2956 | |
2957 | // The loc can be invalid with a "null" designator (i.e. an anonymous |
2958 | // union/struct). Do our best to approximate the location. |
2959 | if (Loc.isInvalid()) |
2960 | Loc = IList->getBeginLoc(); |
2961 | |
2962 | SemaRef.Diag(Loc, DiagID: diag::err_field_designator_unknown) |
2963 | << FieldName << CurrentObjectType << DIE->getSourceRange(); |
2964 | ++Index; |
2965 | return true; |
2966 | } |
2967 | } |
2968 | } |
2969 | |
2970 | unsigned NumBases = 0; |
2971 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) |
2972 | NumBases = CXXRD->getNumBases(); |
2973 | |
2974 | unsigned FieldIndex = NumBases; |
2975 | |
2976 | for (auto *FI : RD->fields()) { |
2977 | if (FI->isUnnamedBitField()) |
2978 | continue; |
2979 | if (declaresSameEntity(D1: KnownField, D2: FI)) { |
2980 | KnownField = FI; |
2981 | break; |
2982 | } |
2983 | ++FieldIndex; |
2984 | } |
2985 | |
2986 | RecordDecl::field_iterator Field = |
2987 | RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField)); |
2988 | |
2989 | // All of the fields of a union are located at the same place in |
2990 | // the initializer list. |
2991 | if (RD->isUnion()) { |
2992 | FieldIndex = 0; |
2993 | if (StructuredList) { |
2994 | FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion(); |
2995 | if (CurrentField && !declaresSameEntity(D1: CurrentField, D2: *Field)) { |
2996 | assert(StructuredList->getNumInits() == 1 |
2997 | && "A union should never have more than one initializer!" ); |
2998 | |
2999 | Expr *ExistingInit = StructuredList->getInit(Init: 0); |
3000 | if (ExistingInit) { |
3001 | // We're about to throw away an initializer, emit warning. |
3002 | diagnoseInitOverride( |
3003 | OldInit: ExistingInit, NewInitRange: SourceRange(D->getBeginLoc(), DIE->getEndLoc()), |
3004 | /*UnionOverride=*/true, |
3005 | /*FullyOverwritten=*/SemaRef.getLangOpts().CPlusPlus ? false |
3006 | : true); |
3007 | } |
3008 | |
3009 | // remove existing initializer |
3010 | StructuredList->resizeInits(Context: SemaRef.Context, NumInits: 0); |
3011 | StructuredList->setInitializedFieldInUnion(nullptr); |
3012 | } |
3013 | |
3014 | StructuredList->setInitializedFieldInUnion(*Field); |
3015 | } |
3016 | } |
3017 | |
3018 | // Make sure we can use this declaration. |
3019 | bool InvalidUse; |
3020 | if (VerifyOnly) |
3021 | InvalidUse = !SemaRef.CanUseDecl(D: *Field, TreatUnavailableAsInvalid); |
3022 | else |
3023 | InvalidUse = SemaRef.DiagnoseUseOfDecl(D: *Field, Locs: D->getFieldLoc()); |
3024 | if (InvalidUse) { |
3025 | ++Index; |
3026 | return true; |
3027 | } |
3028 | |
3029 | // C++20 [dcl.init.list]p3: |
3030 | // The ordered identifiers in the designators of the designated- |
3031 | // initializer-list shall form a subsequence of the ordered identifiers |
3032 | // in the direct non-static data members of T. |
3033 | // |
3034 | // Note that this is not a condition on forming the aggregate |
3035 | // initialization, only on actually performing initialization, |
3036 | // so it is not checked in VerifyOnly mode. |
3037 | // |
3038 | // FIXME: This is the only reordering diagnostic we produce, and it only |
3039 | // catches cases where we have a top-level field designator that jumps |
3040 | // backwards. This is the only such case that is reachable in an |
3041 | // otherwise-valid C++20 program, so is the only case that's required for |
3042 | // conformance, but for consistency, we should diagnose all the other |
3043 | // cases where a designator takes us backwards too. |
3044 | if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus && |
3045 | NextField && |
3046 | (*NextField == RD->field_end() || |
3047 | (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) { |
3048 | // Find the field that we just initialized. |
3049 | FieldDecl *PrevField = nullptr; |
3050 | for (auto FI = RD->field_begin(); FI != RD->field_end(); ++FI) { |
3051 | if (FI->isUnnamedBitField()) |
3052 | continue; |
3053 | if (*NextField != RD->field_end() && |
3054 | declaresSameEntity(D1: *FI, D2: **NextField)) |
3055 | break; |
3056 | PrevField = *FI; |
3057 | } |
3058 | |
3059 | if (PrevField && |
3060 | PrevField->getFieldIndex() > KnownField->getFieldIndex()) { |
3061 | SemaRef.Diag(Loc: DIE->getInit()->getBeginLoc(), |
3062 | DiagID: diag::ext_designated_init_reordered) |
3063 | << KnownField << PrevField << DIE->getSourceRange(); |
3064 | |
3065 | unsigned OldIndex = StructuredIndex - 1; |
3066 | if (StructuredList && OldIndex <= StructuredList->getNumInits()) { |
3067 | if (Expr *PrevInit = StructuredList->getInit(Init: OldIndex)) { |
3068 | SemaRef.Diag(Loc: PrevInit->getBeginLoc(), |
3069 | DiagID: diag::note_previous_field_init) |
3070 | << PrevField << PrevInit->getSourceRange(); |
3071 | } |
3072 | } |
3073 | } |
3074 | } |
3075 | |
3076 | |
3077 | // Update the designator with the field declaration. |
3078 | if (!VerifyOnly) |
3079 | D->setFieldDecl(*Field); |
3080 | |
3081 | // Make sure that our non-designated initializer list has space |
3082 | // for a subobject corresponding to this field. |
3083 | if (StructuredList && FieldIndex >= StructuredList->getNumInits()) |
3084 | StructuredList->resizeInits(Context: SemaRef.Context, NumInits: FieldIndex + 1); |
3085 | |
3086 | // This designator names a flexible array member. |
3087 | if (Field->getType()->isIncompleteArrayType()) { |
3088 | bool Invalid = false; |
3089 | if ((DesigIdx + 1) != DIE->size()) { |
3090 | // We can't designate an object within the flexible array |
3091 | // member (because GCC doesn't allow it). |
3092 | if (!VerifyOnly) { |
3093 | DesignatedInitExpr::Designator *NextD |
3094 | = DIE->getDesignator(Idx: DesigIdx + 1); |
3095 | SemaRef.Diag(Loc: NextD->getBeginLoc(), |
3096 | DiagID: diag::err_designator_into_flexible_array_member) |
3097 | << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc()); |
3098 | SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_flexible_array_member) |
3099 | << *Field; |
3100 | } |
3101 | Invalid = true; |
3102 | } |
3103 | |
3104 | if (!hadError && !isa<InitListExpr>(Val: DIE->getInit()) && |
3105 | !isa<StringLiteral>(Val: DIE->getInit())) { |
3106 | // The initializer is not an initializer list. |
3107 | if (!VerifyOnly) { |
3108 | SemaRef.Diag(Loc: DIE->getInit()->getBeginLoc(), |
3109 | DiagID: diag::err_flexible_array_init_needs_braces) |
3110 | << DIE->getInit()->getSourceRange(); |
3111 | SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_flexible_array_member) |
3112 | << *Field; |
3113 | } |
3114 | Invalid = true; |
3115 | } |
3116 | |
3117 | // Check GNU flexible array initializer. |
3118 | if (!Invalid && CheckFlexibleArrayInit(Entity, InitExpr: DIE->getInit(), Field: *Field, |
3119 | TopLevelObject)) |
3120 | Invalid = true; |
3121 | |
3122 | if (Invalid) { |
3123 | ++Index; |
3124 | return true; |
3125 | } |
3126 | |
3127 | // Initialize the array. |
3128 | bool prevHadError = hadError; |
3129 | unsigned newStructuredIndex = FieldIndex; |
3130 | unsigned OldIndex = Index; |
3131 | IList->setInit(Init: Index, expr: DIE->getInit()); |
3132 | |
3133 | InitializedEntity MemberEntity = |
3134 | InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity); |
3135 | CheckSubElementType(Entity: MemberEntity, IList, ElemType: Field->getType(), Index, |
3136 | StructuredList, StructuredIndex&: newStructuredIndex); |
3137 | |
3138 | IList->setInit(Init: OldIndex, expr: DIE); |
3139 | if (hadError && !prevHadError) { |
3140 | ++Field; |
3141 | ++FieldIndex; |
3142 | if (NextField) |
3143 | *NextField = Field; |
3144 | StructuredIndex = FieldIndex; |
3145 | return true; |
3146 | } |
3147 | } else { |
3148 | // Recurse to check later designated subobjects. |
3149 | QualType FieldType = Field->getType(); |
3150 | unsigned newStructuredIndex = FieldIndex; |
3151 | |
3152 | InitializedEntity MemberEntity = |
3153 | InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity); |
3154 | if (CheckDesignatedInitializer(Entity: MemberEntity, IList, DIE, DesigIdx: DesigIdx + 1, |
3155 | CurrentObjectType&: FieldType, NextField: nullptr, NextElementIndex: nullptr, Index, |
3156 | StructuredList, StructuredIndex&: newStructuredIndex, |
3157 | FinishSubobjectInit, TopLevelObject: false)) |
3158 | return true; |
3159 | } |
3160 | |
3161 | // Find the position of the next field to be initialized in this |
3162 | // subobject. |
3163 | ++Field; |
3164 | ++FieldIndex; |
3165 | |
3166 | // If this the first designator, our caller will continue checking |
3167 | // the rest of this struct/class/union subobject. |
3168 | if (IsFirstDesignator) { |
3169 | if (Field != RD->field_end() && Field->isUnnamedBitField()) |
3170 | ++Field; |
3171 | |
3172 | if (NextField) |
3173 | *NextField = Field; |
3174 | |
3175 | StructuredIndex = FieldIndex; |
3176 | return false; |
3177 | } |
3178 | |
3179 | if (!FinishSubobjectInit) |
3180 | return false; |
3181 | |
3182 | // We've already initialized something in the union; we're done. |
3183 | if (RD->isUnion()) |
3184 | return hadError; |
3185 | |
3186 | // Check the remaining fields within this class/struct/union subobject. |
3187 | bool prevHadError = hadError; |
3188 | |
3189 | auto NoBases = |
3190 | CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(), |
3191 | CXXRecordDecl::base_class_iterator()); |
3192 | CheckStructUnionTypes(Entity, IList, DeclType: CurrentObjectType, Bases: NoBases, Field, |
3193 | SubobjectIsDesignatorContext: false, Index, StructuredList, StructuredIndex&: FieldIndex); |
3194 | return hadError && !prevHadError; |
3195 | } |
3196 | |
3197 | // C99 6.7.8p6: |
3198 | // |
3199 | // If a designator has the form |
3200 | // |
3201 | // [ constant-expression ] |
3202 | // |
3203 | // then the current object (defined below) shall have array |
3204 | // type and the expression shall be an integer constant |
3205 | // expression. If the array is of unknown size, any |
3206 | // nonnegative value is valid. |
3207 | // |
3208 | // Additionally, cope with the GNU extension that permits |
3209 | // designators of the form |
3210 | // |
3211 | // [ constant-expression ... constant-expression ] |
3212 | const ArrayType *AT = SemaRef.Context.getAsArrayType(T: CurrentObjectType); |
3213 | if (!AT) { |
3214 | if (!VerifyOnly) |
3215 | SemaRef.Diag(Loc: D->getLBracketLoc(), DiagID: diag::err_array_designator_non_array) |
3216 | << CurrentObjectType; |
3217 | ++Index; |
3218 | return true; |
3219 | } |
3220 | |
3221 | Expr *IndexExpr = nullptr; |
3222 | llvm::APSInt DesignatedStartIndex, DesignatedEndIndex; |
3223 | if (D->isArrayDesignator()) { |
3224 | IndexExpr = DIE->getArrayIndex(D: *D); |
3225 | DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(Ctx: SemaRef.Context); |
3226 | DesignatedEndIndex = DesignatedStartIndex; |
3227 | } else { |
3228 | assert(D->isArrayRangeDesignator() && "Need array-range designator" ); |
3229 | |
3230 | DesignatedStartIndex = |
3231 | DIE->getArrayRangeStart(D: *D)->EvaluateKnownConstInt(Ctx: SemaRef.Context); |
3232 | DesignatedEndIndex = |
3233 | DIE->getArrayRangeEnd(D: *D)->EvaluateKnownConstInt(Ctx: SemaRef.Context); |
3234 | IndexExpr = DIE->getArrayRangeEnd(D: *D); |
3235 | |
3236 | // Codegen can't handle evaluating array range designators that have side |
3237 | // effects, because we replicate the AST value for each initialized element. |
3238 | // As such, set the sawArrayRangeDesignator() bit if we initialize multiple |
3239 | // elements with something that has a side effect, so codegen can emit an |
3240 | // "error unsupported" error instead of miscompiling the app. |
3241 | if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&& |
3242 | DIE->getInit()->HasSideEffects(Ctx: SemaRef.Context) && !VerifyOnly) |
3243 | FullyStructuredList->sawArrayRangeDesignator(); |
3244 | } |
3245 | |
3246 | if (isa<ConstantArrayType>(Val: AT)) { |
3247 | llvm::APSInt MaxElements(cast<ConstantArrayType>(Val: AT)->getSize(), false); |
3248 | DesignatedStartIndex |
3249 | = DesignatedStartIndex.extOrTrunc(width: MaxElements.getBitWidth()); |
3250 | DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned()); |
3251 | DesignatedEndIndex |
3252 | = DesignatedEndIndex.extOrTrunc(width: MaxElements.getBitWidth()); |
3253 | DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned()); |
3254 | if (DesignatedEndIndex >= MaxElements) { |
3255 | if (!VerifyOnly) |
3256 | SemaRef.Diag(Loc: IndexExpr->getBeginLoc(), |
3257 | DiagID: diag::err_array_designator_too_large) |
3258 | << toString(I: DesignatedEndIndex, Radix: 10) << toString(I: MaxElements, Radix: 10) |
3259 | << IndexExpr->getSourceRange(); |
3260 | ++Index; |
3261 | return true; |
3262 | } |
3263 | } else { |
3264 | unsigned DesignatedIndexBitWidth = |
3265 | ConstantArrayType::getMaxSizeBits(Context: SemaRef.Context); |
3266 | DesignatedStartIndex = |
3267 | DesignatedStartIndex.extOrTrunc(width: DesignatedIndexBitWidth); |
3268 | DesignatedEndIndex = |
3269 | DesignatedEndIndex.extOrTrunc(width: DesignatedIndexBitWidth); |
3270 | DesignatedStartIndex.setIsUnsigned(true); |
3271 | DesignatedEndIndex.setIsUnsigned(true); |
3272 | } |
3273 | |
3274 | bool IsStringLiteralInitUpdate = |
3275 | StructuredList && StructuredList->isStringLiteralInit(); |
3276 | if (IsStringLiteralInitUpdate && VerifyOnly) { |
3277 | // We're just verifying an update to a string literal init. We don't need |
3278 | // to split the string up into individual characters to do that. |
3279 | StructuredList = nullptr; |
3280 | } else if (IsStringLiteralInitUpdate) { |
3281 | // We're modifying a string literal init; we have to decompose the string |
3282 | // so we can modify the individual characters. |
3283 | ASTContext &Context = SemaRef.Context; |
3284 | Expr *SubExpr = StructuredList->getInit(Init: 0)->IgnoreParenImpCasts(); |
3285 | |
3286 | // Compute the character type |
3287 | QualType CharTy = AT->getElementType(); |
3288 | |
3289 | // Compute the type of the integer literals. |
3290 | QualType PromotedCharTy = CharTy; |
3291 | if (Context.isPromotableIntegerType(T: CharTy)) |
3292 | PromotedCharTy = Context.getPromotedIntegerType(PromotableType: CharTy); |
3293 | unsigned PromotedCharTyWidth = Context.getTypeSize(T: PromotedCharTy); |
3294 | |
3295 | if (StringLiteral *SL = dyn_cast<StringLiteral>(Val: SubExpr)) { |
3296 | // Get the length of the string. |
3297 | uint64_t StrLen = SL->getLength(); |
3298 | if (cast<ConstantArrayType>(Val: AT)->getSize().ult(RHS: StrLen)) |
3299 | StrLen = cast<ConstantArrayType>(Val: AT)->getZExtSize(); |
3300 | StructuredList->resizeInits(Context, NumInits: StrLen); |
3301 | |
3302 | // Build a literal for each character in the string, and put them into |
3303 | // the init list. |
3304 | for (unsigned i = 0, e = StrLen; i != e; ++i) { |
3305 | llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i)); |
3306 | Expr *Init = new (Context) IntegerLiteral( |
3307 | Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc()); |
3308 | if (CharTy != PromotedCharTy) |
3309 | Init = ImplicitCastExpr::Create(Context, T: CharTy, Kind: CK_IntegralCast, |
3310 | Operand: Init, BasePath: nullptr, Cat: VK_PRValue, |
3311 | FPO: FPOptionsOverride()); |
3312 | StructuredList->updateInit(C: Context, Init: i, expr: Init); |
3313 | } |
3314 | } else { |
3315 | ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(Val: SubExpr); |
3316 | std::string Str; |
3317 | Context.getObjCEncodingForType(T: E->getEncodedType(), S&: Str); |
3318 | |
3319 | // Get the length of the string. |
3320 | uint64_t StrLen = Str.size(); |
3321 | if (cast<ConstantArrayType>(Val: AT)->getSize().ult(RHS: StrLen)) |
3322 | StrLen = cast<ConstantArrayType>(Val: AT)->getZExtSize(); |
3323 | StructuredList->resizeInits(Context, NumInits: StrLen); |
3324 | |
3325 | // Build a literal for each character in the string, and put them into |
3326 | // the init list. |
3327 | for (unsigned i = 0, e = StrLen; i != e; ++i) { |
3328 | llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]); |
3329 | Expr *Init = new (Context) IntegerLiteral( |
3330 | Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc()); |
3331 | if (CharTy != PromotedCharTy) |
3332 | Init = ImplicitCastExpr::Create(Context, T: CharTy, Kind: CK_IntegralCast, |
3333 | Operand: Init, BasePath: nullptr, Cat: VK_PRValue, |
3334 | FPO: FPOptionsOverride()); |
3335 | StructuredList->updateInit(C: Context, Init: i, expr: Init); |
3336 | } |
3337 | } |
3338 | } |
3339 | |
3340 | // Make sure that our non-designated initializer list has space |
3341 | // for a subobject corresponding to this array element. |
3342 | if (StructuredList && |
3343 | DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits()) |
3344 | StructuredList->resizeInits(Context: SemaRef.Context, |
3345 | NumInits: DesignatedEndIndex.getZExtValue() + 1); |
3346 | |
3347 | // Repeatedly perform subobject initializations in the range |
3348 | // [DesignatedStartIndex, DesignatedEndIndex]. |
3349 | |
3350 | // Move to the next designator |
3351 | unsigned ElementIndex = DesignatedStartIndex.getZExtValue(); |
3352 | unsigned OldIndex = Index; |
3353 | |
3354 | InitializedEntity ElementEntity = |
3355 | InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity); |
3356 | |
3357 | while (DesignatedStartIndex <= DesignatedEndIndex) { |
3358 | // Recurse to check later designated subobjects. |
3359 | QualType ElementType = AT->getElementType(); |
3360 | Index = OldIndex; |
3361 | |
3362 | ElementEntity.setElementIndex(ElementIndex); |
3363 | if (CheckDesignatedInitializer( |
3364 | Entity: ElementEntity, IList, DIE, DesigIdx: DesigIdx + 1, CurrentObjectType&: ElementType, NextField: nullptr, |
3365 | NextElementIndex: nullptr, Index, StructuredList, StructuredIndex&: ElementIndex, |
3366 | FinishSubobjectInit: FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex), |
3367 | TopLevelObject: false)) |
3368 | return true; |
3369 | |
3370 | // Move to the next index in the array that we'll be initializing. |
3371 | ++DesignatedStartIndex; |
3372 | ElementIndex = DesignatedStartIndex.getZExtValue(); |
3373 | } |
3374 | |
3375 | // If this the first designator, our caller will continue checking |
3376 | // the rest of this array subobject. |
3377 | if (IsFirstDesignator) { |
3378 | if (NextElementIndex) |
3379 | *NextElementIndex = DesignatedStartIndex; |
3380 | StructuredIndex = ElementIndex; |
3381 | return false; |
3382 | } |
3383 | |
3384 | if (!FinishSubobjectInit) |
3385 | return false; |
3386 | |
3387 | // Check the remaining elements within this array subobject. |
3388 | bool prevHadError = hadError; |
3389 | CheckArrayType(Entity, IList, DeclType&: CurrentObjectType, elementIndex: DesignatedStartIndex, |
3390 | /*SubobjectIsDesignatorContext=*/false, Index, |
3391 | StructuredList, StructuredIndex&: ElementIndex); |
3392 | return hadError && !prevHadError; |
3393 | } |
3394 | |
3395 | // Get the structured initializer list for a subobject of type |
3396 | // @p CurrentObjectType. |
3397 | InitListExpr * |
3398 | InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, |
3399 | QualType CurrentObjectType, |
3400 | InitListExpr *StructuredList, |
3401 | unsigned StructuredIndex, |
3402 | SourceRange InitRange, |
3403 | bool IsFullyOverwritten) { |
3404 | if (!StructuredList) |
3405 | return nullptr; |
3406 | |
3407 | Expr *ExistingInit = nullptr; |
3408 | if (StructuredIndex < StructuredList->getNumInits()) |
3409 | ExistingInit = StructuredList->getInit(Init: StructuredIndex); |
3410 | |
3411 | if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(Val: ExistingInit)) |
3412 | // There might have already been initializers for subobjects of the current |
3413 | // object, but a subsequent initializer list will overwrite the entirety |
3414 | // of the current object. (See DR 253 and C99 6.7.8p21). e.g., |
3415 | // |
3416 | // struct P { char x[6]; }; |
3417 | // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } }; |
3418 | // |
3419 | // The first designated initializer is ignored, and l.x is just "f". |
3420 | if (!IsFullyOverwritten) |
3421 | return Result; |
3422 | |
3423 | if (ExistingInit) { |
3424 | // We are creating an initializer list that initializes the |
3425 | // subobjects of the current object, but there was already an |
3426 | // initialization that completely initialized the current |
3427 | // subobject: |
3428 | // |
3429 | // struct X { int a, b; }; |
3430 | // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 }; |
3431 | // |
3432 | // Here, xs[0].a == 1 and xs[0].b == 3, since the second, |
3433 | // designated initializer overwrites the [0].b initializer |
3434 | // from the prior initialization. |
3435 | // |
3436 | // When the existing initializer is an expression rather than an |
3437 | // initializer list, we cannot decompose and update it in this way. |
3438 | // For example: |
3439 | // |
3440 | // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 }; |
3441 | // |
3442 | // This case is handled by CheckDesignatedInitializer. |
3443 | diagnoseInitOverride(OldInit: ExistingInit, NewInitRange: InitRange); |
3444 | } |
3445 | |
3446 | unsigned ExpectedNumInits = 0; |
3447 | if (Index < IList->getNumInits()) { |
3448 | if (auto *Init = dyn_cast_or_null<InitListExpr>(Val: IList->getInit(Init: Index))) |
3449 | ExpectedNumInits = Init->getNumInits(); |
3450 | else |
3451 | ExpectedNumInits = IList->getNumInits() - Index; |
3452 | } |
3453 | |
3454 | InitListExpr *Result = |
3455 | createInitListExpr(CurrentObjectType, InitRange, ExpectedNumInits); |
3456 | |
3457 | // Link this new initializer list into the structured initializer |
3458 | // lists. |
3459 | StructuredList->updateInit(C: SemaRef.Context, Init: StructuredIndex, expr: Result); |
3460 | return Result; |
3461 | } |
3462 | |
3463 | InitListExpr * |
3464 | InitListChecker::createInitListExpr(QualType CurrentObjectType, |
3465 | SourceRange InitRange, |
3466 | unsigned ExpectedNumInits) { |
3467 | InitListExpr *Result = new (SemaRef.Context) InitListExpr( |
3468 | SemaRef.Context, InitRange.getBegin(), {}, InitRange.getEnd()); |
3469 | |
3470 | QualType ResultType = CurrentObjectType; |
3471 | if (!ResultType->isArrayType()) |
3472 | ResultType = ResultType.getNonLValueExprType(Context: SemaRef.Context); |
3473 | Result->setType(ResultType); |
3474 | |
3475 | // Pre-allocate storage for the structured initializer list. |
3476 | unsigned NumElements = 0; |
3477 | |
3478 | if (const ArrayType *AType |
3479 | = SemaRef.Context.getAsArrayType(T: CurrentObjectType)) { |
3480 | if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(Val: AType)) { |
3481 | NumElements = CAType->getZExtSize(); |
3482 | // Simple heuristic so that we don't allocate a very large |
3483 | // initializer with many empty entries at the end. |
3484 | if (NumElements > ExpectedNumInits) |
3485 | NumElements = 0; |
3486 | } |
3487 | } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) { |
3488 | NumElements = VType->getNumElements(); |
3489 | } else if (CurrentObjectType->isRecordType()) { |
3490 | NumElements = numStructUnionElements(DeclType: CurrentObjectType); |
3491 | } else if (CurrentObjectType->isDependentType()) { |
3492 | NumElements = 1; |
3493 | } |
3494 | |
3495 | Result->reserveInits(C: SemaRef.Context, NumInits: NumElements); |
3496 | |
3497 | return Result; |
3498 | } |
3499 | |
3500 | /// Update the initializer at index @p StructuredIndex within the |
3501 | /// structured initializer list to the value @p expr. |
3502 | void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList, |
3503 | unsigned &StructuredIndex, |
3504 | Expr *expr) { |
3505 | // No structured initializer list to update |
3506 | if (!StructuredList) |
3507 | return; |
3508 | |
3509 | if (Expr *PrevInit = StructuredList->updateInit(C: SemaRef.Context, |
3510 | Init: StructuredIndex, expr)) { |
3511 | // This initializer overwrites a previous initializer. |
3512 | // No need to diagnose when `expr` is nullptr because a more relevant |
3513 | // diagnostic has already been issued and this diagnostic is potentially |
3514 | // noise. |
3515 | if (expr) |
3516 | diagnoseInitOverride(OldInit: PrevInit, NewInitRange: expr->getSourceRange()); |
3517 | } |
3518 | |
3519 | ++StructuredIndex; |
3520 | } |
3521 | |
3522 | bool Sema::CanPerformAggregateInitializationForOverloadResolution( |
3523 | const InitializedEntity &Entity, InitListExpr *From) { |
3524 | QualType Type = Entity.getType(); |
3525 | InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true, |
3526 | /*TreatUnavailableAsInvalid=*/false, |
3527 | /*InOverloadResolution=*/true); |
3528 | return !Check.HadError(); |
3529 | } |
3530 | |
3531 | /// Check that the given Index expression is a valid array designator |
3532 | /// value. This is essentially just a wrapper around |
3533 | /// VerifyIntegerConstantExpression that also checks for negative values |
3534 | /// and produces a reasonable diagnostic if there is a |
3535 | /// failure. Returns the index expression, possibly with an implicit cast |
3536 | /// added, on success. If everything went okay, Value will receive the |
3537 | /// value of the constant expression. |
3538 | static ExprResult |
3539 | CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) { |
3540 | SourceLocation Loc = Index->getBeginLoc(); |
3541 | |
3542 | // Make sure this is an integer constant expression. |
3543 | ExprResult Result = |
3544 | S.VerifyIntegerConstantExpression(E: Index, Result: &Value, CanFold: AllowFoldKind::Allow); |
3545 | if (Result.isInvalid()) |
3546 | return Result; |
3547 | |
3548 | if (Value.isSigned() && Value.isNegative()) |
3549 | return S.Diag(Loc, DiagID: diag::err_array_designator_negative) |
3550 | << toString(I: Value, Radix: 10) << Index->getSourceRange(); |
3551 | |
3552 | Value.setIsUnsigned(true); |
3553 | return Result; |
3554 | } |
3555 | |
3556 | ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig, |
3557 | SourceLocation EqualOrColonLoc, |
3558 | bool GNUSyntax, |
3559 | ExprResult Init) { |
3560 | typedef DesignatedInitExpr::Designator ASTDesignator; |
3561 | |
3562 | bool Invalid = false; |
3563 | SmallVector<ASTDesignator, 32> Designators; |
3564 | SmallVector<Expr *, 32> InitExpressions; |
3565 | |
3566 | // Build designators and check array designator expressions. |
3567 | for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) { |
3568 | const Designator &D = Desig.getDesignator(Idx); |
3569 | |
3570 | if (D.isFieldDesignator()) { |
3571 | Designators.push_back(Elt: ASTDesignator::CreateFieldDesignator( |
3572 | FieldName: D.getFieldDecl(), DotLoc: D.getDotLoc(), FieldLoc: D.getFieldLoc())); |
3573 | } else if (D.isArrayDesignator()) { |
3574 | Expr *Index = static_cast<Expr *>(D.getArrayIndex()); |
3575 | llvm::APSInt IndexValue; |
3576 | if (!Index->isTypeDependent() && !Index->isValueDependent()) |
3577 | Index = CheckArrayDesignatorExpr(S&: *this, Index, Value&: IndexValue).get(); |
3578 | if (!Index) |
3579 | Invalid = true; |
3580 | else { |
3581 | Designators.push_back(Elt: ASTDesignator::CreateArrayDesignator( |
3582 | Index: InitExpressions.size(), LBracketLoc: D.getLBracketLoc(), RBracketLoc: D.getRBracketLoc())); |
3583 | InitExpressions.push_back(Elt: Index); |
3584 | } |
3585 | } else if (D.isArrayRangeDesignator()) { |
3586 | Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart()); |
3587 | Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd()); |
3588 | llvm::APSInt StartValue; |
3589 | llvm::APSInt EndValue; |
3590 | bool StartDependent = StartIndex->isTypeDependent() || |
3591 | StartIndex->isValueDependent(); |
3592 | bool EndDependent = EndIndex->isTypeDependent() || |
3593 | EndIndex->isValueDependent(); |
3594 | if (!StartDependent) |
3595 | StartIndex = |
3596 | CheckArrayDesignatorExpr(S&: *this, Index: StartIndex, Value&: StartValue).get(); |
3597 | if (!EndDependent) |
3598 | EndIndex = CheckArrayDesignatorExpr(S&: *this, Index: EndIndex, Value&: EndValue).get(); |
3599 | |
3600 | if (!StartIndex || !EndIndex) |
3601 | Invalid = true; |
3602 | else { |
3603 | // Make sure we're comparing values with the same bit width. |
3604 | if (StartDependent || EndDependent) { |
3605 | // Nothing to compute. |
3606 | } else if (StartValue.getBitWidth() > EndValue.getBitWidth()) |
3607 | EndValue = EndValue.extend(width: StartValue.getBitWidth()); |
3608 | else if (StartValue.getBitWidth() < EndValue.getBitWidth()) |
3609 | StartValue = StartValue.extend(width: EndValue.getBitWidth()); |
3610 | |
3611 | if (!StartDependent && !EndDependent && EndValue < StartValue) { |
3612 | Diag(Loc: D.getEllipsisLoc(), DiagID: diag::err_array_designator_empty_range) |
3613 | << toString(I: StartValue, Radix: 10) << toString(I: EndValue, Radix: 10) |
3614 | << StartIndex->getSourceRange() << EndIndex->getSourceRange(); |
3615 | Invalid = true; |
3616 | } else { |
3617 | Designators.push_back(Elt: ASTDesignator::CreateArrayRangeDesignator( |
3618 | Index: InitExpressions.size(), LBracketLoc: D.getLBracketLoc(), EllipsisLoc: D.getEllipsisLoc(), |
3619 | RBracketLoc: D.getRBracketLoc())); |
3620 | InitExpressions.push_back(Elt: StartIndex); |
3621 | InitExpressions.push_back(Elt: EndIndex); |
3622 | } |
3623 | } |
3624 | } |
3625 | } |
3626 | |
3627 | if (Invalid || Init.isInvalid()) |
3628 | return ExprError(); |
3629 | |
3630 | return DesignatedInitExpr::Create(C: Context, Designators, IndexExprs: InitExpressions, |
3631 | EqualOrColonLoc, GNUSyntax, |
3632 | Init: Init.getAs<Expr>()); |
3633 | } |
3634 | |
3635 | //===----------------------------------------------------------------------===// |
3636 | // Initialization entity |
3637 | //===----------------------------------------------------------------------===// |
3638 | |
3639 | InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index, |
3640 | const InitializedEntity &Parent) |
3641 | : Parent(&Parent), Index(Index) |
3642 | { |
3643 | if (const ArrayType *AT = Context.getAsArrayType(T: Parent.getType())) { |
3644 | Kind = EK_ArrayElement; |
3645 | Type = AT->getElementType(); |
3646 | } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) { |
3647 | Kind = EK_VectorElement; |
3648 | Type = VT->getElementType(); |
3649 | } else { |
3650 | const ComplexType *CT = Parent.getType()->getAs<ComplexType>(); |
3651 | assert(CT && "Unexpected type" ); |
3652 | Kind = EK_ComplexElement; |
3653 | Type = CT->getElementType(); |
3654 | } |
3655 | } |
3656 | |
3657 | InitializedEntity |
3658 | InitializedEntity::InitializeBase(ASTContext &Context, |
3659 | const CXXBaseSpecifier *Base, |
3660 | bool IsInheritedVirtualBase, |
3661 | const InitializedEntity *Parent) { |
3662 | InitializedEntity Result; |
3663 | Result.Kind = EK_Base; |
3664 | Result.Parent = Parent; |
3665 | Result.Base = {Base, IsInheritedVirtualBase}; |
3666 | Result.Type = Base->getType(); |
3667 | return Result; |
3668 | } |
3669 | |
3670 | DeclarationName InitializedEntity::getName() const { |
3671 | switch (getKind()) { |
3672 | case EK_Parameter: |
3673 | case EK_Parameter_CF_Audited: { |
3674 | ParmVarDecl *D = Parameter.getPointer(); |
3675 | return (D ? D->getDeclName() : DeclarationName()); |
3676 | } |
3677 | |
3678 | case EK_Variable: |
3679 | case EK_Member: |
3680 | case EK_ParenAggInitMember: |
3681 | case EK_Binding: |
3682 | case EK_TemplateParameter: |
3683 | return Variable.VariableOrMember->getDeclName(); |
3684 | |
3685 | case EK_LambdaCapture: |
3686 | return DeclarationName(Capture.VarID); |
3687 | |
3688 | case EK_Result: |
3689 | case EK_StmtExprResult: |
3690 | case EK_Exception: |
3691 | case EK_New: |
3692 | case EK_Temporary: |
3693 | case EK_Base: |
3694 | case EK_Delegating: |
3695 | case EK_ArrayElement: |
3696 | case EK_VectorElement: |
3697 | case EK_ComplexElement: |
3698 | case EK_BlockElement: |
3699 | case EK_LambdaToBlockConversionBlockElement: |
3700 | case EK_CompoundLiteralInit: |
3701 | case EK_RelatedResult: |
3702 | return DeclarationName(); |
3703 | } |
3704 | |
3705 | llvm_unreachable("Invalid EntityKind!" ); |
3706 | } |
3707 | |
3708 | ValueDecl *InitializedEntity::getDecl() const { |
3709 | switch (getKind()) { |
3710 | case EK_Variable: |
3711 | case EK_Member: |
3712 | case EK_ParenAggInitMember: |
3713 | case EK_Binding: |
3714 | case EK_TemplateParameter: |
3715 | return Variable.VariableOrMember; |
3716 | |
3717 | case EK_Parameter: |
3718 | case EK_Parameter_CF_Audited: |
3719 | return Parameter.getPointer(); |
3720 | |
3721 | case EK_Result: |
3722 | case EK_StmtExprResult: |
3723 | case EK_Exception: |
3724 | case EK_New: |
3725 | case EK_Temporary: |
3726 | case EK_Base: |
3727 | case EK_Delegating: |
3728 | case EK_ArrayElement: |
3729 | case EK_VectorElement: |
3730 | case EK_ComplexElement: |
3731 | case EK_BlockElement: |
3732 | case EK_LambdaToBlockConversionBlockElement: |
3733 | case EK_LambdaCapture: |
3734 | case EK_CompoundLiteralInit: |
3735 | case EK_RelatedResult: |
3736 | return nullptr; |
3737 | } |
3738 | |
3739 | llvm_unreachable("Invalid EntityKind!" ); |
3740 | } |
3741 | |
3742 | bool InitializedEntity::allowsNRVO() const { |
3743 | switch (getKind()) { |
3744 | case EK_Result: |
3745 | case EK_Exception: |
3746 | return LocAndNRVO.NRVO; |
3747 | |
3748 | case EK_StmtExprResult: |
3749 | case EK_Variable: |
3750 | case EK_Parameter: |
3751 | case EK_Parameter_CF_Audited: |
3752 | case EK_TemplateParameter: |
3753 | case EK_Member: |
3754 | case EK_ParenAggInitMember: |
3755 | case EK_Binding: |
3756 | case EK_New: |
3757 | case EK_Temporary: |
3758 | case EK_CompoundLiteralInit: |
3759 | case EK_Base: |
3760 | case EK_Delegating: |
3761 | case EK_ArrayElement: |
3762 | case EK_VectorElement: |
3763 | case EK_ComplexElement: |
3764 | case EK_BlockElement: |
3765 | case EK_LambdaToBlockConversionBlockElement: |
3766 | case EK_LambdaCapture: |
3767 | case EK_RelatedResult: |
3768 | break; |
3769 | } |
3770 | |
3771 | return false; |
3772 | } |
3773 | |
3774 | unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const { |
3775 | assert(getParent() != this); |
3776 | unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0; |
3777 | for (unsigned I = 0; I != Depth; ++I) |
3778 | OS << "`-" ; |
3779 | |
3780 | switch (getKind()) { |
3781 | case EK_Variable: OS << "Variable" ; break; |
3782 | case EK_Parameter: OS << "Parameter" ; break; |
3783 | case EK_Parameter_CF_Audited: OS << "CF audited function Parameter" ; |
3784 | break; |
3785 | case EK_TemplateParameter: OS << "TemplateParameter" ; break; |
3786 | case EK_Result: OS << "Result" ; break; |
3787 | case EK_StmtExprResult: OS << "StmtExprResult" ; break; |
3788 | case EK_Exception: OS << "Exception" ; break; |
3789 | case EK_Member: |
3790 | case EK_ParenAggInitMember: |
3791 | OS << "Member" ; |
3792 | break; |
3793 | case EK_Binding: OS << "Binding" ; break; |
3794 | case EK_New: OS << "New" ; break; |
3795 | case EK_Temporary: OS << "Temporary" ; break; |
3796 | case EK_CompoundLiteralInit: OS << "CompoundLiteral" ;break; |
3797 | case EK_RelatedResult: OS << "RelatedResult" ; break; |
3798 | case EK_Base: OS << "Base" ; break; |
3799 | case EK_Delegating: OS << "Delegating" ; break; |
3800 | case EK_ArrayElement: OS << "ArrayElement " << Index; break; |
3801 | case EK_VectorElement: OS << "VectorElement " << Index; break; |
3802 | case EK_ComplexElement: OS << "ComplexElement " << Index; break; |
3803 | case EK_BlockElement: OS << "Block" ; break; |
3804 | case EK_LambdaToBlockConversionBlockElement: |
3805 | OS << "Block (lambda)" ; |
3806 | break; |
3807 | case EK_LambdaCapture: |
3808 | OS << "LambdaCapture " ; |
3809 | OS << DeclarationName(Capture.VarID); |
3810 | break; |
3811 | } |
3812 | |
3813 | if (auto *D = getDecl()) { |
3814 | OS << " " ; |
3815 | D->printQualifiedName(OS); |
3816 | } |
3817 | |
3818 | OS << " '" << getType() << "'\n" ; |
3819 | |
3820 | return Depth + 1; |
3821 | } |
3822 | |
3823 | LLVM_DUMP_METHOD void InitializedEntity::dump() const { |
3824 | dumpImpl(OS&: llvm::errs()); |
3825 | } |
3826 | |
3827 | //===----------------------------------------------------------------------===// |
3828 | // Initialization sequence |
3829 | //===----------------------------------------------------------------------===// |
3830 | |
3831 | void InitializationSequence::Step::Destroy() { |
3832 | switch (Kind) { |
3833 | case SK_ResolveAddressOfOverloadedFunction: |
3834 | case SK_CastDerivedToBasePRValue: |
3835 | case SK_CastDerivedToBaseXValue: |
3836 | case SK_CastDerivedToBaseLValue: |
3837 | case SK_BindReference: |
3838 | case SK_BindReferenceToTemporary: |
3839 | case SK_FinalCopy: |
3840 | case SK_ExtraneousCopyToTemporary: |
3841 | case SK_UserConversion: |
3842 | case SK_QualificationConversionPRValue: |
3843 | case SK_QualificationConversionXValue: |
3844 | case SK_QualificationConversionLValue: |
3845 | case SK_FunctionReferenceConversion: |
3846 | case SK_AtomicConversion: |
3847 | case SK_ListInitialization: |
3848 | case SK_UnwrapInitList: |
3849 | case SK_RewrapInitList: |
3850 | case SK_ConstructorInitialization: |
3851 | case SK_ConstructorInitializationFromList: |
3852 | case SK_ZeroInitialization: |
3853 | case SK_CAssignment: |
3854 | case SK_StringInit: |
3855 | case SK_ObjCObjectConversion: |
3856 | case SK_ArrayLoopIndex: |
3857 | case SK_ArrayLoopInit: |
3858 | case SK_ArrayInit: |
3859 | case SK_GNUArrayInit: |
3860 | case SK_ParenthesizedArrayInit: |
3861 | case SK_PassByIndirectCopyRestore: |
3862 | case SK_PassByIndirectRestore: |
3863 | case SK_ProduceObjCObject: |
3864 | case SK_StdInitializerList: |
3865 | case SK_StdInitializerListConstructorCall: |
3866 | case SK_OCLSamplerInit: |
3867 | case SK_OCLZeroOpaqueType: |
3868 | case SK_ParenthesizedListInit: |
3869 | break; |
3870 | |
3871 | case SK_ConversionSequence: |
3872 | case SK_ConversionSequenceNoNarrowing: |
3873 | delete ICS; |
3874 | } |
3875 | } |
3876 | |
3877 | bool InitializationSequence::isDirectReferenceBinding() const { |
3878 | // There can be some lvalue adjustments after the SK_BindReference step. |
3879 | for (const Step &S : llvm::reverse(C: Steps)) { |
3880 | if (S.Kind == SK_BindReference) |
3881 | return true; |
3882 | if (S.Kind == SK_BindReferenceToTemporary) |
3883 | return false; |
3884 | } |
3885 | return false; |
3886 | } |
3887 | |
3888 | bool InitializationSequence::isAmbiguous() const { |
3889 | if (!Failed()) |
3890 | return false; |
3891 | |
3892 | switch (getFailureKind()) { |
3893 | case FK_TooManyInitsForReference: |
3894 | case FK_ParenthesizedListInitForReference: |
3895 | case FK_ArrayNeedsInitList: |
3896 | case FK_ArrayNeedsInitListOrStringLiteral: |
3897 | case FK_ArrayNeedsInitListOrWideStringLiteral: |
3898 | case FK_NarrowStringIntoWideCharArray: |
3899 | case FK_WideStringIntoCharArray: |
3900 | case FK_IncompatWideStringIntoWideChar: |
3901 | case FK_PlainStringIntoUTF8Char: |
3902 | case FK_UTF8StringIntoPlainChar: |
3903 | case FK_AddressOfOverloadFailed: // FIXME: Could do better |
3904 | case FK_NonConstLValueReferenceBindingToTemporary: |
3905 | case FK_NonConstLValueReferenceBindingToBitfield: |
3906 | case FK_NonConstLValueReferenceBindingToVectorElement: |
3907 | case FK_NonConstLValueReferenceBindingToMatrixElement: |
3908 | case FK_NonConstLValueReferenceBindingToUnrelated: |
3909 | case FK_RValueReferenceBindingToLValue: |
3910 | case FK_ReferenceAddrspaceMismatchTemporary: |
3911 | case FK_ReferenceInitDropsQualifiers: |
3912 | case FK_ReferenceInitFailed: |
3913 | case FK_ConversionFailed: |
3914 | case FK_ConversionFromPropertyFailed: |
3915 | case FK_TooManyInitsForScalar: |
3916 | case FK_ParenthesizedListInitForScalar: |
3917 | case FK_ReferenceBindingToInitList: |
3918 | case FK_InitListBadDestinationType: |
3919 | case FK_DefaultInitOfConst: |
3920 | case FK_Incomplete: |
3921 | case FK_ArrayTypeMismatch: |
3922 | case FK_NonConstantArrayInit: |
3923 | case FK_ListInitializationFailed: |
3924 | case FK_VariableLengthArrayHasInitializer: |
3925 | case FK_PlaceholderType: |
3926 | case FK_ExplicitConstructor: |
3927 | case FK_AddressOfUnaddressableFunction: |
3928 | case FK_ParenthesizedListInitFailed: |
3929 | case FK_DesignatedInitForNonAggregate: |
3930 | return false; |
3931 | |
3932 | case FK_ReferenceInitOverloadFailed: |
3933 | case FK_UserConversionOverloadFailed: |
3934 | case FK_ConstructorOverloadFailed: |
3935 | case FK_ListConstructorOverloadFailed: |
3936 | return FailedOverloadResult == OR_Ambiguous; |
3937 | } |
3938 | |
3939 | llvm_unreachable("Invalid EntityKind!" ); |
3940 | } |
3941 | |
3942 | bool InitializationSequence::isConstructorInitialization() const { |
3943 | return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization; |
3944 | } |
3945 | |
3946 | void |
3947 | InitializationSequence |
3948 | ::AddAddressOverloadResolutionStep(FunctionDecl *Function, |
3949 | DeclAccessPair Found, |
3950 | bool HadMultipleCandidates) { |
3951 | Step S; |
3952 | S.Kind = SK_ResolveAddressOfOverloadedFunction; |
3953 | S.Type = Function->getType(); |
3954 | S.Function.HadMultipleCandidates = HadMultipleCandidates; |
3955 | S.Function.Function = Function; |
3956 | S.Function.FoundDecl = Found; |
3957 | Steps.push_back(Elt: S); |
3958 | } |
3959 | |
3960 | void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType, |
3961 | ExprValueKind VK) { |
3962 | Step S; |
3963 | switch (VK) { |
3964 | case VK_PRValue: |
3965 | S.Kind = SK_CastDerivedToBasePRValue; |
3966 | break; |
3967 | case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break; |
3968 | case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break; |
3969 | } |
3970 | S.Type = BaseType; |
3971 | Steps.push_back(Elt: S); |
3972 | } |
3973 | |
3974 | void InitializationSequence::AddReferenceBindingStep(QualType T, |
3975 | bool BindingTemporary) { |
3976 | Step S; |
3977 | S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference; |
3978 | S.Type = T; |
3979 | Steps.push_back(Elt: S); |
3980 | } |
3981 | |
3982 | void InitializationSequence::AddFinalCopy(QualType T) { |
3983 | Step S; |
3984 | S.Kind = SK_FinalCopy; |
3985 | S.Type = T; |
3986 | Steps.push_back(Elt: S); |
3987 | } |
3988 | |
3989 | void InitializationSequence::(QualType T) { |
3990 | Step S; |
3991 | S.Kind = SK_ExtraneousCopyToTemporary; |
3992 | S.Type = T; |
3993 | Steps.push_back(Elt: S); |
3994 | } |
3995 | |
3996 | void |
3997 | InitializationSequence::AddUserConversionStep(FunctionDecl *Function, |
3998 | DeclAccessPair FoundDecl, |
3999 | QualType T, |
4000 | bool HadMultipleCandidates) { |
4001 | Step S; |
4002 | S.Kind = SK_UserConversion; |
4003 | S.Type = T; |
4004 | S.Function.HadMultipleCandidates = HadMultipleCandidates; |
4005 | S.Function.Function = Function; |
4006 | S.Function.FoundDecl = FoundDecl; |
4007 | Steps.push_back(Elt: S); |
4008 | } |
4009 | |
4010 | void InitializationSequence::AddQualificationConversionStep(QualType Ty, |
4011 | ExprValueKind VK) { |
4012 | Step S; |
4013 | S.Kind = SK_QualificationConversionPRValue; // work around a gcc warning |
4014 | switch (VK) { |
4015 | case VK_PRValue: |
4016 | S.Kind = SK_QualificationConversionPRValue; |
4017 | break; |
4018 | case VK_XValue: |
4019 | S.Kind = SK_QualificationConversionXValue; |
4020 | break; |
4021 | case VK_LValue: |
4022 | S.Kind = SK_QualificationConversionLValue; |
4023 | break; |
4024 | } |
4025 | S.Type = Ty; |
4026 | Steps.push_back(Elt: S); |
4027 | } |
4028 | |
4029 | void InitializationSequence::AddFunctionReferenceConversionStep(QualType Ty) { |
4030 | Step S; |
4031 | S.Kind = SK_FunctionReferenceConversion; |
4032 | S.Type = Ty; |
4033 | Steps.push_back(Elt: S); |
4034 | } |
4035 | |
4036 | void InitializationSequence::AddAtomicConversionStep(QualType Ty) { |
4037 | Step S; |
4038 | S.Kind = SK_AtomicConversion; |
4039 | S.Type = Ty; |
4040 | Steps.push_back(Elt: S); |
4041 | } |
4042 | |
4043 | void InitializationSequence::AddConversionSequenceStep( |
4044 | const ImplicitConversionSequence &ICS, QualType T, |
4045 | bool TopLevelOfInitList) { |
4046 | Step S; |
4047 | S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing |
4048 | : SK_ConversionSequence; |
4049 | S.Type = T; |
4050 | S.ICS = new ImplicitConversionSequence(ICS); |
4051 | Steps.push_back(Elt: S); |
4052 | } |
4053 | |
4054 | void InitializationSequence::AddListInitializationStep(QualType T) { |
4055 | Step S; |
4056 | S.Kind = SK_ListInitialization; |
4057 | S.Type = T; |
4058 | Steps.push_back(Elt: S); |
4059 | } |
4060 | |
4061 | void InitializationSequence::AddConstructorInitializationStep( |
4062 | DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T, |
4063 | bool HadMultipleCandidates, bool FromInitList, bool AsInitList) { |
4064 | Step S; |
4065 | S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall |
4066 | : SK_ConstructorInitializationFromList |
4067 | : SK_ConstructorInitialization; |
4068 | S.Type = T; |
4069 | S.Function.HadMultipleCandidates = HadMultipleCandidates; |
4070 | S.Function.Function = Constructor; |
4071 | S.Function.FoundDecl = FoundDecl; |
4072 | Steps.push_back(Elt: S); |
4073 | } |
4074 | |
4075 | void InitializationSequence::AddZeroInitializationStep(QualType T) { |
4076 | Step S; |
4077 | S.Kind = SK_ZeroInitialization; |
4078 | S.Type = T; |
4079 | Steps.push_back(Elt: S); |
4080 | } |
4081 | |
4082 | void InitializationSequence::AddCAssignmentStep(QualType T) { |
4083 | Step S; |
4084 | S.Kind = SK_CAssignment; |
4085 | S.Type = T; |
4086 | Steps.push_back(Elt: S); |
4087 | } |
4088 | |
4089 | void InitializationSequence::AddStringInitStep(QualType T) { |
4090 | Step S; |
4091 | S.Kind = SK_StringInit; |
4092 | S.Type = T; |
4093 | Steps.push_back(Elt: S); |
4094 | } |
4095 | |
4096 | void InitializationSequence::AddObjCObjectConversionStep(QualType T) { |
4097 | Step S; |
4098 | S.Kind = SK_ObjCObjectConversion; |
4099 | S.Type = T; |
4100 | Steps.push_back(Elt: S); |
4101 | } |
4102 | |
4103 | void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) { |
4104 | Step S; |
4105 | S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit; |
4106 | S.Type = T; |
4107 | Steps.push_back(Elt: S); |
4108 | } |
4109 | |
4110 | void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) { |
4111 | Step S; |
4112 | S.Kind = SK_ArrayLoopIndex; |
4113 | S.Type = EltT; |
4114 | Steps.insert(I: Steps.begin(), Elt: S); |
4115 | |
4116 | S.Kind = SK_ArrayLoopInit; |
4117 | S.Type = T; |
4118 | Steps.push_back(Elt: S); |
4119 | } |
4120 | |
4121 | void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) { |
4122 | Step S; |
4123 | S.Kind = SK_ParenthesizedArrayInit; |
4124 | S.Type = T; |
4125 | Steps.push_back(Elt: S); |
4126 | } |
4127 | |
4128 | void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type, |
4129 | bool shouldCopy) { |
4130 | Step s; |
4131 | s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore |
4132 | : SK_PassByIndirectRestore); |
4133 | s.Type = type; |
4134 | Steps.push_back(Elt: s); |
4135 | } |
4136 | |
4137 | void InitializationSequence::AddProduceObjCObjectStep(QualType T) { |
4138 | Step S; |
4139 | S.Kind = SK_ProduceObjCObject; |
4140 | S.Type = T; |
4141 | Steps.push_back(Elt: S); |
4142 | } |
4143 | |
4144 | void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) { |
4145 | Step S; |
4146 | S.Kind = SK_StdInitializerList; |
4147 | S.Type = T; |
4148 | Steps.push_back(Elt: S); |
4149 | } |
4150 | |
4151 | void InitializationSequence::AddOCLSamplerInitStep(QualType T) { |
4152 | Step S; |
4153 | S.Kind = SK_OCLSamplerInit; |
4154 | S.Type = T; |
4155 | Steps.push_back(Elt: S); |
4156 | } |
4157 | |
4158 | void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T) { |
4159 | Step S; |
4160 | S.Kind = SK_OCLZeroOpaqueType; |
4161 | S.Type = T; |
4162 | Steps.push_back(Elt: S); |
4163 | } |
4164 | |
4165 | void InitializationSequence::AddParenthesizedListInitStep(QualType T) { |
4166 | Step S; |
4167 | S.Kind = SK_ParenthesizedListInit; |
4168 | S.Type = T; |
4169 | Steps.push_back(Elt: S); |
4170 | } |
4171 | |
4172 | void InitializationSequence::AddUnwrapInitListInitStep( |
4173 | InitListExpr *Syntactic) { |
4174 | assert(Syntactic->getNumInits() == 1 && |
4175 | "Can only unwrap trivial init lists." ); |
4176 | Step S; |
4177 | S.Kind = SK_UnwrapInitList; |
4178 | S.Type = Syntactic->getInit(Init: 0)->getType(); |
4179 | Steps.insert(I: Steps.begin(), Elt: S); |
4180 | } |
4181 | |
4182 | void InitializationSequence::RewrapReferenceInitList(QualType T, |
4183 | InitListExpr *Syntactic) { |
4184 | assert(Syntactic->getNumInits() == 1 && |
4185 | "Can only rewrap trivial init lists." ); |
4186 | Step S; |
4187 | S.Kind = SK_UnwrapInitList; |
4188 | S.Type = Syntactic->getInit(Init: 0)->getType(); |
4189 | Steps.insert(I: Steps.begin(), Elt: S); |
4190 | |
4191 | S.Kind = SK_RewrapInitList; |
4192 | S.Type = T; |
4193 | S.WrappingSyntacticList = Syntactic; |
4194 | Steps.push_back(Elt: S); |
4195 | } |
4196 | |
4197 | void InitializationSequence::SetOverloadFailure(FailureKind Failure, |
4198 | OverloadingResult Result) { |
4199 | setSequenceKind(FailedSequence); |
4200 | this->Failure = Failure; |
4201 | this->FailedOverloadResult = Result; |
4202 | } |
4203 | |
4204 | //===----------------------------------------------------------------------===// |
4205 | // Attempt initialization |
4206 | //===----------------------------------------------------------------------===// |
4207 | |
4208 | /// Tries to add a zero initializer. Returns true if that worked. |
4209 | static bool |
4210 | maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence, |
4211 | const InitializedEntity &Entity) { |
4212 | if (Entity.getKind() != InitializedEntity::EK_Variable) |
4213 | return false; |
4214 | |
4215 | VarDecl *VD = cast<VarDecl>(Val: Entity.getDecl()); |
4216 | if (VD->getInit() || VD->getEndLoc().isMacroID()) |
4217 | return false; |
4218 | |
4219 | QualType VariableTy = VD->getType().getCanonicalType(); |
4220 | SourceLocation Loc = S.getLocForEndOfToken(Loc: VD->getEndLoc()); |
4221 | std::string Init = S.getFixItZeroInitializerForType(T: VariableTy, Loc); |
4222 | if (!Init.empty()) { |
4223 | Sequence.AddZeroInitializationStep(T: Entity.getType()); |
4224 | Sequence.SetZeroInitializationFixit(Fixit: Init, L: Loc); |
4225 | return true; |
4226 | } |
4227 | return false; |
4228 | } |
4229 | |
4230 | static void MaybeProduceObjCObject(Sema &S, |
4231 | InitializationSequence &Sequence, |
4232 | const InitializedEntity &Entity) { |
4233 | if (!S.getLangOpts().ObjCAutoRefCount) return; |
4234 | |
4235 | /// When initializing a parameter, produce the value if it's marked |
4236 | /// __attribute__((ns_consumed)). |
4237 | if (Entity.isParameterKind()) { |
4238 | if (!Entity.isParameterConsumed()) |
4239 | return; |
4240 | |
4241 | assert(Entity.getType()->isObjCRetainableType() && |
4242 | "consuming an object of unretainable type?" ); |
4243 | Sequence.AddProduceObjCObjectStep(T: Entity.getType()); |
4244 | |
4245 | /// When initializing a return value, if the return type is a |
4246 | /// retainable type, then returns need to immediately retain the |
4247 | /// object. If an autorelease is required, it will be done at the |
4248 | /// last instant. |
4249 | } else if (Entity.getKind() == InitializedEntity::EK_Result || |
4250 | Entity.getKind() == InitializedEntity::EK_StmtExprResult) { |
4251 | if (!Entity.getType()->isObjCRetainableType()) |
4252 | return; |
4253 | |
4254 | Sequence.AddProduceObjCObjectStep(T: Entity.getType()); |
4255 | } |
4256 | } |
4257 | |
4258 | /// Initialize an array from another array |
4259 | static void TryArrayCopy(Sema &S, const InitializationKind &Kind, |
4260 | const InitializedEntity &Entity, Expr *Initializer, |
4261 | QualType DestType, InitializationSequence &Sequence, |
4262 | bool TreatUnavailableAsInvalid) { |
4263 | // If source is a prvalue, use it directly. |
4264 | if (Initializer->isPRValue()) { |
4265 | Sequence.AddArrayInitStep(T: DestType, /*IsGNUExtension*/ false); |
4266 | return; |
4267 | } |
4268 | |
4269 | // Emit element-at-a-time copy loop. |
4270 | InitializedEntity Element = |
4271 | InitializedEntity::InitializeElement(Context&: S.Context, Index: 0, Parent: Entity); |
4272 | QualType InitEltT = |
4273 | S.Context.getAsArrayType(T: Initializer->getType())->getElementType(); |
4274 | OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT, |
4275 | Initializer->getValueKind(), |
4276 | Initializer->getObjectKind()); |
4277 | Expr *OVEAsExpr = &OVE; |
4278 | Sequence.InitializeFrom(S, Entity: Element, Kind, Args: OVEAsExpr, |
4279 | /*TopLevelOfInitList*/ false, |
4280 | TreatUnavailableAsInvalid); |
4281 | if (Sequence) |
4282 | Sequence.AddArrayInitLoopStep(T: Entity.getType(), EltT: InitEltT); |
4283 | } |
4284 | |
4285 | static void TryListInitialization(Sema &S, |
4286 | const InitializedEntity &Entity, |
4287 | const InitializationKind &Kind, |
4288 | InitListExpr *InitList, |
4289 | InitializationSequence &Sequence, |
4290 | bool TreatUnavailableAsInvalid); |
4291 | |
4292 | /// When initializing from init list via constructor, handle |
4293 | /// initialization of an object of type std::initializer_list<T>. |
4294 | /// |
4295 | /// \return true if we have handled initialization of an object of type |
4296 | /// std::initializer_list<T>, false otherwise. |
4297 | static bool TryInitializerListConstruction(Sema &S, |
4298 | InitListExpr *List, |
4299 | QualType DestType, |
4300 | InitializationSequence &Sequence, |
4301 | bool TreatUnavailableAsInvalid) { |
4302 | QualType E; |
4303 | if (!S.isStdInitializerList(Ty: DestType, Element: &E)) |
4304 | return false; |
4305 | |
4306 | if (!S.isCompleteType(Loc: List->getExprLoc(), T: E)) { |
4307 | Sequence.setIncompleteTypeFailure(E); |
4308 | return true; |
4309 | } |
4310 | |
4311 | // Try initializing a temporary array from the init list. |
4312 | QualType ArrayType = S.Context.getConstantArrayType( |
4313 | EltTy: E.withConst(), |
4314 | ArySize: llvm::APInt(S.Context.getTypeSize(T: S.Context.getSizeType()), |
4315 | List->getNumInitsWithEmbedExpanded()), |
4316 | SizeExpr: nullptr, ASM: clang::ArraySizeModifier::Normal, IndexTypeQuals: 0); |
4317 | InitializedEntity HiddenArray = |
4318 | InitializedEntity::InitializeTemporary(Type: ArrayType); |
4319 | InitializationKind Kind = InitializationKind::CreateDirectList( |
4320 | InitLoc: List->getExprLoc(), LBraceLoc: List->getBeginLoc(), RBraceLoc: List->getEndLoc()); |
4321 | TryListInitialization(S, Entity: HiddenArray, Kind, InitList: List, Sequence, |
4322 | TreatUnavailableAsInvalid); |
4323 | if (Sequence) |
4324 | Sequence.AddStdInitializerListConstructionStep(T: DestType); |
4325 | return true; |
4326 | } |
4327 | |
4328 | /// Determine if the constructor has the signature of a copy or move |
4329 | /// constructor for the type T of the class in which it was found. That is, |
4330 | /// determine if its first parameter is of type T or reference to (possibly |
4331 | /// cv-qualified) T. |
4332 | static bool hasCopyOrMoveCtorParam(ASTContext &Ctx, |
4333 | const ConstructorInfo &Info) { |
4334 | if (Info.Constructor->getNumParams() == 0) |
4335 | return false; |
4336 | |
4337 | QualType ParmT = |
4338 | Info.Constructor->getParamDecl(i: 0)->getType().getNonReferenceType(); |
4339 | QualType ClassT = |
4340 | Ctx.getRecordType(Decl: cast<CXXRecordDecl>(Val: Info.FoundDecl->getDeclContext())); |
4341 | |
4342 | return Ctx.hasSameUnqualifiedType(T1: ParmT, T2: ClassT); |
4343 | } |
4344 | |
4345 | static OverloadingResult ResolveConstructorOverload( |
4346 | Sema &S, SourceLocation DeclLoc, MultiExprArg Args, |
4347 | OverloadCandidateSet &CandidateSet, QualType DestType, |
4348 | DeclContext::lookup_result Ctors, OverloadCandidateSet::iterator &Best, |
4349 | bool CopyInitializing, bool AllowExplicit, bool OnlyListConstructors, |
4350 | bool IsListInit, bool RequireActualConstructor, |
4351 | bool SecondStepOfCopyInit = false) { |
4352 | CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByConstructor); |
4353 | CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace()); |
4354 | |
4355 | for (NamedDecl *D : Ctors) { |
4356 | auto Info = getConstructorInfo(ND: D); |
4357 | if (!Info.Constructor || Info.Constructor->isInvalidDecl()) |
4358 | continue; |
4359 | |
4360 | if (OnlyListConstructors && !S.isInitListConstructor(Ctor: Info.Constructor)) |
4361 | continue; |
4362 | |
4363 | // C++11 [over.best.ics]p4: |
4364 | // ... and the constructor or user-defined conversion function is a |
4365 | // candidate by |
4366 | // - 13.3.1.3, when the argument is the temporary in the second step |
4367 | // of a class copy-initialization, or |
4368 | // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here] |
4369 | // - the second phase of 13.3.1.7 when the initializer list has exactly |
4370 | // one element that is itself an initializer list, and the target is |
4371 | // the first parameter of a constructor of class X, and the conversion |
4372 | // is to X or reference to (possibly cv-qualified X), |
4373 | // user-defined conversion sequences are not considered. |
4374 | bool SuppressUserConversions = |
4375 | SecondStepOfCopyInit || |
4376 | (IsListInit && Args.size() == 1 && isa<InitListExpr>(Val: Args[0]) && |
4377 | hasCopyOrMoveCtorParam(Ctx&: S.Context, Info)); |
4378 | |
4379 | if (Info.ConstructorTmpl) |
4380 | S.AddTemplateOverloadCandidate( |
4381 | FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl, |
4382 | /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args, CandidateSet, SuppressUserConversions, |
4383 | /*PartialOverloading=*/false, AllowExplicit); |
4384 | else { |
4385 | // C++ [over.match.copy]p1: |
4386 | // - When initializing a temporary to be bound to the first parameter |
4387 | // of a constructor [for type T] that takes a reference to possibly |
4388 | // cv-qualified T as its first argument, called with a single |
4389 | // argument in the context of direct-initialization, explicit |
4390 | // conversion functions are also considered. |
4391 | // FIXME: What if a constructor template instantiates to such a signature? |
4392 | bool AllowExplicitConv = AllowExplicit && !CopyInitializing && |
4393 | Args.size() == 1 && |
4394 | hasCopyOrMoveCtorParam(Ctx&: S.Context, Info); |
4395 | S.AddOverloadCandidate(Function: Info.Constructor, FoundDecl: Info.FoundDecl, Args, |
4396 | CandidateSet, SuppressUserConversions, |
4397 | /*PartialOverloading=*/false, AllowExplicit, |
4398 | AllowExplicitConversion: AllowExplicitConv); |
4399 | } |
4400 | } |
4401 | |
4402 | // FIXME: Work around a bug in C++17 guaranteed copy elision. |
4403 | // |
4404 | // When initializing an object of class type T by constructor |
4405 | // ([over.match.ctor]) or by list-initialization ([over.match.list]) |
4406 | // from a single expression of class type U, conversion functions of |
4407 | // U that convert to the non-reference type cv T are candidates. |
4408 | // Explicit conversion functions are only candidates during |
4409 | // direct-initialization. |
4410 | // |
4411 | // Note: SecondStepOfCopyInit is only ever true in this case when |
4412 | // evaluating whether to produce a C++98 compatibility warning. |
4413 | if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 && |
4414 | !RequireActualConstructor && !SecondStepOfCopyInit) { |
4415 | Expr *Initializer = Args[0]; |
4416 | auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl(); |
4417 | if (SourceRD && S.isCompleteType(Loc: DeclLoc, T: Initializer->getType())) { |
4418 | const auto &Conversions = SourceRD->getVisibleConversionFunctions(); |
4419 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { |
4420 | NamedDecl *D = *I; |
4421 | CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: D->getDeclContext()); |
4422 | D = D->getUnderlyingDecl(); |
4423 | |
4424 | FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D); |
4425 | CXXConversionDecl *Conv; |
4426 | if (ConvTemplate) |
4427 | Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl()); |
4428 | else |
4429 | Conv = cast<CXXConversionDecl>(Val: D); |
4430 | |
4431 | if (ConvTemplate) |
4432 | S.AddTemplateConversionCandidate( |
4433 | FunctionTemplate: ConvTemplate, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer, ToType: DestType, |
4434 | CandidateSet, AllowObjCConversionOnExplicit: AllowExplicit, AllowExplicit, |
4435 | /*AllowResultConversion*/ false); |
4436 | else |
4437 | S.AddConversionCandidate(Conversion: Conv, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer, |
4438 | ToType: DestType, CandidateSet, AllowObjCConversionOnExplicit: AllowExplicit, |
4439 | AllowExplicit, |
4440 | /*AllowResultConversion*/ false); |
4441 | } |
4442 | } |
4443 | } |
4444 | |
4445 | // Perform overload resolution and return the result. |
4446 | return CandidateSet.BestViableFunction(S, Loc: DeclLoc, Best); |
4447 | } |
4448 | |
4449 | /// Attempt initialization by constructor (C++ [dcl.init]), which |
4450 | /// enumerates the constructors of the initialized entity and performs overload |
4451 | /// resolution to select the best. |
4452 | /// \param DestType The destination class type. |
4453 | /// \param DestArrayType The destination type, which is either DestType or |
4454 | /// a (possibly multidimensional) array of DestType. |
4455 | /// \param IsListInit Is this list-initialization? |
4456 | /// \param IsInitListCopy Is this non-list-initialization resulting from a |
4457 | /// list-initialization from {x} where x is the same |
4458 | /// aggregate type as the entity? |
4459 | static void TryConstructorInitialization(Sema &S, |
4460 | const InitializedEntity &Entity, |
4461 | const InitializationKind &Kind, |
4462 | MultiExprArg Args, QualType DestType, |
4463 | QualType DestArrayType, |
4464 | InitializationSequence &Sequence, |
4465 | bool IsListInit = false, |
4466 | bool IsInitListCopy = false) { |
4467 | assert(((!IsListInit && !IsInitListCopy) || |
4468 | (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && |
4469 | "IsListInit/IsInitListCopy must come with a single initializer list " |
4470 | "argument." ); |
4471 | InitListExpr *ILE = |
4472 | (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Val: Args[0]) : nullptr; |
4473 | MultiExprArg UnwrappedArgs = |
4474 | ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args; |
4475 | |
4476 | // The type we're constructing needs to be complete. |
4477 | if (!S.isCompleteType(Loc: Kind.getLocation(), T: DestType)) { |
4478 | Sequence.setIncompleteTypeFailure(DestType); |
4479 | return; |
4480 | } |
4481 | |
4482 | bool RequireActualConstructor = |
4483 | !(Entity.getKind() != InitializedEntity::EK_Base && |
4484 | Entity.getKind() != InitializedEntity::EK_Delegating && |
4485 | Entity.getKind() != |
4486 | InitializedEntity::EK_LambdaToBlockConversionBlockElement); |
4487 | |
4488 | bool CopyElisionPossible = false; |
4489 | auto ElideConstructor = [&] { |
4490 | // Convert qualifications if necessary. |
4491 | Sequence.AddQualificationConversionStep(Ty: DestType, VK: VK_PRValue); |
4492 | if (ILE) |
4493 | Sequence.RewrapReferenceInitList(T: DestType, Syntactic: ILE); |
4494 | }; |
4495 | |
4496 | // C++17 [dcl.init]p17: |
4497 | // - If the initializer expression is a prvalue and the cv-unqualified |
4498 | // version of the source type is the same class as the class of the |
4499 | // destination, the initializer expression is used to initialize the |
4500 | // destination object. |
4501 | // Per DR (no number yet), this does not apply when initializing a base |
4502 | // class or delegating to another constructor from a mem-initializer. |
4503 | // ObjC++: Lambda captured by the block in the lambda to block conversion |
4504 | // should avoid copy elision. |
4505 | if (S.getLangOpts().CPlusPlus17 && !RequireActualConstructor && |
4506 | UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() && |
4507 | S.Context.hasSameUnqualifiedType(T1: UnwrappedArgs[0]->getType(), T2: DestType)) { |
4508 | if (ILE && !DestType->isAggregateType()) { |
4509 | // CWG2311: T{ prvalue_of_type_T } is not eligible for copy elision |
4510 | // Make this an elision if this won't call an initializer-list |
4511 | // constructor. (Always on an aggregate type or check constructors first.) |
4512 | |
4513 | // This effectively makes our resolution as follows. The parts in angle |
4514 | // brackets are additions. |
4515 | // C++17 [over.match.list]p(1.2): |
4516 | // - If no viable initializer-list constructor is found <and the |
4517 | // initializer list does not consist of exactly a single element with |
4518 | // the same cv-unqualified class type as T>, [...] |
4519 | // C++17 [dcl.init.list]p(3.6): |
4520 | // - Otherwise, if T is a class type, constructors are considered. The |
4521 | // applicable constructors are enumerated and the best one is chosen |
4522 | // through overload resolution. <If no constructor is found and the |
4523 | // initializer list consists of exactly a single element with the same |
4524 | // cv-unqualified class type as T, the object is initialized from that |
4525 | // element (by copy-initialization for copy-list-initialization, or by |
4526 | // direct-initialization for direct-list-initialization). Otherwise, > |
4527 | // if a narrowing conversion [...] |
4528 | assert(!IsInitListCopy && |
4529 | "IsInitListCopy only possible with aggregate types" ); |
4530 | CopyElisionPossible = true; |
4531 | } else { |
4532 | ElideConstructor(); |
4533 | return; |
4534 | } |
4535 | } |
4536 | |
4537 | const RecordType *DestRecordType = DestType->getAs<RecordType>(); |
4538 | assert(DestRecordType && "Constructor initialization requires record type" ); |
4539 | CXXRecordDecl *DestRecordDecl |
4540 | = cast<CXXRecordDecl>(Val: DestRecordType->getDecl()); |
4541 | |
4542 | // Build the candidate set directly in the initialization sequence |
4543 | // structure, so that it will persist if we fail. |
4544 | OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); |
4545 | |
4546 | // Determine whether we are allowed to call explicit constructors or |
4547 | // explicit conversion operators. |
4548 | bool AllowExplicit = Kind.AllowExplicit() || IsListInit; |
4549 | bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy; |
4550 | |
4551 | // - Otherwise, if T is a class type, constructors are considered. The |
4552 | // applicable constructors are enumerated, and the best one is chosen |
4553 | // through overload resolution. |
4554 | DeclContext::lookup_result Ctors = S.LookupConstructors(Class: DestRecordDecl); |
4555 | |
4556 | OverloadingResult Result = OR_No_Viable_Function; |
4557 | OverloadCandidateSet::iterator Best; |
4558 | bool AsInitializerList = false; |
4559 | |
4560 | // C++11 [over.match.list]p1, per DR1467: |
4561 | // When objects of non-aggregate type T are list-initialized, such that |
4562 | // 8.5.4 [dcl.init.list] specifies that overload resolution is performed |
4563 | // according to the rules in this section, overload resolution selects |
4564 | // the constructor in two phases: |
4565 | // |
4566 | // - Initially, the candidate functions are the initializer-list |
4567 | // constructors of the class T and the argument list consists of the |
4568 | // initializer list as a single argument. |
4569 | if (IsListInit) { |
4570 | AsInitializerList = true; |
4571 | |
4572 | // If the initializer list has no elements and T has a default constructor, |
4573 | // the first phase is omitted. |
4574 | if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(Class: DestRecordDecl))) |
4575 | Result = ResolveConstructorOverload( |
4576 | S, DeclLoc: Kind.getLocation(), Args, CandidateSet, DestType, Ctors, Best, |
4577 | CopyInitializing: CopyInitialization, AllowExplicit, |
4578 | /*OnlyListConstructors=*/true, IsListInit, RequireActualConstructor); |
4579 | |
4580 | if (CopyElisionPossible && Result == OR_No_Viable_Function) { |
4581 | // No initializer list candidate |
4582 | ElideConstructor(); |
4583 | return; |
4584 | } |
4585 | } |
4586 | |
4587 | // C++11 [over.match.list]p1: |
4588 | // - If no viable initializer-list constructor is found, overload resolution |
4589 | // is performed again, where the candidate functions are all the |
4590 | // constructors of the class T and the argument list consists of the |
4591 | // elements of the initializer list. |
4592 | if (Result == OR_No_Viable_Function) { |
4593 | AsInitializerList = false; |
4594 | Result = ResolveConstructorOverload( |
4595 | S, DeclLoc: Kind.getLocation(), Args: UnwrappedArgs, CandidateSet, DestType, Ctors, |
4596 | Best, CopyInitializing: CopyInitialization, AllowExplicit, |
4597 | /*OnlyListConstructors=*/false, IsListInit, RequireActualConstructor); |
4598 | } |
4599 | if (Result) { |
4600 | Sequence.SetOverloadFailure( |
4601 | Failure: IsListInit ? InitializationSequence::FK_ListConstructorOverloadFailed |
4602 | : InitializationSequence::FK_ConstructorOverloadFailed, |
4603 | Result); |
4604 | |
4605 | if (Result != OR_Deleted) |
4606 | return; |
4607 | } |
4608 | |
4609 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
4610 | |
4611 | // In C++17, ResolveConstructorOverload can select a conversion function |
4612 | // instead of a constructor. |
4613 | if (auto *CD = dyn_cast<CXXConversionDecl>(Val: Best->Function)) { |
4614 | // Add the user-defined conversion step that calls the conversion function. |
4615 | QualType ConvType = CD->getConversionType(); |
4616 | assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) && |
4617 | "should not have selected this conversion function" ); |
4618 | Sequence.AddUserConversionStep(Function: CD, FoundDecl: Best->FoundDecl, T: ConvType, |
4619 | HadMultipleCandidates); |
4620 | if (!S.Context.hasSameType(T1: ConvType, T2: DestType)) |
4621 | Sequence.AddQualificationConversionStep(Ty: DestType, VK: VK_PRValue); |
4622 | if (IsListInit) |
4623 | Sequence.RewrapReferenceInitList(T: Entity.getType(), Syntactic: ILE); |
4624 | return; |
4625 | } |
4626 | |
4627 | CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Val: Best->Function); |
4628 | if (Result != OR_Deleted) { |
4629 | if (!IsListInit && |
4630 | (Kind.getKind() == InitializationKind::IK_Default || |
4631 | Kind.getKind() == InitializationKind::IK_Direct) && |
4632 | !(CtorDecl->isCopyOrMoveConstructor() && CtorDecl->isImplicit()) && |
4633 | DestRecordDecl->isAggregate() && |
4634 | DestRecordDecl->hasUninitializedExplicitInitFields()) { |
4635 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::warn_field_requires_explicit_init) |
4636 | << /* Var-in-Record */ 1 << DestRecordDecl; |
4637 | emitUninitializedExplicitInitFields(S, R: DestRecordDecl); |
4638 | } |
4639 | |
4640 | // C++11 [dcl.init]p6: |
4641 | // If a program calls for the default initialization of an object |
4642 | // of a const-qualified type T, T shall be a class type with a |
4643 | // user-provided default constructor. |
4644 | // C++ core issue 253 proposal: |
4645 | // If the implicit default constructor initializes all subobjects, no |
4646 | // initializer should be required. |
4647 | // The 253 proposal is for example needed to process libstdc++ headers |
4648 | // in 5.x. |
4649 | if (Kind.getKind() == InitializationKind::IK_Default && |
4650 | Entity.getType().isConstQualified()) { |
4651 | if (!CtorDecl->getParent()->allowConstDefaultInit()) { |
4652 | if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity)) |
4653 | Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); |
4654 | return; |
4655 | } |
4656 | } |
4657 | |
4658 | // C++11 [over.match.list]p1: |
4659 | // In copy-list-initialization, if an explicit constructor is chosen, the |
4660 | // initializer is ill-formed. |
4661 | if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) { |
4662 | Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor); |
4663 | return; |
4664 | } |
4665 | } |
4666 | |
4667 | // [class.copy.elision]p3: |
4668 | // In some copy-initialization contexts, a two-stage overload resolution |
4669 | // is performed. |
4670 | // If the first overload resolution selects a deleted function, we also |
4671 | // need the initialization sequence to decide whether to perform the second |
4672 | // overload resolution. |
4673 | // For deleted functions in other contexts, there is no need to get the |
4674 | // initialization sequence. |
4675 | if (Result == OR_Deleted && Kind.getKind() != InitializationKind::IK_Copy) |
4676 | return; |
4677 | |
4678 | // Add the constructor initialization step. Any cv-qualification conversion is |
4679 | // subsumed by the initialization. |
4680 | Sequence.AddConstructorInitializationStep( |
4681 | FoundDecl: Best->FoundDecl, Constructor: CtorDecl, T: DestArrayType, HadMultipleCandidates, |
4682 | FromInitList: IsListInit | IsInitListCopy, AsInitList: AsInitializerList); |
4683 | } |
4684 | |
4685 | static void TryOrBuildParenListInitialization( |
4686 | Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, |
4687 | ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly, |
4688 | ExprResult *Result = nullptr); |
4689 | |
4690 | /// Attempt to initialize an object of a class type either by |
4691 | /// direct-initialization, or by copy-initialization from an |
4692 | /// expression of the same or derived class type. This corresponds |
4693 | /// to the first two sub-bullets of C++2c [dcl.init.general] p16.6. |
4694 | /// |
4695 | /// \param IsAggrListInit Is this non-list-initialization being done as |
4696 | /// part of a list-initialization of an aggregate |
4697 | /// from a single expression of the same or |
4698 | /// derived class type (C++2c [dcl.init.list] p3.2)? |
4699 | static void TryConstructorOrParenListInitialization( |
4700 | Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, |
4701 | MultiExprArg Args, QualType DestType, InitializationSequence &Sequence, |
4702 | bool IsAggrListInit) { |
4703 | // C++2c [dcl.init.general] p16.6: |
4704 | // * Otherwise, if the destination type is a class type: |
4705 | // * If the initializer expression is a prvalue and |
4706 | // the cv-unqualified version of the source type is the same |
4707 | // as the destination type, the initializer expression is used |
4708 | // to initialize the destination object. |
4709 | // * Otherwise, if the initialization is direct-initialization, |
4710 | // or if it is copy-initialization where the cv-unqualified |
4711 | // version of the source type is the same as or is derived from |
4712 | // the class of the destination type, constructors are considered. |
4713 | // The applicable constructors are enumerated, and the best one |
4714 | // is chosen through overload resolution. Then: |
4715 | // * If overload resolution is successful, the selected |
4716 | // constructor is called to initialize the object, with |
4717 | // the initializer expression or expression-list as its |
4718 | // argument(s). |
4719 | TryConstructorInitialization(S, Entity, Kind, Args, DestType, DestArrayType: DestType, |
4720 | Sequence, /*IsListInit=*/false, IsInitListCopy: IsAggrListInit); |
4721 | |
4722 | // * Otherwise, if no constructor is viable, the destination type |
4723 | // is an aggregate class, and the initializer is a parenthesized |
4724 | // expression-list, the object is initialized as follows. [...] |
4725 | // Parenthesized initialization of aggregates is a C++20 feature. |
4726 | if (S.getLangOpts().CPlusPlus20 && |
4727 | Kind.getKind() == InitializationKind::IK_Direct && Sequence.Failed() && |
4728 | Sequence.getFailureKind() == |
4729 | InitializationSequence::FK_ConstructorOverloadFailed && |
4730 | Sequence.getFailedOverloadResult() == OR_No_Viable_Function && |
4731 | (IsAggrListInit || DestType->isAggregateType())) |
4732 | TryOrBuildParenListInitialization(S, Entity, Kind, Args, Sequence, |
4733 | /*VerifyOnly=*/true); |
4734 | |
4735 | // * Otherwise, the initialization is ill-formed. |
4736 | } |
4737 | |
4738 | static bool |
4739 | ResolveOverloadedFunctionForReferenceBinding(Sema &S, |
4740 | Expr *Initializer, |
4741 | QualType &SourceType, |
4742 | QualType &UnqualifiedSourceType, |
4743 | QualType UnqualifiedTargetType, |
4744 | InitializationSequence &Sequence) { |
4745 | if (S.Context.getCanonicalType(T: UnqualifiedSourceType) == |
4746 | S.Context.OverloadTy) { |
4747 | DeclAccessPair Found; |
4748 | bool HadMultipleCandidates = false; |
4749 | if (FunctionDecl *Fn |
4750 | = S.ResolveAddressOfOverloadedFunction(AddressOfExpr: Initializer, |
4751 | TargetType: UnqualifiedTargetType, |
4752 | Complain: false, Found, |
4753 | pHadMultipleCandidates: &HadMultipleCandidates)) { |
4754 | Sequence.AddAddressOverloadResolutionStep(Function: Fn, Found, |
4755 | HadMultipleCandidates); |
4756 | SourceType = Fn->getType(); |
4757 | UnqualifiedSourceType = SourceType.getUnqualifiedType(); |
4758 | } else if (!UnqualifiedTargetType->isRecordType()) { |
4759 | Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); |
4760 | return true; |
4761 | } |
4762 | } |
4763 | return false; |
4764 | } |
4765 | |
4766 | static void TryReferenceInitializationCore(Sema &S, |
4767 | const InitializedEntity &Entity, |
4768 | const InitializationKind &Kind, |
4769 | Expr *Initializer, |
4770 | QualType cv1T1, QualType T1, |
4771 | Qualifiers T1Quals, |
4772 | QualType cv2T2, QualType T2, |
4773 | Qualifiers T2Quals, |
4774 | InitializationSequence &Sequence, |
4775 | bool TopLevelOfInitList); |
4776 | |
4777 | static void TryValueInitialization(Sema &S, |
4778 | const InitializedEntity &Entity, |
4779 | const InitializationKind &Kind, |
4780 | InitializationSequence &Sequence, |
4781 | InitListExpr *InitList = nullptr); |
4782 | |
4783 | /// Attempt list initialization of a reference. |
4784 | static void TryReferenceListInitialization(Sema &S, |
4785 | const InitializedEntity &Entity, |
4786 | const InitializationKind &Kind, |
4787 | InitListExpr *InitList, |
4788 | InitializationSequence &Sequence, |
4789 | bool TreatUnavailableAsInvalid) { |
4790 | // First, catch C++03 where this isn't possible. |
4791 | if (!S.getLangOpts().CPlusPlus11) { |
4792 | Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList); |
4793 | return; |
4794 | } |
4795 | // Can't reference initialize a compound literal. |
4796 | if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) { |
4797 | Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList); |
4798 | return; |
4799 | } |
4800 | |
4801 | QualType DestType = Entity.getType(); |
4802 | QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType(); |
4803 | Qualifiers T1Quals; |
4804 | QualType T1 = S.Context.getUnqualifiedArrayType(T: cv1T1, Quals&: T1Quals); |
4805 | |
4806 | // Reference initialization via an initializer list works thus: |
4807 | // If the initializer list consists of a single element that is |
4808 | // reference-related to the referenced type, bind directly to that element |
4809 | // (possibly creating temporaries). |
4810 | // Otherwise, initialize a temporary with the initializer list and |
4811 | // bind to that. |
4812 | if (InitList->getNumInits() == 1) { |
4813 | Expr *Initializer = InitList->getInit(Init: 0); |
4814 | QualType cv2T2 = S.getCompletedType(E: Initializer); |
4815 | Qualifiers T2Quals; |
4816 | QualType T2 = S.Context.getUnqualifiedArrayType(T: cv2T2, Quals&: T2Quals); |
4817 | |
4818 | // If this fails, creating a temporary wouldn't work either. |
4819 | if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, SourceType&: cv2T2, UnqualifiedSourceType&: T2, |
4820 | UnqualifiedTargetType: T1, Sequence)) |
4821 | return; |
4822 | |
4823 | SourceLocation DeclLoc = Initializer->getBeginLoc(); |
4824 | Sema::ReferenceCompareResult RefRelationship |
4825 | = S.CompareReferenceRelationship(Loc: DeclLoc, T1: cv1T1, T2: cv2T2); |
4826 | if (RefRelationship >= Sema::Ref_Related) { |
4827 | // Try to bind the reference here. |
4828 | TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1, |
4829 | T1Quals, cv2T2, T2, T2Quals, Sequence, |
4830 | /*TopLevelOfInitList=*/true); |
4831 | if (Sequence) |
4832 | Sequence.RewrapReferenceInitList(T: cv1T1, Syntactic: InitList); |
4833 | return; |
4834 | } |
4835 | |
4836 | // Update the initializer if we've resolved an overloaded function. |
4837 | if (Sequence.step_begin() != Sequence.step_end()) |
4838 | Sequence.RewrapReferenceInitList(T: cv1T1, Syntactic: InitList); |
4839 | } |
4840 | // Perform address space compatibility check. |
4841 | QualType cv1T1IgnoreAS = cv1T1; |
4842 | if (T1Quals.hasAddressSpace()) { |
4843 | Qualifiers T2Quals; |
4844 | (void)S.Context.getUnqualifiedArrayType(T: InitList->getType(), Quals&: T2Quals); |
4845 | if (!T1Quals.isAddressSpaceSupersetOf(other: T2Quals, Ctx: S.getASTContext())) { |
4846 | Sequence.SetFailed( |
4847 | InitializationSequence::FK_ReferenceInitDropsQualifiers); |
4848 | return; |
4849 | } |
4850 | // Ignore address space of reference type at this point and perform address |
4851 | // space conversion after the reference binding step. |
4852 | cv1T1IgnoreAS = |
4853 | S.Context.getQualifiedType(T: T1, Qs: T1Quals.withoutAddressSpace()); |
4854 | } |
4855 | // Not reference-related. Create a temporary and bind to that. |
4856 | InitializedEntity TempEntity = |
4857 | InitializedEntity::InitializeTemporary(Type: cv1T1IgnoreAS); |
4858 | |
4859 | TryListInitialization(S, Entity: TempEntity, Kind, InitList, Sequence, |
4860 | TreatUnavailableAsInvalid); |
4861 | if (Sequence) { |
4862 | if (DestType->isRValueReferenceType() || |
4863 | (T1Quals.hasConst() && !T1Quals.hasVolatile())) { |
4864 | if (S.getLangOpts().CPlusPlus20 && |
4865 | isa<IncompleteArrayType>(Val: T1->getUnqualifiedDesugaredType()) && |
4866 | DestType->isRValueReferenceType()) { |
4867 | // C++20 [dcl.init.list]p3.10: |
4868 | // List-initialization of an object or reference of type T is defined as |
4869 | // follows: |
4870 | // ..., unless T is “reference to array of unknown bound of U”, in which |
4871 | // case the type of the prvalue is the type of x in the declaration U |
4872 | // x[] H, where H is the initializer list. |
4873 | Sequence.AddQualificationConversionStep(Ty: cv1T1, VK: clang::VK_PRValue); |
4874 | } |
4875 | Sequence.AddReferenceBindingStep(T: cv1T1IgnoreAS, |
4876 | /*BindingTemporary=*/true); |
4877 | if (T1Quals.hasAddressSpace()) |
4878 | Sequence.AddQualificationConversionStep( |
4879 | Ty: cv1T1, VK: DestType->isRValueReferenceType() ? VK_XValue : VK_LValue); |
4880 | } else |
4881 | Sequence.SetFailed( |
4882 | InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary); |
4883 | } |
4884 | } |
4885 | |
4886 | /// Attempt list initialization (C++0x [dcl.init.list]) |
4887 | static void TryListInitialization(Sema &S, |
4888 | const InitializedEntity &Entity, |
4889 | const InitializationKind &Kind, |
4890 | InitListExpr *InitList, |
4891 | InitializationSequence &Sequence, |
4892 | bool TreatUnavailableAsInvalid) { |
4893 | QualType DestType = Entity.getType(); |
4894 | |
4895 | if (S.getLangOpts().HLSL && !S.HLSL().transformInitList(Entity, Init: InitList)) |
4896 | return; |
4897 | |
4898 | // C++ doesn't allow scalar initialization with more than one argument. |
4899 | // But C99 complex numbers are scalars and it makes sense there. |
4900 | if (S.getLangOpts().CPlusPlus && DestType->isScalarType() && |
4901 | !DestType->isAnyComplexType() && InitList->getNumInits() > 1) { |
4902 | Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar); |
4903 | return; |
4904 | } |
4905 | if (DestType->isReferenceType()) { |
4906 | TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence, |
4907 | TreatUnavailableAsInvalid); |
4908 | return; |
4909 | } |
4910 | |
4911 | if (DestType->isRecordType() && |
4912 | !S.isCompleteType(Loc: InitList->getBeginLoc(), T: DestType)) { |
4913 | Sequence.setIncompleteTypeFailure(DestType); |
4914 | return; |
4915 | } |
4916 | |
4917 | // C++20 [dcl.init.list]p3: |
4918 | // - If the braced-init-list contains a designated-initializer-list, T shall |
4919 | // be an aggregate class. [...] Aggregate initialization is performed. |
4920 | // |
4921 | // We allow arrays here too in order to support array designators. |
4922 | // |
4923 | // FIXME: This check should precede the handling of reference initialization. |
4924 | // We follow other compilers in allowing things like 'Aggr &&a = {.x = 1};' |
4925 | // as a tentative DR resolution. |
4926 | bool IsDesignatedInit = InitList->hasDesignatedInit(); |
4927 | if (!DestType->isAggregateType() && IsDesignatedInit) { |
4928 | Sequence.SetFailed( |
4929 | InitializationSequence::FK_DesignatedInitForNonAggregate); |
4930 | return; |
4931 | } |
4932 | |
4933 | // C++11 [dcl.init.list]p3, per DR1467 and DR2137: |
4934 | // - If T is an aggregate class and the initializer list has a single element |
4935 | // of type cv U, where U is T or a class derived from T, the object is |
4936 | // initialized from that element (by copy-initialization for |
4937 | // copy-list-initialization, or by direct-initialization for |
4938 | // direct-list-initialization). |
4939 | // - Otherwise, if T is a character array and the initializer list has a |
4940 | // single element that is an appropriately-typed string literal |
4941 | // (8.5.2 [dcl.init.string]), initialization is performed as described |
4942 | // in that section. |
4943 | // - Otherwise, if T is an aggregate, [...] (continue below). |
4944 | if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1 && |
4945 | !IsDesignatedInit) { |
4946 | if (DestType->isRecordType() && DestType->isAggregateType()) { |
4947 | QualType InitType = InitList->getInit(Init: 0)->getType(); |
4948 | if (S.Context.hasSameUnqualifiedType(T1: InitType, T2: DestType) || |
4949 | S.IsDerivedFrom(Loc: InitList->getBeginLoc(), Derived: InitType, Base: DestType)) { |
4950 | InitializationKind SubKind = |
4951 | Kind.getKind() == InitializationKind::IK_DirectList |
4952 | ? InitializationKind::CreateDirect(InitLoc: Kind.getLocation(), |
4953 | LParenLoc: InitList->getLBraceLoc(), |
4954 | RParenLoc: InitList->getRBraceLoc()) |
4955 | : Kind; |
4956 | Expr *InitListAsExpr = InitList; |
4957 | TryConstructorOrParenListInitialization( |
4958 | S, Entity, Kind: SubKind, Args: InitListAsExpr, DestType, Sequence, |
4959 | /*IsAggrListInit=*/true); |
4960 | return; |
4961 | } |
4962 | } |
4963 | if (const ArrayType *DestAT = S.Context.getAsArrayType(T: DestType)) { |
4964 | Expr *SubInit[1] = {InitList->getInit(Init: 0)}; |
4965 | |
4966 | // C++17 [dcl.struct.bind]p1: |
4967 | // ... If the assignment-expression in the initializer has array type A |
4968 | // and no ref-qualifier is present, e has type cv A and each element is |
4969 | // copy-initialized or direct-initialized from the corresponding element |
4970 | // of the assignment-expression as specified by the form of the |
4971 | // initializer. ... |
4972 | // |
4973 | // This is a special case not following list-initialization. |
4974 | if (isa<ConstantArrayType>(Val: DestAT) && |
4975 | Entity.getKind() == InitializedEntity::EK_Variable && |
4976 | isa<DecompositionDecl>(Val: Entity.getDecl())) { |
4977 | assert( |
4978 | S.Context.hasSameUnqualifiedType(SubInit[0]->getType(), DestType) && |
4979 | "Deduced to other type?" ); |
4980 | assert(Kind.getKind() == clang::InitializationKind::IK_DirectList && |
4981 | "List-initialize structured bindings but not " |
4982 | "direct-list-initialization?" ); |
4983 | TryArrayCopy(S, |
4984 | Kind: InitializationKind::CreateDirect(InitLoc: Kind.getLocation(), |
4985 | LParenLoc: InitList->getLBraceLoc(), |
4986 | RParenLoc: InitList->getRBraceLoc()), |
4987 | Entity, Initializer: SubInit[0], DestType, Sequence, |
4988 | TreatUnavailableAsInvalid); |
4989 | if (Sequence) |
4990 | Sequence.AddUnwrapInitListInitStep(Syntactic: InitList); |
4991 | return; |
4992 | } |
4993 | |
4994 | if (!isa<VariableArrayType>(Val: DestAT) && |
4995 | IsStringInit(Init: SubInit[0], AT: DestAT, Context&: S.Context) == SIF_None) { |
4996 | InitializationKind SubKind = |
4997 | Kind.getKind() == InitializationKind::IK_DirectList |
4998 | ? InitializationKind::CreateDirect(InitLoc: Kind.getLocation(), |
4999 | LParenLoc: InitList->getLBraceLoc(), |
5000 | RParenLoc: InitList->getRBraceLoc()) |
5001 | : Kind; |
5002 | Sequence.InitializeFrom(S, Entity, Kind: SubKind, Args: SubInit, |
5003 | /*TopLevelOfInitList*/ true, |
5004 | TreatUnavailableAsInvalid); |
5005 | |
5006 | // TryStringLiteralInitialization() (in InitializeFrom()) will fail if |
5007 | // the element is not an appropriately-typed string literal, in which |
5008 | // case we should proceed as in C++11 (below). |
5009 | if (Sequence) { |
5010 | Sequence.RewrapReferenceInitList(T: Entity.getType(), Syntactic: InitList); |
5011 | return; |
5012 | } |
5013 | } |
5014 | } |
5015 | } |
5016 | |
5017 | // C++11 [dcl.init.list]p3: |
5018 | // - If T is an aggregate, aggregate initialization is performed. |
5019 | if ((DestType->isRecordType() && !DestType->isAggregateType()) || |
5020 | (S.getLangOpts().CPlusPlus11 && |
5021 | S.isStdInitializerList(Ty: DestType, Element: nullptr) && !IsDesignatedInit)) { |
5022 | if (S.getLangOpts().CPlusPlus11) { |
5023 | // - Otherwise, if the initializer list has no elements and T is a |
5024 | // class type with a default constructor, the object is |
5025 | // value-initialized. |
5026 | if (InitList->getNumInits() == 0) { |
5027 | CXXRecordDecl *RD = DestType->getAsCXXRecordDecl(); |
5028 | if (S.LookupDefaultConstructor(Class: RD)) { |
5029 | TryValueInitialization(S, Entity, Kind, Sequence, InitList); |
5030 | return; |
5031 | } |
5032 | } |
5033 | |
5034 | // - Otherwise, if T is a specialization of std::initializer_list<E>, |
5035 | // an initializer_list object constructed [...] |
5036 | if (TryInitializerListConstruction(S, List: InitList, DestType, Sequence, |
5037 | TreatUnavailableAsInvalid)) |
5038 | return; |
5039 | |
5040 | // - Otherwise, if T is a class type, constructors are considered. |
5041 | Expr *InitListAsExpr = InitList; |
5042 | TryConstructorInitialization(S, Entity, Kind, Args: InitListAsExpr, DestType, |
5043 | DestArrayType: DestType, Sequence, /*InitListSyntax*/IsListInit: true); |
5044 | } else |
5045 | Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType); |
5046 | return; |
5047 | } |
5048 | |
5049 | if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() && |
5050 | InitList->getNumInits() == 1) { |
5051 | Expr *E = InitList->getInit(Init: 0); |
5052 | |
5053 | // - Otherwise, if T is an enumeration with a fixed underlying type, |
5054 | // the initializer-list has a single element v, and the initialization |
5055 | // is direct-list-initialization, the object is initialized with the |
5056 | // value T(v); if a narrowing conversion is required to convert v to |
5057 | // the underlying type of T, the program is ill-formed. |
5058 | auto *ET = DestType->getAs<EnumType>(); |
5059 | if (S.getLangOpts().CPlusPlus17 && |
5060 | Kind.getKind() == InitializationKind::IK_DirectList && |
5061 | ET && ET->getDecl()->isFixed() && |
5062 | !S.Context.hasSameUnqualifiedType(T1: E->getType(), T2: DestType) && |
5063 | (E->getType()->isIntegralOrUnscopedEnumerationType() || |
5064 | E->getType()->isFloatingType())) { |
5065 | // There are two ways that T(v) can work when T is an enumeration type. |
5066 | // If there is either an implicit conversion sequence from v to T or |
5067 | // a conversion function that can convert from v to T, then we use that. |
5068 | // Otherwise, if v is of integral, unscoped enumeration, or floating-point |
5069 | // type, it is converted to the enumeration type via its underlying type. |
5070 | // There is no overlap possible between these two cases (except when the |
5071 | // source value is already of the destination type), and the first |
5072 | // case is handled by the general case for single-element lists below. |
5073 | ImplicitConversionSequence ICS; |
5074 | ICS.setStandard(); |
5075 | ICS.Standard.setAsIdentityConversion(); |
5076 | if (!E->isPRValue()) |
5077 | ICS.Standard.First = ICK_Lvalue_To_Rvalue; |
5078 | // If E is of a floating-point type, then the conversion is ill-formed |
5079 | // due to narrowing, but go through the motions in order to produce the |
5080 | // right diagnostic. |
5081 | ICS.Standard.Second = E->getType()->isFloatingType() |
5082 | ? ICK_Floating_Integral |
5083 | : ICK_Integral_Conversion; |
5084 | ICS.Standard.setFromType(E->getType()); |
5085 | ICS.Standard.setToType(Idx: 0, T: E->getType()); |
5086 | ICS.Standard.setToType(Idx: 1, T: DestType); |
5087 | ICS.Standard.setToType(Idx: 2, T: DestType); |
5088 | Sequence.AddConversionSequenceStep(ICS, T: ICS.Standard.getToType(Idx: 2), |
5089 | /*TopLevelOfInitList*/true); |
5090 | Sequence.RewrapReferenceInitList(T: Entity.getType(), Syntactic: InitList); |
5091 | return; |
5092 | } |
5093 | |
5094 | // - Otherwise, if the initializer list has a single element of type E |
5095 | // [...references are handled above...], the object or reference is |
5096 | // initialized from that element (by copy-initialization for |
5097 | // copy-list-initialization, or by direct-initialization for |
5098 | // direct-list-initialization); if a narrowing conversion is required |
5099 | // to convert the element to T, the program is ill-formed. |
5100 | // |
5101 | // Per core-24034, this is direct-initialization if we were performing |
5102 | // direct-list-initialization and copy-initialization otherwise. |
5103 | // We can't use InitListChecker for this, because it always performs |
5104 | // copy-initialization. This only matters if we might use an 'explicit' |
5105 | // conversion operator, or for the special case conversion of nullptr_t to |
5106 | // bool, so we only need to handle those cases. |
5107 | // |
5108 | // FIXME: Why not do this in all cases? |
5109 | Expr *Init = InitList->getInit(Init: 0); |
5110 | if (Init->getType()->isRecordType() || |
5111 | (Init->getType()->isNullPtrType() && DestType->isBooleanType())) { |
5112 | InitializationKind SubKind = |
5113 | Kind.getKind() == InitializationKind::IK_DirectList |
5114 | ? InitializationKind::CreateDirect(InitLoc: Kind.getLocation(), |
5115 | LParenLoc: InitList->getLBraceLoc(), |
5116 | RParenLoc: InitList->getRBraceLoc()) |
5117 | : Kind; |
5118 | Expr *SubInit[1] = { Init }; |
5119 | Sequence.InitializeFrom(S, Entity, Kind: SubKind, Args: SubInit, |
5120 | /*TopLevelOfInitList*/true, |
5121 | TreatUnavailableAsInvalid); |
5122 | if (Sequence) |
5123 | Sequence.RewrapReferenceInitList(T: Entity.getType(), Syntactic: InitList); |
5124 | return; |
5125 | } |
5126 | } |
5127 | |
5128 | InitListChecker CheckInitList(S, Entity, InitList, |
5129 | DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid); |
5130 | if (CheckInitList.HadError()) { |
5131 | Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed); |
5132 | return; |
5133 | } |
5134 | |
5135 | // Add the list initialization step with the built init list. |
5136 | Sequence.AddListInitializationStep(T: DestType); |
5137 | } |
5138 | |
5139 | /// Try a reference initialization that involves calling a conversion |
5140 | /// function. |
5141 | static OverloadingResult TryRefInitWithConversionFunction( |
5142 | Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, |
5143 | Expr *Initializer, bool AllowRValues, bool IsLValueRef, |
5144 | InitializationSequence &Sequence) { |
5145 | QualType DestType = Entity.getType(); |
5146 | QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType(); |
5147 | QualType T1 = cv1T1.getUnqualifiedType(); |
5148 | QualType cv2T2 = Initializer->getType(); |
5149 | QualType T2 = cv2T2.getUnqualifiedType(); |
5150 | |
5151 | assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) && |
5152 | "Must have incompatible references when binding via conversion" ); |
5153 | |
5154 | // Build the candidate set directly in the initialization sequence |
5155 | // structure, so that it will persist if we fail. |
5156 | OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); |
5157 | CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion); |
5158 | |
5159 | // Determine whether we are allowed to call explicit conversion operators. |
5160 | // Note that none of [over.match.copy], [over.match.conv], nor |
5161 | // [over.match.ref] permit an explicit constructor to be chosen when |
5162 | // initializing a reference, not even for direct-initialization. |
5163 | bool AllowExplicitCtors = false; |
5164 | bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding(); |
5165 | |
5166 | const RecordType *T1RecordType = nullptr; |
5167 | if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) && |
5168 | S.isCompleteType(Loc: Kind.getLocation(), T: T1)) { |
5169 | // The type we're converting to is a class type. Enumerate its constructors |
5170 | // to see if there is a suitable conversion. |
5171 | CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(Val: T1RecordType->getDecl()); |
5172 | |
5173 | for (NamedDecl *D : S.LookupConstructors(Class: T1RecordDecl)) { |
5174 | auto Info = getConstructorInfo(ND: D); |
5175 | if (!Info.Constructor) |
5176 | continue; |
5177 | |
5178 | if (!Info.Constructor->isInvalidDecl() && |
5179 | Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) { |
5180 | if (Info.ConstructorTmpl) |
5181 | S.AddTemplateOverloadCandidate( |
5182 | FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl, |
5183 | /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: Initializer, CandidateSet, |
5184 | /*SuppressUserConversions=*/true, |
5185 | /*PartialOverloading*/ false, AllowExplicit: AllowExplicitCtors); |
5186 | else |
5187 | S.AddOverloadCandidate( |
5188 | Function: Info.Constructor, FoundDecl: Info.FoundDecl, Args: Initializer, CandidateSet, |
5189 | /*SuppressUserConversions=*/true, |
5190 | /*PartialOverloading*/ false, AllowExplicit: AllowExplicitCtors); |
5191 | } |
5192 | } |
5193 | } |
5194 | if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl()) |
5195 | return OR_No_Viable_Function; |
5196 | |
5197 | const RecordType *T2RecordType = nullptr; |
5198 | if ((T2RecordType = T2->getAs<RecordType>()) && |
5199 | S.isCompleteType(Loc: Kind.getLocation(), T: T2)) { |
5200 | // The type we're converting from is a class type, enumerate its conversion |
5201 | // functions. |
5202 | CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(Val: T2RecordType->getDecl()); |
5203 | |
5204 | const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); |
5205 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { |
5206 | NamedDecl *D = *I; |
5207 | CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: D->getDeclContext()); |
5208 | if (isa<UsingShadowDecl>(Val: D)) |
5209 | D = cast<UsingShadowDecl>(Val: D)->getTargetDecl(); |
5210 | |
5211 | FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D); |
5212 | CXXConversionDecl *Conv; |
5213 | if (ConvTemplate) |
5214 | Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl()); |
5215 | else |
5216 | Conv = cast<CXXConversionDecl>(Val: D); |
5217 | |
5218 | // If the conversion function doesn't return a reference type, |
5219 | // it can't be considered for this conversion unless we're allowed to |
5220 | // consider rvalues. |
5221 | // FIXME: Do we need to make sure that we only consider conversion |
5222 | // candidates with reference-compatible results? That might be needed to |
5223 | // break recursion. |
5224 | if ((AllowRValues || |
5225 | Conv->getConversionType()->isLValueReferenceType())) { |
5226 | if (ConvTemplate) |
5227 | S.AddTemplateConversionCandidate( |
5228 | FunctionTemplate: ConvTemplate, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer, ToType: DestType, |
5229 | CandidateSet, |
5230 | /*AllowObjCConversionOnExplicit=*/false, AllowExplicit: AllowExplicitConvs); |
5231 | else |
5232 | S.AddConversionCandidate( |
5233 | Conversion: Conv, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer, ToType: DestType, CandidateSet, |
5234 | /*AllowObjCConversionOnExplicit=*/false, AllowExplicit: AllowExplicitConvs); |
5235 | } |
5236 | } |
5237 | } |
5238 | if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl()) |
5239 | return OR_No_Viable_Function; |
5240 | |
5241 | SourceLocation DeclLoc = Initializer->getBeginLoc(); |
5242 | |
5243 | // Perform overload resolution. If it fails, return the failed result. |
5244 | OverloadCandidateSet::iterator Best; |
5245 | if (OverloadingResult Result |
5246 | = CandidateSet.BestViableFunction(S, Loc: DeclLoc, Best)) |
5247 | return Result; |
5248 | |
5249 | FunctionDecl *Function = Best->Function; |
5250 | // This is the overload that will be used for this initialization step if we |
5251 | // use this initialization. Mark it as referenced. |
5252 | Function->setReferenced(); |
5253 | |
5254 | // Compute the returned type and value kind of the conversion. |
5255 | QualType cv3T3; |
5256 | if (isa<CXXConversionDecl>(Val: Function)) |
5257 | cv3T3 = Function->getReturnType(); |
5258 | else |
5259 | cv3T3 = T1; |
5260 | |
5261 | ExprValueKind VK = VK_PRValue; |
5262 | if (cv3T3->isLValueReferenceType()) |
5263 | VK = VK_LValue; |
5264 | else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>()) |
5265 | VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue; |
5266 | cv3T3 = cv3T3.getNonLValueExprType(Context: S.Context); |
5267 | |
5268 | // Add the user-defined conversion step. |
5269 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
5270 | Sequence.AddUserConversionStep(Function, FoundDecl: Best->FoundDecl, T: cv3T3, |
5271 | HadMultipleCandidates); |
5272 | |
5273 | // Determine whether we'll need to perform derived-to-base adjustments or |
5274 | // other conversions. |
5275 | Sema::ReferenceConversions RefConv; |
5276 | Sema::ReferenceCompareResult NewRefRelationship = |
5277 | S.CompareReferenceRelationship(Loc: DeclLoc, T1, T2: cv3T3, Conv: &RefConv); |
5278 | |
5279 | // Add the final conversion sequence, if necessary. |
5280 | if (NewRefRelationship == Sema::Ref_Incompatible) { |
5281 | assert(Best->HasFinalConversion && !isa<CXXConstructorDecl>(Function) && |
5282 | "should not have conversion after constructor" ); |
5283 | |
5284 | ImplicitConversionSequence ICS; |
5285 | ICS.setStandard(); |
5286 | ICS.Standard = Best->FinalConversion; |
5287 | Sequence.AddConversionSequenceStep(ICS, T: ICS.Standard.getToType(Idx: 2)); |
5288 | |
5289 | // Every implicit conversion results in a prvalue, except for a glvalue |
5290 | // derived-to-base conversion, which we handle below. |
5291 | cv3T3 = ICS.Standard.getToType(Idx: 2); |
5292 | VK = VK_PRValue; |
5293 | } |
5294 | |
5295 | // If the converted initializer is a prvalue, its type T4 is adjusted to |
5296 | // type "cv1 T4" and the temporary materialization conversion is applied. |
5297 | // |
5298 | // We adjust the cv-qualifications to match the reference regardless of |
5299 | // whether we have a prvalue so that the AST records the change. In this |
5300 | // case, T4 is "cv3 T3". |
5301 | QualType cv1T4 = S.Context.getQualifiedType(T: cv3T3, Qs: cv1T1.getQualifiers()); |
5302 | if (cv1T4.getQualifiers() != cv3T3.getQualifiers()) |
5303 | Sequence.AddQualificationConversionStep(Ty: cv1T4, VK); |
5304 | Sequence.AddReferenceBindingStep(T: cv1T4, BindingTemporary: VK == VK_PRValue); |
5305 | VK = IsLValueRef ? VK_LValue : VK_XValue; |
5306 | |
5307 | if (RefConv & Sema::ReferenceConversions::DerivedToBase) |
5308 | Sequence.AddDerivedToBaseCastStep(BaseType: cv1T1, VK); |
5309 | else if (RefConv & Sema::ReferenceConversions::ObjC) |
5310 | Sequence.AddObjCObjectConversionStep(T: cv1T1); |
5311 | else if (RefConv & Sema::ReferenceConversions::Function) |
5312 | Sequence.AddFunctionReferenceConversionStep(Ty: cv1T1); |
5313 | else if (RefConv & Sema::ReferenceConversions::Qualification) { |
5314 | if (!S.Context.hasSameType(T1: cv1T4, T2: cv1T1)) |
5315 | Sequence.AddQualificationConversionStep(Ty: cv1T1, VK); |
5316 | } |
5317 | |
5318 | return OR_Success; |
5319 | } |
5320 | |
5321 | static void CheckCXX98CompatAccessibleCopy(Sema &S, |
5322 | const InitializedEntity &Entity, |
5323 | Expr *CurInitExpr); |
5324 | |
5325 | /// Attempt reference initialization (C++0x [dcl.init.ref]) |
5326 | static void TryReferenceInitialization(Sema &S, const InitializedEntity &Entity, |
5327 | const InitializationKind &Kind, |
5328 | Expr *Initializer, |
5329 | InitializationSequence &Sequence, |
5330 | bool TopLevelOfInitList) { |
5331 | QualType DestType = Entity.getType(); |
5332 | QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType(); |
5333 | Qualifiers T1Quals; |
5334 | QualType T1 = S.Context.getUnqualifiedArrayType(T: cv1T1, Quals&: T1Quals); |
5335 | QualType cv2T2 = S.getCompletedType(E: Initializer); |
5336 | Qualifiers T2Quals; |
5337 | QualType T2 = S.Context.getUnqualifiedArrayType(T: cv2T2, Quals&: T2Quals); |
5338 | |
5339 | // If the initializer is the address of an overloaded function, try |
5340 | // to resolve the overloaded function. If all goes well, T2 is the |
5341 | // type of the resulting function. |
5342 | if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, SourceType&: cv2T2, UnqualifiedSourceType&: T2, |
5343 | UnqualifiedTargetType: T1, Sequence)) |
5344 | return; |
5345 | |
5346 | // Delegate everything else to a subfunction. |
5347 | TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1, |
5348 | T1Quals, cv2T2, T2, T2Quals, Sequence, |
5349 | TopLevelOfInitList); |
5350 | } |
5351 | |
5352 | /// Determine whether an expression is a non-referenceable glvalue (one to |
5353 | /// which a reference can never bind). Attempting to bind a reference to |
5354 | /// such a glvalue will always create a temporary. |
5355 | static bool isNonReferenceableGLValue(Expr *E) { |
5356 | return E->refersToBitField() || E->refersToVectorElement() || |
5357 | E->refersToMatrixElement(); |
5358 | } |
5359 | |
5360 | /// Reference initialization without resolving overloaded functions. |
5361 | /// |
5362 | /// We also can get here in C if we call a builtin which is declared as |
5363 | /// a function with a parameter of reference type (such as __builtin_va_end()). |
5364 | static void TryReferenceInitializationCore(Sema &S, |
5365 | const InitializedEntity &Entity, |
5366 | const InitializationKind &Kind, |
5367 | Expr *Initializer, |
5368 | QualType cv1T1, QualType T1, |
5369 | Qualifiers T1Quals, |
5370 | QualType cv2T2, QualType T2, |
5371 | Qualifiers T2Quals, |
5372 | InitializationSequence &Sequence, |
5373 | bool TopLevelOfInitList) { |
5374 | QualType DestType = Entity.getType(); |
5375 | SourceLocation DeclLoc = Initializer->getBeginLoc(); |
5376 | |
5377 | // Compute some basic properties of the types and the initializer. |
5378 | bool isLValueRef = DestType->isLValueReferenceType(); |
5379 | bool isRValueRef = !isLValueRef; |
5380 | Expr::Classification InitCategory = Initializer->Classify(Ctx&: S.Context); |
5381 | |
5382 | Sema::ReferenceConversions RefConv; |
5383 | Sema::ReferenceCompareResult RefRelationship = |
5384 | S.CompareReferenceRelationship(Loc: DeclLoc, T1: cv1T1, T2: cv2T2, Conv: &RefConv); |
5385 | |
5386 | // C++0x [dcl.init.ref]p5: |
5387 | // A reference to type "cv1 T1" is initialized by an expression of type |
5388 | // "cv2 T2" as follows: |
5389 | // |
5390 | // - If the reference is an lvalue reference and the initializer |
5391 | // expression |
5392 | // Note the analogous bullet points for rvalue refs to functions. Because |
5393 | // there are no function rvalues in C++, rvalue refs to functions are treated |
5394 | // like lvalue refs. |
5395 | OverloadingResult ConvOvlResult = OR_Success; |
5396 | bool T1Function = T1->isFunctionType(); |
5397 | if (isLValueRef || T1Function) { |
5398 | if (InitCategory.isLValue() && !isNonReferenceableGLValue(E: Initializer) && |
5399 | (RefRelationship == Sema::Ref_Compatible || |
5400 | (Kind.isCStyleOrFunctionalCast() && |
5401 | RefRelationship == Sema::Ref_Related))) { |
5402 | // - is an lvalue (but is not a bit-field), and "cv1 T1" is |
5403 | // reference-compatible with "cv2 T2," or |
5404 | if (RefConv & (Sema::ReferenceConversions::DerivedToBase | |
5405 | Sema::ReferenceConversions::ObjC)) { |
5406 | // If we're converting the pointee, add any qualifiers first; |
5407 | // these qualifiers must all be top-level, so just convert to "cv1 T2". |
5408 | if (RefConv & (Sema::ReferenceConversions::Qualification)) |
5409 | Sequence.AddQualificationConversionStep( |
5410 | Ty: S.Context.getQualifiedType(T: T2, Qs: T1Quals), |
5411 | VK: Initializer->getValueKind()); |
5412 | if (RefConv & Sema::ReferenceConversions::DerivedToBase) |
5413 | Sequence.AddDerivedToBaseCastStep(BaseType: cv1T1, VK: VK_LValue); |
5414 | else |
5415 | Sequence.AddObjCObjectConversionStep(T: cv1T1); |
5416 | } else if (RefConv & Sema::ReferenceConversions::Qualification) { |
5417 | // Perform a (possibly multi-level) qualification conversion. |
5418 | Sequence.AddQualificationConversionStep(Ty: cv1T1, |
5419 | VK: Initializer->getValueKind()); |
5420 | } else if (RefConv & Sema::ReferenceConversions::Function) { |
5421 | Sequence.AddFunctionReferenceConversionStep(Ty: cv1T1); |
5422 | } |
5423 | |
5424 | // We only create a temporary here when binding a reference to a |
5425 | // bit-field or vector element. Those cases are't supposed to be |
5426 | // handled by this bullet, but the outcome is the same either way. |
5427 | Sequence.AddReferenceBindingStep(T: cv1T1, BindingTemporary: false); |
5428 | return; |
5429 | } |
5430 | |
5431 | // - has a class type (i.e., T2 is a class type), where T1 is not |
5432 | // reference-related to T2, and can be implicitly converted to an |
5433 | // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible |
5434 | // with "cv3 T3" (this conversion is selected by enumerating the |
5435 | // applicable conversion functions (13.3.1.6) and choosing the best |
5436 | // one through overload resolution (13.3)), |
5437 | // If we have an rvalue ref to function type here, the rhs must be |
5438 | // an rvalue. DR1287 removed the "implicitly" here. |
5439 | if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() && |
5440 | (isLValueRef || InitCategory.isRValue())) { |
5441 | if (S.getLangOpts().CPlusPlus) { |
5442 | // Try conversion functions only for C++. |
5443 | ConvOvlResult = TryRefInitWithConversionFunction( |
5444 | S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef, |
5445 | /*IsLValueRef*/ isLValueRef, Sequence); |
5446 | if (ConvOvlResult == OR_Success) |
5447 | return; |
5448 | if (ConvOvlResult != OR_No_Viable_Function) |
5449 | Sequence.SetOverloadFailure( |
5450 | Failure: InitializationSequence::FK_ReferenceInitOverloadFailed, |
5451 | Result: ConvOvlResult); |
5452 | } else { |
5453 | ConvOvlResult = OR_No_Viable_Function; |
5454 | } |
5455 | } |
5456 | } |
5457 | |
5458 | // - Otherwise, the reference shall be an lvalue reference to a |
5459 | // non-volatile const type (i.e., cv1 shall be const), or the reference |
5460 | // shall be an rvalue reference. |
5461 | // For address spaces, we interpret this to mean that an addr space |
5462 | // of a reference "cv1 T1" is a superset of addr space of "cv2 T2". |
5463 | if (isLValueRef && |
5464 | !(T1Quals.hasConst() && !T1Quals.hasVolatile() && |
5465 | T1Quals.isAddressSpaceSupersetOf(other: T2Quals, Ctx: S.getASTContext()))) { |
5466 | if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) |
5467 | Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); |
5468 | else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) |
5469 | Sequence.SetOverloadFailure( |
5470 | Failure: InitializationSequence::FK_ReferenceInitOverloadFailed, |
5471 | Result: ConvOvlResult); |
5472 | else if (!InitCategory.isLValue()) |
5473 | Sequence.SetFailed( |
5474 | T1Quals.isAddressSpaceSupersetOf(other: T2Quals, Ctx: S.getASTContext()) |
5475 | ? InitializationSequence:: |
5476 | FK_NonConstLValueReferenceBindingToTemporary |
5477 | : InitializationSequence::FK_ReferenceInitDropsQualifiers); |
5478 | else { |
5479 | InitializationSequence::FailureKind FK; |
5480 | switch (RefRelationship) { |
5481 | case Sema::Ref_Compatible: |
5482 | if (Initializer->refersToBitField()) |
5483 | FK = InitializationSequence:: |
5484 | FK_NonConstLValueReferenceBindingToBitfield; |
5485 | else if (Initializer->refersToVectorElement()) |
5486 | FK = InitializationSequence:: |
5487 | FK_NonConstLValueReferenceBindingToVectorElement; |
5488 | else if (Initializer->refersToMatrixElement()) |
5489 | FK = InitializationSequence:: |
5490 | FK_NonConstLValueReferenceBindingToMatrixElement; |
5491 | else |
5492 | llvm_unreachable("unexpected kind of compatible initializer" ); |
5493 | break; |
5494 | case Sema::Ref_Related: |
5495 | FK = InitializationSequence::FK_ReferenceInitDropsQualifiers; |
5496 | break; |
5497 | case Sema::Ref_Incompatible: |
5498 | FK = InitializationSequence:: |
5499 | FK_NonConstLValueReferenceBindingToUnrelated; |
5500 | break; |
5501 | } |
5502 | Sequence.SetFailed(FK); |
5503 | } |
5504 | return; |
5505 | } |
5506 | |
5507 | // - If the initializer expression |
5508 | // - is an |
5509 | // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or |
5510 | // [1z] rvalue (but not a bit-field) or |
5511 | // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2" |
5512 | // |
5513 | // Note: functions are handled above and below rather than here... |
5514 | if (!T1Function && |
5515 | (RefRelationship == Sema::Ref_Compatible || |
5516 | (Kind.isCStyleOrFunctionalCast() && |
5517 | RefRelationship == Sema::Ref_Related)) && |
5518 | ((InitCategory.isXValue() && !isNonReferenceableGLValue(E: Initializer)) || |
5519 | (InitCategory.isPRValue() && |
5520 | (S.getLangOpts().CPlusPlus17 || T2->isRecordType() || |
5521 | T2->isArrayType())))) { |
5522 | ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_PRValue; |
5523 | if (InitCategory.isPRValue() && T2->isRecordType()) { |
5524 | // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the |
5525 | // compiler the freedom to perform a copy here or bind to the |
5526 | // object, while C++0x requires that we bind directly to the |
5527 | // object. Hence, we always bind to the object without making an |
5528 | // extra copy. However, in C++03 requires that we check for the |
5529 | // presence of a suitable copy constructor: |
5530 | // |
5531 | // The constructor that would be used to make the copy shall |
5532 | // be callable whether or not the copy is actually done. |
5533 | if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt) |
5534 | Sequence.AddExtraneousCopyToTemporary(T: cv2T2); |
5535 | else if (S.getLangOpts().CPlusPlus11) |
5536 | CheckCXX98CompatAccessibleCopy(S, Entity, CurInitExpr: Initializer); |
5537 | } |
5538 | |
5539 | // C++1z [dcl.init.ref]/5.2.1.2: |
5540 | // If the converted initializer is a prvalue, its type T4 is adjusted |
5541 | // to type "cv1 T4" and the temporary materialization conversion is |
5542 | // applied. |
5543 | // Postpone address space conversions to after the temporary materialization |
5544 | // conversion to allow creating temporaries in the alloca address space. |
5545 | auto T1QualsIgnoreAS = T1Quals; |
5546 | auto T2QualsIgnoreAS = T2Quals; |
5547 | if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) { |
5548 | T1QualsIgnoreAS.removeAddressSpace(); |
5549 | T2QualsIgnoreAS.removeAddressSpace(); |
5550 | } |
5551 | QualType cv1T4 = S.Context.getQualifiedType(T: cv2T2, Qs: T1QualsIgnoreAS); |
5552 | if (T1QualsIgnoreAS != T2QualsIgnoreAS) |
5553 | Sequence.AddQualificationConversionStep(Ty: cv1T4, VK: ValueKind); |
5554 | Sequence.AddReferenceBindingStep(T: cv1T4, BindingTemporary: ValueKind == VK_PRValue); |
5555 | ValueKind = isLValueRef ? VK_LValue : VK_XValue; |
5556 | // Add addr space conversion if required. |
5557 | if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) { |
5558 | auto T4Quals = cv1T4.getQualifiers(); |
5559 | T4Quals.addAddressSpace(space: T1Quals.getAddressSpace()); |
5560 | QualType cv1T4WithAS = S.Context.getQualifiedType(T: T2, Qs: T4Quals); |
5561 | Sequence.AddQualificationConversionStep(Ty: cv1T4WithAS, VK: ValueKind); |
5562 | cv1T4 = cv1T4WithAS; |
5563 | } |
5564 | |
5565 | // In any case, the reference is bound to the resulting glvalue (or to |
5566 | // an appropriate base class subobject). |
5567 | if (RefConv & Sema::ReferenceConversions::DerivedToBase) |
5568 | Sequence.AddDerivedToBaseCastStep(BaseType: cv1T1, VK: ValueKind); |
5569 | else if (RefConv & Sema::ReferenceConversions::ObjC) |
5570 | Sequence.AddObjCObjectConversionStep(T: cv1T1); |
5571 | else if (RefConv & Sema::ReferenceConversions::Qualification) { |
5572 | if (!S.Context.hasSameType(T1: cv1T4, T2: cv1T1)) |
5573 | Sequence.AddQualificationConversionStep(Ty: cv1T1, VK: ValueKind); |
5574 | } |
5575 | return; |
5576 | } |
5577 | |
5578 | // - has a class type (i.e., T2 is a class type), where T1 is not |
5579 | // reference-related to T2, and can be implicitly converted to an |
5580 | // xvalue, class prvalue, or function lvalue of type "cv3 T3", |
5581 | // where "cv1 T1" is reference-compatible with "cv3 T3", |
5582 | // |
5583 | // DR1287 removes the "implicitly" here. |
5584 | if (T2->isRecordType()) { |
5585 | if (RefRelationship == Sema::Ref_Incompatible) { |
5586 | ConvOvlResult = TryRefInitWithConversionFunction( |
5587 | S, Entity, Kind, Initializer, /*AllowRValues*/ true, |
5588 | /*IsLValueRef*/ isLValueRef, Sequence); |
5589 | if (ConvOvlResult) |
5590 | Sequence.SetOverloadFailure( |
5591 | Failure: InitializationSequence::FK_ReferenceInitOverloadFailed, |
5592 | Result: ConvOvlResult); |
5593 | |
5594 | return; |
5595 | } |
5596 | |
5597 | if (RefRelationship == Sema::Ref_Compatible && |
5598 | isRValueRef && InitCategory.isLValue()) { |
5599 | Sequence.SetFailed( |
5600 | InitializationSequence::FK_RValueReferenceBindingToLValue); |
5601 | return; |
5602 | } |
5603 | |
5604 | Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); |
5605 | return; |
5606 | } |
5607 | |
5608 | // - Otherwise, a temporary of type "cv1 T1" is created and initialized |
5609 | // from the initializer expression using the rules for a non-reference |
5610 | // copy-initialization (8.5). The reference is then bound to the |
5611 | // temporary. [...] |
5612 | |
5613 | // Ignore address space of reference type at this point and perform address |
5614 | // space conversion after the reference binding step. |
5615 | QualType cv1T1IgnoreAS = |
5616 | T1Quals.hasAddressSpace() |
5617 | ? S.Context.getQualifiedType(T: T1, Qs: T1Quals.withoutAddressSpace()) |
5618 | : cv1T1; |
5619 | |
5620 | InitializedEntity TempEntity = |
5621 | InitializedEntity::InitializeTemporary(Type: cv1T1IgnoreAS); |
5622 | |
5623 | // FIXME: Why do we use an implicit conversion here rather than trying |
5624 | // copy-initialization? |
5625 | ImplicitConversionSequence ICS |
5626 | = S.TryImplicitConversion(From: Initializer, ToType: TempEntity.getType(), |
5627 | /*SuppressUserConversions=*/false, |
5628 | AllowExplicit: Sema::AllowedExplicit::None, |
5629 | /*FIXME:InOverloadResolution=*/InOverloadResolution: false, |
5630 | /*CStyle=*/Kind.isCStyleOrFunctionalCast(), |
5631 | /*AllowObjCWritebackConversion=*/false); |
5632 | |
5633 | if (ICS.isBad()) { |
5634 | // FIXME: Use the conversion function set stored in ICS to turn |
5635 | // this into an overloading ambiguity diagnostic. However, we need |
5636 | // to keep that set as an OverloadCandidateSet rather than as some |
5637 | // other kind of set. |
5638 | if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) |
5639 | Sequence.SetOverloadFailure( |
5640 | Failure: InitializationSequence::FK_ReferenceInitOverloadFailed, |
5641 | Result: ConvOvlResult); |
5642 | else if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) |
5643 | Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); |
5644 | else |
5645 | Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed); |
5646 | return; |
5647 | } else { |
5648 | Sequence.AddConversionSequenceStep(ICS, T: TempEntity.getType(), |
5649 | TopLevelOfInitList); |
5650 | } |
5651 | |
5652 | // [...] If T1 is reference-related to T2, cv1 must be the |
5653 | // same cv-qualification as, or greater cv-qualification |
5654 | // than, cv2; otherwise, the program is ill-formed. |
5655 | unsigned T1CVRQuals = T1Quals.getCVRQualifiers(); |
5656 | unsigned T2CVRQuals = T2Quals.getCVRQualifiers(); |
5657 | if (RefRelationship == Sema::Ref_Related && |
5658 | ((T1CVRQuals | T2CVRQuals) != T1CVRQuals || |
5659 | !T1Quals.isAddressSpaceSupersetOf(other: T2Quals, Ctx: S.getASTContext()))) { |
5660 | Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); |
5661 | return; |
5662 | } |
5663 | |
5664 | // [...] If T1 is reference-related to T2 and the reference is an rvalue |
5665 | // reference, the initializer expression shall not be an lvalue. |
5666 | if (RefRelationship >= Sema::Ref_Related && !isLValueRef && |
5667 | InitCategory.isLValue()) { |
5668 | Sequence.SetFailed( |
5669 | InitializationSequence::FK_RValueReferenceBindingToLValue); |
5670 | return; |
5671 | } |
5672 | |
5673 | Sequence.AddReferenceBindingStep(T: cv1T1IgnoreAS, /*BindingTemporary=*/true); |
5674 | |
5675 | if (T1Quals.hasAddressSpace()) { |
5676 | if (!Qualifiers::isAddressSpaceSupersetOf( |
5677 | A: T1Quals.getAddressSpace(), B: LangAS::Default, Ctx: S.getASTContext())) { |
5678 | Sequence.SetFailed( |
5679 | InitializationSequence::FK_ReferenceAddrspaceMismatchTemporary); |
5680 | return; |
5681 | } |
5682 | Sequence.AddQualificationConversionStep(Ty: cv1T1, VK: isLValueRef ? VK_LValue |
5683 | : VK_XValue); |
5684 | } |
5685 | } |
5686 | |
5687 | /// Attempt character array initialization from a string literal |
5688 | /// (C++ [dcl.init.string], C99 6.7.8). |
5689 | static void TryStringLiteralInitialization(Sema &S, |
5690 | const InitializedEntity &Entity, |
5691 | const InitializationKind &Kind, |
5692 | Expr *Initializer, |
5693 | InitializationSequence &Sequence) { |
5694 | Sequence.AddStringInitStep(T: Entity.getType()); |
5695 | } |
5696 | |
5697 | /// Attempt value initialization (C++ [dcl.init]p7). |
5698 | static void TryValueInitialization(Sema &S, |
5699 | const InitializedEntity &Entity, |
5700 | const InitializationKind &Kind, |
5701 | InitializationSequence &Sequence, |
5702 | InitListExpr *InitList) { |
5703 | assert((!InitList || InitList->getNumInits() == 0) && |
5704 | "Shouldn't use value-init for non-empty init lists" ); |
5705 | |
5706 | // C++98 [dcl.init]p5, C++11 [dcl.init]p7: |
5707 | // |
5708 | // To value-initialize an object of type T means: |
5709 | QualType T = Entity.getType(); |
5710 | assert(!T->isVoidType() && "Cannot value-init void" ); |
5711 | |
5712 | // -- if T is an array type, then each element is value-initialized; |
5713 | T = S.Context.getBaseElementType(QT: T); |
5714 | |
5715 | if (const RecordType *RT = T->getAs<RecordType>()) { |
5716 | if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Val: RT->getDecl())) { |
5717 | bool NeedZeroInitialization = true; |
5718 | // C++98: |
5719 | // -- if T is a class type (clause 9) with a user-declared constructor |
5720 | // (12.1), then the default constructor for T is called (and the |
5721 | // initialization is ill-formed if T has no accessible default |
5722 | // constructor); |
5723 | // C++11: |
5724 | // -- if T is a class type (clause 9) with either no default constructor |
5725 | // (12.1 [class.ctor]) or a default constructor that is user-provided |
5726 | // or deleted, then the object is default-initialized; |
5727 | // |
5728 | // Note that the C++11 rule is the same as the C++98 rule if there are no |
5729 | // defaulted or deleted constructors, so we just use it unconditionally. |
5730 | CXXConstructorDecl *CD = S.LookupDefaultConstructor(Class: ClassDecl); |
5731 | if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted()) |
5732 | NeedZeroInitialization = false; |
5733 | |
5734 | // -- if T is a (possibly cv-qualified) non-union class type without a |
5735 | // user-provided or deleted default constructor, then the object is |
5736 | // zero-initialized and, if T has a non-trivial default constructor, |
5737 | // default-initialized; |
5738 | // The 'non-union' here was removed by DR1502. The 'non-trivial default |
5739 | // constructor' part was removed by DR1507. |
5740 | if (NeedZeroInitialization) |
5741 | Sequence.AddZeroInitializationStep(T: Entity.getType()); |
5742 | |
5743 | // C++03: |
5744 | // -- if T is a non-union class type without a user-declared constructor, |
5745 | // then every non-static data member and base class component of T is |
5746 | // value-initialized; |
5747 | // [...] A program that calls for [...] value-initialization of an |
5748 | // entity of reference type is ill-formed. |
5749 | // |
5750 | // C++11 doesn't need this handling, because value-initialization does not |
5751 | // occur recursively there, and the implicit default constructor is |
5752 | // defined as deleted in the problematic cases. |
5753 | if (!S.getLangOpts().CPlusPlus11 && |
5754 | ClassDecl->hasUninitializedReferenceMember()) { |
5755 | Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference); |
5756 | return; |
5757 | } |
5758 | |
5759 | // If this is list-value-initialization, pass the empty init list on when |
5760 | // building the constructor call. This affects the semantics of a few |
5761 | // things (such as whether an explicit default constructor can be called). |
5762 | Expr *InitListAsExpr = InitList; |
5763 | MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0); |
5764 | bool InitListSyntax = InitList; |
5765 | |
5766 | // FIXME: Instead of creating a CXXConstructExpr of array type here, |
5767 | // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr. |
5768 | return TryConstructorInitialization( |
5769 | S, Entity, Kind, Args, DestType: T, DestArrayType: Entity.getType(), Sequence, IsListInit: InitListSyntax); |
5770 | } |
5771 | } |
5772 | |
5773 | Sequence.AddZeroInitializationStep(T: Entity.getType()); |
5774 | } |
5775 | |
5776 | /// Attempt default initialization (C++ [dcl.init]p6). |
5777 | static void TryDefaultInitialization(Sema &S, |
5778 | const InitializedEntity &Entity, |
5779 | const InitializationKind &Kind, |
5780 | InitializationSequence &Sequence) { |
5781 | assert(Kind.getKind() == InitializationKind::IK_Default); |
5782 | |
5783 | // C++ [dcl.init]p6: |
5784 | // To default-initialize an object of type T means: |
5785 | // - if T is an array type, each element is default-initialized; |
5786 | QualType DestType = S.Context.getBaseElementType(QT: Entity.getType()); |
5787 | |
5788 | // - if T is a (possibly cv-qualified) class type (Clause 9), the default |
5789 | // constructor for T is called (and the initialization is ill-formed if |
5790 | // T has no accessible default constructor); |
5791 | if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) { |
5792 | TryConstructorInitialization(S, Entity, Kind, Args: {}, DestType, |
5793 | DestArrayType: Entity.getType(), Sequence); |
5794 | return; |
5795 | } |
5796 | |
5797 | // - otherwise, no initialization is performed. |
5798 | |
5799 | // If a program calls for the default initialization of an object of |
5800 | // a const-qualified type T, T shall be a class type with a user-provided |
5801 | // default constructor. |
5802 | if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) { |
5803 | if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity)) |
5804 | Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); |
5805 | return; |
5806 | } |
5807 | |
5808 | // If the destination type has a lifetime property, zero-initialize it. |
5809 | if (DestType.getQualifiers().hasObjCLifetime()) { |
5810 | Sequence.AddZeroInitializationStep(T: Entity.getType()); |
5811 | return; |
5812 | } |
5813 | } |
5814 | |
5815 | static void TryOrBuildParenListInitialization( |
5816 | Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, |
5817 | ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly, |
5818 | ExprResult *Result) { |
5819 | unsigned EntityIndexToProcess = 0; |
5820 | SmallVector<Expr *, 4> InitExprs; |
5821 | QualType ResultType; |
5822 | Expr *ArrayFiller = nullptr; |
5823 | FieldDecl *InitializedFieldInUnion = nullptr; |
5824 | |
5825 | auto HandleInitializedEntity = [&](const InitializedEntity &SubEntity, |
5826 | const InitializationKind &SubKind, |
5827 | Expr *Arg, Expr **InitExpr = nullptr) { |
5828 | InitializationSequence IS = InitializationSequence( |
5829 | S, SubEntity, SubKind, |
5830 | Arg ? MultiExprArg(Arg) : MutableArrayRef<Expr *>()); |
5831 | |
5832 | if (IS.Failed()) { |
5833 | if (!VerifyOnly) { |
5834 | IS.Diagnose(S, Entity: SubEntity, Kind: SubKind, |
5835 | Args: Arg ? ArrayRef(Arg) : ArrayRef<Expr *>()); |
5836 | } else { |
5837 | Sequence.SetFailed( |
5838 | InitializationSequence::FK_ParenthesizedListInitFailed); |
5839 | } |
5840 | |
5841 | return false; |
5842 | } |
5843 | if (!VerifyOnly) { |
5844 | ExprResult ER; |
5845 | ER = IS.Perform(S, Entity: SubEntity, Kind: SubKind, |
5846 | Args: Arg ? MultiExprArg(Arg) : MutableArrayRef<Expr *>()); |
5847 | |
5848 | if (ER.isInvalid()) |
5849 | return false; |
5850 | |
5851 | if (InitExpr) |
5852 | *InitExpr = ER.get(); |
5853 | else |
5854 | InitExprs.push_back(Elt: ER.get()); |
5855 | } |
5856 | return true; |
5857 | }; |
5858 | |
5859 | if (const ArrayType *AT = |
5860 | S.getASTContext().getAsArrayType(T: Entity.getType())) { |
5861 | uint64_t ArrayLength; |
5862 | // C++ [dcl.init]p16.5 |
5863 | // if the destination type is an array, the object is initialized as |
5864 | // follows. Let x1, . . . , xk be the elements of the expression-list. If |
5865 | // the destination type is an array of unknown bound, it is defined as |
5866 | // having k elements. |
5867 | if (const ConstantArrayType *CAT = |
5868 | S.getASTContext().getAsConstantArrayType(T: Entity.getType())) { |
5869 | ArrayLength = CAT->getZExtSize(); |
5870 | ResultType = Entity.getType(); |
5871 | } else if (const VariableArrayType *VAT = |
5872 | S.getASTContext().getAsVariableArrayType(T: Entity.getType())) { |
5873 | // Braced-initialization of variable array types is not allowed, even if |
5874 | // the size is greater than or equal to the number of args, so we don't |
5875 | // allow them to be initialized via parenthesized aggregate initialization |
5876 | // either. |
5877 | const Expr *SE = VAT->getSizeExpr(); |
5878 | S.Diag(Loc: SE->getBeginLoc(), DiagID: diag::err_variable_object_no_init) |
5879 | << SE->getSourceRange(); |
5880 | return; |
5881 | } else { |
5882 | assert(Entity.getType()->isIncompleteArrayType()); |
5883 | ArrayLength = Args.size(); |
5884 | } |
5885 | EntityIndexToProcess = ArrayLength; |
5886 | |
5887 | // ...the ith array element is copy-initialized with xi for each |
5888 | // 1 <= i <= k |
5889 | for (Expr *E : Args) { |
5890 | InitializedEntity SubEntity = InitializedEntity::InitializeElement( |
5891 | Context&: S.getASTContext(), Index: EntityIndexToProcess, Parent: Entity); |
5892 | InitializationKind SubKind = InitializationKind::CreateForInit( |
5893 | Loc: E->getExprLoc(), /*isDirectInit=*/DirectInit: false, Init: E); |
5894 | if (!HandleInitializedEntity(SubEntity, SubKind, E)) |
5895 | return; |
5896 | } |
5897 | // ...and value-initialized for each k < i <= n; |
5898 | if (ArrayLength > Args.size() || Entity.isVariableLengthArrayNew()) { |
5899 | InitializedEntity SubEntity = InitializedEntity::InitializeElement( |
5900 | Context&: S.getASTContext(), Index: Args.size(), Parent: Entity); |
5901 | InitializationKind SubKind = InitializationKind::CreateValue( |
5902 | InitLoc: Kind.getLocation(), LParenLoc: Kind.getLocation(), RParenLoc: Kind.getLocation(), isImplicit: true); |
5903 | if (!HandleInitializedEntity(SubEntity, SubKind, nullptr, &ArrayFiller)) |
5904 | return; |
5905 | } |
5906 | |
5907 | if (ResultType.isNull()) { |
5908 | ResultType = S.Context.getConstantArrayType( |
5909 | EltTy: AT->getElementType(), ArySize: llvm::APInt(/*numBits=*/32, ArrayLength), |
5910 | /*SizeExpr=*/nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0); |
5911 | } |
5912 | } else if (auto *RT = Entity.getType()->getAs<RecordType>()) { |
5913 | bool IsUnion = RT->isUnionType(); |
5914 | const CXXRecordDecl *RD = cast<CXXRecordDecl>(Val: RT->getDecl()); |
5915 | if (RD->isInvalidDecl()) { |
5916 | // Exit early to avoid confusion when processing members. |
5917 | // We do the same for braced list initialization in |
5918 | // `CheckStructUnionTypes`. |
5919 | Sequence.SetFailed( |
5920 | clang::InitializationSequence::FK_ParenthesizedListInitFailed); |
5921 | return; |
5922 | } |
5923 | |
5924 | if (!IsUnion) { |
5925 | for (const CXXBaseSpecifier &Base : RD->bases()) { |
5926 | InitializedEntity SubEntity = InitializedEntity::InitializeBase( |
5927 | Context&: S.getASTContext(), Base: &Base, IsInheritedVirtualBase: false, Parent: &Entity); |
5928 | if (EntityIndexToProcess < Args.size()) { |
5929 | // C++ [dcl.init]p16.6.2.2. |
5930 | // ...the object is initialized is follows. Let e1, ..., en be the |
5931 | // elements of the aggregate([dcl.init.aggr]). Let x1, ..., xk be |
5932 | // the elements of the expression-list...The element ei is |
5933 | // copy-initialized with xi for 1 <= i <= k. |
5934 | Expr *E = Args[EntityIndexToProcess]; |
5935 | InitializationKind SubKind = InitializationKind::CreateForInit( |
5936 | Loc: E->getExprLoc(), /*isDirectInit=*/DirectInit: false, Init: E); |
5937 | if (!HandleInitializedEntity(SubEntity, SubKind, E)) |
5938 | return; |
5939 | } else { |
5940 | // We've processed all of the args, but there are still base classes |
5941 | // that have to be initialized. |
5942 | // C++ [dcl.init]p17.6.2.2 |
5943 | // The remaining elements...otherwise are value initialzed |
5944 | InitializationKind SubKind = InitializationKind::CreateValue( |
5945 | InitLoc: Kind.getLocation(), LParenLoc: Kind.getLocation(), RParenLoc: Kind.getLocation(), |
5946 | /*IsImplicit=*/isImplicit: true); |
5947 | if (!HandleInitializedEntity(SubEntity, SubKind, nullptr)) |
5948 | return; |
5949 | } |
5950 | EntityIndexToProcess++; |
5951 | } |
5952 | } |
5953 | |
5954 | for (FieldDecl *FD : RD->fields()) { |
5955 | // Unnamed bitfields should not be initialized at all, either with an arg |
5956 | // or by default. |
5957 | if (FD->isUnnamedBitField()) |
5958 | continue; |
5959 | |
5960 | InitializedEntity SubEntity = |
5961 | InitializedEntity::InitializeMemberFromParenAggInit(Member: FD); |
5962 | |
5963 | if (EntityIndexToProcess < Args.size()) { |
5964 | // ...The element ei is copy-initialized with xi for 1 <= i <= k. |
5965 | Expr *E = Args[EntityIndexToProcess]; |
5966 | |
5967 | // Incomplete array types indicate flexible array members. Do not allow |
5968 | // paren list initializations of structs with these members, as GCC |
5969 | // doesn't either. |
5970 | if (FD->getType()->isIncompleteArrayType()) { |
5971 | if (!VerifyOnly) { |
5972 | S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_flexible_array_init) |
5973 | << SourceRange(E->getBeginLoc(), E->getEndLoc()); |
5974 | S.Diag(Loc: FD->getLocation(), DiagID: diag::note_flexible_array_member) << FD; |
5975 | } |
5976 | Sequence.SetFailed( |
5977 | InitializationSequence::FK_ParenthesizedListInitFailed); |
5978 | return; |
5979 | } |
5980 | |
5981 | InitializationKind SubKind = InitializationKind::CreateForInit( |
5982 | Loc: E->getExprLoc(), /*isDirectInit=*/DirectInit: false, Init: E); |
5983 | if (!HandleInitializedEntity(SubEntity, SubKind, E)) |
5984 | return; |
5985 | |
5986 | // Unions should have only one initializer expression, so we bail out |
5987 | // after processing the first field. If there are more initializers then |
5988 | // it will be caught when we later check whether EntityIndexToProcess is |
5989 | // less than Args.size(); |
5990 | if (IsUnion) { |
5991 | InitializedFieldInUnion = FD; |
5992 | EntityIndexToProcess = 1; |
5993 | break; |
5994 | } |
5995 | } else { |
5996 | // We've processed all of the args, but there are still members that |
5997 | // have to be initialized. |
5998 | if (!VerifyOnly && FD->hasAttr<ExplicitInitAttr>()) { |
5999 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::warn_field_requires_explicit_init) |
6000 | << /* Var-in-Record */ 0 << FD; |
6001 | S.Diag(Loc: FD->getLocation(), DiagID: diag::note_entity_declared_at) << FD; |
6002 | } |
6003 | |
6004 | if (FD->hasInClassInitializer()) { |
6005 | if (!VerifyOnly) { |
6006 | // C++ [dcl.init]p16.6.2.2 |
6007 | // The remaining elements are initialized with their default |
6008 | // member initializers, if any |
6009 | ExprResult DIE = S.BuildCXXDefaultInitExpr( |
6010 | Loc: Kind.getParenOrBraceRange().getEnd(), Field: FD); |
6011 | if (DIE.isInvalid()) |
6012 | return; |
6013 | S.checkInitializerLifetime(Entity: SubEntity, Init: DIE.get()); |
6014 | InitExprs.push_back(Elt: DIE.get()); |
6015 | } |
6016 | } else { |
6017 | // C++ [dcl.init]p17.6.2.2 |
6018 | // The remaining elements...otherwise are value initialzed |
6019 | if (FD->getType()->isReferenceType()) { |
6020 | Sequence.SetFailed( |
6021 | InitializationSequence::FK_ParenthesizedListInitFailed); |
6022 | if (!VerifyOnly) { |
6023 | SourceRange SR = Kind.getParenOrBraceRange(); |
6024 | S.Diag(Loc: SR.getEnd(), DiagID: diag::err_init_reference_member_uninitialized) |
6025 | << FD->getType() << SR; |
6026 | S.Diag(Loc: FD->getLocation(), DiagID: diag::note_uninit_reference_member); |
6027 | } |
6028 | return; |
6029 | } |
6030 | InitializationKind SubKind = InitializationKind::CreateValue( |
6031 | InitLoc: Kind.getLocation(), LParenLoc: Kind.getLocation(), RParenLoc: Kind.getLocation(), isImplicit: true); |
6032 | if (!HandleInitializedEntity(SubEntity, SubKind, nullptr)) |
6033 | return; |
6034 | } |
6035 | } |
6036 | EntityIndexToProcess++; |
6037 | } |
6038 | ResultType = Entity.getType(); |
6039 | } |
6040 | |
6041 | // Not all of the args have been processed, so there must've been more args |
6042 | // than were required to initialize the element. |
6043 | if (EntityIndexToProcess < Args.size()) { |
6044 | Sequence.SetFailed(InitializationSequence::FK_ParenthesizedListInitFailed); |
6045 | if (!VerifyOnly) { |
6046 | QualType T = Entity.getType(); |
6047 | int InitKind = T->isArrayType() ? 0 : T->isUnionType() ? 3 : 4; |
6048 | SourceRange ExcessInitSR(Args[EntityIndexToProcess]->getBeginLoc(), |
6049 | Args.back()->getEndLoc()); |
6050 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_excess_initializers) |
6051 | << InitKind << ExcessInitSR; |
6052 | } |
6053 | return; |
6054 | } |
6055 | |
6056 | if (VerifyOnly) { |
6057 | Sequence.setSequenceKind(InitializationSequence::NormalSequence); |
6058 | Sequence.AddParenthesizedListInitStep(T: Entity.getType()); |
6059 | } else if (Result) { |
6060 | SourceRange SR = Kind.getParenOrBraceRange(); |
6061 | auto *CPLIE = CXXParenListInitExpr::Create( |
6062 | C&: S.getASTContext(), Args: InitExprs, T: ResultType, NumUserSpecifiedExprs: Args.size(), |
6063 | InitLoc: Kind.getLocation(), LParenLoc: SR.getBegin(), RParenLoc: SR.getEnd()); |
6064 | if (ArrayFiller) |
6065 | CPLIE->setArrayFiller(ArrayFiller); |
6066 | if (InitializedFieldInUnion) |
6067 | CPLIE->setInitializedFieldInUnion(InitializedFieldInUnion); |
6068 | *Result = CPLIE; |
6069 | S.Diag(Loc: Kind.getLocation(), |
6070 | DiagID: diag::warn_cxx17_compat_aggregate_init_paren_list) |
6071 | << Kind.getLocation() << SR << ResultType; |
6072 | } |
6073 | } |
6074 | |
6075 | /// Attempt a user-defined conversion between two types (C++ [dcl.init]), |
6076 | /// which enumerates all conversion functions and performs overload resolution |
6077 | /// to select the best. |
6078 | static void TryUserDefinedConversion(Sema &S, |
6079 | QualType DestType, |
6080 | const InitializationKind &Kind, |
6081 | Expr *Initializer, |
6082 | InitializationSequence &Sequence, |
6083 | bool TopLevelOfInitList) { |
6084 | assert(!DestType->isReferenceType() && "References are handled elsewhere" ); |
6085 | QualType SourceType = Initializer->getType(); |
6086 | assert((DestType->isRecordType() || SourceType->isRecordType()) && |
6087 | "Must have a class type to perform a user-defined conversion" ); |
6088 | |
6089 | // Build the candidate set directly in the initialization sequence |
6090 | // structure, so that it will persist if we fail. |
6091 | OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); |
6092 | CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion); |
6093 | CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace()); |
6094 | |
6095 | // Determine whether we are allowed to call explicit constructors or |
6096 | // explicit conversion operators. |
6097 | bool AllowExplicit = Kind.AllowExplicit(); |
6098 | |
6099 | if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) { |
6100 | // The type we're converting to is a class type. Enumerate its constructors |
6101 | // to see if there is a suitable conversion. |
6102 | CXXRecordDecl *DestRecordDecl |
6103 | = cast<CXXRecordDecl>(Val: DestRecordType->getDecl()); |
6104 | |
6105 | // Try to complete the type we're converting to. |
6106 | if (S.isCompleteType(Loc: Kind.getLocation(), T: DestType)) { |
6107 | for (NamedDecl *D : S.LookupConstructors(Class: DestRecordDecl)) { |
6108 | auto Info = getConstructorInfo(ND: D); |
6109 | if (!Info.Constructor) |
6110 | continue; |
6111 | |
6112 | if (!Info.Constructor->isInvalidDecl() && |
6113 | Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) { |
6114 | if (Info.ConstructorTmpl) |
6115 | S.AddTemplateOverloadCandidate( |
6116 | FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl, |
6117 | /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: Initializer, CandidateSet, |
6118 | /*SuppressUserConversions=*/true, |
6119 | /*PartialOverloading*/ false, AllowExplicit); |
6120 | else |
6121 | S.AddOverloadCandidate(Function: Info.Constructor, FoundDecl: Info.FoundDecl, |
6122 | Args: Initializer, CandidateSet, |
6123 | /*SuppressUserConversions=*/true, |
6124 | /*PartialOverloading*/ false, AllowExplicit); |
6125 | } |
6126 | } |
6127 | } |
6128 | } |
6129 | |
6130 | SourceLocation DeclLoc = Initializer->getBeginLoc(); |
6131 | |
6132 | if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) { |
6133 | // The type we're converting from is a class type, enumerate its conversion |
6134 | // functions. |
6135 | |
6136 | // We can only enumerate the conversion functions for a complete type; if |
6137 | // the type isn't complete, simply skip this step. |
6138 | if (S.isCompleteType(Loc: DeclLoc, T: SourceType)) { |
6139 | CXXRecordDecl *SourceRecordDecl |
6140 | = cast<CXXRecordDecl>(Val: SourceRecordType->getDecl()); |
6141 | |
6142 | const auto &Conversions = |
6143 | SourceRecordDecl->getVisibleConversionFunctions(); |
6144 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { |
6145 | NamedDecl *D = *I; |
6146 | CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: D->getDeclContext()); |
6147 | if (isa<UsingShadowDecl>(Val: D)) |
6148 | D = cast<UsingShadowDecl>(Val: D)->getTargetDecl(); |
6149 | |
6150 | FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D); |
6151 | CXXConversionDecl *Conv; |
6152 | if (ConvTemplate) |
6153 | Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl()); |
6154 | else |
6155 | Conv = cast<CXXConversionDecl>(Val: D); |
6156 | |
6157 | if (ConvTemplate) |
6158 | S.AddTemplateConversionCandidate( |
6159 | FunctionTemplate: ConvTemplate, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer, ToType: DestType, |
6160 | CandidateSet, AllowObjCConversionOnExplicit: AllowExplicit, AllowExplicit); |
6161 | else |
6162 | S.AddConversionCandidate(Conversion: Conv, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer, |
6163 | ToType: DestType, CandidateSet, AllowObjCConversionOnExplicit: AllowExplicit, |
6164 | AllowExplicit); |
6165 | } |
6166 | } |
6167 | } |
6168 | |
6169 | // Perform overload resolution. If it fails, return the failed result. |
6170 | OverloadCandidateSet::iterator Best; |
6171 | if (OverloadingResult Result |
6172 | = CandidateSet.BestViableFunction(S, Loc: DeclLoc, Best)) { |
6173 | Sequence.SetOverloadFailure( |
6174 | Failure: InitializationSequence::FK_UserConversionOverloadFailed, Result); |
6175 | |
6176 | // [class.copy.elision]p3: |
6177 | // In some copy-initialization contexts, a two-stage overload resolution |
6178 | // is performed. |
6179 | // If the first overload resolution selects a deleted function, we also |
6180 | // need the initialization sequence to decide whether to perform the second |
6181 | // overload resolution. |
6182 | if (!(Result == OR_Deleted && |
6183 | Kind.getKind() == InitializationKind::IK_Copy)) |
6184 | return; |
6185 | } |
6186 | |
6187 | FunctionDecl *Function = Best->Function; |
6188 | Function->setReferenced(); |
6189 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
6190 | |
6191 | if (isa<CXXConstructorDecl>(Val: Function)) { |
6192 | // Add the user-defined conversion step. Any cv-qualification conversion is |
6193 | // subsumed by the initialization. Per DR5, the created temporary is of the |
6194 | // cv-unqualified type of the destination. |
6195 | Sequence.AddUserConversionStep(Function, FoundDecl: Best->FoundDecl, |
6196 | T: DestType.getUnqualifiedType(), |
6197 | HadMultipleCandidates); |
6198 | |
6199 | // C++14 and before: |
6200 | // - if the function is a constructor, the call initializes a temporary |
6201 | // of the cv-unqualified version of the destination type. The [...] |
6202 | // temporary [...] is then used to direct-initialize, according to the |
6203 | // rules above, the object that is the destination of the |
6204 | // copy-initialization. |
6205 | // Note that this just performs a simple object copy from the temporary. |
6206 | // |
6207 | // C++17: |
6208 | // - if the function is a constructor, the call is a prvalue of the |
6209 | // cv-unqualified version of the destination type whose return object |
6210 | // is initialized by the constructor. The call is used to |
6211 | // direct-initialize, according to the rules above, the object that |
6212 | // is the destination of the copy-initialization. |
6213 | // Therefore we need to do nothing further. |
6214 | // |
6215 | // FIXME: Mark this copy as extraneous. |
6216 | if (!S.getLangOpts().CPlusPlus17) |
6217 | Sequence.AddFinalCopy(T: DestType); |
6218 | else if (DestType.hasQualifiers()) |
6219 | Sequence.AddQualificationConversionStep(Ty: DestType, VK: VK_PRValue); |
6220 | return; |
6221 | } |
6222 | |
6223 | // Add the user-defined conversion step that calls the conversion function. |
6224 | QualType ConvType = Function->getCallResultType(); |
6225 | Sequence.AddUserConversionStep(Function, FoundDecl: Best->FoundDecl, T: ConvType, |
6226 | HadMultipleCandidates); |
6227 | |
6228 | if (ConvType->getAs<RecordType>()) { |
6229 | // The call is used to direct-initialize [...] the object that is the |
6230 | // destination of the copy-initialization. |
6231 | // |
6232 | // In C++17, this does not call a constructor if we enter /17.6.1: |
6233 | // - If the initializer expression is a prvalue and the cv-unqualified |
6234 | // version of the source type is the same as the class of the |
6235 | // destination [... do not make an extra copy] |
6236 | // |
6237 | // FIXME: Mark this copy as extraneous. |
6238 | if (!S.getLangOpts().CPlusPlus17 || |
6239 | Function->getReturnType()->isReferenceType() || |
6240 | !S.Context.hasSameUnqualifiedType(T1: ConvType, T2: DestType)) |
6241 | Sequence.AddFinalCopy(T: DestType); |
6242 | else if (!S.Context.hasSameType(T1: ConvType, T2: DestType)) |
6243 | Sequence.AddQualificationConversionStep(Ty: DestType, VK: VK_PRValue); |
6244 | return; |
6245 | } |
6246 | |
6247 | // If the conversion following the call to the conversion function |
6248 | // is interesting, add it as a separate step. |
6249 | assert(Best->HasFinalConversion); |
6250 | if (Best->FinalConversion.First || Best->FinalConversion.Second || |
6251 | Best->FinalConversion.Third) { |
6252 | ImplicitConversionSequence ICS; |
6253 | ICS.setStandard(); |
6254 | ICS.Standard = Best->FinalConversion; |
6255 | Sequence.AddConversionSequenceStep(ICS, T: DestType, TopLevelOfInitList); |
6256 | } |
6257 | } |
6258 | |
6259 | /// The non-zero enum values here are indexes into diagnostic alternatives. |
6260 | enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar }; |
6261 | |
6262 | /// Determines whether this expression is an acceptable ICR source. |
6263 | static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e, |
6264 | bool isAddressOf, bool &isWeakAccess) { |
6265 | // Skip parens. |
6266 | e = e->IgnoreParens(); |
6267 | |
6268 | // Skip address-of nodes. |
6269 | if (UnaryOperator *op = dyn_cast<UnaryOperator>(Val: e)) { |
6270 | if (op->getOpcode() == UO_AddrOf) |
6271 | return isInvalidICRSource(C, e: op->getSubExpr(), /*addressof*/ isAddressOf: true, |
6272 | isWeakAccess); |
6273 | |
6274 | // Skip certain casts. |
6275 | } else if (CastExpr *ce = dyn_cast<CastExpr>(Val: e)) { |
6276 | switch (ce->getCastKind()) { |
6277 | case CK_Dependent: |
6278 | case CK_BitCast: |
6279 | case CK_LValueBitCast: |
6280 | case CK_NoOp: |
6281 | return isInvalidICRSource(C, e: ce->getSubExpr(), isAddressOf, isWeakAccess); |
6282 | |
6283 | case CK_ArrayToPointerDecay: |
6284 | return IIK_nonscalar; |
6285 | |
6286 | case CK_NullToPointer: |
6287 | return IIK_okay; |
6288 | |
6289 | default: |
6290 | break; |
6291 | } |
6292 | |
6293 | // If we have a declaration reference, it had better be a local variable. |
6294 | } else if (isa<DeclRefExpr>(Val: e)) { |
6295 | // set isWeakAccess to true, to mean that there will be an implicit |
6296 | // load which requires a cleanup. |
6297 | if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak) |
6298 | isWeakAccess = true; |
6299 | |
6300 | if (!isAddressOf) return IIK_nonlocal; |
6301 | |
6302 | VarDecl *var = dyn_cast<VarDecl>(Val: cast<DeclRefExpr>(Val: e)->getDecl()); |
6303 | if (!var) return IIK_nonlocal; |
6304 | |
6305 | return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal); |
6306 | |
6307 | // If we have a conditional operator, check both sides. |
6308 | } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(Val: e)) { |
6309 | if (InvalidICRKind iik = isInvalidICRSource(C, e: cond->getLHS(), isAddressOf, |
6310 | isWeakAccess)) |
6311 | return iik; |
6312 | |
6313 | return isInvalidICRSource(C, e: cond->getRHS(), isAddressOf, isWeakAccess); |
6314 | |
6315 | // These are never scalar. |
6316 | } else if (isa<ArraySubscriptExpr>(Val: e)) { |
6317 | return IIK_nonscalar; |
6318 | |
6319 | // Otherwise, it needs to be a null pointer constant. |
6320 | } else { |
6321 | return (e->isNullPointerConstant(Ctx&: C, NPC: Expr::NPC_ValueDependentIsNull) |
6322 | ? IIK_okay : IIK_nonlocal); |
6323 | } |
6324 | |
6325 | return IIK_nonlocal; |
6326 | } |
6327 | |
6328 | /// Check whether the given expression is a valid operand for an |
6329 | /// indirect copy/restore. |
6330 | static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) { |
6331 | assert(src->isPRValue()); |
6332 | bool isWeakAccess = false; |
6333 | InvalidICRKind iik = isInvalidICRSource(C&: S.Context, e: src, isAddressOf: false, isWeakAccess); |
6334 | // If isWeakAccess to true, there will be an implicit |
6335 | // load which requires a cleanup. |
6336 | if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess) |
6337 | S.Cleanup.setExprNeedsCleanups(true); |
6338 | |
6339 | if (iik == IIK_okay) return; |
6340 | |
6341 | S.Diag(Loc: src->getExprLoc(), DiagID: diag::err_arc_nonlocal_writeback) |
6342 | << ((unsigned) iik - 1) // shift index into diagnostic explanations |
6343 | << src->getSourceRange(); |
6344 | } |
6345 | |
6346 | /// Determine whether we have compatible array types for the |
6347 | /// purposes of GNU by-copy array initialization. |
6348 | static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest, |
6349 | const ArrayType *Source) { |
6350 | // If the source and destination array types are equivalent, we're |
6351 | // done. |
6352 | if (Context.hasSameType(T1: QualType(Dest, 0), T2: QualType(Source, 0))) |
6353 | return true; |
6354 | |
6355 | // Make sure that the element types are the same. |
6356 | if (!Context.hasSameType(T1: Dest->getElementType(), T2: Source->getElementType())) |
6357 | return false; |
6358 | |
6359 | // The only mismatch we allow is when the destination is an |
6360 | // incomplete array type and the source is a constant array type. |
6361 | return Source->isConstantArrayType() && Dest->isIncompleteArrayType(); |
6362 | } |
6363 | |
6364 | static bool tryObjCWritebackConversion(Sema &S, |
6365 | InitializationSequence &Sequence, |
6366 | const InitializedEntity &Entity, |
6367 | Expr *Initializer) { |
6368 | bool ArrayDecay = false; |
6369 | QualType ArgType = Initializer->getType(); |
6370 | QualType ArgPointee; |
6371 | if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(T: ArgType)) { |
6372 | ArrayDecay = true; |
6373 | ArgPointee = ArgArrayType->getElementType(); |
6374 | ArgType = S.Context.getPointerType(T: ArgPointee); |
6375 | } |
6376 | |
6377 | // Handle write-back conversion. |
6378 | QualType ConvertedArgType; |
6379 | if (!S.ObjC().isObjCWritebackConversion(FromType: ArgType, ToType: Entity.getType(), |
6380 | ConvertedType&: ConvertedArgType)) |
6381 | return false; |
6382 | |
6383 | // We should copy unless we're passing to an argument explicitly |
6384 | // marked 'out'. |
6385 | bool ShouldCopy = true; |
6386 | if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Val: Entity.getDecl())) |
6387 | ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); |
6388 | |
6389 | // Do we need an lvalue conversion? |
6390 | if (ArrayDecay || Initializer->isGLValue()) { |
6391 | ImplicitConversionSequence ICS; |
6392 | ICS.setStandard(); |
6393 | ICS.Standard.setAsIdentityConversion(); |
6394 | |
6395 | QualType ResultType; |
6396 | if (ArrayDecay) { |
6397 | ICS.Standard.First = ICK_Array_To_Pointer; |
6398 | ResultType = S.Context.getPointerType(T: ArgPointee); |
6399 | } else { |
6400 | ICS.Standard.First = ICK_Lvalue_To_Rvalue; |
6401 | ResultType = Initializer->getType().getNonLValueExprType(Context: S.Context); |
6402 | } |
6403 | |
6404 | Sequence.AddConversionSequenceStep(ICS, T: ResultType); |
6405 | } |
6406 | |
6407 | Sequence.AddPassByIndirectCopyRestoreStep(type: Entity.getType(), shouldCopy: ShouldCopy); |
6408 | return true; |
6409 | } |
6410 | |
6411 | static bool TryOCLSamplerInitialization(Sema &S, |
6412 | InitializationSequence &Sequence, |
6413 | QualType DestType, |
6414 | Expr *Initializer) { |
6415 | if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() || |
6416 | (!Initializer->isIntegerConstantExpr(Ctx: S.Context) && |
6417 | !Initializer->getType()->isSamplerT())) |
6418 | return false; |
6419 | |
6420 | Sequence.AddOCLSamplerInitStep(T: DestType); |
6421 | return true; |
6422 | } |
6423 | |
6424 | static bool IsZeroInitializer(const Expr *Init, ASTContext &Ctx) { |
6425 | std::optional<llvm::APSInt> Value = Init->getIntegerConstantExpr(Ctx); |
6426 | return Value && Value->isZero(); |
6427 | } |
6428 | |
6429 | static bool TryOCLZeroOpaqueTypeInitialization(Sema &S, |
6430 | InitializationSequence &Sequence, |
6431 | QualType DestType, |
6432 | Expr *Initializer) { |
6433 | if (!S.getLangOpts().OpenCL) |
6434 | return false; |
6435 | |
6436 | // |
6437 | // OpenCL 1.2 spec, s6.12.10 |
6438 | // |
6439 | // The event argument can also be used to associate the |
6440 | // async_work_group_copy with a previous async copy allowing |
6441 | // an event to be shared by multiple async copies; otherwise |
6442 | // event should be zero. |
6443 | // |
6444 | if (DestType->isEventT() || DestType->isQueueT()) { |
6445 | if (!IsZeroInitializer(Init: Initializer, Ctx&: S.getASTContext())) |
6446 | return false; |
6447 | |
6448 | Sequence.AddOCLZeroOpaqueTypeStep(T: DestType); |
6449 | return true; |
6450 | } |
6451 | |
6452 | // We should allow zero initialization for all types defined in the |
6453 | // cl_intel_device_side_avc_motion_estimation extension, except |
6454 | // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t. |
6455 | if (S.getOpenCLOptions().isAvailableOption( |
6456 | Ext: "cl_intel_device_side_avc_motion_estimation" , LO: S.getLangOpts()) && |
6457 | DestType->isOCLIntelSubgroupAVCType()) { |
6458 | if (DestType->isOCLIntelSubgroupAVCMcePayloadType() || |
6459 | DestType->isOCLIntelSubgroupAVCMceResultType()) |
6460 | return false; |
6461 | if (!IsZeroInitializer(Init: Initializer, Ctx&: S.getASTContext())) |
6462 | return false; |
6463 | |
6464 | Sequence.AddOCLZeroOpaqueTypeStep(T: DestType); |
6465 | return true; |
6466 | } |
6467 | |
6468 | return false; |
6469 | } |
6470 | |
6471 | InitializationSequence::InitializationSequence( |
6472 | Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, |
6473 | MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid) |
6474 | : FailedOverloadResult(OR_Success), |
6475 | FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) { |
6476 | InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList, |
6477 | TreatUnavailableAsInvalid); |
6478 | } |
6479 | |
6480 | /// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the |
6481 | /// address of that function, this returns true. Otherwise, it returns false. |
6482 | static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) { |
6483 | auto *DRE = dyn_cast<DeclRefExpr>(Val: E); |
6484 | if (!DRE || !isa<FunctionDecl>(Val: DRE->getDecl())) |
6485 | return false; |
6486 | |
6487 | return !S.checkAddressOfFunctionIsAvailable( |
6488 | Function: cast<FunctionDecl>(Val: DRE->getDecl())); |
6489 | } |
6490 | |
6491 | /// Determine whether we can perform an elementwise array copy for this kind |
6492 | /// of entity. |
6493 | static bool canPerformArrayCopy(const InitializedEntity &Entity) { |
6494 | switch (Entity.getKind()) { |
6495 | case InitializedEntity::EK_LambdaCapture: |
6496 | // C++ [expr.prim.lambda]p24: |
6497 | // For array members, the array elements are direct-initialized in |
6498 | // increasing subscript order. |
6499 | return true; |
6500 | |
6501 | case InitializedEntity::EK_Variable: |
6502 | // C++ [dcl.decomp]p1: |
6503 | // [...] each element is copy-initialized or direct-initialized from the |
6504 | // corresponding element of the assignment-expression [...] |
6505 | return isa<DecompositionDecl>(Val: Entity.getDecl()); |
6506 | |
6507 | case InitializedEntity::EK_Member: |
6508 | // C++ [class.copy.ctor]p14: |
6509 | // - if the member is an array, each element is direct-initialized with |
6510 | // the corresponding subobject of x |
6511 | return Entity.isImplicitMemberInitializer(); |
6512 | |
6513 | case InitializedEntity::EK_ArrayElement: |
6514 | // All the above cases are intended to apply recursively, even though none |
6515 | // of them actually say that. |
6516 | if (auto *E = Entity.getParent()) |
6517 | return canPerformArrayCopy(Entity: *E); |
6518 | break; |
6519 | |
6520 | default: |
6521 | break; |
6522 | } |
6523 | |
6524 | return false; |
6525 | } |
6526 | |
6527 | static const FieldDecl *getConstField(const RecordDecl *RD) { |
6528 | assert(!isa<CXXRecordDecl>(RD) && "Only expect to call this in C mode" ); |
6529 | for (const FieldDecl *FD : RD->fields()) { |
6530 | // If the field is a flexible array member, we don't want to consider it |
6531 | // as a const field because there's no way to initialize the FAM anyway. |
6532 | const ASTContext &Ctx = FD->getASTContext(); |
6533 | if (Decl::isFlexibleArrayMemberLike( |
6534 | Context: Ctx, D: FD, Ty: FD->getType(), |
6535 | StrictFlexArraysLevel: Ctx.getLangOpts().getStrictFlexArraysLevel(), |
6536 | /*IgnoreTemplateOrMacroSubstitution=*/true)) |
6537 | continue; |
6538 | |
6539 | QualType QT = FD->getType(); |
6540 | if (QT.isConstQualified()) |
6541 | return FD; |
6542 | if (const auto *RD = QT->getAsRecordDecl()) { |
6543 | if (const FieldDecl *FD = getConstField(RD)) |
6544 | return FD; |
6545 | } |
6546 | } |
6547 | return nullptr; |
6548 | } |
6549 | |
6550 | void InitializationSequence::InitializeFrom(Sema &S, |
6551 | const InitializedEntity &Entity, |
6552 | const InitializationKind &Kind, |
6553 | MultiExprArg Args, |
6554 | bool TopLevelOfInitList, |
6555 | bool TreatUnavailableAsInvalid) { |
6556 | ASTContext &Context = S.Context; |
6557 | |
6558 | // Eliminate non-overload placeholder types in the arguments. We |
6559 | // need to do this before checking whether types are dependent |
6560 | // because lowering a pseudo-object expression might well give us |
6561 | // something of dependent type. |
6562 | for (unsigned I = 0, E = Args.size(); I != E; ++I) |
6563 | if (Args[I]->getType()->isNonOverloadPlaceholderType()) { |
6564 | // FIXME: should we be doing this here? |
6565 | ExprResult result = S.CheckPlaceholderExpr(E: Args[I]); |
6566 | if (result.isInvalid()) { |
6567 | SetFailed(FK_PlaceholderType); |
6568 | return; |
6569 | } |
6570 | Args[I] = result.get(); |
6571 | } |
6572 | |
6573 | // C++0x [dcl.init]p16: |
6574 | // The semantics of initializers are as follows. The destination type is |
6575 | // the type of the object or reference being initialized and the source |
6576 | // type is the type of the initializer expression. The source type is not |
6577 | // defined when the initializer is a braced-init-list or when it is a |
6578 | // parenthesized list of expressions. |
6579 | QualType DestType = Entity.getType(); |
6580 | |
6581 | if (DestType->isDependentType() || |
6582 | Expr::hasAnyTypeDependentArguments(Exprs: Args)) { |
6583 | SequenceKind = DependentSequence; |
6584 | return; |
6585 | } |
6586 | |
6587 | // Almost everything is a normal sequence. |
6588 | setSequenceKind(NormalSequence); |
6589 | |
6590 | QualType SourceType; |
6591 | Expr *Initializer = nullptr; |
6592 | if (Args.size() == 1) { |
6593 | Initializer = Args[0]; |
6594 | if (S.getLangOpts().ObjC) { |
6595 | if (S.ObjC().CheckObjCBridgeRelatedConversions( |
6596 | Loc: Initializer->getBeginLoc(), DestType, SrcType: Initializer->getType(), |
6597 | SrcExpr&: Initializer) || |
6598 | S.ObjC().CheckConversionToObjCLiteral(DstType: DestType, SrcExpr&: Initializer)) |
6599 | Args[0] = Initializer; |
6600 | } |
6601 | if (!isa<InitListExpr>(Val: Initializer)) |
6602 | SourceType = Initializer->getType(); |
6603 | } |
6604 | |
6605 | // - If the initializer is a (non-parenthesized) braced-init-list, the |
6606 | // object is list-initialized (8.5.4). |
6607 | if (Kind.getKind() != InitializationKind::IK_Direct) { |
6608 | if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Val: Initializer)) { |
6609 | TryListInitialization(S, Entity, Kind, InitList, Sequence&: *this, |
6610 | TreatUnavailableAsInvalid); |
6611 | return; |
6612 | } |
6613 | } |
6614 | |
6615 | if (!S.getLangOpts().CPlusPlus && |
6616 | Kind.getKind() == InitializationKind::IK_Default) { |
6617 | if (RecordDecl *Rec = DestType->getAsRecordDecl()) { |
6618 | VarDecl *Var = dyn_cast_or_null<VarDecl>(Val: Entity.getDecl()); |
6619 | if (Rec->hasUninitializedExplicitInitFields()) { |
6620 | if (Var && !Initializer) { |
6621 | S.Diag(Loc: Var->getLocation(), DiagID: diag::warn_field_requires_explicit_init) |
6622 | << /* Var-in-Record */ 1 << Rec; |
6623 | emitUninitializedExplicitInitFields(S, R: Rec); |
6624 | } |
6625 | } |
6626 | // If the record has any members which are const (recursively checked), |
6627 | // then we want to diagnose those as being uninitialized if there is no |
6628 | // initializer present. However, we only do this for structure types, not |
6629 | // union types, because an unitialized field in a union is generally |
6630 | // reasonable, especially in C where unions can be used for type punning. |
6631 | if (Var && !Initializer && !Rec->isUnion() && !Rec->isInvalidDecl()) { |
6632 | if (const FieldDecl *FD = getConstField(RD: Rec)) { |
6633 | unsigned DiagID = diag::warn_default_init_const_field_unsafe; |
6634 | if (Var->getStorageDuration() == SD_Static || |
6635 | Var->getStorageDuration() == SD_Thread) |
6636 | DiagID = diag::warn_default_init_const_field; |
6637 | |
6638 | bool EmitCppCompat = !S.Diags.isIgnored( |
6639 | DiagID: diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit, |
6640 | Loc: Var->getLocation()); |
6641 | |
6642 | S.Diag(Loc: Var->getLocation(), DiagID) << Var->getType() << EmitCppCompat; |
6643 | S.Diag(Loc: FD->getLocation(), DiagID: diag::note_default_init_const_member) << FD; |
6644 | } |
6645 | } |
6646 | } |
6647 | } |
6648 | |
6649 | // - If the destination type is a reference type, see 8.5.3. |
6650 | if (DestType->isReferenceType()) { |
6651 | // C++0x [dcl.init.ref]p1: |
6652 | // A variable declared to be a T& or T&&, that is, "reference to type T" |
6653 | // (8.3.2), shall be initialized by an object, or function, of type T or |
6654 | // by an object that can be converted into a T. |
6655 | // (Therefore, multiple arguments are not permitted.) |
6656 | if (Args.size() != 1) |
6657 | SetFailed(FK_TooManyInitsForReference); |
6658 | // C++17 [dcl.init.ref]p5: |
6659 | // A reference [...] is initialized by an expression [...] as follows: |
6660 | // If the initializer is not an expression, presumably we should reject, |
6661 | // but the standard fails to actually say so. |
6662 | else if (isa<InitListExpr>(Val: Args[0])) |
6663 | SetFailed(FK_ParenthesizedListInitForReference); |
6664 | else |
6665 | TryReferenceInitialization(S, Entity, Kind, Initializer: Args[0], Sequence&: *this, |
6666 | TopLevelOfInitList); |
6667 | return; |
6668 | } |
6669 | |
6670 | // - If the initializer is (), the object is value-initialized. |
6671 | if (Kind.getKind() == InitializationKind::IK_Value || |
6672 | (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) { |
6673 | TryValueInitialization(S, Entity, Kind, Sequence&: *this); |
6674 | return; |
6675 | } |
6676 | |
6677 | // Handle default initialization. |
6678 | if (Kind.getKind() == InitializationKind::IK_Default) { |
6679 | TryDefaultInitialization(S, Entity, Kind, Sequence&: *this); |
6680 | return; |
6681 | } |
6682 | |
6683 | // - If the destination type is an array of characters, an array of |
6684 | // char16_t, an array of char32_t, or an array of wchar_t, and the |
6685 | // initializer is a string literal, see 8.5.2. |
6686 | // - Otherwise, if the destination type is an array, the program is |
6687 | // ill-formed. |
6688 | // - Except in HLSL, where non-decaying array parameters behave like |
6689 | // non-array types for initialization. |
6690 | if (DestType->isArrayType() && !DestType->isArrayParameterType()) { |
6691 | const ArrayType *DestAT = Context.getAsArrayType(T: DestType); |
6692 | if (Initializer && isa<VariableArrayType>(Val: DestAT)) { |
6693 | SetFailed(FK_VariableLengthArrayHasInitializer); |
6694 | return; |
6695 | } |
6696 | |
6697 | if (Initializer) { |
6698 | switch (IsStringInit(Init: Initializer, AT: DestAT, Context)) { |
6699 | case SIF_None: |
6700 | TryStringLiteralInitialization(S, Entity, Kind, Initializer, Sequence&: *this); |
6701 | return; |
6702 | case SIF_NarrowStringIntoWideChar: |
6703 | SetFailed(FK_NarrowStringIntoWideCharArray); |
6704 | return; |
6705 | case SIF_WideStringIntoChar: |
6706 | SetFailed(FK_WideStringIntoCharArray); |
6707 | return; |
6708 | case SIF_IncompatWideStringIntoWideChar: |
6709 | SetFailed(FK_IncompatWideStringIntoWideChar); |
6710 | return; |
6711 | case SIF_PlainStringIntoUTF8Char: |
6712 | SetFailed(FK_PlainStringIntoUTF8Char); |
6713 | return; |
6714 | case SIF_UTF8StringIntoPlainChar: |
6715 | SetFailed(FK_UTF8StringIntoPlainChar); |
6716 | return; |
6717 | case SIF_Other: |
6718 | break; |
6719 | } |
6720 | } |
6721 | |
6722 | if (S.getLangOpts().HLSL && Initializer && isa<ConstantArrayType>(Val: DestAT)) { |
6723 | QualType SrcType = Entity.getType(); |
6724 | if (SrcType->isArrayParameterType()) |
6725 | SrcType = |
6726 | cast<ArrayParameterType>(Val&: SrcType)->getConstantArrayType(Ctx: Context); |
6727 | if (S.Context.hasSameUnqualifiedType(T1: DestType, T2: SrcType)) { |
6728 | TryArrayCopy(S, Kind, Entity, Initializer, DestType, Sequence&: *this, |
6729 | TreatUnavailableAsInvalid); |
6730 | return; |
6731 | } |
6732 | } |
6733 | |
6734 | // Some kinds of initialization permit an array to be initialized from |
6735 | // another array of the same type, and perform elementwise initialization. |
6736 | if (Initializer && isa<ConstantArrayType>(Val: DestAT) && |
6737 | S.Context.hasSameUnqualifiedType(T1: Initializer->getType(), |
6738 | T2: Entity.getType()) && |
6739 | canPerformArrayCopy(Entity)) { |
6740 | TryArrayCopy(S, Kind, Entity, Initializer, DestType, Sequence&: *this, |
6741 | TreatUnavailableAsInvalid); |
6742 | return; |
6743 | } |
6744 | |
6745 | // Note: as an GNU C extension, we allow initialization of an |
6746 | // array from a compound literal that creates an array of the same |
6747 | // type, so long as the initializer has no side effects. |
6748 | if (!S.getLangOpts().CPlusPlus && Initializer && |
6749 | isa<CompoundLiteralExpr>(Val: Initializer->IgnoreParens()) && |
6750 | Initializer->getType()->isArrayType()) { |
6751 | const ArrayType *SourceAT |
6752 | = Context.getAsArrayType(T: Initializer->getType()); |
6753 | if (!hasCompatibleArrayTypes(Context&: S.Context, Dest: DestAT, Source: SourceAT)) |
6754 | SetFailed(FK_ArrayTypeMismatch); |
6755 | else if (Initializer->HasSideEffects(Ctx: S.Context)) |
6756 | SetFailed(FK_NonConstantArrayInit); |
6757 | else { |
6758 | AddArrayInitStep(T: DestType, /*IsGNUExtension*/true); |
6759 | } |
6760 | } |
6761 | // Note: as a GNU C++ extension, we allow list-initialization of a |
6762 | // class member of array type from a parenthesized initializer list. |
6763 | else if (S.getLangOpts().CPlusPlus && |
6764 | Entity.getKind() == InitializedEntity::EK_Member && |
6765 | isa_and_nonnull<InitListExpr>(Val: Initializer)) { |
6766 | TryListInitialization(S, Entity, Kind, InitList: cast<InitListExpr>(Val: Initializer), |
6767 | Sequence&: *this, TreatUnavailableAsInvalid); |
6768 | AddParenthesizedArrayInitStep(T: DestType); |
6769 | } else if (S.getLangOpts().CPlusPlus20 && !TopLevelOfInitList && |
6770 | Kind.getKind() == InitializationKind::IK_Direct) |
6771 | TryOrBuildParenListInitialization(S, Entity, Kind, Args, Sequence&: *this, |
6772 | /*VerifyOnly=*/true); |
6773 | else if (DestAT->getElementType()->isCharType()) |
6774 | SetFailed(FK_ArrayNeedsInitListOrStringLiteral); |
6775 | else if (IsWideCharCompatible(T: DestAT->getElementType(), Context)) |
6776 | SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral); |
6777 | else |
6778 | SetFailed(FK_ArrayNeedsInitList); |
6779 | |
6780 | return; |
6781 | } |
6782 | |
6783 | // Determine whether we should consider writeback conversions for |
6784 | // Objective-C ARC. |
6785 | bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount && |
6786 | Entity.isParameterKind(); |
6787 | |
6788 | if (TryOCLSamplerInitialization(S, Sequence&: *this, DestType, Initializer)) |
6789 | return; |
6790 | |
6791 | // We're at the end of the line for C: it's either a write-back conversion |
6792 | // or it's a C assignment. There's no need to check anything else. |
6793 | if (!S.getLangOpts().CPlusPlus) { |
6794 | assert(Initializer && "Initializer must be non-null" ); |
6795 | // If allowed, check whether this is an Objective-C writeback conversion. |
6796 | if (allowObjCWritebackConversion && |
6797 | tryObjCWritebackConversion(S, Sequence&: *this, Entity, Initializer)) { |
6798 | return; |
6799 | } |
6800 | |
6801 | if (TryOCLZeroOpaqueTypeInitialization(S, Sequence&: *this, DestType, Initializer)) |
6802 | return; |
6803 | |
6804 | // Handle initialization in C |
6805 | AddCAssignmentStep(T: DestType); |
6806 | MaybeProduceObjCObject(S, Sequence&: *this, Entity); |
6807 | return; |
6808 | } |
6809 | |
6810 | assert(S.getLangOpts().CPlusPlus); |
6811 | |
6812 | // - If the destination type is a (possibly cv-qualified) class type: |
6813 | if (DestType->isRecordType()) { |
6814 | // - If the initialization is direct-initialization, or if it is |
6815 | // copy-initialization where the cv-unqualified version of the |
6816 | // source type is the same class as, or a derived class of, the |
6817 | // class of the destination, constructors are considered. [...] |
6818 | if (Kind.getKind() == InitializationKind::IK_Direct || |
6819 | (Kind.getKind() == InitializationKind::IK_Copy && |
6820 | (Context.hasSameUnqualifiedType(T1: SourceType, T2: DestType) || |
6821 | (Initializer && S.IsDerivedFrom(Loc: Initializer->getBeginLoc(), |
6822 | Derived: SourceType, Base: DestType))))) { |
6823 | TryConstructorOrParenListInitialization(S, Entity, Kind, Args, DestType, |
6824 | Sequence&: *this, /*IsAggrListInit=*/false); |
6825 | } else { |
6826 | // - Otherwise (i.e., for the remaining copy-initialization cases), |
6827 | // user-defined conversion sequences that can convert from the |
6828 | // source type to the destination type or (when a conversion |
6829 | // function is used) to a derived class thereof are enumerated as |
6830 | // described in 13.3.1.4, and the best one is chosen through |
6831 | // overload resolution (13.3). |
6832 | assert(Initializer && "Initializer must be non-null" ); |
6833 | TryUserDefinedConversion(S, DestType, Kind, Initializer, Sequence&: *this, |
6834 | TopLevelOfInitList); |
6835 | } |
6836 | return; |
6837 | } |
6838 | |
6839 | assert(Args.size() >= 1 && "Zero-argument case handled above" ); |
6840 | |
6841 | // For HLSL ext vector types we allow list initialization behavior for C++ |
6842 | // constructor syntax. This is accomplished by converting initialization |
6843 | // arguments an InitListExpr late. |
6844 | if (S.getLangOpts().HLSL && Args.size() > 1 && DestType->isExtVectorType() && |
6845 | (SourceType.isNull() || |
6846 | !Context.hasSameUnqualifiedType(T1: SourceType, T2: DestType))) { |
6847 | |
6848 | llvm::SmallVector<Expr *> InitArgs; |
6849 | for (auto *Arg : Args) { |
6850 | if (Arg->getType()->isExtVectorType()) { |
6851 | const auto *VTy = Arg->getType()->castAs<ExtVectorType>(); |
6852 | unsigned Elm = VTy->getNumElements(); |
6853 | for (unsigned Idx = 0; Idx < Elm; ++Idx) { |
6854 | InitArgs.emplace_back(Args: new (Context) ArraySubscriptExpr( |
6855 | Arg, |
6856 | IntegerLiteral::Create( |
6857 | C: Context, V: llvm::APInt(Context.getIntWidth(T: Context.IntTy), Idx), |
6858 | type: Context.IntTy, l: SourceLocation()), |
6859 | VTy->getElementType(), Arg->getValueKind(), Arg->getObjectKind(), |
6860 | SourceLocation())); |
6861 | } |
6862 | } else |
6863 | InitArgs.emplace_back(Args&: Arg); |
6864 | } |
6865 | InitListExpr *ILE = new (Context) InitListExpr( |
6866 | S.getASTContext(), SourceLocation(), InitArgs, SourceLocation()); |
6867 | Args[0] = ILE; |
6868 | AddListInitializationStep(T: DestType); |
6869 | return; |
6870 | } |
6871 | |
6872 | // The remaining cases all need a source type. |
6873 | if (Args.size() > 1) { |
6874 | SetFailed(FK_TooManyInitsForScalar); |
6875 | return; |
6876 | } else if (isa<InitListExpr>(Val: Args[0])) { |
6877 | SetFailed(FK_ParenthesizedListInitForScalar); |
6878 | return; |
6879 | } |
6880 | |
6881 | // - Otherwise, if the source type is a (possibly cv-qualified) class |
6882 | // type, conversion functions are considered. |
6883 | if (!SourceType.isNull() && SourceType->isRecordType()) { |
6884 | assert(Initializer && "Initializer must be non-null" ); |
6885 | // For a conversion to _Atomic(T) from either T or a class type derived |
6886 | // from T, initialize the T object then convert to _Atomic type. |
6887 | bool NeedAtomicConversion = false; |
6888 | if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) { |
6889 | if (Context.hasSameUnqualifiedType(T1: SourceType, T2: Atomic->getValueType()) || |
6890 | S.IsDerivedFrom(Loc: Initializer->getBeginLoc(), Derived: SourceType, |
6891 | Base: Atomic->getValueType())) { |
6892 | DestType = Atomic->getValueType(); |
6893 | NeedAtomicConversion = true; |
6894 | } |
6895 | } |
6896 | |
6897 | TryUserDefinedConversion(S, DestType, Kind, Initializer, Sequence&: *this, |
6898 | TopLevelOfInitList); |
6899 | MaybeProduceObjCObject(S, Sequence&: *this, Entity); |
6900 | if (!Failed() && NeedAtomicConversion) |
6901 | AddAtomicConversionStep(Ty: Entity.getType()); |
6902 | return; |
6903 | } |
6904 | |
6905 | // - Otherwise, if the initialization is direct-initialization, the source |
6906 | // type is std::nullptr_t, and the destination type is bool, the initial |
6907 | // value of the object being initialized is false. |
6908 | if (!SourceType.isNull() && SourceType->isNullPtrType() && |
6909 | DestType->isBooleanType() && |
6910 | Kind.getKind() == InitializationKind::IK_Direct) { |
6911 | AddConversionSequenceStep( |
6912 | ICS: ImplicitConversionSequence::getNullptrToBool(SourceType, DestType, |
6913 | NeedLValToRVal: Initializer->isGLValue()), |
6914 | T: DestType); |
6915 | return; |
6916 | } |
6917 | |
6918 | // - Otherwise, the initial value of the object being initialized is the |
6919 | // (possibly converted) value of the initializer expression. Standard |
6920 | // conversions (Clause 4) will be used, if necessary, to convert the |
6921 | // initializer expression to the cv-unqualified version of the |
6922 | // destination type; no user-defined conversions are considered. |
6923 | |
6924 | ImplicitConversionSequence ICS |
6925 | = S.TryImplicitConversion(From: Initializer, ToType: DestType, |
6926 | /*SuppressUserConversions*/true, |
6927 | AllowExplicit: Sema::AllowedExplicit::None, |
6928 | /*InOverloadResolution*/ false, |
6929 | /*CStyle=*/Kind.isCStyleOrFunctionalCast(), |
6930 | AllowObjCWritebackConversion: allowObjCWritebackConversion); |
6931 | |
6932 | if (ICS.isStandard() && |
6933 | ICS.Standard.Second == ICK_Writeback_Conversion) { |
6934 | // Objective-C ARC writeback conversion. |
6935 | |
6936 | // We should copy unless we're passing to an argument explicitly |
6937 | // marked 'out'. |
6938 | bool ShouldCopy = true; |
6939 | if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Val: Entity.getDecl())) |
6940 | ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); |
6941 | |
6942 | // If there was an lvalue adjustment, add it as a separate conversion. |
6943 | if (ICS.Standard.First == ICK_Array_To_Pointer || |
6944 | ICS.Standard.First == ICK_Lvalue_To_Rvalue) { |
6945 | ImplicitConversionSequence LvalueICS; |
6946 | LvalueICS.setStandard(); |
6947 | LvalueICS.Standard.setAsIdentityConversion(); |
6948 | LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(Idx: 0)); |
6949 | LvalueICS.Standard.First = ICS.Standard.First; |
6950 | AddConversionSequenceStep(ICS: LvalueICS, T: ICS.Standard.getToType(Idx: 0)); |
6951 | } |
6952 | |
6953 | AddPassByIndirectCopyRestoreStep(type: DestType, shouldCopy: ShouldCopy); |
6954 | } else if (ICS.isBad()) { |
6955 | if (DeclAccessPair Found; |
6956 | Initializer->getType() == Context.OverloadTy && |
6957 | !S.ResolveAddressOfOverloadedFunction(AddressOfExpr: Initializer, TargetType: DestType, |
6958 | /*Complain=*/false, Found)) |
6959 | SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); |
6960 | else if (Initializer->getType()->isFunctionType() && |
6961 | isExprAnUnaddressableFunction(S, E: Initializer)) |
6962 | SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction); |
6963 | else |
6964 | SetFailed(InitializationSequence::FK_ConversionFailed); |
6965 | } else { |
6966 | AddConversionSequenceStep(ICS, T: DestType, TopLevelOfInitList); |
6967 | |
6968 | MaybeProduceObjCObject(S, Sequence&: *this, Entity); |
6969 | } |
6970 | } |
6971 | |
6972 | InitializationSequence::~InitializationSequence() { |
6973 | for (auto &S : Steps) |
6974 | S.Destroy(); |
6975 | } |
6976 | |
6977 | //===----------------------------------------------------------------------===// |
6978 | // Perform initialization |
6979 | //===----------------------------------------------------------------------===// |
6980 | static AssignmentAction getAssignmentAction(const InitializedEntity &Entity, |
6981 | bool Diagnose = false) { |
6982 | switch(Entity.getKind()) { |
6983 | case InitializedEntity::EK_Variable: |
6984 | case InitializedEntity::EK_New: |
6985 | case InitializedEntity::EK_Exception: |
6986 | case InitializedEntity::EK_Base: |
6987 | case InitializedEntity::EK_Delegating: |
6988 | return AssignmentAction::Initializing; |
6989 | |
6990 | case InitializedEntity::EK_Parameter: |
6991 | if (Entity.getDecl() && |
6992 | isa<ObjCMethodDecl>(Val: Entity.getDecl()->getDeclContext())) |
6993 | return AssignmentAction::Sending; |
6994 | |
6995 | return AssignmentAction::Passing; |
6996 | |
6997 | case InitializedEntity::EK_Parameter_CF_Audited: |
6998 | if (Entity.getDecl() && |
6999 | isa<ObjCMethodDecl>(Val: Entity.getDecl()->getDeclContext())) |
7000 | return AssignmentAction::Sending; |
7001 | |
7002 | return !Diagnose ? AssignmentAction::Passing |
7003 | : AssignmentAction::Passing_CFAudited; |
7004 | |
7005 | case InitializedEntity::EK_Result: |
7006 | case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right. |
7007 | return AssignmentAction::Returning; |
7008 | |
7009 | case InitializedEntity::EK_Temporary: |
7010 | case InitializedEntity::EK_RelatedResult: |
7011 | // FIXME: Can we tell apart casting vs. converting? |
7012 | return AssignmentAction::Casting; |
7013 | |
7014 | case InitializedEntity::EK_TemplateParameter: |
7015 | // This is really initialization, but refer to it as conversion for |
7016 | // consistency with CheckConvertedConstantExpression. |
7017 | return AssignmentAction::Converting; |
7018 | |
7019 | case InitializedEntity::EK_Member: |
7020 | case InitializedEntity::EK_ParenAggInitMember: |
7021 | case InitializedEntity::EK_Binding: |
7022 | case InitializedEntity::EK_ArrayElement: |
7023 | case InitializedEntity::EK_VectorElement: |
7024 | case InitializedEntity::EK_ComplexElement: |
7025 | case InitializedEntity::EK_BlockElement: |
7026 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: |
7027 | case InitializedEntity::EK_LambdaCapture: |
7028 | case InitializedEntity::EK_CompoundLiteralInit: |
7029 | return AssignmentAction::Initializing; |
7030 | } |
7031 | |
7032 | llvm_unreachable("Invalid EntityKind!" ); |
7033 | } |
7034 | |
7035 | /// Whether we should bind a created object as a temporary when |
7036 | /// initializing the given entity. |
7037 | static bool shouldBindAsTemporary(const InitializedEntity &Entity) { |
7038 | switch (Entity.getKind()) { |
7039 | case InitializedEntity::EK_ArrayElement: |
7040 | case InitializedEntity::EK_Member: |
7041 | case InitializedEntity::EK_ParenAggInitMember: |
7042 | case InitializedEntity::EK_Result: |
7043 | case InitializedEntity::EK_StmtExprResult: |
7044 | case InitializedEntity::EK_New: |
7045 | case InitializedEntity::EK_Variable: |
7046 | case InitializedEntity::EK_Base: |
7047 | case InitializedEntity::EK_Delegating: |
7048 | case InitializedEntity::EK_VectorElement: |
7049 | case InitializedEntity::EK_ComplexElement: |
7050 | case InitializedEntity::EK_Exception: |
7051 | case InitializedEntity::EK_BlockElement: |
7052 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: |
7053 | case InitializedEntity::EK_LambdaCapture: |
7054 | case InitializedEntity::EK_CompoundLiteralInit: |
7055 | case InitializedEntity::EK_TemplateParameter: |
7056 | return false; |
7057 | |
7058 | case InitializedEntity::EK_Parameter: |
7059 | case InitializedEntity::EK_Parameter_CF_Audited: |
7060 | case InitializedEntity::EK_Temporary: |
7061 | case InitializedEntity::EK_RelatedResult: |
7062 | case InitializedEntity::EK_Binding: |
7063 | return true; |
7064 | } |
7065 | |
7066 | llvm_unreachable("missed an InitializedEntity kind?" ); |
7067 | } |
7068 | |
7069 | /// Whether the given entity, when initialized with an object |
7070 | /// created for that initialization, requires destruction. |
7071 | static bool shouldDestroyEntity(const InitializedEntity &Entity) { |
7072 | switch (Entity.getKind()) { |
7073 | case InitializedEntity::EK_Result: |
7074 | case InitializedEntity::EK_StmtExprResult: |
7075 | case InitializedEntity::EK_New: |
7076 | case InitializedEntity::EK_Base: |
7077 | case InitializedEntity::EK_Delegating: |
7078 | case InitializedEntity::EK_VectorElement: |
7079 | case InitializedEntity::EK_ComplexElement: |
7080 | case InitializedEntity::EK_BlockElement: |
7081 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: |
7082 | case InitializedEntity::EK_LambdaCapture: |
7083 | return false; |
7084 | |
7085 | case InitializedEntity::EK_Member: |
7086 | case InitializedEntity::EK_ParenAggInitMember: |
7087 | case InitializedEntity::EK_Binding: |
7088 | case InitializedEntity::EK_Variable: |
7089 | case InitializedEntity::EK_Parameter: |
7090 | case InitializedEntity::EK_Parameter_CF_Audited: |
7091 | case InitializedEntity::EK_TemplateParameter: |
7092 | case InitializedEntity::EK_Temporary: |
7093 | case InitializedEntity::EK_ArrayElement: |
7094 | case InitializedEntity::EK_Exception: |
7095 | case InitializedEntity::EK_CompoundLiteralInit: |
7096 | case InitializedEntity::EK_RelatedResult: |
7097 | return true; |
7098 | } |
7099 | |
7100 | llvm_unreachable("missed an InitializedEntity kind?" ); |
7101 | } |
7102 | |
7103 | /// Get the location at which initialization diagnostics should appear. |
7104 | static SourceLocation getInitializationLoc(const InitializedEntity &Entity, |
7105 | Expr *Initializer) { |
7106 | switch (Entity.getKind()) { |
7107 | case InitializedEntity::EK_Result: |
7108 | case InitializedEntity::EK_StmtExprResult: |
7109 | return Entity.getReturnLoc(); |
7110 | |
7111 | case InitializedEntity::EK_Exception: |
7112 | return Entity.getThrowLoc(); |
7113 | |
7114 | case InitializedEntity::EK_Variable: |
7115 | case InitializedEntity::EK_Binding: |
7116 | return Entity.getDecl()->getLocation(); |
7117 | |
7118 | case InitializedEntity::EK_LambdaCapture: |
7119 | return Entity.getCaptureLoc(); |
7120 | |
7121 | case InitializedEntity::EK_ArrayElement: |
7122 | case InitializedEntity::EK_Member: |
7123 | case InitializedEntity::EK_ParenAggInitMember: |
7124 | case InitializedEntity::EK_Parameter: |
7125 | case InitializedEntity::EK_Parameter_CF_Audited: |
7126 | case InitializedEntity::EK_TemplateParameter: |
7127 | case InitializedEntity::EK_Temporary: |
7128 | case InitializedEntity::EK_New: |
7129 | case InitializedEntity::EK_Base: |
7130 | case InitializedEntity::EK_Delegating: |
7131 | case InitializedEntity::EK_VectorElement: |
7132 | case InitializedEntity::EK_ComplexElement: |
7133 | case InitializedEntity::EK_BlockElement: |
7134 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: |
7135 | case InitializedEntity::EK_CompoundLiteralInit: |
7136 | case InitializedEntity::EK_RelatedResult: |
7137 | return Initializer->getBeginLoc(); |
7138 | } |
7139 | llvm_unreachable("missed an InitializedEntity kind?" ); |
7140 | } |
7141 | |
7142 | /// Make a (potentially elidable) temporary copy of the object |
7143 | /// provided by the given initializer by calling the appropriate copy |
7144 | /// constructor. |
7145 | /// |
7146 | /// \param S The Sema object used for type-checking. |
7147 | /// |
7148 | /// \param T The type of the temporary object, which must either be |
7149 | /// the type of the initializer expression or a superclass thereof. |
7150 | /// |
7151 | /// \param Entity The entity being initialized. |
7152 | /// |
7153 | /// \param CurInit The initializer expression. |
7154 | /// |
7155 | /// \param IsExtraneousCopy Whether this is an "extraneous" copy that |
7156 | /// is permitted in C++03 (but not C++0x) when binding a reference to |
7157 | /// an rvalue. |
7158 | /// |
7159 | /// \returns An expression that copies the initializer expression into |
7160 | /// a temporary object, or an error expression if a copy could not be |
7161 | /// created. |
7162 | static ExprResult CopyObject(Sema &S, |
7163 | QualType T, |
7164 | const InitializedEntity &Entity, |
7165 | ExprResult CurInit, |
7166 | bool ) { |
7167 | if (CurInit.isInvalid()) |
7168 | return CurInit; |
7169 | // Determine which class type we're copying to. |
7170 | Expr *CurInitExpr = (Expr *)CurInit.get(); |
7171 | CXXRecordDecl *Class = nullptr; |
7172 | if (const RecordType *Record = T->getAs<RecordType>()) |
7173 | Class = cast<CXXRecordDecl>(Val: Record->getDecl()); |
7174 | if (!Class) |
7175 | return CurInit; |
7176 | |
7177 | SourceLocation Loc = getInitializationLoc(Entity, Initializer: CurInit.get()); |
7178 | |
7179 | // Make sure that the type we are copying is complete. |
7180 | if (S.RequireCompleteType(Loc, T, DiagID: diag::err_temp_copy_incomplete)) |
7181 | return CurInit; |
7182 | |
7183 | // Perform overload resolution using the class's constructors. Per |
7184 | // C++11 [dcl.init]p16, second bullet for class types, this initialization |
7185 | // is direct-initialization. |
7186 | OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); |
7187 | DeclContext::lookup_result Ctors = S.LookupConstructors(Class); |
7188 | |
7189 | OverloadCandidateSet::iterator Best; |
7190 | switch (ResolveConstructorOverload( |
7191 | S, DeclLoc: Loc, Args: CurInitExpr, CandidateSet, DestType: T, Ctors, Best, |
7192 | /*CopyInitializing=*/false, /*AllowExplicit=*/true, |
7193 | /*OnlyListConstructors=*/false, /*IsListInit=*/false, |
7194 | /*RequireActualConstructor=*/false, |
7195 | /*SecondStepOfCopyInit=*/true)) { |
7196 | case OR_Success: |
7197 | break; |
7198 | |
7199 | case OR_No_Viable_Function: |
7200 | CandidateSet.NoteCandidates( |
7201 | PA: PartialDiagnosticAt( |
7202 | Loc, S.PDiag(DiagID: IsExtraneousCopy && !S.isSFINAEContext() |
7203 | ? diag::ext_rvalue_to_reference_temp_copy_no_viable |
7204 | : diag::err_temp_copy_no_viable) |
7205 | << (int)Entity.getKind() << CurInitExpr->getType() |
7206 | << CurInitExpr->getSourceRange()), |
7207 | S, OCD: OCD_AllCandidates, Args: CurInitExpr); |
7208 | if (!IsExtraneousCopy || S.isSFINAEContext()) |
7209 | return ExprError(); |
7210 | return CurInit; |
7211 | |
7212 | case OR_Ambiguous: |
7213 | CandidateSet.NoteCandidates( |
7214 | PA: PartialDiagnosticAt(Loc, S.PDiag(DiagID: diag::err_temp_copy_ambiguous) |
7215 | << (int)Entity.getKind() |
7216 | << CurInitExpr->getType() |
7217 | << CurInitExpr->getSourceRange()), |
7218 | S, OCD: OCD_AmbiguousCandidates, Args: CurInitExpr); |
7219 | return ExprError(); |
7220 | |
7221 | case OR_Deleted: |
7222 | S.Diag(Loc, DiagID: diag::err_temp_copy_deleted) |
7223 | << (int)Entity.getKind() << CurInitExpr->getType() |
7224 | << CurInitExpr->getSourceRange(); |
7225 | S.NoteDeletedFunction(FD: Best->Function); |
7226 | return ExprError(); |
7227 | } |
7228 | |
7229 | bool HadMultipleCandidates = CandidateSet.size() > 1; |
7230 | |
7231 | CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Val: Best->Function); |
7232 | SmallVector<Expr*, 8> ConstructorArgs; |
7233 | CurInit.get(); // Ownership transferred into MultiExprArg, below. |
7234 | |
7235 | S.CheckConstructorAccess(Loc, D: Constructor, FoundDecl: Best->FoundDecl, Entity, |
7236 | IsCopyBindingRefToTemp: IsExtraneousCopy); |
7237 | |
7238 | if (IsExtraneousCopy) { |
7239 | // If this is a totally extraneous copy for C++03 reference |
7240 | // binding purposes, just return the original initialization |
7241 | // expression. We don't generate an (elided) copy operation here |
7242 | // because doing so would require us to pass down a flag to avoid |
7243 | // infinite recursion, where each step adds another extraneous, |
7244 | // elidable copy. |
7245 | |
7246 | // Instantiate the default arguments of any extra parameters in |
7247 | // the selected copy constructor, as if we were going to create a |
7248 | // proper call to the copy constructor. |
7249 | for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) { |
7250 | ParmVarDecl *Parm = Constructor->getParamDecl(i: I); |
7251 | if (S.RequireCompleteType(Loc, T: Parm->getType(), |
7252 | DiagID: diag::err_call_incomplete_argument)) |
7253 | break; |
7254 | |
7255 | // Build the default argument expression; we don't actually care |
7256 | // if this succeeds or not, because this routine will complain |
7257 | // if there was a problem. |
7258 | S.BuildCXXDefaultArgExpr(CallLoc: Loc, FD: Constructor, Param: Parm); |
7259 | } |
7260 | |
7261 | return CurInitExpr; |
7262 | } |
7263 | |
7264 | // Determine the arguments required to actually perform the |
7265 | // constructor call (we might have derived-to-base conversions, or |
7266 | // the copy constructor may have default arguments). |
7267 | if (S.CompleteConstructorCall(Constructor, DeclInitType: T, ArgsPtr: CurInitExpr, Loc, |
7268 | ConvertedArgs&: ConstructorArgs)) |
7269 | return ExprError(); |
7270 | |
7271 | // C++0x [class.copy]p32: |
7272 | // When certain criteria are met, an implementation is allowed to |
7273 | // omit the copy/move construction of a class object, even if the |
7274 | // copy/move constructor and/or destructor for the object have |
7275 | // side effects. [...] |
7276 | // - when a temporary class object that has not been bound to a |
7277 | // reference (12.2) would be copied/moved to a class object |
7278 | // with the same cv-unqualified type, the copy/move operation |
7279 | // can be omitted by constructing the temporary object |
7280 | // directly into the target of the omitted copy/move |
7281 | // |
7282 | // Note that the other three bullets are handled elsewhere. Copy |
7283 | // elision for return statements and throw expressions are handled as part |
7284 | // of constructor initialization, while copy elision for exception handlers |
7285 | // is handled by the run-time. |
7286 | // |
7287 | // FIXME: If the function parameter is not the same type as the temporary, we |
7288 | // should still be able to elide the copy, but we don't have a way to |
7289 | // represent in the AST how much should be elided in this case. |
7290 | bool Elidable = |
7291 | CurInitExpr->isTemporaryObject(Ctx&: S.Context, TempTy: Class) && |
7292 | S.Context.hasSameUnqualifiedType( |
7293 | T1: Best->Function->getParamDecl(i: 0)->getType().getNonReferenceType(), |
7294 | T2: CurInitExpr->getType()); |
7295 | |
7296 | // Actually perform the constructor call. |
7297 | CurInit = S.BuildCXXConstructExpr( |
7298 | ConstructLoc: Loc, DeclInitType: T, FoundDecl: Best->FoundDecl, Constructor, Elidable, Exprs: ConstructorArgs, |
7299 | HadMultipleCandidates, |
7300 | /*ListInit*/ IsListInitialization: false, |
7301 | /*StdInitListInit*/ IsStdInitListInitialization: false, |
7302 | /*ZeroInit*/ RequiresZeroInit: false, ConstructKind: CXXConstructionKind::Complete, ParenRange: SourceRange()); |
7303 | |
7304 | // If we're supposed to bind temporaries, do so. |
7305 | if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity)) |
7306 | CurInit = S.MaybeBindToTemporary(E: CurInit.getAs<Expr>()); |
7307 | return CurInit; |
7308 | } |
7309 | |
7310 | /// Check whether elidable copy construction for binding a reference to |
7311 | /// a temporary would have succeeded if we were building in C++98 mode, for |
7312 | /// -Wc++98-compat. |
7313 | static void CheckCXX98CompatAccessibleCopy(Sema &S, |
7314 | const InitializedEntity &Entity, |
7315 | Expr *CurInitExpr) { |
7316 | assert(S.getLangOpts().CPlusPlus11); |
7317 | |
7318 | const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>(); |
7319 | if (!Record) |
7320 | return; |
7321 | |
7322 | SourceLocation Loc = getInitializationLoc(Entity, Initializer: CurInitExpr); |
7323 | if (S.Diags.isIgnored(DiagID: diag::warn_cxx98_compat_temp_copy, Loc)) |
7324 | return; |
7325 | |
7326 | // Find constructors which would have been considered. |
7327 | OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); |
7328 | DeclContext::lookup_result Ctors = |
7329 | S.LookupConstructors(Class: cast<CXXRecordDecl>(Val: Record->getDecl())); |
7330 | |
7331 | // Perform overload resolution. |
7332 | OverloadCandidateSet::iterator Best; |
7333 | OverloadingResult OR = ResolveConstructorOverload( |
7334 | S, DeclLoc: Loc, Args: CurInitExpr, CandidateSet, DestType: CurInitExpr->getType(), Ctors, Best, |
7335 | /*CopyInitializing=*/false, /*AllowExplicit=*/true, |
7336 | /*OnlyListConstructors=*/false, /*IsListInit=*/false, |
7337 | /*RequireActualConstructor=*/false, |
7338 | /*SecondStepOfCopyInit=*/true); |
7339 | |
7340 | PartialDiagnostic Diag = S.PDiag(DiagID: diag::warn_cxx98_compat_temp_copy) |
7341 | << OR << (int)Entity.getKind() << CurInitExpr->getType() |
7342 | << CurInitExpr->getSourceRange(); |
7343 | |
7344 | switch (OR) { |
7345 | case OR_Success: |
7346 | S.CheckConstructorAccess(Loc, D: cast<CXXConstructorDecl>(Val: Best->Function), |
7347 | FoundDecl: Best->FoundDecl, Entity, PDiag: Diag); |
7348 | // FIXME: Check default arguments as far as that's possible. |
7349 | break; |
7350 | |
7351 | case OR_No_Viable_Function: |
7352 | CandidateSet.NoteCandidates(PA: PartialDiagnosticAt(Loc, Diag), S, |
7353 | OCD: OCD_AllCandidates, Args: CurInitExpr); |
7354 | break; |
7355 | |
7356 | case OR_Ambiguous: |
7357 | CandidateSet.NoteCandidates(PA: PartialDiagnosticAt(Loc, Diag), S, |
7358 | OCD: OCD_AmbiguousCandidates, Args: CurInitExpr); |
7359 | break; |
7360 | |
7361 | case OR_Deleted: |
7362 | S.Diag(Loc, PD: Diag); |
7363 | S.NoteDeletedFunction(FD: Best->Function); |
7364 | break; |
7365 | } |
7366 | } |
7367 | |
7368 | void InitializationSequence::PrintInitLocationNote(Sema &S, |
7369 | const InitializedEntity &Entity) { |
7370 | if (Entity.isParamOrTemplateParamKind() && Entity.getDecl()) { |
7371 | if (Entity.getDecl()->getLocation().isInvalid()) |
7372 | return; |
7373 | |
7374 | if (Entity.getDecl()->getDeclName()) |
7375 | S.Diag(Loc: Entity.getDecl()->getLocation(), DiagID: diag::note_parameter_named_here) |
7376 | << Entity.getDecl()->getDeclName(); |
7377 | else |
7378 | S.Diag(Loc: Entity.getDecl()->getLocation(), DiagID: diag::note_parameter_here); |
7379 | } |
7380 | else if (Entity.getKind() == InitializedEntity::EK_RelatedResult && |
7381 | Entity.getMethodDecl()) |
7382 | S.Diag(Loc: Entity.getMethodDecl()->getLocation(), |
7383 | DiagID: diag::note_method_return_type_change) |
7384 | << Entity.getMethodDecl()->getDeclName(); |
7385 | } |
7386 | |
7387 | /// Returns true if the parameters describe a constructor initialization of |
7388 | /// an explicit temporary object, e.g. "Point(x, y)". |
7389 | static bool isExplicitTemporary(const InitializedEntity &Entity, |
7390 | const InitializationKind &Kind, |
7391 | unsigned NumArgs) { |
7392 | switch (Entity.getKind()) { |
7393 | case InitializedEntity::EK_Temporary: |
7394 | case InitializedEntity::EK_CompoundLiteralInit: |
7395 | case InitializedEntity::EK_RelatedResult: |
7396 | break; |
7397 | default: |
7398 | return false; |
7399 | } |
7400 | |
7401 | switch (Kind.getKind()) { |
7402 | case InitializationKind::IK_DirectList: |
7403 | return true; |
7404 | // FIXME: Hack to work around cast weirdness. |
7405 | case InitializationKind::IK_Direct: |
7406 | case InitializationKind::IK_Value: |
7407 | return NumArgs != 1; |
7408 | default: |
7409 | return false; |
7410 | } |
7411 | } |
7412 | |
7413 | static ExprResult |
7414 | PerformConstructorInitialization(Sema &S, |
7415 | const InitializedEntity &Entity, |
7416 | const InitializationKind &Kind, |
7417 | MultiExprArg Args, |
7418 | const InitializationSequence::Step& Step, |
7419 | bool &ConstructorInitRequiresZeroInit, |
7420 | bool IsListInitialization, |
7421 | bool IsStdInitListInitialization, |
7422 | SourceLocation LBraceLoc, |
7423 | SourceLocation RBraceLoc) { |
7424 | unsigned NumArgs = Args.size(); |
7425 | CXXConstructorDecl *Constructor |
7426 | = cast<CXXConstructorDecl>(Val: Step.Function.Function); |
7427 | bool HadMultipleCandidates = Step.Function.HadMultipleCandidates; |
7428 | |
7429 | // Build a call to the selected constructor. |
7430 | SmallVector<Expr*, 8> ConstructorArgs; |
7431 | SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid()) |
7432 | ? Kind.getEqualLoc() |
7433 | : Kind.getLocation(); |
7434 | |
7435 | if (Kind.getKind() == InitializationKind::IK_Default) { |
7436 | // Force even a trivial, implicit default constructor to be |
7437 | // semantically checked. We do this explicitly because we don't build |
7438 | // the definition for completely trivial constructors. |
7439 | assert(Constructor->getParent() && "No parent class for constructor." ); |
7440 | if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() && |
7441 | Constructor->isTrivial() && !Constructor->isUsed(CheckUsedAttr: false)) { |
7442 | S.runWithSufficientStackSpace(Loc, Fn: [&] { |
7443 | S.DefineImplicitDefaultConstructor(CurrentLocation: Loc, Constructor); |
7444 | }); |
7445 | } |
7446 | } |
7447 | |
7448 | ExprResult CurInit((Expr *)nullptr); |
7449 | |
7450 | // C++ [over.match.copy]p1: |
7451 | // - When initializing a temporary to be bound to the first parameter |
7452 | // of a constructor that takes a reference to possibly cv-qualified |
7453 | // T as its first argument, called with a single argument in the |
7454 | // context of direct-initialization, explicit conversion functions |
7455 | // are also considered. |
7456 | bool AllowExplicitConv = |
7457 | Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 && |
7458 | hasCopyOrMoveCtorParam(Ctx&: S.Context, |
7459 | Info: getConstructorInfo(ND: Step.Function.FoundDecl)); |
7460 | |
7461 | // A smart pointer constructed from a nullable pointer is nullable. |
7462 | if (NumArgs == 1 && !Kind.isExplicitCast()) |
7463 | S.diagnoseNullableToNonnullConversion( |
7464 | DstType: Entity.getType(), SrcType: Args.front()->getType(), Loc: Kind.getLocation()); |
7465 | |
7466 | // Determine the arguments required to actually perform the constructor |
7467 | // call. |
7468 | if (S.CompleteConstructorCall(Constructor, DeclInitType: Step.Type, ArgsPtr: Args, Loc, |
7469 | ConvertedArgs&: ConstructorArgs, AllowExplicit: AllowExplicitConv, |
7470 | IsListInitialization)) |
7471 | return ExprError(); |
7472 | |
7473 | if (isExplicitTemporary(Entity, Kind, NumArgs)) { |
7474 | // An explicitly-constructed temporary, e.g., X(1, 2). |
7475 | if (S.DiagnoseUseOfDecl(D: Step.Function.FoundDecl, Locs: Loc)) |
7476 | return ExprError(); |
7477 | |
7478 | if (Kind.getKind() == InitializationKind::IK_Value && |
7479 | Constructor->isImplicit()) { |
7480 | auto *RD = Step.Type.getCanonicalType()->getAsCXXRecordDecl(); |
7481 | if (RD && RD->isAggregate() && RD->hasUninitializedExplicitInitFields()) { |
7482 | unsigned I = 0; |
7483 | for (const FieldDecl *FD : RD->fields()) { |
7484 | if (I >= ConstructorArgs.size() && FD->hasAttr<ExplicitInitAttr>()) { |
7485 | S.Diag(Loc, DiagID: diag::warn_field_requires_explicit_init) |
7486 | << /* Var-in-Record */ 0 << FD; |
7487 | S.Diag(Loc: FD->getLocation(), DiagID: diag::note_entity_declared_at) << FD; |
7488 | } |
7489 | ++I; |
7490 | } |
7491 | } |
7492 | } |
7493 | |
7494 | TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo(); |
7495 | if (!TSInfo) |
7496 | TSInfo = S.Context.getTrivialTypeSourceInfo(T: Entity.getType(), Loc); |
7497 | SourceRange ParenOrBraceRange = |
7498 | (Kind.getKind() == InitializationKind::IK_DirectList) |
7499 | ? SourceRange(LBraceLoc, RBraceLoc) |
7500 | : Kind.getParenOrBraceRange(); |
7501 | |
7502 | CXXConstructorDecl *CalleeDecl = Constructor; |
7503 | if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>( |
7504 | Val: Step.Function.FoundDecl.getDecl())) { |
7505 | CalleeDecl = S.findInheritingConstructor(Loc, BaseCtor: Constructor, DerivedShadow: Shadow); |
7506 | } |
7507 | S.MarkFunctionReferenced(Loc, Func: CalleeDecl); |
7508 | |
7509 | CurInit = S.CheckForImmediateInvocation( |
7510 | E: CXXTemporaryObjectExpr::Create( |
7511 | Ctx: S.Context, Cons: CalleeDecl, |
7512 | Ty: Entity.getType().getNonLValueExprType(Context: S.Context), TSI: TSInfo, |
7513 | Args: ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates, |
7514 | ListInitialization: IsListInitialization, StdInitListInitialization: IsStdInitListInitialization, |
7515 | ZeroInitialization: ConstructorInitRequiresZeroInit), |
7516 | Decl: CalleeDecl); |
7517 | } else { |
7518 | CXXConstructionKind ConstructKind = CXXConstructionKind::Complete; |
7519 | |
7520 | if (Entity.getKind() == InitializedEntity::EK_Base) { |
7521 | ConstructKind = Entity.getBaseSpecifier()->isVirtual() |
7522 | ? CXXConstructionKind::VirtualBase |
7523 | : CXXConstructionKind::NonVirtualBase; |
7524 | } else if (Entity.getKind() == InitializedEntity::EK_Delegating) { |
7525 | ConstructKind = CXXConstructionKind::Delegating; |
7526 | } |
7527 | |
7528 | // Only get the parenthesis or brace range if it is a list initialization or |
7529 | // direct construction. |
7530 | SourceRange ParenOrBraceRange; |
7531 | if (IsListInitialization) |
7532 | ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc); |
7533 | else if (Kind.getKind() == InitializationKind::IK_Direct) |
7534 | ParenOrBraceRange = Kind.getParenOrBraceRange(); |
7535 | |
7536 | // If the entity allows NRVO, mark the construction as elidable |
7537 | // unconditionally. |
7538 | if (Entity.allowsNRVO()) |
7539 | CurInit = S.BuildCXXConstructExpr(ConstructLoc: Loc, DeclInitType: Step.Type, |
7540 | FoundDecl: Step.Function.FoundDecl, |
7541 | Constructor, /*Elidable=*/true, |
7542 | Exprs: ConstructorArgs, |
7543 | HadMultipleCandidates, |
7544 | IsListInitialization, |
7545 | IsStdInitListInitialization, |
7546 | RequiresZeroInit: ConstructorInitRequiresZeroInit, |
7547 | ConstructKind, |
7548 | ParenRange: ParenOrBraceRange); |
7549 | else |
7550 | CurInit = S.BuildCXXConstructExpr(ConstructLoc: Loc, DeclInitType: Step.Type, |
7551 | FoundDecl: Step.Function.FoundDecl, |
7552 | Constructor, |
7553 | Exprs: ConstructorArgs, |
7554 | HadMultipleCandidates, |
7555 | IsListInitialization, |
7556 | IsStdInitListInitialization, |
7557 | RequiresZeroInit: ConstructorInitRequiresZeroInit, |
7558 | ConstructKind, |
7559 | ParenRange: ParenOrBraceRange); |
7560 | } |
7561 | if (CurInit.isInvalid()) |
7562 | return ExprError(); |
7563 | |
7564 | // Only check access if all of that succeeded. |
7565 | S.CheckConstructorAccess(Loc, D: Constructor, FoundDecl: Step.Function.FoundDecl, Entity); |
7566 | if (S.DiagnoseUseOfDecl(D: Step.Function.FoundDecl, Locs: Loc)) |
7567 | return ExprError(); |
7568 | |
7569 | if (const ArrayType *AT = S.Context.getAsArrayType(T: Entity.getType())) |
7570 | if (checkDestructorReference(ElementType: S.Context.getBaseElementType(VAT: AT), Loc, SemaRef&: S)) |
7571 | return ExprError(); |
7572 | |
7573 | if (shouldBindAsTemporary(Entity)) |
7574 | CurInit = S.MaybeBindToTemporary(E: CurInit.get()); |
7575 | |
7576 | return CurInit; |
7577 | } |
7578 | |
7579 | void Sema::checkInitializerLifetime(const InitializedEntity &Entity, |
7580 | Expr *Init) { |
7581 | return sema::checkInitLifetime(SemaRef&: *this, Entity, Init); |
7582 | } |
7583 | |
7584 | static void DiagnoseNarrowingInInitList(Sema &S, |
7585 | const ImplicitConversionSequence &ICS, |
7586 | QualType PreNarrowingType, |
7587 | QualType EntityType, |
7588 | const Expr *PostInit); |
7589 | |
7590 | static void CheckC23ConstexprInitConversion(Sema &S, QualType FromType, |
7591 | QualType ToType, Expr *Init); |
7592 | |
7593 | /// Provide warnings when std::move is used on construction. |
7594 | static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr, |
7595 | bool IsReturnStmt) { |
7596 | if (!InitExpr) |
7597 | return; |
7598 | |
7599 | if (S.inTemplateInstantiation()) |
7600 | return; |
7601 | |
7602 | QualType DestType = InitExpr->getType(); |
7603 | if (!DestType->isRecordType()) |
7604 | return; |
7605 | |
7606 | unsigned DiagID = 0; |
7607 | if (IsReturnStmt) { |
7608 | const CXXConstructExpr *CCE = |
7609 | dyn_cast<CXXConstructExpr>(Val: InitExpr->IgnoreParens()); |
7610 | if (!CCE || CCE->getNumArgs() != 1) |
7611 | return; |
7612 | |
7613 | if (!CCE->getConstructor()->isCopyOrMoveConstructor()) |
7614 | return; |
7615 | |
7616 | InitExpr = CCE->getArg(Arg: 0)->IgnoreImpCasts(); |
7617 | } |
7618 | |
7619 | // Find the std::move call and get the argument. |
7620 | const CallExpr *CE = dyn_cast<CallExpr>(Val: InitExpr->IgnoreParens()); |
7621 | if (!CE || !CE->isCallToStdMove()) |
7622 | return; |
7623 | |
7624 | const Expr *Arg = CE->getArg(Arg: 0)->IgnoreImplicit(); |
7625 | |
7626 | if (IsReturnStmt) { |
7627 | const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Arg->IgnoreParenImpCasts()); |
7628 | if (!DRE || DRE->refersToEnclosingVariableOrCapture()) |
7629 | return; |
7630 | |
7631 | const VarDecl *VD = dyn_cast<VarDecl>(Val: DRE->getDecl()); |
7632 | if (!VD || !VD->hasLocalStorage()) |
7633 | return; |
7634 | |
7635 | // __block variables are not moved implicitly. |
7636 | if (VD->hasAttr<BlocksAttr>()) |
7637 | return; |
7638 | |
7639 | QualType SourceType = VD->getType(); |
7640 | if (!SourceType->isRecordType()) |
7641 | return; |
7642 | |
7643 | if (!S.Context.hasSameUnqualifiedType(T1: DestType, T2: SourceType)) { |
7644 | return; |
7645 | } |
7646 | |
7647 | // If we're returning a function parameter, copy elision |
7648 | // is not possible. |
7649 | if (isa<ParmVarDecl>(Val: VD)) |
7650 | DiagID = diag::warn_redundant_move_on_return; |
7651 | else |
7652 | DiagID = diag::warn_pessimizing_move_on_return; |
7653 | } else { |
7654 | DiagID = diag::warn_pessimizing_move_on_initialization; |
7655 | const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens(); |
7656 | if (!ArgStripped->isPRValue() || !ArgStripped->getType()->isRecordType()) |
7657 | return; |
7658 | } |
7659 | |
7660 | S.Diag(Loc: CE->getBeginLoc(), DiagID); |
7661 | |
7662 | // Get all the locations for a fix-it. Don't emit the fix-it if any location |
7663 | // is within a macro. |
7664 | SourceLocation CallBegin = CE->getCallee()->getBeginLoc(); |
7665 | if (CallBegin.isMacroID()) |
7666 | return; |
7667 | SourceLocation RParen = CE->getRParenLoc(); |
7668 | if (RParen.isMacroID()) |
7669 | return; |
7670 | SourceLocation LParen; |
7671 | SourceLocation ArgLoc = Arg->getBeginLoc(); |
7672 | |
7673 | // Special testing for the argument location. Since the fix-it needs the |
7674 | // location right before the argument, the argument location can be in a |
7675 | // macro only if it is at the beginning of the macro. |
7676 | while (ArgLoc.isMacroID() && |
7677 | S.getSourceManager().isAtStartOfImmediateMacroExpansion(Loc: ArgLoc)) { |
7678 | ArgLoc = S.getSourceManager().getImmediateExpansionRange(Loc: ArgLoc).getBegin(); |
7679 | } |
7680 | |
7681 | if (LParen.isMacroID()) |
7682 | return; |
7683 | |
7684 | LParen = ArgLoc.getLocWithOffset(Offset: -1); |
7685 | |
7686 | S.Diag(Loc: CE->getBeginLoc(), DiagID: diag::note_remove_move) |
7687 | << FixItHint::CreateRemoval(RemoveRange: SourceRange(CallBegin, LParen)) |
7688 | << FixItHint::CreateRemoval(RemoveRange: SourceRange(RParen, RParen)); |
7689 | } |
7690 | |
7691 | static void CheckForNullPointerDereference(Sema &S, const Expr *E) { |
7692 | // Check to see if we are dereferencing a null pointer. If so, this is |
7693 | // undefined behavior, so warn about it. This only handles the pattern |
7694 | // "*null", which is a very syntactic check. |
7695 | if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: E->IgnoreParenCasts())) |
7696 | if (UO->getOpcode() == UO_Deref && |
7697 | UO->getSubExpr()->IgnoreParenCasts()-> |
7698 | isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNotNull)) { |
7699 | S.DiagRuntimeBehavior(Loc: UO->getOperatorLoc(), Statement: UO, |
7700 | PD: S.PDiag(DiagID: diag::warn_binding_null_to_reference) |
7701 | << UO->getSubExpr()->getSourceRange()); |
7702 | } |
7703 | } |
7704 | |
7705 | MaterializeTemporaryExpr * |
7706 | Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, |
7707 | bool BoundToLvalueReference) { |
7708 | auto MTE = new (Context) |
7709 | MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference); |
7710 | |
7711 | // Order an ExprWithCleanups for lifetime marks. |
7712 | // |
7713 | // TODO: It'll be good to have a single place to check the access of the |
7714 | // destructor and generate ExprWithCleanups for various uses. Currently these |
7715 | // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary, |
7716 | // but there may be a chance to merge them. |
7717 | Cleanup.setExprNeedsCleanups(false); |
7718 | if (isInLifetimeExtendingContext()) |
7719 | currentEvaluationContext().ForRangeLifetimeExtendTemps.push_back(Elt: MTE); |
7720 | return MTE; |
7721 | } |
7722 | |
7723 | ExprResult Sema::TemporaryMaterializationConversion(Expr *E) { |
7724 | // In C++98, we don't want to implicitly create an xvalue. C11 added the |
7725 | // same rule, but C99 is broken without this behavior and so we treat the |
7726 | // change as applying to all C language modes. |
7727 | // FIXME: This means that AST consumers need to deal with "prvalues" that |
7728 | // denote materialized temporaries. Maybe we should add another ValueKind |
7729 | // for "xvalue pretending to be a prvalue" for C++98 support. |
7730 | if (!E->isPRValue() || |
7731 | (!getLangOpts().CPlusPlus11 && getLangOpts().CPlusPlus)) |
7732 | return E; |
7733 | |
7734 | // C++1z [conv.rval]/1: T shall be a complete type. |
7735 | // FIXME: Does this ever matter (can we form a prvalue of incomplete type)? |
7736 | // If so, we should check for a non-abstract class type here too. |
7737 | QualType T = E->getType(); |
7738 | if (RequireCompleteType(Loc: E->getExprLoc(), T, DiagID: diag::err_incomplete_type)) |
7739 | return ExprError(); |
7740 | |
7741 | return CreateMaterializeTemporaryExpr(T: E->getType(), Temporary: E, BoundToLvalueReference: false); |
7742 | } |
7743 | |
7744 | ExprResult Sema::PerformQualificationConversion(Expr *E, QualType Ty, |
7745 | ExprValueKind VK, |
7746 | CheckedConversionKind CCK) { |
7747 | |
7748 | CastKind CK = CK_NoOp; |
7749 | |
7750 | if (VK == VK_PRValue) { |
7751 | auto PointeeTy = Ty->getPointeeType(); |
7752 | auto ExprPointeeTy = E->getType()->getPointeeType(); |
7753 | if (!PointeeTy.isNull() && |
7754 | PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace()) |
7755 | CK = CK_AddressSpaceConversion; |
7756 | } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) { |
7757 | CK = CK_AddressSpaceConversion; |
7758 | } |
7759 | |
7760 | return ImpCastExprToType(E, Type: Ty, CK, VK, /*BasePath=*/nullptr, CCK); |
7761 | } |
7762 | |
7763 | ExprResult InitializationSequence::Perform(Sema &S, |
7764 | const InitializedEntity &Entity, |
7765 | const InitializationKind &Kind, |
7766 | MultiExprArg Args, |
7767 | QualType *ResultType) { |
7768 | if (Failed()) { |
7769 | Diagnose(S, Entity, Kind, Args); |
7770 | return ExprError(); |
7771 | } |
7772 | if (!ZeroInitializationFixit.empty()) { |
7773 | const Decl *D = Entity.getDecl(); |
7774 | const auto *VD = dyn_cast_or_null<VarDecl>(Val: D); |
7775 | QualType DestType = Entity.getType(); |
7776 | |
7777 | // The initialization would have succeeded with this fixit. Since the fixit |
7778 | // is on the error, we need to build a valid AST in this case, so this isn't |
7779 | // handled in the Failed() branch above. |
7780 | if (!DestType->isRecordType() && VD && VD->isConstexpr()) { |
7781 | // Use a more useful diagnostic for constexpr variables. |
7782 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_constexpr_var_requires_const_init) |
7783 | << VD |
7784 | << FixItHint::CreateInsertion(InsertionLoc: ZeroInitializationFixitLoc, |
7785 | Code: ZeroInitializationFixit); |
7786 | } else { |
7787 | unsigned DiagID = diag::err_default_init_const; |
7788 | if (S.getLangOpts().MSVCCompat && D && D->hasAttr<SelectAnyAttr>()) |
7789 | DiagID = diag::ext_default_init_const; |
7790 | |
7791 | S.Diag(Loc: Kind.getLocation(), DiagID) |
7792 | << DestType << (bool)DestType->getAs<RecordType>() |
7793 | << FixItHint::CreateInsertion(InsertionLoc: ZeroInitializationFixitLoc, |
7794 | Code: ZeroInitializationFixit); |
7795 | } |
7796 | } |
7797 | |
7798 | if (getKind() == DependentSequence) { |
7799 | // If the declaration is a non-dependent, incomplete array type |
7800 | // that has an initializer, then its type will be completed once |
7801 | // the initializer is instantiated. |
7802 | if (ResultType && !Entity.getType()->isDependentType() && |
7803 | Args.size() == 1) { |
7804 | QualType DeclType = Entity.getType(); |
7805 | if (const IncompleteArrayType *ArrayT |
7806 | = S.Context.getAsIncompleteArrayType(T: DeclType)) { |
7807 | // FIXME: We don't currently have the ability to accurately |
7808 | // compute the length of an initializer list without |
7809 | // performing full type-checking of the initializer list |
7810 | // (since we have to determine where braces are implicitly |
7811 | // introduced and such). So, we fall back to making the array |
7812 | // type a dependently-sized array type with no specified |
7813 | // bound. |
7814 | if (isa<InitListExpr>(Val: (Expr *)Args[0])) |
7815 | *ResultType = S.Context.getDependentSizedArrayType( |
7816 | EltTy: ArrayT->getElementType(), |
7817 | /*NumElts=*/nullptr, ASM: ArrayT->getSizeModifier(), |
7818 | IndexTypeQuals: ArrayT->getIndexTypeCVRQualifiers()); |
7819 | } |
7820 | } |
7821 | if (Kind.getKind() == InitializationKind::IK_Direct && |
7822 | !Kind.isExplicitCast()) { |
7823 | // Rebuild the ParenListExpr. |
7824 | SourceRange ParenRange = Kind.getParenOrBraceRange(); |
7825 | return S.ActOnParenListExpr(L: ParenRange.getBegin(), R: ParenRange.getEnd(), |
7826 | Val: Args); |
7827 | } |
7828 | assert(Kind.getKind() == InitializationKind::IK_Copy || |
7829 | Kind.isExplicitCast() || |
7830 | Kind.getKind() == InitializationKind::IK_DirectList); |
7831 | return ExprResult(Args[0]); |
7832 | } |
7833 | |
7834 | // No steps means no initialization. |
7835 | if (Steps.empty()) |
7836 | return ExprResult((Expr *)nullptr); |
7837 | |
7838 | if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() && |
7839 | Args.size() == 1 && isa<InitListExpr>(Val: Args[0]) && |
7840 | !Entity.isParamOrTemplateParamKind()) { |
7841 | // Produce a C++98 compatibility warning if we are initializing a reference |
7842 | // from an initializer list. For parameters, we produce a better warning |
7843 | // elsewhere. |
7844 | Expr *Init = Args[0]; |
7845 | S.Diag(Loc: Init->getBeginLoc(), DiagID: diag::warn_cxx98_compat_reference_list_init) |
7846 | << Init->getSourceRange(); |
7847 | } |
7848 | |
7849 | if (S.getLangOpts().MicrosoftExt && Args.size() == 1 && |
7850 | isa<PredefinedExpr>(Val: Args[0]) && Entity.getType()->isArrayType()) { |
7851 | // Produce a Microsoft compatibility warning when initializing from a |
7852 | // predefined expression since MSVC treats predefined expressions as string |
7853 | // literals. |
7854 | Expr *Init = Args[0]; |
7855 | S.Diag(Loc: Init->getBeginLoc(), DiagID: diag::ext_init_from_predefined) << Init; |
7856 | } |
7857 | |
7858 | // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope |
7859 | QualType ETy = Entity.getType(); |
7860 | bool HasGlobalAS = ETy.hasAddressSpace() && |
7861 | ETy.getAddressSpace() == LangAS::opencl_global; |
7862 | |
7863 | if (S.getLangOpts().OpenCLVersion >= 200 && |
7864 | ETy->isAtomicType() && !HasGlobalAS && |
7865 | Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) { |
7866 | S.Diag(Loc: Args[0]->getBeginLoc(), DiagID: diag::err_opencl_atomic_init) |
7867 | << 1 |
7868 | << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc()); |
7869 | return ExprError(); |
7870 | } |
7871 | |
7872 | QualType DestType = Entity.getType().getNonReferenceType(); |
7873 | // FIXME: Ugly hack around the fact that Entity.getType() is not |
7874 | // the same as Entity.getDecl()->getType() in cases involving type merging, |
7875 | // and we want latter when it makes sense. |
7876 | if (ResultType) |
7877 | *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() : |
7878 | Entity.getType(); |
7879 | |
7880 | ExprResult CurInit((Expr *)nullptr); |
7881 | SmallVector<Expr*, 4> ArrayLoopCommonExprs; |
7882 | |
7883 | // HLSL allows vector initialization to function like list initialization, but |
7884 | // use the syntax of a C++-like constructor. |
7885 | bool IsHLSLVectorInit = S.getLangOpts().HLSL && DestType->isExtVectorType() && |
7886 | isa<InitListExpr>(Val: Args[0]); |
7887 | (void)IsHLSLVectorInit; |
7888 | |
7889 | // For initialization steps that start with a single initializer, |
7890 | // grab the only argument out the Args and place it into the "current" |
7891 | // initializer. |
7892 | switch (Steps.front().Kind) { |
7893 | case SK_ResolveAddressOfOverloadedFunction: |
7894 | case SK_CastDerivedToBasePRValue: |
7895 | case SK_CastDerivedToBaseXValue: |
7896 | case SK_CastDerivedToBaseLValue: |
7897 | case SK_BindReference: |
7898 | case SK_BindReferenceToTemporary: |
7899 | case SK_FinalCopy: |
7900 | case SK_ExtraneousCopyToTemporary: |
7901 | case SK_UserConversion: |
7902 | case SK_QualificationConversionLValue: |
7903 | case SK_QualificationConversionXValue: |
7904 | case SK_QualificationConversionPRValue: |
7905 | case SK_FunctionReferenceConversion: |
7906 | case SK_AtomicConversion: |
7907 | case SK_ConversionSequence: |
7908 | case SK_ConversionSequenceNoNarrowing: |
7909 | case SK_ListInitialization: |
7910 | case SK_UnwrapInitList: |
7911 | case SK_RewrapInitList: |
7912 | case SK_CAssignment: |
7913 | case SK_StringInit: |
7914 | case SK_ObjCObjectConversion: |
7915 | case SK_ArrayLoopIndex: |
7916 | case SK_ArrayLoopInit: |
7917 | case SK_ArrayInit: |
7918 | case SK_GNUArrayInit: |
7919 | case SK_ParenthesizedArrayInit: |
7920 | case SK_PassByIndirectCopyRestore: |
7921 | case SK_PassByIndirectRestore: |
7922 | case SK_ProduceObjCObject: |
7923 | case SK_StdInitializerList: |
7924 | case SK_OCLSamplerInit: |
7925 | case SK_OCLZeroOpaqueType: { |
7926 | assert(Args.size() == 1 || IsHLSLVectorInit); |
7927 | CurInit = Args[0]; |
7928 | if (!CurInit.get()) return ExprError(); |
7929 | break; |
7930 | } |
7931 | |
7932 | case SK_ConstructorInitialization: |
7933 | case SK_ConstructorInitializationFromList: |
7934 | case SK_StdInitializerListConstructorCall: |
7935 | case SK_ZeroInitialization: |
7936 | case SK_ParenthesizedListInit: |
7937 | break; |
7938 | } |
7939 | |
7940 | // Promote from an unevaluated context to an unevaluated list context in |
7941 | // C++11 list-initialization; we need to instantiate entities usable in |
7942 | // constant expressions here in order to perform narrowing checks =( |
7943 | EnterExpressionEvaluationContext Evaluated( |
7944 | S, EnterExpressionEvaluationContext::InitList, |
7945 | isa_and_nonnull<InitListExpr>(Val: CurInit.get())); |
7946 | |
7947 | // C++ [class.abstract]p2: |
7948 | // no objects of an abstract class can be created except as subobjects |
7949 | // of a class derived from it |
7950 | auto checkAbstractType = [&](QualType T) -> bool { |
7951 | if (Entity.getKind() == InitializedEntity::EK_Base || |
7952 | Entity.getKind() == InitializedEntity::EK_Delegating) |
7953 | return false; |
7954 | return S.RequireNonAbstractType(Loc: Kind.getLocation(), T, |
7955 | DiagID: diag::err_allocation_of_abstract_type); |
7956 | }; |
7957 | |
7958 | // Walk through the computed steps for the initialization sequence, |
7959 | // performing the specified conversions along the way. |
7960 | bool ConstructorInitRequiresZeroInit = false; |
7961 | for (step_iterator Step = step_begin(), StepEnd = step_end(); |
7962 | Step != StepEnd; ++Step) { |
7963 | if (CurInit.isInvalid()) |
7964 | return ExprError(); |
7965 | |
7966 | QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType(); |
7967 | |
7968 | switch (Step->Kind) { |
7969 | case SK_ResolveAddressOfOverloadedFunction: |
7970 | // Overload resolution determined which function invoke; update the |
7971 | // initializer to reflect that choice. |
7972 | S.CheckAddressOfMemberAccess(OvlExpr: CurInit.get(), FoundDecl: Step->Function.FoundDecl); |
7973 | if (S.DiagnoseUseOfDecl(D: Step->Function.FoundDecl, Locs: Kind.getLocation())) |
7974 | return ExprError(); |
7975 | CurInit = S.FixOverloadedFunctionReference(CurInit, |
7976 | FoundDecl: Step->Function.FoundDecl, |
7977 | Fn: Step->Function.Function); |
7978 | // We might get back another placeholder expression if we resolved to a |
7979 | // builtin. |
7980 | if (!CurInit.isInvalid()) |
7981 | CurInit = S.CheckPlaceholderExpr(E: CurInit.get()); |
7982 | break; |
7983 | |
7984 | case SK_CastDerivedToBasePRValue: |
7985 | case SK_CastDerivedToBaseXValue: |
7986 | case SK_CastDerivedToBaseLValue: { |
7987 | // We have a derived-to-base cast that produces either an rvalue or an |
7988 | // lvalue. Perform that cast. |
7989 | |
7990 | CXXCastPath BasePath; |
7991 | |
7992 | // Casts to inaccessible base classes are allowed with C-style casts. |
7993 | bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast(); |
7994 | if (S.CheckDerivedToBaseConversion( |
7995 | Derived: SourceType, Base: Step->Type, Loc: CurInit.get()->getBeginLoc(), |
7996 | Range: CurInit.get()->getSourceRange(), BasePath: &BasePath, IgnoreAccess: IgnoreBaseAccess)) |
7997 | return ExprError(); |
7998 | |
7999 | ExprValueKind VK = |
8000 | Step->Kind == SK_CastDerivedToBaseLValue |
8001 | ? VK_LValue |
8002 | : (Step->Kind == SK_CastDerivedToBaseXValue ? VK_XValue |
8003 | : VK_PRValue); |
8004 | CurInit = ImplicitCastExpr::Create(Context: S.Context, T: Step->Type, |
8005 | Kind: CK_DerivedToBase, Operand: CurInit.get(), |
8006 | BasePath: &BasePath, Cat: VK, FPO: FPOptionsOverride()); |
8007 | break; |
8008 | } |
8009 | |
8010 | case SK_BindReference: |
8011 | // Reference binding does not have any corresponding ASTs. |
8012 | |
8013 | // Check exception specifications |
8014 | if (S.CheckExceptionSpecCompatibility(From: CurInit.get(), ToType: DestType)) |
8015 | return ExprError(); |
8016 | |
8017 | // We don't check for e.g. function pointers here, since address |
8018 | // availability checks should only occur when the function first decays |
8019 | // into a pointer or reference. |
8020 | if (CurInit.get()->getType()->isFunctionProtoType()) { |
8021 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: CurInit.get()->IgnoreParens())) { |
8022 | if (auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl())) { |
8023 | if (!S.checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true, |
8024 | Loc: DRE->getBeginLoc())) |
8025 | return ExprError(); |
8026 | } |
8027 | } |
8028 | } |
8029 | |
8030 | CheckForNullPointerDereference(S, E: CurInit.get()); |
8031 | break; |
8032 | |
8033 | case SK_BindReferenceToTemporary: { |
8034 | // Make sure the "temporary" is actually an rvalue. |
8035 | assert(CurInit.get()->isPRValue() && "not a temporary" ); |
8036 | |
8037 | // Check exception specifications |
8038 | if (S.CheckExceptionSpecCompatibility(From: CurInit.get(), ToType: DestType)) |
8039 | return ExprError(); |
8040 | |
8041 | QualType MTETy = Step->Type; |
8042 | |
8043 | // When this is an incomplete array type (such as when this is |
8044 | // initializing an array of unknown bounds from an init list), use THAT |
8045 | // type instead so that we propagate the array bounds. |
8046 | if (MTETy->isIncompleteArrayType() && |
8047 | !CurInit.get()->getType()->isIncompleteArrayType() && |
8048 | S.Context.hasSameType( |
8049 | T1: MTETy->getPointeeOrArrayElementType(), |
8050 | T2: CurInit.get()->getType()->getPointeeOrArrayElementType())) |
8051 | MTETy = CurInit.get()->getType(); |
8052 | |
8053 | // Materialize the temporary into memory. |
8054 | MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr( |
8055 | T: MTETy, Temporary: CurInit.get(), BoundToLvalueReference: Entity.getType()->isLValueReferenceType()); |
8056 | CurInit = MTE; |
8057 | |
8058 | // If we're extending this temporary to automatic storage duration -- we |
8059 | // need to register its cleanup during the full-expression's cleanups. |
8060 | if (MTE->getStorageDuration() == SD_Automatic && |
8061 | MTE->getType().isDestructedType()) |
8062 | S.Cleanup.setExprNeedsCleanups(true); |
8063 | break; |
8064 | } |
8065 | |
8066 | case SK_FinalCopy: |
8067 | if (checkAbstractType(Step->Type)) |
8068 | return ExprError(); |
8069 | |
8070 | // If the overall initialization is initializing a temporary, we already |
8071 | // bound our argument if it was necessary to do so. If not (if we're |
8072 | // ultimately initializing a non-temporary), our argument needs to be |
8073 | // bound since it's initializing a function parameter. |
8074 | // FIXME: This is a mess. Rationalize temporary destruction. |
8075 | if (!shouldBindAsTemporary(Entity)) |
8076 | CurInit = S.MaybeBindToTemporary(E: CurInit.get()); |
8077 | CurInit = CopyObject(S, T: Step->Type, Entity, CurInit, |
8078 | /*IsExtraneousCopy=*/false); |
8079 | break; |
8080 | |
8081 | case SK_ExtraneousCopyToTemporary: |
8082 | CurInit = CopyObject(S, T: Step->Type, Entity, CurInit, |
8083 | /*IsExtraneousCopy=*/true); |
8084 | break; |
8085 | |
8086 | case SK_UserConversion: { |
8087 | // We have a user-defined conversion that invokes either a constructor |
8088 | // or a conversion function. |
8089 | CastKind CastKind; |
8090 | FunctionDecl *Fn = Step->Function.Function; |
8091 | DeclAccessPair FoundFn = Step->Function.FoundDecl; |
8092 | bool HadMultipleCandidates = Step->Function.HadMultipleCandidates; |
8093 | bool CreatedObject = false; |
8094 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Fn)) { |
8095 | // Build a call to the selected constructor. |
8096 | SmallVector<Expr*, 8> ConstructorArgs; |
8097 | SourceLocation Loc = CurInit.get()->getBeginLoc(); |
8098 | |
8099 | // Determine the arguments required to actually perform the constructor |
8100 | // call. |
8101 | Expr *Arg = CurInit.get(); |
8102 | if (S.CompleteConstructorCall(Constructor, DeclInitType: Step->Type, |
8103 | ArgsPtr: MultiExprArg(&Arg, 1), Loc, |
8104 | ConvertedArgs&: ConstructorArgs)) |
8105 | return ExprError(); |
8106 | |
8107 | // Build an expression that constructs a temporary. |
8108 | CurInit = S.BuildCXXConstructExpr( |
8109 | ConstructLoc: Loc, DeclInitType: Step->Type, FoundDecl: FoundFn, Constructor, Exprs: ConstructorArgs, |
8110 | HadMultipleCandidates, |
8111 | /*ListInit*/ IsListInitialization: false, |
8112 | /*StdInitListInit*/ IsStdInitListInitialization: false, |
8113 | /*ZeroInit*/ RequiresZeroInit: false, ConstructKind: CXXConstructionKind::Complete, ParenRange: SourceRange()); |
8114 | if (CurInit.isInvalid()) |
8115 | return ExprError(); |
8116 | |
8117 | S.CheckConstructorAccess(Loc: Kind.getLocation(), D: Constructor, FoundDecl: FoundFn, |
8118 | Entity); |
8119 | if (S.DiagnoseUseOfDecl(D: FoundFn, Locs: Kind.getLocation())) |
8120 | return ExprError(); |
8121 | |
8122 | CastKind = CK_ConstructorConversion; |
8123 | CreatedObject = true; |
8124 | } else { |
8125 | // Build a call to the conversion function. |
8126 | CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Val: Fn); |
8127 | S.CheckMemberOperatorAccess(Loc: Kind.getLocation(), ObjectExpr: CurInit.get(), ArgExpr: nullptr, |
8128 | FoundDecl: FoundFn); |
8129 | if (S.DiagnoseUseOfDecl(D: FoundFn, Locs: Kind.getLocation())) |
8130 | return ExprError(); |
8131 | |
8132 | CurInit = S.BuildCXXMemberCallExpr(Exp: CurInit.get(), FoundDecl: FoundFn, Method: Conversion, |
8133 | HadMultipleCandidates); |
8134 | if (CurInit.isInvalid()) |
8135 | return ExprError(); |
8136 | |
8137 | CastKind = CK_UserDefinedConversion; |
8138 | CreatedObject = Conversion->getReturnType()->isRecordType(); |
8139 | } |
8140 | |
8141 | if (CreatedObject && checkAbstractType(CurInit.get()->getType())) |
8142 | return ExprError(); |
8143 | |
8144 | CurInit = ImplicitCastExpr::Create( |
8145 | Context: S.Context, T: CurInit.get()->getType(), Kind: CastKind, Operand: CurInit.get(), BasePath: nullptr, |
8146 | Cat: CurInit.get()->getValueKind(), FPO: S.CurFPFeatureOverrides()); |
8147 | |
8148 | if (shouldBindAsTemporary(Entity)) |
8149 | // The overall entity is temporary, so this expression should be |
8150 | // destroyed at the end of its full-expression. |
8151 | CurInit = S.MaybeBindToTemporary(E: CurInit.getAs<Expr>()); |
8152 | else if (CreatedObject && shouldDestroyEntity(Entity)) { |
8153 | // The object outlasts the full-expression, but we need to prepare for |
8154 | // a destructor being run on it. |
8155 | // FIXME: It makes no sense to do this here. This should happen |
8156 | // regardless of how we initialized the entity. |
8157 | QualType T = CurInit.get()->getType(); |
8158 | if (const RecordType *Record = T->getAs<RecordType>()) { |
8159 | CXXDestructorDecl *Destructor |
8160 | = S.LookupDestructor(Class: cast<CXXRecordDecl>(Val: Record->getDecl())); |
8161 | S.CheckDestructorAccess(Loc: CurInit.get()->getBeginLoc(), Dtor: Destructor, |
8162 | PDiag: S.PDiag(DiagID: diag::err_access_dtor_temp) << T); |
8163 | S.MarkFunctionReferenced(Loc: CurInit.get()->getBeginLoc(), Func: Destructor); |
8164 | if (S.DiagnoseUseOfDecl(D: Destructor, Locs: CurInit.get()->getBeginLoc())) |
8165 | return ExprError(); |
8166 | } |
8167 | } |
8168 | break; |
8169 | } |
8170 | |
8171 | case SK_QualificationConversionLValue: |
8172 | case SK_QualificationConversionXValue: |
8173 | case SK_QualificationConversionPRValue: { |
8174 | // Perform a qualification conversion; these can never go wrong. |
8175 | ExprValueKind VK = |
8176 | Step->Kind == SK_QualificationConversionLValue |
8177 | ? VK_LValue |
8178 | : (Step->Kind == SK_QualificationConversionXValue ? VK_XValue |
8179 | : VK_PRValue); |
8180 | CurInit = S.PerformQualificationConversion(E: CurInit.get(), Ty: Step->Type, VK); |
8181 | break; |
8182 | } |
8183 | |
8184 | case SK_FunctionReferenceConversion: |
8185 | assert(CurInit.get()->isLValue() && |
8186 | "function reference should be lvalue" ); |
8187 | CurInit = |
8188 | S.ImpCastExprToType(E: CurInit.get(), Type: Step->Type, CK: CK_NoOp, VK: VK_LValue); |
8189 | break; |
8190 | |
8191 | case SK_AtomicConversion: { |
8192 | assert(CurInit.get()->isPRValue() && "cannot convert glvalue to atomic" ); |
8193 | CurInit = S.ImpCastExprToType(E: CurInit.get(), Type: Step->Type, |
8194 | CK: CK_NonAtomicToAtomic, VK: VK_PRValue); |
8195 | break; |
8196 | } |
8197 | |
8198 | case SK_ConversionSequence: |
8199 | case SK_ConversionSequenceNoNarrowing: { |
8200 | if (const auto *FromPtrType = |
8201 | CurInit.get()->getType()->getAs<PointerType>()) { |
8202 | if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) { |
8203 | if (FromPtrType->getPointeeType()->hasAttr(AK: attr::NoDeref) && |
8204 | !ToPtrType->getPointeeType()->hasAttr(AK: attr::NoDeref)) { |
8205 | // Do not check static casts here because they are checked earlier |
8206 | // in Sema::ActOnCXXNamedCast() |
8207 | if (!Kind.isStaticCast()) { |
8208 | S.Diag(Loc: CurInit.get()->getExprLoc(), |
8209 | DiagID: diag::warn_noderef_to_dereferenceable_pointer) |
8210 | << CurInit.get()->getSourceRange(); |
8211 | } |
8212 | } |
8213 | } |
8214 | } |
8215 | Expr *Init = CurInit.get(); |
8216 | CheckedConversionKind CCK = |
8217 | Kind.isCStyleCast() ? CheckedConversionKind::CStyleCast |
8218 | : Kind.isFunctionalCast() ? CheckedConversionKind::FunctionalCast |
8219 | : Kind.isExplicitCast() ? CheckedConversionKind::OtherCast |
8220 | : CheckedConversionKind::Implicit; |
8221 | ExprResult CurInitExprRes = S.PerformImplicitConversion( |
8222 | From: Init, ToType: Step->Type, ICS: *Step->ICS, Action: getAssignmentAction(Entity), CCK); |
8223 | if (CurInitExprRes.isInvalid()) |
8224 | return ExprError(); |
8225 | |
8226 | S.DiscardMisalignedMemberAddress(T: Step->Type.getTypePtr(), E: Init); |
8227 | |
8228 | CurInit = CurInitExprRes; |
8229 | |
8230 | if (Step->Kind == SK_ConversionSequenceNoNarrowing && |
8231 | S.getLangOpts().CPlusPlus) |
8232 | DiagnoseNarrowingInInitList(S, ICS: *Step->ICS, PreNarrowingType: SourceType, EntityType: Entity.getType(), |
8233 | PostInit: CurInit.get()); |
8234 | |
8235 | break; |
8236 | } |
8237 | |
8238 | case SK_ListInitialization: { |
8239 | if (checkAbstractType(Step->Type)) |
8240 | return ExprError(); |
8241 | |
8242 | InitListExpr *InitList = cast<InitListExpr>(Val: CurInit.get()); |
8243 | // If we're not initializing the top-level entity, we need to create an |
8244 | // InitializeTemporary entity for our target type. |
8245 | QualType Ty = Step->Type; |
8246 | bool IsTemporary = !S.Context.hasSameType(T1: Entity.getType(), T2: Ty); |
8247 | InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Type: Ty); |
8248 | InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity; |
8249 | InitListChecker PerformInitList(S, InitEntity, |
8250 | InitList, Ty, /*VerifyOnly=*/false, |
8251 | /*TreatUnavailableAsInvalid=*/false); |
8252 | if (PerformInitList.HadError()) |
8253 | return ExprError(); |
8254 | |
8255 | // Hack: We must update *ResultType if available in order to set the |
8256 | // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'. |
8257 | // Worst case: 'const int (&arref)[] = {1, 2, 3};'. |
8258 | if (ResultType && |
8259 | ResultType->getNonReferenceType()->isIncompleteArrayType()) { |
8260 | if ((*ResultType)->isRValueReferenceType()) |
8261 | Ty = S.Context.getRValueReferenceType(T: Ty); |
8262 | else if ((*ResultType)->isLValueReferenceType()) |
8263 | Ty = S.Context.getLValueReferenceType(T: Ty, |
8264 | SpelledAsLValue: (*ResultType)->castAs<LValueReferenceType>()->isSpelledAsLValue()); |
8265 | *ResultType = Ty; |
8266 | } |
8267 | |
8268 | InitListExpr *StructuredInitList = |
8269 | PerformInitList.getFullyStructuredList(); |
8270 | CurInit.get(); |
8271 | CurInit = shouldBindAsTemporary(Entity: InitEntity) |
8272 | ? S.MaybeBindToTemporary(E: StructuredInitList) |
8273 | : StructuredInitList; |
8274 | break; |
8275 | } |
8276 | |
8277 | case SK_ConstructorInitializationFromList: { |
8278 | if (checkAbstractType(Step->Type)) |
8279 | return ExprError(); |
8280 | |
8281 | // When an initializer list is passed for a parameter of type "reference |
8282 | // to object", we don't get an EK_Temporary entity, but instead an |
8283 | // EK_Parameter entity with reference type. |
8284 | // FIXME: This is a hack. What we really should do is create a user |
8285 | // conversion step for this case, but this makes it considerably more |
8286 | // complicated. For now, this will do. |
8287 | InitializedEntity TempEntity = InitializedEntity::InitializeTemporary( |
8288 | Type: Entity.getType().getNonReferenceType()); |
8289 | bool UseTemporary = Entity.getType()->isReferenceType(); |
8290 | assert(Args.size() == 1 && "expected a single argument for list init" ); |
8291 | InitListExpr *InitList = cast<InitListExpr>(Val: Args[0]); |
8292 | S.Diag(Loc: InitList->getExprLoc(), DiagID: diag::warn_cxx98_compat_ctor_list_init) |
8293 | << InitList->getSourceRange(); |
8294 | MultiExprArg Arg(InitList->getInits(), InitList->getNumInits()); |
8295 | CurInit = PerformConstructorInitialization(S, Entity: UseTemporary ? TempEntity : |
8296 | Entity, |
8297 | Kind, Args: Arg, Step: *Step, |
8298 | ConstructorInitRequiresZeroInit, |
8299 | /*IsListInitialization*/true, |
8300 | /*IsStdInitListInit*/IsStdInitListInitialization: false, |
8301 | LBraceLoc: InitList->getLBraceLoc(), |
8302 | RBraceLoc: InitList->getRBraceLoc()); |
8303 | break; |
8304 | } |
8305 | |
8306 | case SK_UnwrapInitList: |
8307 | CurInit = cast<InitListExpr>(Val: CurInit.get())->getInit(Init: 0); |
8308 | break; |
8309 | |
8310 | case SK_RewrapInitList: { |
8311 | Expr *E = CurInit.get(); |
8312 | InitListExpr *Syntactic = Step->WrappingSyntacticList; |
8313 | InitListExpr *ILE = new (S.Context) InitListExpr(S.Context, |
8314 | Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc()); |
8315 | ILE->setSyntacticForm(Syntactic); |
8316 | ILE->setType(E->getType()); |
8317 | ILE->setValueKind(E->getValueKind()); |
8318 | CurInit = ILE; |
8319 | break; |
8320 | } |
8321 | |
8322 | case SK_ConstructorInitialization: |
8323 | case SK_StdInitializerListConstructorCall: { |
8324 | if (checkAbstractType(Step->Type)) |
8325 | return ExprError(); |
8326 | |
8327 | // When an initializer list is passed for a parameter of type "reference |
8328 | // to object", we don't get an EK_Temporary entity, but instead an |
8329 | // EK_Parameter entity with reference type. |
8330 | // FIXME: This is a hack. What we really should do is create a user |
8331 | // conversion step for this case, but this makes it considerably more |
8332 | // complicated. For now, this will do. |
8333 | InitializedEntity TempEntity = InitializedEntity::InitializeTemporary( |
8334 | Type: Entity.getType().getNonReferenceType()); |
8335 | bool UseTemporary = Entity.getType()->isReferenceType(); |
8336 | bool IsStdInitListInit = |
8337 | Step->Kind == SK_StdInitializerListConstructorCall; |
8338 | Expr *Source = CurInit.get(); |
8339 | SourceRange Range = Kind.hasParenOrBraceRange() |
8340 | ? Kind.getParenOrBraceRange() |
8341 | : SourceRange(); |
8342 | CurInit = PerformConstructorInitialization( |
8343 | S, Entity: UseTemporary ? TempEntity : Entity, Kind, |
8344 | Args: Source ? MultiExprArg(Source) : Args, Step: *Step, |
8345 | ConstructorInitRequiresZeroInit, |
8346 | /*IsListInitialization*/ IsStdInitListInit, |
8347 | /*IsStdInitListInitialization*/ IsStdInitListInit, |
8348 | /*LBraceLoc*/ Range.getBegin(), |
8349 | /*RBraceLoc*/ Range.getEnd()); |
8350 | break; |
8351 | } |
8352 | |
8353 | case SK_ZeroInitialization: { |
8354 | step_iterator NextStep = Step; |
8355 | ++NextStep; |
8356 | if (NextStep != StepEnd && |
8357 | (NextStep->Kind == SK_ConstructorInitialization || |
8358 | NextStep->Kind == SK_ConstructorInitializationFromList)) { |
8359 | // The need for zero-initialization is recorded directly into |
8360 | // the call to the object's constructor within the next step. |
8361 | ConstructorInitRequiresZeroInit = true; |
8362 | } else if (Kind.getKind() == InitializationKind::IK_Value && |
8363 | S.getLangOpts().CPlusPlus && |
8364 | !Kind.isImplicitValueInit()) { |
8365 | TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo(); |
8366 | if (!TSInfo) |
8367 | TSInfo = S.Context.getTrivialTypeSourceInfo(T: Step->Type, |
8368 | Loc: Kind.getRange().getBegin()); |
8369 | |
8370 | CurInit = new (S.Context) CXXScalarValueInitExpr( |
8371 | Entity.getType().getNonLValueExprType(Context: S.Context), TSInfo, |
8372 | Kind.getRange().getEnd()); |
8373 | } else { |
8374 | CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type); |
8375 | // Note the return value isn't used to return a ExprError() when |
8376 | // initialization fails . For struct initialization allows all field |
8377 | // assignments to be checked rather than bailing on the first error. |
8378 | S.BoundsSafetyCheckInitialization(Entity, Kind, |
8379 | Action: AssignmentAction::Initializing, |
8380 | LHSType: Step->Type, RHSExpr: CurInit.get()); |
8381 | } |
8382 | break; |
8383 | } |
8384 | |
8385 | case SK_CAssignment: { |
8386 | QualType SourceType = CurInit.get()->getType(); |
8387 | Expr *Init = CurInit.get(); |
8388 | |
8389 | // Save off the initial CurInit in case we need to emit a diagnostic |
8390 | ExprResult InitialCurInit = Init; |
8391 | ExprResult Result = Init; |
8392 | AssignConvertType ConvTy = S.CheckSingleAssignmentConstraints( |
8393 | LHSType: Step->Type, RHS&: Result, Diagnose: true, |
8394 | DiagnoseCFAudited: Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited); |
8395 | if (Result.isInvalid()) |
8396 | return ExprError(); |
8397 | CurInit = Result; |
8398 | |
8399 | // If this is a call, allow conversion to a transparent union. |
8400 | ExprResult CurInitExprRes = CurInit; |
8401 | if (!S.IsAssignConvertCompatible(ConvTy) && Entity.isParameterKind() && |
8402 | S.CheckTransparentUnionArgumentConstraints( |
8403 | ArgType: Step->Type, RHS&: CurInitExprRes) == AssignConvertType::Compatible) |
8404 | ConvTy = AssignConvertType::Compatible; |
8405 | if (CurInitExprRes.isInvalid()) |
8406 | return ExprError(); |
8407 | CurInit = CurInitExprRes; |
8408 | |
8409 | if (S.getLangOpts().C23 && initializingConstexprVariable(Entity)) { |
8410 | CheckC23ConstexprInitConversion(S, FromType: SourceType, ToType: Entity.getType(), |
8411 | Init: CurInit.get()); |
8412 | |
8413 | // C23 6.7.1p6: If an object or subobject declared with storage-class |
8414 | // specifier constexpr has pointer, integer, or arithmetic type, any |
8415 | // explicit initializer value for it shall be null, an integer |
8416 | // constant expression, or an arithmetic constant expression, |
8417 | // respectively. |
8418 | Expr::EvalResult ER; |
8419 | if (Entity.getType()->getAs<PointerType>() && |
8420 | CurInit.get()->EvaluateAsRValue(Result&: ER, Ctx: S.Context) && |
8421 | !ER.Val.isNullPointer()) { |
8422 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_c23_constexpr_pointer_not_null); |
8423 | } |
8424 | } |
8425 | |
8426 | // Note the return value isn't used to return a ExprError() when |
8427 | // initialization fails. For struct initialization this allows all field |
8428 | // assignments to be checked rather than bailing on the first error. |
8429 | S.BoundsSafetyCheckInitialization(Entity, Kind, |
8430 | Action: getAssignmentAction(Entity, Diagnose: true), |
8431 | LHSType: Step->Type, RHSExpr: InitialCurInit.get()); |
8432 | |
8433 | bool Complained; |
8434 | if (S.DiagnoseAssignmentResult(ConvTy, Loc: Kind.getLocation(), |
8435 | DstType: Step->Type, SrcType: SourceType, |
8436 | SrcExpr: InitialCurInit.get(), |
8437 | Action: getAssignmentAction(Entity, Diagnose: true), |
8438 | Complained: &Complained)) { |
8439 | PrintInitLocationNote(S, Entity); |
8440 | return ExprError(); |
8441 | } else if (Complained) |
8442 | PrintInitLocationNote(S, Entity); |
8443 | break; |
8444 | } |
8445 | |
8446 | case SK_StringInit: { |
8447 | QualType Ty = Step->Type; |
8448 | bool UpdateType = ResultType && Entity.getType()->isIncompleteArrayType(); |
8449 | CheckStringInit(Str: CurInit.get(), DeclT&: UpdateType ? *ResultType : Ty, |
8450 | AT: S.Context.getAsArrayType(T: Ty), S, Entity, |
8451 | CheckC23ConstexprInit: S.getLangOpts().C23 && |
8452 | initializingConstexprVariable(Entity)); |
8453 | break; |
8454 | } |
8455 | |
8456 | case SK_ObjCObjectConversion: |
8457 | CurInit = S.ImpCastExprToType(E: CurInit.get(), Type: Step->Type, |
8458 | CK: CK_ObjCObjectLValueCast, |
8459 | VK: CurInit.get()->getValueKind()); |
8460 | break; |
8461 | |
8462 | case SK_ArrayLoopIndex: { |
8463 | Expr *Cur = CurInit.get(); |
8464 | Expr *BaseExpr = new (S.Context) |
8465 | OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(), |
8466 | Cur->getValueKind(), Cur->getObjectKind(), Cur); |
8467 | Expr *IndexExpr = |
8468 | new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType()); |
8469 | CurInit = S.CreateBuiltinArraySubscriptExpr( |
8470 | Base: BaseExpr, LLoc: Kind.getLocation(), Idx: IndexExpr, RLoc: Kind.getLocation()); |
8471 | ArrayLoopCommonExprs.push_back(Elt: BaseExpr); |
8472 | break; |
8473 | } |
8474 | |
8475 | case SK_ArrayLoopInit: { |
8476 | assert(!ArrayLoopCommonExprs.empty() && |
8477 | "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit" ); |
8478 | Expr *Common = ArrayLoopCommonExprs.pop_back_val(); |
8479 | CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common, |
8480 | CurInit.get()); |
8481 | break; |
8482 | } |
8483 | |
8484 | case SK_GNUArrayInit: |
8485 | // Okay: we checked everything before creating this step. Note that |
8486 | // this is a GNU extension. |
8487 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::ext_array_init_copy) |
8488 | << Step->Type << CurInit.get()->getType() |
8489 | << CurInit.get()->getSourceRange(); |
8490 | updateGNUCompoundLiteralRValue(E: CurInit.get()); |
8491 | [[fallthrough]]; |
8492 | case SK_ArrayInit: |
8493 | // If the destination type is an incomplete array type, update the |
8494 | // type accordingly. |
8495 | if (ResultType) { |
8496 | if (const IncompleteArrayType *IncompleteDest |
8497 | = S.Context.getAsIncompleteArrayType(T: Step->Type)) { |
8498 | if (const ConstantArrayType *ConstantSource |
8499 | = S.Context.getAsConstantArrayType(T: CurInit.get()->getType())) { |
8500 | *ResultType = S.Context.getConstantArrayType( |
8501 | EltTy: IncompleteDest->getElementType(), ArySize: ConstantSource->getSize(), |
8502 | SizeExpr: ConstantSource->getSizeExpr(), ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0); |
8503 | } |
8504 | } |
8505 | } |
8506 | break; |
8507 | |
8508 | case SK_ParenthesizedArrayInit: |
8509 | // Okay: we checked everything before creating this step. Note that |
8510 | // this is a GNU extension. |
8511 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::ext_array_init_parens) |
8512 | << CurInit.get()->getSourceRange(); |
8513 | break; |
8514 | |
8515 | case SK_PassByIndirectCopyRestore: |
8516 | case SK_PassByIndirectRestore: |
8517 | checkIndirectCopyRestoreSource(S, src: CurInit.get()); |
8518 | CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr( |
8519 | CurInit.get(), Step->Type, |
8520 | Step->Kind == SK_PassByIndirectCopyRestore); |
8521 | break; |
8522 | |
8523 | case SK_ProduceObjCObject: |
8524 | CurInit = ImplicitCastExpr::Create( |
8525 | Context: S.Context, T: Step->Type, Kind: CK_ARCProduceObject, Operand: CurInit.get(), BasePath: nullptr, |
8526 | Cat: VK_PRValue, FPO: FPOptionsOverride()); |
8527 | break; |
8528 | |
8529 | case SK_StdInitializerList: { |
8530 | S.Diag(Loc: CurInit.get()->getExprLoc(), |
8531 | DiagID: diag::warn_cxx98_compat_initializer_list_init) |
8532 | << CurInit.get()->getSourceRange(); |
8533 | |
8534 | // Materialize the temporary into memory. |
8535 | MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr( |
8536 | T: CurInit.get()->getType(), Temporary: CurInit.get(), |
8537 | /*BoundToLvalueReference=*/false); |
8538 | |
8539 | // Wrap it in a construction of a std::initializer_list<T>. |
8540 | CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE); |
8541 | |
8542 | if (!Step->Type->isDependentType()) { |
8543 | QualType ElementType; |
8544 | [[maybe_unused]] bool IsStdInitializerList = |
8545 | S.isStdInitializerList(Ty: Step->Type, Element: &ElementType); |
8546 | assert(IsStdInitializerList && |
8547 | "StdInitializerList step to non-std::initializer_list" ); |
8548 | const CXXRecordDecl *Record = |
8549 | Step->Type->getAsCXXRecordDecl()->getDefinition(); |
8550 | assert(Record && Record->isCompleteDefinition() && |
8551 | "std::initializer_list should have already be " |
8552 | "complete/instantiated by this point" ); |
8553 | |
8554 | auto InvalidType = [&] { |
8555 | S.Diag(Loc: Record->getLocation(), |
8556 | DiagID: diag::err_std_initializer_list_malformed) |
8557 | << Step->Type.getUnqualifiedType(); |
8558 | return ExprError(); |
8559 | }; |
8560 | |
8561 | if (Record->isUnion() || Record->getNumBases() != 0 || |
8562 | Record->isPolymorphic()) |
8563 | return InvalidType(); |
8564 | |
8565 | RecordDecl::field_iterator Field = Record->field_begin(); |
8566 | if (Field == Record->field_end()) |
8567 | return InvalidType(); |
8568 | |
8569 | // Start pointer |
8570 | if (!Field->getType()->isPointerType() || |
8571 | !S.Context.hasSameType(T1: Field->getType()->getPointeeType(), |
8572 | T2: ElementType.withConst())) |
8573 | return InvalidType(); |
8574 | |
8575 | if (++Field == Record->field_end()) |
8576 | return InvalidType(); |
8577 | |
8578 | // Size or end pointer |
8579 | if (const auto *PT = Field->getType()->getAs<PointerType>()) { |
8580 | if (!S.Context.hasSameType(T1: PT->getPointeeType(), |
8581 | T2: ElementType.withConst())) |
8582 | return InvalidType(); |
8583 | } else { |
8584 | if (Field->isBitField() || |
8585 | !S.Context.hasSameType(T1: Field->getType(), T2: S.Context.getSizeType())) |
8586 | return InvalidType(); |
8587 | } |
8588 | |
8589 | if (++Field != Record->field_end()) |
8590 | return InvalidType(); |
8591 | } |
8592 | |
8593 | // Bind the result, in case the library has given initializer_list a |
8594 | // non-trivial destructor. |
8595 | if (shouldBindAsTemporary(Entity)) |
8596 | CurInit = S.MaybeBindToTemporary(E: CurInit.get()); |
8597 | break; |
8598 | } |
8599 | |
8600 | case SK_OCLSamplerInit: { |
8601 | // Sampler initialization have 5 cases: |
8602 | // 1. function argument passing |
8603 | // 1a. argument is a file-scope variable |
8604 | // 1b. argument is a function-scope variable |
8605 | // 1c. argument is one of caller function's parameters |
8606 | // 2. variable initialization |
8607 | // 2a. initializing a file-scope variable |
8608 | // 2b. initializing a function-scope variable |
8609 | // |
8610 | // For file-scope variables, since they cannot be initialized by function |
8611 | // call of __translate_sampler_initializer in LLVM IR, their references |
8612 | // need to be replaced by a cast from their literal initializers to |
8613 | // sampler type. Since sampler variables can only be used in function |
8614 | // calls as arguments, we only need to replace them when handling the |
8615 | // argument passing. |
8616 | assert(Step->Type->isSamplerT() && |
8617 | "Sampler initialization on non-sampler type." ); |
8618 | Expr *Init = CurInit.get()->IgnoreParens(); |
8619 | QualType SourceType = Init->getType(); |
8620 | // Case 1 |
8621 | if (Entity.isParameterKind()) { |
8622 | if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) { |
8623 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_sampler_argument_required) |
8624 | << SourceType; |
8625 | break; |
8626 | } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Init)) { |
8627 | auto Var = cast<VarDecl>(Val: DRE->getDecl()); |
8628 | // Case 1b and 1c |
8629 | // No cast from integer to sampler is needed. |
8630 | if (!Var->hasGlobalStorage()) { |
8631 | CurInit = ImplicitCastExpr::Create( |
8632 | Context: S.Context, T: Step->Type, Kind: CK_LValueToRValue, Operand: Init, |
8633 | /*BasePath=*/nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride()); |
8634 | break; |
8635 | } |
8636 | // Case 1a |
8637 | // For function call with a file-scope sampler variable as argument, |
8638 | // get the integer literal. |
8639 | // Do not diagnose if the file-scope variable does not have initializer |
8640 | // since this has already been diagnosed when parsing the variable |
8641 | // declaration. |
8642 | if (!Var->getInit() || !isa<ImplicitCastExpr>(Val: Var->getInit())) |
8643 | break; |
8644 | Init = cast<ImplicitCastExpr>(Val: const_cast<Expr*>( |
8645 | Var->getInit()))->getSubExpr(); |
8646 | SourceType = Init->getType(); |
8647 | } |
8648 | } else { |
8649 | // Case 2 |
8650 | // Check initializer is 32 bit integer constant. |
8651 | // If the initializer is taken from global variable, do not diagnose since |
8652 | // this has already been done when parsing the variable declaration. |
8653 | if (!Init->isConstantInitializer(Ctx&: S.Context, ForRef: false)) |
8654 | break; |
8655 | |
8656 | if (!SourceType->isIntegerType() || |
8657 | 32 != S.Context.getIntWidth(T: SourceType)) { |
8658 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_sampler_initializer_not_integer) |
8659 | << SourceType; |
8660 | break; |
8661 | } |
8662 | |
8663 | Expr::EvalResult EVResult; |
8664 | Init->EvaluateAsInt(Result&: EVResult, Ctx: S.Context); |
8665 | llvm::APSInt Result = EVResult.Val.getInt(); |
8666 | const uint64_t SamplerValue = Result.getLimitedValue(); |
8667 | // 32-bit value of sampler's initializer is interpreted as |
8668 | // bit-field with the following structure: |
8669 | // |unspecified|Filter|Addressing Mode| Normalized Coords| |
8670 | // |31 6|5 4|3 1| 0| |
8671 | // This structure corresponds to enum values of sampler properties |
8672 | // defined in SPIR spec v1.2 and also opencl-c.h |
8673 | unsigned AddressingMode = (0x0E & SamplerValue) >> 1; |
8674 | unsigned FilterMode = (0x30 & SamplerValue) >> 4; |
8675 | if (FilterMode != 1 && FilterMode != 2 && |
8676 | !S.getOpenCLOptions().isAvailableOption( |
8677 | Ext: "cl_intel_device_side_avc_motion_estimation" , LO: S.getLangOpts())) |
8678 | S.Diag(Loc: Kind.getLocation(), |
8679 | DiagID: diag::warn_sampler_initializer_invalid_bits) |
8680 | << "Filter Mode" ; |
8681 | if (AddressingMode > 4) |
8682 | S.Diag(Loc: Kind.getLocation(), |
8683 | DiagID: diag::warn_sampler_initializer_invalid_bits) |
8684 | << "Addressing Mode" ; |
8685 | } |
8686 | |
8687 | // Cases 1a, 2a and 2b |
8688 | // Insert cast from integer to sampler. |
8689 | CurInit = S.ImpCastExprToType(E: Init, Type: S.Context.OCLSamplerTy, |
8690 | CK: CK_IntToOCLSampler); |
8691 | break; |
8692 | } |
8693 | case SK_OCLZeroOpaqueType: { |
8694 | assert((Step->Type->isEventT() || Step->Type->isQueueT() || |
8695 | Step->Type->isOCLIntelSubgroupAVCType()) && |
8696 | "Wrong type for initialization of OpenCL opaque type." ); |
8697 | |
8698 | CurInit = S.ImpCastExprToType(E: CurInit.get(), Type: Step->Type, |
8699 | CK: CK_ZeroToOCLOpaqueType, |
8700 | VK: CurInit.get()->getValueKind()); |
8701 | break; |
8702 | } |
8703 | case SK_ParenthesizedListInit: { |
8704 | CurInit = nullptr; |
8705 | TryOrBuildParenListInitialization(S, Entity, Kind, Args, Sequence&: *this, |
8706 | /*VerifyOnly=*/false, Result: &CurInit); |
8707 | if (CurInit.get() && ResultType) |
8708 | *ResultType = CurInit.get()->getType(); |
8709 | if (shouldBindAsTemporary(Entity)) |
8710 | CurInit = S.MaybeBindToTemporary(E: CurInit.get()); |
8711 | break; |
8712 | } |
8713 | } |
8714 | } |
8715 | |
8716 | Expr *Init = CurInit.get(); |
8717 | if (!Init) |
8718 | return ExprError(); |
8719 | |
8720 | // Check whether the initializer has a shorter lifetime than the initialized |
8721 | // entity, and if not, either lifetime-extend or warn as appropriate. |
8722 | S.checkInitializerLifetime(Entity, Init); |
8723 | |
8724 | // Diagnose non-fatal problems with the completed initialization. |
8725 | if (InitializedEntity::EntityKind EK = Entity.getKind(); |
8726 | (EK == InitializedEntity::EK_Member || |
8727 | EK == InitializedEntity::EK_ParenAggInitMember) && |
8728 | cast<FieldDecl>(Val: Entity.getDecl())->isBitField()) |
8729 | S.CheckBitFieldInitialization(InitLoc: Kind.getLocation(), |
8730 | Field: cast<FieldDecl>(Val: Entity.getDecl()), Init); |
8731 | |
8732 | // Check for std::move on construction. |
8733 | CheckMoveOnConstruction(S, InitExpr: Init, |
8734 | IsReturnStmt: Entity.getKind() == InitializedEntity::EK_Result); |
8735 | |
8736 | return Init; |
8737 | } |
8738 | |
8739 | /// Somewhere within T there is an uninitialized reference subobject. |
8740 | /// Dig it out and diagnose it. |
8741 | static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc, |
8742 | QualType T) { |
8743 | if (T->isReferenceType()) { |
8744 | S.Diag(Loc, DiagID: diag::err_reference_without_init) |
8745 | << T.getNonReferenceType(); |
8746 | return true; |
8747 | } |
8748 | |
8749 | CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); |
8750 | if (!RD || !RD->hasUninitializedReferenceMember()) |
8751 | return false; |
8752 | |
8753 | for (const auto *FI : RD->fields()) { |
8754 | if (FI->isUnnamedBitField()) |
8755 | continue; |
8756 | |
8757 | if (DiagnoseUninitializedReference(S, Loc: FI->getLocation(), T: FI->getType())) { |
8758 | S.Diag(Loc, DiagID: diag::note_value_initialization_here) << RD; |
8759 | return true; |
8760 | } |
8761 | } |
8762 | |
8763 | for (const auto &BI : RD->bases()) { |
8764 | if (DiagnoseUninitializedReference(S, Loc: BI.getBeginLoc(), T: BI.getType())) { |
8765 | S.Diag(Loc, DiagID: diag::note_value_initialization_here) << RD; |
8766 | return true; |
8767 | } |
8768 | } |
8769 | |
8770 | return false; |
8771 | } |
8772 | |
8773 | |
8774 | //===----------------------------------------------------------------------===// |
8775 | // Diagnose initialization failures |
8776 | //===----------------------------------------------------------------------===// |
8777 | |
8778 | /// Emit notes associated with an initialization that failed due to a |
8779 | /// "simple" conversion failure. |
8780 | static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity, |
8781 | Expr *op) { |
8782 | QualType destType = entity.getType(); |
8783 | if (destType.getNonReferenceType()->isObjCObjectPointerType() && |
8784 | op->getType()->isObjCObjectPointerType()) { |
8785 | |
8786 | // Emit a possible note about the conversion failing because the |
8787 | // operand is a message send with a related result type. |
8788 | S.ObjC().EmitRelatedResultTypeNote(E: op); |
8789 | |
8790 | // Emit a possible note about a return failing because we're |
8791 | // expecting a related result type. |
8792 | if (entity.getKind() == InitializedEntity::EK_Result) |
8793 | S.ObjC().EmitRelatedResultTypeNoteForReturn(destType); |
8794 | } |
8795 | QualType fromType = op->getType(); |
8796 | QualType fromPointeeType = fromType.getCanonicalType()->getPointeeType(); |
8797 | QualType destPointeeType = destType.getCanonicalType()->getPointeeType(); |
8798 | auto *fromDecl = fromType->getPointeeCXXRecordDecl(); |
8799 | auto *destDecl = destType->getPointeeCXXRecordDecl(); |
8800 | if (fromDecl && destDecl && fromDecl->getDeclKind() == Decl::CXXRecord && |
8801 | destDecl->getDeclKind() == Decl::CXXRecord && |
8802 | !fromDecl->isInvalidDecl() && !destDecl->isInvalidDecl() && |
8803 | !fromDecl->hasDefinition() && |
8804 | destPointeeType.getQualifiers().compatiblyIncludes( |
8805 | other: fromPointeeType.getQualifiers(), Ctx: S.getASTContext())) |
8806 | S.Diag(Loc: fromDecl->getLocation(), DiagID: diag::note_forward_class_conversion) |
8807 | << S.getASTContext().getTagDeclType(Decl: fromDecl) |
8808 | << S.getASTContext().getTagDeclType(Decl: destDecl); |
8809 | } |
8810 | |
8811 | static void diagnoseListInit(Sema &S, const InitializedEntity &Entity, |
8812 | InitListExpr *InitList) { |
8813 | QualType DestType = Entity.getType(); |
8814 | |
8815 | QualType E; |
8816 | if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(Ty: DestType, Element: &E)) { |
8817 | QualType ArrayType = S.Context.getConstantArrayType( |
8818 | EltTy: E.withConst(), |
8819 | ArySize: llvm::APInt(S.Context.getTypeSize(T: S.Context.getSizeType()), |
8820 | InitList->getNumInits()), |
8821 | SizeExpr: nullptr, ASM: clang::ArraySizeModifier::Normal, IndexTypeQuals: 0); |
8822 | InitializedEntity HiddenArray = |
8823 | InitializedEntity::InitializeTemporary(Type: ArrayType); |
8824 | return diagnoseListInit(S, Entity: HiddenArray, InitList); |
8825 | } |
8826 | |
8827 | if (DestType->isReferenceType()) { |
8828 | // A list-initialization failure for a reference means that we tried to |
8829 | // create a temporary of the inner type (per [dcl.init.list]p3.6) and the |
8830 | // inner initialization failed. |
8831 | QualType T = DestType->castAs<ReferenceType>()->getPointeeType(); |
8832 | diagnoseListInit(S, Entity: InitializedEntity::InitializeTemporary(Type: T), InitList); |
8833 | SourceLocation Loc = InitList->getBeginLoc(); |
8834 | if (auto *D = Entity.getDecl()) |
8835 | Loc = D->getLocation(); |
8836 | S.Diag(Loc, DiagID: diag::note_in_reference_temporary_list_initializer) << T; |
8837 | return; |
8838 | } |
8839 | |
8840 | InitListChecker DiagnoseInitList(S, Entity, InitList, DestType, |
8841 | /*VerifyOnly=*/false, |
8842 | /*TreatUnavailableAsInvalid=*/false); |
8843 | assert(DiagnoseInitList.HadError() && |
8844 | "Inconsistent init list check result." ); |
8845 | } |
8846 | |
8847 | bool InitializationSequence::Diagnose(Sema &S, |
8848 | const InitializedEntity &Entity, |
8849 | const InitializationKind &Kind, |
8850 | ArrayRef<Expr *> Args) { |
8851 | if (!Failed()) |
8852 | return false; |
8853 | |
8854 | QualType DestType = Entity.getType(); |
8855 | |
8856 | // When we want to diagnose only one element of a braced-init-list, |
8857 | // we need to factor it out. |
8858 | Expr *OnlyArg; |
8859 | if (Args.size() == 1) { |
8860 | auto *List = dyn_cast<InitListExpr>(Val: Args[0]); |
8861 | if (List && List->getNumInits() == 1) |
8862 | OnlyArg = List->getInit(Init: 0); |
8863 | else |
8864 | OnlyArg = Args[0]; |
8865 | |
8866 | if (OnlyArg->getType() == S.Context.OverloadTy) { |
8867 | DeclAccessPair Found; |
8868 | if (FunctionDecl *FD = S.ResolveAddressOfOverloadedFunction( |
8869 | AddressOfExpr: OnlyArg, TargetType: DestType.getNonReferenceType(), /*Complain=*/false, |
8870 | Found)) { |
8871 | if (Expr *Resolved = |
8872 | S.FixOverloadedFunctionReference(E: OnlyArg, FoundDecl: Found, Fn: FD).get()) |
8873 | OnlyArg = Resolved; |
8874 | } |
8875 | } |
8876 | } |
8877 | else |
8878 | OnlyArg = nullptr; |
8879 | |
8880 | switch (Failure) { |
8881 | case FK_TooManyInitsForReference: |
8882 | // FIXME: Customize for the initialized entity? |
8883 | if (Args.empty()) { |
8884 | // Dig out the reference subobject which is uninitialized and diagnose it. |
8885 | // If this is value-initialization, this could be nested some way within |
8886 | // the target type. |
8887 | assert(Kind.getKind() == InitializationKind::IK_Value || |
8888 | DestType->isReferenceType()); |
8889 | bool Diagnosed = |
8890 | DiagnoseUninitializedReference(S, Loc: Kind.getLocation(), T: DestType); |
8891 | assert(Diagnosed && "couldn't find uninitialized reference to diagnose" ); |
8892 | (void)Diagnosed; |
8893 | } else // FIXME: diagnostic below could be better! |
8894 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_has_multiple_inits) |
8895 | << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc()); |
8896 | break; |
8897 | case FK_ParenthesizedListInitForReference: |
8898 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_list_init_in_parens) |
8899 | << 1 << Entity.getType() << Args[0]->getSourceRange(); |
8900 | break; |
8901 | |
8902 | case FK_ArrayNeedsInitList: |
8903 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_array_init_not_init_list) << 0; |
8904 | break; |
8905 | case FK_ArrayNeedsInitListOrStringLiteral: |
8906 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_array_init_not_init_list) << 1; |
8907 | break; |
8908 | case FK_ArrayNeedsInitListOrWideStringLiteral: |
8909 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_array_init_not_init_list) << 2; |
8910 | break; |
8911 | case FK_NarrowStringIntoWideCharArray: |
8912 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_array_init_narrow_string_into_wchar); |
8913 | break; |
8914 | case FK_WideStringIntoCharArray: |
8915 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_array_init_wide_string_into_char); |
8916 | break; |
8917 | case FK_IncompatWideStringIntoWideChar: |
8918 | S.Diag(Loc: Kind.getLocation(), |
8919 | DiagID: diag::err_array_init_incompat_wide_string_into_wchar); |
8920 | break; |
8921 | case FK_PlainStringIntoUTF8Char: |
8922 | S.Diag(Loc: Kind.getLocation(), |
8923 | DiagID: diag::err_array_init_plain_string_into_char8_t); |
8924 | S.Diag(Loc: Args.front()->getBeginLoc(), |
8925 | DiagID: diag::note_array_init_plain_string_into_char8_t) |
8926 | << FixItHint::CreateInsertion(InsertionLoc: Args.front()->getBeginLoc(), Code: "u8" ); |
8927 | break; |
8928 | case FK_UTF8StringIntoPlainChar: |
8929 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_array_init_utf8_string_into_char) |
8930 | << DestType->isSignedIntegerType() << S.getLangOpts().CPlusPlus20; |
8931 | break; |
8932 | case FK_ArrayTypeMismatch: |
8933 | case FK_NonConstantArrayInit: |
8934 | S.Diag(Loc: Kind.getLocation(), |
8935 | DiagID: (Failure == FK_ArrayTypeMismatch |
8936 | ? diag::err_array_init_different_type |
8937 | : diag::err_array_init_non_constant_array)) |
8938 | << DestType.getNonReferenceType() |
8939 | << OnlyArg->getType() |
8940 | << Args[0]->getSourceRange(); |
8941 | break; |
8942 | |
8943 | case FK_VariableLengthArrayHasInitializer: |
8944 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_variable_object_no_init) |
8945 | << Args[0]->getSourceRange(); |
8946 | break; |
8947 | |
8948 | case FK_AddressOfOverloadFailed: { |
8949 | DeclAccessPair Found; |
8950 | S.ResolveAddressOfOverloadedFunction(AddressOfExpr: OnlyArg, |
8951 | TargetType: DestType.getNonReferenceType(), |
8952 | Complain: true, |
8953 | Found); |
8954 | break; |
8955 | } |
8956 | |
8957 | case FK_AddressOfUnaddressableFunction: { |
8958 | auto *FD = cast<FunctionDecl>(Val: cast<DeclRefExpr>(Val: OnlyArg)->getDecl()); |
8959 | S.checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true, |
8960 | Loc: OnlyArg->getBeginLoc()); |
8961 | break; |
8962 | } |
8963 | |
8964 | case FK_ReferenceInitOverloadFailed: |
8965 | case FK_UserConversionOverloadFailed: |
8966 | switch (FailedOverloadResult) { |
8967 | case OR_Ambiguous: |
8968 | |
8969 | FailedCandidateSet.NoteCandidates( |
8970 | PA: PartialDiagnosticAt( |
8971 | Kind.getLocation(), |
8972 | Failure == FK_UserConversionOverloadFailed |
8973 | ? (S.PDiag(DiagID: diag::err_typecheck_ambiguous_condition) |
8974 | << OnlyArg->getType() << DestType |
8975 | << Args[0]->getSourceRange()) |
8976 | : (S.PDiag(DiagID: diag::err_ref_init_ambiguous) |
8977 | << DestType << OnlyArg->getType() |
8978 | << Args[0]->getSourceRange())), |
8979 | S, OCD: OCD_AmbiguousCandidates, Args); |
8980 | break; |
8981 | |
8982 | case OR_No_Viable_Function: { |
8983 | auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD: OCD_AllCandidates, Args); |
8984 | if (!S.RequireCompleteType(Loc: Kind.getLocation(), |
8985 | T: DestType.getNonReferenceType(), |
8986 | DiagID: diag::err_typecheck_nonviable_condition_incomplete, |
8987 | Args: OnlyArg->getType(), Args: Args[0]->getSourceRange())) |
8988 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_typecheck_nonviable_condition) |
8989 | << (Entity.getKind() == InitializedEntity::EK_Result) |
8990 | << OnlyArg->getType() << Args[0]->getSourceRange() |
8991 | << DestType.getNonReferenceType(); |
8992 | |
8993 | FailedCandidateSet.NoteCandidates(S, Args, Cands); |
8994 | break; |
8995 | } |
8996 | case OR_Deleted: { |
8997 | OverloadCandidateSet::iterator Best; |
8998 | OverloadingResult Ovl |
8999 | = FailedCandidateSet.BestViableFunction(S, Loc: Kind.getLocation(), Best); |
9000 | |
9001 | StringLiteral *Msg = Best->Function->getDeletedMessage(); |
9002 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_typecheck_deleted_function) |
9003 | << OnlyArg->getType() << DestType.getNonReferenceType() |
9004 | << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef()) |
9005 | << Args[0]->getSourceRange(); |
9006 | if (Ovl == OR_Deleted) { |
9007 | S.NoteDeletedFunction(FD: Best->Function); |
9008 | } else { |
9009 | llvm_unreachable("Inconsistent overload resolution?" ); |
9010 | } |
9011 | break; |
9012 | } |
9013 | |
9014 | case OR_Success: |
9015 | llvm_unreachable("Conversion did not fail!" ); |
9016 | } |
9017 | break; |
9018 | |
9019 | case FK_NonConstLValueReferenceBindingToTemporary: |
9020 | if (isa<InitListExpr>(Val: Args[0])) { |
9021 | S.Diag(Loc: Kind.getLocation(), |
9022 | DiagID: diag::err_lvalue_reference_bind_to_initlist) |
9023 | << DestType.getNonReferenceType().isVolatileQualified() |
9024 | << DestType.getNonReferenceType() |
9025 | << Args[0]->getSourceRange(); |
9026 | break; |
9027 | } |
9028 | [[fallthrough]]; |
9029 | |
9030 | case FK_NonConstLValueReferenceBindingToUnrelated: |
9031 | S.Diag(Loc: Kind.getLocation(), |
9032 | DiagID: Failure == FK_NonConstLValueReferenceBindingToTemporary |
9033 | ? diag::err_lvalue_reference_bind_to_temporary |
9034 | : diag::err_lvalue_reference_bind_to_unrelated) |
9035 | << DestType.getNonReferenceType().isVolatileQualified() |
9036 | << DestType.getNonReferenceType() |
9037 | << OnlyArg->getType() |
9038 | << Args[0]->getSourceRange(); |
9039 | break; |
9040 | |
9041 | case FK_NonConstLValueReferenceBindingToBitfield: { |
9042 | // We don't necessarily have an unambiguous source bit-field. |
9043 | FieldDecl *BitField = Args[0]->getSourceBitField(); |
9044 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_to_bitfield) |
9045 | << DestType.isVolatileQualified() |
9046 | << (BitField ? BitField->getDeclName() : DeclarationName()) |
9047 | << (BitField != nullptr) |
9048 | << Args[0]->getSourceRange(); |
9049 | if (BitField) |
9050 | S.Diag(Loc: BitField->getLocation(), DiagID: diag::note_bitfield_decl); |
9051 | break; |
9052 | } |
9053 | |
9054 | case FK_NonConstLValueReferenceBindingToVectorElement: |
9055 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_to_vector_element) |
9056 | << DestType.isVolatileQualified() |
9057 | << Args[0]->getSourceRange(); |
9058 | break; |
9059 | |
9060 | case FK_NonConstLValueReferenceBindingToMatrixElement: |
9061 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_to_matrix_element) |
9062 | << DestType.isVolatileQualified() << Args[0]->getSourceRange(); |
9063 | break; |
9064 | |
9065 | case FK_RValueReferenceBindingToLValue: |
9066 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_lvalue_to_rvalue_ref) |
9067 | << DestType.getNonReferenceType() << OnlyArg->getType() |
9068 | << Args[0]->getSourceRange(); |
9069 | break; |
9070 | |
9071 | case FK_ReferenceAddrspaceMismatchTemporary: |
9072 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_temporary_addrspace) |
9073 | << DestType << Args[0]->getSourceRange(); |
9074 | break; |
9075 | |
9076 | case FK_ReferenceInitDropsQualifiers: { |
9077 | QualType SourceType = OnlyArg->getType(); |
9078 | QualType NonRefType = DestType.getNonReferenceType(); |
9079 | Qualifiers DroppedQualifiers = |
9080 | SourceType.getQualifiers() - NonRefType.getQualifiers(); |
9081 | |
9082 | if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf( |
9083 | other: SourceType.getQualifiers(), Ctx: S.getASTContext())) |
9084 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_drops_quals) |
9085 | << NonRefType << SourceType << 1 /*addr space*/ |
9086 | << Args[0]->getSourceRange(); |
9087 | else if (DroppedQualifiers.hasQualifiers()) |
9088 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_drops_quals) |
9089 | << NonRefType << SourceType << 0 /*cv quals*/ |
9090 | << Qualifiers::fromCVRMask(CVR: DroppedQualifiers.getCVRQualifiers()) |
9091 | << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange(); |
9092 | else |
9093 | // FIXME: Consider decomposing the type and explaining which qualifiers |
9094 | // were dropped where, or on which level a 'const' is missing, etc. |
9095 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_drops_quals) |
9096 | << NonRefType << SourceType << 2 /*incompatible quals*/ |
9097 | << Args[0]->getSourceRange(); |
9098 | break; |
9099 | } |
9100 | |
9101 | case FK_ReferenceInitFailed: |
9102 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_failed) |
9103 | << DestType.getNonReferenceType() |
9104 | << DestType.getNonReferenceType()->isIncompleteType() |
9105 | << OnlyArg->isLValue() |
9106 | << OnlyArg->getType() |
9107 | << Args[0]->getSourceRange(); |
9108 | emitBadConversionNotes(S, entity: Entity, op: Args[0]); |
9109 | break; |
9110 | |
9111 | case FK_ConversionFailed: { |
9112 | QualType FromType = OnlyArg->getType(); |
9113 | PartialDiagnostic PDiag = S.PDiag(DiagID: diag::err_init_conversion_failed) |
9114 | << (int)Entity.getKind() |
9115 | << DestType |
9116 | << OnlyArg->isLValue() |
9117 | << FromType |
9118 | << Args[0]->getSourceRange(); |
9119 | S.HandleFunctionTypeMismatch(PDiag, FromType, ToType: DestType); |
9120 | S.Diag(Loc: Kind.getLocation(), PD: PDiag); |
9121 | emitBadConversionNotes(S, entity: Entity, op: Args[0]); |
9122 | break; |
9123 | } |
9124 | |
9125 | case FK_ConversionFromPropertyFailed: |
9126 | // No-op. This error has already been reported. |
9127 | break; |
9128 | |
9129 | case FK_TooManyInitsForScalar: { |
9130 | SourceRange R; |
9131 | |
9132 | auto *InitList = dyn_cast<InitListExpr>(Val: Args[0]); |
9133 | if (InitList && InitList->getNumInits() >= 1) { |
9134 | R = SourceRange(InitList->getInit(Init: 0)->getEndLoc(), InitList->getEndLoc()); |
9135 | } else { |
9136 | assert(Args.size() > 1 && "Expected multiple initializers!" ); |
9137 | R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc()); |
9138 | } |
9139 | |
9140 | R.setBegin(S.getLocForEndOfToken(Loc: R.getBegin())); |
9141 | if (Kind.isCStyleOrFunctionalCast()) |
9142 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_builtin_func_cast_more_than_one_arg) |
9143 | << R; |
9144 | else |
9145 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_excess_initializers) |
9146 | << /*scalar=*/2 << R; |
9147 | break; |
9148 | } |
9149 | |
9150 | case FK_ParenthesizedListInitForScalar: |
9151 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_list_init_in_parens) |
9152 | << 0 << Entity.getType() << Args[0]->getSourceRange(); |
9153 | break; |
9154 | |
9155 | case FK_ReferenceBindingToInitList: |
9156 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_init_list) |
9157 | << DestType.getNonReferenceType() << Args[0]->getSourceRange(); |
9158 | break; |
9159 | |
9160 | case FK_InitListBadDestinationType: |
9161 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_init_list_bad_dest_type) |
9162 | << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange(); |
9163 | break; |
9164 | |
9165 | case FK_ListConstructorOverloadFailed: |
9166 | case FK_ConstructorOverloadFailed: { |
9167 | SourceRange ArgsRange; |
9168 | if (Args.size()) |
9169 | ArgsRange = |
9170 | SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc()); |
9171 | |
9172 | if (Failure == FK_ListConstructorOverloadFailed) { |
9173 | assert(Args.size() == 1 && |
9174 | "List construction from other than 1 argument." ); |
9175 | InitListExpr *InitList = cast<InitListExpr>(Val: Args[0]); |
9176 | Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); |
9177 | } |
9178 | |
9179 | // FIXME: Using "DestType" for the entity we're printing is probably |
9180 | // bad. |
9181 | switch (FailedOverloadResult) { |
9182 | case OR_Ambiguous: |
9183 | FailedCandidateSet.NoteCandidates( |
9184 | PA: PartialDiagnosticAt(Kind.getLocation(), |
9185 | S.PDiag(DiagID: diag::err_ovl_ambiguous_init) |
9186 | << DestType << ArgsRange), |
9187 | S, OCD: OCD_AmbiguousCandidates, Args); |
9188 | break; |
9189 | |
9190 | case OR_No_Viable_Function: |
9191 | if (Kind.getKind() == InitializationKind::IK_Default && |
9192 | (Entity.getKind() == InitializedEntity::EK_Base || |
9193 | Entity.getKind() == InitializedEntity::EK_Member || |
9194 | Entity.getKind() == InitializedEntity::EK_ParenAggInitMember) && |
9195 | isa<CXXConstructorDecl>(Val: S.CurContext)) { |
9196 | // This is implicit default initialization of a member or |
9197 | // base within a constructor. If no viable function was |
9198 | // found, notify the user that they need to explicitly |
9199 | // initialize this base/member. |
9200 | CXXConstructorDecl *Constructor |
9201 | = cast<CXXConstructorDecl>(Val: S.CurContext); |
9202 | const CXXRecordDecl *InheritedFrom = nullptr; |
9203 | if (auto Inherited = Constructor->getInheritedConstructor()) |
9204 | InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass(); |
9205 | if (Entity.getKind() == InitializedEntity::EK_Base) { |
9206 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_missing_default_ctor) |
9207 | << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0) |
9208 | << S.Context.getTypeDeclType(Decl: Constructor->getParent()) |
9209 | << /*base=*/0 |
9210 | << Entity.getType() |
9211 | << InheritedFrom; |
9212 | |
9213 | RecordDecl *BaseDecl |
9214 | = Entity.getBaseSpecifier()->getType()->castAs<RecordType>() |
9215 | ->getDecl(); |
9216 | S.Diag(Loc: BaseDecl->getLocation(), DiagID: diag::note_previous_decl) |
9217 | << S.Context.getTagDeclType(Decl: BaseDecl); |
9218 | } else { |
9219 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_missing_default_ctor) |
9220 | << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0) |
9221 | << S.Context.getTypeDeclType(Decl: Constructor->getParent()) |
9222 | << /*member=*/1 |
9223 | << Entity.getName() |
9224 | << InheritedFrom; |
9225 | S.Diag(Loc: Entity.getDecl()->getLocation(), |
9226 | DiagID: diag::note_member_declared_at); |
9227 | |
9228 | if (const RecordType *Record |
9229 | = Entity.getType()->getAs<RecordType>()) |
9230 | S.Diag(Loc: Record->getDecl()->getLocation(), |
9231 | DiagID: diag::note_previous_decl) |
9232 | << S.Context.getTagDeclType(Decl: Record->getDecl()); |
9233 | } |
9234 | break; |
9235 | } |
9236 | |
9237 | FailedCandidateSet.NoteCandidates( |
9238 | PA: PartialDiagnosticAt( |
9239 | Kind.getLocation(), |
9240 | S.PDiag(DiagID: diag::err_ovl_no_viable_function_in_init) |
9241 | << DestType << ArgsRange), |
9242 | S, OCD: OCD_AllCandidates, Args); |
9243 | break; |
9244 | |
9245 | case OR_Deleted: { |
9246 | OverloadCandidateSet::iterator Best; |
9247 | OverloadingResult Ovl |
9248 | = FailedCandidateSet.BestViableFunction(S, Loc: Kind.getLocation(), Best); |
9249 | if (Ovl != OR_Deleted) { |
9250 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_ovl_deleted_init) |
9251 | << DestType << ArgsRange; |
9252 | llvm_unreachable("Inconsistent overload resolution?" ); |
9253 | break; |
9254 | } |
9255 | |
9256 | // If this is a defaulted or implicitly-declared function, then |
9257 | // it was implicitly deleted. Make it clear that the deletion was |
9258 | // implicit. |
9259 | if (S.isImplicitlyDeleted(FD: Best->Function)) |
9260 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_ovl_deleted_special_init) |
9261 | << S.getSpecialMember(MD: cast<CXXMethodDecl>(Val: Best->Function)) |
9262 | << DestType << ArgsRange; |
9263 | else { |
9264 | StringLiteral *Msg = Best->Function->getDeletedMessage(); |
9265 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_ovl_deleted_init) |
9266 | << DestType << (Msg != nullptr) |
9267 | << (Msg ? Msg->getString() : StringRef()) << ArgsRange; |
9268 | } |
9269 | |
9270 | // If it's a default constructed member, but it's not in the |
9271 | // constructor's initializer list, explicitly note where the member is |
9272 | // declared so the user can see which member is erroneously initialized |
9273 | // with a deleted default constructor. |
9274 | if (Kind.getKind() == InitializationKind::IK_Default && |
9275 | (Entity.getKind() == InitializedEntity::EK_Member || |
9276 | Entity.getKind() == InitializedEntity::EK_ParenAggInitMember)) { |
9277 | S.Diag(Loc: Entity.getDecl()->getLocation(), |
9278 | DiagID: diag::note_default_constructed_field) |
9279 | << Entity.getDecl(); |
9280 | } |
9281 | S.NoteDeletedFunction(FD: Best->Function); |
9282 | break; |
9283 | } |
9284 | |
9285 | case OR_Success: |
9286 | llvm_unreachable("Conversion did not fail!" ); |
9287 | } |
9288 | } |
9289 | break; |
9290 | |
9291 | case FK_DefaultInitOfConst: |
9292 | if (Entity.getKind() == InitializedEntity::EK_Member && |
9293 | isa<CXXConstructorDecl>(Val: S.CurContext)) { |
9294 | // This is implicit default-initialization of a const member in |
9295 | // a constructor. Complain that it needs to be explicitly |
9296 | // initialized. |
9297 | CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Val: S.CurContext); |
9298 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_uninitialized_member_in_ctor) |
9299 | << (Constructor->getInheritedConstructor() ? 2 : |
9300 | Constructor->isImplicit() ? 1 : 0) |
9301 | << S.Context.getTypeDeclType(Decl: Constructor->getParent()) |
9302 | << /*const=*/1 |
9303 | << Entity.getName(); |
9304 | S.Diag(Loc: Entity.getDecl()->getLocation(), DiagID: diag::note_previous_decl) |
9305 | << Entity.getName(); |
9306 | } else if (const auto *VD = dyn_cast_if_present<VarDecl>(Val: Entity.getDecl()); |
9307 | VD && VD->isConstexpr()) { |
9308 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_constexpr_var_requires_const_init) |
9309 | << VD; |
9310 | } else { |
9311 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_default_init_const) |
9312 | << DestType << (bool)DestType->getAs<RecordType>(); |
9313 | } |
9314 | break; |
9315 | |
9316 | case FK_Incomplete: |
9317 | S.RequireCompleteType(Loc: Kind.getLocation(), T: FailedIncompleteType, |
9318 | DiagID: diag::err_init_incomplete_type); |
9319 | break; |
9320 | |
9321 | case FK_ListInitializationFailed: { |
9322 | // Run the init list checker again to emit diagnostics. |
9323 | InitListExpr *InitList = cast<InitListExpr>(Val: Args[0]); |
9324 | diagnoseListInit(S, Entity, InitList); |
9325 | break; |
9326 | } |
9327 | |
9328 | case FK_PlaceholderType: { |
9329 | // FIXME: Already diagnosed! |
9330 | break; |
9331 | } |
9332 | |
9333 | case FK_ExplicitConstructor: { |
9334 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_selected_explicit_constructor) |
9335 | << Args[0]->getSourceRange(); |
9336 | OverloadCandidateSet::iterator Best; |
9337 | OverloadingResult Ovl |
9338 | = FailedCandidateSet.BestViableFunction(S, Loc: Kind.getLocation(), Best); |
9339 | (void)Ovl; |
9340 | assert(Ovl == OR_Success && "Inconsistent overload resolution" ); |
9341 | CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Val: Best->Function); |
9342 | S.Diag(Loc: CtorDecl->getLocation(), |
9343 | DiagID: diag::note_explicit_ctor_deduction_guide_here) << false; |
9344 | break; |
9345 | } |
9346 | |
9347 | case FK_ParenthesizedListInitFailed: |
9348 | TryOrBuildParenListInitialization(S, Entity, Kind, Args, Sequence&: *this, |
9349 | /*VerifyOnly=*/false); |
9350 | break; |
9351 | |
9352 | case FK_DesignatedInitForNonAggregate: |
9353 | InitListExpr *InitList = cast<InitListExpr>(Val: Args[0]); |
9354 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_designated_init_for_non_aggregate) |
9355 | << Entity.getType() << InitList->getSourceRange(); |
9356 | break; |
9357 | } |
9358 | |
9359 | PrintInitLocationNote(S, Entity); |
9360 | return true; |
9361 | } |
9362 | |
9363 | void InitializationSequence::dump(raw_ostream &OS) const { |
9364 | switch (SequenceKind) { |
9365 | case FailedSequence: { |
9366 | OS << "Failed sequence: " ; |
9367 | switch (Failure) { |
9368 | case FK_TooManyInitsForReference: |
9369 | OS << "too many initializers for reference" ; |
9370 | break; |
9371 | |
9372 | case FK_ParenthesizedListInitForReference: |
9373 | OS << "parenthesized list init for reference" ; |
9374 | break; |
9375 | |
9376 | case FK_ArrayNeedsInitList: |
9377 | OS << "array requires initializer list" ; |
9378 | break; |
9379 | |
9380 | case FK_AddressOfUnaddressableFunction: |
9381 | OS << "address of unaddressable function was taken" ; |
9382 | break; |
9383 | |
9384 | case FK_ArrayNeedsInitListOrStringLiteral: |
9385 | OS << "array requires initializer list or string literal" ; |
9386 | break; |
9387 | |
9388 | case FK_ArrayNeedsInitListOrWideStringLiteral: |
9389 | OS << "array requires initializer list or wide string literal" ; |
9390 | break; |
9391 | |
9392 | case FK_NarrowStringIntoWideCharArray: |
9393 | OS << "narrow string into wide char array" ; |
9394 | break; |
9395 | |
9396 | case FK_WideStringIntoCharArray: |
9397 | OS << "wide string into char array" ; |
9398 | break; |
9399 | |
9400 | case FK_IncompatWideStringIntoWideChar: |
9401 | OS << "incompatible wide string into wide char array" ; |
9402 | break; |
9403 | |
9404 | case FK_PlainStringIntoUTF8Char: |
9405 | OS << "plain string literal into char8_t array" ; |
9406 | break; |
9407 | |
9408 | case FK_UTF8StringIntoPlainChar: |
9409 | OS << "u8 string literal into char array" ; |
9410 | break; |
9411 | |
9412 | case FK_ArrayTypeMismatch: |
9413 | OS << "array type mismatch" ; |
9414 | break; |
9415 | |
9416 | case FK_NonConstantArrayInit: |
9417 | OS << "non-constant array initializer" ; |
9418 | break; |
9419 | |
9420 | case FK_AddressOfOverloadFailed: |
9421 | OS << "address of overloaded function failed" ; |
9422 | break; |
9423 | |
9424 | case FK_ReferenceInitOverloadFailed: |
9425 | OS << "overload resolution for reference initialization failed" ; |
9426 | break; |
9427 | |
9428 | case FK_NonConstLValueReferenceBindingToTemporary: |
9429 | OS << "non-const lvalue reference bound to temporary" ; |
9430 | break; |
9431 | |
9432 | case FK_NonConstLValueReferenceBindingToBitfield: |
9433 | OS << "non-const lvalue reference bound to bit-field" ; |
9434 | break; |
9435 | |
9436 | case FK_NonConstLValueReferenceBindingToVectorElement: |
9437 | OS << "non-const lvalue reference bound to vector element" ; |
9438 | break; |
9439 | |
9440 | case FK_NonConstLValueReferenceBindingToMatrixElement: |
9441 | OS << "non-const lvalue reference bound to matrix element" ; |
9442 | break; |
9443 | |
9444 | case FK_NonConstLValueReferenceBindingToUnrelated: |
9445 | OS << "non-const lvalue reference bound to unrelated type" ; |
9446 | break; |
9447 | |
9448 | case FK_RValueReferenceBindingToLValue: |
9449 | OS << "rvalue reference bound to an lvalue" ; |
9450 | break; |
9451 | |
9452 | case FK_ReferenceInitDropsQualifiers: |
9453 | OS << "reference initialization drops qualifiers" ; |
9454 | break; |
9455 | |
9456 | case FK_ReferenceAddrspaceMismatchTemporary: |
9457 | OS << "reference with mismatching address space bound to temporary" ; |
9458 | break; |
9459 | |
9460 | case FK_ReferenceInitFailed: |
9461 | OS << "reference initialization failed" ; |
9462 | break; |
9463 | |
9464 | case FK_ConversionFailed: |
9465 | OS << "conversion failed" ; |
9466 | break; |
9467 | |
9468 | case FK_ConversionFromPropertyFailed: |
9469 | OS << "conversion from property failed" ; |
9470 | break; |
9471 | |
9472 | case FK_TooManyInitsForScalar: |
9473 | OS << "too many initializers for scalar" ; |
9474 | break; |
9475 | |
9476 | case FK_ParenthesizedListInitForScalar: |
9477 | OS << "parenthesized list init for reference" ; |
9478 | break; |
9479 | |
9480 | case FK_ReferenceBindingToInitList: |
9481 | OS << "referencing binding to initializer list" ; |
9482 | break; |
9483 | |
9484 | case FK_InitListBadDestinationType: |
9485 | OS << "initializer list for non-aggregate, non-scalar type" ; |
9486 | break; |
9487 | |
9488 | case FK_UserConversionOverloadFailed: |
9489 | OS << "overloading failed for user-defined conversion" ; |
9490 | break; |
9491 | |
9492 | case FK_ConstructorOverloadFailed: |
9493 | OS << "constructor overloading failed" ; |
9494 | break; |
9495 | |
9496 | case FK_DefaultInitOfConst: |
9497 | OS << "default initialization of a const variable" ; |
9498 | break; |
9499 | |
9500 | case FK_Incomplete: |
9501 | OS << "initialization of incomplete type" ; |
9502 | break; |
9503 | |
9504 | case FK_ListInitializationFailed: |
9505 | OS << "list initialization checker failure" ; |
9506 | break; |
9507 | |
9508 | case FK_VariableLengthArrayHasInitializer: |
9509 | OS << "variable length array has an initializer" ; |
9510 | break; |
9511 | |
9512 | case FK_PlaceholderType: |
9513 | OS << "initializer expression isn't contextually valid" ; |
9514 | break; |
9515 | |
9516 | case FK_ListConstructorOverloadFailed: |
9517 | OS << "list constructor overloading failed" ; |
9518 | break; |
9519 | |
9520 | case FK_ExplicitConstructor: |
9521 | OS << "list copy initialization chose explicit constructor" ; |
9522 | break; |
9523 | |
9524 | case FK_ParenthesizedListInitFailed: |
9525 | OS << "parenthesized list initialization failed" ; |
9526 | break; |
9527 | |
9528 | case FK_DesignatedInitForNonAggregate: |
9529 | OS << "designated initializer for non-aggregate type" ; |
9530 | break; |
9531 | } |
9532 | OS << '\n'; |
9533 | return; |
9534 | } |
9535 | |
9536 | case DependentSequence: |
9537 | OS << "Dependent sequence\n" ; |
9538 | return; |
9539 | |
9540 | case NormalSequence: |
9541 | OS << "Normal sequence: " ; |
9542 | break; |
9543 | } |
9544 | |
9545 | for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) { |
9546 | if (S != step_begin()) { |
9547 | OS << " -> " ; |
9548 | } |
9549 | |
9550 | switch (S->Kind) { |
9551 | case SK_ResolveAddressOfOverloadedFunction: |
9552 | OS << "resolve address of overloaded function" ; |
9553 | break; |
9554 | |
9555 | case SK_CastDerivedToBasePRValue: |
9556 | OS << "derived-to-base (prvalue)" ; |
9557 | break; |
9558 | |
9559 | case SK_CastDerivedToBaseXValue: |
9560 | OS << "derived-to-base (xvalue)" ; |
9561 | break; |
9562 | |
9563 | case SK_CastDerivedToBaseLValue: |
9564 | OS << "derived-to-base (lvalue)" ; |
9565 | break; |
9566 | |
9567 | case SK_BindReference: |
9568 | OS << "bind reference to lvalue" ; |
9569 | break; |
9570 | |
9571 | case SK_BindReferenceToTemporary: |
9572 | OS << "bind reference to a temporary" ; |
9573 | break; |
9574 | |
9575 | case SK_FinalCopy: |
9576 | OS << "final copy in class direct-initialization" ; |
9577 | break; |
9578 | |
9579 | case SK_ExtraneousCopyToTemporary: |
9580 | OS << "extraneous C++03 copy to temporary" ; |
9581 | break; |
9582 | |
9583 | case SK_UserConversion: |
9584 | OS << "user-defined conversion via " << *S->Function.Function; |
9585 | break; |
9586 | |
9587 | case SK_QualificationConversionPRValue: |
9588 | OS << "qualification conversion (prvalue)" ; |
9589 | break; |
9590 | |
9591 | case SK_QualificationConversionXValue: |
9592 | OS << "qualification conversion (xvalue)" ; |
9593 | break; |
9594 | |
9595 | case SK_QualificationConversionLValue: |
9596 | OS << "qualification conversion (lvalue)" ; |
9597 | break; |
9598 | |
9599 | case SK_FunctionReferenceConversion: |
9600 | OS << "function reference conversion" ; |
9601 | break; |
9602 | |
9603 | case SK_AtomicConversion: |
9604 | OS << "non-atomic-to-atomic conversion" ; |
9605 | break; |
9606 | |
9607 | case SK_ConversionSequence: |
9608 | OS << "implicit conversion sequence (" ; |
9609 | S->ICS->dump(); // FIXME: use OS |
9610 | OS << ")" ; |
9611 | break; |
9612 | |
9613 | case SK_ConversionSequenceNoNarrowing: |
9614 | OS << "implicit conversion sequence with narrowing prohibited (" ; |
9615 | S->ICS->dump(); // FIXME: use OS |
9616 | OS << ")" ; |
9617 | break; |
9618 | |
9619 | case SK_ListInitialization: |
9620 | OS << "list aggregate initialization" ; |
9621 | break; |
9622 | |
9623 | case SK_UnwrapInitList: |
9624 | OS << "unwrap reference initializer list" ; |
9625 | break; |
9626 | |
9627 | case SK_RewrapInitList: |
9628 | OS << "rewrap reference initializer list" ; |
9629 | break; |
9630 | |
9631 | case SK_ConstructorInitialization: |
9632 | OS << "constructor initialization" ; |
9633 | break; |
9634 | |
9635 | case SK_ConstructorInitializationFromList: |
9636 | OS << "list initialization via constructor" ; |
9637 | break; |
9638 | |
9639 | case SK_ZeroInitialization: |
9640 | OS << "zero initialization" ; |
9641 | break; |
9642 | |
9643 | case SK_CAssignment: |
9644 | OS << "C assignment" ; |
9645 | break; |
9646 | |
9647 | case SK_StringInit: |
9648 | OS << "string initialization" ; |
9649 | break; |
9650 | |
9651 | case SK_ObjCObjectConversion: |
9652 | OS << "Objective-C object conversion" ; |
9653 | break; |
9654 | |
9655 | case SK_ArrayLoopIndex: |
9656 | OS << "indexing for array initialization loop" ; |
9657 | break; |
9658 | |
9659 | case SK_ArrayLoopInit: |
9660 | OS << "array initialization loop" ; |
9661 | break; |
9662 | |
9663 | case SK_ArrayInit: |
9664 | OS << "array initialization" ; |
9665 | break; |
9666 | |
9667 | case SK_GNUArrayInit: |
9668 | OS << "array initialization (GNU extension)" ; |
9669 | break; |
9670 | |
9671 | case SK_ParenthesizedArrayInit: |
9672 | OS << "parenthesized array initialization" ; |
9673 | break; |
9674 | |
9675 | case SK_PassByIndirectCopyRestore: |
9676 | OS << "pass by indirect copy and restore" ; |
9677 | break; |
9678 | |
9679 | case SK_PassByIndirectRestore: |
9680 | OS << "pass by indirect restore" ; |
9681 | break; |
9682 | |
9683 | case SK_ProduceObjCObject: |
9684 | OS << "Objective-C object retension" ; |
9685 | break; |
9686 | |
9687 | case SK_StdInitializerList: |
9688 | OS << "std::initializer_list from initializer list" ; |
9689 | break; |
9690 | |
9691 | case SK_StdInitializerListConstructorCall: |
9692 | OS << "list initialization from std::initializer_list" ; |
9693 | break; |
9694 | |
9695 | case SK_OCLSamplerInit: |
9696 | OS << "OpenCL sampler_t from integer constant" ; |
9697 | break; |
9698 | |
9699 | case SK_OCLZeroOpaqueType: |
9700 | OS << "OpenCL opaque type from zero" ; |
9701 | break; |
9702 | case SK_ParenthesizedListInit: |
9703 | OS << "initialization from a parenthesized list of values" ; |
9704 | break; |
9705 | } |
9706 | |
9707 | OS << " [" << S->Type << ']'; |
9708 | } |
9709 | |
9710 | OS << '\n'; |
9711 | } |
9712 | |
9713 | void InitializationSequence::dump() const { |
9714 | dump(OS&: llvm::errs()); |
9715 | } |
9716 | |
9717 | static void DiagnoseNarrowingInInitList(Sema &S, |
9718 | const ImplicitConversionSequence &ICS, |
9719 | QualType PreNarrowingType, |
9720 | QualType EntityType, |
9721 | const Expr *PostInit) { |
9722 | const StandardConversionSequence *SCS = nullptr; |
9723 | switch (ICS.getKind()) { |
9724 | case ImplicitConversionSequence::StandardConversion: |
9725 | SCS = &ICS.Standard; |
9726 | break; |
9727 | case ImplicitConversionSequence::UserDefinedConversion: |
9728 | SCS = &ICS.UserDefined.After; |
9729 | break; |
9730 | case ImplicitConversionSequence::AmbiguousConversion: |
9731 | case ImplicitConversionSequence::StaticObjectArgumentConversion: |
9732 | case ImplicitConversionSequence::EllipsisConversion: |
9733 | case ImplicitConversionSequence::BadConversion: |
9734 | return; |
9735 | } |
9736 | |
9737 | auto MakeDiag = [&](bool IsConstRef, unsigned DefaultDiagID, |
9738 | unsigned ConstRefDiagID, unsigned WarnDiagID) { |
9739 | unsigned DiagID; |
9740 | auto &L = S.getLangOpts(); |
9741 | if (L.CPlusPlus11 && !L.HLSL && |
9742 | (!L.MicrosoftExt || L.isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015))) |
9743 | DiagID = IsConstRef ? ConstRefDiagID : DefaultDiagID; |
9744 | else |
9745 | DiagID = WarnDiagID; |
9746 | return S.Diag(Loc: PostInit->getBeginLoc(), DiagID) |
9747 | << PostInit->getSourceRange(); |
9748 | }; |
9749 | |
9750 | // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion. |
9751 | APValue ConstantValue; |
9752 | QualType ConstantType; |
9753 | switch (SCS->getNarrowingKind(Context&: S.Context, Converted: PostInit, ConstantValue, |
9754 | ConstantType)) { |
9755 | case NK_Not_Narrowing: |
9756 | case NK_Dependent_Narrowing: |
9757 | // No narrowing occurred. |
9758 | return; |
9759 | |
9760 | case NK_Type_Narrowing: { |
9761 | // This was a floating-to-integer conversion, which is always considered a |
9762 | // narrowing conversion even if the value is a constant and can be |
9763 | // represented exactly as an integer. |
9764 | QualType T = EntityType.getNonReferenceType(); |
9765 | MakeDiag(T != EntityType, diag::ext_init_list_type_narrowing, |
9766 | diag::ext_init_list_type_narrowing_const_reference, |
9767 | diag::warn_init_list_type_narrowing) |
9768 | << PreNarrowingType.getLocalUnqualifiedType() |
9769 | << T.getLocalUnqualifiedType(); |
9770 | break; |
9771 | } |
9772 | |
9773 | case NK_Constant_Narrowing: { |
9774 | // A constant value was narrowed. |
9775 | MakeDiag(EntityType.getNonReferenceType() != EntityType, |
9776 | diag::ext_init_list_constant_narrowing, |
9777 | diag::ext_init_list_constant_narrowing_const_reference, |
9778 | diag::warn_init_list_constant_narrowing) |
9779 | << ConstantValue.getAsString(Ctx: S.getASTContext(), Ty: ConstantType) |
9780 | << EntityType.getNonReferenceType().getLocalUnqualifiedType(); |
9781 | break; |
9782 | } |
9783 | |
9784 | case NK_Variable_Narrowing: { |
9785 | // A variable's value may have been narrowed. |
9786 | MakeDiag(EntityType.getNonReferenceType() != EntityType, |
9787 | diag::ext_init_list_variable_narrowing, |
9788 | diag::ext_init_list_variable_narrowing_const_reference, |
9789 | diag::warn_init_list_variable_narrowing) |
9790 | << PreNarrowingType.getLocalUnqualifiedType() |
9791 | << EntityType.getNonReferenceType().getLocalUnqualifiedType(); |
9792 | break; |
9793 | } |
9794 | } |
9795 | |
9796 | SmallString<128> StaticCast; |
9797 | llvm::raw_svector_ostream OS(StaticCast); |
9798 | OS << "static_cast<" ; |
9799 | if (const TypedefType *TT = EntityType->getAs<TypedefType>()) { |
9800 | // It's important to use the typedef's name if there is one so that the |
9801 | // fixit doesn't break code using types like int64_t. |
9802 | // |
9803 | // FIXME: This will break if the typedef requires qualification. But |
9804 | // getQualifiedNameAsString() includes non-machine-parsable components. |
9805 | OS << *TT->getDecl(); |
9806 | } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>()) |
9807 | OS << BT->getName(Policy: S.getLangOpts()); |
9808 | else { |
9809 | // Oops, we didn't find the actual type of the variable. Don't emit a fixit |
9810 | // with a broken cast. |
9811 | return; |
9812 | } |
9813 | OS << ">(" ; |
9814 | S.Diag(Loc: PostInit->getBeginLoc(), DiagID: diag::note_init_list_narrowing_silence) |
9815 | << PostInit->getSourceRange() |
9816 | << FixItHint::CreateInsertion(InsertionLoc: PostInit->getBeginLoc(), Code: OS.str()) |
9817 | << FixItHint::CreateInsertion( |
9818 | InsertionLoc: S.getLocForEndOfToken(Loc: PostInit->getEndLoc()), Code: ")" ); |
9819 | } |
9820 | |
9821 | static void CheckC23ConstexprInitConversion(Sema &S, QualType FromType, |
9822 | QualType ToType, Expr *Init) { |
9823 | assert(S.getLangOpts().C23); |
9824 | ImplicitConversionSequence ICS = S.TryImplicitConversion( |
9825 | From: Init->IgnoreParenImpCasts(), ToType, /*SuppressUserConversions*/ false, |
9826 | AllowExplicit: Sema::AllowedExplicit::None, |
9827 | /*InOverloadResolution*/ false, |
9828 | /*CStyle*/ false, |
9829 | /*AllowObjCWritebackConversion=*/false); |
9830 | |
9831 | if (!ICS.isStandard()) |
9832 | return; |
9833 | |
9834 | APValue Value; |
9835 | QualType PreNarrowingType; |
9836 | // Reuse C++ narrowing check. |
9837 | switch (ICS.Standard.getNarrowingKind( |
9838 | Context&: S.Context, Converted: Init, ConstantValue&: Value, ConstantType&: PreNarrowingType, |
9839 | /*IgnoreFloatToIntegralConversion*/ false)) { |
9840 | // The value doesn't fit. |
9841 | case NK_Constant_Narrowing: |
9842 | S.Diag(Loc: Init->getBeginLoc(), DiagID: diag::err_c23_constexpr_init_not_representable) |
9843 | << Value.getAsString(Ctx: S.Context, Ty: PreNarrowingType) << ToType; |
9844 | return; |
9845 | |
9846 | // Conversion to a narrower type. |
9847 | case NK_Type_Narrowing: |
9848 | S.Diag(Loc: Init->getBeginLoc(), DiagID: diag::err_c23_constexpr_init_type_mismatch) |
9849 | << ToType << FromType; |
9850 | return; |
9851 | |
9852 | // Since we only reuse narrowing check for C23 constexpr variables here, we're |
9853 | // not really interested in these cases. |
9854 | case NK_Dependent_Narrowing: |
9855 | case NK_Variable_Narrowing: |
9856 | case NK_Not_Narrowing: |
9857 | return; |
9858 | } |
9859 | llvm_unreachable("unhandled case in switch" ); |
9860 | } |
9861 | |
9862 | static void CheckC23ConstexprInitStringLiteral(const StringLiteral *SE, |
9863 | Sema &SemaRef, QualType &TT) { |
9864 | assert(SemaRef.getLangOpts().C23); |
9865 | // character that string literal contains fits into TT - target type. |
9866 | const ArrayType *AT = SemaRef.Context.getAsArrayType(T: TT); |
9867 | QualType CharType = AT->getElementType(); |
9868 | uint32_t BitWidth = SemaRef.Context.getTypeSize(T: CharType); |
9869 | bool isUnsigned = CharType->isUnsignedIntegerType(); |
9870 | llvm::APSInt Value(BitWidth, isUnsigned); |
9871 | for (unsigned I = 0, N = SE->getLength(); I != N; ++I) { |
9872 | int64_t C = SE->getCodeUnitS(I, BitWidth: SemaRef.Context.getCharWidth()); |
9873 | Value = C; |
9874 | if (Value != C) { |
9875 | SemaRef.Diag(Loc: SemaRef.getLocationOfStringLiteralByte(SL: SE, ByteNo: I), |
9876 | DiagID: diag::err_c23_constexpr_init_not_representable) |
9877 | << C << CharType; |
9878 | return; |
9879 | } |
9880 | } |
9881 | } |
9882 | |
9883 | //===----------------------------------------------------------------------===// |
9884 | // Initialization helper functions |
9885 | //===----------------------------------------------------------------------===// |
9886 | bool |
9887 | Sema::CanPerformCopyInitialization(const InitializedEntity &Entity, |
9888 | ExprResult Init) { |
9889 | if (Init.isInvalid()) |
9890 | return false; |
9891 | |
9892 | Expr *InitE = Init.get(); |
9893 | assert(InitE && "No initialization expression" ); |
9894 | |
9895 | InitializationKind Kind = |
9896 | InitializationKind::CreateCopy(InitLoc: InitE->getBeginLoc(), EqualLoc: SourceLocation()); |
9897 | InitializationSequence Seq(*this, Entity, Kind, InitE); |
9898 | return !Seq.Failed(); |
9899 | } |
9900 | |
9901 | ExprResult |
9902 | Sema::PerformCopyInitialization(const InitializedEntity &Entity, |
9903 | SourceLocation EqualLoc, |
9904 | ExprResult Init, |
9905 | bool TopLevelOfInitList, |
9906 | bool AllowExplicit) { |
9907 | if (Init.isInvalid()) |
9908 | return ExprError(); |
9909 | |
9910 | Expr *InitE = Init.get(); |
9911 | assert(InitE && "No initialization expression?" ); |
9912 | |
9913 | if (EqualLoc.isInvalid()) |
9914 | EqualLoc = InitE->getBeginLoc(); |
9915 | |
9916 | InitializationKind Kind = InitializationKind::CreateCopy( |
9917 | InitLoc: InitE->getBeginLoc(), EqualLoc, AllowExplicitConvs: AllowExplicit); |
9918 | InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList); |
9919 | |
9920 | // Prevent infinite recursion when performing parameter copy-initialization. |
9921 | const bool ShouldTrackCopy = |
9922 | Entity.isParameterKind() && Seq.isConstructorInitialization(); |
9923 | if (ShouldTrackCopy) { |
9924 | if (llvm::is_contained(Range&: CurrentParameterCopyTypes, Element: Entity.getType())) { |
9925 | Seq.SetOverloadFailure( |
9926 | Failure: InitializationSequence::FK_ConstructorOverloadFailed, |
9927 | Result: OR_No_Viable_Function); |
9928 | |
9929 | // Try to give a meaningful diagnostic note for the problematic |
9930 | // constructor. |
9931 | const auto LastStep = Seq.step_end() - 1; |
9932 | assert(LastStep->Kind == |
9933 | InitializationSequence::SK_ConstructorInitialization); |
9934 | const FunctionDecl *Function = LastStep->Function.Function; |
9935 | auto Candidate = |
9936 | llvm::find_if(Range&: Seq.getFailedCandidateSet(), |
9937 | P: [Function](const OverloadCandidate &Candidate) -> bool { |
9938 | return Candidate.Viable && |
9939 | Candidate.Function == Function && |
9940 | Candidate.Conversions.size() > 0; |
9941 | }); |
9942 | if (Candidate != Seq.getFailedCandidateSet().end() && |
9943 | Function->getNumParams() > 0) { |
9944 | Candidate->Viable = false; |
9945 | Candidate->FailureKind = ovl_fail_bad_conversion; |
9946 | Candidate->Conversions[0].setBad(Failure: BadConversionSequence::no_conversion, |
9947 | FromExpr: InitE, |
9948 | ToType: Function->getParamDecl(i: 0)->getType()); |
9949 | } |
9950 | } |
9951 | CurrentParameterCopyTypes.push_back(Elt: Entity.getType()); |
9952 | } |
9953 | |
9954 | ExprResult Result = Seq.Perform(S&: *this, Entity, Kind, Args: InitE); |
9955 | |
9956 | if (ShouldTrackCopy) |
9957 | CurrentParameterCopyTypes.pop_back(); |
9958 | |
9959 | return Result; |
9960 | } |
9961 | |
9962 | /// Determine whether RD is, or is derived from, a specialization of CTD. |
9963 | static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD, |
9964 | ClassTemplateDecl *CTD) { |
9965 | auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) { |
9966 | auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Candidate); |
9967 | return !CTSD || !declaresSameEntity(D1: CTSD->getSpecializedTemplate(), D2: CTD); |
9968 | }; |
9969 | return !(NotSpecialization(RD) && RD->forallBases(BaseMatches: NotSpecialization)); |
9970 | } |
9971 | |
9972 | QualType Sema::DeduceTemplateSpecializationFromInitializer( |
9973 | TypeSourceInfo *TSInfo, const InitializedEntity &Entity, |
9974 | const InitializationKind &Kind, MultiExprArg Inits) { |
9975 | auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>( |
9976 | Val: TSInfo->getType()->getContainedDeducedType()); |
9977 | assert(DeducedTST && "not a deduced template specialization type" ); |
9978 | |
9979 | auto TemplateName = DeducedTST->getTemplateName(); |
9980 | if (TemplateName.isDependent()) |
9981 | return SubstAutoTypeSourceInfoDependent(TypeWithAuto: TSInfo)->getType(); |
9982 | |
9983 | // We can only perform deduction for class templates or alias templates. |
9984 | auto *Template = |
9985 | dyn_cast_or_null<ClassTemplateDecl>(Val: TemplateName.getAsTemplateDecl()); |
9986 | TemplateDecl *LookupTemplateDecl = Template; |
9987 | if (!Template) { |
9988 | if (auto *AliasTemplate = dyn_cast_or_null<TypeAliasTemplateDecl>( |
9989 | Val: TemplateName.getAsTemplateDecl())) { |
9990 | DiagCompat(Loc: Kind.getLocation(), CompatDiagId: diag_compat::ctad_for_alias_templates); |
9991 | LookupTemplateDecl = AliasTemplate; |
9992 | auto UnderlyingType = AliasTemplate->getTemplatedDecl() |
9993 | ->getUnderlyingType() |
9994 | .getCanonicalType(); |
9995 | // C++ [over.match.class.deduct#3]: ..., the defining-type-id of A must be |
9996 | // of the form |
9997 | // [typename] [nested-name-specifier] [template] simple-template-id |
9998 | if (const auto *TST = |
9999 | UnderlyingType->getAs<TemplateSpecializationType>()) { |
10000 | Template = dyn_cast_or_null<ClassTemplateDecl>( |
10001 | Val: TST->getTemplateName().getAsTemplateDecl()); |
10002 | } else if (const auto *RT = UnderlyingType->getAs<RecordType>()) { |
10003 | // Cases where template arguments in the RHS of the alias are not |
10004 | // dependent. e.g. |
10005 | // using AliasFoo = Foo<bool>; |
10006 | if (const auto *CTSD = llvm::dyn_cast<ClassTemplateSpecializationDecl>( |
10007 | Val: RT->getAsCXXRecordDecl())) |
10008 | Template = CTSD->getSpecializedTemplate(); |
10009 | } |
10010 | } |
10011 | } |
10012 | if (!Template) { |
10013 | Diag(Loc: Kind.getLocation(), |
10014 | DiagID: diag::err_deduced_non_class_or_alias_template_specialization_type) |
10015 | << (int)getTemplateNameKindForDiagnostics(Name: TemplateName) << TemplateName; |
10016 | if (auto *TD = TemplateName.getAsTemplateDecl()) |
10017 | NoteTemplateLocation(Decl: *TD); |
10018 | return QualType(); |
10019 | } |
10020 | |
10021 | // Can't deduce from dependent arguments. |
10022 | if (Expr::hasAnyTypeDependentArguments(Exprs: Inits)) { |
10023 | Diag(Loc: TSInfo->getTypeLoc().getBeginLoc(), |
10024 | DiagID: diag::warn_cxx14_compat_class_template_argument_deduction) |
10025 | << TSInfo->getTypeLoc().getSourceRange() << 0; |
10026 | return SubstAutoTypeSourceInfoDependent(TypeWithAuto: TSInfo)->getType(); |
10027 | } |
10028 | |
10029 | // FIXME: Perform "exact type" matching first, per CWG discussion? |
10030 | // Or implement this via an implied 'T(T) -> T' deduction guide? |
10031 | |
10032 | // Look up deduction guides, including those synthesized from constructors. |
10033 | // |
10034 | // C++1z [over.match.class.deduct]p1: |
10035 | // A set of functions and function templates is formed comprising: |
10036 | // - For each constructor of the class template designated by the |
10037 | // template-name, a function template [...] |
10038 | // - For each deduction-guide, a function or function template [...] |
10039 | DeclarationNameInfo NameInfo( |
10040 | Context.DeclarationNames.getCXXDeductionGuideName(TD: LookupTemplateDecl), |
10041 | TSInfo->getTypeLoc().getEndLoc()); |
10042 | LookupResult Guides(*this, NameInfo, LookupOrdinaryName); |
10043 | LookupQualifiedName(R&: Guides, LookupCtx: LookupTemplateDecl->getDeclContext()); |
10044 | |
10045 | // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't |
10046 | // clear on this, but they're not found by name so access does not apply. |
10047 | Guides.suppressDiagnostics(); |
10048 | |
10049 | // Figure out if this is list-initialization. |
10050 | InitListExpr *ListInit = |
10051 | (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct) |
10052 | ? dyn_cast<InitListExpr>(Val: Inits[0]) |
10053 | : nullptr; |
10054 | |
10055 | // C++1z [over.match.class.deduct]p1: |
10056 | // Initialization and overload resolution are performed as described in |
10057 | // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list] |
10058 | // (as appropriate for the type of initialization performed) for an object |
10059 | // of a hypothetical class type, where the selected functions and function |
10060 | // templates are considered to be the constructors of that class type |
10061 | // |
10062 | // Since we know we're initializing a class type of a type unrelated to that |
10063 | // of the initializer, this reduces to something fairly reasonable. |
10064 | OverloadCandidateSet Candidates(Kind.getLocation(), |
10065 | OverloadCandidateSet::CSK_Normal); |
10066 | OverloadCandidateSet::iterator Best; |
10067 | |
10068 | bool AllowExplicit = !Kind.isCopyInit() || ListInit; |
10069 | |
10070 | // Return true if the candidate is added successfully, false otherwise. |
10071 | auto addDeductionCandidate = [&](FunctionTemplateDecl *TD, |
10072 | CXXDeductionGuideDecl *GD, |
10073 | DeclAccessPair FoundDecl, |
10074 | bool OnlyListConstructors, |
10075 | bool AllowAggregateDeductionCandidate) { |
10076 | // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class) |
10077 | // For copy-initialization, the candidate functions are all the |
10078 | // converting constructors (12.3.1) of that class. |
10079 | // C++ [over.match.copy]p1: (non-list copy-initialization from class) |
10080 | // The converting constructors of T are candidate functions. |
10081 | if (!AllowExplicit) { |
10082 | // Overload resolution checks whether the deduction guide is declared |
10083 | // explicit for us. |
10084 | |
10085 | // When looking for a converting constructor, deduction guides that |
10086 | // could never be called with one argument are not interesting to |
10087 | // check or note. |
10088 | if (GD->getMinRequiredArguments() > 1 || |
10089 | (GD->getNumParams() == 0 && !GD->isVariadic())) |
10090 | return; |
10091 | } |
10092 | |
10093 | // C++ [over.match.list]p1.1: (first phase list initialization) |
10094 | // Initially, the candidate functions are the initializer-list |
10095 | // constructors of the class T |
10096 | if (OnlyListConstructors && !isInitListConstructor(Ctor: GD)) |
10097 | return; |
10098 | |
10099 | if (!AllowAggregateDeductionCandidate && |
10100 | GD->getDeductionCandidateKind() == DeductionCandidate::Aggregate) |
10101 | return; |
10102 | |
10103 | // C++ [over.match.list]p1.2: (second phase list initialization) |
10104 | // the candidate functions are all the constructors of the class T |
10105 | // C++ [over.match.ctor]p1: (all other cases) |
10106 | // the candidate functions are all the constructors of the class of |
10107 | // the object being initialized |
10108 | |
10109 | // C++ [over.best.ics]p4: |
10110 | // When [...] the constructor [...] is a candidate by |
10111 | // - [over.match.copy] (in all cases) |
10112 | if (TD) { |
10113 | |
10114 | // As template candidates are not deduced immediately, |
10115 | // persist the array in the overload set. |
10116 | MutableArrayRef<Expr *> TmpInits = |
10117 | Candidates.getPersistentArgsArray(N: Inits.size()); |
10118 | |
10119 | for (auto [I, E] : llvm::enumerate(First&: Inits)) { |
10120 | if (auto *DI = dyn_cast<DesignatedInitExpr>(Val: E)) |
10121 | TmpInits[I] = DI->getInit(); |
10122 | else |
10123 | TmpInits[I] = E; |
10124 | } |
10125 | |
10126 | AddTemplateOverloadCandidate( |
10127 | FunctionTemplate: TD, FoundDecl, /*ExplicitArgs=*/ExplicitTemplateArgs: nullptr, Args: TmpInits, CandidateSet&: Candidates, |
10128 | /*SuppressUserConversions=*/false, |
10129 | /*PartialOverloading=*/false, AllowExplicit, IsADLCandidate: ADLCallKind::NotADL, |
10130 | /*PO=*/{}, AggregateCandidateDeduction: AllowAggregateDeductionCandidate); |
10131 | } else { |
10132 | AddOverloadCandidate(Function: GD, FoundDecl, Args: Inits, CandidateSet&: Candidates, |
10133 | /*SuppressUserConversions=*/false, |
10134 | /*PartialOverloading=*/false, AllowExplicit); |
10135 | } |
10136 | }; |
10137 | |
10138 | bool FoundDeductionGuide = false; |
10139 | |
10140 | auto TryToResolveOverload = |
10141 | [&](bool OnlyListConstructors) -> OverloadingResult { |
10142 | Candidates.clear(CSK: OverloadCandidateSet::CSK_Normal); |
10143 | bool HasAnyDeductionGuide = false; |
10144 | |
10145 | auto SynthesizeAggrGuide = [&](InitListExpr *ListInit) { |
10146 | auto *Pattern = Template; |
10147 | while (Pattern->getInstantiatedFromMemberTemplate()) { |
10148 | if (Pattern->isMemberSpecialization()) |
10149 | break; |
10150 | Pattern = Pattern->getInstantiatedFromMemberTemplate(); |
10151 | } |
10152 | |
10153 | auto *RD = cast<CXXRecordDecl>(Val: Pattern->getTemplatedDecl()); |
10154 | if (!(RD->getDefinition() && RD->isAggregate())) |
10155 | return; |
10156 | QualType Ty = Context.getRecordType(Decl: RD); |
10157 | SmallVector<QualType, 8> ElementTypes; |
10158 | |
10159 | InitListChecker CheckInitList(*this, Entity, ListInit, Ty, ElementTypes); |
10160 | if (!CheckInitList.HadError()) { |
10161 | // C++ [over.match.class.deduct]p1.8: |
10162 | // if e_i is of array type and x_i is a braced-init-list, T_i is an |
10163 | // rvalue reference to the declared type of e_i and |
10164 | // C++ [over.match.class.deduct]p1.9: |
10165 | // if e_i is of array type and x_i is a string-literal, T_i is an |
10166 | // lvalue reference to the const-qualified declared type of e_i and |
10167 | // C++ [over.match.class.deduct]p1.10: |
10168 | // otherwise, T_i is the declared type of e_i |
10169 | for (int I = 0, E = ListInit->getNumInits(); |
10170 | I < E && !isa<PackExpansionType>(Val: ElementTypes[I]); ++I) |
10171 | if (ElementTypes[I]->isArrayType()) { |
10172 | if (isa<InitListExpr, DesignatedInitExpr>(Val: ListInit->getInit(Init: I))) |
10173 | ElementTypes[I] = Context.getRValueReferenceType(T: ElementTypes[I]); |
10174 | else if (isa<StringLiteral>( |
10175 | Val: ListInit->getInit(Init: I)->IgnoreParenImpCasts())) |
10176 | ElementTypes[I] = |
10177 | Context.getLValueReferenceType(T: ElementTypes[I].withConst()); |
10178 | } |
10179 | |
10180 | if (FunctionTemplateDecl *TD = |
10181 | DeclareAggregateDeductionGuideFromInitList( |
10182 | Template: LookupTemplateDecl, ParamTypes: ElementTypes, |
10183 | Loc: TSInfo->getTypeLoc().getEndLoc())) { |
10184 | auto *GD = cast<CXXDeductionGuideDecl>(Val: TD->getTemplatedDecl()); |
10185 | addDeductionCandidate(TD, GD, DeclAccessPair::make(D: TD, AS: AS_public), |
10186 | OnlyListConstructors, |
10187 | /*AllowAggregateDeductionCandidate=*/true); |
10188 | HasAnyDeductionGuide = true; |
10189 | } |
10190 | } |
10191 | }; |
10192 | |
10193 | for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) { |
10194 | NamedDecl *D = (*I)->getUnderlyingDecl(); |
10195 | if (D->isInvalidDecl()) |
10196 | continue; |
10197 | |
10198 | auto *TD = dyn_cast<FunctionTemplateDecl>(Val: D); |
10199 | auto *GD = dyn_cast_if_present<CXXDeductionGuideDecl>( |
10200 | Val: TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(Val: D)); |
10201 | if (!GD) |
10202 | continue; |
10203 | |
10204 | if (!GD->isImplicit()) |
10205 | HasAnyDeductionGuide = true; |
10206 | |
10207 | addDeductionCandidate(TD, GD, I.getPair(), OnlyListConstructors, |
10208 | /*AllowAggregateDeductionCandidate=*/false); |
10209 | } |
10210 | |
10211 | // C++ [over.match.class.deduct]p1.4: |
10212 | // if C is defined and its definition satisfies the conditions for an |
10213 | // aggregate class ([dcl.init.aggr]) with the assumption that any |
10214 | // dependent base class has no virtual functions and no virtual base |
10215 | // classes, and the initializer is a non-empty braced-init-list or |
10216 | // parenthesized expression-list, and there are no deduction-guides for |
10217 | // C, the set contains an additional function template, called the |
10218 | // aggregate deduction candidate, defined as follows. |
10219 | if (getLangOpts().CPlusPlus20 && !HasAnyDeductionGuide) { |
10220 | if (ListInit && ListInit->getNumInits()) { |
10221 | SynthesizeAggrGuide(ListInit); |
10222 | } else if (Inits.size()) { // parenthesized expression-list |
10223 | // Inits are expressions inside the parentheses. We don't have |
10224 | // the parentheses source locations, use the begin/end of Inits as the |
10225 | // best heuristic. |
10226 | InitListExpr TempListInit(getASTContext(), Inits.front()->getBeginLoc(), |
10227 | Inits, Inits.back()->getEndLoc()); |
10228 | SynthesizeAggrGuide(&TempListInit); |
10229 | } |
10230 | } |
10231 | |
10232 | FoundDeductionGuide = FoundDeductionGuide || HasAnyDeductionGuide; |
10233 | |
10234 | return Candidates.BestViableFunction(S&: *this, Loc: Kind.getLocation(), Best); |
10235 | }; |
10236 | |
10237 | OverloadingResult Result = OR_No_Viable_Function; |
10238 | |
10239 | // C++11 [over.match.list]p1, per DR1467: for list-initialization, first |
10240 | // try initializer-list constructors. |
10241 | if (ListInit) { |
10242 | bool TryListConstructors = true; |
10243 | |
10244 | // Try list constructors unless the list is empty and the class has one or |
10245 | // more default constructors, in which case those constructors win. |
10246 | if (!ListInit->getNumInits()) { |
10247 | for (NamedDecl *D : Guides) { |
10248 | auto *FD = dyn_cast<FunctionDecl>(Val: D->getUnderlyingDecl()); |
10249 | if (FD && FD->getMinRequiredArguments() == 0) { |
10250 | TryListConstructors = false; |
10251 | break; |
10252 | } |
10253 | } |
10254 | } else if (ListInit->getNumInits() == 1) { |
10255 | // C++ [over.match.class.deduct]: |
10256 | // As an exception, the first phase in [over.match.list] (considering |
10257 | // initializer-list constructors) is omitted if the initializer list |
10258 | // consists of a single expression of type cv U, where U is a |
10259 | // specialization of C or a class derived from a specialization of C. |
10260 | Expr *E = ListInit->getInit(Init: 0); |
10261 | auto *RD = E->getType()->getAsCXXRecordDecl(); |
10262 | if (!isa<InitListExpr>(Val: E) && RD && |
10263 | isCompleteType(Loc: Kind.getLocation(), T: E->getType()) && |
10264 | isOrIsDerivedFromSpecializationOf(RD, CTD: Template)) |
10265 | TryListConstructors = false; |
10266 | } |
10267 | |
10268 | if (TryListConstructors) |
10269 | Result = TryToResolveOverload(/*OnlyListConstructor*/true); |
10270 | // Then unwrap the initializer list and try again considering all |
10271 | // constructors. |
10272 | Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits()); |
10273 | } |
10274 | |
10275 | // If list-initialization fails, or if we're doing any other kind of |
10276 | // initialization, we (eventually) consider constructors. |
10277 | if (Result == OR_No_Viable_Function) |
10278 | Result = TryToResolveOverload(/*OnlyListConstructor*/false); |
10279 | |
10280 | switch (Result) { |
10281 | case OR_Ambiguous: |
10282 | // FIXME: For list-initialization candidates, it'd usually be better to |
10283 | // list why they were not viable when given the initializer list itself as |
10284 | // an argument. |
10285 | Candidates.NoteCandidates( |
10286 | PA: PartialDiagnosticAt( |
10287 | Kind.getLocation(), |
10288 | PDiag(DiagID: diag::err_deduced_class_template_ctor_ambiguous) |
10289 | << TemplateName), |
10290 | S&: *this, OCD: OCD_AmbiguousCandidates, Args: Inits); |
10291 | return QualType(); |
10292 | |
10293 | case OR_No_Viable_Function: { |
10294 | CXXRecordDecl *Primary = |
10295 | cast<ClassTemplateDecl>(Val: Template)->getTemplatedDecl(); |
10296 | bool Complete = |
10297 | isCompleteType(Loc: Kind.getLocation(), T: Context.getTypeDeclType(Decl: Primary)); |
10298 | Candidates.NoteCandidates( |
10299 | PA: PartialDiagnosticAt( |
10300 | Kind.getLocation(), |
10301 | PDiag(DiagID: Complete ? diag::err_deduced_class_template_ctor_no_viable |
10302 | : diag::err_deduced_class_template_incomplete) |
10303 | << TemplateName << !Guides.empty()), |
10304 | S&: *this, OCD: OCD_AllCandidates, Args: Inits); |
10305 | return QualType(); |
10306 | } |
10307 | |
10308 | case OR_Deleted: { |
10309 | // FIXME: There are no tests for this diagnostic, and it doesn't seem |
10310 | // like we ever get here; attempts to trigger this seem to yield a |
10311 | // generic c'all to deleted function' diagnostic instead. |
10312 | Diag(Loc: Kind.getLocation(), DiagID: diag::err_deduced_class_template_deleted) |
10313 | << TemplateName; |
10314 | NoteDeletedFunction(FD: Best->Function); |
10315 | return QualType(); |
10316 | } |
10317 | |
10318 | case OR_Success: |
10319 | // C++ [over.match.list]p1: |
10320 | // In copy-list-initialization, if an explicit constructor is chosen, the |
10321 | // initialization is ill-formed. |
10322 | if (Kind.isCopyInit() && ListInit && |
10323 | cast<CXXDeductionGuideDecl>(Val: Best->Function)->isExplicit()) { |
10324 | bool IsDeductionGuide = !Best->Function->isImplicit(); |
10325 | Diag(Loc: Kind.getLocation(), DiagID: diag::err_deduced_class_template_explicit) |
10326 | << TemplateName << IsDeductionGuide; |
10327 | Diag(Loc: Best->Function->getLocation(), |
10328 | DiagID: diag::note_explicit_ctor_deduction_guide_here) |
10329 | << IsDeductionGuide; |
10330 | return QualType(); |
10331 | } |
10332 | |
10333 | // Make sure we didn't select an unusable deduction guide, and mark it |
10334 | // as referenced. |
10335 | DiagnoseUseOfDecl(D: Best->FoundDecl, Locs: Kind.getLocation()); |
10336 | MarkFunctionReferenced(Loc: Kind.getLocation(), Func: Best->Function); |
10337 | break; |
10338 | } |
10339 | |
10340 | // C++ [dcl.type.class.deduct]p1: |
10341 | // The placeholder is replaced by the return type of the function selected |
10342 | // by overload resolution for class template deduction. |
10343 | QualType DeducedType = |
10344 | SubstAutoTypeSourceInfo(TypeWithAuto: TSInfo, Replacement: Best->Function->getReturnType()) |
10345 | ->getType(); |
10346 | Diag(Loc: TSInfo->getTypeLoc().getBeginLoc(), |
10347 | DiagID: diag::warn_cxx14_compat_class_template_argument_deduction) |
10348 | << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType; |
10349 | |
10350 | // Warn if CTAD was used on a type that does not have any user-defined |
10351 | // deduction guides. |
10352 | if (!FoundDeductionGuide) { |
10353 | Diag(Loc: TSInfo->getTypeLoc().getBeginLoc(), |
10354 | DiagID: diag::warn_ctad_maybe_unsupported) |
10355 | << TemplateName; |
10356 | Diag(Loc: Template->getLocation(), DiagID: diag::note_suppress_ctad_maybe_unsupported); |
10357 | } |
10358 | |
10359 | return DeducedType; |
10360 | } |
10361 | |