1 | //===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | // This file implements semantic analysis for initializers. |
10 | // |
11 | //===----------------------------------------------------------------------===// |
12 | |
13 | #include "clang/AST/ASTContext.h" |
14 | #include "clang/AST/DeclObjC.h" |
15 | #include "clang/AST/Expr.h" |
16 | #include "clang/AST/ExprCXX.h" |
17 | #include "clang/AST/ExprObjC.h" |
18 | #include "clang/AST/ExprOpenMP.h" |
19 | #include "clang/AST/IgnoreExpr.h" |
20 | #include "clang/AST/TypeLoc.h" |
21 | #include "clang/Basic/CharInfo.h" |
22 | #include "clang/Basic/SourceManager.h" |
23 | #include "clang/Basic/Specifiers.h" |
24 | #include "clang/Basic/TargetInfo.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/SemaInternal.h" |
31 | #include "llvm/ADT/APInt.h" |
32 | #include "llvm/ADT/FoldingSet.h" |
33 | #include "llvm/ADT/PointerIntPair.h" |
34 | #include "llvm/ADT/SmallString.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 | // char array can be initialized with a narrow string. |
110 | // Only allow char x[] = "foo"; not char x[] = L"foo"; |
111 | if (ElemTy->isCharType()) |
112 | return (SL->getKind() == StringLiteralKind::UTF8 && |
113 | Context.getLangOpts().Char8) |
114 | ? SIF_UTF8StringIntoPlainChar |
115 | : SIF_None; |
116 | if (ElemTy->isChar8Type()) |
117 | return SIF_PlainStringIntoUTF8Char; |
118 | if (IsWideCharCompatible(T: ElemTy, Context)) |
119 | return SIF_NarrowStringIntoWideChar; |
120 | return SIF_Other; |
121 | // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15: |
122 | // "An array with element type compatible with a qualified or unqualified |
123 | // version of wchar_t, char16_t, or char32_t may be initialized by a wide |
124 | // string literal with the corresponding encoding prefix (L, u, or U, |
125 | // respectively), optionally enclosed in braces. |
126 | case StringLiteralKind::UTF16: |
127 | if (Context.typesAreCompatible(T1: Context.Char16Ty, T2: ElemTy)) |
128 | return SIF_None; |
129 | if (ElemTy->isCharType() || ElemTy->isChar8Type()) |
130 | return SIF_WideStringIntoChar; |
131 | if (IsWideCharCompatible(T: ElemTy, Context)) |
132 | return SIF_IncompatWideStringIntoWideChar; |
133 | return SIF_Other; |
134 | case StringLiteralKind::UTF32: |
135 | if (Context.typesAreCompatible(T1: Context.Char32Ty, T2: ElemTy)) |
136 | return SIF_None; |
137 | if (ElemTy->isCharType() || ElemTy->isChar8Type()) |
138 | return SIF_WideStringIntoChar; |
139 | if (IsWideCharCompatible(T: ElemTy, Context)) |
140 | return SIF_IncompatWideStringIntoWideChar; |
141 | return SIF_Other; |
142 | case StringLiteralKind::Wide: |
143 | if (Context.typesAreCompatible(T1: Context.getWideCharType(), T2: ElemTy)) |
144 | return SIF_None; |
145 | if (ElemTy->isCharType() || ElemTy->isChar8Type()) |
146 | return SIF_WideStringIntoChar; |
147 | if (IsWideCharCompatible(T: ElemTy, Context)) |
148 | return SIF_IncompatWideStringIntoWideChar; |
149 | return SIF_Other; |
150 | case StringLiteralKind::Unevaluated: |
151 | assert(false && "Unevaluated string literal in initialization" ); |
152 | break; |
153 | } |
154 | |
155 | llvm_unreachable("missed a StringLiteral kind?" ); |
156 | } |
157 | |
158 | static StringInitFailureKind IsStringInit(Expr *init, QualType declType, |
159 | ASTContext &Context) { |
160 | const ArrayType *arrayType = Context.getAsArrayType(T: declType); |
161 | if (!arrayType) |
162 | return SIF_Other; |
163 | return IsStringInit(Init: init, AT: arrayType, Context); |
164 | } |
165 | |
166 | bool Sema::IsStringInit(Expr *Init, const ArrayType *AT) { |
167 | return ::IsStringInit(Init, AT, Context) == SIF_None; |
168 | } |
169 | |
170 | /// Update the type of a string literal, including any surrounding parentheses, |
171 | /// to match the type of the object which it is initializing. |
172 | static void updateStringLiteralType(Expr *E, QualType Ty) { |
173 | while (true) { |
174 | E->setType(Ty); |
175 | E->setValueKind(VK_PRValue); |
176 | if (isa<StringLiteral>(Val: E) || isa<ObjCEncodeExpr>(Val: E)) |
177 | break; |
178 | E = IgnoreParensSingleStep(E); |
179 | } |
180 | } |
181 | |
182 | /// Fix a compound literal initializing an array so it's correctly marked |
183 | /// as an rvalue. |
184 | static void updateGNUCompoundLiteralRValue(Expr *E) { |
185 | while (true) { |
186 | E->setValueKind(VK_PRValue); |
187 | if (isa<CompoundLiteralExpr>(Val: E)) |
188 | break; |
189 | E = IgnoreParensSingleStep(E); |
190 | } |
191 | } |
192 | |
193 | static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT, |
194 | Sema &S) { |
195 | // Get the length of the string as parsed. |
196 | auto *ConstantArrayTy = |
197 | cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe()); |
198 | uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue(); |
199 | |
200 | if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(Val: AT)) { |
201 | // C99 6.7.8p14. We have an array of character type with unknown size |
202 | // being initialized to a string literal. |
203 | llvm::APInt ConstVal(32, StrLength); |
204 | // Return a new array type (C99 6.7.8p22). |
205 | DeclT = S.Context.getConstantArrayType( |
206 | EltTy: IAT->getElementType(), ArySize: ConstVal, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0); |
207 | updateStringLiteralType(E: Str, Ty: DeclT); |
208 | return; |
209 | } |
210 | |
211 | const ConstantArrayType *CAT = cast<ConstantArrayType>(Val: AT); |
212 | |
213 | // We have an array of character type with known size. However, |
214 | // the size may be smaller or larger than the string we are initializing. |
215 | // FIXME: Avoid truncation for 64-bit length strings. |
216 | if (S.getLangOpts().CPlusPlus) { |
217 | if (StringLiteral *SL = dyn_cast<StringLiteral>(Val: Str->IgnoreParens())) { |
218 | // For Pascal strings it's OK to strip off the terminating null character, |
219 | // so the example below is valid: |
220 | // |
221 | // unsigned char a[2] = "\pa"; |
222 | if (SL->isPascal()) |
223 | StrLength--; |
224 | } |
225 | |
226 | // [dcl.init.string]p2 |
227 | if (StrLength > CAT->getSize().getZExtValue()) |
228 | S.Diag(Str->getBeginLoc(), |
229 | diag::err_initializer_string_for_char_array_too_long) |
230 | << CAT->getSize().getZExtValue() << StrLength |
231 | << Str->getSourceRange(); |
232 | } else { |
233 | // C99 6.7.8p14. |
234 | if (StrLength-1 > CAT->getSize().getZExtValue()) |
235 | S.Diag(Str->getBeginLoc(), |
236 | diag::ext_initializer_string_for_char_array_too_long) |
237 | << Str->getSourceRange(); |
238 | } |
239 | |
240 | // Set the type to the actual size that we are initializing. If we have |
241 | // something like: |
242 | // char x[1] = "foo"; |
243 | // then this will set the string literal's type to char[1]. |
244 | updateStringLiteralType(E: Str, Ty: DeclT); |
245 | } |
246 | |
247 | //===----------------------------------------------------------------------===// |
248 | // Semantic checking for initializer lists. |
249 | //===----------------------------------------------------------------------===// |
250 | |
251 | namespace { |
252 | |
253 | /// Semantic checking for initializer lists. |
254 | /// |
255 | /// The InitListChecker class contains a set of routines that each |
256 | /// handle the initialization of a certain kind of entity, e.g., |
257 | /// arrays, vectors, struct/union types, scalars, etc. The |
258 | /// InitListChecker itself performs a recursive walk of the subobject |
259 | /// structure of the type to be initialized, while stepping through |
260 | /// the initializer list one element at a time. The IList and Index |
261 | /// parameters to each of the Check* routines contain the active |
262 | /// (syntactic) initializer list and the index into that initializer |
263 | /// list that represents the current initializer. Each routine is |
264 | /// responsible for moving that Index forward as it consumes elements. |
265 | /// |
266 | /// Each Check* routine also has a StructuredList/StructuredIndex |
267 | /// arguments, which contains the current "structured" (semantic) |
268 | /// initializer list and the index into that initializer list where we |
269 | /// are copying initializers as we map them over to the semantic |
270 | /// list. Once we have completed our recursive walk of the subobject |
271 | /// structure, we will have constructed a full semantic initializer |
272 | /// list. |
273 | /// |
274 | /// C99 designators cause changes in the initializer list traversal, |
275 | /// because they make the initialization "jump" into a specific |
276 | /// subobject and then continue the initialization from that |
277 | /// point. CheckDesignatedInitializer() recursively steps into the |
278 | /// designated subobject and manages backing out the recursion to |
279 | /// initialize the subobjects after the one designated. |
280 | /// |
281 | /// If an initializer list contains any designators, we build a placeholder |
282 | /// structured list even in 'verify only' mode, so that we can track which |
283 | /// elements need 'empty' initializtion. |
284 | class InitListChecker { |
285 | Sema &SemaRef; |
286 | bool hadError = false; |
287 | bool VerifyOnly; // No diagnostics. |
288 | bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode. |
289 | bool InOverloadResolution; |
290 | InitListExpr *FullyStructuredList = nullptr; |
291 | NoInitExpr *DummyExpr = nullptr; |
292 | SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr; |
293 | |
294 | NoInitExpr *getDummyInit() { |
295 | if (!DummyExpr) |
296 | DummyExpr = new (SemaRef.Context) NoInitExpr(SemaRef.Context.VoidTy); |
297 | return DummyExpr; |
298 | } |
299 | |
300 | void CheckImplicitInitList(const InitializedEntity &Entity, |
301 | InitListExpr *ParentIList, QualType T, |
302 | unsigned &Index, InitListExpr *StructuredList, |
303 | unsigned &StructuredIndex); |
304 | void CheckExplicitInitList(const InitializedEntity &Entity, |
305 | InitListExpr *IList, QualType &T, |
306 | InitListExpr *StructuredList, |
307 | bool TopLevelObject = false); |
308 | void CheckListElementTypes(const InitializedEntity &Entity, |
309 | InitListExpr *IList, QualType &DeclType, |
310 | bool SubobjectIsDesignatorContext, |
311 | unsigned &Index, |
312 | InitListExpr *StructuredList, |
313 | unsigned &StructuredIndex, |
314 | bool TopLevelObject = false); |
315 | void CheckSubElementType(const InitializedEntity &Entity, |
316 | InitListExpr *IList, QualType ElemType, |
317 | unsigned &Index, |
318 | InitListExpr *StructuredList, |
319 | unsigned &StructuredIndex, |
320 | bool DirectlyDesignated = false); |
321 | void CheckComplexType(const InitializedEntity &Entity, |
322 | InitListExpr *IList, QualType DeclType, |
323 | unsigned &Index, |
324 | InitListExpr *StructuredList, |
325 | unsigned &StructuredIndex); |
326 | void CheckScalarType(const InitializedEntity &Entity, |
327 | InitListExpr *IList, QualType DeclType, |
328 | unsigned &Index, |
329 | InitListExpr *StructuredList, |
330 | unsigned &StructuredIndex); |
331 | void CheckReferenceType(const InitializedEntity &Entity, |
332 | InitListExpr *IList, QualType DeclType, |
333 | unsigned &Index, |
334 | InitListExpr *StructuredList, |
335 | unsigned &StructuredIndex); |
336 | void CheckVectorType(const InitializedEntity &Entity, |
337 | InitListExpr *IList, QualType DeclType, unsigned &Index, |
338 | InitListExpr *StructuredList, |
339 | unsigned &StructuredIndex); |
340 | void CheckStructUnionTypes(const InitializedEntity &Entity, |
341 | InitListExpr *IList, QualType DeclType, |
342 | CXXRecordDecl::base_class_const_range Bases, |
343 | RecordDecl::field_iterator Field, |
344 | bool SubobjectIsDesignatorContext, unsigned &Index, |
345 | InitListExpr *StructuredList, |
346 | unsigned &StructuredIndex, |
347 | bool TopLevelObject = false); |
348 | void CheckArrayType(const InitializedEntity &Entity, |
349 | InitListExpr *IList, QualType &DeclType, |
350 | llvm::APSInt elementIndex, |
351 | bool SubobjectIsDesignatorContext, unsigned &Index, |
352 | InitListExpr *StructuredList, |
353 | unsigned &StructuredIndex); |
354 | bool CheckDesignatedInitializer(const InitializedEntity &Entity, |
355 | InitListExpr *IList, DesignatedInitExpr *DIE, |
356 | unsigned DesigIdx, |
357 | QualType &CurrentObjectType, |
358 | RecordDecl::field_iterator *NextField, |
359 | llvm::APSInt *NextElementIndex, |
360 | unsigned &Index, |
361 | InitListExpr *StructuredList, |
362 | unsigned &StructuredIndex, |
363 | bool FinishSubobjectInit, |
364 | bool TopLevelObject); |
365 | InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, |
366 | QualType CurrentObjectType, |
367 | InitListExpr *StructuredList, |
368 | unsigned StructuredIndex, |
369 | SourceRange InitRange, |
370 | bool IsFullyOverwritten = false); |
371 | void UpdateStructuredListElement(InitListExpr *StructuredList, |
372 | unsigned &StructuredIndex, |
373 | Expr *expr); |
374 | InitListExpr *createInitListExpr(QualType CurrentObjectType, |
375 | SourceRange InitRange, |
376 | unsigned ExpectedNumInits); |
377 | int numArrayElements(QualType DeclType); |
378 | int numStructUnionElements(QualType DeclType); |
379 | static RecordDecl *getRecordDecl(QualType DeclType); |
380 | |
381 | ExprResult PerformEmptyInit(SourceLocation Loc, |
382 | const InitializedEntity &Entity); |
383 | |
384 | /// Diagnose that OldInit (or part thereof) has been overridden by NewInit. |
385 | void diagnoseInitOverride(Expr *OldInit, SourceRange NewInitRange, |
386 | bool UnionOverride = false, |
387 | bool FullyOverwritten = true) { |
388 | // Overriding an initializer via a designator is valid with C99 designated |
389 | // initializers, but ill-formed with C++20 designated initializers. |
390 | unsigned DiagID = |
391 | SemaRef.getLangOpts().CPlusPlus |
392 | ? (UnionOverride ? diag::ext_initializer_union_overrides |
393 | : diag::ext_initializer_overrides) |
394 | : diag::warn_initializer_overrides; |
395 | |
396 | if (InOverloadResolution && SemaRef.getLangOpts().CPlusPlus) { |
397 | // In overload resolution, we have to strictly enforce the rules, and so |
398 | // don't allow any overriding of prior initializers. This matters for a |
399 | // case such as: |
400 | // |
401 | // union U { int a, b; }; |
402 | // struct S { int a, b; }; |
403 | // void f(U), f(S); |
404 | // |
405 | // Here, f({.a = 1, .b = 2}) is required to call the struct overload. For |
406 | // consistency, we disallow all overriding of prior initializers in |
407 | // overload resolution, not only overriding of union members. |
408 | hadError = true; |
409 | } else if (OldInit->getType().isDestructedType() && !FullyOverwritten) { |
410 | // If we'll be keeping around the old initializer but overwriting part of |
411 | // the object it initialized, and that object is not trivially |
412 | // destructible, this can leak. Don't allow that, not even as an |
413 | // extension. |
414 | // |
415 | // FIXME: It might be reasonable to allow this in cases where the part of |
416 | // the initializer that we're overriding has trivial destruction. |
417 | DiagID = diag::err_initializer_overrides_destructed; |
418 | } else if (!OldInit->getSourceRange().isValid()) { |
419 | // We need to check on source range validity because the previous |
420 | // initializer does not have to be an explicit initializer. e.g., |
421 | // |
422 | // struct P { int a, b; }; |
423 | // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 }; |
424 | // |
425 | // There is an overwrite taking place because the first braced initializer |
426 | // list "{ .a = 2 }" already provides value for .p.b (which is zero). |
427 | // |
428 | // Such overwrites are harmless, so we don't diagnose them. (Note that in |
429 | // C++, this cannot be reached unless we've already seen and diagnosed a |
430 | // different conformance issue, such as a mixture of designated and |
431 | // non-designated initializers or a multi-level designator.) |
432 | return; |
433 | } |
434 | |
435 | if (!VerifyOnly) { |
436 | SemaRef.Diag(Loc: NewInitRange.getBegin(), DiagID) |
437 | << NewInitRange << FullyOverwritten << OldInit->getType(); |
438 | SemaRef.Diag(OldInit->getBeginLoc(), diag::note_previous_initializer) |
439 | << (OldInit->HasSideEffects(SemaRef.Context) && FullyOverwritten) |
440 | << OldInit->getSourceRange(); |
441 | } |
442 | } |
443 | |
444 | // Explanation on the "FillWithNoInit" mode: |
445 | // |
446 | // Assume we have the following definitions (Case#1): |
447 | // struct P { char x[6][6]; } xp = { .x[1] = "bar" }; |
448 | // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' }; |
449 | // |
450 | // l.lp.x[1][0..1] should not be filled with implicit initializers because the |
451 | // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf". |
452 | // |
453 | // But if we have (Case#2): |
454 | // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } }; |
455 | // |
456 | // l.lp.x[1][0..1] are implicitly initialized and do not use values from the |
457 | // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0". |
458 | // |
459 | // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes" |
460 | // in the InitListExpr, the "holes" in Case#1 are filled not with empty |
461 | // initializers but with special "NoInitExpr" place holders, which tells the |
462 | // CodeGen not to generate any initializers for these parts. |
463 | void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base, |
464 | const InitializedEntity &ParentEntity, |
465 | InitListExpr *ILE, bool &RequiresSecondPass, |
466 | bool FillWithNoInit); |
467 | void FillInEmptyInitForField(unsigned Init, FieldDecl *Field, |
468 | const InitializedEntity &ParentEntity, |
469 | InitListExpr *ILE, bool &RequiresSecondPass, |
470 | bool FillWithNoInit = false); |
471 | void FillInEmptyInitializations(const InitializedEntity &Entity, |
472 | InitListExpr *ILE, bool &RequiresSecondPass, |
473 | InitListExpr *OuterILE, unsigned OuterIndex, |
474 | bool FillWithNoInit = false); |
475 | bool CheckFlexibleArrayInit(const InitializedEntity &Entity, |
476 | Expr *InitExpr, FieldDecl *Field, |
477 | bool TopLevelObject); |
478 | void CheckEmptyInitializable(const InitializedEntity &Entity, |
479 | SourceLocation Loc); |
480 | |
481 | public: |
482 | InitListChecker( |
483 | Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T, |
484 | bool VerifyOnly, bool TreatUnavailableAsInvalid, |
485 | bool InOverloadResolution = false, |
486 | SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr); |
487 | InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL, |
488 | QualType &T, |
489 | SmallVectorImpl<QualType> &AggrDeductionCandidateParamTypes) |
490 | : InitListChecker(S, Entity, IL, T, /*VerifyOnly=*/true, |
491 | /*TreatUnavailableAsInvalid=*/false, |
492 | /*InOverloadResolution=*/false, |
493 | &AggrDeductionCandidateParamTypes){}; |
494 | |
495 | bool HadError() { return hadError; } |
496 | |
497 | // Retrieves the fully-structured initializer list used for |
498 | // semantic analysis and code generation. |
499 | InitListExpr *getFullyStructuredList() const { return FullyStructuredList; } |
500 | }; |
501 | |
502 | } // end anonymous namespace |
503 | |
504 | ExprResult InitListChecker::PerformEmptyInit(SourceLocation Loc, |
505 | const InitializedEntity &Entity) { |
506 | InitializationKind Kind = InitializationKind::CreateValue(InitLoc: Loc, LParenLoc: Loc, RParenLoc: Loc, |
507 | isImplicit: true); |
508 | MultiExprArg SubInit; |
509 | Expr *InitExpr; |
510 | InitListExpr DummyInitList(SemaRef.Context, Loc, std::nullopt, Loc); |
511 | |
512 | // C++ [dcl.init.aggr]p7: |
513 | // If there are fewer initializer-clauses in the list than there are |
514 | // members in the aggregate, then each member not explicitly initialized |
515 | // ... |
516 | bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 && |
517 | Entity.getType()->getBaseElementTypeUnsafe()->isRecordType(); |
518 | if (EmptyInitList) { |
519 | // C++1y / DR1070: |
520 | // shall be initialized [...] from an empty initializer list. |
521 | // |
522 | // We apply the resolution of this DR to C++11 but not C++98, since C++98 |
523 | // does not have useful semantics for initialization from an init list. |
524 | // We treat this as copy-initialization, because aggregate initialization |
525 | // always performs copy-initialization on its elements. |
526 | // |
527 | // Only do this if we're initializing a class type, to avoid filling in |
528 | // the initializer list where possible. |
529 | InitExpr = VerifyOnly |
530 | ? &DummyInitList |
531 | : new (SemaRef.Context) |
532 | InitListExpr(SemaRef.Context, Loc, std::nullopt, Loc); |
533 | InitExpr->setType(SemaRef.Context.VoidTy); |
534 | SubInit = InitExpr; |
535 | Kind = InitializationKind::CreateCopy(InitLoc: Loc, EqualLoc: Loc); |
536 | } else { |
537 | // C++03: |
538 | // shall be value-initialized. |
539 | } |
540 | |
541 | InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit); |
542 | // libstdc++4.6 marks the vector default constructor as explicit in |
543 | // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case. |
544 | // stlport does so too. Look for std::__debug for libstdc++, and for |
545 | // std:: for stlport. This is effectively a compiler-side implementation of |
546 | // LWG2193. |
547 | if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() == |
548 | InitializationSequence::FK_ExplicitConstructor) { |
549 | OverloadCandidateSet::iterator Best; |
550 | OverloadingResult O = |
551 | InitSeq.getFailedCandidateSet() |
552 | .BestViableFunction(S&: SemaRef, Loc: Kind.getLocation(), Best); |
553 | (void)O; |
554 | assert(O == OR_Success && "Inconsistent overload resolution" ); |
555 | CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Val: Best->Function); |
556 | CXXRecordDecl *R = CtorDecl->getParent(); |
557 | |
558 | if (CtorDecl->getMinRequiredArguments() == 0 && |
559 | CtorDecl->isExplicit() && R->getDeclName() && |
560 | SemaRef.SourceMgr.isInSystemHeader(Loc: CtorDecl->getLocation())) { |
561 | bool IsInStd = false; |
562 | for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext()); |
563 | ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) { |
564 | if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND)) |
565 | IsInStd = true; |
566 | } |
567 | |
568 | if (IsInStd && llvm::StringSwitch<bool>(R->getName()) |
569 | .Cases(S0: "basic_string" , S1: "deque" , S2: "forward_list" , Value: true) |
570 | .Cases(S0: "list" , S1: "map" , S2: "multimap" , S3: "multiset" , Value: true) |
571 | .Cases(S0: "priority_queue" , S1: "queue" , S2: "set" , S3: "stack" , Value: true) |
572 | .Cases(S0: "unordered_map" , S1: "unordered_set" , S2: "vector" , Value: true) |
573 | .Default(Value: false)) { |
574 | InitSeq.InitializeFrom( |
575 | S&: SemaRef, Entity, |
576 | Kind: InitializationKind::CreateValue(InitLoc: Loc, LParenLoc: Loc, RParenLoc: Loc, isImplicit: true), |
577 | Args: MultiExprArg(), /*TopLevelOfInitList=*/false, |
578 | TreatUnavailableAsInvalid); |
579 | // Emit a warning for this. System header warnings aren't shown |
580 | // by default, but people working on system headers should see it. |
581 | if (!VerifyOnly) { |
582 | SemaRef.Diag(CtorDecl->getLocation(), |
583 | diag::warn_invalid_initializer_from_system_header); |
584 | if (Entity.getKind() == InitializedEntity::EK_Member) |
585 | SemaRef.Diag(Entity.getDecl()->getLocation(), |
586 | diag::note_used_in_initialization_here); |
587 | else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) |
588 | SemaRef.Diag(Loc, diag::note_used_in_initialization_here); |
589 | } |
590 | } |
591 | } |
592 | } |
593 | if (!InitSeq) { |
594 | if (!VerifyOnly) { |
595 | InitSeq.Diagnose(S&: SemaRef, Entity, Kind, Args: SubInit); |
596 | if (Entity.getKind() == InitializedEntity::EK_Member) |
597 | SemaRef.Diag(Entity.getDecl()->getLocation(), |
598 | diag::note_in_omitted_aggregate_initializer) |
599 | << /*field*/1 << Entity.getDecl(); |
600 | else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) { |
601 | bool IsTrailingArrayNewMember = |
602 | Entity.getParent() && |
603 | Entity.getParent()->isVariableLengthArrayNew(); |
604 | SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer) |
605 | << (IsTrailingArrayNewMember ? 2 : /*array element*/0) |
606 | << Entity.getElementIndex(); |
607 | } |
608 | } |
609 | hadError = true; |
610 | return ExprError(); |
611 | } |
612 | |
613 | return VerifyOnly ? ExprResult() |
614 | : InitSeq.Perform(S&: SemaRef, Entity, Kind, Args: SubInit); |
615 | } |
616 | |
617 | void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity, |
618 | SourceLocation Loc) { |
619 | // If we're building a fully-structured list, we'll check this at the end |
620 | // once we know which elements are actually initialized. Otherwise, we know |
621 | // that there are no designators so we can just check now. |
622 | if (FullyStructuredList) |
623 | return; |
624 | PerformEmptyInit(Loc, Entity); |
625 | } |
626 | |
627 | void InitListChecker::FillInEmptyInitForBase( |
628 | unsigned Init, const CXXBaseSpecifier &Base, |
629 | const InitializedEntity &ParentEntity, InitListExpr *ILE, |
630 | bool &RequiresSecondPass, bool FillWithNoInit) { |
631 | InitializedEntity BaseEntity = InitializedEntity::InitializeBase( |
632 | Context&: SemaRef.Context, Base: &Base, IsInheritedVirtualBase: false, Parent: &ParentEntity); |
633 | |
634 | if (Init >= ILE->getNumInits() || !ILE->getInit(Init)) { |
635 | ExprResult BaseInit = FillWithNoInit |
636 | ? new (SemaRef.Context) NoInitExpr(Base.getType()) |
637 | : PerformEmptyInit(Loc: ILE->getEndLoc(), Entity: BaseEntity); |
638 | if (BaseInit.isInvalid()) { |
639 | hadError = true; |
640 | return; |
641 | } |
642 | |
643 | if (!VerifyOnly) { |
644 | assert(Init < ILE->getNumInits() && "should have been expanded" ); |
645 | ILE->setInit(Init, expr: BaseInit.getAs<Expr>()); |
646 | } |
647 | } else if (InitListExpr *InnerILE = |
648 | dyn_cast<InitListExpr>(Val: ILE->getInit(Init))) { |
649 | FillInEmptyInitializations(Entity: BaseEntity, ILE: InnerILE, RequiresSecondPass, |
650 | OuterILE: ILE, OuterIndex: Init, FillWithNoInit); |
651 | } else if (DesignatedInitUpdateExpr *InnerDIUE = |
652 | dyn_cast<DesignatedInitUpdateExpr>(Val: ILE->getInit(Init))) { |
653 | FillInEmptyInitializations(Entity: BaseEntity, ILE: InnerDIUE->getUpdater(), |
654 | RequiresSecondPass, OuterILE: ILE, OuterIndex: Init, |
655 | /*FillWithNoInit =*/true); |
656 | } |
657 | } |
658 | |
659 | void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field, |
660 | const InitializedEntity &ParentEntity, |
661 | InitListExpr *ILE, |
662 | bool &RequiresSecondPass, |
663 | bool FillWithNoInit) { |
664 | SourceLocation Loc = ILE->getEndLoc(); |
665 | unsigned NumInits = ILE->getNumInits(); |
666 | InitializedEntity MemberEntity |
667 | = InitializedEntity::InitializeMember(Member: Field, Parent: &ParentEntity); |
668 | |
669 | if (Init >= NumInits || !ILE->getInit(Init)) { |
670 | if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) |
671 | if (!RType->getDecl()->isUnion()) |
672 | assert((Init < NumInits || VerifyOnly) && |
673 | "This ILE should have been expanded" ); |
674 | |
675 | if (FillWithNoInit) { |
676 | assert(!VerifyOnly && "should not fill with no-init in verify-only mode" ); |
677 | Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType()); |
678 | if (Init < NumInits) |
679 | ILE->setInit(Init, expr: Filler); |
680 | else |
681 | ILE->updateInit(C: SemaRef.Context, Init, expr: Filler); |
682 | return; |
683 | } |
684 | // C++1y [dcl.init.aggr]p7: |
685 | // If there are fewer initializer-clauses in the list than there are |
686 | // members in the aggregate, then each member not explicitly initialized |
687 | // shall be initialized from its brace-or-equal-initializer [...] |
688 | if (Field->hasInClassInitializer()) { |
689 | if (VerifyOnly) |
690 | return; |
691 | |
692 | ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field); |
693 | if (DIE.isInvalid()) { |
694 | hadError = true; |
695 | return; |
696 | } |
697 | SemaRef.checkInitializerLifetime(Entity: MemberEntity, Init: DIE.get()); |
698 | if (Init < NumInits) |
699 | ILE->setInit(Init, expr: DIE.get()); |
700 | else { |
701 | ILE->updateInit(C: SemaRef.Context, Init, expr: DIE.get()); |
702 | RequiresSecondPass = true; |
703 | } |
704 | return; |
705 | } |
706 | |
707 | if (Field->getType()->isReferenceType()) { |
708 | if (!VerifyOnly) { |
709 | // C++ [dcl.init.aggr]p9: |
710 | // If an incomplete or empty initializer-list leaves a |
711 | // member of reference type uninitialized, the program is |
712 | // ill-formed. |
713 | SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized) |
714 | << Field->getType() |
715 | << (ILE->isSyntacticForm() ? ILE : ILE->getSyntacticForm()) |
716 | ->getSourceRange(); |
717 | SemaRef.Diag(Field->getLocation(), diag::note_uninit_reference_member); |
718 | } |
719 | hadError = true; |
720 | return; |
721 | } |
722 | |
723 | ExprResult MemberInit = PerformEmptyInit(Loc, Entity: MemberEntity); |
724 | if (MemberInit.isInvalid()) { |
725 | hadError = true; |
726 | return; |
727 | } |
728 | |
729 | if (hadError || VerifyOnly) { |
730 | // Do nothing |
731 | } else if (Init < NumInits) { |
732 | ILE->setInit(Init, expr: MemberInit.getAs<Expr>()); |
733 | } else if (!isa<ImplicitValueInitExpr>(Val: MemberInit.get())) { |
734 | // Empty initialization requires a constructor call, so |
735 | // extend the initializer list to include the constructor |
736 | // call and make a note that we'll need to take another pass |
737 | // through the initializer list. |
738 | ILE->updateInit(C: SemaRef.Context, Init, expr: MemberInit.getAs<Expr>()); |
739 | RequiresSecondPass = true; |
740 | } |
741 | } else if (InitListExpr *InnerILE |
742 | = dyn_cast<InitListExpr>(Val: ILE->getInit(Init))) { |
743 | FillInEmptyInitializations(Entity: MemberEntity, ILE: InnerILE, |
744 | RequiresSecondPass, OuterILE: ILE, OuterIndex: Init, FillWithNoInit); |
745 | } else if (DesignatedInitUpdateExpr *InnerDIUE = |
746 | dyn_cast<DesignatedInitUpdateExpr>(Val: ILE->getInit(Init))) { |
747 | FillInEmptyInitializations(Entity: MemberEntity, ILE: InnerDIUE->getUpdater(), |
748 | RequiresSecondPass, OuterILE: ILE, OuterIndex: Init, |
749 | /*FillWithNoInit =*/true); |
750 | } |
751 | } |
752 | |
753 | /// Recursively replaces NULL values within the given initializer list |
754 | /// with expressions that perform value-initialization of the |
755 | /// appropriate type, and finish off the InitListExpr formation. |
756 | void |
757 | InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity, |
758 | InitListExpr *ILE, |
759 | bool &RequiresSecondPass, |
760 | InitListExpr *OuterILE, |
761 | unsigned OuterIndex, |
762 | bool FillWithNoInit) { |
763 | assert((ILE->getType() != SemaRef.Context.VoidTy) && |
764 | "Should not have void type" ); |
765 | |
766 | // We don't need to do any checks when just filling NoInitExprs; that can't |
767 | // fail. |
768 | if (FillWithNoInit && VerifyOnly) |
769 | return; |
770 | |
771 | // If this is a nested initializer list, we might have changed its contents |
772 | // (and therefore some of its properties, such as instantiation-dependence) |
773 | // while filling it in. Inform the outer initializer list so that its state |
774 | // can be updated to match. |
775 | // FIXME: We should fully build the inner initializers before constructing |
776 | // the outer InitListExpr instead of mutating AST nodes after they have |
777 | // been used as subexpressions of other nodes. |
778 | struct UpdateOuterILEWithUpdatedInit { |
779 | InitListExpr *Outer; |
780 | unsigned OuterIndex; |
781 | ~UpdateOuterILEWithUpdatedInit() { |
782 | if (Outer) |
783 | Outer->setInit(Init: OuterIndex, expr: Outer->getInit(Init: OuterIndex)); |
784 | } |
785 | } UpdateOuterRAII = {.Outer: OuterILE, .OuterIndex: OuterIndex}; |
786 | |
787 | // A transparent ILE is not performing aggregate initialization and should |
788 | // not be filled in. |
789 | if (ILE->isTransparent()) |
790 | return; |
791 | |
792 | if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) { |
793 | const RecordDecl *RDecl = RType->getDecl(); |
794 | if (RDecl->isUnion() && ILE->getInitializedFieldInUnion()) |
795 | FillInEmptyInitForField(Init: 0, Field: ILE->getInitializedFieldInUnion(), |
796 | ParentEntity: Entity, ILE, RequiresSecondPass, FillWithNoInit); |
797 | else if (RDecl->isUnion() && isa<CXXRecordDecl>(Val: RDecl) && |
798 | cast<CXXRecordDecl>(Val: RDecl)->hasInClassInitializer()) { |
799 | for (auto *Field : RDecl->fields()) { |
800 | if (Field->hasInClassInitializer()) { |
801 | FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass, |
802 | FillWithNoInit); |
803 | break; |
804 | } |
805 | } |
806 | } else { |
807 | // The fields beyond ILE->getNumInits() are default initialized, so in |
808 | // order to leave them uninitialized, the ILE is expanded and the extra |
809 | // fields are then filled with NoInitExpr. |
810 | unsigned NumElems = numStructUnionElements(DeclType: ILE->getType()); |
811 | if (!RDecl->isUnion() && RDecl->hasFlexibleArrayMember()) |
812 | ++NumElems; |
813 | if (!VerifyOnly && ILE->getNumInits() < NumElems) |
814 | ILE->resizeInits(Context: SemaRef.Context, NumInits: NumElems); |
815 | |
816 | unsigned Init = 0; |
817 | |
818 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) { |
819 | for (auto &Base : CXXRD->bases()) { |
820 | if (hadError) |
821 | return; |
822 | |
823 | FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass, |
824 | FillWithNoInit); |
825 | ++Init; |
826 | } |
827 | } |
828 | |
829 | for (auto *Field : RDecl->fields()) { |
830 | if (Field->isUnnamedBitfield()) |
831 | continue; |
832 | |
833 | if (hadError) |
834 | return; |
835 | |
836 | FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass, |
837 | FillWithNoInit); |
838 | if (hadError) |
839 | return; |
840 | |
841 | ++Init; |
842 | |
843 | // Only look at the first initialization of a union. |
844 | if (RDecl->isUnion()) |
845 | break; |
846 | } |
847 | } |
848 | |
849 | return; |
850 | } |
851 | |
852 | QualType ElementType; |
853 | |
854 | InitializedEntity ElementEntity = Entity; |
855 | unsigned NumInits = ILE->getNumInits(); |
856 | unsigned NumElements = NumInits; |
857 | if (const ArrayType *AType = SemaRef.Context.getAsArrayType(T: ILE->getType())) { |
858 | ElementType = AType->getElementType(); |
859 | if (const auto *CAType = dyn_cast<ConstantArrayType>(AType)) |
860 | NumElements = CAType->getSize().getZExtValue(); |
861 | // For an array new with an unknown bound, ask for one additional element |
862 | // in order to populate the array filler. |
863 | if (Entity.isVariableLengthArrayNew()) |
864 | ++NumElements; |
865 | ElementEntity = InitializedEntity::InitializeElement(Context&: SemaRef.Context, |
866 | Index: 0, Parent: Entity); |
867 | } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) { |
868 | ElementType = VType->getElementType(); |
869 | NumElements = VType->getNumElements(); |
870 | ElementEntity = InitializedEntity::InitializeElement(Context&: SemaRef.Context, |
871 | Index: 0, Parent: Entity); |
872 | } else |
873 | ElementType = ILE->getType(); |
874 | |
875 | bool SkipEmptyInitChecks = false; |
876 | for (unsigned Init = 0; Init != NumElements; ++Init) { |
877 | if (hadError) |
878 | return; |
879 | |
880 | if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement || |
881 | ElementEntity.getKind() == InitializedEntity::EK_VectorElement) |
882 | ElementEntity.setElementIndex(Init); |
883 | |
884 | if (Init >= NumInits && (ILE->hasArrayFiller() || SkipEmptyInitChecks)) |
885 | return; |
886 | |
887 | Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr); |
888 | if (!InitExpr && Init < NumInits && ILE->hasArrayFiller()) |
889 | ILE->setInit(Init, expr: ILE->getArrayFiller()); |
890 | else if (!InitExpr && !ILE->hasArrayFiller()) { |
891 | // In VerifyOnly mode, there's no point performing empty initialization |
892 | // more than once. |
893 | if (SkipEmptyInitChecks) |
894 | continue; |
895 | |
896 | Expr *Filler = nullptr; |
897 | |
898 | if (FillWithNoInit) |
899 | Filler = new (SemaRef.Context) NoInitExpr(ElementType); |
900 | else { |
901 | ExprResult ElementInit = |
902 | PerformEmptyInit(Loc: ILE->getEndLoc(), Entity: ElementEntity); |
903 | if (ElementInit.isInvalid()) { |
904 | hadError = true; |
905 | return; |
906 | } |
907 | |
908 | Filler = ElementInit.getAs<Expr>(); |
909 | } |
910 | |
911 | if (hadError) { |
912 | // Do nothing |
913 | } else if (VerifyOnly) { |
914 | SkipEmptyInitChecks = true; |
915 | } else if (Init < NumInits) { |
916 | // For arrays, just set the expression used for value-initialization |
917 | // of the "holes" in the array. |
918 | if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) |
919 | ILE->setArrayFiller(Filler); |
920 | else |
921 | ILE->setInit(Init, expr: Filler); |
922 | } else { |
923 | // For arrays, just set the expression used for value-initialization |
924 | // of the rest of elements and exit. |
925 | if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) { |
926 | ILE->setArrayFiller(Filler); |
927 | return; |
928 | } |
929 | |
930 | if (!isa<ImplicitValueInitExpr>(Val: Filler) && !isa<NoInitExpr>(Val: Filler)) { |
931 | // Empty initialization requires a constructor call, so |
932 | // extend the initializer list to include the constructor |
933 | // call and make a note that we'll need to take another pass |
934 | // through the initializer list. |
935 | ILE->updateInit(C: SemaRef.Context, Init, expr: Filler); |
936 | RequiresSecondPass = true; |
937 | } |
938 | } |
939 | } else if (InitListExpr *InnerILE |
940 | = dyn_cast_or_null<InitListExpr>(Val: InitExpr)) { |
941 | FillInEmptyInitializations(Entity: ElementEntity, ILE: InnerILE, RequiresSecondPass, |
942 | OuterILE: ILE, OuterIndex: Init, FillWithNoInit); |
943 | } else if (DesignatedInitUpdateExpr *InnerDIUE = |
944 | dyn_cast_or_null<DesignatedInitUpdateExpr>(Val: InitExpr)) { |
945 | FillInEmptyInitializations(Entity: ElementEntity, ILE: InnerDIUE->getUpdater(), |
946 | RequiresSecondPass, OuterILE: ILE, OuterIndex: Init, |
947 | /*FillWithNoInit =*/true); |
948 | } |
949 | } |
950 | } |
951 | |
952 | static bool hasAnyDesignatedInits(const InitListExpr *IL) { |
953 | for (const Stmt *Init : *IL) |
954 | if (isa_and_nonnull<DesignatedInitExpr>(Val: Init)) |
955 | return true; |
956 | return false; |
957 | } |
958 | |
959 | InitListChecker::InitListChecker( |
960 | Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T, |
961 | bool VerifyOnly, bool TreatUnavailableAsInvalid, bool InOverloadResolution, |
962 | SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes) |
963 | : SemaRef(S), VerifyOnly(VerifyOnly), |
964 | TreatUnavailableAsInvalid(TreatUnavailableAsInvalid), |
965 | InOverloadResolution(InOverloadResolution), |
966 | AggrDeductionCandidateParamTypes(AggrDeductionCandidateParamTypes) { |
967 | if (!VerifyOnly || hasAnyDesignatedInits(IL)) { |
968 | FullyStructuredList = |
969 | createInitListExpr(CurrentObjectType: T, InitRange: IL->getSourceRange(), ExpectedNumInits: IL->getNumInits()); |
970 | |
971 | // FIXME: Check that IL isn't already the semantic form of some other |
972 | // InitListExpr. If it is, we'd create a broken AST. |
973 | if (!VerifyOnly) |
974 | FullyStructuredList->setSyntacticForm(IL); |
975 | } |
976 | |
977 | CheckExplicitInitList(Entity, IList: IL, T, StructuredList: FullyStructuredList, |
978 | /*TopLevelObject=*/true); |
979 | |
980 | if (!hadError && !AggrDeductionCandidateParamTypes && FullyStructuredList) { |
981 | bool RequiresSecondPass = false; |
982 | FillInEmptyInitializations(Entity, ILE: FullyStructuredList, RequiresSecondPass, |
983 | /*OuterILE=*/nullptr, /*OuterIndex=*/0); |
984 | if (RequiresSecondPass && !hadError) |
985 | FillInEmptyInitializations(Entity, ILE: FullyStructuredList, |
986 | RequiresSecondPass, OuterILE: nullptr, OuterIndex: 0); |
987 | } |
988 | if (hadError && FullyStructuredList) |
989 | FullyStructuredList->markError(); |
990 | } |
991 | |
992 | int InitListChecker::numArrayElements(QualType DeclType) { |
993 | // FIXME: use a proper constant |
994 | int maxElements = 0x7FFFFFFF; |
995 | if (const ConstantArrayType *CAT = |
996 | SemaRef.Context.getAsConstantArrayType(T: DeclType)) { |
997 | maxElements = static_cast<int>(CAT->getSize().getZExtValue()); |
998 | } |
999 | return maxElements; |
1000 | } |
1001 | |
1002 | int InitListChecker::numStructUnionElements(QualType DeclType) { |
1003 | RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl(); |
1004 | int InitializableMembers = 0; |
1005 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: structDecl)) |
1006 | InitializableMembers += CXXRD->getNumBases(); |
1007 | for (const auto *Field : structDecl->fields()) |
1008 | if (!Field->isUnnamedBitfield()) |
1009 | ++InitializableMembers; |
1010 | |
1011 | if (structDecl->isUnion()) |
1012 | return std::min(a: InitializableMembers, b: 1); |
1013 | return InitializableMembers - structDecl->hasFlexibleArrayMember(); |
1014 | } |
1015 | |
1016 | RecordDecl *InitListChecker::getRecordDecl(QualType DeclType) { |
1017 | if (const auto *RT = DeclType->getAs<RecordType>()) |
1018 | return RT->getDecl(); |
1019 | if (const auto *Inject = DeclType->getAs<InjectedClassNameType>()) |
1020 | return Inject->getDecl(); |
1021 | return nullptr; |
1022 | } |
1023 | |
1024 | /// Determine whether Entity is an entity for which it is idiomatic to elide |
1025 | /// the braces in aggregate initialization. |
1026 | static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) { |
1027 | // Recursive initialization of the one and only field within an aggregate |
1028 | // class is considered idiomatic. This case arises in particular for |
1029 | // initialization of std::array, where the C++ standard suggests the idiom of |
1030 | // |
1031 | // std::array<T, N> arr = {1, 2, 3}; |
1032 | // |
1033 | // (where std::array is an aggregate struct containing a single array field. |
1034 | |
1035 | if (!Entity.getParent()) |
1036 | return false; |
1037 | |
1038 | // Allows elide brace initialization for aggregates with empty base. |
1039 | if (Entity.getKind() == InitializedEntity::EK_Base) { |
1040 | auto *ParentRD = |
1041 | Entity.getParent()->getType()->castAs<RecordType>()->getDecl(); |
1042 | CXXRecordDecl *CXXRD = cast<CXXRecordDecl>(Val: ParentRD); |
1043 | return CXXRD->getNumBases() == 1 && CXXRD->field_empty(); |
1044 | } |
1045 | |
1046 | // Allow brace elision if the only subobject is a field. |
1047 | if (Entity.getKind() == InitializedEntity::EK_Member) { |
1048 | auto *ParentRD = |
1049 | Entity.getParent()->getType()->castAs<RecordType>()->getDecl(); |
1050 | if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(Val: ParentRD)) { |
1051 | if (CXXRD->getNumBases()) { |
1052 | return false; |
1053 | } |
1054 | } |
1055 | auto FieldIt = ParentRD->field_begin(); |
1056 | assert(FieldIt != ParentRD->field_end() && |
1057 | "no fields but have initializer for member?" ); |
1058 | return ++FieldIt == ParentRD->field_end(); |
1059 | } |
1060 | |
1061 | return false; |
1062 | } |
1063 | |
1064 | /// Check whether the range of the initializer \p ParentIList from element |
1065 | /// \p Index onwards can be used to initialize an object of type \p T. Update |
1066 | /// \p Index to indicate how many elements of the list were consumed. |
1067 | /// |
1068 | /// This also fills in \p StructuredList, from element \p StructuredIndex |
1069 | /// onwards, with the fully-braced, desugared form of the initialization. |
1070 | void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity, |
1071 | InitListExpr *ParentIList, |
1072 | QualType T, unsigned &Index, |
1073 | InitListExpr *StructuredList, |
1074 | unsigned &StructuredIndex) { |
1075 | int maxElements = 0; |
1076 | |
1077 | if (T->isArrayType()) |
1078 | maxElements = numArrayElements(DeclType: T); |
1079 | else if (T->isRecordType()) |
1080 | maxElements = numStructUnionElements(DeclType: T); |
1081 | else if (T->isVectorType()) |
1082 | maxElements = T->castAs<VectorType>()->getNumElements(); |
1083 | else |
1084 | llvm_unreachable("CheckImplicitInitList(): Illegal type" ); |
1085 | |
1086 | if (maxElements == 0) { |
1087 | if (!VerifyOnly) |
1088 | SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(), |
1089 | diag::err_implicit_empty_initializer); |
1090 | ++Index; |
1091 | hadError = true; |
1092 | return; |
1093 | } |
1094 | |
1095 | // Build a structured initializer list corresponding to this subobject. |
1096 | InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit( |
1097 | IList: ParentIList, Index, CurrentObjectType: T, StructuredList, StructuredIndex, |
1098 | InitRange: SourceRange(ParentIList->getInit(Init: Index)->getBeginLoc(), |
1099 | ParentIList->getSourceRange().getEnd())); |
1100 | unsigned StructuredSubobjectInitIndex = 0; |
1101 | |
1102 | // Check the element types and build the structural subobject. |
1103 | unsigned StartIndex = Index; |
1104 | CheckListElementTypes(Entity, IList: ParentIList, DeclType&: T, |
1105 | /*SubobjectIsDesignatorContext=*/false, Index, |
1106 | StructuredList: StructuredSubobjectInitList, |
1107 | StructuredIndex&: StructuredSubobjectInitIndex); |
1108 | |
1109 | if (StructuredSubobjectInitList) { |
1110 | StructuredSubobjectInitList->setType(T); |
1111 | |
1112 | unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1); |
1113 | // Update the structured sub-object initializer so that it's ending |
1114 | // range corresponds with the end of the last initializer it used. |
1115 | if (EndIndex < ParentIList->getNumInits() && |
1116 | ParentIList->getInit(Init: EndIndex)) { |
1117 | SourceLocation EndLoc |
1118 | = ParentIList->getInit(Init: EndIndex)->getSourceRange().getEnd(); |
1119 | StructuredSubobjectInitList->setRBraceLoc(EndLoc); |
1120 | } |
1121 | |
1122 | // Complain about missing braces. |
1123 | if (!VerifyOnly && (T->isArrayType() || T->isRecordType()) && |
1124 | !ParentIList->isIdiomaticZeroInitializer(LangOpts: SemaRef.getLangOpts()) && |
1125 | !isIdiomaticBraceElisionEntity(Entity)) { |
1126 | SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(), |
1127 | diag::warn_missing_braces) |
1128 | << StructuredSubobjectInitList->getSourceRange() |
1129 | << FixItHint::CreateInsertion( |
1130 | StructuredSubobjectInitList->getBeginLoc(), "{" ) |
1131 | << FixItHint::CreateInsertion( |
1132 | SemaRef.getLocForEndOfToken( |
1133 | StructuredSubobjectInitList->getEndLoc()), |
1134 | "}" ); |
1135 | } |
1136 | |
1137 | // Warn if this type won't be an aggregate in future versions of C++. |
1138 | auto *CXXRD = T->getAsCXXRecordDecl(); |
1139 | if (!VerifyOnly && CXXRD && CXXRD->hasUserDeclaredConstructor()) { |
1140 | SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(), |
1141 | diag::warn_cxx20_compat_aggregate_init_with_ctors) |
1142 | << StructuredSubobjectInitList->getSourceRange() << T; |
1143 | } |
1144 | } |
1145 | } |
1146 | |
1147 | /// Warn that \p Entity was of scalar type and was initialized by a |
1148 | /// single-element braced initializer list. |
1149 | static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity, |
1150 | SourceRange Braces) { |
1151 | // Don't warn during template instantiation. If the initialization was |
1152 | // non-dependent, we warned during the initial parse; otherwise, the |
1153 | // type might not be scalar in some uses of the template. |
1154 | if (S.inTemplateInstantiation()) |
1155 | return; |
1156 | |
1157 | unsigned DiagID = 0; |
1158 | |
1159 | switch (Entity.getKind()) { |
1160 | case InitializedEntity::EK_VectorElement: |
1161 | case InitializedEntity::EK_ComplexElement: |
1162 | case InitializedEntity::EK_ArrayElement: |
1163 | case InitializedEntity::EK_Parameter: |
1164 | case InitializedEntity::EK_Parameter_CF_Audited: |
1165 | case InitializedEntity::EK_TemplateParameter: |
1166 | case InitializedEntity::EK_Result: |
1167 | case InitializedEntity::EK_ParenAggInitMember: |
1168 | // Extra braces here are suspicious. |
1169 | DiagID = diag::warn_braces_around_init; |
1170 | break; |
1171 | |
1172 | case InitializedEntity::EK_Member: |
1173 | // Warn on aggregate initialization but not on ctor init list or |
1174 | // default member initializer. |
1175 | if (Entity.getParent()) |
1176 | DiagID = diag::warn_braces_around_init; |
1177 | break; |
1178 | |
1179 | case InitializedEntity::EK_Variable: |
1180 | case InitializedEntity::EK_LambdaCapture: |
1181 | // No warning, might be direct-list-initialization. |
1182 | // FIXME: Should we warn for copy-list-initialization in these cases? |
1183 | break; |
1184 | |
1185 | case InitializedEntity::EK_New: |
1186 | case InitializedEntity::EK_Temporary: |
1187 | case InitializedEntity::EK_CompoundLiteralInit: |
1188 | // No warning, braces are part of the syntax of the underlying construct. |
1189 | break; |
1190 | |
1191 | case InitializedEntity::EK_RelatedResult: |
1192 | // No warning, we already warned when initializing the result. |
1193 | break; |
1194 | |
1195 | case InitializedEntity::EK_Exception: |
1196 | case InitializedEntity::EK_Base: |
1197 | case InitializedEntity::EK_Delegating: |
1198 | case InitializedEntity::EK_BlockElement: |
1199 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: |
1200 | case InitializedEntity::EK_Binding: |
1201 | case InitializedEntity::EK_StmtExprResult: |
1202 | llvm_unreachable("unexpected braced scalar init" ); |
1203 | } |
1204 | |
1205 | if (DiagID) { |
1206 | S.Diag(Loc: Braces.getBegin(), DiagID) |
1207 | << Entity.getType()->isSizelessBuiltinType() << Braces |
1208 | << FixItHint::CreateRemoval(RemoveRange: Braces.getBegin()) |
1209 | << FixItHint::CreateRemoval(RemoveRange: Braces.getEnd()); |
1210 | } |
1211 | } |
1212 | |
1213 | /// Check whether the initializer \p IList (that was written with explicit |
1214 | /// braces) can be used to initialize an object of type \p T. |
1215 | /// |
1216 | /// This also fills in \p StructuredList with the fully-braced, desugared |
1217 | /// form of the initialization. |
1218 | void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity, |
1219 | InitListExpr *IList, QualType &T, |
1220 | InitListExpr *StructuredList, |
1221 | bool TopLevelObject) { |
1222 | unsigned Index = 0, StructuredIndex = 0; |
1223 | CheckListElementTypes(Entity, IList, DeclType&: T, /*SubobjectIsDesignatorContext=*/true, |
1224 | Index, StructuredList, StructuredIndex, TopLevelObject); |
1225 | if (StructuredList) { |
1226 | QualType ExprTy = T; |
1227 | if (!ExprTy->isArrayType()) |
1228 | ExprTy = ExprTy.getNonLValueExprType(Context: SemaRef.Context); |
1229 | if (!VerifyOnly) |
1230 | IList->setType(ExprTy); |
1231 | StructuredList->setType(ExprTy); |
1232 | } |
1233 | if (hadError) |
1234 | return; |
1235 | |
1236 | // Don't complain for incomplete types, since we'll get an error elsewhere. |
1237 | if (Index < IList->getNumInits() && !T->isIncompleteType()) { |
1238 | // We have leftover initializers |
1239 | bool = SemaRef.getLangOpts().CPlusPlus || |
1240 | (SemaRef.getLangOpts().OpenCL && T->isVectorType()); |
1241 | hadError = ExtraInitsIsError; |
1242 | if (VerifyOnly) { |
1243 | return; |
1244 | } else if (StructuredIndex == 1 && |
1245 | IsStringInit(init: StructuredList->getInit(Init: 0), declType: T, Context&: SemaRef.Context) == |
1246 | SIF_None) { |
1247 | unsigned DK = |
1248 | ExtraInitsIsError |
1249 | ? diag::err_excess_initializers_in_char_array_initializer |
1250 | : diag::ext_excess_initializers_in_char_array_initializer; |
1251 | SemaRef.Diag(IList->getInit(Init: Index)->getBeginLoc(), DK) |
1252 | << IList->getInit(Init: Index)->getSourceRange(); |
1253 | } else if (T->isSizelessBuiltinType()) { |
1254 | unsigned DK = ExtraInitsIsError |
1255 | ? diag::err_excess_initializers_for_sizeless_type |
1256 | : diag::ext_excess_initializers_for_sizeless_type; |
1257 | SemaRef.Diag(IList->getInit(Init: Index)->getBeginLoc(), DK) |
1258 | << T << IList->getInit(Init: Index)->getSourceRange(); |
1259 | } else { |
1260 | int initKind = T->isArrayType() ? 0 : |
1261 | T->isVectorType() ? 1 : |
1262 | T->isScalarType() ? 2 : |
1263 | T->isUnionType() ? 3 : |
1264 | 4; |
1265 | |
1266 | unsigned DK = ExtraInitsIsError ? diag::err_excess_initializers |
1267 | : diag::ext_excess_initializers; |
1268 | SemaRef.Diag(IList->getInit(Init: Index)->getBeginLoc(), DK) |
1269 | << initKind << IList->getInit(Init: Index)->getSourceRange(); |
1270 | } |
1271 | } |
1272 | |
1273 | if (!VerifyOnly) { |
1274 | if (T->isScalarType() && IList->getNumInits() == 1 && |
1275 | !isa<InitListExpr>(Val: IList->getInit(Init: 0))) |
1276 | warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange()); |
1277 | |
1278 | // Warn if this is a class type that won't be an aggregate in future |
1279 | // versions of C++. |
1280 | auto *CXXRD = T->getAsCXXRecordDecl(); |
1281 | if (CXXRD && CXXRD->hasUserDeclaredConstructor()) { |
1282 | // Don't warn if there's an equivalent default constructor that would be |
1283 | // used instead. |
1284 | bool HasEquivCtor = false; |
1285 | if (IList->getNumInits() == 0) { |
1286 | auto *CD = SemaRef.LookupDefaultConstructor(Class: CXXRD); |
1287 | HasEquivCtor = CD && !CD->isDeleted(); |
1288 | } |
1289 | |
1290 | if (!HasEquivCtor) { |
1291 | SemaRef.Diag(IList->getBeginLoc(), |
1292 | diag::warn_cxx20_compat_aggregate_init_with_ctors) |
1293 | << IList->getSourceRange() << T; |
1294 | } |
1295 | } |
1296 | } |
1297 | } |
1298 | |
1299 | void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity, |
1300 | InitListExpr *IList, |
1301 | QualType &DeclType, |
1302 | bool SubobjectIsDesignatorContext, |
1303 | unsigned &Index, |
1304 | InitListExpr *StructuredList, |
1305 | unsigned &StructuredIndex, |
1306 | bool TopLevelObject) { |
1307 | if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) { |
1308 | // Explicitly braced initializer for complex type can be real+imaginary |
1309 | // parts. |
1310 | CheckComplexType(Entity, IList, DeclType, Index, |
1311 | StructuredList, StructuredIndex); |
1312 | } else if (DeclType->isScalarType()) { |
1313 | CheckScalarType(Entity, IList, DeclType, Index, |
1314 | StructuredList, StructuredIndex); |
1315 | } else if (DeclType->isVectorType()) { |
1316 | CheckVectorType(Entity, IList, DeclType, Index, |
1317 | StructuredList, StructuredIndex); |
1318 | } else if (const RecordDecl *RD = getRecordDecl(DeclType)) { |
1319 | auto Bases = |
1320 | CXXRecordDecl::base_class_const_range(CXXRecordDecl::base_class_const_iterator(), |
1321 | CXXRecordDecl::base_class_const_iterator()); |
1322 | if (DeclType->isRecordType()) { |
1323 | assert(DeclType->isAggregateType() && |
1324 | "non-aggregate records should be handed in CheckSubElementType" ); |
1325 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) |
1326 | Bases = CXXRD->bases(); |
1327 | } else { |
1328 | Bases = cast<CXXRecordDecl>(Val: RD)->bases(); |
1329 | } |
1330 | CheckStructUnionTypes(Entity, IList, DeclType, Bases, Field: RD->field_begin(), |
1331 | SubobjectIsDesignatorContext, Index, StructuredList, |
1332 | StructuredIndex, TopLevelObject); |
1333 | } else if (DeclType->isArrayType()) { |
1334 | llvm::APSInt Zero( |
1335 | SemaRef.Context.getTypeSize(T: SemaRef.Context.getSizeType()), |
1336 | false); |
1337 | CheckArrayType(Entity, IList, DeclType, elementIndex: Zero, |
1338 | SubobjectIsDesignatorContext, Index, |
1339 | StructuredList, StructuredIndex); |
1340 | } else if (DeclType->isVoidType() || DeclType->isFunctionType()) { |
1341 | // This type is invalid, issue a diagnostic. |
1342 | ++Index; |
1343 | if (!VerifyOnly) |
1344 | SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type) |
1345 | << DeclType; |
1346 | hadError = true; |
1347 | } else if (DeclType->isReferenceType()) { |
1348 | CheckReferenceType(Entity, IList, DeclType, Index, |
1349 | StructuredList, StructuredIndex); |
1350 | } else if (DeclType->isObjCObjectType()) { |
1351 | if (!VerifyOnly) |
1352 | SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType; |
1353 | hadError = true; |
1354 | } else if (DeclType->isOCLIntelSubgroupAVCType() || |
1355 | DeclType->isSizelessBuiltinType()) { |
1356 | // Checks for scalar type are sufficient for these types too. |
1357 | CheckScalarType(Entity, IList, DeclType, Index, StructuredList, |
1358 | StructuredIndex); |
1359 | } else if (DeclType->isDependentType()) { |
1360 | // C++ [over.match.class.deduct]p1.5: |
1361 | // brace elision is not considered for any aggregate element that has a |
1362 | // dependent non-array type or an array type with a value-dependent bound |
1363 | ++Index; |
1364 | assert(AggrDeductionCandidateParamTypes); |
1365 | AggrDeductionCandidateParamTypes->push_back(Elt: DeclType); |
1366 | } else { |
1367 | if (!VerifyOnly) |
1368 | SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type) |
1369 | << DeclType; |
1370 | hadError = true; |
1371 | } |
1372 | } |
1373 | |
1374 | void InitListChecker::CheckSubElementType(const InitializedEntity &Entity, |
1375 | InitListExpr *IList, |
1376 | QualType ElemType, |
1377 | unsigned &Index, |
1378 | InitListExpr *StructuredList, |
1379 | unsigned &StructuredIndex, |
1380 | bool DirectlyDesignated) { |
1381 | Expr *expr = IList->getInit(Init: Index); |
1382 | |
1383 | if (ElemType->isReferenceType()) |
1384 | return CheckReferenceType(Entity, IList, DeclType: ElemType, Index, |
1385 | StructuredList, StructuredIndex); |
1386 | |
1387 | if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(Val: expr)) { |
1388 | if (SubInitList->getNumInits() == 1 && |
1389 | IsStringInit(init: SubInitList->getInit(Init: 0), declType: ElemType, Context&: SemaRef.Context) == |
1390 | SIF_None) { |
1391 | // FIXME: It would be more faithful and no less correct to include an |
1392 | // InitListExpr in the semantic form of the initializer list in this case. |
1393 | expr = SubInitList->getInit(Init: 0); |
1394 | } |
1395 | // Nested aggregate initialization and C++ initialization are handled later. |
1396 | } else if (isa<ImplicitValueInitExpr>(Val: expr)) { |
1397 | // This happens during template instantiation when we see an InitListExpr |
1398 | // that we've already checked once. |
1399 | assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) && |
1400 | "found implicit initialization for the wrong type" ); |
1401 | UpdateStructuredListElement(StructuredList, StructuredIndex, expr); |
1402 | ++Index; |
1403 | return; |
1404 | } |
1405 | |
1406 | if (SemaRef.getLangOpts().CPlusPlus || isa<InitListExpr>(Val: expr)) { |
1407 | // C++ [dcl.init.aggr]p2: |
1408 | // Each member is copy-initialized from the corresponding |
1409 | // initializer-clause. |
1410 | |
1411 | // FIXME: Better EqualLoc? |
1412 | InitializationKind Kind = |
1413 | InitializationKind::CreateCopy(InitLoc: expr->getBeginLoc(), EqualLoc: SourceLocation()); |
1414 | |
1415 | // Vector elements can be initialized from other vectors in which case |
1416 | // we need initialization entity with a type of a vector (and not a vector |
1417 | // element!) initializing multiple vector elements. |
1418 | auto TmpEntity = |
1419 | (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType()) |
1420 | ? InitializedEntity::InitializeTemporary(Type: ElemType) |
1421 | : Entity; |
1422 | |
1423 | if (TmpEntity.getType()->isDependentType()) { |
1424 | // C++ [over.match.class.deduct]p1.5: |
1425 | // brace elision is not considered for any aggregate element that has a |
1426 | // dependent non-array type or an array type with a value-dependent |
1427 | // bound |
1428 | assert(AggrDeductionCandidateParamTypes); |
1429 | if (!isa_and_nonnull<ConstantArrayType>( |
1430 | Val: SemaRef.Context.getAsArrayType(T: ElemType))) { |
1431 | ++Index; |
1432 | AggrDeductionCandidateParamTypes->push_back(Elt: ElemType); |
1433 | return; |
1434 | } |
1435 | } else { |
1436 | InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr, |
1437 | /*TopLevelOfInitList*/ true); |
1438 | // C++14 [dcl.init.aggr]p13: |
1439 | // If the assignment-expression can initialize a member, the member is |
1440 | // initialized. Otherwise [...] brace elision is assumed |
1441 | // |
1442 | // Brace elision is never performed if the element is not an |
1443 | // assignment-expression. |
1444 | if (Seq || isa<InitListExpr>(Val: expr)) { |
1445 | if (!VerifyOnly) { |
1446 | ExprResult Result = Seq.Perform(S&: SemaRef, Entity: TmpEntity, Kind, Args: expr); |
1447 | if (Result.isInvalid()) |
1448 | hadError = true; |
1449 | |
1450 | UpdateStructuredListElement(StructuredList, StructuredIndex, |
1451 | expr: Result.getAs<Expr>()); |
1452 | } else if (!Seq) { |
1453 | hadError = true; |
1454 | } else if (StructuredList) { |
1455 | UpdateStructuredListElement(StructuredList, StructuredIndex, |
1456 | getDummyInit()); |
1457 | } |
1458 | ++Index; |
1459 | if (AggrDeductionCandidateParamTypes) |
1460 | AggrDeductionCandidateParamTypes->push_back(Elt: ElemType); |
1461 | return; |
1462 | } |
1463 | } |
1464 | |
1465 | // Fall through for subaggregate initialization |
1466 | } else if (ElemType->isScalarType() || ElemType->isAtomicType()) { |
1467 | // FIXME: Need to handle atomic aggregate types with implicit init lists. |
1468 | return CheckScalarType(Entity, IList, DeclType: ElemType, Index, |
1469 | StructuredList, StructuredIndex); |
1470 | } else if (const ArrayType *arrayType = |
1471 | SemaRef.Context.getAsArrayType(T: ElemType)) { |
1472 | // arrayType can be incomplete if we're initializing a flexible |
1473 | // array member. There's nothing we can do with the completed |
1474 | // type here, though. |
1475 | |
1476 | if (IsStringInit(Init: expr, AT: arrayType, Context&: SemaRef.Context) == SIF_None) { |
1477 | // FIXME: Should we do this checking in verify-only mode? |
1478 | if (!VerifyOnly) |
1479 | CheckStringInit(Str: expr, DeclT&: ElemType, AT: arrayType, S&: SemaRef); |
1480 | if (StructuredList) |
1481 | UpdateStructuredListElement(StructuredList, StructuredIndex, expr); |
1482 | ++Index; |
1483 | return; |
1484 | } |
1485 | |
1486 | // Fall through for subaggregate initialization. |
1487 | |
1488 | } else { |
1489 | assert((ElemType->isRecordType() || ElemType->isVectorType() || |
1490 | ElemType->isOpenCLSpecificType()) && "Unexpected type" ); |
1491 | |
1492 | // C99 6.7.8p13: |
1493 | // |
1494 | // The initializer for a structure or union object that has |
1495 | // automatic storage duration shall be either an initializer |
1496 | // list as described below, or a single expression that has |
1497 | // compatible structure or union type. In the latter case, the |
1498 | // initial value of the object, including unnamed members, is |
1499 | // that of the expression. |
1500 | ExprResult ExprRes = expr; |
1501 | if (SemaRef.CheckSingleAssignmentConstraints( |
1502 | LHSType: ElemType, RHS&: ExprRes, Diagnose: !VerifyOnly) != Sema::Incompatible) { |
1503 | if (ExprRes.isInvalid()) |
1504 | hadError = true; |
1505 | else { |
1506 | ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(E: ExprRes.get()); |
1507 | if (ExprRes.isInvalid()) |
1508 | hadError = true; |
1509 | } |
1510 | UpdateStructuredListElement(StructuredList, StructuredIndex, |
1511 | expr: ExprRes.getAs<Expr>()); |
1512 | ++Index; |
1513 | return; |
1514 | } |
1515 | ExprRes.get(); |
1516 | // Fall through for subaggregate initialization |
1517 | } |
1518 | |
1519 | // C++ [dcl.init.aggr]p12: |
1520 | // |
1521 | // [...] Otherwise, if the member is itself a non-empty |
1522 | // subaggregate, brace elision is assumed and the initializer is |
1523 | // considered for the initialization of the first member of |
1524 | // the subaggregate. |
1525 | // OpenCL vector initializer is handled elsewhere. |
1526 | if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) || |
1527 | ElemType->isAggregateType()) { |
1528 | CheckImplicitInitList(Entity, ParentIList: IList, T: ElemType, Index, StructuredList, |
1529 | StructuredIndex); |
1530 | ++StructuredIndex; |
1531 | |
1532 | // In C++20, brace elision is not permitted for a designated initializer. |
1533 | if (DirectlyDesignated && SemaRef.getLangOpts().CPlusPlus && !hadError) { |
1534 | if (InOverloadResolution) |
1535 | hadError = true; |
1536 | if (!VerifyOnly) { |
1537 | SemaRef.Diag(expr->getBeginLoc(), |
1538 | diag::ext_designated_init_brace_elision) |
1539 | << expr->getSourceRange() |
1540 | << FixItHint::CreateInsertion(expr->getBeginLoc(), "{" ) |
1541 | << FixItHint::CreateInsertion( |
1542 | SemaRef.getLocForEndOfToken(expr->getEndLoc()), "}" ); |
1543 | } |
1544 | } |
1545 | } else { |
1546 | if (!VerifyOnly) { |
1547 | // We cannot initialize this element, so let PerformCopyInitialization |
1548 | // produce the appropriate diagnostic. We already checked that this |
1549 | // initialization will fail. |
1550 | ExprResult Copy = |
1551 | SemaRef.PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: expr, |
1552 | /*TopLevelOfInitList=*/true); |
1553 | (void)Copy; |
1554 | assert(Copy.isInvalid() && |
1555 | "expected non-aggregate initialization to fail" ); |
1556 | } |
1557 | hadError = true; |
1558 | ++Index; |
1559 | ++StructuredIndex; |
1560 | } |
1561 | } |
1562 | |
1563 | void InitListChecker::CheckComplexType(const InitializedEntity &Entity, |
1564 | InitListExpr *IList, QualType DeclType, |
1565 | unsigned &Index, |
1566 | InitListExpr *StructuredList, |
1567 | unsigned &StructuredIndex) { |
1568 | assert(Index == 0 && "Index in explicit init list must be zero" ); |
1569 | |
1570 | // As an extension, clang supports complex initializers, which initialize |
1571 | // a complex number component-wise. When an explicit initializer list for |
1572 | // a complex number contains two initializers, this extension kicks in: |
1573 | // it expects the initializer list to contain two elements convertible to |
1574 | // the element type of the complex type. The first element initializes |
1575 | // the real part, and the second element intitializes the imaginary part. |
1576 | |
1577 | if (IList->getNumInits() < 2) |
1578 | return CheckScalarType(Entity, IList, DeclType, Index, StructuredList, |
1579 | StructuredIndex); |
1580 | |
1581 | // This is an extension in C. (The builtin _Complex type does not exist |
1582 | // in the C++ standard.) |
1583 | if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly) |
1584 | SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init) |
1585 | << IList->getSourceRange(); |
1586 | |
1587 | // Initialize the complex number. |
1588 | QualType elementType = DeclType->castAs<ComplexType>()->getElementType(); |
1589 | InitializedEntity ElementEntity = |
1590 | InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity); |
1591 | |
1592 | for (unsigned i = 0; i < 2; ++i) { |
1593 | ElementEntity.setElementIndex(Index); |
1594 | CheckSubElementType(Entity: ElementEntity, IList, ElemType: elementType, Index, |
1595 | StructuredList, StructuredIndex); |
1596 | } |
1597 | } |
1598 | |
1599 | void InitListChecker::CheckScalarType(const InitializedEntity &Entity, |
1600 | InitListExpr *IList, QualType DeclType, |
1601 | unsigned &Index, |
1602 | InitListExpr *StructuredList, |
1603 | unsigned &StructuredIndex) { |
1604 | if (Index >= IList->getNumInits()) { |
1605 | if (!VerifyOnly) { |
1606 | if (SemaRef.getLangOpts().CPlusPlus) { |
1607 | if (DeclType->isSizelessBuiltinType()) |
1608 | SemaRef.Diag(IList->getBeginLoc(), |
1609 | SemaRef.getLangOpts().CPlusPlus11 |
1610 | ? diag::warn_cxx98_compat_empty_sizeless_initializer |
1611 | : diag::err_empty_sizeless_initializer) |
1612 | << DeclType << IList->getSourceRange(); |
1613 | else |
1614 | SemaRef.Diag(IList->getBeginLoc(), |
1615 | SemaRef.getLangOpts().CPlusPlus11 |
1616 | ? diag::warn_cxx98_compat_empty_scalar_initializer |
1617 | : diag::err_empty_scalar_initializer) |
1618 | << IList->getSourceRange(); |
1619 | } |
1620 | } |
1621 | hadError = |
1622 | SemaRef.getLangOpts().CPlusPlus && !SemaRef.getLangOpts().CPlusPlus11; |
1623 | ++Index; |
1624 | ++StructuredIndex; |
1625 | return; |
1626 | } |
1627 | |
1628 | Expr *expr = IList->getInit(Init: Index); |
1629 | if (InitListExpr *SubIList = dyn_cast<InitListExpr>(Val: expr)) { |
1630 | // FIXME: This is invalid, and accepting it causes overload resolution |
1631 | // to pick the wrong overload in some corner cases. |
1632 | if (!VerifyOnly) |
1633 | SemaRef.Diag(SubIList->getBeginLoc(), diag::ext_many_braces_around_init) |
1634 | << DeclType->isSizelessBuiltinType() << SubIList->getSourceRange(); |
1635 | |
1636 | CheckScalarType(Entity, IList: SubIList, DeclType, Index, StructuredList, |
1637 | StructuredIndex); |
1638 | return; |
1639 | } else if (isa<DesignatedInitExpr>(Val: expr)) { |
1640 | if (!VerifyOnly) |
1641 | SemaRef.Diag(expr->getBeginLoc(), |
1642 | diag::err_designator_for_scalar_or_sizeless_init) |
1643 | << DeclType->isSizelessBuiltinType() << DeclType |
1644 | << expr->getSourceRange(); |
1645 | hadError = true; |
1646 | ++Index; |
1647 | ++StructuredIndex; |
1648 | return; |
1649 | } |
1650 | |
1651 | ExprResult Result; |
1652 | if (VerifyOnly) { |
1653 | if (SemaRef.CanPerformCopyInitialization(Entity, Init: expr)) |
1654 | Result = getDummyInit(); |
1655 | else |
1656 | Result = ExprError(); |
1657 | } else { |
1658 | Result = |
1659 | SemaRef.PerformCopyInitialization(Entity, EqualLoc: expr->getBeginLoc(), Init: expr, |
1660 | /*TopLevelOfInitList=*/true); |
1661 | } |
1662 | |
1663 | Expr *ResultExpr = nullptr; |
1664 | |
1665 | if (Result.isInvalid()) |
1666 | hadError = true; // types weren't compatible. |
1667 | else { |
1668 | ResultExpr = Result.getAs<Expr>(); |
1669 | |
1670 | if (ResultExpr != expr && !VerifyOnly) { |
1671 | // The type was promoted, update initializer list. |
1672 | // FIXME: Why are we updating the syntactic init list? |
1673 | IList->setInit(Init: Index, expr: ResultExpr); |
1674 | } |
1675 | } |
1676 | UpdateStructuredListElement(StructuredList, StructuredIndex, expr: ResultExpr); |
1677 | ++Index; |
1678 | if (AggrDeductionCandidateParamTypes) |
1679 | AggrDeductionCandidateParamTypes->push_back(Elt: DeclType); |
1680 | } |
1681 | |
1682 | void InitListChecker::CheckReferenceType(const InitializedEntity &Entity, |
1683 | InitListExpr *IList, QualType DeclType, |
1684 | unsigned &Index, |
1685 | InitListExpr *StructuredList, |
1686 | unsigned &StructuredIndex) { |
1687 | if (Index >= IList->getNumInits()) { |
1688 | // FIXME: It would be wonderful if we could point at the actual member. In |
1689 | // general, it would be useful to pass location information down the stack, |
1690 | // so that we know the location (or decl) of the "current object" being |
1691 | // initialized. |
1692 | if (!VerifyOnly) |
1693 | SemaRef.Diag(IList->getBeginLoc(), |
1694 | diag::err_init_reference_member_uninitialized) |
1695 | << DeclType << IList->getSourceRange(); |
1696 | hadError = true; |
1697 | ++Index; |
1698 | ++StructuredIndex; |
1699 | return; |
1700 | } |
1701 | |
1702 | Expr *expr = IList->getInit(Init: Index); |
1703 | if (isa<InitListExpr>(Val: expr) && !SemaRef.getLangOpts().CPlusPlus11) { |
1704 | if (!VerifyOnly) |
1705 | SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list) |
1706 | << DeclType << IList->getSourceRange(); |
1707 | hadError = true; |
1708 | ++Index; |
1709 | ++StructuredIndex; |
1710 | return; |
1711 | } |
1712 | |
1713 | ExprResult Result; |
1714 | if (VerifyOnly) { |
1715 | if (SemaRef.CanPerformCopyInitialization(Entity,Init: expr)) |
1716 | Result = getDummyInit(); |
1717 | else |
1718 | Result = ExprError(); |
1719 | } else { |
1720 | Result = |
1721 | SemaRef.PerformCopyInitialization(Entity, EqualLoc: expr->getBeginLoc(), Init: expr, |
1722 | /*TopLevelOfInitList=*/true); |
1723 | } |
1724 | |
1725 | if (Result.isInvalid()) |
1726 | hadError = true; |
1727 | |
1728 | expr = Result.getAs<Expr>(); |
1729 | // FIXME: Why are we updating the syntactic init list? |
1730 | if (!VerifyOnly && expr) |
1731 | IList->setInit(Init: Index, expr); |
1732 | |
1733 | UpdateStructuredListElement(StructuredList, StructuredIndex, expr); |
1734 | ++Index; |
1735 | if (AggrDeductionCandidateParamTypes) |
1736 | AggrDeductionCandidateParamTypes->push_back(Elt: DeclType); |
1737 | } |
1738 | |
1739 | void InitListChecker::CheckVectorType(const InitializedEntity &Entity, |
1740 | InitListExpr *IList, QualType DeclType, |
1741 | unsigned &Index, |
1742 | InitListExpr *StructuredList, |
1743 | unsigned &StructuredIndex) { |
1744 | const VectorType *VT = DeclType->castAs<VectorType>(); |
1745 | unsigned maxElements = VT->getNumElements(); |
1746 | unsigned numEltsInit = 0; |
1747 | QualType elementType = VT->getElementType(); |
1748 | |
1749 | if (Index >= IList->getNumInits()) { |
1750 | // Make sure the element type can be value-initialized. |
1751 | CheckEmptyInitializable( |
1752 | Entity: InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity), |
1753 | Loc: IList->getEndLoc()); |
1754 | return; |
1755 | } |
1756 | |
1757 | if (!SemaRef.getLangOpts().OpenCL && !SemaRef.getLangOpts().HLSL ) { |
1758 | // If the initializing element is a vector, try to copy-initialize |
1759 | // instead of breaking it apart (which is doomed to failure anyway). |
1760 | Expr *Init = IList->getInit(Init: Index); |
1761 | if (!isa<InitListExpr>(Val: Init) && Init->getType()->isVectorType()) { |
1762 | ExprResult Result; |
1763 | if (VerifyOnly) { |
1764 | if (SemaRef.CanPerformCopyInitialization(Entity, Init)) |
1765 | Result = getDummyInit(); |
1766 | else |
1767 | Result = ExprError(); |
1768 | } else { |
1769 | Result = |
1770 | SemaRef.PerformCopyInitialization(Entity, EqualLoc: Init->getBeginLoc(), Init, |
1771 | /*TopLevelOfInitList=*/true); |
1772 | } |
1773 | |
1774 | Expr *ResultExpr = nullptr; |
1775 | if (Result.isInvalid()) |
1776 | hadError = true; // types weren't compatible. |
1777 | else { |
1778 | ResultExpr = Result.getAs<Expr>(); |
1779 | |
1780 | if (ResultExpr != Init && !VerifyOnly) { |
1781 | // The type was promoted, update initializer list. |
1782 | // FIXME: Why are we updating the syntactic init list? |
1783 | IList->setInit(Init: Index, expr: ResultExpr); |
1784 | } |
1785 | } |
1786 | UpdateStructuredListElement(StructuredList, StructuredIndex, expr: ResultExpr); |
1787 | ++Index; |
1788 | if (AggrDeductionCandidateParamTypes) |
1789 | AggrDeductionCandidateParamTypes->push_back(Elt: elementType); |
1790 | return; |
1791 | } |
1792 | |
1793 | InitializedEntity ElementEntity = |
1794 | InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity); |
1795 | |
1796 | for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) { |
1797 | // Don't attempt to go past the end of the init list |
1798 | if (Index >= IList->getNumInits()) { |
1799 | CheckEmptyInitializable(Entity: ElementEntity, Loc: IList->getEndLoc()); |
1800 | break; |
1801 | } |
1802 | |
1803 | ElementEntity.setElementIndex(Index); |
1804 | CheckSubElementType(Entity: ElementEntity, IList, ElemType: elementType, Index, |
1805 | StructuredList, StructuredIndex); |
1806 | } |
1807 | |
1808 | if (VerifyOnly) |
1809 | return; |
1810 | |
1811 | bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian(); |
1812 | const VectorType *T = Entity.getType()->castAs<VectorType>(); |
1813 | if (isBigEndian && (T->getVectorKind() == VectorKind::Neon || |
1814 | T->getVectorKind() == VectorKind::NeonPoly)) { |
1815 | // The ability to use vector initializer lists is a GNU vector extension |
1816 | // and is unrelated to the NEON intrinsics in arm_neon.h. On little |
1817 | // endian machines it works fine, however on big endian machines it |
1818 | // exhibits surprising behaviour: |
1819 | // |
1820 | // uint32x2_t x = {42, 64}; |
1821 | // return vget_lane_u32(x, 0); // Will return 64. |
1822 | // |
1823 | // Because of this, explicitly call out that it is non-portable. |
1824 | // |
1825 | SemaRef.Diag(IList->getBeginLoc(), |
1826 | diag::warn_neon_vector_initializer_non_portable); |
1827 | |
1828 | const char *typeCode; |
1829 | unsigned typeSize = SemaRef.Context.getTypeSize(T: elementType); |
1830 | |
1831 | if (elementType->isFloatingType()) |
1832 | typeCode = "f" ; |
1833 | else if (elementType->isSignedIntegerType()) |
1834 | typeCode = "s" ; |
1835 | else if (elementType->isUnsignedIntegerType()) |
1836 | typeCode = "u" ; |
1837 | else |
1838 | llvm_unreachable("Invalid element type!" ); |
1839 | |
1840 | SemaRef.Diag(IList->getBeginLoc(), |
1841 | SemaRef.Context.getTypeSize(VT) > 64 |
1842 | ? diag::note_neon_vector_initializer_non_portable_q |
1843 | : diag::note_neon_vector_initializer_non_portable) |
1844 | << typeCode << typeSize; |
1845 | } |
1846 | |
1847 | return; |
1848 | } |
1849 | |
1850 | InitializedEntity ElementEntity = |
1851 | InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity); |
1852 | |
1853 | // OpenCL and HLSL initializers allow vectors to be constructed from vectors. |
1854 | for (unsigned i = 0; i < maxElements; ++i) { |
1855 | // Don't attempt to go past the end of the init list |
1856 | if (Index >= IList->getNumInits()) |
1857 | break; |
1858 | |
1859 | ElementEntity.setElementIndex(Index); |
1860 | |
1861 | QualType IType = IList->getInit(Init: Index)->getType(); |
1862 | if (!IType->isVectorType()) { |
1863 | CheckSubElementType(Entity: ElementEntity, IList, ElemType: elementType, Index, |
1864 | StructuredList, StructuredIndex); |
1865 | ++numEltsInit; |
1866 | } else { |
1867 | QualType VecType; |
1868 | const VectorType *IVT = IType->castAs<VectorType>(); |
1869 | unsigned numIElts = IVT->getNumElements(); |
1870 | |
1871 | if (IType->isExtVectorType()) |
1872 | VecType = SemaRef.Context.getExtVectorType(VectorType: elementType, NumElts: numIElts); |
1873 | else |
1874 | VecType = SemaRef.Context.getVectorType(VectorType: elementType, NumElts: numIElts, |
1875 | VecKind: IVT->getVectorKind()); |
1876 | CheckSubElementType(Entity: ElementEntity, IList, ElemType: VecType, Index, |
1877 | StructuredList, StructuredIndex); |
1878 | numEltsInit += numIElts; |
1879 | } |
1880 | } |
1881 | |
1882 | // OpenCL and HLSL require all elements to be initialized. |
1883 | if (numEltsInit != maxElements) { |
1884 | if (!VerifyOnly) |
1885 | SemaRef.Diag(IList->getBeginLoc(), |
1886 | diag::err_vector_incorrect_num_initializers) |
1887 | << (numEltsInit < maxElements) << maxElements << numEltsInit; |
1888 | hadError = true; |
1889 | } |
1890 | } |
1891 | |
1892 | /// Check if the type of a class element has an accessible destructor, and marks |
1893 | /// it referenced. Returns true if we shouldn't form a reference to the |
1894 | /// destructor. |
1895 | /// |
1896 | /// Aggregate initialization requires a class element's destructor be |
1897 | /// accessible per 11.6.1 [dcl.init.aggr]: |
1898 | /// |
1899 | /// The destructor for each element of class type is potentially invoked |
1900 | /// (15.4 [class.dtor]) from the context where the aggregate initialization |
1901 | /// occurs. |
1902 | static bool checkDestructorReference(QualType ElementType, SourceLocation Loc, |
1903 | Sema &SemaRef) { |
1904 | auto *CXXRD = ElementType->getAsCXXRecordDecl(); |
1905 | if (!CXXRD) |
1906 | return false; |
1907 | |
1908 | CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Class: CXXRD); |
1909 | SemaRef.CheckDestructorAccess(Loc, Destructor, |
1910 | SemaRef.PDiag(diag::err_access_dtor_temp) |
1911 | << ElementType); |
1912 | SemaRef.MarkFunctionReferenced(Loc, Destructor); |
1913 | return SemaRef.DiagnoseUseOfDecl(Destructor, Loc); |
1914 | } |
1915 | |
1916 | void InitListChecker::CheckArrayType(const InitializedEntity &Entity, |
1917 | InitListExpr *IList, QualType &DeclType, |
1918 | llvm::APSInt elementIndex, |
1919 | bool SubobjectIsDesignatorContext, |
1920 | unsigned &Index, |
1921 | InitListExpr *StructuredList, |
1922 | unsigned &StructuredIndex) { |
1923 | const ArrayType *arrayType = SemaRef.Context.getAsArrayType(T: DeclType); |
1924 | |
1925 | if (!VerifyOnly) { |
1926 | if (checkDestructorReference(ElementType: arrayType->getElementType(), |
1927 | Loc: IList->getEndLoc(), SemaRef)) { |
1928 | hadError = true; |
1929 | return; |
1930 | } |
1931 | } |
1932 | |
1933 | // Check for the special-case of initializing an array with a string. |
1934 | if (Index < IList->getNumInits()) { |
1935 | if (IsStringInit(Init: IList->getInit(Init: Index), AT: arrayType, Context&: SemaRef.Context) == |
1936 | SIF_None) { |
1937 | // We place the string literal directly into the resulting |
1938 | // initializer list. This is the only place where the structure |
1939 | // of the structured initializer list doesn't match exactly, |
1940 | // because doing so would involve allocating one character |
1941 | // constant for each string. |
1942 | // FIXME: Should we do these checks in verify-only mode too? |
1943 | if (!VerifyOnly) |
1944 | CheckStringInit(Str: IList->getInit(Init: Index), DeclT&: DeclType, AT: arrayType, S&: SemaRef); |
1945 | if (StructuredList) { |
1946 | UpdateStructuredListElement(StructuredList, StructuredIndex, |
1947 | expr: IList->getInit(Init: Index)); |
1948 | StructuredList->resizeInits(Context: SemaRef.Context, NumInits: StructuredIndex); |
1949 | } |
1950 | ++Index; |
1951 | if (AggrDeductionCandidateParamTypes) |
1952 | AggrDeductionCandidateParamTypes->push_back(Elt: DeclType); |
1953 | return; |
1954 | } |
1955 | } |
1956 | if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Val: arrayType)) { |
1957 | // Check for VLAs; in standard C it would be possible to check this |
1958 | // earlier, but I don't know where clang accepts VLAs (gcc accepts |
1959 | // them in all sorts of strange places). |
1960 | bool HasErr = IList->getNumInits() != 0 || SemaRef.getLangOpts().CPlusPlus; |
1961 | if (!VerifyOnly) { |
1962 | // C23 6.7.10p4: An entity of variable length array type shall not be |
1963 | // initialized except by an empty initializer. |
1964 | // |
1965 | // The C extension warnings are issued from ParseBraceInitializer() and |
1966 | // do not need to be issued here. However, we continue to issue an error |
1967 | // in the case there are initializers or we are compiling C++. We allow |
1968 | // use of VLAs in C++, but it's not clear we want to allow {} to zero |
1969 | // init a VLA in C++ in all cases (such as with non-trivial constructors). |
1970 | // FIXME: should we allow this construct in C++ when it makes sense to do |
1971 | // so? |
1972 | if (HasErr) |
1973 | SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(), |
1974 | diag::err_variable_object_no_init) |
1975 | << VAT->getSizeExpr()->getSourceRange(); |
1976 | } |
1977 | hadError = HasErr; |
1978 | ++Index; |
1979 | ++StructuredIndex; |
1980 | return; |
1981 | } |
1982 | |
1983 | // We might know the maximum number of elements in advance. |
1984 | llvm::APSInt maxElements(elementIndex.getBitWidth(), |
1985 | elementIndex.isUnsigned()); |
1986 | bool maxElementsKnown = false; |
1987 | if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Val: arrayType)) { |
1988 | maxElements = CAT->getSize(); |
1989 | elementIndex = elementIndex.extOrTrunc(width: maxElements.getBitWidth()); |
1990 | elementIndex.setIsUnsigned(maxElements.isUnsigned()); |
1991 | maxElementsKnown = true; |
1992 | } |
1993 | |
1994 | QualType elementType = arrayType->getElementType(); |
1995 | while (Index < IList->getNumInits()) { |
1996 | Expr *Init = IList->getInit(Init: Index); |
1997 | if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Val: Init)) { |
1998 | // If we're not the subobject that matches up with the '{' for |
1999 | // the designator, we shouldn't be handling the |
2000 | // designator. Return immediately. |
2001 | if (!SubobjectIsDesignatorContext) |
2002 | return; |
2003 | |
2004 | // Handle this designated initializer. elementIndex will be |
2005 | // updated to be the next array element we'll initialize. |
2006 | if (CheckDesignatedInitializer(Entity, IList, DIE, DesigIdx: 0, |
2007 | CurrentObjectType&: DeclType, NextField: nullptr, NextElementIndex: &elementIndex, Index, |
2008 | StructuredList, StructuredIndex, FinishSubobjectInit: true, |
2009 | TopLevelObject: false)) { |
2010 | hadError = true; |
2011 | continue; |
2012 | } |
2013 | |
2014 | if (elementIndex.getBitWidth() > maxElements.getBitWidth()) |
2015 | maxElements = maxElements.extend(width: elementIndex.getBitWidth()); |
2016 | else if (elementIndex.getBitWidth() < maxElements.getBitWidth()) |
2017 | elementIndex = elementIndex.extend(width: maxElements.getBitWidth()); |
2018 | elementIndex.setIsUnsigned(maxElements.isUnsigned()); |
2019 | |
2020 | // If the array is of incomplete type, keep track of the number of |
2021 | // elements in the initializer. |
2022 | if (!maxElementsKnown && elementIndex > maxElements) |
2023 | maxElements = elementIndex; |
2024 | |
2025 | continue; |
2026 | } |
2027 | |
2028 | // If we know the maximum number of elements, and we've already |
2029 | // hit it, stop consuming elements in the initializer list. |
2030 | if (maxElementsKnown && elementIndex == maxElements) |
2031 | break; |
2032 | |
2033 | InitializedEntity ElementEntity = |
2034 | InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: StructuredIndex, |
2035 | Parent: Entity); |
2036 | // Check this element. |
2037 | CheckSubElementType(Entity: ElementEntity, IList, ElemType: elementType, Index, |
2038 | StructuredList, StructuredIndex); |
2039 | ++elementIndex; |
2040 | |
2041 | // If the array is of incomplete type, keep track of the number of |
2042 | // elements in the initializer. |
2043 | if (!maxElementsKnown && elementIndex > maxElements) |
2044 | maxElements = elementIndex; |
2045 | } |
2046 | if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) { |
2047 | // If this is an incomplete array type, the actual type needs to |
2048 | // be calculated here. |
2049 | llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned()); |
2050 | if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) { |
2051 | // Sizing an array implicitly to zero is not allowed by ISO C, |
2052 | // but is supported by GNU. |
2053 | SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size); |
2054 | } |
2055 | |
2056 | DeclType = SemaRef.Context.getConstantArrayType( |
2057 | EltTy: elementType, ArySize: maxElements, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0); |
2058 | } |
2059 | if (!hadError) { |
2060 | // If there are any members of the array that get value-initialized, check |
2061 | // that is possible. That happens if we know the bound and don't have |
2062 | // enough elements, or if we're performing an array new with an unknown |
2063 | // bound. |
2064 | if ((maxElementsKnown && elementIndex < maxElements) || |
2065 | Entity.isVariableLengthArrayNew()) |
2066 | CheckEmptyInitializable( |
2067 | Entity: InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity), |
2068 | Loc: IList->getEndLoc()); |
2069 | } |
2070 | } |
2071 | |
2072 | bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity, |
2073 | Expr *InitExpr, |
2074 | FieldDecl *Field, |
2075 | bool TopLevelObject) { |
2076 | // Handle GNU flexible array initializers. |
2077 | unsigned FlexArrayDiag; |
2078 | if (isa<InitListExpr>(Val: InitExpr) && |
2079 | cast<InitListExpr>(Val: InitExpr)->getNumInits() == 0) { |
2080 | // Empty flexible array init always allowed as an extension |
2081 | FlexArrayDiag = diag::ext_flexible_array_init; |
2082 | } else if (!TopLevelObject) { |
2083 | // Disallow flexible array init on non-top-level object |
2084 | FlexArrayDiag = diag::err_flexible_array_init; |
2085 | } else if (Entity.getKind() != InitializedEntity::EK_Variable) { |
2086 | // Disallow flexible array init on anything which is not a variable. |
2087 | FlexArrayDiag = diag::err_flexible_array_init; |
2088 | } else if (cast<VarDecl>(Val: Entity.getDecl())->hasLocalStorage()) { |
2089 | // Disallow flexible array init on local variables. |
2090 | FlexArrayDiag = diag::err_flexible_array_init; |
2091 | } else { |
2092 | // Allow other cases. |
2093 | FlexArrayDiag = diag::ext_flexible_array_init; |
2094 | } |
2095 | |
2096 | if (!VerifyOnly) { |
2097 | SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag) |
2098 | << InitExpr->getBeginLoc(); |
2099 | SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) |
2100 | << Field; |
2101 | } |
2102 | |
2103 | return FlexArrayDiag != diag::ext_flexible_array_init; |
2104 | } |
2105 | |
2106 | void InitListChecker::CheckStructUnionTypes( |
2107 | const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType, |
2108 | CXXRecordDecl::base_class_const_range Bases, RecordDecl::field_iterator Field, |
2109 | bool SubobjectIsDesignatorContext, unsigned &Index, |
2110 | InitListExpr *StructuredList, unsigned &StructuredIndex, |
2111 | bool TopLevelObject) { |
2112 | const RecordDecl *RD = getRecordDecl(DeclType); |
2113 | |
2114 | // If the record is invalid, some of it's members are invalid. To avoid |
2115 | // confusion, we forgo checking the initializer for the entire record. |
2116 | if (RD->isInvalidDecl()) { |
2117 | // Assume it was supposed to consume a single initializer. |
2118 | ++Index; |
2119 | hadError = true; |
2120 | return; |
2121 | } |
2122 | |
2123 | if (RD->isUnion() && IList->getNumInits() == 0) { |
2124 | if (!VerifyOnly) |
2125 | for (FieldDecl *FD : RD->fields()) { |
2126 | QualType ET = SemaRef.Context.getBaseElementType(FD->getType()); |
2127 | if (checkDestructorReference(ElementType: ET, Loc: IList->getEndLoc(), SemaRef)) { |
2128 | hadError = true; |
2129 | return; |
2130 | } |
2131 | } |
2132 | |
2133 | // If there's a default initializer, use it. |
2134 | if (isa<CXXRecordDecl>(Val: RD) && |
2135 | cast<CXXRecordDecl>(Val: RD)->hasInClassInitializer()) { |
2136 | if (!StructuredList) |
2137 | return; |
2138 | for (RecordDecl::field_iterator FieldEnd = RD->field_end(); |
2139 | Field != FieldEnd; ++Field) { |
2140 | if (Field->hasInClassInitializer()) { |
2141 | StructuredList->setInitializedFieldInUnion(*Field); |
2142 | // FIXME: Actually build a CXXDefaultInitExpr? |
2143 | return; |
2144 | } |
2145 | } |
2146 | } |
2147 | |
2148 | // Value-initialize the first member of the union that isn't an unnamed |
2149 | // bitfield. |
2150 | for (RecordDecl::field_iterator FieldEnd = RD->field_end(); |
2151 | Field != FieldEnd; ++Field) { |
2152 | if (!Field->isUnnamedBitfield()) { |
2153 | CheckEmptyInitializable( |
2154 | Entity: InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity), |
2155 | Loc: IList->getEndLoc()); |
2156 | if (StructuredList) |
2157 | StructuredList->setInitializedFieldInUnion(*Field); |
2158 | break; |
2159 | } |
2160 | } |
2161 | return; |
2162 | } |
2163 | |
2164 | bool InitializedSomething = false; |
2165 | |
2166 | // If we have any base classes, they are initialized prior to the fields. |
2167 | for (auto I = Bases.begin(), E = Bases.end(); I != E; ++I) { |
2168 | auto &Base = *I; |
2169 | Expr *Init = Index < IList->getNumInits() ? IList->getInit(Init: Index) : nullptr; |
2170 | |
2171 | // Designated inits always initialize fields, so if we see one, all |
2172 | // remaining base classes have no explicit initializer. |
2173 | if (Init && isa<DesignatedInitExpr>(Val: Init)) |
2174 | Init = nullptr; |
2175 | |
2176 | // C++ [over.match.class.deduct]p1.6: |
2177 | // each non-trailing aggregate element that is a pack expansion is assumed |
2178 | // to correspond to no elements of the initializer list, and (1.7) a |
2179 | // trailing aggregate element that is a pack expansion is assumed to |
2180 | // correspond to all remaining elements of the initializer list (if any). |
2181 | |
2182 | // C++ [over.match.class.deduct]p1.9: |
2183 | // ... except that additional parameter packs of the form P_j... are |
2184 | // inserted into the parameter list in their original aggregate element |
2185 | // position corresponding to each non-trailing aggregate element of |
2186 | // type P_j that was skipped because it was a parameter pack, and the |
2187 | // trailing sequence of parameters corresponding to a trailing |
2188 | // aggregate element that is a pack expansion (if any) is replaced |
2189 | // by a single parameter of the form T_n.... |
2190 | if (AggrDeductionCandidateParamTypes && Base.isPackExpansion()) { |
2191 | AggrDeductionCandidateParamTypes->push_back( |
2192 | Elt: SemaRef.Context.getPackExpansionType(Pattern: Base.getType(), NumExpansions: std::nullopt)); |
2193 | |
2194 | // Trailing pack expansion |
2195 | if (I + 1 == E && RD->field_empty()) { |
2196 | if (Index < IList->getNumInits()) |
2197 | Index = IList->getNumInits(); |
2198 | return; |
2199 | } |
2200 | |
2201 | continue; |
2202 | } |
2203 | |
2204 | SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc(); |
2205 | InitializedEntity BaseEntity = InitializedEntity::InitializeBase( |
2206 | Context&: SemaRef.Context, Base: &Base, IsInheritedVirtualBase: false, Parent: &Entity); |
2207 | if (Init) { |
2208 | CheckSubElementType(Entity: BaseEntity, IList, ElemType: Base.getType(), Index, |
2209 | StructuredList, StructuredIndex); |
2210 | InitializedSomething = true; |
2211 | } else { |
2212 | CheckEmptyInitializable(Entity: BaseEntity, Loc: InitLoc); |
2213 | } |
2214 | |
2215 | if (!VerifyOnly) |
2216 | if (checkDestructorReference(ElementType: Base.getType(), Loc: InitLoc, SemaRef)) { |
2217 | hadError = true; |
2218 | return; |
2219 | } |
2220 | } |
2221 | |
2222 | // If structDecl is a forward declaration, this loop won't do |
2223 | // anything except look at designated initializers; That's okay, |
2224 | // because an error should get printed out elsewhere. It might be |
2225 | // worthwhile to skip over the rest of the initializer, though. |
2226 | RecordDecl::field_iterator FieldEnd = RD->field_end(); |
2227 | size_t NumRecordDecls = llvm::count_if(RD->decls(), [&](const Decl *D) { |
2228 | return isa<FieldDecl>(Val: D) || isa<RecordDecl>(Val: D); |
2229 | }); |
2230 | bool CheckForMissingFields = |
2231 | !IList->isIdiomaticZeroInitializer(LangOpts: SemaRef.getLangOpts()); |
2232 | bool HasDesignatedInit = false; |
2233 | |
2234 | llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields; |
2235 | |
2236 | while (Index < IList->getNumInits()) { |
2237 | Expr *Init = IList->getInit(Init: Index); |
2238 | SourceLocation InitLoc = Init->getBeginLoc(); |
2239 | |
2240 | if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Val: Init)) { |
2241 | // If we're not the subobject that matches up with the '{' for |
2242 | // the designator, we shouldn't be handling the |
2243 | // designator. Return immediately. |
2244 | if (!SubobjectIsDesignatorContext) |
2245 | return; |
2246 | |
2247 | HasDesignatedInit = true; |
2248 | |
2249 | // Handle this designated initializer. Field will be updated to |
2250 | // the next field that we'll be initializing. |
2251 | bool DesignatedInitFailed = CheckDesignatedInitializer( |
2252 | Entity, IList, DIE, DesigIdx: 0, CurrentObjectType&: DeclType, NextField: &Field, NextElementIndex: nullptr, Index, |
2253 | StructuredList, StructuredIndex, FinishSubobjectInit: true, TopLevelObject); |
2254 | if (DesignatedInitFailed) |
2255 | hadError = true; |
2256 | |
2257 | // Find the field named by the designated initializer. |
2258 | DesignatedInitExpr::Designator *D = DIE->getDesignator(Idx: 0); |
2259 | if (!VerifyOnly && D->isFieldDesignator()) { |
2260 | FieldDecl *F = D->getFieldDecl(); |
2261 | InitializedFields.insert(Ptr: F); |
2262 | if (!DesignatedInitFailed) { |
2263 | QualType ET = SemaRef.Context.getBaseElementType(F->getType()); |
2264 | if (checkDestructorReference(ElementType: ET, Loc: InitLoc, SemaRef)) { |
2265 | hadError = true; |
2266 | return; |
2267 | } |
2268 | } |
2269 | } |
2270 | |
2271 | InitializedSomething = true; |
2272 | |
2273 | // Disable check for missing fields when designators are used. |
2274 | // This matches gcc behaviour. |
2275 | if (!SemaRef.getLangOpts().CPlusPlus) |
2276 | CheckForMissingFields = false; |
2277 | continue; |
2278 | } |
2279 | |
2280 | // Check if this is an initializer of forms: |
2281 | // |
2282 | // struct foo f = {}; |
2283 | // struct foo g = {0}; |
2284 | // |
2285 | // These are okay for randomized structures. [C99 6.7.8p19] |
2286 | // |
2287 | // Also, if there is only one element in the structure, we allow something |
2288 | // like this, because it's really not randomized in the tranditional sense. |
2289 | // |
2290 | // struct foo h = {bar}; |
2291 | auto IsZeroInitializer = [&](const Expr *I) { |
2292 | if (IList->getNumInits() == 1) { |
2293 | if (NumRecordDecls == 1) |
2294 | return true; |
2295 | if (const auto *IL = dyn_cast<IntegerLiteral>(I)) |
2296 | return IL->getValue().isZero(); |
2297 | } |
2298 | return false; |
2299 | }; |
2300 | |
2301 | // Don't allow non-designated initializers on randomized structures. |
2302 | if (RD->isRandomized() && !IsZeroInitializer(Init)) { |
2303 | if (!VerifyOnly) |
2304 | SemaRef.Diag(InitLoc, diag::err_non_designated_init_used); |
2305 | hadError = true; |
2306 | break; |
2307 | } |
2308 | |
2309 | if (Field == FieldEnd) { |
2310 | // We've run out of fields. We're done. |
2311 | break; |
2312 | } |
2313 | |
2314 | // We've already initialized a member of a union. We're done. |
2315 | if (InitializedSomething && RD->isUnion()) |
2316 | break; |
2317 | |
2318 | // If we've hit the flexible array member at the end, we're done. |
2319 | if (Field->getType()->isIncompleteArrayType()) |
2320 | break; |
2321 | |
2322 | if (Field->isUnnamedBitfield()) { |
2323 | // Don't initialize unnamed bitfields, e.g. "int : 20;" |
2324 | ++Field; |
2325 | continue; |
2326 | } |
2327 | |
2328 | // Make sure we can use this declaration. |
2329 | bool InvalidUse; |
2330 | if (VerifyOnly) |
2331 | InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid); |
2332 | else |
2333 | InvalidUse = SemaRef.DiagnoseUseOfDecl( |
2334 | D: *Field, Locs: IList->getInit(Init: Index)->getBeginLoc()); |
2335 | if (InvalidUse) { |
2336 | ++Index; |
2337 | ++Field; |
2338 | hadError = true; |
2339 | continue; |
2340 | } |
2341 | |
2342 | if (!VerifyOnly) { |
2343 | QualType ET = SemaRef.Context.getBaseElementType(Field->getType()); |
2344 | if (checkDestructorReference(ElementType: ET, Loc: InitLoc, SemaRef)) { |
2345 | hadError = true; |
2346 | return; |
2347 | } |
2348 | } |
2349 | |
2350 | InitializedEntity MemberEntity = |
2351 | InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity); |
2352 | CheckSubElementType(Entity: MemberEntity, IList, ElemType: Field->getType(), Index, |
2353 | StructuredList, StructuredIndex); |
2354 | InitializedSomething = true; |
2355 | InitializedFields.insert(Ptr: *Field); |
2356 | |
2357 | if (RD->isUnion() && StructuredList) { |
2358 | // Initialize the first field within the union. |
2359 | StructuredList->setInitializedFieldInUnion(*Field); |
2360 | } |
2361 | |
2362 | ++Field; |
2363 | } |
2364 | |
2365 | // Emit warnings for missing struct field initializers. |
2366 | if (!VerifyOnly && InitializedSomething && CheckForMissingFields && |
2367 | !RD->isUnion()) { |
2368 | // It is possible we have one or more unnamed bitfields remaining. |
2369 | // Find first (if any) named field and emit warning. |
2370 | for (RecordDecl::field_iterator it = HasDesignatedInit ? RD->field_begin() |
2371 | : Field, |
2372 | end = RD->field_end(); |
2373 | it != end; ++it) { |
2374 | if (HasDesignatedInit && InitializedFields.count(Ptr: *it)) |
2375 | continue; |
2376 | |
2377 | if (!it->isUnnamedBitfield() && !it->hasInClassInitializer() && |
2378 | !it->getType()->isIncompleteArrayType()) { |
2379 | SemaRef.Diag(IList->getSourceRange().getEnd(), |
2380 | diag::warn_missing_field_initializers) |
2381 | << *it; |
2382 | break; |
2383 | } |
2384 | } |
2385 | } |
2386 | |
2387 | // Check that any remaining fields can be value-initialized if we're not |
2388 | // building a structured list. (If we are, we'll check this later.) |
2389 | if (!StructuredList && Field != FieldEnd && !RD->isUnion() && |
2390 | !Field->getType()->isIncompleteArrayType()) { |
2391 | for (; Field != FieldEnd && !hadError; ++Field) { |
2392 | if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer()) |
2393 | CheckEmptyInitializable( |
2394 | Entity: InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity), |
2395 | Loc: IList->getEndLoc()); |
2396 | } |
2397 | } |
2398 | |
2399 | // Check that the types of the remaining fields have accessible destructors. |
2400 | if (!VerifyOnly) { |
2401 | // If the initializer expression has a designated initializer, check the |
2402 | // elements for which a designated initializer is not provided too. |
2403 | RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin() |
2404 | : Field; |
2405 | for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) { |
2406 | QualType ET = SemaRef.Context.getBaseElementType(I->getType()); |
2407 | if (checkDestructorReference(ElementType: ET, Loc: IList->getEndLoc(), SemaRef)) { |
2408 | hadError = true; |
2409 | return; |
2410 | } |
2411 | } |
2412 | } |
2413 | |
2414 | if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() || |
2415 | Index >= IList->getNumInits()) |
2416 | return; |
2417 | |
2418 | if (CheckFlexibleArrayInit(Entity, InitExpr: IList->getInit(Init: Index), Field: *Field, |
2419 | TopLevelObject)) { |
2420 | hadError = true; |
2421 | ++Index; |
2422 | return; |
2423 | } |
2424 | |
2425 | InitializedEntity MemberEntity = |
2426 | InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity); |
2427 | |
2428 | if (isa<InitListExpr>(Val: IList->getInit(Init: Index)) || |
2429 | AggrDeductionCandidateParamTypes) |
2430 | CheckSubElementType(Entity: MemberEntity, IList, ElemType: Field->getType(), Index, |
2431 | StructuredList, StructuredIndex); |
2432 | else |
2433 | CheckImplicitInitList(Entity: MemberEntity, ParentIList: IList, T: Field->getType(), Index, |
2434 | StructuredList, StructuredIndex); |
2435 | } |
2436 | |
2437 | /// Expand a field designator that refers to a member of an |
2438 | /// anonymous struct or union into a series of field designators that |
2439 | /// refers to the field within the appropriate subobject. |
2440 | /// |
2441 | static void ExpandAnonymousFieldDesignator(Sema &SemaRef, |
2442 | DesignatedInitExpr *DIE, |
2443 | unsigned DesigIdx, |
2444 | IndirectFieldDecl *IndirectField) { |
2445 | typedef DesignatedInitExpr::Designator Designator; |
2446 | |
2447 | // Build the replacement designators. |
2448 | SmallVector<Designator, 4> Replacements; |
2449 | for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(), |
2450 | PE = IndirectField->chain_end(); PI != PE; ++PI) { |
2451 | if (PI + 1 == PE) |
2452 | Replacements.push_back(Elt: Designator::CreateFieldDesignator( |
2453 | FieldName: (IdentifierInfo *)nullptr, DotLoc: DIE->getDesignator(Idx: DesigIdx)->getDotLoc(), |
2454 | FieldLoc: DIE->getDesignator(Idx: DesigIdx)->getFieldLoc())); |
2455 | else |
2456 | Replacements.push_back(Elt: Designator::CreateFieldDesignator( |
2457 | FieldName: (IdentifierInfo *)nullptr, DotLoc: SourceLocation(), FieldLoc: SourceLocation())); |
2458 | assert(isa<FieldDecl>(*PI)); |
2459 | Replacements.back().setFieldDecl(cast<FieldDecl>(Val: *PI)); |
2460 | } |
2461 | |
2462 | // Expand the current designator into the set of replacement |
2463 | // designators, so we have a full subobject path down to where the |
2464 | // member of the anonymous struct/union is actually stored. |
2465 | DIE->ExpandDesignator(C: SemaRef.Context, Idx: DesigIdx, First: &Replacements[0], |
2466 | Last: &Replacements[0] + Replacements.size()); |
2467 | } |
2468 | |
2469 | static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef, |
2470 | DesignatedInitExpr *DIE) { |
2471 | unsigned NumIndexExprs = DIE->getNumSubExprs() - 1; |
2472 | SmallVector<Expr*, 4> IndexExprs(NumIndexExprs); |
2473 | for (unsigned I = 0; I < NumIndexExprs; ++I) |
2474 | IndexExprs[I] = DIE->getSubExpr(Idx: I + 1); |
2475 | return DesignatedInitExpr::Create(C: SemaRef.Context, Designators: DIE->designators(), |
2476 | IndexExprs, |
2477 | EqualOrColonLoc: DIE->getEqualOrColonLoc(), |
2478 | GNUSyntax: DIE->usesGNUSyntax(), Init: DIE->getInit()); |
2479 | } |
2480 | |
2481 | namespace { |
2482 | |
2483 | // Callback to only accept typo corrections that are for field members of |
2484 | // the given struct or union. |
2485 | class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback { |
2486 | public: |
2487 | explicit FieldInitializerValidatorCCC(const RecordDecl *RD) |
2488 | : Record(RD) {} |
2489 | |
2490 | bool ValidateCandidate(const TypoCorrection &candidate) override { |
2491 | FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>(); |
2492 | return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record); |
2493 | } |
2494 | |
2495 | std::unique_ptr<CorrectionCandidateCallback> clone() override { |
2496 | return std::make_unique<FieldInitializerValidatorCCC>(args&: *this); |
2497 | } |
2498 | |
2499 | private: |
2500 | const RecordDecl *Record; |
2501 | }; |
2502 | |
2503 | } // end anonymous namespace |
2504 | |
2505 | /// Check the well-formedness of a C99 designated initializer. |
2506 | /// |
2507 | /// Determines whether the designated initializer @p DIE, which |
2508 | /// resides at the given @p Index within the initializer list @p |
2509 | /// IList, is well-formed for a current object of type @p DeclType |
2510 | /// (C99 6.7.8). The actual subobject that this designator refers to |
2511 | /// within the current subobject is returned in either |
2512 | /// @p NextField or @p NextElementIndex (whichever is appropriate). |
2513 | /// |
2514 | /// @param IList The initializer list in which this designated |
2515 | /// initializer occurs. |
2516 | /// |
2517 | /// @param DIE The designated initializer expression. |
2518 | /// |
2519 | /// @param DesigIdx The index of the current designator. |
2520 | /// |
2521 | /// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17), |
2522 | /// into which the designation in @p DIE should refer. |
2523 | /// |
2524 | /// @param NextField If non-NULL and the first designator in @p DIE is |
2525 | /// a field, this will be set to the field declaration corresponding |
2526 | /// to the field named by the designator. On input, this is expected to be |
2527 | /// the next field that would be initialized in the absence of designation, |
2528 | /// if the complete object being initialized is a struct. |
2529 | /// |
2530 | /// @param NextElementIndex If non-NULL and the first designator in @p |
2531 | /// DIE is an array designator or GNU array-range designator, this |
2532 | /// will be set to the last index initialized by this designator. |
2533 | /// |
2534 | /// @param Index Index into @p IList where the designated initializer |
2535 | /// @p DIE occurs. |
2536 | /// |
2537 | /// @param StructuredList The initializer list expression that |
2538 | /// describes all of the subobject initializers in the order they'll |
2539 | /// actually be initialized. |
2540 | /// |
2541 | /// @returns true if there was an error, false otherwise. |
2542 | bool |
2543 | InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity, |
2544 | InitListExpr *IList, |
2545 | DesignatedInitExpr *DIE, |
2546 | unsigned DesigIdx, |
2547 | QualType &CurrentObjectType, |
2548 | RecordDecl::field_iterator *NextField, |
2549 | llvm::APSInt *NextElementIndex, |
2550 | unsigned &Index, |
2551 | InitListExpr *StructuredList, |
2552 | unsigned &StructuredIndex, |
2553 | bool FinishSubobjectInit, |
2554 | bool TopLevelObject) { |
2555 | if (DesigIdx == DIE->size()) { |
2556 | // C++20 designated initialization can result in direct-list-initialization |
2557 | // of the designated subobject. This is the only way that we can end up |
2558 | // performing direct initialization as part of aggregate initialization, so |
2559 | // it needs special handling. |
2560 | if (DIE->isDirectInit()) { |
2561 | Expr *Init = DIE->getInit(); |
2562 | assert(isa<InitListExpr>(Init) && |
2563 | "designator result in direct non-list initialization?" ); |
2564 | InitializationKind Kind = InitializationKind::CreateDirectList( |
2565 | DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc()); |
2566 | InitializationSequence Seq(SemaRef, Entity, Kind, Init, |
2567 | /*TopLevelOfInitList*/ true); |
2568 | if (StructuredList) { |
2569 | ExprResult Result = VerifyOnly |
2570 | ? getDummyInit() |
2571 | : Seq.Perform(S&: SemaRef, Entity, Kind, Args: Init); |
2572 | UpdateStructuredListElement(StructuredList, StructuredIndex, |
2573 | expr: Result.get()); |
2574 | } |
2575 | ++Index; |
2576 | if (AggrDeductionCandidateParamTypes) |
2577 | AggrDeductionCandidateParamTypes->push_back(Elt: CurrentObjectType); |
2578 | return !Seq; |
2579 | } |
2580 | |
2581 | // Check the actual initialization for the designated object type. |
2582 | bool prevHadError = hadError; |
2583 | |
2584 | // Temporarily remove the designator expression from the |
2585 | // initializer list that the child calls see, so that we don't try |
2586 | // to re-process the designator. |
2587 | unsigned OldIndex = Index; |
2588 | IList->setInit(Init: OldIndex, expr: DIE->getInit()); |
2589 | |
2590 | CheckSubElementType(Entity, IList, ElemType: CurrentObjectType, Index, StructuredList, |
2591 | StructuredIndex, /*DirectlyDesignated=*/true); |
2592 | |
2593 | // Restore the designated initializer expression in the syntactic |
2594 | // form of the initializer list. |
2595 | if (IList->getInit(Init: OldIndex) != DIE->getInit()) |
2596 | DIE->setInit(IList->getInit(Init: OldIndex)); |
2597 | IList->setInit(OldIndex, DIE); |
2598 | |
2599 | return hadError && !prevHadError; |
2600 | } |
2601 | |
2602 | DesignatedInitExpr::Designator *D = DIE->getDesignator(Idx: DesigIdx); |
2603 | bool IsFirstDesignator = (DesigIdx == 0); |
2604 | if (IsFirstDesignator ? FullyStructuredList : StructuredList) { |
2605 | // Determine the structural initializer list that corresponds to the |
2606 | // current subobject. |
2607 | if (IsFirstDesignator) |
2608 | StructuredList = FullyStructuredList; |
2609 | else { |
2610 | Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ? |
2611 | StructuredList->getInit(Init: StructuredIndex) : nullptr; |
2612 | if (!ExistingInit && StructuredList->hasArrayFiller()) |
2613 | ExistingInit = StructuredList->getArrayFiller(); |
2614 | |
2615 | if (!ExistingInit) |
2616 | StructuredList = getStructuredSubobjectInit( |
2617 | IList, Index, CurrentObjectType, StructuredList, StructuredIndex, |
2618 | InitRange: SourceRange(D->getBeginLoc(), DIE->getEndLoc())); |
2619 | else if (InitListExpr *Result = dyn_cast<InitListExpr>(Val: ExistingInit)) |
2620 | StructuredList = Result; |
2621 | else { |
2622 | // We are creating an initializer list that initializes the |
2623 | // subobjects of the current object, but there was already an |
2624 | // initialization that completely initialized the current |
2625 | // subobject, e.g., by a compound literal: |
2626 | // |
2627 | // struct X { int a, b; }; |
2628 | // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 }; |
2629 | // |
2630 | // Here, xs[0].a == 1 and xs[0].b == 3, since the second, |
2631 | // designated initializer re-initializes only its current object |
2632 | // subobject [0].b. |
2633 | diagnoseInitOverride(OldInit: ExistingInit, |
2634 | NewInitRange: SourceRange(D->getBeginLoc(), DIE->getEndLoc()), |
2635 | /*UnionOverride=*/false, |
2636 | /*FullyOverwritten=*/false); |
2637 | |
2638 | if (!VerifyOnly) { |
2639 | if (DesignatedInitUpdateExpr *E = |
2640 | dyn_cast<DesignatedInitUpdateExpr>(Val: ExistingInit)) |
2641 | StructuredList = E->getUpdater(); |
2642 | else { |
2643 | DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context) |
2644 | DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(), |
2645 | ExistingInit, DIE->getEndLoc()); |
2646 | StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE); |
2647 | StructuredList = DIUE->getUpdater(); |
2648 | } |
2649 | } else { |
2650 | // We don't need to track the structured representation of a |
2651 | // designated init update of an already-fully-initialized object in |
2652 | // verify-only mode. The only reason we would need the structure is |
2653 | // to determine where the uninitialized "holes" are, and in this |
2654 | // case, we know there aren't any and we can't introduce any. |
2655 | StructuredList = nullptr; |
2656 | } |
2657 | } |
2658 | } |
2659 | } |
2660 | |
2661 | if (D->isFieldDesignator()) { |
2662 | // C99 6.7.8p7: |
2663 | // |
2664 | // If a designator has the form |
2665 | // |
2666 | // . identifier |
2667 | // |
2668 | // then the current object (defined below) shall have |
2669 | // structure or union type and the identifier shall be the |
2670 | // name of a member of that type. |
2671 | RecordDecl *RD = getRecordDecl(DeclType: CurrentObjectType); |
2672 | if (!RD) { |
2673 | SourceLocation Loc = D->getDotLoc(); |
2674 | if (Loc.isInvalid()) |
2675 | Loc = D->getFieldLoc(); |
2676 | if (!VerifyOnly) |
2677 | SemaRef.Diag(Loc, diag::err_field_designator_non_aggr) |
2678 | << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType; |
2679 | ++Index; |
2680 | return true; |
2681 | } |
2682 | |
2683 | FieldDecl *KnownField = D->getFieldDecl(); |
2684 | if (!KnownField) { |
2685 | const IdentifierInfo *FieldName = D->getFieldName(); |
2686 | ValueDecl *VD = SemaRef.tryLookupUnambiguousFieldDecl(ClassDecl: RD, MemberOrBase: FieldName); |
2687 | if (auto *FD = dyn_cast_if_present<FieldDecl>(Val: VD)) { |
2688 | KnownField = FD; |
2689 | } else if (auto *IFD = dyn_cast_if_present<IndirectFieldDecl>(Val: VD)) { |
2690 | // In verify mode, don't modify the original. |
2691 | if (VerifyOnly) |
2692 | DIE = CloneDesignatedInitExpr(SemaRef, DIE); |
2693 | ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IndirectField: IFD); |
2694 | D = DIE->getDesignator(Idx: DesigIdx); |
2695 | KnownField = cast<FieldDecl>(Val: *IFD->chain_begin()); |
2696 | } |
2697 | if (!KnownField) { |
2698 | if (VerifyOnly) { |
2699 | ++Index; |
2700 | return true; // No typo correction when just trying this out. |
2701 | } |
2702 | |
2703 | // We found a placeholder variable |
2704 | if (SemaRef.DiagRedefinedPlaceholderFieldDecl(Loc: DIE->getBeginLoc(), ClassDecl: RD, |
2705 | Name: FieldName)) { |
2706 | ++Index; |
2707 | return true; |
2708 | } |
2709 | // Name lookup found something, but it wasn't a field. |
2710 | if (DeclContextLookupResult Lookup = RD->lookup(FieldName); |
2711 | !Lookup.empty()) { |
2712 | SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield) |
2713 | << FieldName; |
2714 | SemaRef.Diag(Lookup.front()->getLocation(), |
2715 | diag::note_field_designator_found); |
2716 | ++Index; |
2717 | return true; |
2718 | } |
2719 | |
2720 | // Name lookup didn't find anything. |
2721 | // Determine whether this was a typo for another field name. |
2722 | FieldInitializerValidatorCCC CCC(RD); |
2723 | if (TypoCorrection Corrected = SemaRef.CorrectTypo( |
2724 | DeclarationNameInfo(FieldName, D->getFieldLoc()), |
2725 | Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC, |
2726 | Sema::CTK_ErrorRecovery, RD)) { |
2727 | SemaRef.diagnoseTypo( |
2728 | Corrected, |
2729 | SemaRef.PDiag(diag::err_field_designator_unknown_suggest) |
2730 | << FieldName << CurrentObjectType); |
2731 | KnownField = Corrected.getCorrectionDeclAs<FieldDecl>(); |
2732 | hadError = true; |
2733 | } else { |
2734 | // Typo correction didn't find anything. |
2735 | SourceLocation Loc = D->getFieldLoc(); |
2736 | |
2737 | // The loc can be invalid with a "null" designator (i.e. an anonymous |
2738 | // union/struct). Do our best to approximate the location. |
2739 | if (Loc.isInvalid()) |
2740 | Loc = IList->getBeginLoc(); |
2741 | |
2742 | SemaRef.Diag(Loc, diag::err_field_designator_unknown) |
2743 | << FieldName << CurrentObjectType << DIE->getSourceRange(); |
2744 | ++Index; |
2745 | return true; |
2746 | } |
2747 | } |
2748 | } |
2749 | |
2750 | unsigned NumBases = 0; |
2751 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) |
2752 | NumBases = CXXRD->getNumBases(); |
2753 | |
2754 | unsigned FieldIndex = NumBases; |
2755 | |
2756 | for (auto *FI : RD->fields()) { |
2757 | if (FI->isUnnamedBitfield()) |
2758 | continue; |
2759 | if (declaresSameEntity(KnownField, FI)) { |
2760 | KnownField = FI; |
2761 | break; |
2762 | } |
2763 | ++FieldIndex; |
2764 | } |
2765 | |
2766 | RecordDecl::field_iterator Field = |
2767 | RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField)); |
2768 | |
2769 | // All of the fields of a union are located at the same place in |
2770 | // the initializer list. |
2771 | if (RD->isUnion()) { |
2772 | FieldIndex = 0; |
2773 | if (StructuredList) { |
2774 | FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion(); |
2775 | if (CurrentField && !declaresSameEntity(CurrentField, *Field)) { |
2776 | assert(StructuredList->getNumInits() == 1 |
2777 | && "A union should never have more than one initializer!" ); |
2778 | |
2779 | Expr *ExistingInit = StructuredList->getInit(Init: 0); |
2780 | if (ExistingInit) { |
2781 | // We're about to throw away an initializer, emit warning. |
2782 | diagnoseInitOverride( |
2783 | OldInit: ExistingInit, NewInitRange: SourceRange(D->getBeginLoc(), DIE->getEndLoc()), |
2784 | /*UnionOverride=*/true, |
2785 | /*FullyOverwritten=*/SemaRef.getLangOpts().CPlusPlus ? false |
2786 | : true); |
2787 | } |
2788 | |
2789 | // remove existing initializer |
2790 | StructuredList->resizeInits(Context: SemaRef.Context, NumInits: 0); |
2791 | StructuredList->setInitializedFieldInUnion(nullptr); |
2792 | } |
2793 | |
2794 | StructuredList->setInitializedFieldInUnion(*Field); |
2795 | } |
2796 | } |
2797 | |
2798 | // Make sure we can use this declaration. |
2799 | bool InvalidUse; |
2800 | if (VerifyOnly) |
2801 | InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid); |
2802 | else |
2803 | InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc()); |
2804 | if (InvalidUse) { |
2805 | ++Index; |
2806 | return true; |
2807 | } |
2808 | |
2809 | // C++20 [dcl.init.list]p3: |
2810 | // The ordered identifiers in the designators of the designated- |
2811 | // initializer-list shall form a subsequence of the ordered identifiers |
2812 | // in the direct non-static data members of T. |
2813 | // |
2814 | // Note that this is not a condition on forming the aggregate |
2815 | // initialization, only on actually performing initialization, |
2816 | // so it is not checked in VerifyOnly mode. |
2817 | // |
2818 | // FIXME: This is the only reordering diagnostic we produce, and it only |
2819 | // catches cases where we have a top-level field designator that jumps |
2820 | // backwards. This is the only such case that is reachable in an |
2821 | // otherwise-valid C++20 program, so is the only case that's required for |
2822 | // conformance, but for consistency, we should diagnose all the other |
2823 | // cases where a designator takes us backwards too. |
2824 | if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus && |
2825 | NextField && |
2826 | (*NextField == RD->field_end() || |
2827 | (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) { |
2828 | // Find the field that we just initialized. |
2829 | FieldDecl *PrevField = nullptr; |
2830 | for (auto FI = RD->field_begin(); FI != RD->field_end(); ++FI) { |
2831 | if (FI->isUnnamedBitfield()) |
2832 | continue; |
2833 | if (*NextField != RD->field_end() && |
2834 | declaresSameEntity(*FI, **NextField)) |
2835 | break; |
2836 | PrevField = *FI; |
2837 | } |
2838 | |
2839 | if (PrevField && |
2840 | PrevField->getFieldIndex() > KnownField->getFieldIndex()) { |
2841 | SemaRef.Diag(DIE->getInit()->getBeginLoc(), |
2842 | diag::ext_designated_init_reordered) |
2843 | << KnownField << PrevField << DIE->getSourceRange(); |
2844 | |
2845 | unsigned OldIndex = StructuredIndex - 1; |
2846 | if (StructuredList && OldIndex <= StructuredList->getNumInits()) { |
2847 | if (Expr *PrevInit = StructuredList->getInit(Init: OldIndex)) { |
2848 | SemaRef.Diag(PrevInit->getBeginLoc(), |
2849 | diag::note_previous_field_init) |
2850 | << PrevField << PrevInit->getSourceRange(); |
2851 | } |
2852 | } |
2853 | } |
2854 | } |
2855 | |
2856 | |
2857 | // Update the designator with the field declaration. |
2858 | if (!VerifyOnly) |
2859 | D->setFieldDecl(*Field); |
2860 | |
2861 | // Make sure that our non-designated initializer list has space |
2862 | // for a subobject corresponding to this field. |
2863 | if (StructuredList && FieldIndex >= StructuredList->getNumInits()) |
2864 | StructuredList->resizeInits(Context: SemaRef.Context, NumInits: FieldIndex + 1); |
2865 | |
2866 | // This designator names a flexible array member. |
2867 | if (Field->getType()->isIncompleteArrayType()) { |
2868 | bool Invalid = false; |
2869 | if ((DesigIdx + 1) != DIE->size()) { |
2870 | // We can't designate an object within the flexible array |
2871 | // member (because GCC doesn't allow it). |
2872 | if (!VerifyOnly) { |
2873 | DesignatedInitExpr::Designator *NextD |
2874 | = DIE->getDesignator(Idx: DesigIdx + 1); |
2875 | SemaRef.Diag(NextD->getBeginLoc(), |
2876 | diag::err_designator_into_flexible_array_member) |
2877 | << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc()); |
2878 | SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) |
2879 | << *Field; |
2880 | } |
2881 | Invalid = true; |
2882 | } |
2883 | |
2884 | if (!hadError && !isa<InitListExpr>(Val: DIE->getInit()) && |
2885 | !isa<StringLiteral>(Val: DIE->getInit())) { |
2886 | // The initializer is not an initializer list. |
2887 | if (!VerifyOnly) { |
2888 | SemaRef.Diag(DIE->getInit()->getBeginLoc(), |
2889 | diag::err_flexible_array_init_needs_braces) |
2890 | << DIE->getInit()->getSourceRange(); |
2891 | SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) |
2892 | << *Field; |
2893 | } |
2894 | Invalid = true; |
2895 | } |
2896 | |
2897 | // Check GNU flexible array initializer. |
2898 | if (!Invalid && CheckFlexibleArrayInit(Entity, InitExpr: DIE->getInit(), Field: *Field, |
2899 | TopLevelObject)) |
2900 | Invalid = true; |
2901 | |
2902 | if (Invalid) { |
2903 | ++Index; |
2904 | return true; |
2905 | } |
2906 | |
2907 | // Initialize the array. |
2908 | bool prevHadError = hadError; |
2909 | unsigned newStructuredIndex = FieldIndex; |
2910 | unsigned OldIndex = Index; |
2911 | IList->setInit(Init: Index, expr: DIE->getInit()); |
2912 | |
2913 | InitializedEntity MemberEntity = |
2914 | InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity); |
2915 | CheckSubElementType(Entity: MemberEntity, IList, ElemType: Field->getType(), Index, |
2916 | StructuredList, StructuredIndex&: newStructuredIndex); |
2917 | |
2918 | IList->setInit(OldIndex, DIE); |
2919 | if (hadError && !prevHadError) { |
2920 | ++Field; |
2921 | ++FieldIndex; |
2922 | if (NextField) |
2923 | *NextField = Field; |
2924 | StructuredIndex = FieldIndex; |
2925 | return true; |
2926 | } |
2927 | } else { |
2928 | // Recurse to check later designated subobjects. |
2929 | QualType FieldType = Field->getType(); |
2930 | unsigned newStructuredIndex = FieldIndex; |
2931 | |
2932 | InitializedEntity MemberEntity = |
2933 | InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity); |
2934 | if (CheckDesignatedInitializer(Entity: MemberEntity, IList, DIE, DesigIdx: DesigIdx + 1, |
2935 | CurrentObjectType&: FieldType, NextField: nullptr, NextElementIndex: nullptr, Index, |
2936 | StructuredList, StructuredIndex&: newStructuredIndex, |
2937 | FinishSubobjectInit, TopLevelObject: false)) |
2938 | return true; |
2939 | } |
2940 | |
2941 | // Find the position of the next field to be initialized in this |
2942 | // subobject. |
2943 | ++Field; |
2944 | ++FieldIndex; |
2945 | |
2946 | // If this the first designator, our caller will continue checking |
2947 | // the rest of this struct/class/union subobject. |
2948 | if (IsFirstDesignator) { |
2949 | if (Field != RD->field_end() && Field->isUnnamedBitfield()) |
2950 | ++Field; |
2951 | |
2952 | if (NextField) |
2953 | *NextField = Field; |
2954 | |
2955 | StructuredIndex = FieldIndex; |
2956 | return false; |
2957 | } |
2958 | |
2959 | if (!FinishSubobjectInit) |
2960 | return false; |
2961 | |
2962 | // We've already initialized something in the union; we're done. |
2963 | if (RD->isUnion()) |
2964 | return hadError; |
2965 | |
2966 | // Check the remaining fields within this class/struct/union subobject. |
2967 | bool prevHadError = hadError; |
2968 | |
2969 | auto NoBases = |
2970 | CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(), |
2971 | CXXRecordDecl::base_class_iterator()); |
2972 | CheckStructUnionTypes(Entity, IList, DeclType: CurrentObjectType, Bases: NoBases, Field, |
2973 | SubobjectIsDesignatorContext: false, Index, StructuredList, StructuredIndex&: FieldIndex); |
2974 | return hadError && !prevHadError; |
2975 | } |
2976 | |
2977 | // C99 6.7.8p6: |
2978 | // |
2979 | // If a designator has the form |
2980 | // |
2981 | // [ constant-expression ] |
2982 | // |
2983 | // then the current object (defined below) shall have array |
2984 | // type and the expression shall be an integer constant |
2985 | // expression. If the array is of unknown size, any |
2986 | // nonnegative value is valid. |
2987 | // |
2988 | // Additionally, cope with the GNU extension that permits |
2989 | // designators of the form |
2990 | // |
2991 | // [ constant-expression ... constant-expression ] |
2992 | const ArrayType *AT = SemaRef.Context.getAsArrayType(T: CurrentObjectType); |
2993 | if (!AT) { |
2994 | if (!VerifyOnly) |
2995 | SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array) |
2996 | << CurrentObjectType; |
2997 | ++Index; |
2998 | return true; |
2999 | } |
3000 | |
3001 | Expr *IndexExpr = nullptr; |
3002 | llvm::APSInt DesignatedStartIndex, DesignatedEndIndex; |
3003 | if (D->isArrayDesignator()) { |
3004 | IndexExpr = DIE->getArrayIndex(D: *D); |
3005 | DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(Ctx: SemaRef.Context); |
3006 | DesignatedEndIndex = DesignatedStartIndex; |
3007 | } else { |
3008 | assert(D->isArrayRangeDesignator() && "Need array-range designator" ); |
3009 | |
3010 | DesignatedStartIndex = |
3011 | DIE->getArrayRangeStart(D: *D)->EvaluateKnownConstInt(Ctx: SemaRef.Context); |
3012 | DesignatedEndIndex = |
3013 | DIE->getArrayRangeEnd(D: *D)->EvaluateKnownConstInt(Ctx: SemaRef.Context); |
3014 | IndexExpr = DIE->getArrayRangeEnd(D: *D); |
3015 | |
3016 | // Codegen can't handle evaluating array range designators that have side |
3017 | // effects, because we replicate the AST value for each initialized element. |
3018 | // As such, set the sawArrayRangeDesignator() bit if we initialize multiple |
3019 | // elements with something that has a side effect, so codegen can emit an |
3020 | // "error unsupported" error instead of miscompiling the app. |
3021 | if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&& |
3022 | DIE->getInit()->HasSideEffects(Ctx: SemaRef.Context) && !VerifyOnly) |
3023 | FullyStructuredList->sawArrayRangeDesignator(); |
3024 | } |
3025 | |
3026 | if (isa<ConstantArrayType>(Val: AT)) { |
3027 | llvm::APSInt MaxElements(cast<ConstantArrayType>(Val: AT)->getSize(), false); |
3028 | DesignatedStartIndex |
3029 | = DesignatedStartIndex.extOrTrunc(width: MaxElements.getBitWidth()); |
3030 | DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned()); |
3031 | DesignatedEndIndex |
3032 | = DesignatedEndIndex.extOrTrunc(width: MaxElements.getBitWidth()); |
3033 | DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned()); |
3034 | if (DesignatedEndIndex >= MaxElements) { |
3035 | if (!VerifyOnly) |
3036 | SemaRef.Diag(IndexExpr->getBeginLoc(), |
3037 | diag::err_array_designator_too_large) |
3038 | << toString(DesignatedEndIndex, 10) << toString(MaxElements, 10) |
3039 | << IndexExpr->getSourceRange(); |
3040 | ++Index; |
3041 | return true; |
3042 | } |
3043 | } else { |
3044 | unsigned DesignatedIndexBitWidth = |
3045 | ConstantArrayType::getMaxSizeBits(Context: SemaRef.Context); |
3046 | DesignatedStartIndex = |
3047 | DesignatedStartIndex.extOrTrunc(width: DesignatedIndexBitWidth); |
3048 | DesignatedEndIndex = |
3049 | DesignatedEndIndex.extOrTrunc(width: DesignatedIndexBitWidth); |
3050 | DesignatedStartIndex.setIsUnsigned(true); |
3051 | DesignatedEndIndex.setIsUnsigned(true); |
3052 | } |
3053 | |
3054 | bool IsStringLiteralInitUpdate = |
3055 | StructuredList && StructuredList->isStringLiteralInit(); |
3056 | if (IsStringLiteralInitUpdate && VerifyOnly) { |
3057 | // We're just verifying an update to a string literal init. We don't need |
3058 | // to split the string up into individual characters to do that. |
3059 | StructuredList = nullptr; |
3060 | } else if (IsStringLiteralInitUpdate) { |
3061 | // We're modifying a string literal init; we have to decompose the string |
3062 | // so we can modify the individual characters. |
3063 | ASTContext &Context = SemaRef.Context; |
3064 | Expr *SubExpr = StructuredList->getInit(Init: 0)->IgnoreParenImpCasts(); |
3065 | |
3066 | // Compute the character type |
3067 | QualType CharTy = AT->getElementType(); |
3068 | |
3069 | // Compute the type of the integer literals. |
3070 | QualType PromotedCharTy = CharTy; |
3071 | if (Context.isPromotableIntegerType(T: CharTy)) |
3072 | PromotedCharTy = Context.getPromotedIntegerType(PromotableType: CharTy); |
3073 | unsigned PromotedCharTyWidth = Context.getTypeSize(T: PromotedCharTy); |
3074 | |
3075 | if (StringLiteral *SL = dyn_cast<StringLiteral>(Val: SubExpr)) { |
3076 | // Get the length of the string. |
3077 | uint64_t StrLen = SL->getLength(); |
3078 | if (cast<ConstantArrayType>(Val: AT)->getSize().ult(RHS: StrLen)) |
3079 | StrLen = cast<ConstantArrayType>(Val: AT)->getSize().getZExtValue(); |
3080 | StructuredList->resizeInits(Context, NumInits: StrLen); |
3081 | |
3082 | // Build a literal for each character in the string, and put them into |
3083 | // the init list. |
3084 | for (unsigned i = 0, e = StrLen; i != e; ++i) { |
3085 | llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i)); |
3086 | Expr *Init = new (Context) IntegerLiteral( |
3087 | Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc()); |
3088 | if (CharTy != PromotedCharTy) |
3089 | Init = ImplicitCastExpr::Create(Context, T: CharTy, Kind: CK_IntegralCast, |
3090 | Operand: Init, BasePath: nullptr, Cat: VK_PRValue, |
3091 | FPO: FPOptionsOverride()); |
3092 | StructuredList->updateInit(C: Context, Init: i, expr: Init); |
3093 | } |
3094 | } else { |
3095 | ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(Val: SubExpr); |
3096 | std::string Str; |
3097 | Context.getObjCEncodingForType(T: E->getEncodedType(), S&: Str); |
3098 | |
3099 | // Get the length of the string. |
3100 | uint64_t StrLen = Str.size(); |
3101 | if (cast<ConstantArrayType>(Val: AT)->getSize().ult(RHS: StrLen)) |
3102 | StrLen = cast<ConstantArrayType>(Val: AT)->getSize().getZExtValue(); |
3103 | StructuredList->resizeInits(Context, NumInits: StrLen); |
3104 | |
3105 | // Build a literal for each character in the string, and put them into |
3106 | // the init list. |
3107 | for (unsigned i = 0, e = StrLen; i != e; ++i) { |
3108 | llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]); |
3109 | Expr *Init = new (Context) IntegerLiteral( |
3110 | Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc()); |
3111 | if (CharTy != PromotedCharTy) |
3112 | Init = ImplicitCastExpr::Create(Context, T: CharTy, Kind: CK_IntegralCast, |
3113 | Operand: Init, BasePath: nullptr, Cat: VK_PRValue, |
3114 | FPO: FPOptionsOverride()); |
3115 | StructuredList->updateInit(C: Context, Init: i, expr: Init); |
3116 | } |
3117 | } |
3118 | } |
3119 | |
3120 | // Make sure that our non-designated initializer list has space |
3121 | // for a subobject corresponding to this array element. |
3122 | if (StructuredList && |
3123 | DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits()) |
3124 | StructuredList->resizeInits(Context: SemaRef.Context, |
3125 | NumInits: DesignatedEndIndex.getZExtValue() + 1); |
3126 | |
3127 | // Repeatedly perform subobject initializations in the range |
3128 | // [DesignatedStartIndex, DesignatedEndIndex]. |
3129 | |
3130 | // Move to the next designator |
3131 | unsigned ElementIndex = DesignatedStartIndex.getZExtValue(); |
3132 | unsigned OldIndex = Index; |
3133 | |
3134 | InitializedEntity ElementEntity = |
3135 | InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity); |
3136 | |
3137 | while (DesignatedStartIndex <= DesignatedEndIndex) { |
3138 | // Recurse to check later designated subobjects. |
3139 | QualType ElementType = AT->getElementType(); |
3140 | Index = OldIndex; |
3141 | |
3142 | ElementEntity.setElementIndex(ElementIndex); |
3143 | if (CheckDesignatedInitializer( |
3144 | Entity: ElementEntity, IList, DIE, DesigIdx: DesigIdx + 1, CurrentObjectType&: ElementType, NextField: nullptr, |
3145 | NextElementIndex: nullptr, Index, StructuredList, StructuredIndex&: ElementIndex, |
3146 | FinishSubobjectInit: FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex), |
3147 | TopLevelObject: false)) |
3148 | return true; |
3149 | |
3150 | // Move to the next index in the array that we'll be initializing. |
3151 | ++DesignatedStartIndex; |
3152 | ElementIndex = DesignatedStartIndex.getZExtValue(); |
3153 | } |
3154 | |
3155 | // If this the first designator, our caller will continue checking |
3156 | // the rest of this array subobject. |
3157 | if (IsFirstDesignator) { |
3158 | if (NextElementIndex) |
3159 | *NextElementIndex = DesignatedStartIndex; |
3160 | StructuredIndex = ElementIndex; |
3161 | return false; |
3162 | } |
3163 | |
3164 | if (!FinishSubobjectInit) |
3165 | return false; |
3166 | |
3167 | // Check the remaining elements within this array subobject. |
3168 | bool prevHadError = hadError; |
3169 | CheckArrayType(Entity, IList, DeclType&: CurrentObjectType, elementIndex: DesignatedStartIndex, |
3170 | /*SubobjectIsDesignatorContext=*/false, Index, |
3171 | StructuredList, StructuredIndex&: ElementIndex); |
3172 | return hadError && !prevHadError; |
3173 | } |
3174 | |
3175 | // Get the structured initializer list for a subobject of type |
3176 | // @p CurrentObjectType. |
3177 | InitListExpr * |
3178 | InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, |
3179 | QualType CurrentObjectType, |
3180 | InitListExpr *StructuredList, |
3181 | unsigned StructuredIndex, |
3182 | SourceRange InitRange, |
3183 | bool IsFullyOverwritten) { |
3184 | if (!StructuredList) |
3185 | return nullptr; |
3186 | |
3187 | Expr *ExistingInit = nullptr; |
3188 | if (StructuredIndex < StructuredList->getNumInits()) |
3189 | ExistingInit = StructuredList->getInit(Init: StructuredIndex); |
3190 | |
3191 | if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(Val: ExistingInit)) |
3192 | // There might have already been initializers for subobjects of the current |
3193 | // object, but a subsequent initializer list will overwrite the entirety |
3194 | // of the current object. (See DR 253 and C99 6.7.8p21). e.g., |
3195 | // |
3196 | // struct P { char x[6]; }; |
3197 | // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } }; |
3198 | // |
3199 | // The first designated initializer is ignored, and l.x is just "f". |
3200 | if (!IsFullyOverwritten) |
3201 | return Result; |
3202 | |
3203 | if (ExistingInit) { |
3204 | // We are creating an initializer list that initializes the |
3205 | // subobjects of the current object, but there was already an |
3206 | // initialization that completely initialized the current |
3207 | // subobject: |
3208 | // |
3209 | // struct X { int a, b; }; |
3210 | // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 }; |
3211 | // |
3212 | // Here, xs[0].a == 1 and xs[0].b == 3, since the second, |
3213 | // designated initializer overwrites the [0].b initializer |
3214 | // from the prior initialization. |
3215 | // |
3216 | // When the existing initializer is an expression rather than an |
3217 | // initializer list, we cannot decompose and update it in this way. |
3218 | // For example: |
3219 | // |
3220 | // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 }; |
3221 | // |
3222 | // This case is handled by CheckDesignatedInitializer. |
3223 | diagnoseInitOverride(OldInit: ExistingInit, NewInitRange: InitRange); |
3224 | } |
3225 | |
3226 | unsigned ExpectedNumInits = 0; |
3227 | if (Index < IList->getNumInits()) { |
3228 | if (auto *Init = dyn_cast_or_null<InitListExpr>(Val: IList->getInit(Init: Index))) |
3229 | ExpectedNumInits = Init->getNumInits(); |
3230 | else |
3231 | ExpectedNumInits = IList->getNumInits() - Index; |
3232 | } |
3233 | |
3234 | InitListExpr *Result = |
3235 | createInitListExpr(CurrentObjectType, InitRange, ExpectedNumInits); |
3236 | |
3237 | // Link this new initializer list into the structured initializer |
3238 | // lists. |
3239 | StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result); |
3240 | return Result; |
3241 | } |
3242 | |
3243 | InitListExpr * |
3244 | InitListChecker::createInitListExpr(QualType CurrentObjectType, |
3245 | SourceRange InitRange, |
3246 | unsigned ExpectedNumInits) { |
3247 | InitListExpr *Result = new (SemaRef.Context) InitListExpr( |
3248 | SemaRef.Context, InitRange.getBegin(), std::nullopt, InitRange.getEnd()); |
3249 | |
3250 | QualType ResultType = CurrentObjectType; |
3251 | if (!ResultType->isArrayType()) |
3252 | ResultType = ResultType.getNonLValueExprType(Context: SemaRef.Context); |
3253 | Result->setType(ResultType); |
3254 | |
3255 | // Pre-allocate storage for the structured initializer list. |
3256 | unsigned NumElements = 0; |
3257 | |
3258 | if (const ArrayType *AType |
3259 | = SemaRef.Context.getAsArrayType(T: CurrentObjectType)) { |
3260 | if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(Val: AType)) { |
3261 | NumElements = CAType->getSize().getZExtValue(); |
3262 | // Simple heuristic so that we don't allocate a very large |
3263 | // initializer with many empty entries at the end. |
3264 | if (NumElements > ExpectedNumInits) |
3265 | NumElements = 0; |
3266 | } |
3267 | } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) { |
3268 | NumElements = VType->getNumElements(); |
3269 | } else if (CurrentObjectType->isRecordType()) { |
3270 | NumElements = numStructUnionElements(DeclType: CurrentObjectType); |
3271 | } else if (CurrentObjectType->isDependentType()) { |
3272 | NumElements = 1; |
3273 | } |
3274 | |
3275 | Result->reserveInits(C: SemaRef.Context, NumInits: NumElements); |
3276 | |
3277 | return Result; |
3278 | } |
3279 | |
3280 | /// Update the initializer at index @p StructuredIndex within the |
3281 | /// structured initializer list to the value @p expr. |
3282 | void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList, |
3283 | unsigned &StructuredIndex, |
3284 | Expr *expr) { |
3285 | // No structured initializer list to update |
3286 | if (!StructuredList) |
3287 | return; |
3288 | |
3289 | if (Expr *PrevInit = StructuredList->updateInit(C: SemaRef.Context, |
3290 | Init: StructuredIndex, expr)) { |
3291 | // This initializer overwrites a previous initializer. |
3292 | // No need to diagnose when `expr` is nullptr because a more relevant |
3293 | // diagnostic has already been issued and this diagnostic is potentially |
3294 | // noise. |
3295 | if (expr) |
3296 | diagnoseInitOverride(OldInit: PrevInit, NewInitRange: expr->getSourceRange()); |
3297 | } |
3298 | |
3299 | ++StructuredIndex; |
3300 | } |
3301 | |
3302 | /// Determine whether we can perform aggregate initialization for the purposes |
3303 | /// of overload resolution. |
3304 | bool Sema::CanPerformAggregateInitializationForOverloadResolution( |
3305 | const InitializedEntity &Entity, InitListExpr *From) { |
3306 | QualType Type = Entity.getType(); |
3307 | InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true, |
3308 | /*TreatUnavailableAsInvalid=*/false, |
3309 | /*InOverloadResolution=*/true); |
3310 | return !Check.HadError(); |
3311 | } |
3312 | |
3313 | /// Check that the given Index expression is a valid array designator |
3314 | /// value. This is essentially just a wrapper around |
3315 | /// VerifyIntegerConstantExpression that also checks for negative values |
3316 | /// and produces a reasonable diagnostic if there is a |
3317 | /// failure. Returns the index expression, possibly with an implicit cast |
3318 | /// added, on success. If everything went okay, Value will receive the |
3319 | /// value of the constant expression. |
3320 | static ExprResult |
3321 | CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) { |
3322 | SourceLocation Loc = Index->getBeginLoc(); |
3323 | |
3324 | // Make sure this is an integer constant expression. |
3325 | ExprResult Result = |
3326 | S.VerifyIntegerConstantExpression(E: Index, Result: &Value, CanFold: Sema::AllowFold); |
3327 | if (Result.isInvalid()) |
3328 | return Result; |
3329 | |
3330 | if (Value.isSigned() && Value.isNegative()) |
3331 | return S.Diag(Loc, diag::err_array_designator_negative) |
3332 | << toString(Value, 10) << Index->getSourceRange(); |
3333 | |
3334 | Value.setIsUnsigned(true); |
3335 | return Result; |
3336 | } |
3337 | |
3338 | ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig, |
3339 | SourceLocation EqualOrColonLoc, |
3340 | bool GNUSyntax, |
3341 | ExprResult Init) { |
3342 | typedef DesignatedInitExpr::Designator ASTDesignator; |
3343 | |
3344 | bool Invalid = false; |
3345 | SmallVector<ASTDesignator, 32> Designators; |
3346 | SmallVector<Expr *, 32> InitExpressions; |
3347 | |
3348 | // Build designators and check array designator expressions. |
3349 | for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) { |
3350 | const Designator &D = Desig.getDesignator(Idx); |
3351 | |
3352 | if (D.isFieldDesignator()) { |
3353 | Designators.push_back(Elt: ASTDesignator::CreateFieldDesignator( |
3354 | FieldName: D.getFieldDecl(), DotLoc: D.getDotLoc(), FieldLoc: D.getFieldLoc())); |
3355 | } else if (D.isArrayDesignator()) { |
3356 | Expr *Index = static_cast<Expr *>(D.getArrayIndex()); |
3357 | llvm::APSInt IndexValue; |
3358 | if (!Index->isTypeDependent() && !Index->isValueDependent()) |
3359 | Index = CheckArrayDesignatorExpr(S&: *this, Index, Value&: IndexValue).get(); |
3360 | if (!Index) |
3361 | Invalid = true; |
3362 | else { |
3363 | Designators.push_back(Elt: ASTDesignator::CreateArrayDesignator( |
3364 | Index: InitExpressions.size(), LBracketLoc: D.getLBracketLoc(), RBracketLoc: D.getRBracketLoc())); |
3365 | InitExpressions.push_back(Elt: Index); |
3366 | } |
3367 | } else if (D.isArrayRangeDesignator()) { |
3368 | Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart()); |
3369 | Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd()); |
3370 | llvm::APSInt StartValue; |
3371 | llvm::APSInt EndValue; |
3372 | bool StartDependent = StartIndex->isTypeDependent() || |
3373 | StartIndex->isValueDependent(); |
3374 | bool EndDependent = EndIndex->isTypeDependent() || |
3375 | EndIndex->isValueDependent(); |
3376 | if (!StartDependent) |
3377 | StartIndex = |
3378 | CheckArrayDesignatorExpr(S&: *this, Index: StartIndex, Value&: StartValue).get(); |
3379 | if (!EndDependent) |
3380 | EndIndex = CheckArrayDesignatorExpr(S&: *this, Index: EndIndex, Value&: EndValue).get(); |
3381 | |
3382 | if (!StartIndex || !EndIndex) |
3383 | Invalid = true; |
3384 | else { |
3385 | // Make sure we're comparing values with the same bit width. |
3386 | if (StartDependent || EndDependent) { |
3387 | // Nothing to compute. |
3388 | } else if (StartValue.getBitWidth() > EndValue.getBitWidth()) |
3389 | EndValue = EndValue.extend(width: StartValue.getBitWidth()); |
3390 | else if (StartValue.getBitWidth() < EndValue.getBitWidth()) |
3391 | StartValue = StartValue.extend(width: EndValue.getBitWidth()); |
3392 | |
3393 | if (!StartDependent && !EndDependent && EndValue < StartValue) { |
3394 | Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range) |
3395 | << toString(StartValue, 10) << toString(EndValue, 10) |
3396 | << StartIndex->getSourceRange() << EndIndex->getSourceRange(); |
3397 | Invalid = true; |
3398 | } else { |
3399 | Designators.push_back(Elt: ASTDesignator::CreateArrayRangeDesignator( |
3400 | Index: InitExpressions.size(), LBracketLoc: D.getLBracketLoc(), EllipsisLoc: D.getEllipsisLoc(), |
3401 | RBracketLoc: D.getRBracketLoc())); |
3402 | InitExpressions.push_back(Elt: StartIndex); |
3403 | InitExpressions.push_back(Elt: EndIndex); |
3404 | } |
3405 | } |
3406 | } |
3407 | } |
3408 | |
3409 | if (Invalid || Init.isInvalid()) |
3410 | return ExprError(); |
3411 | |
3412 | return DesignatedInitExpr::Create(C: Context, Designators, IndexExprs: InitExpressions, |
3413 | EqualOrColonLoc, GNUSyntax, |
3414 | Init: Init.getAs<Expr>()); |
3415 | } |
3416 | |
3417 | //===----------------------------------------------------------------------===// |
3418 | // Initialization entity |
3419 | //===----------------------------------------------------------------------===// |
3420 | |
3421 | InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index, |
3422 | const InitializedEntity &Parent) |
3423 | : Parent(&Parent), Index(Index) |
3424 | { |
3425 | if (const ArrayType *AT = Context.getAsArrayType(T: Parent.getType())) { |
3426 | Kind = EK_ArrayElement; |
3427 | Type = AT->getElementType(); |
3428 | } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) { |
3429 | Kind = EK_VectorElement; |
3430 | Type = VT->getElementType(); |
3431 | } else { |
3432 | const ComplexType *CT = Parent.getType()->getAs<ComplexType>(); |
3433 | assert(CT && "Unexpected type" ); |
3434 | Kind = EK_ComplexElement; |
3435 | Type = CT->getElementType(); |
3436 | } |
3437 | } |
3438 | |
3439 | InitializedEntity |
3440 | InitializedEntity::InitializeBase(ASTContext &Context, |
3441 | const CXXBaseSpecifier *Base, |
3442 | bool IsInheritedVirtualBase, |
3443 | const InitializedEntity *Parent) { |
3444 | InitializedEntity Result; |
3445 | Result.Kind = EK_Base; |
3446 | Result.Parent = Parent; |
3447 | Result.Base = {Base, IsInheritedVirtualBase}; |
3448 | Result.Type = Base->getType(); |
3449 | return Result; |
3450 | } |
3451 | |
3452 | DeclarationName InitializedEntity::getName() const { |
3453 | switch (getKind()) { |
3454 | case EK_Parameter: |
3455 | case EK_Parameter_CF_Audited: { |
3456 | ParmVarDecl *D = Parameter.getPointer(); |
3457 | return (D ? D->getDeclName() : DeclarationName()); |
3458 | } |
3459 | |
3460 | case EK_Variable: |
3461 | case EK_Member: |
3462 | case EK_ParenAggInitMember: |
3463 | case EK_Binding: |
3464 | case EK_TemplateParameter: |
3465 | return Variable.VariableOrMember->getDeclName(); |
3466 | |
3467 | case EK_LambdaCapture: |
3468 | return DeclarationName(Capture.VarID); |
3469 | |
3470 | case EK_Result: |
3471 | case EK_StmtExprResult: |
3472 | case EK_Exception: |
3473 | case EK_New: |
3474 | case EK_Temporary: |
3475 | case EK_Base: |
3476 | case EK_Delegating: |
3477 | case EK_ArrayElement: |
3478 | case EK_VectorElement: |
3479 | case EK_ComplexElement: |
3480 | case EK_BlockElement: |
3481 | case EK_LambdaToBlockConversionBlockElement: |
3482 | case EK_CompoundLiteralInit: |
3483 | case EK_RelatedResult: |
3484 | return DeclarationName(); |
3485 | } |
3486 | |
3487 | llvm_unreachable("Invalid EntityKind!" ); |
3488 | } |
3489 | |
3490 | ValueDecl *InitializedEntity::getDecl() const { |
3491 | switch (getKind()) { |
3492 | case EK_Variable: |
3493 | case EK_Member: |
3494 | case EK_ParenAggInitMember: |
3495 | case EK_Binding: |
3496 | case EK_TemplateParameter: |
3497 | return Variable.VariableOrMember; |
3498 | |
3499 | case EK_Parameter: |
3500 | case EK_Parameter_CF_Audited: |
3501 | return Parameter.getPointer(); |
3502 | |
3503 | case EK_Result: |
3504 | case EK_StmtExprResult: |
3505 | case EK_Exception: |
3506 | case EK_New: |
3507 | case EK_Temporary: |
3508 | case EK_Base: |
3509 | case EK_Delegating: |
3510 | case EK_ArrayElement: |
3511 | case EK_VectorElement: |
3512 | case EK_ComplexElement: |
3513 | case EK_BlockElement: |
3514 | case EK_LambdaToBlockConversionBlockElement: |
3515 | case EK_LambdaCapture: |
3516 | case EK_CompoundLiteralInit: |
3517 | case EK_RelatedResult: |
3518 | return nullptr; |
3519 | } |
3520 | |
3521 | llvm_unreachable("Invalid EntityKind!" ); |
3522 | } |
3523 | |
3524 | bool InitializedEntity::allowsNRVO() const { |
3525 | switch (getKind()) { |
3526 | case EK_Result: |
3527 | case EK_Exception: |
3528 | return LocAndNRVO.NRVO; |
3529 | |
3530 | case EK_StmtExprResult: |
3531 | case EK_Variable: |
3532 | case EK_Parameter: |
3533 | case EK_Parameter_CF_Audited: |
3534 | case EK_TemplateParameter: |
3535 | case EK_Member: |
3536 | case EK_ParenAggInitMember: |
3537 | case EK_Binding: |
3538 | case EK_New: |
3539 | case EK_Temporary: |
3540 | case EK_CompoundLiteralInit: |
3541 | case EK_Base: |
3542 | case EK_Delegating: |
3543 | case EK_ArrayElement: |
3544 | case EK_VectorElement: |
3545 | case EK_ComplexElement: |
3546 | case EK_BlockElement: |
3547 | case EK_LambdaToBlockConversionBlockElement: |
3548 | case EK_LambdaCapture: |
3549 | case EK_RelatedResult: |
3550 | break; |
3551 | } |
3552 | |
3553 | return false; |
3554 | } |
3555 | |
3556 | unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const { |
3557 | assert(getParent() != this); |
3558 | unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0; |
3559 | for (unsigned I = 0; I != Depth; ++I) |
3560 | OS << "`-" ; |
3561 | |
3562 | switch (getKind()) { |
3563 | case EK_Variable: OS << "Variable" ; break; |
3564 | case EK_Parameter: OS << "Parameter" ; break; |
3565 | case EK_Parameter_CF_Audited: OS << "CF audited function Parameter" ; |
3566 | break; |
3567 | case EK_TemplateParameter: OS << "TemplateParameter" ; break; |
3568 | case EK_Result: OS << "Result" ; break; |
3569 | case EK_StmtExprResult: OS << "StmtExprResult" ; break; |
3570 | case EK_Exception: OS << "Exception" ; break; |
3571 | case EK_Member: |
3572 | case EK_ParenAggInitMember: |
3573 | OS << "Member" ; |
3574 | break; |
3575 | case EK_Binding: OS << "Binding" ; break; |
3576 | case EK_New: OS << "New" ; break; |
3577 | case EK_Temporary: OS << "Temporary" ; break; |
3578 | case EK_CompoundLiteralInit: OS << "CompoundLiteral" ;break; |
3579 | case EK_RelatedResult: OS << "RelatedResult" ; break; |
3580 | case EK_Base: OS << "Base" ; break; |
3581 | case EK_Delegating: OS << "Delegating" ; break; |
3582 | case EK_ArrayElement: OS << "ArrayElement " << Index; break; |
3583 | case EK_VectorElement: OS << "VectorElement " << Index; break; |
3584 | case EK_ComplexElement: OS << "ComplexElement " << Index; break; |
3585 | case EK_BlockElement: OS << "Block" ; break; |
3586 | case EK_LambdaToBlockConversionBlockElement: |
3587 | OS << "Block (lambda)" ; |
3588 | break; |
3589 | case EK_LambdaCapture: |
3590 | OS << "LambdaCapture " ; |
3591 | OS << DeclarationName(Capture.VarID); |
3592 | break; |
3593 | } |
3594 | |
3595 | if (auto *D = getDecl()) { |
3596 | OS << " " ; |
3597 | D->printQualifiedName(OS); |
3598 | } |
3599 | |
3600 | OS << " '" << getType() << "'\n" ; |
3601 | |
3602 | return Depth + 1; |
3603 | } |
3604 | |
3605 | LLVM_DUMP_METHOD void InitializedEntity::dump() const { |
3606 | dumpImpl(OS&: llvm::errs()); |
3607 | } |
3608 | |
3609 | //===----------------------------------------------------------------------===// |
3610 | // Initialization sequence |
3611 | //===----------------------------------------------------------------------===// |
3612 | |
3613 | void InitializationSequence::Step::Destroy() { |
3614 | switch (Kind) { |
3615 | case SK_ResolveAddressOfOverloadedFunction: |
3616 | case SK_CastDerivedToBasePRValue: |
3617 | case SK_CastDerivedToBaseXValue: |
3618 | case SK_CastDerivedToBaseLValue: |
3619 | case SK_BindReference: |
3620 | case SK_BindReferenceToTemporary: |
3621 | case SK_FinalCopy: |
3622 | case SK_ExtraneousCopyToTemporary: |
3623 | case SK_UserConversion: |
3624 | case SK_QualificationConversionPRValue: |
3625 | case SK_QualificationConversionXValue: |
3626 | case SK_QualificationConversionLValue: |
3627 | case SK_FunctionReferenceConversion: |
3628 | case SK_AtomicConversion: |
3629 | case SK_ListInitialization: |
3630 | case SK_UnwrapInitList: |
3631 | case SK_RewrapInitList: |
3632 | case SK_ConstructorInitialization: |
3633 | case SK_ConstructorInitializationFromList: |
3634 | case SK_ZeroInitialization: |
3635 | case SK_CAssignment: |
3636 | case SK_StringInit: |
3637 | case SK_ObjCObjectConversion: |
3638 | case SK_ArrayLoopIndex: |
3639 | case SK_ArrayLoopInit: |
3640 | case SK_ArrayInit: |
3641 | case SK_GNUArrayInit: |
3642 | case SK_ParenthesizedArrayInit: |
3643 | case SK_PassByIndirectCopyRestore: |
3644 | case SK_PassByIndirectRestore: |
3645 | case SK_ProduceObjCObject: |
3646 | case SK_StdInitializerList: |
3647 | case SK_StdInitializerListConstructorCall: |
3648 | case SK_OCLSamplerInit: |
3649 | case SK_OCLZeroOpaqueType: |
3650 | case SK_ParenthesizedListInit: |
3651 | break; |
3652 | |
3653 | case SK_ConversionSequence: |
3654 | case SK_ConversionSequenceNoNarrowing: |
3655 | delete ICS; |
3656 | } |
3657 | } |
3658 | |
3659 | bool InitializationSequence::isDirectReferenceBinding() const { |
3660 | // There can be some lvalue adjustments after the SK_BindReference step. |
3661 | for (const Step &S : llvm::reverse(C: Steps)) { |
3662 | if (S.Kind == SK_BindReference) |
3663 | return true; |
3664 | if (S.Kind == SK_BindReferenceToTemporary) |
3665 | return false; |
3666 | } |
3667 | return false; |
3668 | } |
3669 | |
3670 | bool InitializationSequence::isAmbiguous() const { |
3671 | if (!Failed()) |
3672 | return false; |
3673 | |
3674 | switch (getFailureKind()) { |
3675 | case FK_TooManyInitsForReference: |
3676 | case FK_ParenthesizedListInitForReference: |
3677 | case FK_ArrayNeedsInitList: |
3678 | case FK_ArrayNeedsInitListOrStringLiteral: |
3679 | case FK_ArrayNeedsInitListOrWideStringLiteral: |
3680 | case FK_NarrowStringIntoWideCharArray: |
3681 | case FK_WideStringIntoCharArray: |
3682 | case FK_IncompatWideStringIntoWideChar: |
3683 | case FK_PlainStringIntoUTF8Char: |
3684 | case FK_UTF8StringIntoPlainChar: |
3685 | case FK_AddressOfOverloadFailed: // FIXME: Could do better |
3686 | case FK_NonConstLValueReferenceBindingToTemporary: |
3687 | case FK_NonConstLValueReferenceBindingToBitfield: |
3688 | case FK_NonConstLValueReferenceBindingToVectorElement: |
3689 | case FK_NonConstLValueReferenceBindingToMatrixElement: |
3690 | case FK_NonConstLValueReferenceBindingToUnrelated: |
3691 | case FK_RValueReferenceBindingToLValue: |
3692 | case FK_ReferenceAddrspaceMismatchTemporary: |
3693 | case FK_ReferenceInitDropsQualifiers: |
3694 | case FK_ReferenceInitFailed: |
3695 | case FK_ConversionFailed: |
3696 | case FK_ConversionFromPropertyFailed: |
3697 | case FK_TooManyInitsForScalar: |
3698 | case FK_ParenthesizedListInitForScalar: |
3699 | case FK_ReferenceBindingToInitList: |
3700 | case FK_InitListBadDestinationType: |
3701 | case FK_DefaultInitOfConst: |
3702 | case FK_Incomplete: |
3703 | case FK_ArrayTypeMismatch: |
3704 | case FK_NonConstantArrayInit: |
3705 | case FK_ListInitializationFailed: |
3706 | case FK_VariableLengthArrayHasInitializer: |
3707 | case FK_PlaceholderType: |
3708 | case FK_ExplicitConstructor: |
3709 | case FK_AddressOfUnaddressableFunction: |
3710 | case FK_ParenthesizedListInitFailed: |
3711 | case FK_DesignatedInitForNonAggregate: |
3712 | return false; |
3713 | |
3714 | case FK_ReferenceInitOverloadFailed: |
3715 | case FK_UserConversionOverloadFailed: |
3716 | case FK_ConstructorOverloadFailed: |
3717 | case FK_ListConstructorOverloadFailed: |
3718 | return FailedOverloadResult == OR_Ambiguous; |
3719 | } |
3720 | |
3721 | llvm_unreachable("Invalid EntityKind!" ); |
3722 | } |
3723 | |
3724 | bool InitializationSequence::isConstructorInitialization() const { |
3725 | return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization; |
3726 | } |
3727 | |
3728 | void |
3729 | InitializationSequence |
3730 | ::AddAddressOverloadResolutionStep(FunctionDecl *Function, |
3731 | DeclAccessPair Found, |
3732 | bool HadMultipleCandidates) { |
3733 | Step S; |
3734 | S.Kind = SK_ResolveAddressOfOverloadedFunction; |
3735 | S.Type = Function->getType(); |
3736 | S.Function.HadMultipleCandidates = HadMultipleCandidates; |
3737 | S.Function.Function = Function; |
3738 | S.Function.FoundDecl = Found; |
3739 | Steps.push_back(Elt: S); |
3740 | } |
3741 | |
3742 | void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType, |
3743 | ExprValueKind VK) { |
3744 | Step S; |
3745 | switch (VK) { |
3746 | case VK_PRValue: |
3747 | S.Kind = SK_CastDerivedToBasePRValue; |
3748 | break; |
3749 | case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break; |
3750 | case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break; |
3751 | } |
3752 | S.Type = BaseType; |
3753 | Steps.push_back(Elt: S); |
3754 | } |
3755 | |
3756 | void InitializationSequence::AddReferenceBindingStep(QualType T, |
3757 | bool BindingTemporary) { |
3758 | Step S; |
3759 | S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference; |
3760 | S.Type = T; |
3761 | Steps.push_back(Elt: S); |
3762 | } |
3763 | |
3764 | void InitializationSequence::AddFinalCopy(QualType T) { |
3765 | Step S; |
3766 | S.Kind = SK_FinalCopy; |
3767 | S.Type = T; |
3768 | Steps.push_back(Elt: S); |
3769 | } |
3770 | |
3771 | void InitializationSequence::(QualType T) { |
3772 | Step S; |
3773 | S.Kind = SK_ExtraneousCopyToTemporary; |
3774 | S.Type = T; |
3775 | Steps.push_back(Elt: S); |
3776 | } |
3777 | |
3778 | void |
3779 | InitializationSequence::AddUserConversionStep(FunctionDecl *Function, |
3780 | DeclAccessPair FoundDecl, |
3781 | QualType T, |
3782 | bool HadMultipleCandidates) { |
3783 | Step S; |
3784 | S.Kind = SK_UserConversion; |
3785 | S.Type = T; |
3786 | S.Function.HadMultipleCandidates = HadMultipleCandidates; |
3787 | S.Function.Function = Function; |
3788 | S.Function.FoundDecl = FoundDecl; |
3789 | Steps.push_back(Elt: S); |
3790 | } |
3791 | |
3792 | void InitializationSequence::AddQualificationConversionStep(QualType Ty, |
3793 | ExprValueKind VK) { |
3794 | Step S; |
3795 | S.Kind = SK_QualificationConversionPRValue; // work around a gcc warning |
3796 | switch (VK) { |
3797 | case VK_PRValue: |
3798 | S.Kind = SK_QualificationConversionPRValue; |
3799 | break; |
3800 | case VK_XValue: |
3801 | S.Kind = SK_QualificationConversionXValue; |
3802 | break; |
3803 | case VK_LValue: |
3804 | S.Kind = SK_QualificationConversionLValue; |
3805 | break; |
3806 | } |
3807 | S.Type = Ty; |
3808 | Steps.push_back(Elt: S); |
3809 | } |
3810 | |
3811 | void InitializationSequence::AddFunctionReferenceConversionStep(QualType Ty) { |
3812 | Step S; |
3813 | S.Kind = SK_FunctionReferenceConversion; |
3814 | S.Type = Ty; |
3815 | Steps.push_back(Elt: S); |
3816 | } |
3817 | |
3818 | void InitializationSequence::AddAtomicConversionStep(QualType Ty) { |
3819 | Step S; |
3820 | S.Kind = SK_AtomicConversion; |
3821 | S.Type = Ty; |
3822 | Steps.push_back(Elt: S); |
3823 | } |
3824 | |
3825 | void InitializationSequence::AddConversionSequenceStep( |
3826 | const ImplicitConversionSequence &ICS, QualType T, |
3827 | bool TopLevelOfInitList) { |
3828 | Step S; |
3829 | S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing |
3830 | : SK_ConversionSequence; |
3831 | S.Type = T; |
3832 | S.ICS = new ImplicitConversionSequence(ICS); |
3833 | Steps.push_back(Elt: S); |
3834 | } |
3835 | |
3836 | void InitializationSequence::AddListInitializationStep(QualType T) { |
3837 | Step S; |
3838 | S.Kind = SK_ListInitialization; |
3839 | S.Type = T; |
3840 | Steps.push_back(Elt: S); |
3841 | } |
3842 | |
3843 | void InitializationSequence::AddConstructorInitializationStep( |
3844 | DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T, |
3845 | bool HadMultipleCandidates, bool FromInitList, bool AsInitList) { |
3846 | Step S; |
3847 | S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall |
3848 | : SK_ConstructorInitializationFromList |
3849 | : SK_ConstructorInitialization; |
3850 | S.Type = T; |
3851 | S.Function.HadMultipleCandidates = HadMultipleCandidates; |
3852 | S.Function.Function = Constructor; |
3853 | S.Function.FoundDecl = FoundDecl; |
3854 | Steps.push_back(Elt: S); |
3855 | } |
3856 | |
3857 | void InitializationSequence::AddZeroInitializationStep(QualType T) { |
3858 | Step S; |
3859 | S.Kind = SK_ZeroInitialization; |
3860 | S.Type = T; |
3861 | Steps.push_back(Elt: S); |
3862 | } |
3863 | |
3864 | void InitializationSequence::AddCAssignmentStep(QualType T) { |
3865 | Step S; |
3866 | S.Kind = SK_CAssignment; |
3867 | S.Type = T; |
3868 | Steps.push_back(Elt: S); |
3869 | } |
3870 | |
3871 | void InitializationSequence::AddStringInitStep(QualType T) { |
3872 | Step S; |
3873 | S.Kind = SK_StringInit; |
3874 | S.Type = T; |
3875 | Steps.push_back(Elt: S); |
3876 | } |
3877 | |
3878 | void InitializationSequence::AddObjCObjectConversionStep(QualType T) { |
3879 | Step S; |
3880 | S.Kind = SK_ObjCObjectConversion; |
3881 | S.Type = T; |
3882 | Steps.push_back(Elt: S); |
3883 | } |
3884 | |
3885 | void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) { |
3886 | Step S; |
3887 | S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit; |
3888 | S.Type = T; |
3889 | Steps.push_back(Elt: S); |
3890 | } |
3891 | |
3892 | void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) { |
3893 | Step S; |
3894 | S.Kind = SK_ArrayLoopIndex; |
3895 | S.Type = EltT; |
3896 | Steps.insert(I: Steps.begin(), Elt: S); |
3897 | |
3898 | S.Kind = SK_ArrayLoopInit; |
3899 | S.Type = T; |
3900 | Steps.push_back(Elt: S); |
3901 | } |
3902 | |
3903 | void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) { |
3904 | Step S; |
3905 | S.Kind = SK_ParenthesizedArrayInit; |
3906 | S.Type = T; |
3907 | Steps.push_back(Elt: S); |
3908 | } |
3909 | |
3910 | void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type, |
3911 | bool shouldCopy) { |
3912 | Step s; |
3913 | s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore |
3914 | : SK_PassByIndirectRestore); |
3915 | s.Type = type; |
3916 | Steps.push_back(Elt: s); |
3917 | } |
3918 | |
3919 | void InitializationSequence::AddProduceObjCObjectStep(QualType T) { |
3920 | Step S; |
3921 | S.Kind = SK_ProduceObjCObject; |
3922 | S.Type = T; |
3923 | Steps.push_back(Elt: S); |
3924 | } |
3925 | |
3926 | void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) { |
3927 | Step S; |
3928 | S.Kind = SK_StdInitializerList; |
3929 | S.Type = T; |
3930 | Steps.push_back(Elt: S); |
3931 | } |
3932 | |
3933 | void InitializationSequence::AddOCLSamplerInitStep(QualType T) { |
3934 | Step S; |
3935 | S.Kind = SK_OCLSamplerInit; |
3936 | S.Type = T; |
3937 | Steps.push_back(Elt: S); |
3938 | } |
3939 | |
3940 | void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T) { |
3941 | Step S; |
3942 | S.Kind = SK_OCLZeroOpaqueType; |
3943 | S.Type = T; |
3944 | Steps.push_back(Elt: S); |
3945 | } |
3946 | |
3947 | void InitializationSequence::AddParenthesizedListInitStep(QualType T) { |
3948 | Step S; |
3949 | S.Kind = SK_ParenthesizedListInit; |
3950 | S.Type = T; |
3951 | Steps.push_back(Elt: S); |
3952 | } |
3953 | |
3954 | void InitializationSequence::RewrapReferenceInitList(QualType T, |
3955 | InitListExpr *Syntactic) { |
3956 | assert(Syntactic->getNumInits() == 1 && |
3957 | "Can only rewrap trivial init lists." ); |
3958 | Step S; |
3959 | S.Kind = SK_UnwrapInitList; |
3960 | S.Type = Syntactic->getInit(Init: 0)->getType(); |
3961 | Steps.insert(I: Steps.begin(), Elt: S); |
3962 | |
3963 | S.Kind = SK_RewrapInitList; |
3964 | S.Type = T; |
3965 | S.WrappingSyntacticList = Syntactic; |
3966 | Steps.push_back(Elt: S); |
3967 | } |
3968 | |
3969 | void InitializationSequence::SetOverloadFailure(FailureKind Failure, |
3970 | OverloadingResult Result) { |
3971 | setSequenceKind(FailedSequence); |
3972 | this->Failure = Failure; |
3973 | this->FailedOverloadResult = Result; |
3974 | } |
3975 | |
3976 | //===----------------------------------------------------------------------===// |
3977 | // Attempt initialization |
3978 | //===----------------------------------------------------------------------===// |
3979 | |
3980 | /// Tries to add a zero initializer. Returns true if that worked. |
3981 | static bool |
3982 | maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence, |
3983 | const InitializedEntity &Entity) { |
3984 | if (Entity.getKind() != InitializedEntity::EK_Variable) |
3985 | return false; |
3986 | |
3987 | VarDecl *VD = cast<VarDecl>(Val: Entity.getDecl()); |
3988 | if (VD->getInit() || VD->getEndLoc().isMacroID()) |
3989 | return false; |
3990 | |
3991 | QualType VariableTy = VD->getType().getCanonicalType(); |
3992 | SourceLocation Loc = S.getLocForEndOfToken(Loc: VD->getEndLoc()); |
3993 | std::string Init = S.getFixItZeroInitializerForType(T: VariableTy, Loc); |
3994 | if (!Init.empty()) { |
3995 | Sequence.AddZeroInitializationStep(T: Entity.getType()); |
3996 | Sequence.SetZeroInitializationFixit(Fixit: Init, L: Loc); |
3997 | return true; |
3998 | } |
3999 | return false; |
4000 | } |
4001 | |
4002 | static void MaybeProduceObjCObject(Sema &S, |
4003 | InitializationSequence &Sequence, |
4004 | const InitializedEntity &Entity) { |
4005 | if (!S.getLangOpts().ObjCAutoRefCount) return; |
4006 | |
4007 | /// When initializing a parameter, produce the value if it's marked |
4008 | /// __attribute__((ns_consumed)). |
4009 | if (Entity.isParameterKind()) { |
4010 | if (!Entity.isParameterConsumed()) |
4011 | return; |
4012 | |
4013 | assert(Entity.getType()->isObjCRetainableType() && |
4014 | "consuming an object of unretainable type?" ); |
4015 | Sequence.AddProduceObjCObjectStep(T: Entity.getType()); |
4016 | |
4017 | /// When initializing a return value, if the return type is a |
4018 | /// retainable type, then returns need to immediately retain the |
4019 | /// object. If an autorelease is required, it will be done at the |
4020 | /// last instant. |
4021 | } else if (Entity.getKind() == InitializedEntity::EK_Result || |
4022 | Entity.getKind() == InitializedEntity::EK_StmtExprResult) { |
4023 | if (!Entity.getType()->isObjCRetainableType()) |
4024 | return; |
4025 | |
4026 | Sequence.AddProduceObjCObjectStep(T: Entity.getType()); |
4027 | } |
4028 | } |
4029 | |
4030 | static void TryListInitialization(Sema &S, |
4031 | const InitializedEntity &Entity, |
4032 | const InitializationKind &Kind, |
4033 | InitListExpr *InitList, |
4034 | InitializationSequence &Sequence, |
4035 | bool TreatUnavailableAsInvalid); |
4036 | |
4037 | /// When initializing from init list via constructor, handle |
4038 | /// initialization of an object of type std::initializer_list<T>. |
4039 | /// |
4040 | /// \return true if we have handled initialization of an object of type |
4041 | /// std::initializer_list<T>, false otherwise. |
4042 | static bool TryInitializerListConstruction(Sema &S, |
4043 | InitListExpr *List, |
4044 | QualType DestType, |
4045 | InitializationSequence &Sequence, |
4046 | bool TreatUnavailableAsInvalid) { |
4047 | QualType E; |
4048 | if (!S.isStdInitializerList(Ty: DestType, Element: &E)) |
4049 | return false; |
4050 | |
4051 | if (!S.isCompleteType(Loc: List->getExprLoc(), T: E)) { |
4052 | Sequence.setIncompleteTypeFailure(E); |
4053 | return true; |
4054 | } |
4055 | |
4056 | // Try initializing a temporary array from the init list. |
4057 | QualType ArrayType = S.Context.getConstantArrayType( |
4058 | EltTy: E.withConst(), |
4059 | ArySize: llvm::APInt(S.Context.getTypeSize(T: S.Context.getSizeType()), |
4060 | List->getNumInits()), |
4061 | SizeExpr: nullptr, ASM: clang::ArraySizeModifier::Normal, IndexTypeQuals: 0); |
4062 | InitializedEntity HiddenArray = |
4063 | InitializedEntity::InitializeTemporary(Type: ArrayType); |
4064 | InitializationKind Kind = InitializationKind::CreateDirectList( |
4065 | List->getExprLoc(), List->getBeginLoc(), List->getEndLoc()); |
4066 | TryListInitialization(S, Entity: HiddenArray, Kind, InitList: List, Sequence, |
4067 | TreatUnavailableAsInvalid); |
4068 | if (Sequence) |
4069 | Sequence.AddStdInitializerListConstructionStep(T: DestType); |
4070 | return true; |
4071 | } |
4072 | |
4073 | /// Determine if the constructor has the signature of a copy or move |
4074 | /// constructor for the type T of the class in which it was found. That is, |
4075 | /// determine if its first parameter is of type T or reference to (possibly |
4076 | /// cv-qualified) T. |
4077 | static bool hasCopyOrMoveCtorParam(ASTContext &Ctx, |
4078 | const ConstructorInfo &Info) { |
4079 | if (Info.Constructor->getNumParams() == 0) |
4080 | return false; |
4081 | |
4082 | QualType ParmT = |
4083 | Info.Constructor->getParamDecl(0)->getType().getNonReferenceType(); |
4084 | QualType ClassT = |
4085 | Ctx.getRecordType(Decl: cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext())); |
4086 | |
4087 | return Ctx.hasSameUnqualifiedType(T1: ParmT, T2: ClassT); |
4088 | } |
4089 | |
4090 | static OverloadingResult ResolveConstructorOverload( |
4091 | Sema &S, SourceLocation DeclLoc, MultiExprArg Args, |
4092 | OverloadCandidateSet &CandidateSet, QualType DestType, |
4093 | DeclContext::lookup_result Ctors, OverloadCandidateSet::iterator &Best, |
4094 | bool CopyInitializing, bool AllowExplicit, bool OnlyListConstructors, |
4095 | bool IsListInit, bool RequireActualConstructor, |
4096 | bool SecondStepOfCopyInit = false) { |
4097 | CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByConstructor); |
4098 | CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace()); |
4099 | |
4100 | for (NamedDecl *D : Ctors) { |
4101 | auto Info = getConstructorInfo(ND: D); |
4102 | if (!Info.Constructor || Info.Constructor->isInvalidDecl()) |
4103 | continue; |
4104 | |
4105 | if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor)) |
4106 | continue; |
4107 | |
4108 | // C++11 [over.best.ics]p4: |
4109 | // ... and the constructor or user-defined conversion function is a |
4110 | // candidate by |
4111 | // - 13.3.1.3, when the argument is the temporary in the second step |
4112 | // of a class copy-initialization, or |
4113 | // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here] |
4114 | // - the second phase of 13.3.1.7 when the initializer list has exactly |
4115 | // one element that is itself an initializer list, and the target is |
4116 | // the first parameter of a constructor of class X, and the conversion |
4117 | // is to X or reference to (possibly cv-qualified X), |
4118 | // user-defined conversion sequences are not considered. |
4119 | bool SuppressUserConversions = |
4120 | SecondStepOfCopyInit || |
4121 | (IsListInit && Args.size() == 1 && isa<InitListExpr>(Val: Args[0]) && |
4122 | hasCopyOrMoveCtorParam(Ctx&: S.Context, Info)); |
4123 | |
4124 | if (Info.ConstructorTmpl) |
4125 | S.AddTemplateOverloadCandidate( |
4126 | FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl, |
4127 | /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args, CandidateSet, SuppressUserConversions, |
4128 | /*PartialOverloading=*/false, AllowExplicit); |
4129 | else { |
4130 | // C++ [over.match.copy]p1: |
4131 | // - When initializing a temporary to be bound to the first parameter |
4132 | // of a constructor [for type T] that takes a reference to possibly |
4133 | // cv-qualified T as its first argument, called with a single |
4134 | // argument in the context of direct-initialization, explicit |
4135 | // conversion functions are also considered. |
4136 | // FIXME: What if a constructor template instantiates to such a signature? |
4137 | bool AllowExplicitConv = AllowExplicit && !CopyInitializing && |
4138 | Args.size() == 1 && |
4139 | hasCopyOrMoveCtorParam(Ctx&: S.Context, Info); |
4140 | S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args, |
4141 | CandidateSet, SuppressUserConversions, |
4142 | /*PartialOverloading=*/false, AllowExplicit, |
4143 | AllowExplicitConv); |
4144 | } |
4145 | } |
4146 | |
4147 | // FIXME: Work around a bug in C++17 guaranteed copy elision. |
4148 | // |
4149 | // When initializing an object of class type T by constructor |
4150 | // ([over.match.ctor]) or by list-initialization ([over.match.list]) |
4151 | // from a single expression of class type U, conversion functions of |
4152 | // U that convert to the non-reference type cv T are candidates. |
4153 | // Explicit conversion functions are only candidates during |
4154 | // direct-initialization. |
4155 | // |
4156 | // Note: SecondStepOfCopyInit is only ever true in this case when |
4157 | // evaluating whether to produce a C++98 compatibility warning. |
4158 | if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 && |
4159 | !RequireActualConstructor && !SecondStepOfCopyInit) { |
4160 | Expr *Initializer = Args[0]; |
4161 | auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl(); |
4162 | if (SourceRD && S.isCompleteType(Loc: DeclLoc, T: Initializer->getType())) { |
4163 | const auto &Conversions = SourceRD->getVisibleConversionFunctions(); |
4164 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { |
4165 | NamedDecl *D = *I; |
4166 | CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); |
4167 | D = D->getUnderlyingDecl(); |
4168 | |
4169 | FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D); |
4170 | CXXConversionDecl *Conv; |
4171 | if (ConvTemplate) |
4172 | Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl()); |
4173 | else |
4174 | Conv = cast<CXXConversionDecl>(Val: D); |
4175 | |
4176 | if (ConvTemplate) |
4177 | S.AddTemplateConversionCandidate( |
4178 | FunctionTemplate: ConvTemplate, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer, ToType: DestType, |
4179 | CandidateSet, AllowObjCConversionOnExplicit: AllowExplicit, AllowExplicit, |
4180 | /*AllowResultConversion*/ false); |
4181 | else |
4182 | S.AddConversionCandidate(Conversion: Conv, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer, |
4183 | ToType: DestType, CandidateSet, AllowObjCConversionOnExplicit: AllowExplicit, |
4184 | AllowExplicit, |
4185 | /*AllowResultConversion*/ false); |
4186 | } |
4187 | } |
4188 | } |
4189 | |
4190 | // Perform overload resolution and return the result. |
4191 | return CandidateSet.BestViableFunction(S, Loc: DeclLoc, Best); |
4192 | } |
4193 | |
4194 | /// Attempt initialization by constructor (C++ [dcl.init]), which |
4195 | /// enumerates the constructors of the initialized entity and performs overload |
4196 | /// resolution to select the best. |
4197 | /// \param DestType The destination class type. |
4198 | /// \param DestArrayType The destination type, which is either DestType or |
4199 | /// a (possibly multidimensional) array of DestType. |
4200 | /// \param IsListInit Is this list-initialization? |
4201 | /// \param IsInitListCopy Is this non-list-initialization resulting from a |
4202 | /// list-initialization from {x} where x is the same |
4203 | /// type as the entity? |
4204 | static void TryConstructorInitialization(Sema &S, |
4205 | const InitializedEntity &Entity, |
4206 | const InitializationKind &Kind, |
4207 | MultiExprArg Args, QualType DestType, |
4208 | QualType DestArrayType, |
4209 | InitializationSequence &Sequence, |
4210 | bool IsListInit = false, |
4211 | bool IsInitListCopy = false) { |
4212 | assert(((!IsListInit && !IsInitListCopy) || |
4213 | (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && |
4214 | "IsListInit/IsInitListCopy must come with a single initializer list " |
4215 | "argument." ); |
4216 | InitListExpr *ILE = |
4217 | (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Val: Args[0]) : nullptr; |
4218 | MultiExprArg UnwrappedArgs = |
4219 | ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args; |
4220 | |
4221 | // The type we're constructing needs to be complete. |
4222 | if (!S.isCompleteType(Loc: Kind.getLocation(), T: DestType)) { |
4223 | Sequence.setIncompleteTypeFailure(DestType); |
4224 | return; |
4225 | } |
4226 | |
4227 | bool RequireActualConstructor = |
4228 | !(Entity.getKind() != InitializedEntity::EK_Base && |
4229 | Entity.getKind() != InitializedEntity::EK_Delegating && |
4230 | Entity.getKind() != |
4231 | InitializedEntity::EK_LambdaToBlockConversionBlockElement); |
4232 | |
4233 | // C++17 [dcl.init]p17: |
4234 | // - If the initializer expression is a prvalue and the cv-unqualified |
4235 | // version of the source type is the same class as the class of the |
4236 | // destination, the initializer expression is used to initialize the |
4237 | // destination object. |
4238 | // Per DR (no number yet), this does not apply when initializing a base |
4239 | // class or delegating to another constructor from a mem-initializer. |
4240 | // ObjC++: Lambda captured by the block in the lambda to block conversion |
4241 | // should avoid copy elision. |
4242 | if (S.getLangOpts().CPlusPlus17 && !RequireActualConstructor && |
4243 | UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() && |
4244 | S.Context.hasSameUnqualifiedType(T1: UnwrappedArgs[0]->getType(), T2: DestType)) { |
4245 | // Convert qualifications if necessary. |
4246 | Sequence.AddQualificationConversionStep(Ty: DestType, VK: VK_PRValue); |
4247 | if (ILE) |
4248 | Sequence.RewrapReferenceInitList(T: DestType, Syntactic: ILE); |
4249 | return; |
4250 | } |
4251 | |
4252 | const RecordType *DestRecordType = DestType->getAs<RecordType>(); |
4253 | assert(DestRecordType && "Constructor initialization requires record type" ); |
4254 | CXXRecordDecl *DestRecordDecl |
4255 | = cast<CXXRecordDecl>(Val: DestRecordType->getDecl()); |
4256 | |
4257 | // Build the candidate set directly in the initialization sequence |
4258 | // structure, so that it will persist if we fail. |
4259 | OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); |
4260 | |
4261 | // Determine whether we are allowed to call explicit constructors or |
4262 | // explicit conversion operators. |
4263 | bool AllowExplicit = Kind.AllowExplicit() || IsListInit; |
4264 | bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy; |
4265 | |
4266 | // - Otherwise, if T is a class type, constructors are considered. The |
4267 | // applicable constructors are enumerated, and the best one is chosen |
4268 | // through overload resolution. |
4269 | DeclContext::lookup_result Ctors = S.LookupConstructors(Class: DestRecordDecl); |
4270 | |
4271 | OverloadingResult Result = OR_No_Viable_Function; |
4272 | OverloadCandidateSet::iterator Best; |
4273 | bool AsInitializerList = false; |
4274 | |
4275 | // C++11 [over.match.list]p1, per DR1467: |
4276 | // When objects of non-aggregate type T are list-initialized, such that |
4277 | // 8.5.4 [dcl.init.list] specifies that overload resolution is performed |
4278 | // according to the rules in this section, overload resolution selects |
4279 | // the constructor in two phases: |
4280 | // |
4281 | // - Initially, the candidate functions are the initializer-list |
4282 | // constructors of the class T and the argument list consists of the |
4283 | // initializer list as a single argument. |
4284 | if (IsListInit) { |
4285 | AsInitializerList = true; |
4286 | |
4287 | // If the initializer list has no elements and T has a default constructor, |
4288 | // the first phase is omitted. |
4289 | if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(Class: DestRecordDecl))) |
4290 | Result = ResolveConstructorOverload( |
4291 | S, DeclLoc: Kind.getLocation(), Args, CandidateSet, DestType, Ctors, Best, |
4292 | CopyInitializing: CopyInitialization, AllowExplicit, |
4293 | /*OnlyListConstructors=*/true, IsListInit, RequireActualConstructor); |
4294 | } |
4295 | |
4296 | // C++11 [over.match.list]p1: |
4297 | // - If no viable initializer-list constructor is found, overload resolution |
4298 | // is performed again, where the candidate functions are all the |
4299 | // constructors of the class T and the argument list consists of the |
4300 | // elements of the initializer list. |
4301 | if (Result == OR_No_Viable_Function) { |
4302 | AsInitializerList = false; |
4303 | Result = ResolveConstructorOverload( |
4304 | S, DeclLoc: Kind.getLocation(), Args: UnwrappedArgs, CandidateSet, DestType, Ctors, |
4305 | Best, CopyInitializing: CopyInitialization, AllowExplicit, |
4306 | /*OnlyListConstructors=*/false, IsListInit, RequireActualConstructor); |
4307 | } |
4308 | if (Result) { |
4309 | Sequence.SetOverloadFailure( |
4310 | Failure: IsListInit ? InitializationSequence::FK_ListConstructorOverloadFailed |
4311 | : InitializationSequence::FK_ConstructorOverloadFailed, |
4312 | Result); |
4313 | |
4314 | if (Result != OR_Deleted) |
4315 | return; |
4316 | } |
4317 | |
4318 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
4319 | |
4320 | // In C++17, ResolveConstructorOverload can select a conversion function |
4321 | // instead of a constructor. |
4322 | if (auto *CD = dyn_cast<CXXConversionDecl>(Val: Best->Function)) { |
4323 | // Add the user-defined conversion step that calls the conversion function. |
4324 | QualType ConvType = CD->getConversionType(); |
4325 | assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) && |
4326 | "should not have selected this conversion function" ); |
4327 | Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType, |
4328 | HadMultipleCandidates); |
4329 | if (!S.Context.hasSameType(T1: ConvType, T2: DestType)) |
4330 | Sequence.AddQualificationConversionStep(Ty: DestType, VK: VK_PRValue); |
4331 | if (IsListInit) |
4332 | Sequence.RewrapReferenceInitList(T: Entity.getType(), Syntactic: ILE); |
4333 | return; |
4334 | } |
4335 | |
4336 | CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Val: Best->Function); |
4337 | if (Result != OR_Deleted) { |
4338 | // C++11 [dcl.init]p6: |
4339 | // If a program calls for the default initialization of an object |
4340 | // of a const-qualified type T, T shall be a class type with a |
4341 | // user-provided default constructor. |
4342 | // C++ core issue 253 proposal: |
4343 | // If the implicit default constructor initializes all subobjects, no |
4344 | // initializer should be required. |
4345 | // The 253 proposal is for example needed to process libstdc++ headers |
4346 | // in 5.x. |
4347 | if (Kind.getKind() == InitializationKind::IK_Default && |
4348 | Entity.getType().isConstQualified()) { |
4349 | if (!CtorDecl->getParent()->allowConstDefaultInit()) { |
4350 | if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity)) |
4351 | Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); |
4352 | return; |
4353 | } |
4354 | } |
4355 | |
4356 | // C++11 [over.match.list]p1: |
4357 | // In copy-list-initialization, if an explicit constructor is chosen, the |
4358 | // initializer is ill-formed. |
4359 | if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) { |
4360 | Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor); |
4361 | return; |
4362 | } |
4363 | } |
4364 | |
4365 | // [class.copy.elision]p3: |
4366 | // In some copy-initialization contexts, a two-stage overload resolution |
4367 | // is performed. |
4368 | // If the first overload resolution selects a deleted function, we also |
4369 | // need the initialization sequence to decide whether to perform the second |
4370 | // overload resolution. |
4371 | // For deleted functions in other contexts, there is no need to get the |
4372 | // initialization sequence. |
4373 | if (Result == OR_Deleted && Kind.getKind() != InitializationKind::IK_Copy) |
4374 | return; |
4375 | |
4376 | // Add the constructor initialization step. Any cv-qualification conversion is |
4377 | // subsumed by the initialization. |
4378 | Sequence.AddConstructorInitializationStep( |
4379 | FoundDecl: Best->FoundDecl, Constructor: CtorDecl, T: DestArrayType, HadMultipleCandidates, |
4380 | FromInitList: IsListInit | IsInitListCopy, AsInitList: AsInitializerList); |
4381 | } |
4382 | |
4383 | static bool |
4384 | ResolveOverloadedFunctionForReferenceBinding(Sema &S, |
4385 | Expr *Initializer, |
4386 | QualType &SourceType, |
4387 | QualType &UnqualifiedSourceType, |
4388 | QualType UnqualifiedTargetType, |
4389 | InitializationSequence &Sequence) { |
4390 | if (S.Context.getCanonicalType(T: UnqualifiedSourceType) == |
4391 | S.Context.OverloadTy) { |
4392 | DeclAccessPair Found; |
4393 | bool HadMultipleCandidates = false; |
4394 | if (FunctionDecl *Fn |
4395 | = S.ResolveAddressOfOverloadedFunction(AddressOfExpr: Initializer, |
4396 | TargetType: UnqualifiedTargetType, |
4397 | Complain: false, Found, |
4398 | pHadMultipleCandidates: &HadMultipleCandidates)) { |
4399 | Sequence.AddAddressOverloadResolutionStep(Function: Fn, Found, |
4400 | HadMultipleCandidates); |
4401 | SourceType = Fn->getType(); |
4402 | UnqualifiedSourceType = SourceType.getUnqualifiedType(); |
4403 | } else if (!UnqualifiedTargetType->isRecordType()) { |
4404 | Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); |
4405 | return true; |
4406 | } |
4407 | } |
4408 | return false; |
4409 | } |
4410 | |
4411 | static void TryReferenceInitializationCore(Sema &S, |
4412 | const InitializedEntity &Entity, |
4413 | const InitializationKind &Kind, |
4414 | Expr *Initializer, |
4415 | QualType cv1T1, QualType T1, |
4416 | Qualifiers T1Quals, |
4417 | QualType cv2T2, QualType T2, |
4418 | Qualifiers T2Quals, |
4419 | InitializationSequence &Sequence, |
4420 | bool TopLevelOfInitList); |
4421 | |
4422 | static void TryValueInitialization(Sema &S, |
4423 | const InitializedEntity &Entity, |
4424 | const InitializationKind &Kind, |
4425 | InitializationSequence &Sequence, |
4426 | InitListExpr *InitList = nullptr); |
4427 | |
4428 | /// Attempt list initialization of a reference. |
4429 | static void TryReferenceListInitialization(Sema &S, |
4430 | const InitializedEntity &Entity, |
4431 | const InitializationKind &Kind, |
4432 | InitListExpr *InitList, |
4433 | InitializationSequence &Sequence, |
4434 | bool TreatUnavailableAsInvalid) { |
4435 | // First, catch C++03 where this isn't possible. |
4436 | if (!S.getLangOpts().CPlusPlus11) { |
4437 | Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList); |
4438 | return; |
4439 | } |
4440 | // Can't reference initialize a compound literal. |
4441 | if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) { |
4442 | Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList); |
4443 | return; |
4444 | } |
4445 | |
4446 | QualType DestType = Entity.getType(); |
4447 | QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType(); |
4448 | Qualifiers T1Quals; |
4449 | QualType T1 = S.Context.getUnqualifiedArrayType(T: cv1T1, Quals&: T1Quals); |
4450 | |
4451 | // Reference initialization via an initializer list works thus: |
4452 | // If the initializer list consists of a single element that is |
4453 | // reference-related to the referenced type, bind directly to that element |
4454 | // (possibly creating temporaries). |
4455 | // Otherwise, initialize a temporary with the initializer list and |
4456 | // bind to that. |
4457 | if (InitList->getNumInits() == 1) { |
4458 | Expr *Initializer = InitList->getInit(Init: 0); |
4459 | QualType cv2T2 = S.getCompletedType(E: Initializer); |
4460 | Qualifiers T2Quals; |
4461 | QualType T2 = S.Context.getUnqualifiedArrayType(T: cv2T2, Quals&: T2Quals); |
4462 | |
4463 | // If this fails, creating a temporary wouldn't work either. |
4464 | if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, SourceType&: cv2T2, UnqualifiedSourceType&: T2, |
4465 | UnqualifiedTargetType: T1, Sequence)) |
4466 | return; |
4467 | |
4468 | SourceLocation DeclLoc = Initializer->getBeginLoc(); |
4469 | Sema::ReferenceCompareResult RefRelationship |
4470 | = S.CompareReferenceRelationship(Loc: DeclLoc, T1: cv1T1, T2: cv2T2); |
4471 | if (RefRelationship >= Sema::Ref_Related) { |
4472 | // Try to bind the reference here. |
4473 | TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1, |
4474 | T1Quals, cv2T2, T2, T2Quals, Sequence, |
4475 | /*TopLevelOfInitList=*/true); |
4476 | if (Sequence) |
4477 | Sequence.RewrapReferenceInitList(T: cv1T1, Syntactic: InitList); |
4478 | return; |
4479 | } |
4480 | |
4481 | // Update the initializer if we've resolved an overloaded function. |
4482 | if (Sequence.step_begin() != Sequence.step_end()) |
4483 | Sequence.RewrapReferenceInitList(T: cv1T1, Syntactic: InitList); |
4484 | } |
4485 | // Perform address space compatibility check. |
4486 | QualType cv1T1IgnoreAS = cv1T1; |
4487 | if (T1Quals.hasAddressSpace()) { |
4488 | Qualifiers T2Quals; |
4489 | (void)S.Context.getUnqualifiedArrayType(T: InitList->getType(), Quals&: T2Quals); |
4490 | if (!T1Quals.isAddressSpaceSupersetOf(other: T2Quals)) { |
4491 | Sequence.SetFailed( |
4492 | InitializationSequence::FK_ReferenceInitDropsQualifiers); |
4493 | return; |
4494 | } |
4495 | // Ignore address space of reference type at this point and perform address |
4496 | // space conversion after the reference binding step. |
4497 | cv1T1IgnoreAS = |
4498 | S.Context.getQualifiedType(T: T1, Qs: T1Quals.withoutAddressSpace()); |
4499 | } |
4500 | // Not reference-related. Create a temporary and bind to that. |
4501 | InitializedEntity TempEntity = |
4502 | InitializedEntity::InitializeTemporary(Type: cv1T1IgnoreAS); |
4503 | |
4504 | TryListInitialization(S, Entity: TempEntity, Kind, InitList, Sequence, |
4505 | TreatUnavailableAsInvalid); |
4506 | if (Sequence) { |
4507 | if (DestType->isRValueReferenceType() || |
4508 | (T1Quals.hasConst() && !T1Quals.hasVolatile())) { |
4509 | if (S.getLangOpts().CPlusPlus20 && |
4510 | isa<IncompleteArrayType>(Val: T1->getUnqualifiedDesugaredType()) && |
4511 | DestType->isRValueReferenceType()) { |
4512 | // C++20 [dcl.init.list]p3.10: |
4513 | // List-initialization of an object or reference of type T is defined as |
4514 | // follows: |
4515 | // ..., unless T is “reference to array of unknown bound of U”, in which |
4516 | // case the type of the prvalue is the type of x in the declaration U |
4517 | // x[] H, where H is the initializer list. |
4518 | Sequence.AddQualificationConversionStep(Ty: cv1T1, VK: clang::VK_PRValue); |
4519 | } |
4520 | Sequence.AddReferenceBindingStep(T: cv1T1IgnoreAS, |
4521 | /*BindingTemporary=*/true); |
4522 | if (T1Quals.hasAddressSpace()) |
4523 | Sequence.AddQualificationConversionStep( |
4524 | Ty: cv1T1, VK: DestType->isRValueReferenceType() ? VK_XValue : VK_LValue); |
4525 | } else |
4526 | Sequence.SetFailed( |
4527 | InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary); |
4528 | } |
4529 | } |
4530 | |
4531 | /// Attempt list initialization (C++0x [dcl.init.list]) |
4532 | static void TryListInitialization(Sema &S, |
4533 | const InitializedEntity &Entity, |
4534 | const InitializationKind &Kind, |
4535 | InitListExpr *InitList, |
4536 | InitializationSequence &Sequence, |
4537 | bool TreatUnavailableAsInvalid) { |
4538 | QualType DestType = Entity.getType(); |
4539 | |
4540 | // C++ doesn't allow scalar initialization with more than one argument. |
4541 | // But C99 complex numbers are scalars and it makes sense there. |
4542 | if (S.getLangOpts().CPlusPlus && DestType->isScalarType() && |
4543 | !DestType->isAnyComplexType() && InitList->getNumInits() > 1) { |
4544 | Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar); |
4545 | return; |
4546 | } |
4547 | if (DestType->isReferenceType()) { |
4548 | TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence, |
4549 | TreatUnavailableAsInvalid); |
4550 | return; |
4551 | } |
4552 | |
4553 | if (DestType->isRecordType() && |
4554 | !S.isCompleteType(Loc: InitList->getBeginLoc(), T: DestType)) { |
4555 | Sequence.setIncompleteTypeFailure(DestType); |
4556 | return; |
4557 | } |
4558 | |
4559 | // C++20 [dcl.init.list]p3: |
4560 | // - If the braced-init-list contains a designated-initializer-list, T shall |
4561 | // be an aggregate class. [...] Aggregate initialization is performed. |
4562 | // |
4563 | // We allow arrays here too in order to support array designators. |
4564 | // |
4565 | // FIXME: This check should precede the handling of reference initialization. |
4566 | // We follow other compilers in allowing things like 'Aggr &&a = {.x = 1};' |
4567 | // as a tentative DR resolution. |
4568 | bool IsDesignatedInit = InitList->hasDesignatedInit(); |
4569 | if (!DestType->isAggregateType() && IsDesignatedInit) { |
4570 | Sequence.SetFailed( |
4571 | InitializationSequence::FK_DesignatedInitForNonAggregate); |
4572 | return; |
4573 | } |
4574 | |
4575 | // C++11 [dcl.init.list]p3, per DR1467: |
4576 | // - If T is a class type and the initializer list has a single element of |
4577 | // type cv U, where U is T or a class derived from T, the object is |
4578 | // initialized from that element (by copy-initialization for |
4579 | // copy-list-initialization, or by direct-initialization for |
4580 | // direct-list-initialization). |
4581 | // - Otherwise, if T is a character array and the initializer list has a |
4582 | // single element that is an appropriately-typed string literal |
4583 | // (8.5.2 [dcl.init.string]), initialization is performed as described |
4584 | // in that section. |
4585 | // - Otherwise, if T is an aggregate, [...] (continue below). |
4586 | if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1 && |
4587 | !IsDesignatedInit) { |
4588 | if (DestType->isRecordType()) { |
4589 | QualType InitType = InitList->getInit(Init: 0)->getType(); |
4590 | if (S.Context.hasSameUnqualifiedType(T1: InitType, T2: DestType) || |
4591 | S.IsDerivedFrom(Loc: InitList->getBeginLoc(), Derived: InitType, Base: DestType)) { |
4592 | Expr *InitListAsExpr = InitList; |
4593 | TryConstructorInitialization(S, Entity, Kind, Args: InitListAsExpr, DestType, |
4594 | DestArrayType: DestType, Sequence, |
4595 | /*InitListSyntax*/IsListInit: false, |
4596 | /*IsInitListCopy*/true); |
4597 | return; |
4598 | } |
4599 | } |
4600 | if (const ArrayType *DestAT = S.Context.getAsArrayType(T: DestType)) { |
4601 | Expr *SubInit[1] = {InitList->getInit(Init: 0)}; |
4602 | if (!isa<VariableArrayType>(Val: DestAT) && |
4603 | IsStringInit(Init: SubInit[0], AT: DestAT, Context&: S.Context) == SIF_None) { |
4604 | InitializationKind SubKind = |
4605 | Kind.getKind() == InitializationKind::IK_DirectList |
4606 | ? InitializationKind::CreateDirect(InitLoc: Kind.getLocation(), |
4607 | LParenLoc: InitList->getLBraceLoc(), |
4608 | RParenLoc: InitList->getRBraceLoc()) |
4609 | : Kind; |
4610 | Sequence.InitializeFrom(S, Entity, Kind: SubKind, Args: SubInit, |
4611 | /*TopLevelOfInitList*/ true, |
4612 | TreatUnavailableAsInvalid); |
4613 | |
4614 | // TryStringLiteralInitialization() (in InitializeFrom()) will fail if |
4615 | // the element is not an appropriately-typed string literal, in which |
4616 | // case we should proceed as in C++11 (below). |
4617 | if (Sequence) { |
4618 | Sequence.RewrapReferenceInitList(T: Entity.getType(), Syntactic: InitList); |
4619 | return; |
4620 | } |
4621 | } |
4622 | } |
4623 | } |
4624 | |
4625 | // C++11 [dcl.init.list]p3: |
4626 | // - If T is an aggregate, aggregate initialization is performed. |
4627 | if ((DestType->isRecordType() && !DestType->isAggregateType()) || |
4628 | (S.getLangOpts().CPlusPlus11 && |
4629 | S.isStdInitializerList(Ty: DestType, Element: nullptr) && !IsDesignatedInit)) { |
4630 | if (S.getLangOpts().CPlusPlus11) { |
4631 | // - Otherwise, if the initializer list has no elements and T is a |
4632 | // class type with a default constructor, the object is |
4633 | // value-initialized. |
4634 | if (InitList->getNumInits() == 0) { |
4635 | CXXRecordDecl *RD = DestType->getAsCXXRecordDecl(); |
4636 | if (S.LookupDefaultConstructor(Class: RD)) { |
4637 | TryValueInitialization(S, Entity, Kind, Sequence, InitList); |
4638 | return; |
4639 | } |
4640 | } |
4641 | |
4642 | // - Otherwise, if T is a specialization of std::initializer_list<E>, |
4643 | // an initializer_list object constructed [...] |
4644 | if (TryInitializerListConstruction(S, List: InitList, DestType, Sequence, |
4645 | TreatUnavailableAsInvalid)) |
4646 | return; |
4647 | |
4648 | // - Otherwise, if T is a class type, constructors are considered. |
4649 | Expr *InitListAsExpr = InitList; |
4650 | TryConstructorInitialization(S, Entity, Kind, Args: InitListAsExpr, DestType, |
4651 | DestArrayType: DestType, Sequence, /*InitListSyntax*/IsListInit: true); |
4652 | } else |
4653 | Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType); |
4654 | return; |
4655 | } |
4656 | |
4657 | if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() && |
4658 | InitList->getNumInits() == 1) { |
4659 | Expr *E = InitList->getInit(Init: 0); |
4660 | |
4661 | // - Otherwise, if T is an enumeration with a fixed underlying type, |
4662 | // the initializer-list has a single element v, and the initialization |
4663 | // is direct-list-initialization, the object is initialized with the |
4664 | // value T(v); if a narrowing conversion is required to convert v to |
4665 | // the underlying type of T, the program is ill-formed. |
4666 | auto *ET = DestType->getAs<EnumType>(); |
4667 | if (S.getLangOpts().CPlusPlus17 && |
4668 | Kind.getKind() == InitializationKind::IK_DirectList && |
4669 | ET && ET->getDecl()->isFixed() && |
4670 | !S.Context.hasSameUnqualifiedType(T1: E->getType(), T2: DestType) && |
4671 | (E->getType()->isIntegralOrUnscopedEnumerationType() || |
4672 | E->getType()->isFloatingType())) { |
4673 | // There are two ways that T(v) can work when T is an enumeration type. |
4674 | // If there is either an implicit conversion sequence from v to T or |
4675 | // a conversion function that can convert from v to T, then we use that. |
4676 | // Otherwise, if v is of integral, unscoped enumeration, or floating-point |
4677 | // type, it is converted to the enumeration type via its underlying type. |
4678 | // There is no overlap possible between these two cases (except when the |
4679 | // source value is already of the destination type), and the first |
4680 | // case is handled by the general case for single-element lists below. |
4681 | ImplicitConversionSequence ICS; |
4682 | ICS.setStandard(); |
4683 | ICS.Standard.setAsIdentityConversion(); |
4684 | if (!E->isPRValue()) |
4685 | ICS.Standard.First = ICK_Lvalue_To_Rvalue; |
4686 | // If E is of a floating-point type, then the conversion is ill-formed |
4687 | // due to narrowing, but go through the motions in order to produce the |
4688 | // right diagnostic. |
4689 | ICS.Standard.Second = E->getType()->isFloatingType() |
4690 | ? ICK_Floating_Integral |
4691 | : ICK_Integral_Conversion; |
4692 | ICS.Standard.setFromType(E->getType()); |
4693 | ICS.Standard.setToType(Idx: 0, T: E->getType()); |
4694 | ICS.Standard.setToType(Idx: 1, T: DestType); |
4695 | ICS.Standard.setToType(Idx: 2, T: DestType); |
4696 | Sequence.AddConversionSequenceStep(ICS, T: ICS.Standard.getToType(Idx: 2), |
4697 | /*TopLevelOfInitList*/true); |
4698 | Sequence.RewrapReferenceInitList(T: Entity.getType(), Syntactic: InitList); |
4699 | return; |
4700 | } |
4701 | |
4702 | // - Otherwise, if the initializer list has a single element of type E |
4703 | // [...references are handled above...], the object or reference is |
4704 | // initialized from that element (by copy-initialization for |
4705 | // copy-list-initialization, or by direct-initialization for |
4706 | // direct-list-initialization); if a narrowing conversion is required |
4707 | // to convert the element to T, the program is ill-formed. |
4708 | // |
4709 | // Per core-24034, this is direct-initialization if we were performing |
4710 | // direct-list-initialization and copy-initialization otherwise. |
4711 | // We can't use InitListChecker for this, because it always performs |
4712 | // copy-initialization. This only matters if we might use an 'explicit' |
4713 | // conversion operator, or for the special case conversion of nullptr_t to |
4714 | // bool, so we only need to handle those cases. |
4715 | // |
4716 | // FIXME: Why not do this in all cases? |
4717 | Expr *Init = InitList->getInit(Init: 0); |
4718 | if (Init->getType()->isRecordType() || |
4719 | (Init->getType()->isNullPtrType() && DestType->isBooleanType())) { |
4720 | InitializationKind SubKind = |
4721 | Kind.getKind() == InitializationKind::IK_DirectList |
4722 | ? InitializationKind::CreateDirect(InitLoc: Kind.getLocation(), |
4723 | LParenLoc: InitList->getLBraceLoc(), |
4724 | RParenLoc: InitList->getRBraceLoc()) |
4725 | : Kind; |
4726 | Expr *SubInit[1] = { Init }; |
4727 | Sequence.InitializeFrom(S, Entity, Kind: SubKind, Args: SubInit, |
4728 | /*TopLevelOfInitList*/true, |
4729 | TreatUnavailableAsInvalid); |
4730 | if (Sequence) |
4731 | Sequence.RewrapReferenceInitList(T: Entity.getType(), Syntactic: InitList); |
4732 | return; |
4733 | } |
4734 | } |
4735 | |
4736 | InitListChecker CheckInitList(S, Entity, InitList, |
4737 | DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid); |
4738 | if (CheckInitList.HadError()) { |
4739 | Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed); |
4740 | return; |
4741 | } |
4742 | |
4743 | // Add the list initialization step with the built init list. |
4744 | Sequence.AddListInitializationStep(T: DestType); |
4745 | } |
4746 | |
4747 | /// Try a reference initialization that involves calling a conversion |
4748 | /// function. |
4749 | static OverloadingResult TryRefInitWithConversionFunction( |
4750 | Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, |
4751 | Expr *Initializer, bool AllowRValues, bool IsLValueRef, |
4752 | InitializationSequence &Sequence) { |
4753 | QualType DestType = Entity.getType(); |
4754 | QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType(); |
4755 | QualType T1 = cv1T1.getUnqualifiedType(); |
4756 | QualType cv2T2 = Initializer->getType(); |
4757 | QualType T2 = cv2T2.getUnqualifiedType(); |
4758 | |
4759 | assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) && |
4760 | "Must have incompatible references when binding via conversion" ); |
4761 | |
4762 | // Build the candidate set directly in the initialization sequence |
4763 | // structure, so that it will persist if we fail. |
4764 | OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); |
4765 | CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion); |
4766 | |
4767 | // Determine whether we are allowed to call explicit conversion operators. |
4768 | // Note that none of [over.match.copy], [over.match.conv], nor |
4769 | // [over.match.ref] permit an explicit constructor to be chosen when |
4770 | // initializing a reference, not even for direct-initialization. |
4771 | bool AllowExplicitCtors = false; |
4772 | bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding(); |
4773 | |
4774 | const RecordType *T1RecordType = nullptr; |
4775 | if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) && |
4776 | S.isCompleteType(Loc: Kind.getLocation(), T: T1)) { |
4777 | // The type we're converting to is a class type. Enumerate its constructors |
4778 | // to see if there is a suitable conversion. |
4779 | CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(Val: T1RecordType->getDecl()); |
4780 | |
4781 | for (NamedDecl *D : S.LookupConstructors(Class: T1RecordDecl)) { |
4782 | auto Info = getConstructorInfo(ND: D); |
4783 | if (!Info.Constructor) |
4784 | continue; |
4785 | |
4786 | if (!Info.Constructor->isInvalidDecl() && |
4787 | Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) { |
4788 | if (Info.ConstructorTmpl) |
4789 | S.AddTemplateOverloadCandidate( |
4790 | FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl, |
4791 | /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: Initializer, CandidateSet, |
4792 | /*SuppressUserConversions=*/true, |
4793 | /*PartialOverloading*/ false, AllowExplicit: AllowExplicitCtors); |
4794 | else |
4795 | S.AddOverloadCandidate( |
4796 | Info.Constructor, Info.FoundDecl, Initializer, CandidateSet, |
4797 | /*SuppressUserConversions=*/true, |
4798 | /*PartialOverloading*/ false, AllowExplicitCtors); |
4799 | } |
4800 | } |
4801 | } |
4802 | if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl()) |
4803 | return OR_No_Viable_Function; |
4804 | |
4805 | const RecordType *T2RecordType = nullptr; |
4806 | if ((T2RecordType = T2->getAs<RecordType>()) && |
4807 | S.isCompleteType(Loc: Kind.getLocation(), T: T2)) { |
4808 | // The type we're converting from is a class type, enumerate its conversion |
4809 | // functions. |
4810 | CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(Val: T2RecordType->getDecl()); |
4811 | |
4812 | const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); |
4813 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { |
4814 | NamedDecl *D = *I; |
4815 | CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); |
4816 | if (isa<UsingShadowDecl>(Val: D)) |
4817 | D = cast<UsingShadowDecl>(Val: D)->getTargetDecl(); |
4818 | |
4819 | FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D); |
4820 | CXXConversionDecl *Conv; |
4821 | if (ConvTemplate) |
4822 | Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl()); |
4823 | else |
4824 | Conv = cast<CXXConversionDecl>(Val: D); |
4825 | |
4826 | // If the conversion function doesn't return a reference type, |
4827 | // it can't be considered for this conversion unless we're allowed to |
4828 | // consider rvalues. |
4829 | // FIXME: Do we need to make sure that we only consider conversion |
4830 | // candidates with reference-compatible results? That might be needed to |
4831 | // break recursion. |
4832 | if ((AllowRValues || |
4833 | Conv->getConversionType()->isLValueReferenceType())) { |
4834 | if (ConvTemplate) |
4835 | S.AddTemplateConversionCandidate( |
4836 | FunctionTemplate: ConvTemplate, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer, ToType: DestType, |
4837 | CandidateSet, |
4838 | /*AllowObjCConversionOnExplicit=*/false, AllowExplicit: AllowExplicitConvs); |
4839 | else |
4840 | S.AddConversionCandidate( |
4841 | Conversion: Conv, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer, ToType: DestType, CandidateSet, |
4842 | /*AllowObjCConversionOnExplicit=*/false, AllowExplicit: AllowExplicitConvs); |
4843 | } |
4844 | } |
4845 | } |
4846 | if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl()) |
4847 | return OR_No_Viable_Function; |
4848 | |
4849 | SourceLocation DeclLoc = Initializer->getBeginLoc(); |
4850 | |
4851 | // Perform overload resolution. If it fails, return the failed result. |
4852 | OverloadCandidateSet::iterator Best; |
4853 | if (OverloadingResult Result |
4854 | = CandidateSet.BestViableFunction(S, Loc: DeclLoc, Best)) |
4855 | return Result; |
4856 | |
4857 | FunctionDecl *Function = Best->Function; |
4858 | // This is the overload that will be used for this initialization step if we |
4859 | // use this initialization. Mark it as referenced. |
4860 | Function->setReferenced(); |
4861 | |
4862 | // Compute the returned type and value kind of the conversion. |
4863 | QualType cv3T3; |
4864 | if (isa<CXXConversionDecl>(Val: Function)) |
4865 | cv3T3 = Function->getReturnType(); |
4866 | else |
4867 | cv3T3 = T1; |
4868 | |
4869 | ExprValueKind VK = VK_PRValue; |
4870 | if (cv3T3->isLValueReferenceType()) |
4871 | VK = VK_LValue; |
4872 | else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>()) |
4873 | VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue; |
4874 | cv3T3 = cv3T3.getNonLValueExprType(Context: S.Context); |
4875 | |
4876 | // Add the user-defined conversion step. |
4877 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
4878 | Sequence.AddUserConversionStep(Function, FoundDecl: Best->FoundDecl, T: cv3T3, |
4879 | HadMultipleCandidates); |
4880 | |
4881 | // Determine whether we'll need to perform derived-to-base adjustments or |
4882 | // other conversions. |
4883 | Sema::ReferenceConversions RefConv; |
4884 | Sema::ReferenceCompareResult NewRefRelationship = |
4885 | S.CompareReferenceRelationship(Loc: DeclLoc, T1, T2: cv3T3, Conv: &RefConv); |
4886 | |
4887 | // Add the final conversion sequence, if necessary. |
4888 | if (NewRefRelationship == Sema::Ref_Incompatible) { |
4889 | assert(!isa<CXXConstructorDecl>(Function) && |
4890 | "should not have conversion after constructor" ); |
4891 | |
4892 | ImplicitConversionSequence ICS; |
4893 | ICS.setStandard(); |
4894 | ICS.Standard = Best->FinalConversion; |
4895 | Sequence.AddConversionSequenceStep(ICS, T: ICS.Standard.getToType(Idx: 2)); |
4896 | |
4897 | // Every implicit conversion results in a prvalue, except for a glvalue |
4898 | // derived-to-base conversion, which we handle below. |
4899 | cv3T3 = ICS.Standard.getToType(Idx: 2); |
4900 | VK = VK_PRValue; |
4901 | } |
4902 | |
4903 | // If the converted initializer is a prvalue, its type T4 is adjusted to |
4904 | // type "cv1 T4" and the temporary materialization conversion is applied. |
4905 | // |
4906 | // We adjust the cv-qualifications to match the reference regardless of |
4907 | // whether we have a prvalue so that the AST records the change. In this |
4908 | // case, T4 is "cv3 T3". |
4909 | QualType cv1T4 = S.Context.getQualifiedType(T: cv3T3, Qs: cv1T1.getQualifiers()); |
4910 | if (cv1T4.getQualifiers() != cv3T3.getQualifiers()) |
4911 | Sequence.AddQualificationConversionStep(Ty: cv1T4, VK); |
4912 | Sequence.AddReferenceBindingStep(T: cv1T4, BindingTemporary: VK == VK_PRValue); |
4913 | VK = IsLValueRef ? VK_LValue : VK_XValue; |
4914 | |
4915 | if (RefConv & Sema::ReferenceConversions::DerivedToBase) |
4916 | Sequence.AddDerivedToBaseCastStep(BaseType: cv1T1, VK); |
4917 | else if (RefConv & Sema::ReferenceConversions::ObjC) |
4918 | Sequence.AddObjCObjectConversionStep(T: cv1T1); |
4919 | else if (RefConv & Sema::ReferenceConversions::Function) |
4920 | Sequence.AddFunctionReferenceConversionStep(Ty: cv1T1); |
4921 | else if (RefConv & Sema::ReferenceConversions::Qualification) { |
4922 | if (!S.Context.hasSameType(T1: cv1T4, T2: cv1T1)) |
4923 | Sequence.AddQualificationConversionStep(Ty: cv1T1, VK); |
4924 | } |
4925 | |
4926 | return OR_Success; |
4927 | } |
4928 | |
4929 | static void CheckCXX98CompatAccessibleCopy(Sema &S, |
4930 | const InitializedEntity &Entity, |
4931 | Expr *CurInitExpr); |
4932 | |
4933 | /// Attempt reference initialization (C++0x [dcl.init.ref]) |
4934 | static void TryReferenceInitialization(Sema &S, const InitializedEntity &Entity, |
4935 | const InitializationKind &Kind, |
4936 | Expr *Initializer, |
4937 | InitializationSequence &Sequence, |
4938 | bool TopLevelOfInitList) { |
4939 | QualType DestType = Entity.getType(); |
4940 | QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType(); |
4941 | Qualifiers T1Quals; |
4942 | QualType T1 = S.Context.getUnqualifiedArrayType(T: cv1T1, Quals&: T1Quals); |
4943 | QualType cv2T2 = S.getCompletedType(E: Initializer); |
4944 | Qualifiers T2Quals; |
4945 | QualType T2 = S.Context.getUnqualifiedArrayType(T: cv2T2, Quals&: T2Quals); |
4946 | |
4947 | // If the initializer is the address of an overloaded function, try |
4948 | // to resolve the overloaded function. If all goes well, T2 is the |
4949 | // type of the resulting function. |
4950 | if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, SourceType&: cv2T2, UnqualifiedSourceType&: T2, |
4951 | UnqualifiedTargetType: T1, Sequence)) |
4952 | return; |
4953 | |
4954 | // Delegate everything else to a subfunction. |
4955 | TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1, |
4956 | T1Quals, cv2T2, T2, T2Quals, Sequence, |
4957 | TopLevelOfInitList); |
4958 | } |
4959 | |
4960 | /// Determine whether an expression is a non-referenceable glvalue (one to |
4961 | /// which a reference can never bind). Attempting to bind a reference to |
4962 | /// such a glvalue will always create a temporary. |
4963 | static bool isNonReferenceableGLValue(Expr *E) { |
4964 | return E->refersToBitField() || E->refersToVectorElement() || |
4965 | E->refersToMatrixElement(); |
4966 | } |
4967 | |
4968 | /// Reference initialization without resolving overloaded functions. |
4969 | /// |
4970 | /// We also can get here in C if we call a builtin which is declared as |
4971 | /// a function with a parameter of reference type (such as __builtin_va_end()). |
4972 | static void TryReferenceInitializationCore(Sema &S, |
4973 | const InitializedEntity &Entity, |
4974 | const InitializationKind &Kind, |
4975 | Expr *Initializer, |
4976 | QualType cv1T1, QualType T1, |
4977 | Qualifiers T1Quals, |
4978 | QualType cv2T2, QualType T2, |
4979 | Qualifiers T2Quals, |
4980 | InitializationSequence &Sequence, |
4981 | bool TopLevelOfInitList) { |
4982 | QualType DestType = Entity.getType(); |
4983 | SourceLocation DeclLoc = Initializer->getBeginLoc(); |
4984 | |
4985 | // Compute some basic properties of the types and the initializer. |
4986 | bool isLValueRef = DestType->isLValueReferenceType(); |
4987 | bool isRValueRef = !isLValueRef; |
4988 | Expr::Classification InitCategory = Initializer->Classify(Ctx&: S.Context); |
4989 | |
4990 | Sema::ReferenceConversions RefConv; |
4991 | Sema::ReferenceCompareResult RefRelationship = |
4992 | S.CompareReferenceRelationship(Loc: DeclLoc, T1: cv1T1, T2: cv2T2, Conv: &RefConv); |
4993 | |
4994 | // C++0x [dcl.init.ref]p5: |
4995 | // A reference to type "cv1 T1" is initialized by an expression of type |
4996 | // "cv2 T2" as follows: |
4997 | // |
4998 | // - If the reference is an lvalue reference and the initializer |
4999 | // expression |
5000 | // Note the analogous bullet points for rvalue refs to functions. Because |
5001 | // there are no function rvalues in C++, rvalue refs to functions are treated |
5002 | // like lvalue refs. |
5003 | OverloadingResult ConvOvlResult = OR_Success; |
5004 | bool T1Function = T1->isFunctionType(); |
5005 | if (isLValueRef || T1Function) { |
5006 | if (InitCategory.isLValue() && !isNonReferenceableGLValue(E: Initializer) && |
5007 | (RefRelationship == Sema::Ref_Compatible || |
5008 | (Kind.isCStyleOrFunctionalCast() && |
5009 | RefRelationship == Sema::Ref_Related))) { |
5010 | // - is an lvalue (but is not a bit-field), and "cv1 T1" is |
5011 | // reference-compatible with "cv2 T2," or |
5012 | if (RefConv & (Sema::ReferenceConversions::DerivedToBase | |
5013 | Sema::ReferenceConversions::ObjC)) { |
5014 | // If we're converting the pointee, add any qualifiers first; |
5015 | // these qualifiers must all be top-level, so just convert to "cv1 T2". |
5016 | if (RefConv & (Sema::ReferenceConversions::Qualification)) |
5017 | Sequence.AddQualificationConversionStep( |
5018 | Ty: S.Context.getQualifiedType(T: T2, Qs: T1Quals), |
5019 | VK: Initializer->getValueKind()); |
5020 | if (RefConv & Sema::ReferenceConversions::DerivedToBase) |
5021 | Sequence.AddDerivedToBaseCastStep(BaseType: cv1T1, VK: VK_LValue); |
5022 | else |
5023 | Sequence.AddObjCObjectConversionStep(T: cv1T1); |
5024 | } else if (RefConv & Sema::ReferenceConversions::Qualification) { |
5025 | // Perform a (possibly multi-level) qualification conversion. |
5026 | Sequence.AddQualificationConversionStep(Ty: cv1T1, |
5027 | VK: Initializer->getValueKind()); |
5028 | } else if (RefConv & Sema::ReferenceConversions::Function) { |
5029 | Sequence.AddFunctionReferenceConversionStep(Ty: cv1T1); |
5030 | } |
5031 | |
5032 | // We only create a temporary here when binding a reference to a |
5033 | // bit-field or vector element. Those cases are't supposed to be |
5034 | // handled by this bullet, but the outcome is the same either way. |
5035 | Sequence.AddReferenceBindingStep(T: cv1T1, BindingTemporary: false); |
5036 | return; |
5037 | } |
5038 | |
5039 | // - has a class type (i.e., T2 is a class type), where T1 is not |
5040 | // reference-related to T2, and can be implicitly converted to an |
5041 | // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible |
5042 | // with "cv3 T3" (this conversion is selected by enumerating the |
5043 | // applicable conversion functions (13.3.1.6) and choosing the best |
5044 | // one through overload resolution (13.3)), |
5045 | // If we have an rvalue ref to function type here, the rhs must be |
5046 | // an rvalue. DR1287 removed the "implicitly" here. |
5047 | if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() && |
5048 | (isLValueRef || InitCategory.isRValue())) { |
5049 | if (S.getLangOpts().CPlusPlus) { |
5050 | // Try conversion functions only for C++. |
5051 | ConvOvlResult = TryRefInitWithConversionFunction( |
5052 | S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef, |
5053 | /*IsLValueRef*/ isLValueRef, Sequence); |
5054 | if (ConvOvlResult == OR_Success) |
5055 | return; |
5056 | if (ConvOvlResult != OR_No_Viable_Function) |
5057 | Sequence.SetOverloadFailure( |
5058 | Failure: InitializationSequence::FK_ReferenceInitOverloadFailed, |
5059 | Result: ConvOvlResult); |
5060 | } else { |
5061 | ConvOvlResult = OR_No_Viable_Function; |
5062 | } |
5063 | } |
5064 | } |
5065 | |
5066 | // - Otherwise, the reference shall be an lvalue reference to a |
5067 | // non-volatile const type (i.e., cv1 shall be const), or the reference |
5068 | // shall be an rvalue reference. |
5069 | // For address spaces, we interpret this to mean that an addr space |
5070 | // of a reference "cv1 T1" is a superset of addr space of "cv2 T2". |
5071 | if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile() && |
5072 | T1Quals.isAddressSpaceSupersetOf(other: T2Quals))) { |
5073 | if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) |
5074 | Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); |
5075 | else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) |
5076 | Sequence.SetOverloadFailure( |
5077 | Failure: InitializationSequence::FK_ReferenceInitOverloadFailed, |
5078 | Result: ConvOvlResult); |
5079 | else if (!InitCategory.isLValue()) |
5080 | Sequence.SetFailed( |
5081 | T1Quals.isAddressSpaceSupersetOf(other: T2Quals) |
5082 | ? InitializationSequence:: |
5083 | FK_NonConstLValueReferenceBindingToTemporary |
5084 | : InitializationSequence::FK_ReferenceInitDropsQualifiers); |
5085 | else { |
5086 | InitializationSequence::FailureKind FK; |
5087 | switch (RefRelationship) { |
5088 | case Sema::Ref_Compatible: |
5089 | if (Initializer->refersToBitField()) |
5090 | FK = InitializationSequence:: |
5091 | FK_NonConstLValueReferenceBindingToBitfield; |
5092 | else if (Initializer->refersToVectorElement()) |
5093 | FK = InitializationSequence:: |
5094 | FK_NonConstLValueReferenceBindingToVectorElement; |
5095 | else if (Initializer->refersToMatrixElement()) |
5096 | FK = InitializationSequence:: |
5097 | FK_NonConstLValueReferenceBindingToMatrixElement; |
5098 | else |
5099 | llvm_unreachable("unexpected kind of compatible initializer" ); |
5100 | break; |
5101 | case Sema::Ref_Related: |
5102 | FK = InitializationSequence::FK_ReferenceInitDropsQualifiers; |
5103 | break; |
5104 | case Sema::Ref_Incompatible: |
5105 | FK = InitializationSequence:: |
5106 | FK_NonConstLValueReferenceBindingToUnrelated; |
5107 | break; |
5108 | } |
5109 | Sequence.SetFailed(FK); |
5110 | } |
5111 | return; |
5112 | } |
5113 | |
5114 | // - If the initializer expression |
5115 | // - is an |
5116 | // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or |
5117 | // [1z] rvalue (but not a bit-field) or |
5118 | // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2" |
5119 | // |
5120 | // Note: functions are handled above and below rather than here... |
5121 | if (!T1Function && |
5122 | (RefRelationship == Sema::Ref_Compatible || |
5123 | (Kind.isCStyleOrFunctionalCast() && |
5124 | RefRelationship == Sema::Ref_Related)) && |
5125 | ((InitCategory.isXValue() && !isNonReferenceableGLValue(E: Initializer)) || |
5126 | (InitCategory.isPRValue() && |
5127 | (S.getLangOpts().CPlusPlus17 || T2->isRecordType() || |
5128 | T2->isArrayType())))) { |
5129 | ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_PRValue; |
5130 | if (InitCategory.isPRValue() && T2->isRecordType()) { |
5131 | // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the |
5132 | // compiler the freedom to perform a copy here or bind to the |
5133 | // object, while C++0x requires that we bind directly to the |
5134 | // object. Hence, we always bind to the object without making an |
5135 | // extra copy. However, in C++03 requires that we check for the |
5136 | // presence of a suitable copy constructor: |
5137 | // |
5138 | // The constructor that would be used to make the copy shall |
5139 | // be callable whether or not the copy is actually done. |
5140 | if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt) |
5141 | Sequence.AddExtraneousCopyToTemporary(T: cv2T2); |
5142 | else if (S.getLangOpts().CPlusPlus11) |
5143 | CheckCXX98CompatAccessibleCopy(S, Entity, CurInitExpr: Initializer); |
5144 | } |
5145 | |
5146 | // C++1z [dcl.init.ref]/5.2.1.2: |
5147 | // If the converted initializer is a prvalue, its type T4 is adjusted |
5148 | // to type "cv1 T4" and the temporary materialization conversion is |
5149 | // applied. |
5150 | // Postpone address space conversions to after the temporary materialization |
5151 | // conversion to allow creating temporaries in the alloca address space. |
5152 | auto T1QualsIgnoreAS = T1Quals; |
5153 | auto T2QualsIgnoreAS = T2Quals; |
5154 | if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) { |
5155 | T1QualsIgnoreAS.removeAddressSpace(); |
5156 | T2QualsIgnoreAS.removeAddressSpace(); |
5157 | } |
5158 | QualType cv1T4 = S.Context.getQualifiedType(T: cv2T2, Qs: T1QualsIgnoreAS); |
5159 | if (T1QualsIgnoreAS != T2QualsIgnoreAS) |
5160 | Sequence.AddQualificationConversionStep(Ty: cv1T4, VK: ValueKind); |
5161 | Sequence.AddReferenceBindingStep(T: cv1T4, BindingTemporary: ValueKind == VK_PRValue); |
5162 | ValueKind = isLValueRef ? VK_LValue : VK_XValue; |
5163 | // Add addr space conversion if required. |
5164 | if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) { |
5165 | auto T4Quals = cv1T4.getQualifiers(); |
5166 | T4Quals.addAddressSpace(space: T1Quals.getAddressSpace()); |
5167 | QualType cv1T4WithAS = S.Context.getQualifiedType(T: T2, Qs: T4Quals); |
5168 | Sequence.AddQualificationConversionStep(Ty: cv1T4WithAS, VK: ValueKind); |
5169 | cv1T4 = cv1T4WithAS; |
5170 | } |
5171 | |
5172 | // In any case, the reference is bound to the resulting glvalue (or to |
5173 | // an appropriate base class subobject). |
5174 | if (RefConv & Sema::ReferenceConversions::DerivedToBase) |
5175 | Sequence.AddDerivedToBaseCastStep(BaseType: cv1T1, VK: ValueKind); |
5176 | else if (RefConv & Sema::ReferenceConversions::ObjC) |
5177 | Sequence.AddObjCObjectConversionStep(T: cv1T1); |
5178 | else if (RefConv & Sema::ReferenceConversions::Qualification) { |
5179 | if (!S.Context.hasSameType(T1: cv1T4, T2: cv1T1)) |
5180 | Sequence.AddQualificationConversionStep(Ty: cv1T1, VK: ValueKind); |
5181 | } |
5182 | return; |
5183 | } |
5184 | |
5185 | // - has a class type (i.e., T2 is a class type), where T1 is not |
5186 | // reference-related to T2, and can be implicitly converted to an |
5187 | // xvalue, class prvalue, or function lvalue of type "cv3 T3", |
5188 | // where "cv1 T1" is reference-compatible with "cv3 T3", |
5189 | // |
5190 | // DR1287 removes the "implicitly" here. |
5191 | if (T2->isRecordType()) { |
5192 | if (RefRelationship == Sema::Ref_Incompatible) { |
5193 | ConvOvlResult = TryRefInitWithConversionFunction( |
5194 | S, Entity, Kind, Initializer, /*AllowRValues*/ true, |
5195 | /*IsLValueRef*/ isLValueRef, Sequence); |
5196 | if (ConvOvlResult) |
5197 | Sequence.SetOverloadFailure( |
5198 | Failure: InitializationSequence::FK_ReferenceInitOverloadFailed, |
5199 | Result: ConvOvlResult); |
5200 | |
5201 | return; |
5202 | } |
5203 | |
5204 | if (RefRelationship == Sema::Ref_Compatible && |
5205 | isRValueRef && InitCategory.isLValue()) { |
5206 | Sequence.SetFailed( |
5207 | InitializationSequence::FK_RValueReferenceBindingToLValue); |
5208 | return; |
5209 | } |
5210 | |
5211 | Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); |
5212 | return; |
5213 | } |
5214 | |
5215 | // - Otherwise, a temporary of type "cv1 T1" is created and initialized |
5216 | // from the initializer expression using the rules for a non-reference |
5217 | // copy-initialization (8.5). The reference is then bound to the |
5218 | // temporary. [...] |
5219 | |
5220 | // Ignore address space of reference type at this point and perform address |
5221 | // space conversion after the reference binding step. |
5222 | QualType cv1T1IgnoreAS = |
5223 | T1Quals.hasAddressSpace() |
5224 | ? S.Context.getQualifiedType(T: T1, Qs: T1Quals.withoutAddressSpace()) |
5225 | : cv1T1; |
5226 | |
5227 | InitializedEntity TempEntity = |
5228 | InitializedEntity::InitializeTemporary(Type: cv1T1IgnoreAS); |
5229 | |
5230 | // FIXME: Why do we use an implicit conversion here rather than trying |
5231 | // copy-initialization? |
5232 | ImplicitConversionSequence ICS |
5233 | = S.TryImplicitConversion(From: Initializer, ToType: TempEntity.getType(), |
5234 | /*SuppressUserConversions=*/false, |
5235 | AllowExplicit: Sema::AllowedExplicit::None, |
5236 | /*FIXME:InOverloadResolution=*/InOverloadResolution: false, |
5237 | /*CStyle=*/Kind.isCStyleOrFunctionalCast(), |
5238 | /*AllowObjCWritebackConversion=*/false); |
5239 | |
5240 | if (ICS.isBad()) { |
5241 | // FIXME: Use the conversion function set stored in ICS to turn |
5242 | // this into an overloading ambiguity diagnostic. However, we need |
5243 | // to keep that set as an OverloadCandidateSet rather than as some |
5244 | // other kind of set. |
5245 | if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) |
5246 | Sequence.SetOverloadFailure( |
5247 | Failure: InitializationSequence::FK_ReferenceInitOverloadFailed, |
5248 | Result: ConvOvlResult); |
5249 | else if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) |
5250 | Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); |
5251 | else |
5252 | Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed); |
5253 | return; |
5254 | } else { |
5255 | Sequence.AddConversionSequenceStep(ICS, T: TempEntity.getType(), |
5256 | TopLevelOfInitList); |
5257 | } |
5258 | |
5259 | // [...] If T1 is reference-related to T2, cv1 must be the |
5260 | // same cv-qualification as, or greater cv-qualification |
5261 | // than, cv2; otherwise, the program is ill-formed. |
5262 | unsigned T1CVRQuals = T1Quals.getCVRQualifiers(); |
5263 | unsigned T2CVRQuals = T2Quals.getCVRQualifiers(); |
5264 | if (RefRelationship == Sema::Ref_Related && |
5265 | ((T1CVRQuals | T2CVRQuals) != T1CVRQuals || |
5266 | !T1Quals.isAddressSpaceSupersetOf(other: T2Quals))) { |
5267 | Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); |
5268 | return; |
5269 | } |
5270 | |
5271 | // [...] If T1 is reference-related to T2 and the reference is an rvalue |
5272 | // reference, the initializer expression shall not be an lvalue. |
5273 | if (RefRelationship >= Sema::Ref_Related && !isLValueRef && |
5274 | InitCategory.isLValue()) { |
5275 | Sequence.SetFailed( |
5276 | InitializationSequence::FK_RValueReferenceBindingToLValue); |
5277 | return; |
5278 | } |
5279 | |
5280 | Sequence.AddReferenceBindingStep(T: cv1T1IgnoreAS, /*BindingTemporary=*/true); |
5281 | |
5282 | if (T1Quals.hasAddressSpace()) { |
5283 | if (!Qualifiers::isAddressSpaceSupersetOf(A: T1Quals.getAddressSpace(), |
5284 | B: LangAS::Default)) { |
5285 | Sequence.SetFailed( |
5286 | InitializationSequence::FK_ReferenceAddrspaceMismatchTemporary); |
5287 | return; |
5288 | } |
5289 | Sequence.AddQualificationConversionStep(Ty: cv1T1, VK: isLValueRef ? VK_LValue |
5290 | : VK_XValue); |
5291 | } |
5292 | } |
5293 | |
5294 | /// Attempt character array initialization from a string literal |
5295 | /// (C++ [dcl.init.string], C99 6.7.8). |
5296 | static void TryStringLiteralInitialization(Sema &S, |
5297 | const InitializedEntity &Entity, |
5298 | const InitializationKind &Kind, |
5299 | Expr *Initializer, |
5300 | InitializationSequence &Sequence) { |
5301 | Sequence.AddStringInitStep(T: Entity.getType()); |
5302 | } |
5303 | |
5304 | /// Attempt value initialization (C++ [dcl.init]p7). |
5305 | static void TryValueInitialization(Sema &S, |
5306 | const InitializedEntity &Entity, |
5307 | const InitializationKind &Kind, |
5308 | InitializationSequence &Sequence, |
5309 | InitListExpr *InitList) { |
5310 | assert((!InitList || InitList->getNumInits() == 0) && |
5311 | "Shouldn't use value-init for non-empty init lists" ); |
5312 | |
5313 | // C++98 [dcl.init]p5, C++11 [dcl.init]p7: |
5314 | // |
5315 | // To value-initialize an object of type T means: |
5316 | QualType T = Entity.getType(); |
5317 | |
5318 | // -- if T is an array type, then each element is value-initialized; |
5319 | T = S.Context.getBaseElementType(QT: T); |
5320 | |
5321 | if (const RecordType *RT = T->getAs<RecordType>()) { |
5322 | if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Val: RT->getDecl())) { |
5323 | bool NeedZeroInitialization = true; |
5324 | // C++98: |
5325 | // -- if T is a class type (clause 9) with a user-declared constructor |
5326 | // (12.1), then the default constructor for T is called (and the |
5327 | // initialization is ill-formed if T has no accessible default |
5328 | // constructor); |
5329 | // C++11: |
5330 | // -- if T is a class type (clause 9) with either no default constructor |
5331 | // (12.1 [class.ctor]) or a default constructor that is user-provided |
5332 | // or deleted, then the object is default-initialized; |
5333 | // |
5334 | // Note that the C++11 rule is the same as the C++98 rule if there are no |
5335 | // defaulted or deleted constructors, so we just use it unconditionally. |
5336 | CXXConstructorDecl *CD = S.LookupDefaultConstructor(Class: ClassDecl); |
5337 | if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted()) |
5338 | NeedZeroInitialization = false; |
5339 | |
5340 | // -- if T is a (possibly cv-qualified) non-union class type without a |
5341 | // user-provided or deleted default constructor, then the object is |
5342 | // zero-initialized and, if T has a non-trivial default constructor, |
5343 | // default-initialized; |
5344 | // The 'non-union' here was removed by DR1502. The 'non-trivial default |
5345 | // constructor' part was removed by DR1507. |
5346 | if (NeedZeroInitialization) |
5347 | Sequence.AddZeroInitializationStep(T: Entity.getType()); |
5348 | |
5349 | // C++03: |
5350 | // -- if T is a non-union class type without a user-declared constructor, |
5351 | // then every non-static data member and base class component of T is |
5352 | // value-initialized; |
5353 | // [...] A program that calls for [...] value-initialization of an |
5354 | // entity of reference type is ill-formed. |
5355 | // |
5356 | // C++11 doesn't need this handling, because value-initialization does not |
5357 | // occur recursively there, and the implicit default constructor is |
5358 | // defined as deleted in the problematic cases. |
5359 | if (!S.getLangOpts().CPlusPlus11 && |
5360 | ClassDecl->hasUninitializedReferenceMember()) { |
5361 | Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference); |
5362 | return; |
5363 | } |
5364 | |
5365 | // If this is list-value-initialization, pass the empty init list on when |
5366 | // building the constructor call. This affects the semantics of a few |
5367 | // things (such as whether an explicit default constructor can be called). |
5368 | Expr *InitListAsExpr = InitList; |
5369 | MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0); |
5370 | bool InitListSyntax = InitList; |
5371 | |
5372 | // FIXME: Instead of creating a CXXConstructExpr of array type here, |
5373 | // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr. |
5374 | return TryConstructorInitialization( |
5375 | S, Entity, Kind, Args, DestType: T, DestArrayType: Entity.getType(), Sequence, IsListInit: InitListSyntax); |
5376 | } |
5377 | } |
5378 | |
5379 | Sequence.AddZeroInitializationStep(T: Entity.getType()); |
5380 | } |
5381 | |
5382 | /// Attempt default initialization (C++ [dcl.init]p6). |
5383 | static void TryDefaultInitialization(Sema &S, |
5384 | const InitializedEntity &Entity, |
5385 | const InitializationKind &Kind, |
5386 | InitializationSequence &Sequence) { |
5387 | assert(Kind.getKind() == InitializationKind::IK_Default); |
5388 | |
5389 | // C++ [dcl.init]p6: |
5390 | // To default-initialize an object of type T means: |
5391 | // - if T is an array type, each element is default-initialized; |
5392 | QualType DestType = S.Context.getBaseElementType(QT: Entity.getType()); |
5393 | |
5394 | // - if T is a (possibly cv-qualified) class type (Clause 9), the default |
5395 | // constructor for T is called (and the initialization is ill-formed if |
5396 | // T has no accessible default constructor); |
5397 | if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) { |
5398 | TryConstructorInitialization(S, Entity, Kind, Args: std::nullopt, DestType, |
5399 | DestArrayType: Entity.getType(), Sequence); |
5400 | return; |
5401 | } |
5402 | |
5403 | // - otherwise, no initialization is performed. |
5404 | |
5405 | // If a program calls for the default initialization of an object of |
5406 | // a const-qualified type T, T shall be a class type with a user-provided |
5407 | // default constructor. |
5408 | if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) { |
5409 | if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity)) |
5410 | Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); |
5411 | return; |
5412 | } |
5413 | |
5414 | // If the destination type has a lifetime property, zero-initialize it. |
5415 | if (DestType.getQualifiers().hasObjCLifetime()) { |
5416 | Sequence.AddZeroInitializationStep(T: Entity.getType()); |
5417 | return; |
5418 | } |
5419 | } |
5420 | |
5421 | static void TryOrBuildParenListInitialization( |
5422 | Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, |
5423 | ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly, |
5424 | ExprResult *Result = nullptr) { |
5425 | unsigned EntityIndexToProcess = 0; |
5426 | SmallVector<Expr *, 4> InitExprs; |
5427 | QualType ResultType; |
5428 | Expr *ArrayFiller = nullptr; |
5429 | FieldDecl *InitializedFieldInUnion = nullptr; |
5430 | |
5431 | auto HandleInitializedEntity = [&](const InitializedEntity &SubEntity, |
5432 | const InitializationKind &SubKind, |
5433 | Expr *Arg, Expr **InitExpr = nullptr) { |
5434 | InitializationSequence IS = InitializationSequence( |
5435 | S, SubEntity, SubKind, Arg ? MultiExprArg(Arg) : std::nullopt); |
5436 | |
5437 | if (IS.Failed()) { |
5438 | if (!VerifyOnly) { |
5439 | IS.Diagnose(S, Entity: SubEntity, Kind: SubKind, Args: Arg ? ArrayRef(Arg) : std::nullopt); |
5440 | } else { |
5441 | Sequence.SetFailed( |
5442 | InitializationSequence::FK_ParenthesizedListInitFailed); |
5443 | } |
5444 | |
5445 | return false; |
5446 | } |
5447 | if (!VerifyOnly) { |
5448 | ExprResult ER; |
5449 | ER = IS.Perform(S, Entity: SubEntity, Kind: SubKind, |
5450 | Args: Arg ? MultiExprArg(Arg) : std::nullopt); |
5451 | if (InitExpr) |
5452 | *InitExpr = ER.get(); |
5453 | else |
5454 | InitExprs.push_back(Elt: ER.get()); |
5455 | } |
5456 | return true; |
5457 | }; |
5458 | |
5459 | if (const ArrayType *AT = |
5460 | S.getASTContext().getAsArrayType(T: Entity.getType())) { |
5461 | SmallVector<InitializedEntity, 4> ElementEntities; |
5462 | uint64_t ArrayLength; |
5463 | // C++ [dcl.init]p16.5 |
5464 | // if the destination type is an array, the object is initialized as |
5465 | // follows. Let x1, . . . , xk be the elements of the expression-list. If |
5466 | // the destination type is an array of unknown bound, it is defined as |
5467 | // having k elements. |
5468 | if (const ConstantArrayType *CAT = |
5469 | S.getASTContext().getAsConstantArrayType(T: Entity.getType())) { |
5470 | ArrayLength = CAT->getSize().getZExtValue(); |
5471 | ResultType = Entity.getType(); |
5472 | } else if (const VariableArrayType *VAT = |
5473 | S.getASTContext().getAsVariableArrayType(T: Entity.getType())) { |
5474 | // Braced-initialization of variable array types is not allowed, even if |
5475 | // the size is greater than or equal to the number of args, so we don't |
5476 | // allow them to be initialized via parenthesized aggregate initialization |
5477 | // either. |
5478 | const Expr *SE = VAT->getSizeExpr(); |
5479 | S.Diag(SE->getBeginLoc(), diag::err_variable_object_no_init) |
5480 | << SE->getSourceRange(); |
5481 | return; |
5482 | } else { |
5483 | assert(isa<IncompleteArrayType>(Entity.getType())); |
5484 | ArrayLength = Args.size(); |
5485 | } |
5486 | EntityIndexToProcess = ArrayLength; |
5487 | |
5488 | // ...the ith array element is copy-initialized with xi for each |
5489 | // 1 <= i <= k |
5490 | for (Expr *E : Args) { |
5491 | InitializedEntity SubEntity = InitializedEntity::InitializeElement( |
5492 | Context&: S.getASTContext(), Index: EntityIndexToProcess, Parent: Entity); |
5493 | InitializationKind SubKind = InitializationKind::CreateForInit( |
5494 | Loc: E->getExprLoc(), /*isDirectInit=*/DirectInit: false, Init: E); |
5495 | if (!HandleInitializedEntity(SubEntity, SubKind, E)) |
5496 | return; |
5497 | } |
5498 | // ...and value-initialized for each k < i <= n; |
5499 | if (ArrayLength > Args.size() || Entity.isVariableLengthArrayNew()) { |
5500 | InitializedEntity SubEntity = InitializedEntity::InitializeElement( |
5501 | Context&: S.getASTContext(), Index: Args.size(), Parent: Entity); |
5502 | InitializationKind SubKind = InitializationKind::CreateValue( |
5503 | InitLoc: Kind.getLocation(), LParenLoc: Kind.getLocation(), RParenLoc: Kind.getLocation(), isImplicit: true); |
5504 | if (!HandleInitializedEntity(SubEntity, SubKind, nullptr, &ArrayFiller)) |
5505 | return; |
5506 | } |
5507 | |
5508 | if (ResultType.isNull()) { |
5509 | ResultType = S.Context.getConstantArrayType( |
5510 | EltTy: AT->getElementType(), ArySize: llvm::APInt(/*numBits=*/32, ArrayLength), |
5511 | /*SizeExpr=*/nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0); |
5512 | } |
5513 | } else if (auto *RT = Entity.getType()->getAs<RecordType>()) { |
5514 | bool IsUnion = RT->isUnionType(); |
5515 | const CXXRecordDecl *RD = cast<CXXRecordDecl>(Val: RT->getDecl()); |
5516 | if (RD->isInvalidDecl()) { |
5517 | // Exit early to avoid confusion when processing members. |
5518 | // We do the same for braced list initialization in |
5519 | // `CheckStructUnionTypes`. |
5520 | Sequence.SetFailed( |
5521 | clang::InitializationSequence::FK_ParenthesizedListInitFailed); |
5522 | return; |
5523 | } |
5524 | |
5525 | if (!IsUnion) { |
5526 | for (const CXXBaseSpecifier &Base : RD->bases()) { |
5527 | InitializedEntity SubEntity = InitializedEntity::InitializeBase( |
5528 | Context&: S.getASTContext(), Base: &Base, IsInheritedVirtualBase: false, Parent: &Entity); |
5529 | if (EntityIndexToProcess < Args.size()) { |
5530 | // C++ [dcl.init]p16.6.2.2. |
5531 | // ...the object is initialized is follows. Let e1, ..., en be the |
5532 | // elements of the aggregate([dcl.init.aggr]). Let x1, ..., xk be |
5533 | // the elements of the expression-list...The element ei is |
5534 | // copy-initialized with xi for 1 <= i <= k. |
5535 | Expr *E = Args[EntityIndexToProcess]; |
5536 | InitializationKind SubKind = InitializationKind::CreateForInit( |
5537 | Loc: E->getExprLoc(), /*isDirectInit=*/DirectInit: false, Init: E); |
5538 | if (!HandleInitializedEntity(SubEntity, SubKind, E)) |
5539 | return; |
5540 | } else { |
5541 | // We've processed all of the args, but there are still base classes |
5542 | // that have to be initialized. |
5543 | // C++ [dcl.init]p17.6.2.2 |
5544 | // The remaining elements...otherwise are value initialzed |
5545 | InitializationKind SubKind = InitializationKind::CreateValue( |
5546 | InitLoc: Kind.getLocation(), LParenLoc: Kind.getLocation(), RParenLoc: Kind.getLocation(), |
5547 | /*IsImplicit=*/isImplicit: true); |
5548 | if (!HandleInitializedEntity(SubEntity, SubKind, nullptr)) |
5549 | return; |
5550 | } |
5551 | EntityIndexToProcess++; |
5552 | } |
5553 | } |
5554 | |
5555 | for (FieldDecl *FD : RD->fields()) { |
5556 | // Unnamed bitfields should not be initialized at all, either with an arg |
5557 | // or by default. |
5558 | if (FD->isUnnamedBitfield()) |
5559 | continue; |
5560 | |
5561 | InitializedEntity SubEntity = |
5562 | InitializedEntity::InitializeMemberFromParenAggInit(FD); |
5563 | |
5564 | if (EntityIndexToProcess < Args.size()) { |
5565 | // ...The element ei is copy-initialized with xi for 1 <= i <= k. |
5566 | Expr *E = Args[EntityIndexToProcess]; |
5567 | |
5568 | // Incomplete array types indicate flexible array members. Do not allow |
5569 | // paren list initializations of structs with these members, as GCC |
5570 | // doesn't either. |
5571 | if (FD->getType()->isIncompleteArrayType()) { |
5572 | if (!VerifyOnly) { |
5573 | S.Diag(E->getBeginLoc(), diag::err_flexible_array_init) |
5574 | << SourceRange(E->getBeginLoc(), E->getEndLoc()); |
5575 | S.Diag(FD->getLocation(), diag::note_flexible_array_member) << FD; |
5576 | } |
5577 | Sequence.SetFailed( |
5578 | InitializationSequence::FK_ParenthesizedListInitFailed); |
5579 | return; |
5580 | } |
5581 | |
5582 | InitializationKind SubKind = InitializationKind::CreateForInit( |
5583 | E->getExprLoc(), /*isDirectInit=*/false, E); |
5584 | if (!HandleInitializedEntity(SubEntity, SubKind, E)) |
5585 | return; |
5586 | |
5587 | // Unions should have only one initializer expression, so we bail out |
5588 | // after processing the first field. If there are more initializers then |
5589 | // it will be caught when we later check whether EntityIndexToProcess is |
5590 | // less than Args.size(); |
5591 | if (IsUnion) { |
5592 | InitializedFieldInUnion = FD; |
5593 | EntityIndexToProcess = 1; |
5594 | break; |
5595 | } |
5596 | } else { |
5597 | // We've processed all of the args, but there are still members that |
5598 | // have to be initialized. |
5599 | if (FD->hasInClassInitializer()) { |
5600 | if (!VerifyOnly) { |
5601 | // C++ [dcl.init]p16.6.2.2 |
5602 | // The remaining elements are initialized with their default |
5603 | // member initializers, if any |
5604 | ExprResult DIE = S.BuildCXXDefaultInitExpr( |
5605 | Kind.getParenOrBraceRange().getEnd(), FD); |
5606 | if (DIE.isInvalid()) |
5607 | return; |
5608 | S.checkInitializerLifetime(SubEntity, DIE.get()); |
5609 | InitExprs.push_back(DIE.get()); |
5610 | } |
5611 | } else { |
5612 | // C++ [dcl.init]p17.6.2.2 |
5613 | // The remaining elements...otherwise are value initialzed |
5614 | if (FD->getType()->isReferenceType()) { |
5615 | Sequence.SetFailed( |
5616 | InitializationSequence::FK_ParenthesizedListInitFailed); |
5617 | if (!VerifyOnly) { |
5618 | SourceRange SR = Kind.getParenOrBraceRange(); |
5619 | S.Diag(SR.getEnd(), diag::err_init_reference_member_uninitialized) |
5620 | << FD->getType() << SR; |
5621 | S.Diag(FD->getLocation(), diag::note_uninit_reference_member); |
5622 | } |
5623 | return; |
5624 | } |
5625 | InitializationKind SubKind = InitializationKind::CreateValue( |
5626 | Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true); |
5627 | if (!HandleInitializedEntity(SubEntity, SubKind, nullptr)) |
5628 | return; |
5629 | } |
5630 | } |
5631 | EntityIndexToProcess++; |
5632 | } |
5633 | ResultType = Entity.getType(); |
5634 | } |
5635 | |
5636 | // Not all of the args have been processed, so there must've been more args |
5637 | // than were required to initialize the element. |
5638 | if (EntityIndexToProcess < Args.size()) { |
5639 | Sequence.SetFailed(InitializationSequence::FK_ParenthesizedListInitFailed); |
5640 | if (!VerifyOnly) { |
5641 | QualType T = Entity.getType(); |
5642 | int InitKind = T->isArrayType() ? 0 : T->isUnionType() ? 3 : 4; |
5643 | SourceRange ExcessInitSR(Args[EntityIndexToProcess]->getBeginLoc(), |
5644 | Args.back()->getEndLoc()); |
5645 | S.Diag(Kind.getLocation(), diag::err_excess_initializers) |
5646 | << InitKind << ExcessInitSR; |
5647 | } |
5648 | return; |
5649 | } |
5650 | |
5651 | if (VerifyOnly) { |
5652 | Sequence.setSequenceKind(InitializationSequence::NormalSequence); |
5653 | Sequence.AddParenthesizedListInitStep(T: Entity.getType()); |
5654 | } else if (Result) { |
5655 | SourceRange SR = Kind.getParenOrBraceRange(); |
5656 | auto *CPLIE = CXXParenListInitExpr::Create( |
5657 | C&: S.getASTContext(), Args: InitExprs, T: ResultType, NumUserSpecifiedExprs: Args.size(), |
5658 | InitLoc: Kind.getLocation(), LParenLoc: SR.getBegin(), RParenLoc: SR.getEnd()); |
5659 | if (ArrayFiller) |
5660 | CPLIE->setArrayFiller(ArrayFiller); |
5661 | if (InitializedFieldInUnion) |
5662 | CPLIE->setInitializedFieldInUnion(InitializedFieldInUnion); |
5663 | *Result = CPLIE; |
5664 | S.Diag(Kind.getLocation(), |
5665 | diag::warn_cxx17_compat_aggregate_init_paren_list) |
5666 | << Kind.getLocation() << SR << ResultType; |
5667 | } |
5668 | } |
5669 | |
5670 | /// Attempt a user-defined conversion between two types (C++ [dcl.init]), |
5671 | /// which enumerates all conversion functions and performs overload resolution |
5672 | /// to select the best. |
5673 | static void TryUserDefinedConversion(Sema &S, |
5674 | QualType DestType, |
5675 | const InitializationKind &Kind, |
5676 | Expr *Initializer, |
5677 | InitializationSequence &Sequence, |
5678 | bool TopLevelOfInitList) { |
5679 | assert(!DestType->isReferenceType() && "References are handled elsewhere" ); |
5680 | QualType SourceType = Initializer->getType(); |
5681 | assert((DestType->isRecordType() || SourceType->isRecordType()) && |
5682 | "Must have a class type to perform a user-defined conversion" ); |
5683 | |
5684 | // Build the candidate set directly in the initialization sequence |
5685 | // structure, so that it will persist if we fail. |
5686 | OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); |
5687 | CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion); |
5688 | CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace()); |
5689 | |
5690 | // Determine whether we are allowed to call explicit constructors or |
5691 | // explicit conversion operators. |
5692 | bool AllowExplicit = Kind.AllowExplicit(); |
5693 | |
5694 | if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) { |
5695 | // The type we're converting to is a class type. Enumerate its constructors |
5696 | // to see if there is a suitable conversion. |
5697 | CXXRecordDecl *DestRecordDecl |
5698 | = cast<CXXRecordDecl>(Val: DestRecordType->getDecl()); |
5699 | |
5700 | // Try to complete the type we're converting to. |
5701 | if (S.isCompleteType(Loc: Kind.getLocation(), T: DestType)) { |
5702 | for (NamedDecl *D : S.LookupConstructors(Class: DestRecordDecl)) { |
5703 | auto Info = getConstructorInfo(ND: D); |
5704 | if (!Info.Constructor) |
5705 | continue; |
5706 | |
5707 | if (!Info.Constructor->isInvalidDecl() && |
5708 | Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) { |
5709 | if (Info.ConstructorTmpl) |
5710 | S.AddTemplateOverloadCandidate( |
5711 | FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl, |
5712 | /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: Initializer, CandidateSet, |
5713 | /*SuppressUserConversions=*/true, |
5714 | /*PartialOverloading*/ false, AllowExplicit); |
5715 | else |
5716 | S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, |
5717 | Initializer, CandidateSet, |
5718 | /*SuppressUserConversions=*/true, |
5719 | /*PartialOverloading*/ false, AllowExplicit); |
5720 | } |
5721 | } |
5722 | } |
5723 | } |
5724 | |
5725 | SourceLocation DeclLoc = Initializer->getBeginLoc(); |
5726 | |
5727 | if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) { |
5728 | // The type we're converting from is a class type, enumerate its conversion |
5729 | // functions. |
5730 | |
5731 | // We can only enumerate the conversion functions for a complete type; if |
5732 | // the type isn't complete, simply skip this step. |
5733 | if (S.isCompleteType(Loc: DeclLoc, T: SourceType)) { |
5734 | CXXRecordDecl *SourceRecordDecl |
5735 | = cast<CXXRecordDecl>(Val: SourceRecordType->getDecl()); |
5736 | |
5737 | const auto &Conversions = |
5738 | SourceRecordDecl->getVisibleConversionFunctions(); |
5739 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { |
5740 | NamedDecl *D = *I; |
5741 | CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); |
5742 | if (isa<UsingShadowDecl>(Val: D)) |
5743 | D = cast<UsingShadowDecl>(Val: D)->getTargetDecl(); |
5744 | |
5745 | FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D); |
5746 | CXXConversionDecl *Conv; |
5747 | if (ConvTemplate) |
5748 | Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl()); |
5749 | else |
5750 | Conv = cast<CXXConversionDecl>(Val: D); |
5751 | |
5752 | if (ConvTemplate) |
5753 | S.AddTemplateConversionCandidate( |
5754 | FunctionTemplate: ConvTemplate, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer, ToType: DestType, |
5755 | CandidateSet, AllowObjCConversionOnExplicit: AllowExplicit, AllowExplicit); |
5756 | else |
5757 | S.AddConversionCandidate(Conversion: Conv, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer, |
5758 | ToType: DestType, CandidateSet, AllowObjCConversionOnExplicit: AllowExplicit, |
5759 | AllowExplicit); |
5760 | } |
5761 | } |
5762 | } |
5763 | |
5764 | // Perform overload resolution. If it fails, return the failed result. |
5765 | OverloadCandidateSet::iterator Best; |
5766 | if (OverloadingResult Result |
5767 | = CandidateSet.BestViableFunction(S, Loc: DeclLoc, Best)) { |
5768 | Sequence.SetOverloadFailure( |
5769 | Failure: InitializationSequence::FK_UserConversionOverloadFailed, Result); |
5770 | |
5771 | // [class.copy.elision]p3: |
5772 | // In some copy-initialization contexts, a two-stage overload resolution |
5773 | // is performed. |
5774 | // If the first overload resolution selects a deleted function, we also |
5775 | // need the initialization sequence to decide whether to perform the second |
5776 | // overload resolution. |
5777 | if (!(Result == OR_Deleted && |
5778 | Kind.getKind() == InitializationKind::IK_Copy)) |
5779 | return; |
5780 | } |
5781 | |
5782 | FunctionDecl *Function = Best->Function; |
5783 | Function->setReferenced(); |
5784 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
5785 | |
5786 | if (isa<CXXConstructorDecl>(Val: Function)) { |
5787 | // Add the user-defined conversion step. Any cv-qualification conversion is |
5788 | // subsumed by the initialization. Per DR5, the created temporary is of the |
5789 | // cv-unqualified type of the destination. |
5790 | Sequence.AddUserConversionStep(Function, FoundDecl: Best->FoundDecl, |
5791 | T: DestType.getUnqualifiedType(), |
5792 | HadMultipleCandidates); |
5793 | |
5794 | // C++14 and before: |
5795 | // - if the function is a constructor, the call initializes a temporary |
5796 | // of the cv-unqualified version of the destination type. The [...] |
5797 | // temporary [...] is then used to direct-initialize, according to the |
5798 | // rules above, the object that is the destination of the |
5799 | // copy-initialization. |
5800 | // Note that this just performs a simple object copy from the temporary. |
5801 | // |
5802 | // C++17: |
5803 | // - if the function is a constructor, the call is a prvalue of the |
5804 | // cv-unqualified version of the destination type whose return object |
5805 | // is initialized by the constructor. The call is used to |
5806 | // direct-initialize, according to the rules above, the object that |
5807 | // is the destination of the copy-initialization. |
5808 | // Therefore we need to do nothing further. |
5809 | // |
5810 | // FIXME: Mark this copy as extraneous. |
5811 | if (!S.getLangOpts().CPlusPlus17) |
5812 | Sequence.AddFinalCopy(T: DestType); |
5813 | else if (DestType.hasQualifiers()) |
5814 | Sequence.AddQualificationConversionStep(Ty: DestType, VK: VK_PRValue); |
5815 | return; |
5816 | } |
5817 | |
5818 | // Add the user-defined conversion step that calls the conversion function. |
5819 | QualType ConvType = Function->getCallResultType(); |
5820 | Sequence.AddUserConversionStep(Function, FoundDecl: Best->FoundDecl, T: ConvType, |
5821 | HadMultipleCandidates); |
5822 | |
5823 | if (ConvType->getAs<RecordType>()) { |
5824 | // The call is used to direct-initialize [...] the object that is the |
5825 | // destination of the copy-initialization. |
5826 | // |
5827 | // In C++17, this does not call a constructor if we enter /17.6.1: |
5828 | // - If the initializer expression is a prvalue and the cv-unqualified |
5829 | // version of the source type is the same as the class of the |
5830 | // destination [... do not make an extra copy] |
5831 | // |
5832 | // FIXME: Mark this copy as extraneous. |
5833 | if (!S.getLangOpts().CPlusPlus17 || |
5834 | Function->getReturnType()->isReferenceType() || |
5835 | !S.Context.hasSameUnqualifiedType(T1: ConvType, T2: DestType)) |
5836 | Sequence.AddFinalCopy(T: DestType); |
5837 | else if (!S.Context.hasSameType(T1: ConvType, T2: DestType)) |
5838 | Sequence.AddQualificationConversionStep(Ty: DestType, VK: VK_PRValue); |
5839 | return; |
5840 | } |
5841 | |
5842 | // If the conversion following the call to the conversion function |
5843 | // is interesting, add it as a separate step. |
5844 | if (Best->FinalConversion.First || Best->FinalConversion.Second || |
5845 | Best->FinalConversion.Third) { |
5846 | ImplicitConversionSequence ICS; |
5847 | ICS.setStandard(); |
5848 | ICS.Standard = Best->FinalConversion; |
5849 | Sequence.AddConversionSequenceStep(ICS, T: DestType, TopLevelOfInitList); |
5850 | } |
5851 | } |
5852 | |
5853 | /// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>, |
5854 | /// a function with a pointer return type contains a 'return false;' statement. |
5855 | /// In C++11, 'false' is not a null pointer, so this breaks the build of any |
5856 | /// code using that header. |
5857 | /// |
5858 | /// Work around this by treating 'return false;' as zero-initializing the result |
5859 | /// if it's used in a pointer-returning function in a system header. |
5860 | static bool isLibstdcxxPointerReturnFalseHack(Sema &S, |
5861 | const InitializedEntity &Entity, |
5862 | const Expr *Init) { |
5863 | return S.getLangOpts().CPlusPlus11 && |
5864 | Entity.getKind() == InitializedEntity::EK_Result && |
5865 | Entity.getType()->isPointerType() && |
5866 | isa<CXXBoolLiteralExpr>(Val: Init) && |
5867 | !cast<CXXBoolLiteralExpr>(Val: Init)->getValue() && |
5868 | S.getSourceManager().isInSystemHeader(Loc: Init->getExprLoc()); |
5869 | } |
5870 | |
5871 | /// The non-zero enum values here are indexes into diagnostic alternatives. |
5872 | enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar }; |
5873 | |
5874 | /// Determines whether this expression is an acceptable ICR source. |
5875 | static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e, |
5876 | bool isAddressOf, bool &isWeakAccess) { |
5877 | // Skip parens. |
5878 | e = e->IgnoreParens(); |
5879 | |
5880 | // Skip address-of nodes. |
5881 | if (UnaryOperator *op = dyn_cast<UnaryOperator>(Val: e)) { |
5882 | if (op->getOpcode() == UO_AddrOf) |
5883 | return isInvalidICRSource(C, e: op->getSubExpr(), /*addressof*/ isAddressOf: true, |
5884 | isWeakAccess); |
5885 | |
5886 | // Skip certain casts. |
5887 | } else if (CastExpr *ce = dyn_cast<CastExpr>(Val: e)) { |
5888 | switch (ce->getCastKind()) { |
5889 | case CK_Dependent: |
5890 | case CK_BitCast: |
5891 | case CK_LValueBitCast: |
5892 | case CK_NoOp: |
5893 | return isInvalidICRSource(C, e: ce->getSubExpr(), isAddressOf, isWeakAccess); |
5894 | |
5895 | case CK_ArrayToPointerDecay: |
5896 | return IIK_nonscalar; |
5897 | |
5898 | case CK_NullToPointer: |
5899 | return IIK_okay; |
5900 | |
5901 | default: |
5902 | break; |
5903 | } |
5904 | |
5905 | // If we have a declaration reference, it had better be a local variable. |
5906 | } else if (isa<DeclRefExpr>(Val: e)) { |
5907 | // set isWeakAccess to true, to mean that there will be an implicit |
5908 | // load which requires a cleanup. |
5909 | if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak) |
5910 | isWeakAccess = true; |
5911 | |
5912 | if (!isAddressOf) return IIK_nonlocal; |
5913 | |
5914 | VarDecl *var = dyn_cast<VarDecl>(Val: cast<DeclRefExpr>(Val: e)->getDecl()); |
5915 | if (!var) return IIK_nonlocal; |
5916 | |
5917 | return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal); |
5918 | |
5919 | // If we have a conditional operator, check both sides. |
5920 | } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(Val: e)) { |
5921 | if (InvalidICRKind iik = isInvalidICRSource(C, e: cond->getLHS(), isAddressOf, |
5922 | isWeakAccess)) |
5923 | return iik; |
5924 | |
5925 | return isInvalidICRSource(C, e: cond->getRHS(), isAddressOf, isWeakAccess); |
5926 | |
5927 | // These are never scalar. |
5928 | } else if (isa<ArraySubscriptExpr>(Val: e)) { |
5929 | return IIK_nonscalar; |
5930 | |
5931 | // Otherwise, it needs to be a null pointer constant. |
5932 | } else { |
5933 | return (e->isNullPointerConstant(Ctx&: C, NPC: Expr::NPC_ValueDependentIsNull) |
5934 | ? IIK_okay : IIK_nonlocal); |
5935 | } |
5936 | |
5937 | return IIK_nonlocal; |
5938 | } |
5939 | |
5940 | /// Check whether the given expression is a valid operand for an |
5941 | /// indirect copy/restore. |
5942 | static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) { |
5943 | assert(src->isPRValue()); |
5944 | bool isWeakAccess = false; |
5945 | InvalidICRKind iik = isInvalidICRSource(C&: S.Context, e: src, isAddressOf: false, isWeakAccess); |
5946 | // If isWeakAccess to true, there will be an implicit |
5947 | // load which requires a cleanup. |
5948 | if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess) |
5949 | S.Cleanup.setExprNeedsCleanups(true); |
5950 | |
5951 | if (iik == IIK_okay) return; |
5952 | |
5953 | S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback) |
5954 | << ((unsigned) iik - 1) // shift index into diagnostic explanations |
5955 | << src->getSourceRange(); |
5956 | } |
5957 | |
5958 | /// Determine whether we have compatible array types for the |
5959 | /// purposes of GNU by-copy array initialization. |
5960 | static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest, |
5961 | const ArrayType *Source) { |
5962 | // If the source and destination array types are equivalent, we're |
5963 | // done. |
5964 | if (Context.hasSameType(T1: QualType(Dest, 0), T2: QualType(Source, 0))) |
5965 | return true; |
5966 | |
5967 | // Make sure that the element types are the same. |
5968 | if (!Context.hasSameType(T1: Dest->getElementType(), T2: Source->getElementType())) |
5969 | return false; |
5970 | |
5971 | // The only mismatch we allow is when the destination is an |
5972 | // incomplete array type and the source is a constant array type. |
5973 | return Source->isConstantArrayType() && Dest->isIncompleteArrayType(); |
5974 | } |
5975 | |
5976 | static bool tryObjCWritebackConversion(Sema &S, |
5977 | InitializationSequence &Sequence, |
5978 | const InitializedEntity &Entity, |
5979 | Expr *Initializer) { |
5980 | bool ArrayDecay = false; |
5981 | QualType ArgType = Initializer->getType(); |
5982 | QualType ArgPointee; |
5983 | if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(T: ArgType)) { |
5984 | ArrayDecay = true; |
5985 | ArgPointee = ArgArrayType->getElementType(); |
5986 | ArgType = S.Context.getPointerType(T: ArgPointee); |
5987 | } |
5988 | |
5989 | // Handle write-back conversion. |
5990 | QualType ConvertedArgType; |
5991 | if (!S.isObjCWritebackConversion(FromType: ArgType, ToType: Entity.getType(), |
5992 | ConvertedType&: ConvertedArgType)) |
5993 | return false; |
5994 | |
5995 | // We should copy unless we're passing to an argument explicitly |
5996 | // marked 'out'. |
5997 | bool ShouldCopy = true; |
5998 | if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Val: Entity.getDecl())) |
5999 | ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); |
6000 | |
6001 | // Do we need an lvalue conversion? |
6002 | if (ArrayDecay || Initializer->isGLValue()) { |
6003 | ImplicitConversionSequence ICS; |
6004 | ICS.setStandard(); |
6005 | ICS.Standard.setAsIdentityConversion(); |
6006 | |
6007 | QualType ResultType; |
6008 | if (ArrayDecay) { |
6009 | ICS.Standard.First = ICK_Array_To_Pointer; |
6010 | ResultType = S.Context.getPointerType(T: ArgPointee); |
6011 | } else { |
6012 | ICS.Standard.First = ICK_Lvalue_To_Rvalue; |
6013 | ResultType = Initializer->getType().getNonLValueExprType(Context: S.Context); |
6014 | } |
6015 | |
6016 | Sequence.AddConversionSequenceStep(ICS, T: ResultType); |
6017 | } |
6018 | |
6019 | Sequence.AddPassByIndirectCopyRestoreStep(type: Entity.getType(), shouldCopy: ShouldCopy); |
6020 | return true; |
6021 | } |
6022 | |
6023 | static bool TryOCLSamplerInitialization(Sema &S, |
6024 | InitializationSequence &Sequence, |
6025 | QualType DestType, |
6026 | Expr *Initializer) { |
6027 | if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() || |
6028 | (!Initializer->isIntegerConstantExpr(Ctx: S.Context) && |
6029 | !Initializer->getType()->isSamplerT())) |
6030 | return false; |
6031 | |
6032 | Sequence.AddOCLSamplerInitStep(T: DestType); |
6033 | return true; |
6034 | } |
6035 | |
6036 | static bool IsZeroInitializer(Expr *Initializer, Sema &S) { |
6037 | return Initializer->isIntegerConstantExpr(Ctx: S.getASTContext()) && |
6038 | (Initializer->EvaluateKnownConstInt(Ctx: S.getASTContext()) == 0); |
6039 | } |
6040 | |
6041 | static bool TryOCLZeroOpaqueTypeInitialization(Sema &S, |
6042 | InitializationSequence &Sequence, |
6043 | QualType DestType, |
6044 | Expr *Initializer) { |
6045 | if (!S.getLangOpts().OpenCL) |
6046 | return false; |
6047 | |
6048 | // |
6049 | // OpenCL 1.2 spec, s6.12.10 |
6050 | // |
6051 | // The event argument can also be used to associate the |
6052 | // async_work_group_copy with a previous async copy allowing |
6053 | // an event to be shared by multiple async copies; otherwise |
6054 | // event should be zero. |
6055 | // |
6056 | if (DestType->isEventT() || DestType->isQueueT()) { |
6057 | if (!IsZeroInitializer(Initializer, S)) |
6058 | return false; |
6059 | |
6060 | Sequence.AddOCLZeroOpaqueTypeStep(T: DestType); |
6061 | return true; |
6062 | } |
6063 | |
6064 | // We should allow zero initialization for all types defined in the |
6065 | // cl_intel_device_side_avc_motion_estimation extension, except |
6066 | // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t. |
6067 | if (S.getOpenCLOptions().isAvailableOption( |
6068 | Ext: "cl_intel_device_side_avc_motion_estimation" , LO: S.getLangOpts()) && |
6069 | DestType->isOCLIntelSubgroupAVCType()) { |
6070 | if (DestType->isOCLIntelSubgroupAVCMcePayloadType() || |
6071 | DestType->isOCLIntelSubgroupAVCMceResultType()) |
6072 | return false; |
6073 | if (!IsZeroInitializer(Initializer, S)) |
6074 | return false; |
6075 | |
6076 | Sequence.AddOCLZeroOpaqueTypeStep(T: DestType); |
6077 | return true; |
6078 | } |
6079 | |
6080 | return false; |
6081 | } |
6082 | |
6083 | InitializationSequence::InitializationSequence( |
6084 | Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, |
6085 | MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid) |
6086 | : FailedOverloadResult(OR_Success), |
6087 | FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) { |
6088 | InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList, |
6089 | TreatUnavailableAsInvalid); |
6090 | } |
6091 | |
6092 | /// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the |
6093 | /// address of that function, this returns true. Otherwise, it returns false. |
6094 | static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) { |
6095 | auto *DRE = dyn_cast<DeclRefExpr>(Val: E); |
6096 | if (!DRE || !isa<FunctionDecl>(Val: DRE->getDecl())) |
6097 | return false; |
6098 | |
6099 | return !S.checkAddressOfFunctionIsAvailable( |
6100 | Function: cast<FunctionDecl>(Val: DRE->getDecl())); |
6101 | } |
6102 | |
6103 | /// Determine whether we can perform an elementwise array copy for this kind |
6104 | /// of entity. |
6105 | static bool canPerformArrayCopy(const InitializedEntity &Entity) { |
6106 | switch (Entity.getKind()) { |
6107 | case InitializedEntity::EK_LambdaCapture: |
6108 | // C++ [expr.prim.lambda]p24: |
6109 | // For array members, the array elements are direct-initialized in |
6110 | // increasing subscript order. |
6111 | return true; |
6112 | |
6113 | case InitializedEntity::EK_Variable: |
6114 | // C++ [dcl.decomp]p1: |
6115 | // [...] each element is copy-initialized or direct-initialized from the |
6116 | // corresponding element of the assignment-expression [...] |
6117 | return isa<DecompositionDecl>(Val: Entity.getDecl()); |
6118 | |
6119 | case InitializedEntity::EK_Member: |
6120 | // C++ [class.copy.ctor]p14: |
6121 | // - if the member is an array, each element is direct-initialized with |
6122 | // the corresponding subobject of x |
6123 | return Entity.isImplicitMemberInitializer(); |
6124 | |
6125 | case InitializedEntity::EK_ArrayElement: |
6126 | // All the above cases are intended to apply recursively, even though none |
6127 | // of them actually say that. |
6128 | if (auto *E = Entity.getParent()) |
6129 | return canPerformArrayCopy(Entity: *E); |
6130 | break; |
6131 | |
6132 | default: |
6133 | break; |
6134 | } |
6135 | |
6136 | return false; |
6137 | } |
6138 | |
6139 | void InitializationSequence::InitializeFrom(Sema &S, |
6140 | const InitializedEntity &Entity, |
6141 | const InitializationKind &Kind, |
6142 | MultiExprArg Args, |
6143 | bool TopLevelOfInitList, |
6144 | bool TreatUnavailableAsInvalid) { |
6145 | ASTContext &Context = S.Context; |
6146 | |
6147 | // Eliminate non-overload placeholder types in the arguments. We |
6148 | // need to do this before checking whether types are dependent |
6149 | // because lowering a pseudo-object expression might well give us |
6150 | // something of dependent type. |
6151 | for (unsigned I = 0, E = Args.size(); I != E; ++I) |
6152 | if (Args[I]->getType()->isNonOverloadPlaceholderType()) { |
6153 | // FIXME: should we be doing this here? |
6154 | ExprResult result = S.CheckPlaceholderExpr(E: Args[I]); |
6155 | if (result.isInvalid()) { |
6156 | SetFailed(FK_PlaceholderType); |
6157 | return; |
6158 | } |
6159 | Args[I] = result.get(); |
6160 | } |
6161 | |
6162 | // C++0x [dcl.init]p16: |
6163 | // The semantics of initializers are as follows. The destination type is |
6164 | // the type of the object or reference being initialized and the source |
6165 | // type is the type of the initializer expression. The source type is not |
6166 | // defined when the initializer is a braced-init-list or when it is a |
6167 | // parenthesized list of expressions. |
6168 | QualType DestType = Entity.getType(); |
6169 | |
6170 | if (DestType->isDependentType() || |
6171 | Expr::hasAnyTypeDependentArguments(Exprs: Args)) { |
6172 | SequenceKind = DependentSequence; |
6173 | return; |
6174 | } |
6175 | |
6176 | // Almost everything is a normal sequence. |
6177 | setSequenceKind(NormalSequence); |
6178 | |
6179 | QualType SourceType; |
6180 | Expr *Initializer = nullptr; |
6181 | if (Args.size() == 1) { |
6182 | Initializer = Args[0]; |
6183 | if (S.getLangOpts().ObjC) { |
6184 | if (S.CheckObjCBridgeRelatedConversions(Loc: Initializer->getBeginLoc(), |
6185 | DestType, SrcType: Initializer->getType(), |
6186 | SrcExpr&: Initializer) || |
6187 | S.CheckConversionToObjCLiteral(DstType: DestType, SrcExpr&: Initializer)) |
6188 | Args[0] = Initializer; |
6189 | } |
6190 | if (!isa<InitListExpr>(Val: Initializer)) |
6191 | SourceType = Initializer->getType(); |
6192 | } |
6193 | |
6194 | // - If the initializer is a (non-parenthesized) braced-init-list, the |
6195 | // object is list-initialized (8.5.4). |
6196 | if (Kind.getKind() != InitializationKind::IK_Direct) { |
6197 | if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Val: Initializer)) { |
6198 | TryListInitialization(S, Entity, Kind, InitList, Sequence&: *this, |
6199 | TreatUnavailableAsInvalid); |
6200 | return; |
6201 | } |
6202 | } |
6203 | |
6204 | // - If the destination type is a reference type, see 8.5.3. |
6205 | if (DestType->isReferenceType()) { |
6206 | // C++0x [dcl.init.ref]p1: |
6207 | // A variable declared to be a T& or T&&, that is, "reference to type T" |
6208 | // (8.3.2), shall be initialized by an object, or function, of type T or |
6209 | // by an object that can be converted into a T. |
6210 | // (Therefore, multiple arguments are not permitted.) |
6211 | if (Args.size() != 1) |
6212 | SetFailed(FK_TooManyInitsForReference); |
6213 | // C++17 [dcl.init.ref]p5: |
6214 | // A reference [...] is initialized by an expression [...] as follows: |
6215 | // If the initializer is not an expression, presumably we should reject, |
6216 | // but the standard fails to actually say so. |
6217 | else if (isa<InitListExpr>(Val: Args[0])) |
6218 | SetFailed(FK_ParenthesizedListInitForReference); |
6219 | else |
6220 | TryReferenceInitialization(S, Entity, Kind, Initializer: Args[0], Sequence&: *this, |
6221 | TopLevelOfInitList); |
6222 | return; |
6223 | } |
6224 | |
6225 | // - If the initializer is (), the object is value-initialized. |
6226 | if (Kind.getKind() == InitializationKind::IK_Value || |
6227 | (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) { |
6228 | TryValueInitialization(S, Entity, Kind, Sequence&: *this); |
6229 | return; |
6230 | } |
6231 | |
6232 | // Handle default initialization. |
6233 | if (Kind.getKind() == InitializationKind::IK_Default) { |
6234 | TryDefaultInitialization(S, Entity, Kind, Sequence&: *this); |
6235 | return; |
6236 | } |
6237 | |
6238 | // - If the destination type is an array of characters, an array of |
6239 | // char16_t, an array of char32_t, or an array of wchar_t, and the |
6240 | // initializer is a string literal, see 8.5.2. |
6241 | // - Otherwise, if the destination type is an array, the program is |
6242 | // ill-formed. |
6243 | if (const ArrayType *DestAT = Context.getAsArrayType(T: DestType)) { |
6244 | if (Initializer && isa<VariableArrayType>(Val: DestAT)) { |
6245 | SetFailed(FK_VariableLengthArrayHasInitializer); |
6246 | return; |
6247 | } |
6248 | |
6249 | if (Initializer) { |
6250 | switch (IsStringInit(Init: Initializer, AT: DestAT, Context)) { |
6251 | case SIF_None: |
6252 | TryStringLiteralInitialization(S, Entity, Kind, Initializer, Sequence&: *this); |
6253 | return; |
6254 | case SIF_NarrowStringIntoWideChar: |
6255 | SetFailed(FK_NarrowStringIntoWideCharArray); |
6256 | return; |
6257 | case SIF_WideStringIntoChar: |
6258 | SetFailed(FK_WideStringIntoCharArray); |
6259 | return; |
6260 | case SIF_IncompatWideStringIntoWideChar: |
6261 | SetFailed(FK_IncompatWideStringIntoWideChar); |
6262 | return; |
6263 | case SIF_PlainStringIntoUTF8Char: |
6264 | SetFailed(FK_PlainStringIntoUTF8Char); |
6265 | return; |
6266 | case SIF_UTF8StringIntoPlainChar: |
6267 | SetFailed(FK_UTF8StringIntoPlainChar); |
6268 | return; |
6269 | case SIF_Other: |
6270 | break; |
6271 | } |
6272 | } |
6273 | |
6274 | // Some kinds of initialization permit an array to be initialized from |
6275 | // another array of the same type, and perform elementwise initialization. |
6276 | if (Initializer && isa<ConstantArrayType>(Val: DestAT) && |
6277 | S.Context.hasSameUnqualifiedType(T1: Initializer->getType(), |
6278 | T2: Entity.getType()) && |
6279 | canPerformArrayCopy(Entity)) { |
6280 | // If source is a prvalue, use it directly. |
6281 | if (Initializer->isPRValue()) { |
6282 | AddArrayInitStep(T: DestType, /*IsGNUExtension*/false); |
6283 | return; |
6284 | } |
6285 | |
6286 | // Emit element-at-a-time copy loop. |
6287 | InitializedEntity Element = |
6288 | InitializedEntity::InitializeElement(Context&: S.Context, Index: 0, Parent: Entity); |
6289 | QualType InitEltT = |
6290 | Context.getAsArrayType(T: Initializer->getType())->getElementType(); |
6291 | OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT, |
6292 | Initializer->getValueKind(), |
6293 | Initializer->getObjectKind()); |
6294 | Expr *OVEAsExpr = &OVE; |
6295 | InitializeFrom(S, Entity: Element, Kind, Args: OVEAsExpr, TopLevelOfInitList, |
6296 | TreatUnavailableAsInvalid); |
6297 | if (!Failed()) |
6298 | AddArrayInitLoopStep(T: Entity.getType(), EltT: InitEltT); |
6299 | return; |
6300 | } |
6301 | |
6302 | // Note: as an GNU C extension, we allow initialization of an |
6303 | // array from a compound literal that creates an array of the same |
6304 | // type, so long as the initializer has no side effects. |
6305 | if (!S.getLangOpts().CPlusPlus && Initializer && |
6306 | isa<CompoundLiteralExpr>(Val: Initializer->IgnoreParens()) && |
6307 | Initializer->getType()->isArrayType()) { |
6308 | const ArrayType *SourceAT |
6309 | = Context.getAsArrayType(T: Initializer->getType()); |
6310 | if (!hasCompatibleArrayTypes(Context&: S.Context, Dest: DestAT, Source: SourceAT)) |
6311 | SetFailed(FK_ArrayTypeMismatch); |
6312 | else if (Initializer->HasSideEffects(Ctx: S.Context)) |
6313 | SetFailed(FK_NonConstantArrayInit); |
6314 | else { |
6315 | AddArrayInitStep(T: DestType, /*IsGNUExtension*/true); |
6316 | } |
6317 | } |
6318 | // Note: as a GNU C++ extension, we allow list-initialization of a |
6319 | // class member of array type from a parenthesized initializer list. |
6320 | else if (S.getLangOpts().CPlusPlus && |
6321 | Entity.getKind() == InitializedEntity::EK_Member && |
6322 | Initializer && isa<InitListExpr>(Val: Initializer)) { |
6323 | TryListInitialization(S, Entity, Kind, InitList: cast<InitListExpr>(Val: Initializer), |
6324 | Sequence&: *this, TreatUnavailableAsInvalid); |
6325 | AddParenthesizedArrayInitStep(T: DestType); |
6326 | } else if (S.getLangOpts().CPlusPlus20 && !TopLevelOfInitList && |
6327 | Kind.getKind() == InitializationKind::IK_Direct) |
6328 | TryOrBuildParenListInitialization(S, Entity, Kind, Args, Sequence&: *this, |
6329 | /*VerifyOnly=*/true); |
6330 | else if (DestAT->getElementType()->isCharType()) |
6331 | SetFailed(FK_ArrayNeedsInitListOrStringLiteral); |
6332 | else if (IsWideCharCompatible(T: DestAT->getElementType(), Context)) |
6333 | SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral); |
6334 | else |
6335 | SetFailed(FK_ArrayNeedsInitList); |
6336 | |
6337 | return; |
6338 | } |
6339 | |
6340 | // Determine whether we should consider writeback conversions for |
6341 | // Objective-C ARC. |
6342 | bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount && |
6343 | Entity.isParameterKind(); |
6344 | |
6345 | if (TryOCLSamplerInitialization(S, Sequence&: *this, DestType, Initializer)) |
6346 | return; |
6347 | |
6348 | // We're at the end of the line for C: it's either a write-back conversion |
6349 | // or it's a C assignment. There's no need to check anything else. |
6350 | if (!S.getLangOpts().CPlusPlus) { |
6351 | assert(Initializer && "Initializer must be non-null" ); |
6352 | // If allowed, check whether this is an Objective-C writeback conversion. |
6353 | if (allowObjCWritebackConversion && |
6354 | tryObjCWritebackConversion(S, Sequence&: *this, Entity, Initializer)) { |
6355 | return; |
6356 | } |
6357 | |
6358 | if (TryOCLZeroOpaqueTypeInitialization(S, Sequence&: *this, DestType, Initializer)) |
6359 | return; |
6360 | |
6361 | // Handle initialization in C |
6362 | AddCAssignmentStep(T: DestType); |
6363 | MaybeProduceObjCObject(S, Sequence&: *this, Entity); |
6364 | return; |
6365 | } |
6366 | |
6367 | assert(S.getLangOpts().CPlusPlus); |
6368 | |
6369 | // - If the destination type is a (possibly cv-qualified) class type: |
6370 | if (DestType->isRecordType()) { |
6371 | // - If the initialization is direct-initialization, or if it is |
6372 | // copy-initialization where the cv-unqualified version of the |
6373 | // source type is the same class as, or a derived class of, the |
6374 | // class of the destination, constructors are considered. [...] |
6375 | if (Kind.getKind() == InitializationKind::IK_Direct || |
6376 | (Kind.getKind() == InitializationKind::IK_Copy && |
6377 | (Context.hasSameUnqualifiedType(T1: SourceType, T2: DestType) || |
6378 | (Initializer && S.IsDerivedFrom(Initializer->getBeginLoc(), |
6379 | SourceType, DestType))))) { |
6380 | TryConstructorInitialization(S, Entity, Kind, Args, DestType, DestArrayType: DestType, |
6381 | Sequence&: *this); |
6382 | |
6383 | // We fall back to the "no matching constructor" path if the |
6384 | // failed candidate set has functions other than the three default |
6385 | // constructors. For example, conversion function. |
6386 | if (const auto *RD = |
6387 | dyn_cast<CXXRecordDecl>(Val: DestType->getAs<RecordType>()->getDecl()); |
6388 | // In general, we should call isCompleteType for RD to check its |
6389 | // completeness, we don't call it here as it was already called in the |
6390 | // above TryConstructorInitialization. |
6391 | S.getLangOpts().CPlusPlus20 && RD && RD->hasDefinition() && |
6392 | RD->isAggregate() && Failed() && |
6393 | getFailureKind() == FK_ConstructorOverloadFailed) { |
6394 | // Do not attempt paren list initialization if overload resolution |
6395 | // resolves to a deleted function . |
6396 | // |
6397 | // We may reach this condition if we have a union wrapping a class with |
6398 | // a non-trivial copy or move constructor and we call one of those two |
6399 | // constructors. The union is an aggregate, but the matched constructor |
6400 | // is implicitly deleted, so we need to prevent aggregate initialization |
6401 | // (otherwise, it'll attempt aggregate initialization by initializing |
6402 | // the first element with a reference to the union). |
6403 | OverloadCandidateSet::iterator Best; |
6404 | OverloadingResult OR = getFailedCandidateSet().BestViableFunction( |
6405 | S, Loc: Kind.getLocation(), Best); |
6406 | if (OR != OverloadingResult::OR_Deleted) { |
6407 | // C++20 [dcl.init] 17.6.2.2: |
6408 | // - Otherwise, if no constructor is viable, the destination type is |
6409 | // an |
6410 | // aggregate class, and the initializer is a parenthesized |
6411 | // expression-list. |
6412 | TryOrBuildParenListInitialization(S, Entity, Kind, Args, Sequence&: *this, |
6413 | /*VerifyOnly=*/true); |
6414 | } |
6415 | } |
6416 | } else { |
6417 | // - Otherwise (i.e., for the remaining copy-initialization cases), |
6418 | // user-defined conversion sequences that can convert from the |
6419 | // source type to the destination type or (when a conversion |
6420 | // function is used) to a derived class thereof are enumerated as |
6421 | // described in 13.3.1.4, and the best one is chosen through |
6422 | // overload resolution (13.3). |
6423 | assert(Initializer && "Initializer must be non-null" ); |
6424 | TryUserDefinedConversion(S, DestType, Kind, Initializer, Sequence&: *this, |
6425 | TopLevelOfInitList); |
6426 | } |
6427 | return; |
6428 | } |
6429 | |
6430 | assert(Args.size() >= 1 && "Zero-argument case handled above" ); |
6431 | |
6432 | // For HLSL ext vector types we allow list initialization behavior for C++ |
6433 | // constructor syntax. This is accomplished by converting initialization |
6434 | // arguments an InitListExpr late. |
6435 | if (S.getLangOpts().HLSL && DestType->isExtVectorType() && |
6436 | (SourceType.isNull() || |
6437 | !Context.hasSameUnqualifiedType(T1: SourceType, T2: DestType))) { |
6438 | |
6439 | llvm::SmallVector<Expr *> InitArgs; |
6440 | for (auto *Arg : Args) { |
6441 | if (Arg->getType()->isExtVectorType()) { |
6442 | const auto *VTy = Arg->getType()->castAs<ExtVectorType>(); |
6443 | unsigned Elm = VTy->getNumElements(); |
6444 | for (unsigned Idx = 0; Idx < Elm; ++Idx) { |
6445 | InitArgs.emplace_back(Args: new (Context) ArraySubscriptExpr( |
6446 | Arg, |
6447 | IntegerLiteral::Create( |
6448 | Context, llvm::APInt(Context.getIntWidth(T: Context.IntTy), Idx), |
6449 | Context.IntTy, SourceLocation()), |
6450 | VTy->getElementType(), Arg->getValueKind(), Arg->getObjectKind(), |
6451 | SourceLocation())); |
6452 | } |
6453 | } else |
6454 | InitArgs.emplace_back(Args&: Arg); |
6455 | } |
6456 | InitListExpr *ILE = new (Context) InitListExpr( |
6457 | S.getASTContext(), SourceLocation(), InitArgs, SourceLocation()); |
6458 | Args[0] = ILE; |
6459 | AddListInitializationStep(T: DestType); |
6460 | return; |
6461 | } |
6462 | |
6463 | // The remaining cases all need a source type. |
6464 | if (Args.size() > 1) { |
6465 | SetFailed(FK_TooManyInitsForScalar); |
6466 | return; |
6467 | } else if (isa<InitListExpr>(Val: Args[0])) { |
6468 | SetFailed(FK_ParenthesizedListInitForScalar); |
6469 | return; |
6470 | } |
6471 | |
6472 | // - Otherwise, if the source type is a (possibly cv-qualified) class |
6473 | // type, conversion functions are considered. |
6474 | if (!SourceType.isNull() && SourceType->isRecordType()) { |
6475 | assert(Initializer && "Initializer must be non-null" ); |
6476 | // For a conversion to _Atomic(T) from either T or a class type derived |
6477 | // from T, initialize the T object then convert to _Atomic type. |
6478 | bool NeedAtomicConversion = false; |
6479 | if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) { |
6480 | if (Context.hasSameUnqualifiedType(T1: SourceType, T2: Atomic->getValueType()) || |
6481 | S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType, |
6482 | Atomic->getValueType())) { |
6483 | DestType = Atomic->getValueType(); |
6484 | NeedAtomicConversion = true; |
6485 | } |
6486 | } |
6487 | |
6488 | TryUserDefinedConversion(S, DestType, Kind, Initializer, Sequence&: *this, |
6489 | TopLevelOfInitList); |
6490 | MaybeProduceObjCObject(S, Sequence&: *this, Entity); |
6491 | if (!Failed() && NeedAtomicConversion) |
6492 | AddAtomicConversionStep(Ty: Entity.getType()); |
6493 | return; |
6494 | } |
6495 | |
6496 | // - Otherwise, if the initialization is direct-initialization, the source |
6497 | // type is std::nullptr_t, and the destination type is bool, the initial |
6498 | // value of the object being initialized is false. |
6499 | if (!SourceType.isNull() && SourceType->isNullPtrType() && |
6500 | DestType->isBooleanType() && |
6501 | Kind.getKind() == InitializationKind::IK_Direct) { |
6502 | AddConversionSequenceStep( |
6503 | ICS: ImplicitConversionSequence::getNullptrToBool(SourceType, DestType, |
6504 | NeedLValToRVal: Initializer->isGLValue()), |
6505 | T: DestType); |
6506 | return; |
6507 | } |
6508 | |
6509 | // - Otherwise, the initial value of the object being initialized is the |
6510 | // (possibly converted) value of the initializer expression. Standard |
6511 | // conversions (Clause 4) will be used, if necessary, to convert the |
6512 | // initializer expression to the cv-unqualified version of the |
6513 | // destination type; no user-defined conversions are considered. |
6514 | |
6515 | ImplicitConversionSequence ICS |
6516 | = S.TryImplicitConversion(From: Initializer, ToType: DestType, |
6517 | /*SuppressUserConversions*/true, |
6518 | AllowExplicit: Sema::AllowedExplicit::None, |
6519 | /*InOverloadResolution*/ false, |
6520 | /*CStyle=*/Kind.isCStyleOrFunctionalCast(), |
6521 | AllowObjCWritebackConversion: allowObjCWritebackConversion); |
6522 | |
6523 | if (ICS.isStandard() && |
6524 | ICS.Standard.Second == ICK_Writeback_Conversion) { |
6525 | // Objective-C ARC writeback conversion. |
6526 | |
6527 | // We should copy unless we're passing to an argument explicitly |
6528 | // marked 'out'. |
6529 | bool ShouldCopy = true; |
6530 | if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Val: Entity.getDecl())) |
6531 | ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); |
6532 | |
6533 | // If there was an lvalue adjustment, add it as a separate conversion. |
6534 | if (ICS.Standard.First == ICK_Array_To_Pointer || |
6535 | ICS.Standard.First == ICK_Lvalue_To_Rvalue) { |
6536 | ImplicitConversionSequence LvalueICS; |
6537 | LvalueICS.setStandard(); |
6538 | LvalueICS.Standard.setAsIdentityConversion(); |
6539 | LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(Idx: 0)); |
6540 | LvalueICS.Standard.First = ICS.Standard.First; |
6541 | AddConversionSequenceStep(ICS: LvalueICS, T: ICS.Standard.getToType(Idx: 0)); |
6542 | } |
6543 | |
6544 | AddPassByIndirectCopyRestoreStep(type: DestType, shouldCopy: ShouldCopy); |
6545 | } else if (ICS.isBad()) { |
6546 | DeclAccessPair dap; |
6547 | if (isLibstdcxxPointerReturnFalseHack(S, Entity, Init: Initializer)) { |
6548 | AddZeroInitializationStep(T: Entity.getType()); |
6549 | } else if (Initializer->getType() == Context.OverloadTy && |
6550 | !S.ResolveAddressOfOverloadedFunction(AddressOfExpr: Initializer, TargetType: DestType, |
6551 | Complain: false, Found&: dap)) |
6552 | SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); |
6553 | else if (Initializer->getType()->isFunctionType() && |
6554 | isExprAnUnaddressableFunction(S, E: Initializer)) |
6555 | SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction); |
6556 | else |
6557 | SetFailed(InitializationSequence::FK_ConversionFailed); |
6558 | } else { |
6559 | AddConversionSequenceStep(ICS, T: DestType, TopLevelOfInitList); |
6560 | |
6561 | MaybeProduceObjCObject(S, Sequence&: *this, Entity); |
6562 | } |
6563 | } |
6564 | |
6565 | InitializationSequence::~InitializationSequence() { |
6566 | for (auto &S : Steps) |
6567 | S.Destroy(); |
6568 | } |
6569 | |
6570 | //===----------------------------------------------------------------------===// |
6571 | // Perform initialization |
6572 | //===----------------------------------------------------------------------===// |
6573 | static Sema::AssignmentAction |
6574 | getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) { |
6575 | switch(Entity.getKind()) { |
6576 | case InitializedEntity::EK_Variable: |
6577 | case InitializedEntity::EK_New: |
6578 | case InitializedEntity::EK_Exception: |
6579 | case InitializedEntity::EK_Base: |
6580 | case InitializedEntity::EK_Delegating: |
6581 | return Sema::AA_Initializing; |
6582 | |
6583 | case InitializedEntity::EK_Parameter: |
6584 | if (Entity.getDecl() && |
6585 | isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext())) |
6586 | return Sema::AA_Sending; |
6587 | |
6588 | return Sema::AA_Passing; |
6589 | |
6590 | case InitializedEntity::EK_Parameter_CF_Audited: |
6591 | if (Entity.getDecl() && |
6592 | isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext())) |
6593 | return Sema::AA_Sending; |
6594 | |
6595 | return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited; |
6596 | |
6597 | case InitializedEntity::EK_Result: |
6598 | case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right. |
6599 | return Sema::AA_Returning; |
6600 | |
6601 | case InitializedEntity::EK_Temporary: |
6602 | case InitializedEntity::EK_RelatedResult: |
6603 | // FIXME: Can we tell apart casting vs. converting? |
6604 | return Sema::AA_Casting; |
6605 | |
6606 | case InitializedEntity::EK_TemplateParameter: |
6607 | // This is really initialization, but refer to it as conversion for |
6608 | // consistency with CheckConvertedConstantExpression. |
6609 | return Sema::AA_Converting; |
6610 | |
6611 | case InitializedEntity::EK_Member: |
6612 | case InitializedEntity::EK_ParenAggInitMember: |
6613 | case InitializedEntity::EK_Binding: |
6614 | case InitializedEntity::EK_ArrayElement: |
6615 | case InitializedEntity::EK_VectorElement: |
6616 | case InitializedEntity::EK_ComplexElement: |
6617 | case InitializedEntity::EK_BlockElement: |
6618 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: |
6619 | case InitializedEntity::EK_LambdaCapture: |
6620 | case InitializedEntity::EK_CompoundLiteralInit: |
6621 | return Sema::AA_Initializing; |
6622 | } |
6623 | |
6624 | llvm_unreachable("Invalid EntityKind!" ); |
6625 | } |
6626 | |
6627 | /// Whether we should bind a created object as a temporary when |
6628 | /// initializing the given entity. |
6629 | static bool shouldBindAsTemporary(const InitializedEntity &Entity) { |
6630 | switch (Entity.getKind()) { |
6631 | case InitializedEntity::EK_ArrayElement: |
6632 | case InitializedEntity::EK_Member: |
6633 | case InitializedEntity::EK_ParenAggInitMember: |
6634 | case InitializedEntity::EK_Result: |
6635 | case InitializedEntity::EK_StmtExprResult: |
6636 | case InitializedEntity::EK_New: |
6637 | case InitializedEntity::EK_Variable: |
6638 | case InitializedEntity::EK_Base: |
6639 | case InitializedEntity::EK_Delegating: |
6640 | case InitializedEntity::EK_VectorElement: |
6641 | case InitializedEntity::EK_ComplexElement: |
6642 | case InitializedEntity::EK_Exception: |
6643 | case InitializedEntity::EK_BlockElement: |
6644 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: |
6645 | case InitializedEntity::EK_LambdaCapture: |
6646 | case InitializedEntity::EK_CompoundLiteralInit: |
6647 | case InitializedEntity::EK_TemplateParameter: |
6648 | return false; |
6649 | |
6650 | case InitializedEntity::EK_Parameter: |
6651 | case InitializedEntity::EK_Parameter_CF_Audited: |
6652 | case InitializedEntity::EK_Temporary: |
6653 | case InitializedEntity::EK_RelatedResult: |
6654 | case InitializedEntity::EK_Binding: |
6655 | return true; |
6656 | } |
6657 | |
6658 | llvm_unreachable("missed an InitializedEntity kind?" ); |
6659 | } |
6660 | |
6661 | /// Whether the given entity, when initialized with an object |
6662 | /// created for that initialization, requires destruction. |
6663 | static bool shouldDestroyEntity(const InitializedEntity &Entity) { |
6664 | switch (Entity.getKind()) { |
6665 | case InitializedEntity::EK_Result: |
6666 | case InitializedEntity::EK_StmtExprResult: |
6667 | case InitializedEntity::EK_New: |
6668 | case InitializedEntity::EK_Base: |
6669 | case InitializedEntity::EK_Delegating: |
6670 | case InitializedEntity::EK_VectorElement: |
6671 | case InitializedEntity::EK_ComplexElement: |
6672 | case InitializedEntity::EK_BlockElement: |
6673 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: |
6674 | case InitializedEntity::EK_LambdaCapture: |
6675 | return false; |
6676 | |
6677 | case InitializedEntity::EK_Member: |
6678 | case InitializedEntity::EK_ParenAggInitMember: |
6679 | case InitializedEntity::EK_Binding: |
6680 | case InitializedEntity::EK_Variable: |
6681 | case InitializedEntity::EK_Parameter: |
6682 | case InitializedEntity::EK_Parameter_CF_Audited: |
6683 | case InitializedEntity::EK_TemplateParameter: |
6684 | case InitializedEntity::EK_Temporary: |
6685 | case InitializedEntity::EK_ArrayElement: |
6686 | case InitializedEntity::EK_Exception: |
6687 | case InitializedEntity::EK_CompoundLiteralInit: |
6688 | case InitializedEntity::EK_RelatedResult: |
6689 | return true; |
6690 | } |
6691 | |
6692 | llvm_unreachable("missed an InitializedEntity kind?" ); |
6693 | } |
6694 | |
6695 | /// Get the location at which initialization diagnostics should appear. |
6696 | static SourceLocation getInitializationLoc(const InitializedEntity &Entity, |
6697 | Expr *Initializer) { |
6698 | switch (Entity.getKind()) { |
6699 | case InitializedEntity::EK_Result: |
6700 | case InitializedEntity::EK_StmtExprResult: |
6701 | return Entity.getReturnLoc(); |
6702 | |
6703 | case InitializedEntity::EK_Exception: |
6704 | return Entity.getThrowLoc(); |
6705 | |
6706 | case InitializedEntity::EK_Variable: |
6707 | case InitializedEntity::EK_Binding: |
6708 | return Entity.getDecl()->getLocation(); |
6709 | |
6710 | case InitializedEntity::EK_LambdaCapture: |
6711 | return Entity.getCaptureLoc(); |
6712 | |
6713 | case InitializedEntity::EK_ArrayElement: |
6714 | case InitializedEntity::EK_Member: |
6715 | case InitializedEntity::EK_ParenAggInitMember: |
6716 | case InitializedEntity::EK_Parameter: |
6717 | case InitializedEntity::EK_Parameter_CF_Audited: |
6718 | case InitializedEntity::EK_TemplateParameter: |
6719 | case InitializedEntity::EK_Temporary: |
6720 | case InitializedEntity::EK_New: |
6721 | case InitializedEntity::EK_Base: |
6722 | case InitializedEntity::EK_Delegating: |
6723 | case InitializedEntity::EK_VectorElement: |
6724 | case InitializedEntity::EK_ComplexElement: |
6725 | case InitializedEntity::EK_BlockElement: |
6726 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: |
6727 | case InitializedEntity::EK_CompoundLiteralInit: |
6728 | case InitializedEntity::EK_RelatedResult: |
6729 | return Initializer->getBeginLoc(); |
6730 | } |
6731 | llvm_unreachable("missed an InitializedEntity kind?" ); |
6732 | } |
6733 | |
6734 | /// Make a (potentially elidable) temporary copy of the object |
6735 | /// provided by the given initializer by calling the appropriate copy |
6736 | /// constructor. |
6737 | /// |
6738 | /// \param S The Sema object used for type-checking. |
6739 | /// |
6740 | /// \param T The type of the temporary object, which must either be |
6741 | /// the type of the initializer expression or a superclass thereof. |
6742 | /// |
6743 | /// \param Entity The entity being initialized. |
6744 | /// |
6745 | /// \param CurInit The initializer expression. |
6746 | /// |
6747 | /// \param IsExtraneousCopy Whether this is an "extraneous" copy that |
6748 | /// is permitted in C++03 (but not C++0x) when binding a reference to |
6749 | /// an rvalue. |
6750 | /// |
6751 | /// \returns An expression that copies the initializer expression into |
6752 | /// a temporary object, or an error expression if a copy could not be |
6753 | /// created. |
6754 | static ExprResult CopyObject(Sema &S, |
6755 | QualType T, |
6756 | const InitializedEntity &Entity, |
6757 | ExprResult CurInit, |
6758 | bool ) { |
6759 | if (CurInit.isInvalid()) |
6760 | return CurInit; |
6761 | // Determine which class type we're copying to. |
6762 | Expr *CurInitExpr = (Expr *)CurInit.get(); |
6763 | CXXRecordDecl *Class = nullptr; |
6764 | if (const RecordType *Record = T->getAs<RecordType>()) |
6765 | Class = cast<CXXRecordDecl>(Val: Record->getDecl()); |
6766 | if (!Class) |
6767 | return CurInit; |
6768 | |
6769 | SourceLocation Loc = getInitializationLoc(Entity, Initializer: CurInit.get()); |
6770 | |
6771 | // Make sure that the type we are copying is complete. |
6772 | if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete)) |
6773 | return CurInit; |
6774 | |
6775 | // Perform overload resolution using the class's constructors. Per |
6776 | // C++11 [dcl.init]p16, second bullet for class types, this initialization |
6777 | // is direct-initialization. |
6778 | OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); |
6779 | DeclContext::lookup_result Ctors = S.LookupConstructors(Class); |
6780 | |
6781 | OverloadCandidateSet::iterator Best; |
6782 | switch (ResolveConstructorOverload( |
6783 | S, DeclLoc: Loc, Args: CurInitExpr, CandidateSet, DestType: T, Ctors, Best, |
6784 | /*CopyInitializing=*/false, /*AllowExplicit=*/true, |
6785 | /*OnlyListConstructors=*/false, /*IsListInit=*/false, |
6786 | /*RequireActualConstructor=*/false, |
6787 | /*SecondStepOfCopyInit=*/true)) { |
6788 | case OR_Success: |
6789 | break; |
6790 | |
6791 | case OR_No_Viable_Function: |
6792 | CandidateSet.NoteCandidates( |
6793 | PartialDiagnosticAt( |
6794 | Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext() |
6795 | ? diag::ext_rvalue_to_reference_temp_copy_no_viable |
6796 | : diag::err_temp_copy_no_viable) |
6797 | << (int)Entity.getKind() << CurInitExpr->getType() |
6798 | << CurInitExpr->getSourceRange()), |
6799 | S, OCD_AllCandidates, CurInitExpr); |
6800 | if (!IsExtraneousCopy || S.isSFINAEContext()) |
6801 | return ExprError(); |
6802 | return CurInit; |
6803 | |
6804 | case OR_Ambiguous: |
6805 | CandidateSet.NoteCandidates( |
6806 | PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous) |
6807 | << (int)Entity.getKind() |
6808 | << CurInitExpr->getType() |
6809 | << CurInitExpr->getSourceRange()), |
6810 | S, OCD_AmbiguousCandidates, CurInitExpr); |
6811 | return ExprError(); |
6812 | |
6813 | case OR_Deleted: |
6814 | S.Diag(Loc, diag::err_temp_copy_deleted) |
6815 | << (int)Entity.getKind() << CurInitExpr->getType() |
6816 | << CurInitExpr->getSourceRange(); |
6817 | S.NoteDeletedFunction(FD: Best->Function); |
6818 | return ExprError(); |
6819 | } |
6820 | |
6821 | bool HadMultipleCandidates = CandidateSet.size() > 1; |
6822 | |
6823 | CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Val: Best->Function); |
6824 | SmallVector<Expr*, 8> ConstructorArgs; |
6825 | CurInit.get(); // Ownership transferred into MultiExprArg, below. |
6826 | |
6827 | S.CheckConstructorAccess(Loc, D: Constructor, FoundDecl: Best->FoundDecl, Entity, |
6828 | IsCopyBindingRefToTemp: IsExtraneousCopy); |
6829 | |
6830 | if (IsExtraneousCopy) { |
6831 | // If this is a totally extraneous copy for C++03 reference |
6832 | // binding purposes, just return the original initialization |
6833 | // expression. We don't generate an (elided) copy operation here |
6834 | // because doing so would require us to pass down a flag to avoid |
6835 | // infinite recursion, where each step adds another extraneous, |
6836 | // elidable copy. |
6837 | |
6838 | // Instantiate the default arguments of any extra parameters in |
6839 | // the selected copy constructor, as if we were going to create a |
6840 | // proper call to the copy constructor. |
6841 | for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) { |
6842 | ParmVarDecl *Parm = Constructor->getParamDecl(I); |
6843 | if (S.RequireCompleteType(Loc, Parm->getType(), |
6844 | diag::err_call_incomplete_argument)) |
6845 | break; |
6846 | |
6847 | // Build the default argument expression; we don't actually care |
6848 | // if this succeeds or not, because this routine will complain |
6849 | // if there was a problem. |
6850 | S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm); |
6851 | } |
6852 | |
6853 | return CurInitExpr; |
6854 | } |
6855 | |
6856 | // Determine the arguments required to actually perform the |
6857 | // constructor call (we might have derived-to-base conversions, or |
6858 | // the copy constructor may have default arguments). |
6859 | if (S.CompleteConstructorCall(Constructor, DeclInitType: T, ArgsPtr: CurInitExpr, Loc, |
6860 | ConvertedArgs&: ConstructorArgs)) |
6861 | return ExprError(); |
6862 | |
6863 | // C++0x [class.copy]p32: |
6864 | // When certain criteria are met, an implementation is allowed to |
6865 | // omit the copy/move construction of a class object, even if the |
6866 | // copy/move constructor and/or destructor for the object have |
6867 | // side effects. [...] |
6868 | // - when a temporary class object that has not been bound to a |
6869 | // reference (12.2) would be copied/moved to a class object |
6870 | // with the same cv-unqualified type, the copy/move operation |
6871 | // can be omitted by constructing the temporary object |
6872 | // directly into the target of the omitted copy/move |
6873 | // |
6874 | // Note that the other three bullets are handled elsewhere. Copy |
6875 | // elision for return statements and throw expressions are handled as part |
6876 | // of constructor initialization, while copy elision for exception handlers |
6877 | // is handled by the run-time. |
6878 | // |
6879 | // FIXME: If the function parameter is not the same type as the temporary, we |
6880 | // should still be able to elide the copy, but we don't have a way to |
6881 | // represent in the AST how much should be elided in this case. |
6882 | bool Elidable = |
6883 | CurInitExpr->isTemporaryObject(Ctx&: S.Context, TempTy: Class) && |
6884 | S.Context.hasSameUnqualifiedType( |
6885 | T1: Best->Function->getParamDecl(i: 0)->getType().getNonReferenceType(), |
6886 | T2: CurInitExpr->getType()); |
6887 | |
6888 | // Actually perform the constructor call. |
6889 | CurInit = S.BuildCXXConstructExpr( |
6890 | ConstructLoc: Loc, DeclInitType: T, FoundDecl: Best->FoundDecl, Constructor, Elidable, Exprs: ConstructorArgs, |
6891 | HadMultipleCandidates, |
6892 | /*ListInit*/ IsListInitialization: false, |
6893 | /*StdInitListInit*/ IsStdInitListInitialization: false, |
6894 | /*ZeroInit*/ RequiresZeroInit: false, ConstructKind: CXXConstructionKind::Complete, ParenRange: SourceRange()); |
6895 | |
6896 | // If we're supposed to bind temporaries, do so. |
6897 | if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity)) |
6898 | CurInit = S.MaybeBindToTemporary(E: CurInit.getAs<Expr>()); |
6899 | return CurInit; |
6900 | } |
6901 | |
6902 | /// Check whether elidable copy construction for binding a reference to |
6903 | /// a temporary would have succeeded if we were building in C++98 mode, for |
6904 | /// -Wc++98-compat. |
6905 | static void CheckCXX98CompatAccessibleCopy(Sema &S, |
6906 | const InitializedEntity &Entity, |
6907 | Expr *CurInitExpr) { |
6908 | assert(S.getLangOpts().CPlusPlus11); |
6909 | |
6910 | const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>(); |
6911 | if (!Record) |
6912 | return; |
6913 | |
6914 | SourceLocation Loc = getInitializationLoc(Entity, Initializer: CurInitExpr); |
6915 | if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc)) |
6916 | return; |
6917 | |
6918 | // Find constructors which would have been considered. |
6919 | OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); |
6920 | DeclContext::lookup_result Ctors = |
6921 | S.LookupConstructors(Class: cast<CXXRecordDecl>(Val: Record->getDecl())); |
6922 | |
6923 | // Perform overload resolution. |
6924 | OverloadCandidateSet::iterator Best; |
6925 | OverloadingResult OR = ResolveConstructorOverload( |
6926 | S, DeclLoc: Loc, Args: CurInitExpr, CandidateSet, DestType: CurInitExpr->getType(), Ctors, Best, |
6927 | /*CopyInitializing=*/false, /*AllowExplicit=*/true, |
6928 | /*OnlyListConstructors=*/false, /*IsListInit=*/false, |
6929 | /*RequireActualConstructor=*/false, |
6930 | /*SecondStepOfCopyInit=*/true); |
6931 | |
6932 | PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy) |
6933 | << OR << (int)Entity.getKind() << CurInitExpr->getType() |
6934 | << CurInitExpr->getSourceRange(); |
6935 | |
6936 | switch (OR) { |
6937 | case OR_Success: |
6938 | S.CheckConstructorAccess(Loc, D: cast<CXXConstructorDecl>(Val: Best->Function), |
6939 | FoundDecl: Best->FoundDecl, Entity, PDiag: Diag); |
6940 | // FIXME: Check default arguments as far as that's possible. |
6941 | break; |
6942 | |
6943 | case OR_No_Viable_Function: |
6944 | CandidateSet.NoteCandidates(PA: PartialDiagnosticAt(Loc, Diag), S, |
6945 | OCD: OCD_AllCandidates, Args: CurInitExpr); |
6946 | break; |
6947 | |
6948 | case OR_Ambiguous: |
6949 | CandidateSet.NoteCandidates(PA: PartialDiagnosticAt(Loc, Diag), S, |
6950 | OCD: OCD_AmbiguousCandidates, Args: CurInitExpr); |
6951 | break; |
6952 | |
6953 | case OR_Deleted: |
6954 | S.Diag(Loc, PD: Diag); |
6955 | S.NoteDeletedFunction(FD: Best->Function); |
6956 | break; |
6957 | } |
6958 | } |
6959 | |
6960 | void InitializationSequence::PrintInitLocationNote(Sema &S, |
6961 | const InitializedEntity &Entity) { |
6962 | if (Entity.isParamOrTemplateParamKind() && Entity.getDecl()) { |
6963 | if (Entity.getDecl()->getLocation().isInvalid()) |
6964 | return; |
6965 | |
6966 | if (Entity.getDecl()->getDeclName()) |
6967 | S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here) |
6968 | << Entity.getDecl()->getDeclName(); |
6969 | else |
6970 | S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here); |
6971 | } |
6972 | else if (Entity.getKind() == InitializedEntity::EK_RelatedResult && |
6973 | Entity.getMethodDecl()) |
6974 | S.Diag(Entity.getMethodDecl()->getLocation(), |
6975 | diag::note_method_return_type_change) |
6976 | << Entity.getMethodDecl()->getDeclName(); |
6977 | } |
6978 | |
6979 | /// Returns true if the parameters describe a constructor initialization of |
6980 | /// an explicit temporary object, e.g. "Point(x, y)". |
6981 | static bool isExplicitTemporary(const InitializedEntity &Entity, |
6982 | const InitializationKind &Kind, |
6983 | unsigned NumArgs) { |
6984 | switch (Entity.getKind()) { |
6985 | case InitializedEntity::EK_Temporary: |
6986 | case InitializedEntity::EK_CompoundLiteralInit: |
6987 | case InitializedEntity::EK_RelatedResult: |
6988 | break; |
6989 | default: |
6990 | return false; |
6991 | } |
6992 | |
6993 | switch (Kind.getKind()) { |
6994 | case InitializationKind::IK_DirectList: |
6995 | return true; |
6996 | // FIXME: Hack to work around cast weirdness. |
6997 | case InitializationKind::IK_Direct: |
6998 | case InitializationKind::IK_Value: |
6999 | return NumArgs != 1; |
7000 | default: |
7001 | return false; |
7002 | } |
7003 | } |
7004 | |
7005 | static ExprResult |
7006 | PerformConstructorInitialization(Sema &S, |
7007 | const InitializedEntity &Entity, |
7008 | const InitializationKind &Kind, |
7009 | MultiExprArg Args, |
7010 | const InitializationSequence::Step& Step, |
7011 | bool &ConstructorInitRequiresZeroInit, |
7012 | bool IsListInitialization, |
7013 | bool IsStdInitListInitialization, |
7014 | SourceLocation LBraceLoc, |
7015 | SourceLocation RBraceLoc) { |
7016 | unsigned NumArgs = Args.size(); |
7017 | CXXConstructorDecl *Constructor |
7018 | = cast<CXXConstructorDecl>(Val: Step.Function.Function); |
7019 | bool HadMultipleCandidates = Step.Function.HadMultipleCandidates; |
7020 | |
7021 | // Build a call to the selected constructor. |
7022 | SmallVector<Expr*, 8> ConstructorArgs; |
7023 | SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid()) |
7024 | ? Kind.getEqualLoc() |
7025 | : Kind.getLocation(); |
7026 | |
7027 | if (Kind.getKind() == InitializationKind::IK_Default) { |
7028 | // Force even a trivial, implicit default constructor to be |
7029 | // semantically checked. We do this explicitly because we don't build |
7030 | // the definition for completely trivial constructors. |
7031 | assert(Constructor->getParent() && "No parent class for constructor." ); |
7032 | if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() && |
7033 | Constructor->isTrivial() && !Constructor->isUsed(false)) { |
7034 | S.runWithSufficientStackSpace(Loc, Fn: [&] { |
7035 | S.DefineImplicitDefaultConstructor(CurrentLocation: Loc, Constructor); |
7036 | }); |
7037 | } |
7038 | } |
7039 | |
7040 | ExprResult CurInit((Expr *)nullptr); |
7041 | |
7042 | // C++ [over.match.copy]p1: |
7043 | // - When initializing a temporary to be bound to the first parameter |
7044 | // of a constructor that takes a reference to possibly cv-qualified |
7045 | // T as its first argument, called with a single argument in the |
7046 | // context of direct-initialization, explicit conversion functions |
7047 | // are also considered. |
7048 | bool AllowExplicitConv = |
7049 | Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 && |
7050 | hasCopyOrMoveCtorParam(Ctx&: S.Context, |
7051 | Info: getConstructorInfo(ND: Step.Function.FoundDecl)); |
7052 | |
7053 | // Determine the arguments required to actually perform the constructor |
7054 | // call. |
7055 | if (S.CompleteConstructorCall(Constructor, DeclInitType: Step.Type, ArgsPtr: Args, Loc, |
7056 | ConvertedArgs&: ConstructorArgs, AllowExplicit: AllowExplicitConv, |
7057 | IsListInitialization)) |
7058 | return ExprError(); |
7059 | |
7060 | if (isExplicitTemporary(Entity, Kind, NumArgs)) { |
7061 | // An explicitly-constructed temporary, e.g., X(1, 2). |
7062 | if (S.DiagnoseUseOfDecl(D: Step.Function.FoundDecl, Locs: Loc)) |
7063 | return ExprError(); |
7064 | |
7065 | TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo(); |
7066 | if (!TSInfo) |
7067 | TSInfo = S.Context.getTrivialTypeSourceInfo(T: Entity.getType(), Loc); |
7068 | SourceRange ParenOrBraceRange = |
7069 | (Kind.getKind() == InitializationKind::IK_DirectList) |
7070 | ? SourceRange(LBraceLoc, RBraceLoc) |
7071 | : Kind.getParenOrBraceRange(); |
7072 | |
7073 | CXXConstructorDecl *CalleeDecl = Constructor; |
7074 | if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>( |
7075 | Val: Step.Function.FoundDecl.getDecl())) { |
7076 | CalleeDecl = S.findInheritingConstructor(Loc, BaseCtor: Constructor, DerivedShadow: Shadow); |
7077 | } |
7078 | S.MarkFunctionReferenced(Loc, CalleeDecl); |
7079 | |
7080 | CurInit = S.CheckForImmediateInvocation( |
7081 | CXXTemporaryObjectExpr::Create( |
7082 | Ctx: S.Context, Cons: CalleeDecl, |
7083 | Ty: Entity.getType().getNonLValueExprType(Context: S.Context), TSI: TSInfo, |
7084 | Args: ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates, |
7085 | ListInitialization: IsListInitialization, StdInitListInitialization: IsStdInitListInitialization, |
7086 | ZeroInitialization: ConstructorInitRequiresZeroInit), |
7087 | CalleeDecl); |
7088 | } else { |
7089 | CXXConstructionKind ConstructKind = CXXConstructionKind::Complete; |
7090 | |
7091 | if (Entity.getKind() == InitializedEntity::EK_Base) { |
7092 | ConstructKind = Entity.getBaseSpecifier()->isVirtual() |
7093 | ? CXXConstructionKind::VirtualBase |
7094 | : CXXConstructionKind::NonVirtualBase; |
7095 | } else if (Entity.getKind() == InitializedEntity::EK_Delegating) { |
7096 | ConstructKind = CXXConstructionKind::Delegating; |
7097 | } |
7098 | |
7099 | // Only get the parenthesis or brace range if it is a list initialization or |
7100 | // direct construction. |
7101 | SourceRange ParenOrBraceRange; |
7102 | if (IsListInitialization) |
7103 | ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc); |
7104 | else if (Kind.getKind() == InitializationKind::IK_Direct) |
7105 | ParenOrBraceRange = Kind.getParenOrBraceRange(); |
7106 | |
7107 | // If the entity allows NRVO, mark the construction as elidable |
7108 | // unconditionally. |
7109 | if (Entity.allowsNRVO()) |
7110 | CurInit = S.BuildCXXConstructExpr(Loc, Step.Type, |
7111 | Step.Function.FoundDecl, |
7112 | Constructor, /*Elidable=*/true, |
7113 | ConstructorArgs, |
7114 | HadMultipleCandidates, |
7115 | IsListInitialization, |
7116 | IsStdInitListInitialization, |
7117 | ConstructorInitRequiresZeroInit, |
7118 | ConstructKind, |
7119 | ParenOrBraceRange); |
7120 | else |
7121 | CurInit = S.BuildCXXConstructExpr(Loc, Step.Type, |
7122 | Step.Function.FoundDecl, |
7123 | Constructor, |
7124 | ConstructorArgs, |
7125 | HadMultipleCandidates, |
7126 | IsListInitialization, |
7127 | IsStdInitListInitialization, |
7128 | ConstructorInitRequiresZeroInit, |
7129 | ConstructKind, |
7130 | ParenOrBraceRange); |
7131 | } |
7132 | if (CurInit.isInvalid()) |
7133 | return ExprError(); |
7134 | |
7135 | // Only check access if all of that succeeded. |
7136 | S.CheckConstructorAccess(Loc, D: Constructor, FoundDecl: Step.Function.FoundDecl, Entity); |
7137 | if (S.DiagnoseUseOfDecl(D: Step.Function.FoundDecl, Locs: Loc)) |
7138 | return ExprError(); |
7139 | |
7140 | if (const ArrayType *AT = S.Context.getAsArrayType(T: Entity.getType())) |
7141 | if (checkDestructorReference(ElementType: S.Context.getBaseElementType(VAT: AT), Loc, SemaRef&: S)) |
7142 | return ExprError(); |
7143 | |
7144 | if (shouldBindAsTemporary(Entity)) |
7145 | CurInit = S.MaybeBindToTemporary(E: CurInit.get()); |
7146 | |
7147 | return CurInit; |
7148 | } |
7149 | |
7150 | namespace { |
7151 | enum LifetimeKind { |
7152 | /// The lifetime of a temporary bound to this entity ends at the end of the |
7153 | /// full-expression, and that's (probably) fine. |
7154 | LK_FullExpression, |
7155 | |
7156 | /// The lifetime of a temporary bound to this entity is extended to the |
7157 | /// lifeitme of the entity itself. |
7158 | LK_Extended, |
7159 | |
7160 | /// The lifetime of a temporary bound to this entity probably ends too soon, |
7161 | /// because the entity is allocated in a new-expression. |
7162 | LK_New, |
7163 | |
7164 | /// The lifetime of a temporary bound to this entity ends too soon, because |
7165 | /// the entity is a return object. |
7166 | LK_Return, |
7167 | |
7168 | /// The lifetime of a temporary bound to this entity ends too soon, because |
7169 | /// the entity is the result of a statement expression. |
7170 | LK_StmtExprResult, |
7171 | |
7172 | /// This is a mem-initializer: if it would extend a temporary (other than via |
7173 | /// a default member initializer), the program is ill-formed. |
7174 | LK_MemInitializer, |
7175 | }; |
7176 | using LifetimeResult = |
7177 | llvm::PointerIntPair<const InitializedEntity *, 3, LifetimeKind>; |
7178 | } |
7179 | |
7180 | /// Determine the declaration which an initialized entity ultimately refers to, |
7181 | /// for the purpose of lifetime-extending a temporary bound to a reference in |
7182 | /// the initialization of \p Entity. |
7183 | static LifetimeResult getEntityLifetime( |
7184 | const InitializedEntity *Entity, |
7185 | const InitializedEntity *InitField = nullptr) { |
7186 | // C++11 [class.temporary]p5: |
7187 | switch (Entity->getKind()) { |
7188 | case InitializedEntity::EK_Variable: |
7189 | // The temporary [...] persists for the lifetime of the reference |
7190 | return {Entity, LK_Extended}; |
7191 | |
7192 | case InitializedEntity::EK_Member: |
7193 | // For subobjects, we look at the complete object. |
7194 | if (Entity->getParent()) |
7195 | return getEntityLifetime(Entity: Entity->getParent(), InitField: Entity); |
7196 | |
7197 | // except: |
7198 | // C++17 [class.base.init]p8: |
7199 | // A temporary expression bound to a reference member in a |
7200 | // mem-initializer is ill-formed. |
7201 | // C++17 [class.base.init]p11: |
7202 | // A temporary expression bound to a reference member from a |
7203 | // default member initializer is ill-formed. |
7204 | // |
7205 | // The context of p11 and its example suggest that it's only the use of a |
7206 | // default member initializer from a constructor that makes the program |
7207 | // ill-formed, not its mere existence, and that it can even be used by |
7208 | // aggregate initialization. |
7209 | return {Entity, Entity->isDefaultMemberInitializer() ? LK_Extended |
7210 | : LK_MemInitializer}; |
7211 | |
7212 | case InitializedEntity::EK_Binding: |
7213 | // Per [dcl.decomp]p3, the binding is treated as a variable of reference |
7214 | // type. |
7215 | return {Entity, LK_Extended}; |
7216 | |
7217 | case InitializedEntity::EK_Parameter: |
7218 | case InitializedEntity::EK_Parameter_CF_Audited: |
7219 | // -- A temporary bound to a reference parameter in a function call |
7220 | // persists until the completion of the full-expression containing |
7221 | // the call. |
7222 | return {nullptr, LK_FullExpression}; |
7223 | |
7224 | case InitializedEntity::EK_TemplateParameter: |
7225 | // FIXME: This will always be ill-formed; should we eagerly diagnose it here? |
7226 | return {nullptr, LK_FullExpression}; |
7227 | |
7228 | case InitializedEntity::EK_Result: |
7229 | // -- The lifetime of a temporary bound to the returned value in a |
7230 | // function return statement is not extended; the temporary is |
7231 | // destroyed at the end of the full-expression in the return statement. |
7232 | return {nullptr, LK_Return}; |
7233 | |
7234 | case InitializedEntity::EK_StmtExprResult: |
7235 | // FIXME: Should we lifetime-extend through the result of a statement |
7236 | // expression? |
7237 | return {nullptr, LK_StmtExprResult}; |
7238 | |
7239 | case InitializedEntity::EK_New: |
7240 | // -- A temporary bound to a reference in a new-initializer persists |
7241 | // until the completion of the full-expression containing the |
7242 | // new-initializer. |
7243 | return {nullptr, LK_New}; |
7244 | |
7245 | case InitializedEntity::EK_Temporary: |
7246 | case InitializedEntity::EK_CompoundLiteralInit: |
7247 | case InitializedEntity::EK_RelatedResult: |
7248 | // We don't yet know the storage duration of the surrounding temporary. |
7249 | // Assume it's got full-expression duration for now, it will patch up our |
7250 | // storage duration if that's not correct. |
7251 | return {nullptr, LK_FullExpression}; |
7252 | |
7253 | case InitializedEntity::EK_ArrayElement: |
7254 | // For subobjects, we look at the complete object. |
7255 | return getEntityLifetime(Entity: Entity->getParent(), InitField); |
7256 | |
7257 | case InitializedEntity::EK_Base: |
7258 | // For subobjects, we look at the complete object. |
7259 | if (Entity->getParent()) |
7260 | return getEntityLifetime(Entity: Entity->getParent(), InitField); |
7261 | return {InitField, LK_MemInitializer}; |
7262 | |
7263 | case InitializedEntity::EK_Delegating: |
7264 | // We can reach this case for aggregate initialization in a constructor: |
7265 | // struct A { int &&r; }; |
7266 | // struct B : A { B() : A{0} {} }; |
7267 | // In this case, use the outermost field decl as the context. |
7268 | return {InitField, LK_MemInitializer}; |
7269 | |
7270 | case InitializedEntity::EK_BlockElement: |
7271 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: |
7272 | case InitializedEntity::EK_LambdaCapture: |
7273 | case InitializedEntity::EK_VectorElement: |
7274 | case InitializedEntity::EK_ComplexElement: |
7275 | return {nullptr, LK_FullExpression}; |
7276 | |
7277 | case InitializedEntity::EK_Exception: |
7278 | // FIXME: Can we diagnose lifetime problems with exceptions? |
7279 | return {nullptr, LK_FullExpression}; |
7280 | |
7281 | case InitializedEntity::EK_ParenAggInitMember: |
7282 | // -- A temporary object bound to a reference element of an aggregate of |
7283 | // class type initialized from a parenthesized expression-list |
7284 | // [dcl.init, 9.3] persists until the completion of the full-expression |
7285 | // containing the expression-list. |
7286 | return {nullptr, LK_FullExpression}; |
7287 | } |
7288 | |
7289 | llvm_unreachable("unknown entity kind" ); |
7290 | } |
7291 | |
7292 | namespace { |
7293 | enum ReferenceKind { |
7294 | /// Lifetime would be extended by a reference binding to a temporary. |
7295 | RK_ReferenceBinding, |
7296 | /// Lifetime would be extended by a std::initializer_list object binding to |
7297 | /// its backing array. |
7298 | RK_StdInitializerList, |
7299 | }; |
7300 | |
7301 | /// A temporary or local variable. This will be one of: |
7302 | /// * A MaterializeTemporaryExpr. |
7303 | /// * A DeclRefExpr whose declaration is a local. |
7304 | /// * An AddrLabelExpr. |
7305 | /// * A BlockExpr for a block with captures. |
7306 | using Local = Expr*; |
7307 | |
7308 | /// Expressions we stepped over when looking for the local state. Any steps |
7309 | /// that would inhibit lifetime extension or take us out of subexpressions of |
7310 | /// the initializer are included. |
7311 | struct IndirectLocalPathEntry { |
7312 | enum EntryKind { |
7313 | DefaultInit, |
7314 | AddressOf, |
7315 | VarInit, |
7316 | LValToRVal, |
7317 | LifetimeBoundCall, |
7318 | TemporaryCopy, |
7319 | LambdaCaptureInit, |
7320 | GslReferenceInit, |
7321 | GslPointerInit |
7322 | } Kind; |
7323 | Expr *E; |
7324 | union { |
7325 | const Decl *D = nullptr; |
7326 | const LambdaCapture *Capture; |
7327 | }; |
7328 | IndirectLocalPathEntry() {} |
7329 | IndirectLocalPathEntry(EntryKind K, Expr *E) : Kind(K), E(E) {} |
7330 | IndirectLocalPathEntry(EntryKind K, Expr *E, const Decl *D) |
7331 | : Kind(K), E(E), D(D) {} |
7332 | IndirectLocalPathEntry(EntryKind K, Expr *E, const LambdaCapture *Capture) |
7333 | : Kind(K), E(E), Capture(Capture) {} |
7334 | }; |
7335 | |
7336 | using IndirectLocalPath = llvm::SmallVectorImpl<IndirectLocalPathEntry>; |
7337 | |
7338 | struct RevertToOldSizeRAII { |
7339 | IndirectLocalPath &Path; |
7340 | unsigned OldSize = Path.size(); |
7341 | RevertToOldSizeRAII(IndirectLocalPath &Path) : Path(Path) {} |
7342 | ~RevertToOldSizeRAII() { Path.resize(N: OldSize); } |
7343 | }; |
7344 | |
7345 | using LocalVisitor = llvm::function_ref<bool(IndirectLocalPath &Path, Local L, |
7346 | ReferenceKind RK)>; |
7347 | } |
7348 | |
7349 | static bool isVarOnPath(IndirectLocalPath &Path, VarDecl *VD) { |
7350 | for (auto E : Path) |
7351 | if (E.Kind == IndirectLocalPathEntry::VarInit && E.D == VD) |
7352 | return true; |
7353 | return false; |
7354 | } |
7355 | |
7356 | static bool pathContainsInit(IndirectLocalPath &Path) { |
7357 | return llvm::any_of(Range&: Path, P: [=](IndirectLocalPathEntry E) { |
7358 | return E.Kind == IndirectLocalPathEntry::DefaultInit || |
7359 | E.Kind == IndirectLocalPathEntry::VarInit; |
7360 | }); |
7361 | } |
7362 | |
7363 | static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path, |
7364 | Expr *Init, LocalVisitor Visit, |
7365 | bool RevisitSubinits, |
7366 | bool EnableLifetimeWarnings); |
7367 | |
7368 | static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path, |
7369 | Expr *Init, ReferenceKind RK, |
7370 | LocalVisitor Visit, |
7371 | bool EnableLifetimeWarnings); |
7372 | |
7373 | template <typename T> static bool isRecordWithAttr(QualType Type) { |
7374 | if (auto *RD = Type->getAsCXXRecordDecl()) |
7375 | return RD->hasAttr<T>(); |
7376 | return false; |
7377 | } |
7378 | |
7379 | // Decl::isInStdNamespace will return false for iterators in some STL |
7380 | // implementations due to them being defined in a namespace outside of the std |
7381 | // namespace. |
7382 | static bool isInStlNamespace(const Decl *D) { |
7383 | const DeclContext *DC = D->getDeclContext(); |
7384 | if (!DC) |
7385 | return false; |
7386 | if (const auto *ND = dyn_cast<NamespaceDecl>(Val: DC)) |
7387 | if (const IdentifierInfo *II = ND->getIdentifier()) { |
7388 | StringRef Name = II->getName(); |
7389 | if (Name.size() >= 2 && Name.front() == '_' && |
7390 | (Name[1] == '_' || isUppercase(c: Name[1]))) |
7391 | return true; |
7392 | } |
7393 | |
7394 | return DC->isStdNamespace(); |
7395 | } |
7396 | |
7397 | static bool shouldTrackImplicitObjectArg(const CXXMethodDecl *Callee) { |
7398 | if (auto *Conv = dyn_cast_or_null<CXXConversionDecl>(Val: Callee)) |
7399 | if (isRecordWithAttr<PointerAttr>(Conv->getConversionType())) |
7400 | return true; |
7401 | if (!isInStlNamespace(Callee->getParent())) |
7402 | return false; |
7403 | if (!isRecordWithAttr<PointerAttr>( |
7404 | Callee->getFunctionObjectParameterType()) && |
7405 | !isRecordWithAttr<OwnerAttr>(Callee->getFunctionObjectParameterType())) |
7406 | return false; |
7407 | if (Callee->getReturnType()->isPointerType() || |
7408 | isRecordWithAttr<PointerAttr>(Callee->getReturnType())) { |
7409 | if (!Callee->getIdentifier()) |
7410 | return false; |
7411 | return llvm::StringSwitch<bool>(Callee->getName()) |
7412 | .Cases(S0: "begin" , S1: "rbegin" , S2: "cbegin" , S3: "crbegin" , Value: true) |
7413 | .Cases(S0: "end" , S1: "rend" , S2: "cend" , S3: "crend" , Value: true) |
7414 | .Cases(S0: "c_str" , S1: "data" , S2: "get" , Value: true) |
7415 | // Map and set types. |
7416 | .Cases(S0: "find" , S1: "equal_range" , S2: "lower_bound" , S3: "upper_bound" , Value: true) |
7417 | .Default(Value: false); |
7418 | } else if (Callee->getReturnType()->isReferenceType()) { |
7419 | if (!Callee->getIdentifier()) { |
7420 | auto OO = Callee->getOverloadedOperator(); |
7421 | return OO == OverloadedOperatorKind::OO_Subscript || |
7422 | OO == OverloadedOperatorKind::OO_Star; |
7423 | } |
7424 | return llvm::StringSwitch<bool>(Callee->getName()) |
7425 | .Cases(S0: "front" , S1: "back" , S2: "at" , S3: "top" , S4: "value" , Value: true) |
7426 | .Default(Value: false); |
7427 | } |
7428 | return false; |
7429 | } |
7430 | |
7431 | static bool shouldTrackFirstArgument(const FunctionDecl *FD) { |
7432 | if (!FD->getIdentifier() || FD->getNumParams() != 1) |
7433 | return false; |
7434 | const auto *RD = FD->getParamDecl(i: 0)->getType()->getPointeeCXXRecordDecl(); |
7435 | if (!FD->isInStdNamespace() || !RD || !RD->isInStdNamespace()) |
7436 | return false; |
7437 | if (!isRecordWithAttr<PointerAttr>(QualType(RD->getTypeForDecl(), 0)) && |
7438 | !isRecordWithAttr<OwnerAttr>(QualType(RD->getTypeForDecl(), 0))) |
7439 | return false; |
7440 | if (FD->getReturnType()->isPointerType() || |
7441 | isRecordWithAttr<PointerAttr>(FD->getReturnType())) { |
7442 | return llvm::StringSwitch<bool>(FD->getName()) |
7443 | .Cases(S0: "begin" , S1: "rbegin" , S2: "cbegin" , S3: "crbegin" , Value: true) |
7444 | .Cases(S0: "end" , S1: "rend" , S2: "cend" , S3: "crend" , Value: true) |
7445 | .Case(S: "data" , Value: true) |
7446 | .Default(Value: false); |
7447 | } else if (FD->getReturnType()->isReferenceType()) { |
7448 | return llvm::StringSwitch<bool>(FD->getName()) |
7449 | .Cases(S0: "get" , S1: "any_cast" , Value: true) |
7450 | .Default(Value: false); |
7451 | } |
7452 | return false; |
7453 | } |
7454 | |
7455 | static void handleGslAnnotatedTypes(IndirectLocalPath &Path, Expr *Call, |
7456 | LocalVisitor Visit) { |
7457 | auto VisitPointerArg = [&](const Decl *D, Expr *Arg, bool Value) { |
7458 | // We are not interested in the temporary base objects of gsl Pointers: |
7459 | // Temp().ptr; // Here ptr might not dangle. |
7460 | if (isa<MemberExpr>(Val: Arg->IgnoreImpCasts())) |
7461 | return; |
7462 | // Once we initialized a value with a reference, it can no longer dangle. |
7463 | if (!Value) { |
7464 | for (const IndirectLocalPathEntry &PE : llvm::reverse(C&: Path)) { |
7465 | if (PE.Kind == IndirectLocalPathEntry::GslReferenceInit) |
7466 | continue; |
7467 | if (PE.Kind == IndirectLocalPathEntry::GslPointerInit) |
7468 | return; |
7469 | break; |
7470 | } |
7471 | } |
7472 | Path.push_back(Elt: {Value ? IndirectLocalPathEntry::GslPointerInit |
7473 | : IndirectLocalPathEntry::GslReferenceInit, |
7474 | Arg, D}); |
7475 | if (Arg->isGLValue()) |
7476 | visitLocalsRetainedByReferenceBinding(Path, Init: Arg, RK: RK_ReferenceBinding, |
7477 | Visit, |
7478 | /*EnableLifetimeWarnings=*/true); |
7479 | else |
7480 | visitLocalsRetainedByInitializer(Path, Init: Arg, Visit, RevisitSubinits: true, |
7481 | /*EnableLifetimeWarnings=*/true); |
7482 | Path.pop_back(); |
7483 | }; |
7484 | |
7485 | if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Val: Call)) { |
7486 | const auto *MD = cast_or_null<CXXMethodDecl>(MCE->getDirectCallee()); |
7487 | if (MD && shouldTrackImplicitObjectArg(MD)) |
7488 | VisitPointerArg(MD, MCE->getImplicitObjectArgument(), |
7489 | !MD->getReturnType()->isReferenceType()); |
7490 | return; |
7491 | } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(Val: Call)) { |
7492 | FunctionDecl *Callee = OCE->getDirectCallee(); |
7493 | if (Callee && Callee->isCXXInstanceMember() && |
7494 | shouldTrackImplicitObjectArg(Callee: cast<CXXMethodDecl>(Val: Callee))) |
7495 | VisitPointerArg(Callee, OCE->getArg(0), |
7496 | !Callee->getReturnType()->isReferenceType()); |
7497 | return; |
7498 | } else if (auto *CE = dyn_cast<CallExpr>(Val: Call)) { |
7499 | FunctionDecl *Callee = CE->getDirectCallee(); |
7500 | if (Callee && shouldTrackFirstArgument(FD: Callee)) |
7501 | VisitPointerArg(Callee, CE->getArg(Arg: 0), |
7502 | !Callee->getReturnType()->isReferenceType()); |
7503 | return; |
7504 | } |
7505 | |
7506 | if (auto *CCE = dyn_cast<CXXConstructExpr>(Val: Call)) { |
7507 | const auto *Ctor = CCE->getConstructor(); |
7508 | const CXXRecordDecl *RD = Ctor->getParent(); |
7509 | if (CCE->getNumArgs() > 0 && RD->hasAttr<PointerAttr>()) |
7510 | VisitPointerArg(Ctor->getParamDecl(0), CCE->getArgs()[0], true); |
7511 | } |
7512 | } |
7513 | |
7514 | static bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD) { |
7515 | const TypeSourceInfo *TSI = FD->getTypeSourceInfo(); |
7516 | if (!TSI) |
7517 | return false; |
7518 | // Don't declare this variable in the second operand of the for-statement; |
7519 | // GCC miscompiles that by ending its lifetime before evaluating the |
7520 | // third operand. See gcc.gnu.org/PR86769. |
7521 | AttributedTypeLoc ATL; |
7522 | for (TypeLoc TL = TSI->getTypeLoc(); |
7523 | (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); |
7524 | TL = ATL.getModifiedLoc()) { |
7525 | if (ATL.getAttrAs<LifetimeBoundAttr>()) |
7526 | return true; |
7527 | } |
7528 | |
7529 | // Assume that all assignment operators with a "normal" return type return |
7530 | // *this, that is, an lvalue reference that is the same type as the implicit |
7531 | // object parameter (or the LHS for a non-member operator$=). |
7532 | OverloadedOperatorKind OO = FD->getDeclName().getCXXOverloadedOperator(); |
7533 | if (OO == OO_Equal || isCompoundAssignmentOperator(Kind: OO)) { |
7534 | QualType RetT = FD->getReturnType(); |
7535 | if (RetT->isLValueReferenceType()) { |
7536 | ASTContext &Ctx = FD->getASTContext(); |
7537 | QualType LHST; |
7538 | auto *MD = dyn_cast<CXXMethodDecl>(Val: FD); |
7539 | if (MD && MD->isCXXInstanceMember()) |
7540 | LHST = Ctx.getLValueReferenceType(T: MD->getFunctionObjectParameterType()); |
7541 | else |
7542 | LHST = MD->getParamDecl(0)->getType(); |
7543 | if (Ctx.hasSameType(T1: RetT, T2: LHST)) |
7544 | return true; |
7545 | } |
7546 | } |
7547 | |
7548 | return false; |
7549 | } |
7550 | |
7551 | static void visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call, |
7552 | LocalVisitor Visit) { |
7553 | const FunctionDecl *Callee; |
7554 | ArrayRef<Expr*> Args; |
7555 | |
7556 | if (auto *CE = dyn_cast<CallExpr>(Val: Call)) { |
7557 | Callee = CE->getDirectCallee(); |
7558 | Args = llvm::ArrayRef(CE->getArgs(), CE->getNumArgs()); |
7559 | } else { |
7560 | auto *CCE = cast<CXXConstructExpr>(Val: Call); |
7561 | Callee = CCE->getConstructor(); |
7562 | Args = llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()); |
7563 | } |
7564 | if (!Callee) |
7565 | return; |
7566 | |
7567 | Expr *ObjectArg = nullptr; |
7568 | if (isa<CXXOperatorCallExpr>(Val: Call) && Callee->isCXXInstanceMember()) { |
7569 | ObjectArg = Args[0]; |
7570 | Args = Args.slice(N: 1); |
7571 | } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Val: Call)) { |
7572 | ObjectArg = MCE->getImplicitObjectArgument(); |
7573 | } |
7574 | |
7575 | auto VisitLifetimeBoundArg = [&](const Decl *D, Expr *Arg) { |
7576 | Path.push_back(Elt: {IndirectLocalPathEntry::LifetimeBoundCall, Arg, D}); |
7577 | if (Arg->isGLValue()) |
7578 | visitLocalsRetainedByReferenceBinding(Path, Init: Arg, RK: RK_ReferenceBinding, |
7579 | Visit, |
7580 | /*EnableLifetimeWarnings=*/false); |
7581 | else |
7582 | visitLocalsRetainedByInitializer(Path, Init: Arg, Visit, RevisitSubinits: true, |
7583 | /*EnableLifetimeWarnings=*/false); |
7584 | Path.pop_back(); |
7585 | }; |
7586 | |
7587 | bool CheckCoroCall = false; |
7588 | if (const auto *RD = Callee->getReturnType()->getAsRecordDecl()) { |
7589 | CheckCoroCall = RD->hasAttr<CoroLifetimeBoundAttr>() && |
7590 | RD->hasAttr<CoroReturnTypeAttr>() && |
7591 | !Callee->hasAttr<CoroDisableLifetimeBoundAttr>(); |
7592 | } |
7593 | |
7594 | if (ObjectArg) { |
7595 | bool CheckCoroObjArg = CheckCoroCall; |
7596 | // Coroutine lambda objects with empty capture list are not lifetimebound. |
7597 | if (auto *LE = dyn_cast<LambdaExpr>(Val: ObjectArg->IgnoreImplicit()); |
7598 | LE && LE->captures().empty()) |
7599 | CheckCoroObjArg = false; |
7600 | // Allow `get_return_object()` as the object param (__promise) is not |
7601 | // lifetimebound. |
7602 | if (Sema::CanBeGetReturnObject(FD: Callee)) |
7603 | CheckCoroObjArg = false; |
7604 | if (implicitObjectParamIsLifetimeBound(FD: Callee) || CheckCoroObjArg) |
7605 | VisitLifetimeBoundArg(Callee, ObjectArg); |
7606 | } |
7607 | |
7608 | for (unsigned I = 0, |
7609 | N = std::min<unsigned>(a: Callee->getNumParams(), b: Args.size()); |
7610 | I != N; ++I) { |
7611 | if (CheckCoroCall || Callee->getParamDecl(I)->hasAttr<LifetimeBoundAttr>()) |
7612 | VisitLifetimeBoundArg(Callee->getParamDecl(i: I), Args[I]); |
7613 | } |
7614 | } |
7615 | |
7616 | /// Visit the locals that would be reachable through a reference bound to the |
7617 | /// glvalue expression \c Init. |
7618 | static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path, |
7619 | Expr *Init, ReferenceKind RK, |
7620 | LocalVisitor Visit, |
7621 | bool EnableLifetimeWarnings) { |
7622 | RevertToOldSizeRAII RAII(Path); |
7623 | |
7624 | // Walk past any constructs which we can lifetime-extend across. |
7625 | Expr *Old; |
7626 | do { |
7627 | Old = Init; |
7628 | |
7629 | if (auto *FE = dyn_cast<FullExpr>(Val: Init)) |
7630 | Init = FE->getSubExpr(); |
7631 | |
7632 | if (InitListExpr *ILE = dyn_cast<InitListExpr>(Val: Init)) { |
7633 | // If this is just redundant braces around an initializer, step over it. |
7634 | if (ILE->isTransparent()) |
7635 | Init = ILE->getInit(Init: 0); |
7636 | } |
7637 | |
7638 | // Step over any subobject adjustments; we may have a materialized |
7639 | // temporary inside them. |
7640 | Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments()); |
7641 | |
7642 | // Per current approach for DR1376, look through casts to reference type |
7643 | // when performing lifetime extension. |
7644 | if (CastExpr *CE = dyn_cast<CastExpr>(Val: Init)) |
7645 | if (CE->getSubExpr()->isGLValue()) |
7646 | Init = CE->getSubExpr(); |
7647 | |
7648 | // Per the current approach for DR1299, look through array element access |
7649 | // on array glvalues when performing lifetime extension. |
7650 | if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Val: Init)) { |
7651 | Init = ASE->getBase(); |
7652 | auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Init); |
7653 | if (ICE && ICE->getCastKind() == CK_ArrayToPointerDecay) |
7654 | Init = ICE->getSubExpr(); |
7655 | else |
7656 | // We can't lifetime extend through this but we might still find some |
7657 | // retained temporaries. |
7658 | return visitLocalsRetainedByInitializer(Path, Init, Visit, RevisitSubinits: true, |
7659 | EnableLifetimeWarnings); |
7660 | } |
7661 | |
7662 | // Step into CXXDefaultInitExprs so we can diagnose cases where a |
7663 | // constructor inherits one as an implicit mem-initializer. |
7664 | if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Val: Init)) { |
7665 | Path.push_back( |
7666 | {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()}); |
7667 | Init = DIE->getExpr(); |
7668 | } |
7669 | } while (Init != Old); |
7670 | |
7671 | if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: Init)) { |
7672 | if (Visit(Path, Local(MTE), RK)) |
7673 | visitLocalsRetainedByInitializer(Path, Init: MTE->getSubExpr(), Visit, RevisitSubinits: true, |
7674 | EnableLifetimeWarnings); |
7675 | } |
7676 | |
7677 | if (isa<CallExpr>(Val: Init)) { |
7678 | if (EnableLifetimeWarnings) |
7679 | handleGslAnnotatedTypes(Path, Call: Init, Visit); |
7680 | return visitLifetimeBoundArguments(Path, Call: Init, Visit); |
7681 | } |
7682 | |
7683 | switch (Init->getStmtClass()) { |
7684 | case Stmt::DeclRefExprClass: { |
7685 | // If we find the name of a local non-reference parameter, we could have a |
7686 | // lifetime problem. |
7687 | auto *DRE = cast<DeclRefExpr>(Val: Init); |
7688 | auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl()); |
7689 | if (VD && VD->hasLocalStorage() && |
7690 | !DRE->refersToEnclosingVariableOrCapture()) { |
7691 | if (!VD->getType()->isReferenceType()) { |
7692 | Visit(Path, Local(DRE), RK); |
7693 | } else if (isa<ParmVarDecl>(Val: DRE->getDecl())) { |
7694 | // The lifetime of a reference parameter is unknown; assume it's OK |
7695 | // for now. |
7696 | break; |
7697 | } else if (VD->getInit() && !isVarOnPath(Path, VD)) { |
7698 | Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD}); |
7699 | visitLocalsRetainedByReferenceBinding(Path, Init: VD->getInit(), |
7700 | RK: RK_ReferenceBinding, Visit, |
7701 | EnableLifetimeWarnings); |
7702 | } |
7703 | } |
7704 | break; |
7705 | } |
7706 | |
7707 | case Stmt::UnaryOperatorClass: { |
7708 | // The only unary operator that make sense to handle here |
7709 | // is Deref. All others don't resolve to a "name." This includes |
7710 | // handling all sorts of rvalues passed to a unary operator. |
7711 | const UnaryOperator *U = cast<UnaryOperator>(Val: Init); |
7712 | if (U->getOpcode() == UO_Deref) |
7713 | visitLocalsRetainedByInitializer(Path, Init: U->getSubExpr(), Visit, RevisitSubinits: true, |
7714 | EnableLifetimeWarnings); |
7715 | break; |
7716 | } |
7717 | |
7718 | case Stmt::OMPArraySectionExprClass: { |
7719 | visitLocalsRetainedByInitializer(Path, |
7720 | Init: cast<OMPArraySectionExpr>(Val: Init)->getBase(), |
7721 | Visit, RevisitSubinits: true, EnableLifetimeWarnings); |
7722 | break; |
7723 | } |
7724 | |
7725 | case Stmt::ConditionalOperatorClass: |
7726 | case Stmt::BinaryConditionalOperatorClass: { |
7727 | auto *C = cast<AbstractConditionalOperator>(Val: Init); |
7728 | if (!C->getTrueExpr()->getType()->isVoidType()) |
7729 | visitLocalsRetainedByReferenceBinding(Path, Init: C->getTrueExpr(), RK, Visit, |
7730 | EnableLifetimeWarnings); |
7731 | if (!C->getFalseExpr()->getType()->isVoidType()) |
7732 | visitLocalsRetainedByReferenceBinding(Path, Init: C->getFalseExpr(), RK, Visit, |
7733 | EnableLifetimeWarnings); |
7734 | break; |
7735 | } |
7736 | |
7737 | // FIXME: Visit the left-hand side of an -> or ->*. |
7738 | |
7739 | default: |
7740 | break; |
7741 | } |
7742 | } |
7743 | |
7744 | /// Visit the locals that would be reachable through an object initialized by |
7745 | /// the prvalue expression \c Init. |
7746 | static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path, |
7747 | Expr *Init, LocalVisitor Visit, |
7748 | bool RevisitSubinits, |
7749 | bool EnableLifetimeWarnings) { |
7750 | RevertToOldSizeRAII RAII(Path); |
7751 | |
7752 | Expr *Old; |
7753 | do { |
7754 | Old = Init; |
7755 | |
7756 | // Step into CXXDefaultInitExprs so we can diagnose cases where a |
7757 | // constructor inherits one as an implicit mem-initializer. |
7758 | if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Val: Init)) { |
7759 | Path.push_back({IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()}); |
7760 | Init = DIE->getExpr(); |
7761 | } |
7762 | |
7763 | if (auto *FE = dyn_cast<FullExpr>(Val: Init)) |
7764 | Init = FE->getSubExpr(); |
7765 | |
7766 | // Dig out the expression which constructs the extended temporary. |
7767 | Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments()); |
7768 | |
7769 | if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Val: Init)) |
7770 | Init = BTE->getSubExpr(); |
7771 | |
7772 | Init = Init->IgnoreParens(); |
7773 | |
7774 | // Step over value-preserving rvalue casts. |
7775 | if (auto *CE = dyn_cast<CastExpr>(Val: Init)) { |
7776 | switch (CE->getCastKind()) { |
7777 | case CK_LValueToRValue: |
7778 | // If we can match the lvalue to a const object, we can look at its |
7779 | // initializer. |
7780 | Path.push_back({IndirectLocalPathEntry::LValToRVal, CE}); |
7781 | return visitLocalsRetainedByReferenceBinding( |
7782 | Path, Init, RK: RK_ReferenceBinding, |
7783 | Visit: [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool { |
7784 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: L)) { |
7785 | auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl()); |
7786 | if (VD && VD->getType().isConstQualified() && VD->getInit() && |
7787 | !isVarOnPath(Path, VD)) { |
7788 | Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD}); |
7789 | visitLocalsRetainedByInitializer(Path, Init: VD->getInit(), Visit, RevisitSubinits: true, |
7790 | EnableLifetimeWarnings); |
7791 | } |
7792 | } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: L)) { |
7793 | if (MTE->getType().isConstQualified()) |
7794 | visitLocalsRetainedByInitializer(Path, Init: MTE->getSubExpr(), Visit, |
7795 | RevisitSubinits: true, EnableLifetimeWarnings); |
7796 | } |
7797 | return false; |
7798 | }, EnableLifetimeWarnings); |
7799 | |
7800 | // We assume that objects can be retained by pointers cast to integers, |
7801 | // but not if the integer is cast to floating-point type or to _Complex. |
7802 | // We assume that casts to 'bool' do not preserve enough information to |
7803 | // retain a local object. |
7804 | case CK_NoOp: |
7805 | case CK_BitCast: |
7806 | case CK_BaseToDerived: |
7807 | case CK_DerivedToBase: |
7808 | case CK_UncheckedDerivedToBase: |
7809 | case CK_Dynamic: |
7810 | case CK_ToUnion: |
7811 | case CK_UserDefinedConversion: |
7812 | case CK_ConstructorConversion: |
7813 | case CK_IntegralToPointer: |
7814 | case CK_PointerToIntegral: |
7815 | case CK_VectorSplat: |
7816 | case CK_IntegralCast: |
7817 | case CK_CPointerToObjCPointerCast: |
7818 | case CK_BlockPointerToObjCPointerCast: |
7819 | case CK_AnyPointerToBlockPointerCast: |
7820 | case CK_AddressSpaceConversion: |
7821 | break; |
7822 | |
7823 | case CK_ArrayToPointerDecay: |
7824 | // Model array-to-pointer decay as taking the address of the array |
7825 | // lvalue. |
7826 | Path.push_back({IndirectLocalPathEntry::AddressOf, CE}); |
7827 | return visitLocalsRetainedByReferenceBinding(Path, Init: CE->getSubExpr(), |
7828 | RK: RK_ReferenceBinding, Visit, |
7829 | EnableLifetimeWarnings); |
7830 | |
7831 | default: |
7832 | return; |
7833 | } |
7834 | |
7835 | Init = CE->getSubExpr(); |
7836 | } |
7837 | } while (Old != Init); |
7838 | |
7839 | // C++17 [dcl.init.list]p6: |
7840 | // initializing an initializer_list object from the array extends the |
7841 | // lifetime of the array exactly like binding a reference to a temporary. |
7842 | if (auto *ILE = dyn_cast<CXXStdInitializerListExpr>(Val: Init)) |
7843 | return visitLocalsRetainedByReferenceBinding(Path, Init: ILE->getSubExpr(), |
7844 | RK: RK_StdInitializerList, Visit, |
7845 | EnableLifetimeWarnings); |
7846 | |
7847 | if (InitListExpr *ILE = dyn_cast<InitListExpr>(Val: Init)) { |
7848 | // We already visited the elements of this initializer list while |
7849 | // performing the initialization. Don't visit them again unless we've |
7850 | // changed the lifetime of the initialized entity. |
7851 | if (!RevisitSubinits) |
7852 | return; |
7853 | |
7854 | if (ILE->isTransparent()) |
7855 | return visitLocalsRetainedByInitializer(Path, Init: ILE->getInit(Init: 0), Visit, |
7856 | RevisitSubinits, |
7857 | EnableLifetimeWarnings); |
7858 | |
7859 | if (ILE->getType()->isArrayType()) { |
7860 | for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I) |
7861 | visitLocalsRetainedByInitializer(Path, Init: ILE->getInit(Init: I), Visit, |
7862 | RevisitSubinits, |
7863 | EnableLifetimeWarnings); |
7864 | return; |
7865 | } |
7866 | |
7867 | if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) { |
7868 | assert(RD->isAggregate() && "aggregate init on non-aggregate" ); |
7869 | |
7870 | // If we lifetime-extend a braced initializer which is initializing an |
7871 | // aggregate, and that aggregate contains reference members which are |
7872 | // bound to temporaries, those temporaries are also lifetime-extended. |
7873 | if (RD->isUnion() && ILE->getInitializedFieldInUnion() && |
7874 | ILE->getInitializedFieldInUnion()->getType()->isReferenceType()) |
7875 | visitLocalsRetainedByReferenceBinding(Path, Init: ILE->getInit(Init: 0), |
7876 | RK: RK_ReferenceBinding, Visit, |
7877 | EnableLifetimeWarnings); |
7878 | else { |
7879 | unsigned Index = 0; |
7880 | for (; Index < RD->getNumBases() && Index < ILE->getNumInits(); ++Index) |
7881 | visitLocalsRetainedByInitializer(Path, Init: ILE->getInit(Init: Index), Visit, |
7882 | RevisitSubinits, |
7883 | EnableLifetimeWarnings); |
7884 | for (const auto *I : RD->fields()) { |
7885 | if (Index >= ILE->getNumInits()) |
7886 | break; |
7887 | if (I->isUnnamedBitfield()) |
7888 | continue; |
7889 | Expr *SubInit = ILE->getInit(Index); |
7890 | if (I->getType()->isReferenceType()) |
7891 | visitLocalsRetainedByReferenceBinding(Path, SubInit, |
7892 | RK_ReferenceBinding, Visit, |
7893 | EnableLifetimeWarnings); |
7894 | else |
7895 | // This might be either aggregate-initialization of a member or |
7896 | // initialization of a std::initializer_list object. Regardless, |
7897 | // we should recursively lifetime-extend that initializer. |
7898 | visitLocalsRetainedByInitializer(Path, SubInit, Visit, |
7899 | RevisitSubinits, |
7900 | EnableLifetimeWarnings); |
7901 | ++Index; |
7902 | } |
7903 | } |
7904 | } |
7905 | return; |
7906 | } |
7907 | |
7908 | // The lifetime of an init-capture is that of the closure object constructed |
7909 | // by a lambda-expression. |
7910 | if (auto *LE = dyn_cast<LambdaExpr>(Val: Init)) { |
7911 | LambdaExpr::capture_iterator CapI = LE->capture_begin(); |
7912 | for (Expr *E : LE->capture_inits()) { |
7913 | assert(CapI != LE->capture_end()); |
7914 | const LambdaCapture &Cap = *CapI++; |
7915 | if (!E) |
7916 | continue; |
7917 | if (Cap.capturesVariable()) |
7918 | Path.push_back(Elt: {IndirectLocalPathEntry::LambdaCaptureInit, E, &Cap}); |
7919 | if (E->isGLValue()) |
7920 | visitLocalsRetainedByReferenceBinding(Path, Init: E, RK: RK_ReferenceBinding, |
7921 | Visit, EnableLifetimeWarnings); |
7922 | else |
7923 | visitLocalsRetainedByInitializer(Path, Init: E, Visit, RevisitSubinits: true, |
7924 | EnableLifetimeWarnings); |
7925 | if (Cap.capturesVariable()) |
7926 | Path.pop_back(); |
7927 | } |
7928 | } |
7929 | |
7930 | // Assume that a copy or move from a temporary references the same objects |
7931 | // that the temporary does. |
7932 | if (auto *CCE = dyn_cast<CXXConstructExpr>(Val: Init)) { |
7933 | if (CCE->getConstructor()->isCopyOrMoveConstructor()) { |
7934 | if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: CCE->getArg(Arg: 0))) { |
7935 | Expr *Arg = MTE->getSubExpr(); |
7936 | Path.push_back({IndirectLocalPathEntry::TemporaryCopy, Arg, |
7937 | CCE->getConstructor()}); |
7938 | visitLocalsRetainedByInitializer(Path, Init: Arg, Visit, RevisitSubinits: true, |
7939 | /*EnableLifetimeWarnings*/false); |
7940 | Path.pop_back(); |
7941 | } |
7942 | } |
7943 | } |
7944 | |
7945 | if (isa<CallExpr>(Val: Init) || isa<CXXConstructExpr>(Val: Init)) { |
7946 | if (EnableLifetimeWarnings) |
7947 | handleGslAnnotatedTypes(Path, Call: Init, Visit); |
7948 | return visitLifetimeBoundArguments(Path, Call: Init, Visit); |
7949 | } |
7950 | |
7951 | switch (Init->getStmtClass()) { |
7952 | case Stmt::UnaryOperatorClass: { |
7953 | auto *UO = cast<UnaryOperator>(Val: Init); |
7954 | // If the initializer is the address of a local, we could have a lifetime |
7955 | // problem. |
7956 | if (UO->getOpcode() == UO_AddrOf) { |
7957 | // If this is &rvalue, then it's ill-formed and we have already diagnosed |
7958 | // it. Don't produce a redundant warning about the lifetime of the |
7959 | // temporary. |
7960 | if (isa<MaterializeTemporaryExpr>(Val: UO->getSubExpr())) |
7961 | return; |
7962 | |
7963 | Path.push_back({IndirectLocalPathEntry::AddressOf, UO}); |
7964 | visitLocalsRetainedByReferenceBinding(Path, Init: UO->getSubExpr(), |
7965 | RK: RK_ReferenceBinding, Visit, |
7966 | EnableLifetimeWarnings); |
7967 | } |
7968 | break; |
7969 | } |
7970 | |
7971 | case Stmt::BinaryOperatorClass: { |
7972 | // Handle pointer arithmetic. |
7973 | auto *BO = cast<BinaryOperator>(Val: Init); |
7974 | BinaryOperatorKind BOK = BO->getOpcode(); |
7975 | if (!BO->getType()->isPointerType() || (BOK != BO_Add && BOK != BO_Sub)) |
7976 | break; |
7977 | |
7978 | if (BO->getLHS()->getType()->isPointerType()) |
7979 | visitLocalsRetainedByInitializer(Path, Init: BO->getLHS(), Visit, RevisitSubinits: true, |
7980 | EnableLifetimeWarnings); |
7981 | else if (BO->getRHS()->getType()->isPointerType()) |
7982 | visitLocalsRetainedByInitializer(Path, Init: BO->getRHS(), Visit, RevisitSubinits: true, |
7983 | EnableLifetimeWarnings); |
7984 | break; |
7985 | } |
7986 | |
7987 | case Stmt::ConditionalOperatorClass: |
7988 | case Stmt::BinaryConditionalOperatorClass: { |
7989 | auto *C = cast<AbstractConditionalOperator>(Val: Init); |
7990 | // In C++, we can have a throw-expression operand, which has 'void' type |
7991 | // and isn't interesting from a lifetime perspective. |
7992 | if (!C->getTrueExpr()->getType()->isVoidType()) |
7993 | visitLocalsRetainedByInitializer(Path, Init: C->getTrueExpr(), Visit, RevisitSubinits: true, |
7994 | EnableLifetimeWarnings); |
7995 | if (!C->getFalseExpr()->getType()->isVoidType()) |
7996 | visitLocalsRetainedByInitializer(Path, Init: C->getFalseExpr(), Visit, RevisitSubinits: true, |
7997 | EnableLifetimeWarnings); |
7998 | break; |
7999 | } |
8000 | |
8001 | case Stmt::BlockExprClass: |
8002 | if (cast<BlockExpr>(Val: Init)->getBlockDecl()->hasCaptures()) { |
8003 | // This is a local block, whose lifetime is that of the function. |
8004 | Visit(Path, Local(cast<BlockExpr>(Val: Init)), RK_ReferenceBinding); |
8005 | } |
8006 | break; |
8007 | |
8008 | case Stmt::AddrLabelExprClass: |
8009 | // We want to warn if the address of a label would escape the function. |
8010 | Visit(Path, Local(cast<AddrLabelExpr>(Val: Init)), RK_ReferenceBinding); |
8011 | break; |
8012 | |
8013 | default: |
8014 | break; |
8015 | } |
8016 | } |
8017 | |
8018 | /// Whether a path to an object supports lifetime extension. |
8019 | enum PathLifetimeKind { |
8020 | /// Lifetime-extend along this path. |
8021 | Extend, |
8022 | /// We should lifetime-extend, but we don't because (due to technical |
8023 | /// limitations) we can't. This happens for default member initializers, |
8024 | /// which we don't clone for every use, so we don't have a unique |
8025 | /// MaterializeTemporaryExpr to update. |
8026 | ShouldExtend, |
8027 | /// Do not lifetime extend along this path. |
8028 | NoExtend |
8029 | }; |
8030 | |
8031 | /// Determine whether this is an indirect path to a temporary that we are |
8032 | /// supposed to lifetime-extend along. |
8033 | static PathLifetimeKind |
8034 | shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path) { |
8035 | PathLifetimeKind Kind = PathLifetimeKind::Extend; |
8036 | for (auto Elem : Path) { |
8037 | if (Elem.Kind == IndirectLocalPathEntry::DefaultInit) |
8038 | Kind = PathLifetimeKind::ShouldExtend; |
8039 | else if (Elem.Kind != IndirectLocalPathEntry::LambdaCaptureInit) |
8040 | return PathLifetimeKind::NoExtend; |
8041 | } |
8042 | return Kind; |
8043 | } |
8044 | |
8045 | /// Find the range for the first interesting entry in the path at or after I. |
8046 | static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I, |
8047 | Expr *E) { |
8048 | for (unsigned N = Path.size(); I != N; ++I) { |
8049 | switch (Path[I].Kind) { |
8050 | case IndirectLocalPathEntry::AddressOf: |
8051 | case IndirectLocalPathEntry::LValToRVal: |
8052 | case IndirectLocalPathEntry::LifetimeBoundCall: |
8053 | case IndirectLocalPathEntry::TemporaryCopy: |
8054 | case IndirectLocalPathEntry::GslReferenceInit: |
8055 | case IndirectLocalPathEntry::GslPointerInit: |
8056 | // These exist primarily to mark the path as not permitting or |
8057 | // supporting lifetime extension. |
8058 | break; |
8059 | |
8060 | case IndirectLocalPathEntry::VarInit: |
8061 | if (cast<VarDecl>(Val: Path[I].D)->isImplicit()) |
8062 | return SourceRange(); |
8063 | [[fallthrough]]; |
8064 | case IndirectLocalPathEntry::DefaultInit: |
8065 | return Path[I].E->getSourceRange(); |
8066 | |
8067 | case IndirectLocalPathEntry::LambdaCaptureInit: |
8068 | if (!Path[I].Capture->capturesVariable()) |
8069 | continue; |
8070 | return Path[I].E->getSourceRange(); |
8071 | } |
8072 | } |
8073 | return E->getSourceRange(); |
8074 | } |
8075 | |
8076 | static bool pathOnlyInitializesGslPointer(IndirectLocalPath &Path) { |
8077 | for (const auto &It : llvm::reverse(C&: Path)) { |
8078 | if (It.Kind == IndirectLocalPathEntry::VarInit) |
8079 | continue; |
8080 | if (It.Kind == IndirectLocalPathEntry::AddressOf) |
8081 | continue; |
8082 | if (It.Kind == IndirectLocalPathEntry::LifetimeBoundCall) |
8083 | continue; |
8084 | return It.Kind == IndirectLocalPathEntry::GslPointerInit || |
8085 | It.Kind == IndirectLocalPathEntry::GslReferenceInit; |
8086 | } |
8087 | return false; |
8088 | } |
8089 | |
8090 | void Sema::checkInitializerLifetime(const InitializedEntity &Entity, |
8091 | Expr *Init) { |
8092 | LifetimeResult LR = getEntityLifetime(Entity: &Entity); |
8093 | LifetimeKind LK = LR.getInt(); |
8094 | const InitializedEntity *ExtendingEntity = LR.getPointer(); |
8095 | |
8096 | // If this entity doesn't have an interesting lifetime, don't bother looking |
8097 | // for temporaries within its initializer. |
8098 | if (LK == LK_FullExpression) |
8099 | return; |
8100 | |
8101 | auto TemporaryVisitor = [&](IndirectLocalPath &Path, Local L, |
8102 | ReferenceKind RK) -> bool { |
8103 | SourceRange DiagRange = nextPathEntryRange(Path, I: 0, E: L); |
8104 | SourceLocation DiagLoc = DiagRange.getBegin(); |
8105 | |
8106 | auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: L); |
8107 | |
8108 | bool IsGslPtrInitWithGslTempOwner = false; |
8109 | bool IsLocalGslOwner = false; |
8110 | if (pathOnlyInitializesGslPointer(Path)) { |
8111 | if (isa<DeclRefExpr>(Val: L)) { |
8112 | // We do not want to follow the references when returning a pointer originating |
8113 | // from a local owner to avoid the following false positive: |
8114 | // int &p = *localUniquePtr; |
8115 | // someContainer.add(std::move(localUniquePtr)); |
8116 | // return p; |
8117 | IsLocalGslOwner = isRecordWithAttr<OwnerAttr>(L->getType()); |
8118 | if (pathContainsInit(Path) || !IsLocalGslOwner) |
8119 | return false; |
8120 | } else { |
8121 | IsGslPtrInitWithGslTempOwner = MTE && !MTE->getExtendingDecl() && |
8122 | isRecordWithAttr<OwnerAttr>(MTE->getType()); |
8123 | // Skipping a chain of initializing gsl::Pointer annotated objects. |
8124 | // We are looking only for the final source to find out if it was |
8125 | // a local or temporary owner or the address of a local variable/param. |
8126 | if (!IsGslPtrInitWithGslTempOwner) |
8127 | return true; |
8128 | } |
8129 | } |
8130 | |
8131 | switch (LK) { |
8132 | case LK_FullExpression: |
8133 | llvm_unreachable("already handled this" ); |
8134 | |
8135 | case LK_Extended: { |
8136 | if (!MTE) { |
8137 | // The initialized entity has lifetime beyond the full-expression, |
8138 | // and the local entity does too, so don't warn. |
8139 | // |
8140 | // FIXME: We should consider warning if a static / thread storage |
8141 | // duration variable retains an automatic storage duration local. |
8142 | return false; |
8143 | } |
8144 | |
8145 | if (IsGslPtrInitWithGslTempOwner && DiagLoc.isValid()) { |
8146 | Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange; |
8147 | return false; |
8148 | } |
8149 | |
8150 | switch (shouldLifetimeExtendThroughPath(Path)) { |
8151 | case PathLifetimeKind::Extend: |
8152 | // Update the storage duration of the materialized temporary. |
8153 | // FIXME: Rebuild the expression instead of mutating it. |
8154 | MTE->setExtendingDecl(ExtendedBy: ExtendingEntity->getDecl(), |
8155 | ManglingNumber: ExtendingEntity->allocateManglingNumber()); |
8156 | // Also visit the temporaries lifetime-extended by this initializer. |
8157 | return true; |
8158 | |
8159 | case PathLifetimeKind::ShouldExtend: |
8160 | // We're supposed to lifetime-extend the temporary along this path (per |
8161 | // the resolution of DR1815), but we don't support that yet. |
8162 | // |
8163 | // FIXME: Properly handle this situation. Perhaps the easiest approach |
8164 | // would be to clone the initializer expression on each use that would |
8165 | // lifetime extend its temporaries. |
8166 | Diag(DiagLoc, diag::warn_unsupported_lifetime_extension) |
8167 | << RK << DiagRange; |
8168 | break; |
8169 | |
8170 | case PathLifetimeKind::NoExtend: |
8171 | // If the path goes through the initialization of a variable or field, |
8172 | // it can't possibly reach a temporary created in this full-expression. |
8173 | // We will have already diagnosed any problems with the initializer. |
8174 | if (pathContainsInit(Path)) |
8175 | return false; |
8176 | |
8177 | Diag(DiagLoc, diag::warn_dangling_variable) |
8178 | << RK << !Entity.getParent() |
8179 | << ExtendingEntity->getDecl()->isImplicit() |
8180 | << ExtendingEntity->getDecl() << Init->isGLValue() << DiagRange; |
8181 | break; |
8182 | } |
8183 | break; |
8184 | } |
8185 | |
8186 | case LK_MemInitializer: { |
8187 | if (isa<MaterializeTemporaryExpr>(Val: L)) { |
8188 | // Under C++ DR1696, if a mem-initializer (or a default member |
8189 | // initializer used by the absence of one) would lifetime-extend a |
8190 | // temporary, the program is ill-formed. |
8191 | if (auto *ExtendingDecl = |
8192 | ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) { |
8193 | if (IsGslPtrInitWithGslTempOwner) { |
8194 | Diag(DiagLoc, diag::warn_dangling_lifetime_pointer_member) |
8195 | << ExtendingDecl << DiagRange; |
8196 | Diag(ExtendingDecl->getLocation(), |
8197 | diag::note_ref_or_ptr_member_declared_here) |
8198 | << true; |
8199 | return false; |
8200 | } |
8201 | bool IsSubobjectMember = ExtendingEntity != &Entity; |
8202 | Diag(DiagLoc, shouldLifetimeExtendThroughPath(Path) != |
8203 | PathLifetimeKind::NoExtend |
8204 | ? diag::err_dangling_member |
8205 | : diag::warn_dangling_member) |
8206 | << ExtendingDecl << IsSubobjectMember << RK << DiagRange; |
8207 | // Don't bother adding a note pointing to the field if we're inside |
8208 | // its default member initializer; our primary diagnostic points to |
8209 | // the same place in that case. |
8210 | if (Path.empty() || |
8211 | Path.back().Kind != IndirectLocalPathEntry::DefaultInit) { |
8212 | Diag(ExtendingDecl->getLocation(), |
8213 | diag::note_lifetime_extending_member_declared_here) |
8214 | << RK << IsSubobjectMember; |
8215 | } |
8216 | } else { |
8217 | // We have a mem-initializer but no particular field within it; this |
8218 | // is either a base class or a delegating initializer directly |
8219 | // initializing the base-class from something that doesn't live long |
8220 | // enough. |
8221 | // |
8222 | // FIXME: Warn on this. |
8223 | return false; |
8224 | } |
8225 | } else { |
8226 | // Paths via a default initializer can only occur during error recovery |
8227 | // (there's no other way that a default initializer can refer to a |
8228 | // local). Don't produce a bogus warning on those cases. |
8229 | if (pathContainsInit(Path)) |
8230 | return false; |
8231 | |
8232 | // Suppress false positives for code like the one below: |
8233 | // Ctor(unique_ptr<T> up) : member(*up), member2(move(up)) {} |
8234 | if (IsLocalGslOwner && pathOnlyInitializesGslPointer(Path)) |
8235 | return false; |
8236 | |
8237 | auto *DRE = dyn_cast<DeclRefExpr>(Val: L); |
8238 | auto *VD = DRE ? dyn_cast<VarDecl>(Val: DRE->getDecl()) : nullptr; |
8239 | if (!VD) { |
8240 | // A member was initialized to a local block. |
8241 | // FIXME: Warn on this. |
8242 | return false; |
8243 | } |
8244 | |
8245 | if (auto *Member = |
8246 | ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) { |
8247 | bool IsPointer = !Member->getType()->isReferenceType(); |
8248 | Diag(DiagLoc, IsPointer ? diag::warn_init_ptr_member_to_parameter_addr |
8249 | : diag::warn_bind_ref_member_to_parameter) |
8250 | << Member << VD << isa<ParmVarDecl>(VD) << DiagRange; |
8251 | Diag(Member->getLocation(), |
8252 | diag::note_ref_or_ptr_member_declared_here) |
8253 | << (unsigned)IsPointer; |
8254 | } |
8255 | } |
8256 | break; |
8257 | } |
8258 | |
8259 | case LK_New: |
8260 | if (isa<MaterializeTemporaryExpr>(Val: L)) { |
8261 | if (IsGslPtrInitWithGslTempOwner) |
8262 | Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange; |
8263 | else |
8264 | Diag(DiagLoc, RK == RK_ReferenceBinding |
8265 | ? diag::warn_new_dangling_reference |
8266 | : diag::warn_new_dangling_initializer_list) |
8267 | << !Entity.getParent() << DiagRange; |
8268 | } else { |
8269 | // We can't determine if the allocation outlives the local declaration. |
8270 | return false; |
8271 | } |
8272 | break; |
8273 | |
8274 | case LK_Return: |
8275 | case LK_StmtExprResult: |
8276 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: L)) { |
8277 | // We can't determine if the local variable outlives the statement |
8278 | // expression. |
8279 | if (LK == LK_StmtExprResult) |
8280 | return false; |
8281 | Diag(DiagLoc, diag::warn_ret_stack_addr_ref) |
8282 | << Entity.getType()->isReferenceType() << DRE->getDecl() |
8283 | << isa<ParmVarDecl>(DRE->getDecl()) << DiagRange; |
8284 | } else if (isa<BlockExpr>(Val: L)) { |
8285 | Diag(DiagLoc, diag::err_ret_local_block) << DiagRange; |
8286 | } else if (isa<AddrLabelExpr>(Val: L)) { |
8287 | // Don't warn when returning a label from a statement expression. |
8288 | // Leaving the scope doesn't end its lifetime. |
8289 | if (LK == LK_StmtExprResult) |
8290 | return false; |
8291 | Diag(DiagLoc, diag::warn_ret_addr_label) << DiagRange; |
8292 | } else { |
8293 | Diag(DiagLoc, diag::warn_ret_local_temp_addr_ref) |
8294 | << Entity.getType()->isReferenceType() << DiagRange; |
8295 | } |
8296 | break; |
8297 | } |
8298 | |
8299 | for (unsigned I = 0; I != Path.size(); ++I) { |
8300 | auto Elem = Path[I]; |
8301 | |
8302 | switch (Elem.Kind) { |
8303 | case IndirectLocalPathEntry::AddressOf: |
8304 | case IndirectLocalPathEntry::LValToRVal: |
8305 | // These exist primarily to mark the path as not permitting or |
8306 | // supporting lifetime extension. |
8307 | break; |
8308 | |
8309 | case IndirectLocalPathEntry::LifetimeBoundCall: |
8310 | case IndirectLocalPathEntry::TemporaryCopy: |
8311 | case IndirectLocalPathEntry::GslPointerInit: |
8312 | case IndirectLocalPathEntry::GslReferenceInit: |
8313 | // FIXME: Consider adding a note for these. |
8314 | break; |
8315 | |
8316 | case IndirectLocalPathEntry::DefaultInit: { |
8317 | auto *FD = cast<FieldDecl>(Val: Elem.D); |
8318 | Diag(FD->getLocation(), diag::note_init_with_default_member_initializer) |
8319 | << FD << nextPathEntryRange(Path, I + 1, L); |
8320 | break; |
8321 | } |
8322 | |
8323 | case IndirectLocalPathEntry::VarInit: { |
8324 | const VarDecl *VD = cast<VarDecl>(Val: Elem.D); |
8325 | Diag(VD->getLocation(), diag::note_local_var_initializer) |
8326 | << VD->getType()->isReferenceType() |
8327 | << VD->isImplicit() << VD->getDeclName() |
8328 | << nextPathEntryRange(Path, I + 1, L); |
8329 | break; |
8330 | } |
8331 | |
8332 | case IndirectLocalPathEntry::LambdaCaptureInit: |
8333 | if (!Elem.Capture->capturesVariable()) |
8334 | break; |
8335 | // FIXME: We can't easily tell apart an init-capture from a nested |
8336 | // capture of an init-capture. |
8337 | const ValueDecl *VD = Elem.Capture->getCapturedVar(); |
8338 | Diag(Elem.Capture->getLocation(), diag::note_lambda_capture_initializer) |
8339 | << VD << VD->isInitCapture() << Elem.Capture->isExplicit() |
8340 | << (Elem.Capture->getCaptureKind() == LCK_ByRef) << VD |
8341 | << nextPathEntryRange(Path, I + 1, L); |
8342 | break; |
8343 | } |
8344 | } |
8345 | |
8346 | // We didn't lifetime-extend, so don't go any further; we don't need more |
8347 | // warnings or errors on inner temporaries within this one's initializer. |
8348 | return false; |
8349 | }; |
8350 | |
8351 | bool EnableLifetimeWarnings = !getDiagnostics().isIgnored( |
8352 | diag::warn_dangling_lifetime_pointer, SourceLocation()); |
8353 | llvm::SmallVector<IndirectLocalPathEntry, 8> Path; |
8354 | if (Init->isGLValue()) |
8355 | visitLocalsRetainedByReferenceBinding(Path, Init, RK: RK_ReferenceBinding, |
8356 | Visit: TemporaryVisitor, |
8357 | EnableLifetimeWarnings); |
8358 | else |
8359 | visitLocalsRetainedByInitializer(Path, Init, Visit: TemporaryVisitor, RevisitSubinits: false, |
8360 | EnableLifetimeWarnings); |
8361 | } |
8362 | |
8363 | static void DiagnoseNarrowingInInitList(Sema &S, |
8364 | const ImplicitConversionSequence &ICS, |
8365 | QualType PreNarrowingType, |
8366 | QualType EntityType, |
8367 | const Expr *PostInit); |
8368 | |
8369 | /// Provide warnings when std::move is used on construction. |
8370 | static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr, |
8371 | bool IsReturnStmt) { |
8372 | if (!InitExpr) |
8373 | return; |
8374 | |
8375 | if (S.inTemplateInstantiation()) |
8376 | return; |
8377 | |
8378 | QualType DestType = InitExpr->getType(); |
8379 | if (!DestType->isRecordType()) |
8380 | return; |
8381 | |
8382 | unsigned DiagID = 0; |
8383 | if (IsReturnStmt) { |
8384 | const CXXConstructExpr *CCE = |
8385 | dyn_cast<CXXConstructExpr>(Val: InitExpr->IgnoreParens()); |
8386 | if (!CCE || CCE->getNumArgs() != 1) |
8387 | return; |
8388 | |
8389 | if (!CCE->getConstructor()->isCopyOrMoveConstructor()) |
8390 | return; |
8391 | |
8392 | InitExpr = CCE->getArg(Arg: 0)->IgnoreImpCasts(); |
8393 | } |
8394 | |
8395 | // Find the std::move call and get the argument. |
8396 | const CallExpr *CE = dyn_cast<CallExpr>(Val: InitExpr->IgnoreParens()); |
8397 | if (!CE || !CE->isCallToStdMove()) |
8398 | return; |
8399 | |
8400 | const Expr *Arg = CE->getArg(Arg: 0)->IgnoreImplicit(); |
8401 | |
8402 | if (IsReturnStmt) { |
8403 | const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Arg->IgnoreParenImpCasts()); |
8404 | if (!DRE || DRE->refersToEnclosingVariableOrCapture()) |
8405 | return; |
8406 | |
8407 | const VarDecl *VD = dyn_cast<VarDecl>(Val: DRE->getDecl()); |
8408 | if (!VD || !VD->hasLocalStorage()) |
8409 | return; |
8410 | |
8411 | // __block variables are not moved implicitly. |
8412 | if (VD->hasAttr<BlocksAttr>()) |
8413 | return; |
8414 | |
8415 | QualType SourceType = VD->getType(); |
8416 | if (!SourceType->isRecordType()) |
8417 | return; |
8418 | |
8419 | if (!S.Context.hasSameUnqualifiedType(T1: DestType, T2: SourceType)) { |
8420 | return; |
8421 | } |
8422 | |
8423 | // If we're returning a function parameter, copy elision |
8424 | // is not possible. |
8425 | if (isa<ParmVarDecl>(VD)) |
8426 | DiagID = diag::warn_redundant_move_on_return; |
8427 | else |
8428 | DiagID = diag::warn_pessimizing_move_on_return; |
8429 | } else { |
8430 | DiagID = diag::warn_pessimizing_move_on_initialization; |
8431 | const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens(); |
8432 | if (!ArgStripped->isPRValue() || !ArgStripped->getType()->isRecordType()) |
8433 | return; |
8434 | } |
8435 | |
8436 | S.Diag(Loc: CE->getBeginLoc(), DiagID); |
8437 | |
8438 | // Get all the locations for a fix-it. Don't emit the fix-it if any location |
8439 | // is within a macro. |
8440 | SourceLocation CallBegin = CE->getCallee()->getBeginLoc(); |
8441 | if (CallBegin.isMacroID()) |
8442 | return; |
8443 | SourceLocation RParen = CE->getRParenLoc(); |
8444 | if (RParen.isMacroID()) |
8445 | return; |
8446 | SourceLocation LParen; |
8447 | SourceLocation ArgLoc = Arg->getBeginLoc(); |
8448 | |
8449 | // Special testing for the argument location. Since the fix-it needs the |
8450 | // location right before the argument, the argument location can be in a |
8451 | // macro only if it is at the beginning of the macro. |
8452 | while (ArgLoc.isMacroID() && |
8453 | S.getSourceManager().isAtStartOfImmediateMacroExpansion(Loc: ArgLoc)) { |
8454 | ArgLoc = S.getSourceManager().getImmediateExpansionRange(Loc: ArgLoc).getBegin(); |
8455 | } |
8456 | |
8457 | if (LParen.isMacroID()) |
8458 | return; |
8459 | |
8460 | LParen = ArgLoc.getLocWithOffset(Offset: -1); |
8461 | |
8462 | S.Diag(CE->getBeginLoc(), diag::note_remove_move) |
8463 | << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen)) |
8464 | << FixItHint::CreateRemoval(SourceRange(RParen, RParen)); |
8465 | } |
8466 | |
8467 | static void CheckForNullPointerDereference(Sema &S, const Expr *E) { |
8468 | // Check to see if we are dereferencing a null pointer. If so, this is |
8469 | // undefined behavior, so warn about it. This only handles the pattern |
8470 | // "*null", which is a very syntactic check. |
8471 | if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: E->IgnoreParenCasts())) |
8472 | if (UO->getOpcode() == UO_Deref && |
8473 | UO->getSubExpr()->IgnoreParenCasts()-> |
8474 | isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNotNull)) { |
8475 | S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, |
8476 | S.PDiag(diag::warn_binding_null_to_reference) |
8477 | << UO->getSubExpr()->getSourceRange()); |
8478 | } |
8479 | } |
8480 | |
8481 | MaterializeTemporaryExpr * |
8482 | Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, |
8483 | bool BoundToLvalueReference) { |
8484 | auto MTE = new (Context) |
8485 | MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference); |
8486 | |
8487 | // Order an ExprWithCleanups for lifetime marks. |
8488 | // |
8489 | // TODO: It'll be good to have a single place to check the access of the |
8490 | // destructor and generate ExprWithCleanups for various uses. Currently these |
8491 | // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary, |
8492 | // but there may be a chance to merge them. |
8493 | Cleanup.setExprNeedsCleanups(false); |
8494 | if (isInLifetimeExtendingContext()) { |
8495 | auto &Record = ExprEvalContexts.back(); |
8496 | Record.ForRangeLifetimeExtendTemps.push_back(Elt: MTE); |
8497 | } |
8498 | return MTE; |
8499 | } |
8500 | |
8501 | ExprResult Sema::TemporaryMaterializationConversion(Expr *E) { |
8502 | // In C++98, we don't want to implicitly create an xvalue. |
8503 | // FIXME: This means that AST consumers need to deal with "prvalues" that |
8504 | // denote materialized temporaries. Maybe we should add another ValueKind |
8505 | // for "xvalue pretending to be a prvalue" for C++98 support. |
8506 | if (!E->isPRValue() || !getLangOpts().CPlusPlus11) |
8507 | return E; |
8508 | |
8509 | // C++1z [conv.rval]/1: T shall be a complete type. |
8510 | // FIXME: Does this ever matter (can we form a prvalue of incomplete type)? |
8511 | // If so, we should check for a non-abstract class type here too. |
8512 | QualType T = E->getType(); |
8513 | if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type)) |
8514 | return ExprError(); |
8515 | |
8516 | return CreateMaterializeTemporaryExpr(T: E->getType(), Temporary: E, BoundToLvalueReference: false); |
8517 | } |
8518 | |
8519 | ExprResult Sema::PerformQualificationConversion(Expr *E, QualType Ty, |
8520 | ExprValueKind VK, |
8521 | CheckedConversionKind CCK) { |
8522 | |
8523 | CastKind CK = CK_NoOp; |
8524 | |
8525 | if (VK == VK_PRValue) { |
8526 | auto PointeeTy = Ty->getPointeeType(); |
8527 | auto ExprPointeeTy = E->getType()->getPointeeType(); |
8528 | if (!PointeeTy.isNull() && |
8529 | PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace()) |
8530 | CK = CK_AddressSpaceConversion; |
8531 | } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) { |
8532 | CK = CK_AddressSpaceConversion; |
8533 | } |
8534 | |
8535 | return ImpCastExprToType(E, Type: Ty, CK, VK, /*BasePath=*/nullptr, CCK); |
8536 | } |
8537 | |
8538 | ExprResult InitializationSequence::Perform(Sema &S, |
8539 | const InitializedEntity &Entity, |
8540 | const InitializationKind &Kind, |
8541 | MultiExprArg Args, |
8542 | QualType *ResultType) { |
8543 | if (Failed()) { |
8544 | Diagnose(S, Entity, Kind, Args); |
8545 | return ExprError(); |
8546 | } |
8547 | if (!ZeroInitializationFixit.empty()) { |
8548 | const Decl *D = Entity.getDecl(); |
8549 | const auto *VD = dyn_cast_or_null<VarDecl>(Val: D); |
8550 | QualType DestType = Entity.getType(); |
8551 | |
8552 | // The initialization would have succeeded with this fixit. Since the fixit |
8553 | // is on the error, we need to build a valid AST in this case, so this isn't |
8554 | // handled in the Failed() branch above. |
8555 | if (!DestType->isRecordType() && VD && VD->isConstexpr()) { |
8556 | // Use a more useful diagnostic for constexpr variables. |
8557 | S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init) |
8558 | << VD |
8559 | << FixItHint::CreateInsertion(ZeroInitializationFixitLoc, |
8560 | ZeroInitializationFixit); |
8561 | } else { |
8562 | unsigned DiagID = diag::err_default_init_const; |
8563 | if (S.getLangOpts().MSVCCompat && D && D->hasAttr<SelectAnyAttr>()) |
8564 | DiagID = diag::ext_default_init_const; |
8565 | |
8566 | S.Diag(Loc: Kind.getLocation(), DiagID) |
8567 | << DestType << (bool)DestType->getAs<RecordType>() |
8568 | << FixItHint::CreateInsertion(InsertionLoc: ZeroInitializationFixitLoc, |
8569 | Code: ZeroInitializationFixit); |
8570 | } |
8571 | } |
8572 | |
8573 | if (getKind() == DependentSequence) { |
8574 | // If the declaration is a non-dependent, incomplete array type |
8575 | // that has an initializer, then its type will be completed once |
8576 | // the initializer is instantiated. |
8577 | if (ResultType && !Entity.getType()->isDependentType() && |
8578 | Args.size() == 1) { |
8579 | QualType DeclType = Entity.getType(); |
8580 | if (const IncompleteArrayType *ArrayT |
8581 | = S.Context.getAsIncompleteArrayType(T: DeclType)) { |
8582 | // FIXME: We don't currently have the ability to accurately |
8583 | // compute the length of an initializer list without |
8584 | // performing full type-checking of the initializer list |
8585 | // (since we have to determine where braces are implicitly |
8586 | // introduced and such). So, we fall back to making the array |
8587 | // type a dependently-sized array type with no specified |
8588 | // bound. |
8589 | if (isa<InitListExpr>(Val: (Expr *)Args[0])) { |
8590 | SourceRange Brackets; |
8591 | |
8592 | // Scavange the location of the brackets from the entity, if we can. |
8593 | if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Val: Entity.getDecl())) { |
8594 | if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) { |
8595 | TypeLoc TL = TInfo->getTypeLoc(); |
8596 | if (IncompleteArrayTypeLoc ArrayLoc = |
8597 | TL.getAs<IncompleteArrayTypeLoc>()) |
8598 | Brackets = ArrayLoc.getBracketsRange(); |
8599 | } |
8600 | } |
8601 | |
8602 | *ResultType |
8603 | = S.Context.getDependentSizedArrayType(EltTy: ArrayT->getElementType(), |
8604 | /*NumElts=*/nullptr, |
8605 | ASM: ArrayT->getSizeModifier(), |
8606 | IndexTypeQuals: ArrayT->getIndexTypeCVRQualifiers(), |
8607 | Brackets); |
8608 | } |
8609 | |
8610 | } |
8611 | } |
8612 | if (Kind.getKind() == InitializationKind::IK_Direct && |
8613 | !Kind.isExplicitCast()) { |
8614 | // Rebuild the ParenListExpr. |
8615 | SourceRange ParenRange = Kind.getParenOrBraceRange(); |
8616 | return S.ActOnParenListExpr(L: ParenRange.getBegin(), R: ParenRange.getEnd(), |
8617 | Val: Args); |
8618 | } |
8619 | assert(Kind.getKind() == InitializationKind::IK_Copy || |
8620 | Kind.isExplicitCast() || |
8621 | Kind.getKind() == InitializationKind::IK_DirectList); |
8622 | return ExprResult(Args[0]); |
8623 | } |
8624 | |
8625 | // No steps means no initialization. |
8626 | if (Steps.empty()) |
8627 | return ExprResult((Expr *)nullptr); |
8628 | |
8629 | if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() && |
8630 | Args.size() == 1 && isa<InitListExpr>(Val: Args[0]) && |
8631 | !Entity.isParamOrTemplateParamKind()) { |
8632 | // Produce a C++98 compatibility warning if we are initializing a reference |
8633 | // from an initializer list. For parameters, we produce a better warning |
8634 | // elsewhere. |
8635 | Expr *Init = Args[0]; |
8636 | S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init) |
8637 | << Init->getSourceRange(); |
8638 | } |
8639 | |
8640 | if (S.getLangOpts().MicrosoftExt && Args.size() == 1 && |
8641 | isa<PredefinedExpr>(Val: Args[0]) && Entity.getType()->isArrayType()) { |
8642 | // Produce a Microsoft compatibility warning when initializing from a |
8643 | // predefined expression since MSVC treats predefined expressions as string |
8644 | // literals. |
8645 | Expr *Init = Args[0]; |
8646 | S.Diag(Init->getBeginLoc(), diag::ext_init_from_predefined) << Init; |
8647 | } |
8648 | |
8649 | // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope |
8650 | QualType ETy = Entity.getType(); |
8651 | bool HasGlobalAS = ETy.hasAddressSpace() && |
8652 | ETy.getAddressSpace() == LangAS::opencl_global; |
8653 | |
8654 | if (S.getLangOpts().OpenCLVersion >= 200 && |
8655 | ETy->isAtomicType() && !HasGlobalAS && |
8656 | Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) { |
8657 | S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init) |
8658 | << 1 |
8659 | << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc()); |
8660 | return ExprError(); |
8661 | } |
8662 | |
8663 | QualType DestType = Entity.getType().getNonReferenceType(); |
8664 | // FIXME: Ugly hack around the fact that Entity.getType() is not |
8665 | // the same as Entity.getDecl()->getType() in cases involving type merging, |
8666 | // and we want latter when it makes sense. |
8667 | if (ResultType) |
8668 | *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() : |
8669 | Entity.getType(); |
8670 | |
8671 | ExprResult CurInit((Expr *)nullptr); |
8672 | SmallVector<Expr*, 4> ArrayLoopCommonExprs; |
8673 | |
8674 | // HLSL allows vector initialization to function like list initialization, but |
8675 | // use the syntax of a C++-like constructor. |
8676 | bool IsHLSLVectorInit = S.getLangOpts().HLSL && DestType->isExtVectorType() && |
8677 | isa<InitListExpr>(Val: Args[0]); |
8678 | (void)IsHLSLVectorInit; |
8679 | |
8680 | // For initialization steps that start with a single initializer, |
8681 | // grab the only argument out the Args and place it into the "current" |
8682 | // initializer. |
8683 | switch (Steps.front().Kind) { |
8684 | case SK_ResolveAddressOfOverloadedFunction: |
8685 | case SK_CastDerivedToBasePRValue: |
8686 | case SK_CastDerivedToBaseXValue: |
8687 | case SK_CastDerivedToBaseLValue: |
8688 | case SK_BindReference: |
8689 | case SK_BindReferenceToTemporary: |
8690 | case SK_FinalCopy: |
8691 | case SK_ExtraneousCopyToTemporary: |
8692 | case SK_UserConversion: |
8693 | case SK_QualificationConversionLValue: |
8694 | case SK_QualificationConversionXValue: |
8695 | case SK_QualificationConversionPRValue: |
8696 | case SK_FunctionReferenceConversion: |
8697 | case SK_AtomicConversion: |
8698 | case SK_ConversionSequence: |
8699 | case SK_ConversionSequenceNoNarrowing: |
8700 | case SK_ListInitialization: |
8701 | case SK_UnwrapInitList: |
8702 | case SK_RewrapInitList: |
8703 | case SK_CAssignment: |
8704 | case SK_StringInit: |
8705 | case SK_ObjCObjectConversion: |
8706 | case SK_ArrayLoopIndex: |
8707 | case SK_ArrayLoopInit: |
8708 | case SK_ArrayInit: |
8709 | case SK_GNUArrayInit: |
8710 | case SK_ParenthesizedArrayInit: |
8711 | case SK_PassByIndirectCopyRestore: |
8712 | case SK_PassByIndirectRestore: |
8713 | case SK_ProduceObjCObject: |
8714 | case SK_StdInitializerList: |
8715 | case SK_OCLSamplerInit: |
8716 | case SK_OCLZeroOpaqueType: { |
8717 | assert(Args.size() == 1 || IsHLSLVectorInit); |
8718 | CurInit = Args[0]; |
8719 | if (!CurInit.get()) return ExprError(); |
8720 | break; |
8721 | } |
8722 | |
8723 | case SK_ConstructorInitialization: |
8724 | case SK_ConstructorInitializationFromList: |
8725 | case SK_StdInitializerListConstructorCall: |
8726 | case SK_ZeroInitialization: |
8727 | case SK_ParenthesizedListInit: |
8728 | break; |
8729 | } |
8730 | |
8731 | // Promote from an unevaluated context to an unevaluated list context in |
8732 | // C++11 list-initialization; we need to instantiate entities usable in |
8733 | // constant expressions here in order to perform narrowing checks =( |
8734 | EnterExpressionEvaluationContext Evaluated( |
8735 | S, EnterExpressionEvaluationContext::InitList, |
8736 | CurInit.get() && isa<InitListExpr>(Val: CurInit.get())); |
8737 | |
8738 | // C++ [class.abstract]p2: |
8739 | // no objects of an abstract class can be created except as subobjects |
8740 | // of a class derived from it |
8741 | auto checkAbstractType = [&](QualType T) -> bool { |
8742 | if (Entity.getKind() == InitializedEntity::EK_Base || |
8743 | Entity.getKind() == InitializedEntity::EK_Delegating) |
8744 | return false; |
8745 | return S.RequireNonAbstractType(Kind.getLocation(), T, |
8746 | diag::err_allocation_of_abstract_type); |
8747 | }; |
8748 | |
8749 | // Walk through the computed steps for the initialization sequence, |
8750 | // performing the specified conversions along the way. |
8751 | bool ConstructorInitRequiresZeroInit = false; |
8752 | for (step_iterator Step = step_begin(), StepEnd = step_end(); |
8753 | Step != StepEnd; ++Step) { |
8754 | if (CurInit.isInvalid()) |
8755 | return ExprError(); |
8756 | |
8757 | QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType(); |
8758 | |
8759 | switch (Step->Kind) { |
8760 | case SK_ResolveAddressOfOverloadedFunction: |
8761 | // Overload resolution determined which function invoke; update the |
8762 | // initializer to reflect that choice. |
8763 | S.CheckAddressOfMemberAccess(OvlExpr: CurInit.get(), FoundDecl: Step->Function.FoundDecl); |
8764 | if (S.DiagnoseUseOfDecl(D: Step->Function.FoundDecl, Locs: Kind.getLocation())) |
8765 | return ExprError(); |
8766 | CurInit = S.FixOverloadedFunctionReference(CurInit, |
8767 | FoundDecl: Step->Function.FoundDecl, |
8768 | Fn: Step->Function.Function); |
8769 | // We might get back another placeholder expression if we resolved to a |
8770 | // builtin. |
8771 | if (!CurInit.isInvalid()) |
8772 | CurInit = S.CheckPlaceholderExpr(E: CurInit.get()); |
8773 | break; |
8774 | |
8775 | case SK_CastDerivedToBasePRValue: |
8776 | case SK_CastDerivedToBaseXValue: |
8777 | case SK_CastDerivedToBaseLValue: { |
8778 | // We have a derived-to-base cast that produces either an rvalue or an |
8779 | // lvalue. Perform that cast. |
8780 | |
8781 | CXXCastPath BasePath; |
8782 | |
8783 | // Casts to inaccessible base classes are allowed with C-style casts. |
8784 | bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast(); |
8785 | if (S.CheckDerivedToBaseConversion( |
8786 | SourceType, Step->Type, CurInit.get()->getBeginLoc(), |
8787 | CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess)) |
8788 | return ExprError(); |
8789 | |
8790 | ExprValueKind VK = |
8791 | Step->Kind == SK_CastDerivedToBaseLValue |
8792 | ? VK_LValue |
8793 | : (Step->Kind == SK_CastDerivedToBaseXValue ? VK_XValue |
8794 | : VK_PRValue); |
8795 | CurInit = ImplicitCastExpr::Create(Context: S.Context, T: Step->Type, |
8796 | Kind: CK_DerivedToBase, Operand: CurInit.get(), |
8797 | BasePath: &BasePath, Cat: VK, FPO: FPOptionsOverride()); |
8798 | break; |
8799 | } |
8800 | |
8801 | case SK_BindReference: |
8802 | // Reference binding does not have any corresponding ASTs. |
8803 | |
8804 | // Check exception specifications |
8805 | if (S.CheckExceptionSpecCompatibility(From: CurInit.get(), ToType: DestType)) |
8806 | return ExprError(); |
8807 | |
8808 | // We don't check for e.g. function pointers here, since address |
8809 | // availability checks should only occur when the function first decays |
8810 | // into a pointer or reference. |
8811 | if (CurInit.get()->getType()->isFunctionProtoType()) { |
8812 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: CurInit.get()->IgnoreParens())) { |
8813 | if (auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl())) { |
8814 | if (!S.checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true, |
8815 | Loc: DRE->getBeginLoc())) |
8816 | return ExprError(); |
8817 | } |
8818 | } |
8819 | } |
8820 | |
8821 | CheckForNullPointerDereference(S, E: CurInit.get()); |
8822 | break; |
8823 | |
8824 | case SK_BindReferenceToTemporary: { |
8825 | // Make sure the "temporary" is actually an rvalue. |
8826 | assert(CurInit.get()->isPRValue() && "not a temporary" ); |
8827 | |
8828 | // Check exception specifications |
8829 | if (S.CheckExceptionSpecCompatibility(From: CurInit.get(), ToType: DestType)) |
8830 | return ExprError(); |
8831 | |
8832 | QualType MTETy = Step->Type; |
8833 | |
8834 | // When this is an incomplete array type (such as when this is |
8835 | // initializing an array of unknown bounds from an init list), use THAT |
8836 | // type instead so that we propagate the array bounds. |
8837 | if (MTETy->isIncompleteArrayType() && |
8838 | !CurInit.get()->getType()->isIncompleteArrayType() && |
8839 | S.Context.hasSameType( |
8840 | T1: MTETy->getPointeeOrArrayElementType(), |
8841 | T2: CurInit.get()->getType()->getPointeeOrArrayElementType())) |
8842 | MTETy = CurInit.get()->getType(); |
8843 | |
8844 | // Materialize the temporary into memory. |
8845 | MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr( |
8846 | T: MTETy, Temporary: CurInit.get(), BoundToLvalueReference: Entity.getType()->isLValueReferenceType()); |
8847 | CurInit = MTE; |
8848 | |
8849 | // If we're extending this temporary to automatic storage duration -- we |
8850 | // need to register its cleanup during the full-expression's cleanups. |
8851 | if (MTE->getStorageDuration() == SD_Automatic && |
8852 | MTE->getType().isDestructedType()) |
8853 | S.Cleanup.setExprNeedsCleanups(true); |
8854 | break; |
8855 | } |
8856 | |
8857 | case SK_FinalCopy: |
8858 | if (checkAbstractType(Step->Type)) |
8859 | return ExprError(); |
8860 | |
8861 | // If the overall initialization is initializing a temporary, we already |
8862 | // bound our argument if it was necessary to do so. If not (if we're |
8863 | // ultimately initializing a non-temporary), our argument needs to be |
8864 | // bound since it's initializing a function parameter. |
8865 | // FIXME: This is a mess. Rationalize temporary destruction. |
8866 | if (!shouldBindAsTemporary(Entity)) |
8867 | CurInit = S.MaybeBindToTemporary(E: CurInit.get()); |
8868 | CurInit = CopyObject(S, Step->Type, Entity, CurInit, |
8869 | /*IsExtraneousCopy=*/false); |
8870 | break; |
8871 | |
8872 | case SK_ExtraneousCopyToTemporary: |
8873 | CurInit = CopyObject(S, Step->Type, Entity, CurInit, |
8874 | /*IsExtraneousCopy=*/true); |
8875 | break; |
8876 | |
8877 | case SK_UserConversion: { |
8878 | // We have a user-defined conversion that invokes either a constructor |
8879 | // or a conversion function. |
8880 | CastKind CastKind; |
8881 | FunctionDecl *Fn = Step->Function.Function; |
8882 | DeclAccessPair FoundFn = Step->Function.FoundDecl; |
8883 | bool HadMultipleCandidates = Step->Function.HadMultipleCandidates; |
8884 | bool CreatedObject = false; |
8885 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Fn)) { |
8886 | // Build a call to the selected constructor. |
8887 | SmallVector<Expr*, 8> ConstructorArgs; |
8888 | SourceLocation Loc = CurInit.get()->getBeginLoc(); |
8889 | |
8890 | // Determine the arguments required to actually perform the constructor |
8891 | // call. |
8892 | Expr *Arg = CurInit.get(); |
8893 | if (S.CompleteConstructorCall(Constructor, DeclInitType: Step->Type, |
8894 | ArgsPtr: MultiExprArg(&Arg, 1), Loc, |
8895 | ConvertedArgs&: ConstructorArgs)) |
8896 | return ExprError(); |
8897 | |
8898 | // Build an expression that constructs a temporary. |
8899 | CurInit = S.BuildCXXConstructExpr( |
8900 | Loc, Step->Type, FoundFn, Constructor, ConstructorArgs, |
8901 | HadMultipleCandidates, |
8902 | /*ListInit*/ false, |
8903 | /*StdInitListInit*/ false, |
8904 | /*ZeroInit*/ false, CXXConstructionKind::Complete, SourceRange()); |
8905 | if (CurInit.isInvalid()) |
8906 | return ExprError(); |
8907 | |
8908 | S.CheckConstructorAccess(Loc: Kind.getLocation(), D: Constructor, FoundDecl: FoundFn, |
8909 | Entity); |
8910 | if (S.DiagnoseUseOfDecl(D: FoundFn, Locs: Kind.getLocation())) |
8911 | return ExprError(); |
8912 | |
8913 | CastKind = CK_ConstructorConversion; |
8914 | CreatedObject = true; |
8915 | } else { |
8916 | // Build a call to the conversion function. |
8917 | CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Val: Fn); |
8918 | S.CheckMemberOperatorAccess(Loc: Kind.getLocation(), ObjectExpr: CurInit.get(), ArgExpr: nullptr, |
8919 | FoundDecl: FoundFn); |
8920 | if (S.DiagnoseUseOfDecl(D: FoundFn, Locs: Kind.getLocation())) |
8921 | return ExprError(); |
8922 | |
8923 | CurInit = S.BuildCXXMemberCallExpr(Exp: CurInit.get(), FoundDecl: FoundFn, Method: Conversion, |
8924 | HadMultipleCandidates); |
8925 | if (CurInit.isInvalid()) |
8926 | return ExprError(); |
8927 | |
8928 | CastKind = CK_UserDefinedConversion; |
8929 | CreatedObject = Conversion->getReturnType()->isRecordType(); |
8930 | } |
8931 | |
8932 | if (CreatedObject && checkAbstractType(CurInit.get()->getType())) |
8933 | return ExprError(); |
8934 | |
8935 | CurInit = ImplicitCastExpr::Create( |
8936 | Context: S.Context, T: CurInit.get()->getType(), Kind: CastKind, Operand: CurInit.get(), BasePath: nullptr, |
8937 | Cat: CurInit.get()->getValueKind(), FPO: S.CurFPFeatureOverrides()); |
8938 | |
8939 | if (shouldBindAsTemporary(Entity)) |
8940 | // The overall entity is temporary, so this expression should be |
8941 | // destroyed at the end of its full-expression. |
8942 | CurInit = S.MaybeBindToTemporary(E: CurInit.getAs<Expr>()); |
8943 | else if (CreatedObject && shouldDestroyEntity(Entity)) { |
8944 | // The object outlasts the full-expression, but we need to prepare for |
8945 | // a destructor being run on it. |
8946 | // FIXME: It makes no sense to do this here. This should happen |
8947 | // regardless of how we initialized the entity. |
8948 | QualType T = CurInit.get()->getType(); |
8949 | if (const RecordType *Record = T->getAs<RecordType>()) { |
8950 | CXXDestructorDecl *Destructor |
8951 | = S.LookupDestructor(Class: cast<CXXRecordDecl>(Val: Record->getDecl())); |
8952 | S.CheckDestructorAccess(CurInit.get()->getBeginLoc(), Destructor, |
8953 | S.PDiag(diag::err_access_dtor_temp) << T); |
8954 | S.MarkFunctionReferenced(Loc: CurInit.get()->getBeginLoc(), Func: Destructor); |
8955 | if (S.DiagnoseUseOfDecl(D: Destructor, Locs: CurInit.get()->getBeginLoc())) |
8956 | return ExprError(); |
8957 | } |
8958 | } |
8959 | break; |
8960 | } |
8961 | |
8962 | case SK_QualificationConversionLValue: |
8963 | case SK_QualificationConversionXValue: |
8964 | case SK_QualificationConversionPRValue: { |
8965 | // Perform a qualification conversion; these can never go wrong. |
8966 | ExprValueKind VK = |
8967 | Step->Kind == SK_QualificationConversionLValue |
8968 | ? VK_LValue |
8969 | : (Step->Kind == SK_QualificationConversionXValue ? VK_XValue |
8970 | : VK_PRValue); |
8971 | CurInit = S.PerformQualificationConversion(E: CurInit.get(), Ty: Step->Type, VK); |
8972 | break; |
8973 | } |
8974 | |
8975 | case SK_FunctionReferenceConversion: |
8976 | assert(CurInit.get()->isLValue() && |
8977 | "function reference should be lvalue" ); |
8978 | CurInit = |
8979 | S.ImpCastExprToType(E: CurInit.get(), Type: Step->Type, CK: CK_NoOp, VK: VK_LValue); |
8980 | break; |
8981 | |
8982 | case SK_AtomicConversion: { |
8983 | assert(CurInit.get()->isPRValue() && "cannot convert glvalue to atomic" ); |
8984 | CurInit = S.ImpCastExprToType(E: CurInit.get(), Type: Step->Type, |
8985 | CK: CK_NonAtomicToAtomic, VK: VK_PRValue); |
8986 | break; |
8987 | } |
8988 | |
8989 | case SK_ConversionSequence: |
8990 | case SK_ConversionSequenceNoNarrowing: { |
8991 | if (const auto *FromPtrType = |
8992 | CurInit.get()->getType()->getAs<PointerType>()) { |
8993 | if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) { |
8994 | if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) && |
8995 | !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { |
8996 | // Do not check static casts here because they are checked earlier |
8997 | // in Sema::ActOnCXXNamedCast() |
8998 | if (!Kind.isStaticCast()) { |
8999 | S.Diag(CurInit.get()->getExprLoc(), |
9000 | diag::warn_noderef_to_dereferenceable_pointer) |
9001 | << CurInit.get()->getSourceRange(); |
9002 | } |
9003 | } |
9004 | } |
9005 | } |
9006 | |
9007 | Sema::CheckedConversionKind CCK |
9008 | = Kind.isCStyleCast()? Sema::CCK_CStyleCast |
9009 | : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast |
9010 | : Kind.isExplicitCast()? Sema::CCK_OtherCast |
9011 | : Sema::CCK_ImplicitConversion; |
9012 | ExprResult CurInitExprRes = |
9013 | S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS, |
9014 | getAssignmentAction(Entity), CCK); |
9015 | if (CurInitExprRes.isInvalid()) |
9016 | return ExprError(); |
9017 | |
9018 | S.DiscardMisalignedMemberAddress(T: Step->Type.getTypePtr(), E: CurInit.get()); |
9019 | |
9020 | CurInit = CurInitExprRes; |
9021 | |
9022 | if (Step->Kind == SK_ConversionSequenceNoNarrowing && |
9023 | S.getLangOpts().CPlusPlus) |
9024 | DiagnoseNarrowingInInitList(S, ICS: *Step->ICS, PreNarrowingType: SourceType, EntityType: Entity.getType(), |
9025 | PostInit: CurInit.get()); |
9026 | |
9027 | break; |
9028 | } |
9029 | |
9030 | case SK_ListInitialization: { |
9031 | if (checkAbstractType(Step->Type)) |
9032 | return ExprError(); |
9033 | |
9034 | InitListExpr *InitList = cast<InitListExpr>(Val: CurInit.get()); |
9035 | // If we're not initializing the top-level entity, we need to create an |
9036 | // InitializeTemporary entity for our target type. |
9037 | QualType Ty = Step->Type; |
9038 | bool IsTemporary = !S.Context.hasSameType(T1: Entity.getType(), T2: Ty); |
9039 | InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Type: Ty); |
9040 | InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity; |
9041 | InitListChecker PerformInitList(S, InitEntity, |
9042 | InitList, Ty, /*VerifyOnly=*/false, |
9043 | /*TreatUnavailableAsInvalid=*/false); |
9044 | if (PerformInitList.HadError()) |
9045 | return ExprError(); |
9046 | |
9047 | // Hack: We must update *ResultType if available in order to set the |
9048 | // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'. |
9049 | // Worst case: 'const int (&arref)[] = {1, 2, 3};'. |
9050 | if (ResultType && |
9051 | ResultType->getNonReferenceType()->isIncompleteArrayType()) { |
9052 | if ((*ResultType)->isRValueReferenceType()) |
9053 | Ty = S.Context.getRValueReferenceType(T: Ty); |
9054 | else if ((*ResultType)->isLValueReferenceType()) |
9055 | Ty = S.Context.getLValueReferenceType(T: Ty, |
9056 | SpelledAsLValue: (*ResultType)->castAs<LValueReferenceType>()->isSpelledAsLValue()); |
9057 | *ResultType = Ty; |
9058 | } |
9059 | |
9060 | InitListExpr *StructuredInitList = |
9061 | PerformInitList.getFullyStructuredList(); |
9062 | CurInit.get(); |
9063 | CurInit = shouldBindAsTemporary(Entity: InitEntity) |
9064 | ? S.MaybeBindToTemporary(StructuredInitList) |
9065 | : StructuredInitList; |
9066 | break; |
9067 | } |
9068 | |
9069 | case SK_ConstructorInitializationFromList: { |
9070 | if (checkAbstractType(Step->Type)) |
9071 | return ExprError(); |
9072 | |
9073 | // When an initializer list is passed for a parameter of type "reference |
9074 | // to object", we don't get an EK_Temporary entity, but instead an |
9075 | // EK_Parameter entity with reference type. |
9076 | // FIXME: This is a hack. What we really should do is create a user |
9077 | // conversion step for this case, but this makes it considerably more |
9078 | // complicated. For now, this will do. |
9079 | InitializedEntity TempEntity = InitializedEntity::InitializeTemporary( |
9080 | Type: Entity.getType().getNonReferenceType()); |
9081 | bool UseTemporary = Entity.getType()->isReferenceType(); |
9082 | assert(Args.size() == 1 && "expected a single argument for list init" ); |
9083 | InitListExpr *InitList = cast<InitListExpr>(Val: Args[0]); |
9084 | S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init) |
9085 | << InitList->getSourceRange(); |
9086 | MultiExprArg Arg(InitList->getInits(), InitList->getNumInits()); |
9087 | CurInit = PerformConstructorInitialization(S, Entity: UseTemporary ? TempEntity : |
9088 | Entity, |
9089 | Kind, Args: Arg, Step: *Step, |
9090 | ConstructorInitRequiresZeroInit, |
9091 | /*IsListInitialization*/true, |
9092 | /*IsStdInitListInit*/IsStdInitListInitialization: false, |
9093 | LBraceLoc: InitList->getLBraceLoc(), |
9094 | RBraceLoc: InitList->getRBraceLoc()); |
9095 | break; |
9096 | } |
9097 | |
9098 | case SK_UnwrapInitList: |
9099 | CurInit = cast<InitListExpr>(Val: CurInit.get())->getInit(Init: 0); |
9100 | break; |
9101 | |
9102 | case SK_RewrapInitList: { |
9103 | Expr *E = CurInit.get(); |
9104 | InitListExpr *Syntactic = Step->WrappingSyntacticList; |
9105 | InitListExpr *ILE = new (S.Context) InitListExpr(S.Context, |
9106 | Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc()); |
9107 | ILE->setSyntacticForm(Syntactic); |
9108 | ILE->setType(E->getType()); |
9109 | ILE->setValueKind(E->getValueKind()); |
9110 | CurInit = ILE; |
9111 | break; |
9112 | } |
9113 | |
9114 | case SK_ConstructorInitialization: |
9115 | case SK_StdInitializerListConstructorCall: { |
9116 | if (checkAbstractType(Step->Type)) |
9117 | return ExprError(); |
9118 | |
9119 | // When an initializer list is passed for a parameter of type "reference |
9120 | // to object", we don't get an EK_Temporary entity, but instead an |
9121 | // EK_Parameter entity with reference type. |
9122 | // FIXME: This is a hack. What we really should do is create a user |
9123 | // conversion step for this case, but this makes it considerably more |
9124 | // complicated. For now, this will do. |
9125 | InitializedEntity TempEntity = InitializedEntity::InitializeTemporary( |
9126 | Type: Entity.getType().getNonReferenceType()); |
9127 | bool UseTemporary = Entity.getType()->isReferenceType(); |
9128 | bool IsStdInitListInit = |
9129 | Step->Kind == SK_StdInitializerListConstructorCall; |
9130 | Expr *Source = CurInit.get(); |
9131 | SourceRange Range = Kind.hasParenOrBraceRange() |
9132 | ? Kind.getParenOrBraceRange() |
9133 | : SourceRange(); |
9134 | CurInit = PerformConstructorInitialization( |
9135 | S, Entity: UseTemporary ? TempEntity : Entity, Kind, |
9136 | Args: Source ? MultiExprArg(Source) : Args, Step: *Step, |
9137 | ConstructorInitRequiresZeroInit, |
9138 | /*IsListInitialization*/ IsStdInitListInit, |
9139 | /*IsStdInitListInitialization*/ IsStdInitListInit, |
9140 | /*LBraceLoc*/ Range.getBegin(), |
9141 | /*RBraceLoc*/ Range.getEnd()); |
9142 | break; |
9143 | } |
9144 | |
9145 | case SK_ZeroInitialization: { |
9146 | step_iterator NextStep = Step; |
9147 | ++NextStep; |
9148 | if (NextStep != StepEnd && |
9149 | (NextStep->Kind == SK_ConstructorInitialization || |
9150 | NextStep->Kind == SK_ConstructorInitializationFromList)) { |
9151 | // The need for zero-initialization is recorded directly into |
9152 | // the call to the object's constructor within the next step. |
9153 | ConstructorInitRequiresZeroInit = true; |
9154 | } else if (Kind.getKind() == InitializationKind::IK_Value && |
9155 | S.getLangOpts().CPlusPlus && |
9156 | !Kind.isImplicitValueInit()) { |
9157 | TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo(); |
9158 | if (!TSInfo) |
9159 | TSInfo = S.Context.getTrivialTypeSourceInfo(T: Step->Type, |
9160 | Loc: Kind.getRange().getBegin()); |
9161 | |
9162 | CurInit = new (S.Context) CXXScalarValueInitExpr( |
9163 | Entity.getType().getNonLValueExprType(Context: S.Context), TSInfo, |
9164 | Kind.getRange().getEnd()); |
9165 | } else { |
9166 | CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type); |
9167 | } |
9168 | break; |
9169 | } |
9170 | |
9171 | case SK_CAssignment: { |
9172 | QualType SourceType = CurInit.get()->getType(); |
9173 | |
9174 | // Save off the initial CurInit in case we need to emit a diagnostic |
9175 | ExprResult InitialCurInit = CurInit; |
9176 | ExprResult Result = CurInit; |
9177 | Sema::AssignConvertType ConvTy = |
9178 | S.CheckSingleAssignmentConstraints(LHSType: Step->Type, RHS&: Result, Diagnose: true, |
9179 | DiagnoseCFAudited: Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited); |
9180 | if (Result.isInvalid()) |
9181 | return ExprError(); |
9182 | CurInit = Result; |
9183 | |
9184 | // If this is a call, allow conversion to a transparent union. |
9185 | ExprResult CurInitExprRes = CurInit; |
9186 | if (ConvTy != Sema::Compatible && |
9187 | Entity.isParameterKind() && |
9188 | S.CheckTransparentUnionArgumentConstraints(ArgType: Step->Type, RHS&: CurInitExprRes) |
9189 | == Sema::Compatible) |
9190 | ConvTy = Sema::Compatible; |
9191 | if (CurInitExprRes.isInvalid()) |
9192 | return ExprError(); |
9193 | CurInit = CurInitExprRes; |
9194 | |
9195 | bool Complained; |
9196 | if (S.DiagnoseAssignmentResult(ConvTy, Loc: Kind.getLocation(), |
9197 | DstType: Step->Type, SrcType: SourceType, |
9198 | SrcExpr: InitialCurInit.get(), |
9199 | Action: getAssignmentAction(Entity, Diagnose: true), |
9200 | Complained: &Complained)) { |
9201 | PrintInitLocationNote(S, Entity); |
9202 | return ExprError(); |
9203 | } else if (Complained) |
9204 | PrintInitLocationNote(S, Entity); |
9205 | break; |
9206 | } |
9207 | |
9208 | case SK_StringInit: { |
9209 | QualType Ty = Step->Type; |
9210 | bool UpdateType = ResultType && Entity.getType()->isIncompleteArrayType(); |
9211 | CheckStringInit(Str: CurInit.get(), DeclT&: UpdateType ? *ResultType : Ty, |
9212 | AT: S.Context.getAsArrayType(T: Ty), S); |
9213 | break; |
9214 | } |
9215 | |
9216 | case SK_ObjCObjectConversion: |
9217 | CurInit = S.ImpCastExprToType(E: CurInit.get(), Type: Step->Type, |
9218 | CK: CK_ObjCObjectLValueCast, |
9219 | VK: CurInit.get()->getValueKind()); |
9220 | break; |
9221 | |
9222 | case SK_ArrayLoopIndex: { |
9223 | Expr *Cur = CurInit.get(); |
9224 | Expr *BaseExpr = new (S.Context) |
9225 | OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(), |
9226 | Cur->getValueKind(), Cur->getObjectKind(), Cur); |
9227 | Expr *IndexExpr = |
9228 | new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType()); |
9229 | CurInit = S.CreateBuiltinArraySubscriptExpr( |
9230 | Base: BaseExpr, LLoc: Kind.getLocation(), Idx: IndexExpr, RLoc: Kind.getLocation()); |
9231 | ArrayLoopCommonExprs.push_back(Elt: BaseExpr); |
9232 | break; |
9233 | } |
9234 | |
9235 | case SK_ArrayLoopInit: { |
9236 | assert(!ArrayLoopCommonExprs.empty() && |
9237 | "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit" ); |
9238 | Expr *Common = ArrayLoopCommonExprs.pop_back_val(); |
9239 | CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common, |
9240 | CurInit.get()); |
9241 | break; |
9242 | } |
9243 | |
9244 | case SK_GNUArrayInit: |
9245 | // Okay: we checked everything before creating this step. Note that |
9246 | // this is a GNU extension. |
9247 | S.Diag(Kind.getLocation(), diag::ext_array_init_copy) |
9248 | << Step->Type << CurInit.get()->getType() |
9249 | << CurInit.get()->getSourceRange(); |
9250 | updateGNUCompoundLiteralRValue(E: CurInit.get()); |
9251 | [[fallthrough]]; |
9252 | case SK_ArrayInit: |
9253 | // If the destination type is an incomplete array type, update the |
9254 | // type accordingly. |
9255 | if (ResultType) { |
9256 | if (const IncompleteArrayType *IncompleteDest |
9257 | = S.Context.getAsIncompleteArrayType(T: Step->Type)) { |
9258 | if (const ConstantArrayType *ConstantSource |
9259 | = S.Context.getAsConstantArrayType(T: CurInit.get()->getType())) { |
9260 | *ResultType = S.Context.getConstantArrayType( |
9261 | EltTy: IncompleteDest->getElementType(), ArySize: ConstantSource->getSize(), |
9262 | SizeExpr: ConstantSource->getSizeExpr(), ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0); |
9263 | } |
9264 | } |
9265 | } |
9266 | break; |
9267 | |
9268 | case SK_ParenthesizedArrayInit: |
9269 | // Okay: we checked everything before creating this step. Note that |
9270 | // this is a GNU extension. |
9271 | S.Diag(Kind.getLocation(), diag::ext_array_init_parens) |
9272 | << CurInit.get()->getSourceRange(); |
9273 | break; |
9274 | |
9275 | case SK_PassByIndirectCopyRestore: |
9276 | case SK_PassByIndirectRestore: |
9277 | checkIndirectCopyRestoreSource(S, src: CurInit.get()); |
9278 | CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr( |
9279 | CurInit.get(), Step->Type, |
9280 | Step->Kind == SK_PassByIndirectCopyRestore); |
9281 | break; |
9282 | |
9283 | case SK_ProduceObjCObject: |
9284 | CurInit = ImplicitCastExpr::Create( |
9285 | Context: S.Context, T: Step->Type, Kind: CK_ARCProduceObject, Operand: CurInit.get(), BasePath: nullptr, |
9286 | Cat: VK_PRValue, FPO: FPOptionsOverride()); |
9287 | break; |
9288 | |
9289 | case SK_StdInitializerList: { |
9290 | S.Diag(CurInit.get()->getExprLoc(), |
9291 | diag::warn_cxx98_compat_initializer_list_init) |
9292 | << CurInit.get()->getSourceRange(); |
9293 | |
9294 | // Materialize the temporary into memory. |
9295 | MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr( |
9296 | T: CurInit.get()->getType(), Temporary: CurInit.get(), |
9297 | /*BoundToLvalueReference=*/false); |
9298 | |
9299 | // Wrap it in a construction of a std::initializer_list<T>. |
9300 | CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE); |
9301 | |
9302 | // Bind the result, in case the library has given initializer_list a |
9303 | // non-trivial destructor. |
9304 | if (shouldBindAsTemporary(Entity)) |
9305 | CurInit = S.MaybeBindToTemporary(E: CurInit.get()); |
9306 | break; |
9307 | } |
9308 | |
9309 | case SK_OCLSamplerInit: { |
9310 | // Sampler initialization have 5 cases: |
9311 | // 1. function argument passing |
9312 | // 1a. argument is a file-scope variable |
9313 | // 1b. argument is a function-scope variable |
9314 | // 1c. argument is one of caller function's parameters |
9315 | // 2. variable initialization |
9316 | // 2a. initializing a file-scope variable |
9317 | // 2b. initializing a function-scope variable |
9318 | // |
9319 | // For file-scope variables, since they cannot be initialized by function |
9320 | // call of __translate_sampler_initializer in LLVM IR, their references |
9321 | // need to be replaced by a cast from their literal initializers to |
9322 | // sampler type. Since sampler variables can only be used in function |
9323 | // calls as arguments, we only need to replace them when handling the |
9324 | // argument passing. |
9325 | assert(Step->Type->isSamplerT() && |
9326 | "Sampler initialization on non-sampler type." ); |
9327 | Expr *Init = CurInit.get()->IgnoreParens(); |
9328 | QualType SourceType = Init->getType(); |
9329 | // Case 1 |
9330 | if (Entity.isParameterKind()) { |
9331 | if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) { |
9332 | S.Diag(Kind.getLocation(), diag::err_sampler_argument_required) |
9333 | << SourceType; |
9334 | break; |
9335 | } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Init)) { |
9336 | auto Var = cast<VarDecl>(Val: DRE->getDecl()); |
9337 | // Case 1b and 1c |
9338 | // No cast from integer to sampler is needed. |
9339 | if (!Var->hasGlobalStorage()) { |
9340 | CurInit = ImplicitCastExpr::Create( |
9341 | Context: S.Context, T: Step->Type, Kind: CK_LValueToRValue, Operand: Init, |
9342 | /*BasePath=*/nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride()); |
9343 | break; |
9344 | } |
9345 | // Case 1a |
9346 | // For function call with a file-scope sampler variable as argument, |
9347 | // get the integer literal. |
9348 | // Do not diagnose if the file-scope variable does not have initializer |
9349 | // since this has already been diagnosed when parsing the variable |
9350 | // declaration. |
9351 | if (!Var->getInit() || !isa<ImplicitCastExpr>(Val: Var->getInit())) |
9352 | break; |
9353 | Init = cast<ImplicitCastExpr>(Val: const_cast<Expr*>( |
9354 | Var->getInit()))->getSubExpr(); |
9355 | SourceType = Init->getType(); |
9356 | } |
9357 | } else { |
9358 | // Case 2 |
9359 | // Check initializer is 32 bit integer constant. |
9360 | // If the initializer is taken from global variable, do not diagnose since |
9361 | // this has already been done when parsing the variable declaration. |
9362 | if (!Init->isConstantInitializer(Ctx&: S.Context, ForRef: false)) |
9363 | break; |
9364 | |
9365 | if (!SourceType->isIntegerType() || |
9366 | 32 != S.Context.getIntWidth(T: SourceType)) { |
9367 | S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer) |
9368 | << SourceType; |
9369 | break; |
9370 | } |
9371 | |
9372 | Expr::EvalResult EVResult; |
9373 | Init->EvaluateAsInt(Result&: EVResult, Ctx: S.Context); |
9374 | llvm::APSInt Result = EVResult.Val.getInt(); |
9375 | const uint64_t SamplerValue = Result.getLimitedValue(); |
9376 | // 32-bit value of sampler's initializer is interpreted as |
9377 | // bit-field with the following structure: |
9378 | // |unspecified|Filter|Addressing Mode| Normalized Coords| |
9379 | // |31 6|5 4|3 1| 0| |
9380 | // This structure corresponds to enum values of sampler properties |
9381 | // defined in SPIR spec v1.2 and also opencl-c.h |
9382 | unsigned AddressingMode = (0x0E & SamplerValue) >> 1; |
9383 | unsigned FilterMode = (0x30 & SamplerValue) >> 4; |
9384 | if (FilterMode != 1 && FilterMode != 2 && |
9385 | !S.getOpenCLOptions().isAvailableOption( |
9386 | "cl_intel_device_side_avc_motion_estimation" , S.getLangOpts())) |
9387 | S.Diag(Kind.getLocation(), |
9388 | diag::warn_sampler_initializer_invalid_bits) |
9389 | << "Filter Mode" ; |
9390 | if (AddressingMode > 4) |
9391 | S.Diag(Kind.getLocation(), |
9392 | diag::warn_sampler_initializer_invalid_bits) |
9393 | << "Addressing Mode" ; |
9394 | } |
9395 | |
9396 | // Cases 1a, 2a and 2b |
9397 | // Insert cast from integer to sampler. |
9398 | CurInit = S.ImpCastExprToType(E: Init, Type: S.Context.OCLSamplerTy, |
9399 | CK: CK_IntToOCLSampler); |
9400 | break; |
9401 | } |
9402 | case SK_OCLZeroOpaqueType: { |
9403 | assert((Step->Type->isEventT() || Step->Type->isQueueT() || |
9404 | Step->Type->isOCLIntelSubgroupAVCType()) && |
9405 | "Wrong type for initialization of OpenCL opaque type." ); |
9406 | |
9407 | CurInit = S.ImpCastExprToType(E: CurInit.get(), Type: Step->Type, |
9408 | CK: CK_ZeroToOCLOpaqueType, |
9409 | VK: CurInit.get()->getValueKind()); |
9410 | break; |
9411 | } |
9412 | case SK_ParenthesizedListInit: { |
9413 | CurInit = nullptr; |
9414 | TryOrBuildParenListInitialization(S, Entity, Kind, Args, Sequence&: *this, |
9415 | /*VerifyOnly=*/false, Result: &CurInit); |
9416 | if (CurInit.get() && ResultType) |
9417 | *ResultType = CurInit.get()->getType(); |
9418 | if (shouldBindAsTemporary(Entity)) |
9419 | CurInit = S.MaybeBindToTemporary(E: CurInit.get()); |
9420 | break; |
9421 | } |
9422 | } |
9423 | } |
9424 | |
9425 | Expr *Init = CurInit.get(); |
9426 | if (!Init) |
9427 | return ExprError(); |
9428 | |
9429 | // Check whether the initializer has a shorter lifetime than the initialized |
9430 | // entity, and if not, either lifetime-extend or warn as appropriate. |
9431 | S.checkInitializerLifetime(Entity, Init); |
9432 | |
9433 | // Diagnose non-fatal problems with the completed initialization. |
9434 | if (InitializedEntity::EntityKind EK = Entity.getKind(); |
9435 | (EK == InitializedEntity::EK_Member || |
9436 | EK == InitializedEntity::EK_ParenAggInitMember) && |
9437 | cast<FieldDecl>(Val: Entity.getDecl())->isBitField()) |
9438 | S.CheckBitFieldInitialization(InitLoc: Kind.getLocation(), |
9439 | Field: cast<FieldDecl>(Val: Entity.getDecl()), Init); |
9440 | |
9441 | // Check for std::move on construction. |
9442 | CheckMoveOnConstruction(S, InitExpr: Init, |
9443 | IsReturnStmt: Entity.getKind() == InitializedEntity::EK_Result); |
9444 | |
9445 | return Init; |
9446 | } |
9447 | |
9448 | /// Somewhere within T there is an uninitialized reference subobject. |
9449 | /// Dig it out and diagnose it. |
9450 | static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc, |
9451 | QualType T) { |
9452 | if (T->isReferenceType()) { |
9453 | S.Diag(Loc, diag::err_reference_without_init) |
9454 | << T.getNonReferenceType(); |
9455 | return true; |
9456 | } |
9457 | |
9458 | CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); |
9459 | if (!RD || !RD->hasUninitializedReferenceMember()) |
9460 | return false; |
9461 | |
9462 | for (const auto *FI : RD->fields()) { |
9463 | if (FI->isUnnamedBitfield()) |
9464 | continue; |
9465 | |
9466 | if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) { |
9467 | S.Diag(Loc, diag::note_value_initialization_here) << RD; |
9468 | return true; |
9469 | } |
9470 | } |
9471 | |
9472 | for (const auto &BI : RD->bases()) { |
9473 | if (DiagnoseUninitializedReference(S, Loc: BI.getBeginLoc(), T: BI.getType())) { |
9474 | S.Diag(Loc, diag::note_value_initialization_here) << RD; |
9475 | return true; |
9476 | } |
9477 | } |
9478 | |
9479 | return false; |
9480 | } |
9481 | |
9482 | |
9483 | //===----------------------------------------------------------------------===// |
9484 | // Diagnose initialization failures |
9485 | //===----------------------------------------------------------------------===// |
9486 | |
9487 | /// Emit notes associated with an initialization that failed due to a |
9488 | /// "simple" conversion failure. |
9489 | static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity, |
9490 | Expr *op) { |
9491 | QualType destType = entity.getType(); |
9492 | if (destType.getNonReferenceType()->isObjCObjectPointerType() && |
9493 | op->getType()->isObjCObjectPointerType()) { |
9494 | |
9495 | // Emit a possible note about the conversion failing because the |
9496 | // operand is a message send with a related result type. |
9497 | S.EmitRelatedResultTypeNote(E: op); |
9498 | |
9499 | // Emit a possible note about a return failing because we're |
9500 | // expecting a related result type. |
9501 | if (entity.getKind() == InitializedEntity::EK_Result) |
9502 | S.EmitRelatedResultTypeNoteForReturn(destType); |
9503 | } |
9504 | QualType fromType = op->getType(); |
9505 | QualType fromPointeeType = fromType.getCanonicalType()->getPointeeType(); |
9506 | QualType destPointeeType = destType.getCanonicalType()->getPointeeType(); |
9507 | auto *fromDecl = fromType->getPointeeCXXRecordDecl(); |
9508 | auto *destDecl = destType->getPointeeCXXRecordDecl(); |
9509 | if (fromDecl && destDecl && fromDecl->getDeclKind() == Decl::CXXRecord && |
9510 | destDecl->getDeclKind() == Decl::CXXRecord && |
9511 | !fromDecl->isInvalidDecl() && !destDecl->isInvalidDecl() && |
9512 | !fromDecl->hasDefinition() && |
9513 | destPointeeType.getQualifiers().compatiblyIncludes( |
9514 | fromPointeeType.getQualifiers())) |
9515 | S.Diag(fromDecl->getLocation(), diag::note_forward_class_conversion) |
9516 | << S.getASTContext().getTagDeclType(fromDecl) |
9517 | << S.getASTContext().getTagDeclType(destDecl); |
9518 | } |
9519 | |
9520 | static void diagnoseListInit(Sema &S, const InitializedEntity &Entity, |
9521 | InitListExpr *InitList) { |
9522 | QualType DestType = Entity.getType(); |
9523 | |
9524 | QualType E; |
9525 | if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(Ty: DestType, Element: &E)) { |
9526 | QualType ArrayType = S.Context.getConstantArrayType( |
9527 | EltTy: E.withConst(), |
9528 | ArySize: llvm::APInt(S.Context.getTypeSize(T: S.Context.getSizeType()), |
9529 | InitList->getNumInits()), |
9530 | SizeExpr: nullptr, ASM: clang::ArraySizeModifier::Normal, IndexTypeQuals: 0); |
9531 | InitializedEntity HiddenArray = |
9532 | InitializedEntity::InitializeTemporary(Type: ArrayType); |
9533 | return diagnoseListInit(S, Entity: HiddenArray, InitList); |
9534 | } |
9535 | |
9536 | if (DestType->isReferenceType()) { |
9537 | // A list-initialization failure for a reference means that we tried to |
9538 | // create a temporary of the inner type (per [dcl.init.list]p3.6) and the |
9539 | // inner initialization failed. |
9540 | QualType T = DestType->castAs<ReferenceType>()->getPointeeType(); |
9541 | diagnoseListInit(S, Entity: InitializedEntity::InitializeTemporary(Type: T), InitList); |
9542 | SourceLocation Loc = InitList->getBeginLoc(); |
9543 | if (auto *D = Entity.getDecl()) |
9544 | Loc = D->getLocation(); |
9545 | S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T; |
9546 | return; |
9547 | } |
9548 | |
9549 | InitListChecker DiagnoseInitList(S, Entity, InitList, DestType, |
9550 | /*VerifyOnly=*/false, |
9551 | /*TreatUnavailableAsInvalid=*/false); |
9552 | assert(DiagnoseInitList.HadError() && |
9553 | "Inconsistent init list check result." ); |
9554 | } |
9555 | |
9556 | bool InitializationSequence::Diagnose(Sema &S, |
9557 | const InitializedEntity &Entity, |
9558 | const InitializationKind &Kind, |
9559 | ArrayRef<Expr *> Args) { |
9560 | if (!Failed()) |
9561 | return false; |
9562 | |
9563 | // When we want to diagnose only one element of a braced-init-list, |
9564 | // we need to factor it out. |
9565 | Expr *OnlyArg; |
9566 | if (Args.size() == 1) { |
9567 | auto *List = dyn_cast<InitListExpr>(Val: Args[0]); |
9568 | if (List && List->getNumInits() == 1) |
9569 | OnlyArg = List->getInit(Init: 0); |
9570 | else |
9571 | OnlyArg = Args[0]; |
9572 | } |
9573 | else |
9574 | OnlyArg = nullptr; |
9575 | |
9576 | QualType DestType = Entity.getType(); |
9577 | switch (Failure) { |
9578 | case FK_TooManyInitsForReference: |
9579 | // FIXME: Customize for the initialized entity? |
9580 | if (Args.empty()) { |
9581 | // Dig out the reference subobject which is uninitialized and diagnose it. |
9582 | // If this is value-initialization, this could be nested some way within |
9583 | // the target type. |
9584 | assert(Kind.getKind() == InitializationKind::IK_Value || |
9585 | DestType->isReferenceType()); |
9586 | bool Diagnosed = |
9587 | DiagnoseUninitializedReference(S, Loc: Kind.getLocation(), T: DestType); |
9588 | assert(Diagnosed && "couldn't find uninitialized reference to diagnose" ); |
9589 | (void)Diagnosed; |
9590 | } else // FIXME: diagnostic below could be better! |
9591 | S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits) |
9592 | << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc()); |
9593 | break; |
9594 | case FK_ParenthesizedListInitForReference: |
9595 | S.Diag(Kind.getLocation(), diag::err_list_init_in_parens) |
9596 | << 1 << Entity.getType() << Args[0]->getSourceRange(); |
9597 | break; |
9598 | |
9599 | case FK_ArrayNeedsInitList: |
9600 | S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0; |
9601 | break; |
9602 | case FK_ArrayNeedsInitListOrStringLiteral: |
9603 | S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1; |
9604 | break; |
9605 | case FK_ArrayNeedsInitListOrWideStringLiteral: |
9606 | S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2; |
9607 | break; |
9608 | case FK_NarrowStringIntoWideCharArray: |
9609 | S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar); |
9610 | break; |
9611 | case FK_WideStringIntoCharArray: |
9612 | S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char); |
9613 | break; |
9614 | case FK_IncompatWideStringIntoWideChar: |
9615 | S.Diag(Kind.getLocation(), |
9616 | diag::err_array_init_incompat_wide_string_into_wchar); |
9617 | break; |
9618 | case FK_PlainStringIntoUTF8Char: |
9619 | S.Diag(Kind.getLocation(), |
9620 | diag::err_array_init_plain_string_into_char8_t); |
9621 | S.Diag(Args.front()->getBeginLoc(), |
9622 | diag::note_array_init_plain_string_into_char8_t) |
9623 | << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8" ); |
9624 | break; |
9625 | case FK_UTF8StringIntoPlainChar: |
9626 | S.Diag(Kind.getLocation(), diag::err_array_init_utf8_string_into_char) |
9627 | << DestType->isSignedIntegerType() << S.getLangOpts().CPlusPlus20; |
9628 | break; |
9629 | case FK_ArrayTypeMismatch: |
9630 | case FK_NonConstantArrayInit: |
9631 | S.Diag(Kind.getLocation(), |
9632 | (Failure == FK_ArrayTypeMismatch |
9633 | ? diag::err_array_init_different_type |
9634 | : diag::err_array_init_non_constant_array)) |
9635 | << DestType.getNonReferenceType() |
9636 | << OnlyArg->getType() |
9637 | << Args[0]->getSourceRange(); |
9638 | break; |
9639 | |
9640 | case FK_VariableLengthArrayHasInitializer: |
9641 | S.Diag(Kind.getLocation(), diag::err_variable_object_no_init) |
9642 | << Args[0]->getSourceRange(); |
9643 | break; |
9644 | |
9645 | case FK_AddressOfOverloadFailed: { |
9646 | DeclAccessPair Found; |
9647 | S.ResolveAddressOfOverloadedFunction(AddressOfExpr: OnlyArg, |
9648 | TargetType: DestType.getNonReferenceType(), |
9649 | Complain: true, |
9650 | Found); |
9651 | break; |
9652 | } |
9653 | |
9654 | case FK_AddressOfUnaddressableFunction: { |
9655 | auto *FD = cast<FunctionDecl>(Val: cast<DeclRefExpr>(Val: OnlyArg)->getDecl()); |
9656 | S.checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true, |
9657 | Loc: OnlyArg->getBeginLoc()); |
9658 | break; |
9659 | } |
9660 | |
9661 | case FK_ReferenceInitOverloadFailed: |
9662 | case FK_UserConversionOverloadFailed: |
9663 | switch (FailedOverloadResult) { |
9664 | case OR_Ambiguous: |
9665 | |
9666 | FailedCandidateSet.NoteCandidates( |
9667 | PartialDiagnosticAt( |
9668 | Kind.getLocation(), |
9669 | Failure == FK_UserConversionOverloadFailed |
9670 | ? (S.PDiag(diag::err_typecheck_ambiguous_condition) |
9671 | << OnlyArg->getType() << DestType |
9672 | << Args[0]->getSourceRange()) |
9673 | : (S.PDiag(diag::err_ref_init_ambiguous) |
9674 | << DestType << OnlyArg->getType() |
9675 | << Args[0]->getSourceRange())), |
9676 | S, OCD_AmbiguousCandidates, Args); |
9677 | break; |
9678 | |
9679 | case OR_No_Viable_Function: { |
9680 | auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD: OCD_AllCandidates, Args); |
9681 | if (!S.RequireCompleteType(Kind.getLocation(), |
9682 | DestType.getNonReferenceType(), |
9683 | diag::err_typecheck_nonviable_condition_incomplete, |
9684 | OnlyArg->getType(), Args[0]->getSourceRange())) |
9685 | S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition) |
9686 | << (Entity.getKind() == InitializedEntity::EK_Result) |
9687 | << OnlyArg->getType() << Args[0]->getSourceRange() |
9688 | << DestType.getNonReferenceType(); |
9689 | |
9690 | FailedCandidateSet.NoteCandidates(S, Args, Cands); |
9691 | break; |
9692 | } |
9693 | case OR_Deleted: { |
9694 | S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function) |
9695 | << OnlyArg->getType() << DestType.getNonReferenceType() |
9696 | << Args[0]->getSourceRange(); |
9697 | OverloadCandidateSet::iterator Best; |
9698 | OverloadingResult Ovl |
9699 | = FailedCandidateSet.BestViableFunction(S, Loc: Kind.getLocation(), Best); |
9700 | if (Ovl == OR_Deleted) { |
9701 | S.NoteDeletedFunction(FD: Best->Function); |
9702 | } else { |
9703 | llvm_unreachable("Inconsistent overload resolution?" ); |
9704 | } |
9705 | break; |
9706 | } |
9707 | |
9708 | case OR_Success: |
9709 | llvm_unreachable("Conversion did not fail!" ); |
9710 | } |
9711 | break; |
9712 | |
9713 | case FK_NonConstLValueReferenceBindingToTemporary: |
9714 | if (isa<InitListExpr>(Val: Args[0])) { |
9715 | S.Diag(Kind.getLocation(), |
9716 | diag::err_lvalue_reference_bind_to_initlist) |
9717 | << DestType.getNonReferenceType().isVolatileQualified() |
9718 | << DestType.getNonReferenceType() |
9719 | << Args[0]->getSourceRange(); |
9720 | break; |
9721 | } |
9722 | [[fallthrough]]; |
9723 | |
9724 | case FK_NonConstLValueReferenceBindingToUnrelated: |
9725 | S.Diag(Kind.getLocation(), |
9726 | Failure == FK_NonConstLValueReferenceBindingToTemporary |
9727 | ? diag::err_lvalue_reference_bind_to_temporary |
9728 | : diag::err_lvalue_reference_bind_to_unrelated) |
9729 | << DestType.getNonReferenceType().isVolatileQualified() |
9730 | << DestType.getNonReferenceType() |
9731 | << OnlyArg->getType() |
9732 | << Args[0]->getSourceRange(); |
9733 | break; |
9734 | |
9735 | case FK_NonConstLValueReferenceBindingToBitfield: { |
9736 | // We don't necessarily have an unambiguous source bit-field. |
9737 | FieldDecl *BitField = Args[0]->getSourceBitField(); |
9738 | S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield) |
9739 | << DestType.isVolatileQualified() |
9740 | << (BitField ? BitField->getDeclName() : DeclarationName()) |
9741 | << (BitField != nullptr) |
9742 | << Args[0]->getSourceRange(); |
9743 | if (BitField) |
9744 | S.Diag(BitField->getLocation(), diag::note_bitfield_decl); |
9745 | break; |
9746 | } |
9747 | |
9748 | case FK_NonConstLValueReferenceBindingToVectorElement: |
9749 | S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element) |
9750 | << DestType.isVolatileQualified() |
9751 | << Args[0]->getSourceRange(); |
9752 | break; |
9753 | |
9754 | case FK_NonConstLValueReferenceBindingToMatrixElement: |
9755 | S.Diag(Kind.getLocation(), diag::err_reference_bind_to_matrix_element) |
9756 | << DestType.isVolatileQualified() << Args[0]->getSourceRange(); |
9757 | break; |
9758 | |
9759 | case FK_RValueReferenceBindingToLValue: |
9760 | S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref) |
9761 | << DestType.getNonReferenceType() << OnlyArg->getType() |
9762 | << Args[0]->getSourceRange(); |
9763 | break; |
9764 | |
9765 | case FK_ReferenceAddrspaceMismatchTemporary: |
9766 | S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace) |
9767 | << DestType << Args[0]->getSourceRange(); |
9768 | break; |
9769 | |
9770 | case FK_ReferenceInitDropsQualifiers: { |
9771 | QualType SourceType = OnlyArg->getType(); |
9772 | QualType NonRefType = DestType.getNonReferenceType(); |
9773 | Qualifiers DroppedQualifiers = |
9774 | SourceType.getQualifiers() - NonRefType.getQualifiers(); |
9775 | |
9776 | if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf( |
9777 | SourceType.getQualifiers())) |
9778 | S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals) |
9779 | << NonRefType << SourceType << 1 /*addr space*/ |
9780 | << Args[0]->getSourceRange(); |
9781 | else if (DroppedQualifiers.hasQualifiers()) |
9782 | S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals) |
9783 | << NonRefType << SourceType << 0 /*cv quals*/ |
9784 | << Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers()) |
9785 | << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange(); |
9786 | else |
9787 | // FIXME: Consider decomposing the type and explaining which qualifiers |
9788 | // were dropped where, or on which level a 'const' is missing, etc. |
9789 | S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals) |
9790 | << NonRefType << SourceType << 2 /*incompatible quals*/ |
9791 | << Args[0]->getSourceRange(); |
9792 | break; |
9793 | } |
9794 | |
9795 | case FK_ReferenceInitFailed: |
9796 | S.Diag(Kind.getLocation(), diag::err_reference_bind_failed) |
9797 | << DestType.getNonReferenceType() |
9798 | << DestType.getNonReferenceType()->isIncompleteType() |
9799 | << OnlyArg->isLValue() |
9800 | << OnlyArg->getType() |
9801 | << Args[0]->getSourceRange(); |
9802 | emitBadConversionNotes(S, entity: Entity, op: Args[0]); |
9803 | break; |
9804 | |
9805 | case FK_ConversionFailed: { |
9806 | QualType FromType = OnlyArg->getType(); |
9807 | PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed) |
9808 | << (int)Entity.getKind() |
9809 | << DestType |
9810 | << OnlyArg->isLValue() |
9811 | << FromType |
9812 | << Args[0]->getSourceRange(); |
9813 | S.HandleFunctionTypeMismatch(PDiag, FromType, ToType: DestType); |
9814 | S.Diag(Loc: Kind.getLocation(), PD: PDiag); |
9815 | emitBadConversionNotes(S, entity: Entity, op: Args[0]); |
9816 | break; |
9817 | } |
9818 | |
9819 | case FK_ConversionFromPropertyFailed: |
9820 | // No-op. This error has already been reported. |
9821 | break; |
9822 | |
9823 | case FK_TooManyInitsForScalar: { |
9824 | SourceRange R; |
9825 | |
9826 | auto *InitList = dyn_cast<InitListExpr>(Val: Args[0]); |
9827 | if (InitList && InitList->getNumInits() >= 1) { |
9828 | R = SourceRange(InitList->getInit(Init: 0)->getEndLoc(), InitList->getEndLoc()); |
9829 | } else { |
9830 | assert(Args.size() > 1 && "Expected multiple initializers!" ); |
9831 | R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc()); |
9832 | } |
9833 | |
9834 | R.setBegin(S.getLocForEndOfToken(Loc: R.getBegin())); |
9835 | if (Kind.isCStyleOrFunctionalCast()) |
9836 | S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg) |
9837 | << R; |
9838 | else |
9839 | S.Diag(Kind.getLocation(), diag::err_excess_initializers) |
9840 | << /*scalar=*/2 << R; |
9841 | break; |
9842 | } |
9843 | |
9844 | case FK_ParenthesizedListInitForScalar: |
9845 | S.Diag(Kind.getLocation(), diag::err_list_init_in_parens) |
9846 | << 0 << Entity.getType() << Args[0]->getSourceRange(); |
9847 | break; |
9848 | |
9849 | case FK_ReferenceBindingToInitList: |
9850 | S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list) |
9851 | << DestType.getNonReferenceType() << Args[0]->getSourceRange(); |
9852 | break; |
9853 | |
9854 | case FK_InitListBadDestinationType: |
9855 | S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type) |
9856 | << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange(); |
9857 | break; |
9858 | |
9859 | case FK_ListConstructorOverloadFailed: |
9860 | case FK_ConstructorOverloadFailed: { |
9861 | SourceRange ArgsRange; |
9862 | if (Args.size()) |
9863 | ArgsRange = |
9864 | SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc()); |
9865 | |
9866 | if (Failure == FK_ListConstructorOverloadFailed) { |
9867 | assert(Args.size() == 1 && |
9868 | "List construction from other than 1 argument." ); |
9869 | InitListExpr *InitList = cast<InitListExpr>(Val: Args[0]); |
9870 | Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); |
9871 | } |
9872 | |
9873 | // FIXME: Using "DestType" for the entity we're printing is probably |
9874 | // bad. |
9875 | switch (FailedOverloadResult) { |
9876 | case OR_Ambiguous: |
9877 | FailedCandidateSet.NoteCandidates( |
9878 | PartialDiagnosticAt(Kind.getLocation(), |
9879 | S.PDiag(diag::err_ovl_ambiguous_init) |
9880 | << DestType << ArgsRange), |
9881 | S, OCD_AmbiguousCandidates, Args); |
9882 | break; |
9883 | |
9884 | case OR_No_Viable_Function: |
9885 | if (Kind.getKind() == InitializationKind::IK_Default && |
9886 | (Entity.getKind() == InitializedEntity::EK_Base || |
9887 | Entity.getKind() == InitializedEntity::EK_Member || |
9888 | Entity.getKind() == InitializedEntity::EK_ParenAggInitMember) && |
9889 | isa<CXXConstructorDecl>(Val: S.CurContext)) { |
9890 | // This is implicit default initialization of a member or |
9891 | // base within a constructor. If no viable function was |
9892 | // found, notify the user that they need to explicitly |
9893 | // initialize this base/member. |
9894 | CXXConstructorDecl *Constructor |
9895 | = cast<CXXConstructorDecl>(Val: S.CurContext); |
9896 | const CXXRecordDecl *InheritedFrom = nullptr; |
9897 | if (auto Inherited = Constructor->getInheritedConstructor()) |
9898 | InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass(); |
9899 | if (Entity.getKind() == InitializedEntity::EK_Base) { |
9900 | S.Diag(Kind.getLocation(), diag::err_missing_default_ctor) |
9901 | << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0) |
9902 | << S.Context.getTypeDeclType(Constructor->getParent()) |
9903 | << /*base=*/0 |
9904 | << Entity.getType() |
9905 | << InheritedFrom; |
9906 | |
9907 | RecordDecl *BaseDecl |
9908 | = Entity.getBaseSpecifier()->getType()->castAs<RecordType>() |
9909 | ->getDecl(); |
9910 | S.Diag(BaseDecl->getLocation(), diag::note_previous_decl) |
9911 | << S.Context.getTagDeclType(BaseDecl); |
9912 | } else { |
9913 | S.Diag(Kind.getLocation(), diag::err_missing_default_ctor) |
9914 | << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0) |
9915 | << S.Context.getTypeDeclType(Constructor->getParent()) |
9916 | << /*member=*/1 |
9917 | << Entity.getName() |
9918 | << InheritedFrom; |
9919 | S.Diag(Entity.getDecl()->getLocation(), |
9920 | diag::note_member_declared_at); |
9921 | |
9922 | if (const RecordType *Record |
9923 | = Entity.getType()->getAs<RecordType>()) |
9924 | S.Diag(Record->getDecl()->getLocation(), |
9925 | diag::note_previous_decl) |
9926 | << S.Context.getTagDeclType(Record->getDecl()); |
9927 | } |
9928 | break; |
9929 | } |
9930 | |
9931 | FailedCandidateSet.NoteCandidates( |
9932 | PartialDiagnosticAt( |
9933 | Kind.getLocation(), |
9934 | S.PDiag(diag::err_ovl_no_viable_function_in_init) |
9935 | << DestType << ArgsRange), |
9936 | S, OCD_AllCandidates, Args); |
9937 | break; |
9938 | |
9939 | case OR_Deleted: { |
9940 | OverloadCandidateSet::iterator Best; |
9941 | OverloadingResult Ovl |
9942 | = FailedCandidateSet.BestViableFunction(S, Loc: Kind.getLocation(), Best); |
9943 | if (Ovl != OR_Deleted) { |
9944 | S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init) |
9945 | << DestType << ArgsRange; |
9946 | llvm_unreachable("Inconsistent overload resolution?" ); |
9947 | break; |
9948 | } |
9949 | |
9950 | // If this is a defaulted or implicitly-declared function, then |
9951 | // it was implicitly deleted. Make it clear that the deletion was |
9952 | // implicit. |
9953 | if (S.isImplicitlyDeleted(Best->Function)) |
9954 | S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init) |
9955 | << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function)) |
9956 | << DestType << ArgsRange; |
9957 | else |
9958 | S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init) |
9959 | << DestType << ArgsRange; |
9960 | |
9961 | S.NoteDeletedFunction(FD: Best->Function); |
9962 | break; |
9963 | } |
9964 | |
9965 | case OR_Success: |
9966 | llvm_unreachable("Conversion did not fail!" ); |
9967 | } |
9968 | } |
9969 | break; |
9970 | |
9971 | case FK_DefaultInitOfConst: |
9972 | if (Entity.getKind() == InitializedEntity::EK_Member && |
9973 | isa<CXXConstructorDecl>(Val: S.CurContext)) { |
9974 | // This is implicit default-initialization of a const member in |
9975 | // a constructor. Complain that it needs to be explicitly |
9976 | // initialized. |
9977 | CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Val: S.CurContext); |
9978 | S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor) |
9979 | << (Constructor->getInheritedConstructor() ? 2 : |
9980 | Constructor->isImplicit() ? 1 : 0) |
9981 | << S.Context.getTypeDeclType(Constructor->getParent()) |
9982 | << /*const=*/1 |
9983 | << Entity.getName(); |
9984 | S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl) |
9985 | << Entity.getName(); |
9986 | } else if (const auto *VD = dyn_cast_if_present<VarDecl>(Val: Entity.getDecl()); |
9987 | VD && VD->isConstexpr()) { |
9988 | S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init) |
9989 | << VD; |
9990 | } else { |
9991 | S.Diag(Kind.getLocation(), diag::err_default_init_const) |
9992 | << DestType << (bool)DestType->getAs<RecordType>(); |
9993 | } |
9994 | break; |
9995 | |
9996 | case FK_Incomplete: |
9997 | S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType, |
9998 | diag::err_init_incomplete_type); |
9999 | break; |
10000 | |
10001 | case FK_ListInitializationFailed: { |
10002 | // Run the init list checker again to emit diagnostics. |
10003 | InitListExpr *InitList = cast<InitListExpr>(Val: Args[0]); |
10004 | diagnoseListInit(S, Entity, InitList); |
10005 | break; |
10006 | } |
10007 | |
10008 | case FK_PlaceholderType: { |
10009 | // FIXME: Already diagnosed! |
10010 | break; |
10011 | } |
10012 | |
10013 | case FK_ExplicitConstructor: { |
10014 | S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor) |
10015 | << Args[0]->getSourceRange(); |
10016 | OverloadCandidateSet::iterator Best; |
10017 | OverloadingResult Ovl |
10018 | = FailedCandidateSet.BestViableFunction(S, Loc: Kind.getLocation(), Best); |
10019 | (void)Ovl; |
10020 | assert(Ovl == OR_Success && "Inconsistent overload resolution" ); |
10021 | CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Val: Best->Function); |
10022 | S.Diag(CtorDecl->getLocation(), |
10023 | diag::note_explicit_ctor_deduction_guide_here) << false; |
10024 | break; |
10025 | } |
10026 | |
10027 | case FK_ParenthesizedListInitFailed: |
10028 | TryOrBuildParenListInitialization(S, Entity, Kind, Args, Sequence&: *this, |
10029 | /*VerifyOnly=*/false); |
10030 | break; |
10031 | |
10032 | case FK_DesignatedInitForNonAggregate: |
10033 | InitListExpr *InitList = cast<InitListExpr>(Val: Args[0]); |
10034 | S.Diag(Kind.getLocation(), diag::err_designated_init_for_non_aggregate) |
10035 | << Entity.getType() << InitList->getSourceRange(); |
10036 | break; |
10037 | } |
10038 | |
10039 | PrintInitLocationNote(S, Entity); |
10040 | return true; |
10041 | } |
10042 | |
10043 | void InitializationSequence::dump(raw_ostream &OS) const { |
10044 | switch (SequenceKind) { |
10045 | case FailedSequence: { |
10046 | OS << "Failed sequence: " ; |
10047 | switch (Failure) { |
10048 | case FK_TooManyInitsForReference: |
10049 | OS << "too many initializers for reference" ; |
10050 | break; |
10051 | |
10052 | case FK_ParenthesizedListInitForReference: |
10053 | OS << "parenthesized list init for reference" ; |
10054 | break; |
10055 | |
10056 | case FK_ArrayNeedsInitList: |
10057 | OS << "array requires initializer list" ; |
10058 | break; |
10059 | |
10060 | case FK_AddressOfUnaddressableFunction: |
10061 | OS << "address of unaddressable function was taken" ; |
10062 | break; |
10063 | |
10064 | case FK_ArrayNeedsInitListOrStringLiteral: |
10065 | OS << "array requires initializer list or string literal" ; |
10066 | break; |
10067 | |
10068 | case FK_ArrayNeedsInitListOrWideStringLiteral: |
10069 | OS << "array requires initializer list or wide string literal" ; |
10070 | break; |
10071 | |
10072 | case FK_NarrowStringIntoWideCharArray: |
10073 | OS << "narrow string into wide char array" ; |
10074 | break; |
10075 | |
10076 | case FK_WideStringIntoCharArray: |
10077 | OS << "wide string into char array" ; |
10078 | break; |
10079 | |
10080 | case FK_IncompatWideStringIntoWideChar: |
10081 | OS << "incompatible wide string into wide char array" ; |
10082 | break; |
10083 | |
10084 | case FK_PlainStringIntoUTF8Char: |
10085 | OS << "plain string literal into char8_t array" ; |
10086 | break; |
10087 | |
10088 | case FK_UTF8StringIntoPlainChar: |
10089 | OS << "u8 string literal into char array" ; |
10090 | break; |
10091 | |
10092 | case FK_ArrayTypeMismatch: |
10093 | OS << "array type mismatch" ; |
10094 | break; |
10095 | |
10096 | case FK_NonConstantArrayInit: |
10097 | OS << "non-constant array initializer" ; |
10098 | break; |
10099 | |
10100 | case FK_AddressOfOverloadFailed: |
10101 | OS << "address of overloaded function failed" ; |
10102 | break; |
10103 | |
10104 | case FK_ReferenceInitOverloadFailed: |
10105 | OS << "overload resolution for reference initialization failed" ; |
10106 | break; |
10107 | |
10108 | case FK_NonConstLValueReferenceBindingToTemporary: |
10109 | OS << "non-const lvalue reference bound to temporary" ; |
10110 | break; |
10111 | |
10112 | case FK_NonConstLValueReferenceBindingToBitfield: |
10113 | OS << "non-const lvalue reference bound to bit-field" ; |
10114 | break; |
10115 | |
10116 | case FK_NonConstLValueReferenceBindingToVectorElement: |
10117 | OS << "non-const lvalue reference bound to vector element" ; |
10118 | break; |
10119 | |
10120 | case FK_NonConstLValueReferenceBindingToMatrixElement: |
10121 | OS << "non-const lvalue reference bound to matrix element" ; |
10122 | break; |
10123 | |
10124 | case FK_NonConstLValueReferenceBindingToUnrelated: |
10125 | OS << "non-const lvalue reference bound to unrelated type" ; |
10126 | break; |
10127 | |
10128 | case FK_RValueReferenceBindingToLValue: |
10129 | OS << "rvalue reference bound to an lvalue" ; |
10130 | break; |
10131 | |
10132 | case FK_ReferenceInitDropsQualifiers: |
10133 | OS << "reference initialization drops qualifiers" ; |
10134 | break; |
10135 | |
10136 | case FK_ReferenceAddrspaceMismatchTemporary: |
10137 | OS << "reference with mismatching address space bound to temporary" ; |
10138 | break; |
10139 | |
10140 | case FK_ReferenceInitFailed: |
10141 | OS << "reference initialization failed" ; |
10142 | break; |
10143 | |
10144 | case FK_ConversionFailed: |
10145 | OS << "conversion failed" ; |
10146 | break; |
10147 | |
10148 | case FK_ConversionFromPropertyFailed: |
10149 | OS << "conversion from property failed" ; |
10150 | break; |
10151 | |
10152 | case FK_TooManyInitsForScalar: |
10153 | OS << "too many initializers for scalar" ; |
10154 | break; |
10155 | |
10156 | case FK_ParenthesizedListInitForScalar: |
10157 | OS << "parenthesized list init for reference" ; |
10158 | break; |
10159 | |
10160 | case FK_ReferenceBindingToInitList: |
10161 | OS << "referencing binding to initializer list" ; |
10162 | break; |
10163 | |
10164 | case FK_InitListBadDestinationType: |
10165 | OS << "initializer list for non-aggregate, non-scalar type" ; |
10166 | break; |
10167 | |
10168 | case FK_UserConversionOverloadFailed: |
10169 | OS << "overloading failed for user-defined conversion" ; |
10170 | break; |
10171 | |
10172 | case FK_ConstructorOverloadFailed: |
10173 | OS << "constructor overloading failed" ; |
10174 | break; |
10175 | |
10176 | case FK_DefaultInitOfConst: |
10177 | OS << "default initialization of a const variable" ; |
10178 | break; |
10179 | |
10180 | case FK_Incomplete: |
10181 | OS << "initialization of incomplete type" ; |
10182 | break; |
10183 | |
10184 | case FK_ListInitializationFailed: |
10185 | OS << "list initialization checker failure" ; |
10186 | break; |
10187 | |
10188 | case FK_VariableLengthArrayHasInitializer: |
10189 | OS << "variable length array has an initializer" ; |
10190 | break; |
10191 | |
10192 | case FK_PlaceholderType: |
10193 | OS << "initializer expression isn't contextually valid" ; |
10194 | break; |
10195 | |
10196 | case FK_ListConstructorOverloadFailed: |
10197 | OS << "list constructor overloading failed" ; |
10198 | break; |
10199 | |
10200 | case FK_ExplicitConstructor: |
10201 | OS << "list copy initialization chose explicit constructor" ; |
10202 | break; |
10203 | |
10204 | case FK_ParenthesizedListInitFailed: |
10205 | OS << "parenthesized list initialization failed" ; |
10206 | break; |
10207 | |
10208 | case FK_DesignatedInitForNonAggregate: |
10209 | OS << "designated initializer for non-aggregate type" ; |
10210 | break; |
10211 | } |
10212 | OS << '\n'; |
10213 | return; |
10214 | } |
10215 | |
10216 | case DependentSequence: |
10217 | OS << "Dependent sequence\n" ; |
10218 | return; |
10219 | |
10220 | case NormalSequence: |
10221 | OS << "Normal sequence: " ; |
10222 | break; |
10223 | } |
10224 | |
10225 | for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) { |
10226 | if (S != step_begin()) { |
10227 | OS << " -> " ; |
10228 | } |
10229 | |
10230 | switch (S->Kind) { |
10231 | case SK_ResolveAddressOfOverloadedFunction: |
10232 | OS << "resolve address of overloaded function" ; |
10233 | break; |
10234 | |
10235 | case SK_CastDerivedToBasePRValue: |
10236 | OS << "derived-to-base (prvalue)" ; |
10237 | break; |
10238 | |
10239 | case SK_CastDerivedToBaseXValue: |
10240 | OS << "derived-to-base (xvalue)" ; |
10241 | break; |
10242 | |
10243 | case SK_CastDerivedToBaseLValue: |
10244 | OS << "derived-to-base (lvalue)" ; |
10245 | break; |
10246 | |
10247 | case SK_BindReference: |
10248 | OS << "bind reference to lvalue" ; |
10249 | break; |
10250 | |
10251 | case SK_BindReferenceToTemporary: |
10252 | OS << "bind reference to a temporary" ; |
10253 | break; |
10254 | |
10255 | case SK_FinalCopy: |
10256 | OS << "final copy in class direct-initialization" ; |
10257 | break; |
10258 | |
10259 | case SK_ExtraneousCopyToTemporary: |
10260 | OS << "extraneous C++03 copy to temporary" ; |
10261 | break; |
10262 | |
10263 | case SK_UserConversion: |
10264 | OS << "user-defined conversion via " << *S->Function.Function; |
10265 | break; |
10266 | |
10267 | case SK_QualificationConversionPRValue: |
10268 | OS << "qualification conversion (prvalue)" ; |
10269 | break; |
10270 | |
10271 | case SK_QualificationConversionXValue: |
10272 | OS << "qualification conversion (xvalue)" ; |
10273 | break; |
10274 | |
10275 | case SK_QualificationConversionLValue: |
10276 | OS << "qualification conversion (lvalue)" ; |
10277 | break; |
10278 | |
10279 | case SK_FunctionReferenceConversion: |
10280 | OS << "function reference conversion" ; |
10281 | break; |
10282 | |
10283 | case SK_AtomicConversion: |
10284 | OS << "non-atomic-to-atomic conversion" ; |
10285 | break; |
10286 | |
10287 | case SK_ConversionSequence: |
10288 | OS << "implicit conversion sequence (" ; |
10289 | S->ICS->dump(); // FIXME: use OS |
10290 | OS << ")" ; |
10291 | break; |
10292 | |
10293 | case SK_ConversionSequenceNoNarrowing: |
10294 | OS << "implicit conversion sequence with narrowing prohibited (" ; |
10295 | S->ICS->dump(); // FIXME: use OS |
10296 | OS << ")" ; |
10297 | break; |
10298 | |
10299 | case SK_ListInitialization: |
10300 | OS << "list aggregate initialization" ; |
10301 | break; |
10302 | |
10303 | case SK_UnwrapInitList: |
10304 | OS << "unwrap reference initializer list" ; |
10305 | break; |
10306 | |
10307 | case SK_RewrapInitList: |
10308 | OS << "rewrap reference initializer list" ; |
10309 | break; |
10310 | |
10311 | case SK_ConstructorInitialization: |
10312 | OS << "constructor initialization" ; |
10313 | break; |
10314 | |
10315 | case SK_ConstructorInitializationFromList: |
10316 | OS << "list initialization via constructor" ; |
10317 | break; |
10318 | |
10319 | case SK_ZeroInitialization: |
10320 | OS << "zero initialization" ; |
10321 | break; |
10322 | |
10323 | case SK_CAssignment: |
10324 | OS << "C assignment" ; |
10325 | break; |
10326 | |
10327 | case SK_StringInit: |
10328 | OS << "string initialization" ; |
10329 | break; |
10330 | |
10331 | case SK_ObjCObjectConversion: |
10332 | OS << "Objective-C object conversion" ; |
10333 | break; |
10334 | |
10335 | case SK_ArrayLoopIndex: |
10336 | OS << "indexing for array initialization loop" ; |
10337 | break; |
10338 | |
10339 | case SK_ArrayLoopInit: |
10340 | OS << "array initialization loop" ; |
10341 | break; |
10342 | |
10343 | case SK_ArrayInit: |
10344 | OS << "array initialization" ; |
10345 | break; |
10346 | |
10347 | case SK_GNUArrayInit: |
10348 | OS << "array initialization (GNU extension)" ; |
10349 | break; |
10350 | |
10351 | case SK_ParenthesizedArrayInit: |
10352 | OS << "parenthesized array initialization" ; |
10353 | break; |
10354 | |
10355 | case SK_PassByIndirectCopyRestore: |
10356 | OS << "pass by indirect copy and restore" ; |
10357 | break; |
10358 | |
10359 | case SK_PassByIndirectRestore: |
10360 | OS << "pass by indirect restore" ; |
10361 | break; |
10362 | |
10363 | case SK_ProduceObjCObject: |
10364 | OS << "Objective-C object retension" ; |
10365 | break; |
10366 | |
10367 | case SK_StdInitializerList: |
10368 | OS << "std::initializer_list from initializer list" ; |
10369 | break; |
10370 | |
10371 | case SK_StdInitializerListConstructorCall: |
10372 | OS << "list initialization from std::initializer_list" ; |
10373 | break; |
10374 | |
10375 | case SK_OCLSamplerInit: |
10376 | OS << "OpenCL sampler_t from integer constant" ; |
10377 | break; |
10378 | |
10379 | case SK_OCLZeroOpaqueType: |
10380 | OS << "OpenCL opaque type from zero" ; |
10381 | break; |
10382 | case SK_ParenthesizedListInit: |
10383 | OS << "initialization from a parenthesized list of values" ; |
10384 | break; |
10385 | } |
10386 | |
10387 | OS << " [" << S->Type << ']'; |
10388 | } |
10389 | |
10390 | OS << '\n'; |
10391 | } |
10392 | |
10393 | void InitializationSequence::dump() const { |
10394 | dump(OS&: llvm::errs()); |
10395 | } |
10396 | |
10397 | static void DiagnoseNarrowingInInitList(Sema &S, |
10398 | const ImplicitConversionSequence &ICS, |
10399 | QualType PreNarrowingType, |
10400 | QualType EntityType, |
10401 | const Expr *PostInit) { |
10402 | const StandardConversionSequence *SCS = nullptr; |
10403 | switch (ICS.getKind()) { |
10404 | case ImplicitConversionSequence::StandardConversion: |
10405 | SCS = &ICS.Standard; |
10406 | break; |
10407 | case ImplicitConversionSequence::UserDefinedConversion: |
10408 | SCS = &ICS.UserDefined.After; |
10409 | break; |
10410 | case ImplicitConversionSequence::AmbiguousConversion: |
10411 | case ImplicitConversionSequence::StaticObjectArgumentConversion: |
10412 | case ImplicitConversionSequence::EllipsisConversion: |
10413 | case ImplicitConversionSequence::BadConversion: |
10414 | return; |
10415 | } |
10416 | |
10417 | auto MakeDiag = [&](bool IsConstRef, unsigned DefaultDiagID, |
10418 | unsigned ConstRefDiagID, unsigned WarnDiagID) { |
10419 | unsigned DiagID; |
10420 | auto &L = S.getLangOpts(); |
10421 | if (L.CPlusPlus11 && |
10422 | (!L.MicrosoftExt || L.isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015))) |
10423 | DiagID = IsConstRef ? ConstRefDiagID : DefaultDiagID; |
10424 | else |
10425 | DiagID = WarnDiagID; |
10426 | return S.Diag(PostInit->getBeginLoc(), DiagID) |
10427 | << PostInit->getSourceRange(); |
10428 | }; |
10429 | |
10430 | // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion. |
10431 | APValue ConstantValue; |
10432 | QualType ConstantType; |
10433 | switch (SCS->getNarrowingKind(Context&: S.Context, Converted: PostInit, ConstantValue, |
10434 | ConstantType)) { |
10435 | case NK_Not_Narrowing: |
10436 | case NK_Dependent_Narrowing: |
10437 | // No narrowing occurred. |
10438 | return; |
10439 | |
10440 | case NK_Type_Narrowing: { |
10441 | // This was a floating-to-integer conversion, which is always considered a |
10442 | // narrowing conversion even if the value is a constant and can be |
10443 | // represented exactly as an integer. |
10444 | QualType T = EntityType.getNonReferenceType(); |
10445 | MakeDiag(T != EntityType, diag::ext_init_list_type_narrowing, |
10446 | diag::ext_init_list_type_narrowing_const_reference, |
10447 | diag::warn_init_list_type_narrowing) |
10448 | << PreNarrowingType.getLocalUnqualifiedType() |
10449 | << T.getLocalUnqualifiedType(); |
10450 | break; |
10451 | } |
10452 | |
10453 | case NK_Constant_Narrowing: { |
10454 | // A constant value was narrowed. |
10455 | MakeDiag(EntityType.getNonReferenceType() != EntityType, |
10456 | diag::ext_init_list_constant_narrowing, |
10457 | diag::ext_init_list_constant_narrowing_const_reference, |
10458 | diag::warn_init_list_constant_narrowing) |
10459 | << ConstantValue.getAsString(S.getASTContext(), ConstantType) |
10460 | << EntityType.getNonReferenceType().getLocalUnqualifiedType(); |
10461 | break; |
10462 | } |
10463 | |
10464 | case NK_Variable_Narrowing: { |
10465 | // A variable's value may have been narrowed. |
10466 | MakeDiag(EntityType.getNonReferenceType() != EntityType, |
10467 | diag::ext_init_list_variable_narrowing, |
10468 | diag::ext_init_list_variable_narrowing_const_reference, |
10469 | diag::warn_init_list_variable_narrowing) |
10470 | << PreNarrowingType.getLocalUnqualifiedType() |
10471 | << EntityType.getNonReferenceType().getLocalUnqualifiedType(); |
10472 | break; |
10473 | } |
10474 | } |
10475 | |
10476 | SmallString<128> StaticCast; |
10477 | llvm::raw_svector_ostream OS(StaticCast); |
10478 | OS << "static_cast<" ; |
10479 | if (const TypedefType *TT = EntityType->getAs<TypedefType>()) { |
10480 | // It's important to use the typedef's name if there is one so that the |
10481 | // fixit doesn't break code using types like int64_t. |
10482 | // |
10483 | // FIXME: This will break if the typedef requires qualification. But |
10484 | // getQualifiedNameAsString() includes non-machine-parsable components. |
10485 | OS << *TT->getDecl(); |
10486 | } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>()) |
10487 | OS << BT->getName(Policy: S.getLangOpts()); |
10488 | else { |
10489 | // Oops, we didn't find the actual type of the variable. Don't emit a fixit |
10490 | // with a broken cast. |
10491 | return; |
10492 | } |
10493 | OS << ">(" ; |
10494 | S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence) |
10495 | << PostInit->getSourceRange() |
10496 | << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str()) |
10497 | << FixItHint::CreateInsertion( |
10498 | S.getLocForEndOfToken(PostInit->getEndLoc()), ")" ); |
10499 | } |
10500 | |
10501 | //===----------------------------------------------------------------------===// |
10502 | // Initialization helper functions |
10503 | //===----------------------------------------------------------------------===// |
10504 | bool |
10505 | Sema::CanPerformCopyInitialization(const InitializedEntity &Entity, |
10506 | ExprResult Init) { |
10507 | if (Init.isInvalid()) |
10508 | return false; |
10509 | |
10510 | Expr *InitE = Init.get(); |
10511 | assert(InitE && "No initialization expression" ); |
10512 | |
10513 | InitializationKind Kind = |
10514 | InitializationKind::CreateCopy(InitLoc: InitE->getBeginLoc(), EqualLoc: SourceLocation()); |
10515 | InitializationSequence Seq(*this, Entity, Kind, InitE); |
10516 | return !Seq.Failed(); |
10517 | } |
10518 | |
10519 | ExprResult |
10520 | Sema::PerformCopyInitialization(const InitializedEntity &Entity, |
10521 | SourceLocation EqualLoc, |
10522 | ExprResult Init, |
10523 | bool TopLevelOfInitList, |
10524 | bool AllowExplicit) { |
10525 | if (Init.isInvalid()) |
10526 | return ExprError(); |
10527 | |
10528 | Expr *InitE = Init.get(); |
10529 | assert(InitE && "No initialization expression?" ); |
10530 | |
10531 | if (EqualLoc.isInvalid()) |
10532 | EqualLoc = InitE->getBeginLoc(); |
10533 | |
10534 | InitializationKind Kind = InitializationKind::CreateCopy( |
10535 | InitLoc: InitE->getBeginLoc(), EqualLoc, AllowExplicitConvs: AllowExplicit); |
10536 | InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList); |
10537 | |
10538 | // Prevent infinite recursion when performing parameter copy-initialization. |
10539 | const bool ShouldTrackCopy = |
10540 | Entity.isParameterKind() && Seq.isConstructorInitialization(); |
10541 | if (ShouldTrackCopy) { |
10542 | if (llvm::is_contained(Range&: CurrentParameterCopyTypes, Element: Entity.getType())) { |
10543 | Seq.SetOverloadFailure( |
10544 | Failure: InitializationSequence::FK_ConstructorOverloadFailed, |
10545 | Result: OR_No_Viable_Function); |
10546 | |
10547 | // Try to give a meaningful diagnostic note for the problematic |
10548 | // constructor. |
10549 | const auto LastStep = Seq.step_end() - 1; |
10550 | assert(LastStep->Kind == |
10551 | InitializationSequence::SK_ConstructorInitialization); |
10552 | const FunctionDecl *Function = LastStep->Function.Function; |
10553 | auto Candidate = |
10554 | llvm::find_if(Range&: Seq.getFailedCandidateSet(), |
10555 | P: [Function](const OverloadCandidate &Candidate) -> bool { |
10556 | return Candidate.Viable && |
10557 | Candidate.Function == Function && |
10558 | Candidate.Conversions.size() > 0; |
10559 | }); |
10560 | if (Candidate != Seq.getFailedCandidateSet().end() && |
10561 | Function->getNumParams() > 0) { |
10562 | Candidate->Viable = false; |
10563 | Candidate->FailureKind = ovl_fail_bad_conversion; |
10564 | Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion, |
10565 | InitE, |
10566 | Function->getParamDecl(i: 0)->getType()); |
10567 | } |
10568 | } |
10569 | CurrentParameterCopyTypes.push_back(Elt: Entity.getType()); |
10570 | } |
10571 | |
10572 | ExprResult Result = Seq.Perform(S&: *this, Entity, Kind, Args: InitE); |
10573 | |
10574 | if (ShouldTrackCopy) |
10575 | CurrentParameterCopyTypes.pop_back(); |
10576 | |
10577 | return Result; |
10578 | } |
10579 | |
10580 | /// Determine whether RD is, or is derived from, a specialization of CTD. |
10581 | static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD, |
10582 | ClassTemplateDecl *CTD) { |
10583 | auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) { |
10584 | auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Candidate); |
10585 | return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD); |
10586 | }; |
10587 | return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization)); |
10588 | } |
10589 | |
10590 | QualType Sema::DeduceTemplateSpecializationFromInitializer( |
10591 | TypeSourceInfo *TSInfo, const InitializedEntity &Entity, |
10592 | const InitializationKind &Kind, MultiExprArg Inits) { |
10593 | auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>( |
10594 | TSInfo->getType()->getContainedDeducedType()); |
10595 | assert(DeducedTST && "not a deduced template specialization type" ); |
10596 | |
10597 | auto TemplateName = DeducedTST->getTemplateName(); |
10598 | if (TemplateName.isDependent()) |
10599 | return SubstAutoTypeDependent(TypeWithAuto: TSInfo->getType()); |
10600 | |
10601 | // We can only perform deduction for class templates. |
10602 | auto *Template = |
10603 | dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl()); |
10604 | if (!Template) { |
10605 | Diag(Kind.getLocation(), |
10606 | diag::err_deduced_non_class_template_specialization_type) |
10607 | << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName; |
10608 | if (auto *TD = TemplateName.getAsTemplateDecl()) |
10609 | NoteTemplateLocation(Decl: *TD); |
10610 | return QualType(); |
10611 | } |
10612 | |
10613 | // Can't deduce from dependent arguments. |
10614 | if (Expr::hasAnyTypeDependentArguments(Exprs: Inits)) { |
10615 | Diag(TSInfo->getTypeLoc().getBeginLoc(), |
10616 | diag::warn_cxx14_compat_class_template_argument_deduction) |
10617 | << TSInfo->getTypeLoc().getSourceRange() << 0; |
10618 | return SubstAutoTypeDependent(TypeWithAuto: TSInfo->getType()); |
10619 | } |
10620 | |
10621 | // FIXME: Perform "exact type" matching first, per CWG discussion? |
10622 | // Or implement this via an implied 'T(T) -> T' deduction guide? |
10623 | |
10624 | // FIXME: Do we need/want a std::initializer_list<T> special case? |
10625 | |
10626 | // Look up deduction guides, including those synthesized from constructors. |
10627 | // |
10628 | // C++1z [over.match.class.deduct]p1: |
10629 | // A set of functions and function templates is formed comprising: |
10630 | // - For each constructor of the class template designated by the |
10631 | // template-name, a function template [...] |
10632 | // - For each deduction-guide, a function or function template [...] |
10633 | DeclarationNameInfo NameInfo( |
10634 | Context.DeclarationNames.getCXXDeductionGuideName(TD: Template), |
10635 | TSInfo->getTypeLoc().getEndLoc()); |
10636 | LookupResult Guides(*this, NameInfo, LookupOrdinaryName); |
10637 | LookupQualifiedName(Guides, Template->getDeclContext()); |
10638 | |
10639 | // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't |
10640 | // clear on this, but they're not found by name so access does not apply. |
10641 | Guides.suppressDiagnostics(); |
10642 | |
10643 | // Figure out if this is list-initialization. |
10644 | InitListExpr *ListInit = |
10645 | (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct) |
10646 | ? dyn_cast<InitListExpr>(Val: Inits[0]) |
10647 | : nullptr; |
10648 | |
10649 | // C++1z [over.match.class.deduct]p1: |
10650 | // Initialization and overload resolution are performed as described in |
10651 | // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list] |
10652 | // (as appropriate for the type of initialization performed) for an object |
10653 | // of a hypothetical class type, where the selected functions and function |
10654 | // templates are considered to be the constructors of that class type |
10655 | // |
10656 | // Since we know we're initializing a class type of a type unrelated to that |
10657 | // of the initializer, this reduces to something fairly reasonable. |
10658 | OverloadCandidateSet Candidates(Kind.getLocation(), |
10659 | OverloadCandidateSet::CSK_Normal); |
10660 | OverloadCandidateSet::iterator Best; |
10661 | |
10662 | bool AllowExplicit = !Kind.isCopyInit() || ListInit; |
10663 | |
10664 | // Return true if the candidate is added successfully, false otherwise. |
10665 | auto addDeductionCandidate = [&](FunctionTemplateDecl *TD, |
10666 | CXXDeductionGuideDecl *GD, |
10667 | DeclAccessPair FoundDecl, |
10668 | bool OnlyListConstructors, |
10669 | bool AllowAggregateDeductionCandidate) { |
10670 | // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class) |
10671 | // For copy-initialization, the candidate functions are all the |
10672 | // converting constructors (12.3.1) of that class. |
10673 | // C++ [over.match.copy]p1: (non-list copy-initialization from class) |
10674 | // The converting constructors of T are candidate functions. |
10675 | if (!AllowExplicit) { |
10676 | // Overload resolution checks whether the deduction guide is declared |
10677 | // explicit for us. |
10678 | |
10679 | // When looking for a converting constructor, deduction guides that |
10680 | // could never be called with one argument are not interesting to |
10681 | // check or note. |
10682 | if (GD->getMinRequiredArguments() > 1 || |
10683 | (GD->getNumParams() == 0 && !GD->isVariadic())) |
10684 | return; |
10685 | } |
10686 | |
10687 | // C++ [over.match.list]p1.1: (first phase list initialization) |
10688 | // Initially, the candidate functions are the initializer-list |
10689 | // constructors of the class T |
10690 | if (OnlyListConstructors && !isInitListConstructor(GD)) |
10691 | return; |
10692 | |
10693 | if (!AllowAggregateDeductionCandidate && |
10694 | GD->getDeductionCandidateKind() == DeductionCandidate::Aggregate) |
10695 | return; |
10696 | |
10697 | // C++ [over.match.list]p1.2: (second phase list initialization) |
10698 | // the candidate functions are all the constructors of the class T |
10699 | // C++ [over.match.ctor]p1: (all other cases) |
10700 | // the candidate functions are all the constructors of the class of |
10701 | // the object being initialized |
10702 | |
10703 | // C++ [over.best.ics]p4: |
10704 | // When [...] the constructor [...] is a candidate by |
10705 | // - [over.match.copy] (in all cases) |
10706 | // FIXME: The "second phase of [over.match.list] case can also |
10707 | // theoretically happen here, but it's not clear whether we can |
10708 | // ever have a parameter of the right type. |
10709 | bool SuppressUserConversions = Kind.isCopyInit(); |
10710 | |
10711 | if (TD) { |
10712 | SmallVector<Expr *, 8> TmpInits; |
10713 | for (Expr *E : Inits) |
10714 | if (auto *DI = dyn_cast<DesignatedInitExpr>(Val: E)) |
10715 | TmpInits.push_back(Elt: DI->getInit()); |
10716 | else |
10717 | TmpInits.push_back(Elt: E); |
10718 | AddTemplateOverloadCandidate( |
10719 | FunctionTemplate: TD, FoundDecl, /*ExplicitArgs=*/ExplicitTemplateArgs: nullptr, Args: TmpInits, CandidateSet&: Candidates, |
10720 | SuppressUserConversions, |
10721 | /*PartialOverloading=*/false, AllowExplicit, IsADLCandidate: ADLCallKind::NotADL, |
10722 | /*PO=*/{}, AggregateCandidateDeduction: AllowAggregateDeductionCandidate); |
10723 | } else { |
10724 | AddOverloadCandidate(GD, FoundDecl, Inits, Candidates, |
10725 | SuppressUserConversions, |
10726 | /*PartialOverloading=*/false, AllowExplicit); |
10727 | } |
10728 | }; |
10729 | |
10730 | bool FoundDeductionGuide = false; |
10731 | |
10732 | auto TryToResolveOverload = |
10733 | [&](bool OnlyListConstructors) -> OverloadingResult { |
10734 | Candidates.clear(CSK: OverloadCandidateSet::CSK_Normal); |
10735 | bool HasAnyDeductionGuide = false; |
10736 | |
10737 | auto SynthesizeAggrGuide = [&](InitListExpr *ListInit) { |
10738 | auto *Pattern = Template; |
10739 | while (Pattern->getInstantiatedFromMemberTemplate()) { |
10740 | if (Pattern->isMemberSpecialization()) |
10741 | break; |
10742 | Pattern = Pattern->getInstantiatedFromMemberTemplate(); |
10743 | } |
10744 | |
10745 | auto *RD = cast<CXXRecordDecl>(Pattern->getTemplatedDecl()); |
10746 | if (!(RD->getDefinition() && RD->isAggregate())) |
10747 | return; |
10748 | QualType Ty = Context.getRecordType(Decl: RD); |
10749 | SmallVector<QualType, 8> ElementTypes; |
10750 | |
10751 | InitListChecker CheckInitList(*this, Entity, ListInit, Ty, ElementTypes); |
10752 | if (!CheckInitList.HadError()) { |
10753 | // C++ [over.match.class.deduct]p1.8: |
10754 | // if e_i is of array type and x_i is a braced-init-list, T_i is an |
10755 | // rvalue reference to the declared type of e_i and |
10756 | // C++ [over.match.class.deduct]p1.9: |
10757 | // if e_i is of array type and x_i is a bstring-literal, T_i is an |
10758 | // lvalue reference to the const-qualified declared type of e_i and |
10759 | // C++ [over.match.class.deduct]p1.10: |
10760 | // otherwise, T_i is the declared type of e_i |
10761 | for (int I = 0, E = ListInit->getNumInits(); |
10762 | I < E && !isa<PackExpansionType>(Val: ElementTypes[I]); ++I) |
10763 | if (ElementTypes[I]->isArrayType()) { |
10764 | if (isa<InitListExpr>(Val: ListInit->getInit(Init: I))) |
10765 | ElementTypes[I] = Context.getRValueReferenceType(T: ElementTypes[I]); |
10766 | else if (isa<StringLiteral>( |
10767 | Val: ListInit->getInit(Init: I)->IgnoreParenImpCasts())) |
10768 | ElementTypes[I] = |
10769 | Context.getLValueReferenceType(T: ElementTypes[I].withConst()); |
10770 | } |
10771 | |
10772 | llvm::FoldingSetNodeID ID; |
10773 | ID.AddPointer(Ptr: Template); |
10774 | for (auto &T : ElementTypes) |
10775 | T.getCanonicalType().Profile(ID); |
10776 | unsigned Hash = ID.ComputeHash(); |
10777 | if (AggregateDeductionCandidates.count(Val: Hash) == 0) { |
10778 | if (FunctionTemplateDecl *TD = |
10779 | DeclareImplicitDeductionGuideFromInitList( |
10780 | Template: Template, ParamTypes: ElementTypes, |
10781 | Loc: TSInfo->getTypeLoc().getEndLoc())) { |
10782 | auto *GD = cast<CXXDeductionGuideDecl>(Val: TD->getTemplatedDecl()); |
10783 | GD->setDeductionCandidateKind(DeductionCandidate::Aggregate); |
10784 | AggregateDeductionCandidates[Hash] = GD; |
10785 | addDeductionCandidate(TD, GD, DeclAccessPair::make(TD, AS_public), |
10786 | OnlyListConstructors, |
10787 | /*AllowAggregateDeductionCandidate=*/true); |
10788 | } |
10789 | } else { |
10790 | CXXDeductionGuideDecl *GD = AggregateDeductionCandidates[Hash]; |
10791 | FunctionTemplateDecl *TD = GD->getDescribedFunctionTemplate(); |
10792 | assert(TD && "aggregate deduction candidate is function template" ); |
10793 | addDeductionCandidate(TD, GD, DeclAccessPair::make(TD, AS_public), |
10794 | OnlyListConstructors, |
10795 | /*AllowAggregateDeductionCandidate=*/true); |
10796 | } |
10797 | HasAnyDeductionGuide = true; |
10798 | } |
10799 | }; |
10800 | |
10801 | for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) { |
10802 | NamedDecl *D = (*I)->getUnderlyingDecl(); |
10803 | if (D->isInvalidDecl()) |
10804 | continue; |
10805 | |
10806 | auto *TD = dyn_cast<FunctionTemplateDecl>(Val: D); |
10807 | auto *GD = dyn_cast_if_present<CXXDeductionGuideDecl>( |
10808 | TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(Val: D)); |
10809 | if (!GD) |
10810 | continue; |
10811 | |
10812 | if (!GD->isImplicit()) |
10813 | HasAnyDeductionGuide = true; |
10814 | |
10815 | addDeductionCandidate(TD, GD, I.getPair(), OnlyListConstructors, |
10816 | /*AllowAggregateDeductionCandidate=*/false); |
10817 | } |
10818 | |
10819 | // C++ [over.match.class.deduct]p1.4: |
10820 | // if C is defined and its definition satisfies the conditions for an |
10821 | // aggregate class ([dcl.init.aggr]) with the assumption that any |
10822 | // dependent base class has no virtual functions and no virtual base |
10823 | // classes, and the initializer is a non-empty braced-init-list or |
10824 | // parenthesized expression-list, and there are no deduction-guides for |
10825 | // C, the set contains an additional function template, called the |
10826 | // aggregate deduction candidate, defined as follows. |
10827 | if (getLangOpts().CPlusPlus20 && !HasAnyDeductionGuide) { |
10828 | if (ListInit && ListInit->getNumInits()) { |
10829 | SynthesizeAggrGuide(ListInit); |
10830 | } else if (Inits.size()) { // parenthesized expression-list |
10831 | // Inits are expressions inside the parentheses. We don't have |
10832 | // the parentheses source locations, use the begin/end of Inits as the |
10833 | // best heuristic. |
10834 | InitListExpr TempListInit(getASTContext(), Inits.front()->getBeginLoc(), |
10835 | Inits, Inits.back()->getEndLoc()); |
10836 | SynthesizeAggrGuide(&TempListInit); |
10837 | } |
10838 | } |
10839 | |
10840 | FoundDeductionGuide = FoundDeductionGuide || HasAnyDeductionGuide; |
10841 | |
10842 | return Candidates.BestViableFunction(S&: *this, Loc: Kind.getLocation(), Best); |
10843 | }; |
10844 | |
10845 | OverloadingResult Result = OR_No_Viable_Function; |
10846 | |
10847 | // C++11 [over.match.list]p1, per DR1467: for list-initialization, first |
10848 | // try initializer-list constructors. |
10849 | if (ListInit) { |
10850 | bool TryListConstructors = true; |
10851 | |
10852 | // Try list constructors unless the list is empty and the class has one or |
10853 | // more default constructors, in which case those constructors win. |
10854 | if (!ListInit->getNumInits()) { |
10855 | for (NamedDecl *D : Guides) { |
10856 | auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl()); |
10857 | if (FD && FD->getMinRequiredArguments() == 0) { |
10858 | TryListConstructors = false; |
10859 | break; |
10860 | } |
10861 | } |
10862 | } else if (ListInit->getNumInits() == 1) { |
10863 | // C++ [over.match.class.deduct]: |
10864 | // As an exception, the first phase in [over.match.list] (considering |
10865 | // initializer-list constructors) is omitted if the initializer list |
10866 | // consists of a single expression of type cv U, where U is a |
10867 | // specialization of C or a class derived from a specialization of C. |
10868 | Expr *E = ListInit->getInit(Init: 0); |
10869 | auto *RD = E->getType()->getAsCXXRecordDecl(); |
10870 | if (!isa<InitListExpr>(Val: E) && RD && |
10871 | isCompleteType(Loc: Kind.getLocation(), T: E->getType()) && |
10872 | isOrIsDerivedFromSpecializationOf(RD, Template)) |
10873 | TryListConstructors = false; |
10874 | } |
10875 | |
10876 | if (TryListConstructors) |
10877 | Result = TryToResolveOverload(/*OnlyListConstructor*/true); |
10878 | // Then unwrap the initializer list and try again considering all |
10879 | // constructors. |
10880 | Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits()); |
10881 | } |
10882 | |
10883 | // If list-initialization fails, or if we're doing any other kind of |
10884 | // initialization, we (eventually) consider constructors. |
10885 | if (Result == OR_No_Viable_Function) |
10886 | Result = TryToResolveOverload(/*OnlyListConstructor*/false); |
10887 | |
10888 | switch (Result) { |
10889 | case OR_Ambiguous: |
10890 | // FIXME: For list-initialization candidates, it'd usually be better to |
10891 | // list why they were not viable when given the initializer list itself as |
10892 | // an argument. |
10893 | Candidates.NoteCandidates( |
10894 | PartialDiagnosticAt( |
10895 | Kind.getLocation(), |
10896 | PDiag(diag::err_deduced_class_template_ctor_ambiguous) |
10897 | << TemplateName), |
10898 | *this, OCD_AmbiguousCandidates, Inits); |
10899 | return QualType(); |
10900 | |
10901 | case OR_No_Viable_Function: { |
10902 | CXXRecordDecl *Primary = |
10903 | cast<ClassTemplateDecl>(Template)->getTemplatedDecl(); |
10904 | bool Complete = |
10905 | isCompleteType(Loc: Kind.getLocation(), T: Context.getTypeDeclType(Primary)); |
10906 | Candidates.NoteCandidates( |
10907 | PartialDiagnosticAt( |
10908 | Kind.getLocation(), |
10909 | PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable |
10910 | : diag::err_deduced_class_template_incomplete) |
10911 | << TemplateName << !Guides.empty()), |
10912 | *this, OCD_AllCandidates, Inits); |
10913 | return QualType(); |
10914 | } |
10915 | |
10916 | case OR_Deleted: { |
10917 | Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted) |
10918 | << TemplateName; |
10919 | NoteDeletedFunction(FD: Best->Function); |
10920 | return QualType(); |
10921 | } |
10922 | |
10923 | case OR_Success: |
10924 | // C++ [over.match.list]p1: |
10925 | // In copy-list-initialization, if an explicit constructor is chosen, the |
10926 | // initialization is ill-formed. |
10927 | if (Kind.isCopyInit() && ListInit && |
10928 | cast<CXXDeductionGuideDecl>(Val: Best->Function)->isExplicit()) { |
10929 | bool IsDeductionGuide = !Best->Function->isImplicit(); |
10930 | Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit) |
10931 | << TemplateName << IsDeductionGuide; |
10932 | Diag(Best->Function->getLocation(), |
10933 | diag::note_explicit_ctor_deduction_guide_here) |
10934 | << IsDeductionGuide; |
10935 | return QualType(); |
10936 | } |
10937 | |
10938 | // Make sure we didn't select an unusable deduction guide, and mark it |
10939 | // as referenced. |
10940 | DiagnoseUseOfDecl(D: Best->FoundDecl, Locs: Kind.getLocation()); |
10941 | MarkFunctionReferenced(Loc: Kind.getLocation(), Func: Best->Function); |
10942 | break; |
10943 | } |
10944 | |
10945 | // C++ [dcl.type.class.deduct]p1: |
10946 | // The placeholder is replaced by the return type of the function selected |
10947 | // by overload resolution for class template deduction. |
10948 | QualType DeducedType = |
10949 | SubstAutoType(TypeWithAuto: TSInfo->getType(), Replacement: Best->Function->getReturnType()); |
10950 | Diag(TSInfo->getTypeLoc().getBeginLoc(), |
10951 | diag::warn_cxx14_compat_class_template_argument_deduction) |
10952 | << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType; |
10953 | |
10954 | // Warn if CTAD was used on a type that does not have any user-defined |
10955 | // deduction guides. |
10956 | if (!FoundDeductionGuide) { |
10957 | Diag(TSInfo->getTypeLoc().getBeginLoc(), |
10958 | diag::warn_ctad_maybe_unsupported) |
10959 | << TemplateName; |
10960 | Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported); |
10961 | } |
10962 | |
10963 | return DeducedType; |
10964 | } |
10965 | |