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