File: | clang/lib/Sema/SemaInit.cpp |
Warning: | line 8941, 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/TargetInfo.h" | |||
21 | #include "clang/Sema/Designator.h" | |||
22 | #include "clang/Sema/Initialization.h" | |||
23 | #include "clang/Sema/Lookup.h" | |||
24 | #include "clang/Sema/SemaInternal.h" | |||
25 | #include "llvm/ADT/APInt.h" | |||
26 | #include "llvm/ADT/SmallString.h" | |||
27 | #include "llvm/Support/ErrorHandling.h" | |||
28 | #include "llvm/Support/raw_ostream.h" | |||
29 | ||||
30 | using namespace clang; | |||
31 | ||||
32 | //===----------------------------------------------------------------------===// | |||
33 | // Sema Initialization Checking | |||
34 | //===----------------------------------------------------------------------===// | |||
35 | ||||
36 | /// Check whether T is compatible with a wide character type (wchar_t, | |||
37 | /// char16_t or char32_t). | |||
38 | static bool IsWideCharCompatible(QualType T, ASTContext &Context) { | |||
39 | if (Context.typesAreCompatible(Context.getWideCharType(), T)) | |||
40 | return true; | |||
41 | if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) { | |||
42 | return Context.typesAreCompatible(Context.Char16Ty, T) || | |||
43 | Context.typesAreCompatible(Context.Char32Ty, T); | |||
44 | } | |||
45 | return false; | |||
46 | } | |||
47 | ||||
48 | enum StringInitFailureKind { | |||
49 | SIF_None, | |||
50 | SIF_NarrowStringIntoWideChar, | |||
51 | SIF_WideStringIntoChar, | |||
52 | SIF_IncompatWideStringIntoWideChar, | |||
53 | SIF_UTF8StringIntoPlainChar, | |||
54 | SIF_PlainStringIntoUTF8Char, | |||
55 | SIF_Other | |||
56 | }; | |||
57 | ||||
58 | /// Check whether the array of type AT can be initialized by the Init | |||
59 | /// expression by means of string initialization. Returns SIF_None if so, | |||
60 | /// otherwise returns a StringInitFailureKind that describes why the | |||
61 | /// initialization would not work. | |||
62 | static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT, | |||
63 | ASTContext &Context) { | |||
64 | if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT)) | |||
65 | return SIF_Other; | |||
66 | ||||
67 | // See if this is a string literal or @encode. | |||
68 | Init = Init->IgnoreParens(); | |||
69 | ||||
70 | // Handle @encode, which is a narrow string. | |||
71 | if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType()) | |||
72 | return SIF_None; | |||
73 | ||||
74 | // Otherwise we can only handle string literals. | |||
75 | StringLiteral *SL = dyn_cast<StringLiteral>(Init); | |||
76 | if (!SL) | |||
77 | return SIF_Other; | |||
78 | ||||
79 | const QualType ElemTy = | |||
80 | Context.getCanonicalType(AT->getElementType()).getUnqualifiedType(); | |||
81 | ||||
82 | switch (SL->getKind()) { | |||
83 | case StringLiteral::UTF8: | |||
84 | // char8_t array can be initialized with a UTF-8 string. | |||
85 | if (ElemTy->isChar8Type()) | |||
86 | return SIF_None; | |||
87 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
88 | case StringLiteral::Ascii: | |||
89 | // char array can be initialized with a narrow string. | |||
90 | // Only allow char x[] = "foo"; not char x[] = L"foo"; | |||
91 | if (ElemTy->isCharType()) | |||
92 | return (SL->getKind() == StringLiteral::UTF8 && | |||
93 | Context.getLangOpts().Char8) | |||
94 | ? SIF_UTF8StringIntoPlainChar | |||
95 | : SIF_None; | |||
96 | if (ElemTy->isChar8Type()) | |||
97 | return SIF_PlainStringIntoUTF8Char; | |||
98 | if (IsWideCharCompatible(ElemTy, Context)) | |||
99 | return SIF_NarrowStringIntoWideChar; | |||
100 | return SIF_Other; | |||
101 | // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15: | |||
102 | // "An array with element type compatible with a qualified or unqualified | |||
103 | // version of wchar_t, char16_t, or char32_t may be initialized by a wide | |||
104 | // string literal with the corresponding encoding prefix (L, u, or U, | |||
105 | // respectively), optionally enclosed in braces. | |||
106 | case StringLiteral::UTF16: | |||
107 | if (Context.typesAreCompatible(Context.Char16Ty, ElemTy)) | |||
108 | return SIF_None; | |||
109 | if (ElemTy->isCharType() || ElemTy->isChar8Type()) | |||
110 | return SIF_WideStringIntoChar; | |||
111 | if (IsWideCharCompatible(ElemTy, Context)) | |||
112 | return SIF_IncompatWideStringIntoWideChar; | |||
113 | return SIF_Other; | |||
114 | case StringLiteral::UTF32: | |||
115 | if (Context.typesAreCompatible(Context.Char32Ty, ElemTy)) | |||
116 | return SIF_None; | |||
117 | if (ElemTy->isCharType() || ElemTy->isChar8Type()) | |||
118 | return SIF_WideStringIntoChar; | |||
119 | if (IsWideCharCompatible(ElemTy, Context)) | |||
120 | return SIF_IncompatWideStringIntoWideChar; | |||
121 | return SIF_Other; | |||
122 | case StringLiteral::Wide: | |||
123 | if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy)) | |||
124 | return SIF_None; | |||
125 | if (ElemTy->isCharType() || ElemTy->isChar8Type()) | |||
126 | return SIF_WideStringIntoChar; | |||
127 | if (IsWideCharCompatible(ElemTy, Context)) | |||
128 | return SIF_IncompatWideStringIntoWideChar; | |||
129 | return SIF_Other; | |||
130 | } | |||
131 | ||||
132 | llvm_unreachable("missed a StringLiteral kind?")::llvm::llvm_unreachable_internal("missed a StringLiteral kind?" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 132); | |||
133 | } | |||
134 | ||||
135 | static StringInitFailureKind IsStringInit(Expr *init, QualType declType, | |||
136 | ASTContext &Context) { | |||
137 | const ArrayType *arrayType = Context.getAsArrayType(declType); | |||
138 | if (!arrayType) | |||
139 | return SIF_Other; | |||
140 | return IsStringInit(init, arrayType, Context); | |||
141 | } | |||
142 | ||||
143 | /// Update the type of a string literal, including any surrounding parentheses, | |||
144 | /// to match the type of the object which it is initializing. | |||
145 | static void updateStringLiteralType(Expr *E, QualType Ty) { | |||
146 | while (true) { | |||
147 | E->setType(Ty); | |||
148 | E->setValueKind(VK_RValue); | |||
149 | if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E)) { | |||
150 | break; | |||
151 | } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { | |||
152 | E = PE->getSubExpr(); | |||
153 | } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { | |||
154 | assert(UO->getOpcode() == UO_Extension)((UO->getOpcode() == UO_Extension) ? static_cast<void> (0) : __assert_fail ("UO->getOpcode() == UO_Extension", "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 154, __PRETTY_FUNCTION__)); | |||
155 | E = UO->getSubExpr(); | |||
156 | } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) { | |||
157 | E = GSE->getResultExpr(); | |||
158 | } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) { | |||
159 | E = CE->getChosenSubExpr(); | |||
160 | } else { | |||
161 | llvm_unreachable("unexpected expr in string literal init")::llvm::llvm_unreachable_internal("unexpected expr in string literal init" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 161); | |||
162 | } | |||
163 | } | |||
164 | } | |||
165 | ||||
166 | /// Fix a compound literal initializing an array so it's correctly marked | |||
167 | /// as an rvalue. | |||
168 | static void updateGNUCompoundLiteralRValue(Expr *E) { | |||
169 | while (true) { | |||
170 | E->setValueKind(VK_RValue); | |||
171 | if (isa<CompoundLiteralExpr>(E)) { | |||
172 | break; | |||
173 | } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { | |||
174 | E = PE->getSubExpr(); | |||
175 | } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { | |||
176 | assert(UO->getOpcode() == UO_Extension)((UO->getOpcode() == UO_Extension) ? static_cast<void> (0) : __assert_fail ("UO->getOpcode() == UO_Extension", "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 176, __PRETTY_FUNCTION__)); | |||
177 | E = UO->getSubExpr(); | |||
178 | } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) { | |||
179 | E = GSE->getResultExpr(); | |||
180 | } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) { | |||
181 | E = CE->getChosenSubExpr(); | |||
182 | } else { | |||
183 | llvm_unreachable("unexpected expr in array compound literal init")::llvm::llvm_unreachable_internal("unexpected expr in array compound literal init" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 183); | |||
184 | } | |||
185 | } | |||
186 | } | |||
187 | ||||
188 | static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT, | |||
189 | Sema &S) { | |||
190 | // Get the length of the string as parsed. | |||
191 | auto *ConstantArrayTy = | |||
192 | cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe()); | |||
193 | uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue(); | |||
194 | ||||
195 | if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) { | |||
196 | // C99 6.7.8p14. We have an array of character type with unknown size | |||
197 | // being initialized to a string literal. | |||
198 | llvm::APInt ConstVal(32, StrLength); | |||
199 | // Return a new array type (C99 6.7.8p22). | |||
200 | DeclT = S.Context.getConstantArrayType(IAT->getElementType(), | |||
201 | ConstVal, nullptr, | |||
202 | ArrayType::Normal, 0); | |||
203 | updateStringLiteralType(Str, DeclT); | |||
204 | return; | |||
205 | } | |||
206 | ||||
207 | const ConstantArrayType *CAT = cast<ConstantArrayType>(AT); | |||
208 | ||||
209 | // We have an array of character type with known size. However, | |||
210 | // the size may be smaller or larger than the string we are initializing. | |||
211 | // FIXME: Avoid truncation for 64-bit length strings. | |||
212 | if (S.getLangOpts().CPlusPlus) { | |||
213 | if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) { | |||
214 | // For Pascal strings it's OK to strip off the terminating null character, | |||
215 | // so the example below is valid: | |||
216 | // | |||
217 | // unsigned char a[2] = "\pa"; | |||
218 | if (SL->isPascal()) | |||
219 | StrLength--; | |||
220 | } | |||
221 | ||||
222 | // [dcl.init.string]p2 | |||
223 | if (StrLength > CAT->getSize().getZExtValue()) | |||
224 | S.Diag(Str->getBeginLoc(), | |||
225 | diag::err_initializer_string_for_char_array_too_long) | |||
226 | << Str->getSourceRange(); | |||
227 | } else { | |||
228 | // C99 6.7.8p14. | |||
229 | if (StrLength-1 > CAT->getSize().getZExtValue()) | |||
230 | S.Diag(Str->getBeginLoc(), | |||
231 | diag::ext_initializer_string_for_char_array_too_long) | |||
232 | << Str->getSourceRange(); | |||
233 | } | |||
234 | ||||
235 | // Set the type to the actual size that we are initializing. If we have | |||
236 | // something like: | |||
237 | // char x[1] = "foo"; | |||
238 | // then this will set the string literal's type to char[1]. | |||
239 | updateStringLiteralType(Str, DeclT); | |||
240 | } | |||
241 | ||||
242 | //===----------------------------------------------------------------------===// | |||
243 | // Semantic checking for initializer lists. | |||
244 | //===----------------------------------------------------------------------===// | |||
245 | ||||
246 | namespace { | |||
247 | ||||
248 | /// Semantic checking for initializer lists. | |||
249 | /// | |||
250 | /// The InitListChecker class contains a set of routines that each | |||
251 | /// handle the initialization of a certain kind of entity, e.g., | |||
252 | /// arrays, vectors, struct/union types, scalars, etc. The | |||
253 | /// InitListChecker itself performs a recursive walk of the subobject | |||
254 | /// structure of the type to be initialized, while stepping through | |||
255 | /// the initializer list one element at a time. The IList and Index | |||
256 | /// parameters to each of the Check* routines contain the active | |||
257 | /// (syntactic) initializer list and the index into that initializer | |||
258 | /// list that represents the current initializer. Each routine is | |||
259 | /// responsible for moving that Index forward as it consumes elements. | |||
260 | /// | |||
261 | /// Each Check* routine also has a StructuredList/StructuredIndex | |||
262 | /// arguments, which contains the current "structured" (semantic) | |||
263 | /// initializer list and the index into that initializer list where we | |||
264 | /// are copying initializers as we map them over to the semantic | |||
265 | /// list. Once we have completed our recursive walk of the subobject | |||
266 | /// structure, we will have constructed a full semantic initializer | |||
267 | /// list. | |||
268 | /// | |||
269 | /// C99 designators cause changes in the initializer list traversal, | |||
270 | /// because they make the initialization "jump" into a specific | |||
271 | /// subobject and then continue the initialization from that | |||
272 | /// point. CheckDesignatedInitializer() recursively steps into the | |||
273 | /// designated subobject and manages backing out the recursion to | |||
274 | /// initialize the subobjects after the one designated. | |||
275 | /// | |||
276 | /// If an initializer list contains any designators, we build a placeholder | |||
277 | /// structured list even in 'verify only' mode, so that we can track which | |||
278 | /// elements need 'empty' initializtion. | |||
279 | class InitListChecker { | |||
280 | Sema &SemaRef; | |||
281 | bool hadError = false; | |||
282 | bool VerifyOnly; // No diagnostics. | |||
283 | bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode. | |||
284 | bool InOverloadResolution; | |||
285 | InitListExpr *FullyStructuredList = nullptr; | |||
286 | NoInitExpr *DummyExpr = nullptr; | |||
287 | ||||
288 | NoInitExpr *getDummyInit() { | |||
289 | if (!DummyExpr) | |||
290 | DummyExpr = new (SemaRef.Context) NoInitExpr(SemaRef.Context.VoidTy); | |||
291 | return DummyExpr; | |||
292 | } | |||
293 | ||||
294 | void CheckImplicitInitList(const InitializedEntity &Entity, | |||
295 | InitListExpr *ParentIList, QualType T, | |||
296 | unsigned &Index, InitListExpr *StructuredList, | |||
297 | unsigned &StructuredIndex); | |||
298 | void CheckExplicitInitList(const InitializedEntity &Entity, | |||
299 | InitListExpr *IList, QualType &T, | |||
300 | InitListExpr *StructuredList, | |||
301 | bool TopLevelObject = false); | |||
302 | void CheckListElementTypes(const InitializedEntity &Entity, | |||
303 | InitListExpr *IList, QualType &DeclType, | |||
304 | bool SubobjectIsDesignatorContext, | |||
305 | unsigned &Index, | |||
306 | InitListExpr *StructuredList, | |||
307 | unsigned &StructuredIndex, | |||
308 | bool TopLevelObject = false); | |||
309 | void CheckSubElementType(const InitializedEntity &Entity, | |||
310 | InitListExpr *IList, QualType ElemType, | |||
311 | unsigned &Index, | |||
312 | InitListExpr *StructuredList, | |||
313 | unsigned &StructuredIndex); | |||
314 | void CheckComplexType(const InitializedEntity &Entity, | |||
315 | InitListExpr *IList, QualType DeclType, | |||
316 | unsigned &Index, | |||
317 | InitListExpr *StructuredList, | |||
318 | unsigned &StructuredIndex); | |||
319 | void CheckScalarType(const InitializedEntity &Entity, | |||
320 | InitListExpr *IList, QualType DeclType, | |||
321 | unsigned &Index, | |||
322 | InitListExpr *StructuredList, | |||
323 | unsigned &StructuredIndex); | |||
324 | void CheckReferenceType(const InitializedEntity &Entity, | |||
325 | InitListExpr *IList, QualType DeclType, | |||
326 | unsigned &Index, | |||
327 | InitListExpr *StructuredList, | |||
328 | unsigned &StructuredIndex); | |||
329 | void CheckVectorType(const InitializedEntity &Entity, | |||
330 | InitListExpr *IList, QualType DeclType, unsigned &Index, | |||
331 | InitListExpr *StructuredList, | |||
332 | unsigned &StructuredIndex); | |||
333 | void CheckStructUnionTypes(const InitializedEntity &Entity, | |||
334 | InitListExpr *IList, QualType DeclType, | |||
335 | CXXRecordDecl::base_class_range Bases, | |||
336 | RecordDecl::field_iterator Field, | |||
337 | bool SubobjectIsDesignatorContext, unsigned &Index, | |||
338 | InitListExpr *StructuredList, | |||
339 | unsigned &StructuredIndex, | |||
340 | bool TopLevelObject = false); | |||
341 | void CheckArrayType(const InitializedEntity &Entity, | |||
342 | InitListExpr *IList, QualType &DeclType, | |||
343 | llvm::APSInt elementIndex, | |||
344 | bool SubobjectIsDesignatorContext, unsigned &Index, | |||
345 | InitListExpr *StructuredList, | |||
346 | unsigned &StructuredIndex); | |||
347 | bool CheckDesignatedInitializer(const InitializedEntity &Entity, | |||
348 | InitListExpr *IList, DesignatedInitExpr *DIE, | |||
349 | unsigned DesigIdx, | |||
350 | QualType &CurrentObjectType, | |||
351 | RecordDecl::field_iterator *NextField, | |||
352 | llvm::APSInt *NextElementIndex, | |||
353 | unsigned &Index, | |||
354 | InitListExpr *StructuredList, | |||
355 | unsigned &StructuredIndex, | |||
356 | bool FinishSubobjectInit, | |||
357 | bool TopLevelObject); | |||
358 | InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, | |||
359 | QualType CurrentObjectType, | |||
360 | InitListExpr *StructuredList, | |||
361 | unsigned StructuredIndex, | |||
362 | SourceRange InitRange, | |||
363 | bool IsFullyOverwritten = false); | |||
364 | void UpdateStructuredListElement(InitListExpr *StructuredList, | |||
365 | unsigned &StructuredIndex, | |||
366 | Expr *expr); | |||
367 | InitListExpr *createInitListExpr(QualType CurrentObjectType, | |||
368 | SourceRange InitRange, | |||
369 | unsigned ExpectedNumInits); | |||
370 | int numArrayElements(QualType DeclType); | |||
371 | int numStructUnionElements(QualType DeclType); | |||
372 | ||||
373 | ExprResult PerformEmptyInit(SourceLocation Loc, | |||
374 | const InitializedEntity &Entity); | |||
375 | ||||
376 | /// Diagnose that OldInit (or part thereof) has been overridden by NewInit. | |||
377 | void diagnoseInitOverride(Expr *OldInit, SourceRange NewInitRange, | |||
378 | bool FullyOverwritten = true) { | |||
379 | // Overriding an initializer via a designator is valid with C99 designated | |||
380 | // initializers, but ill-formed with C++20 designated initializers. | |||
381 | unsigned DiagID = SemaRef.getLangOpts().CPlusPlus | |||
382 | ? diag::ext_initializer_overrides | |||
383 | : diag::warn_initializer_overrides; | |||
384 | ||||
385 | if (InOverloadResolution && SemaRef.getLangOpts().CPlusPlus) { | |||
386 | // In overload resolution, we have to strictly enforce the rules, and so | |||
387 | // don't allow any overriding of prior initializers. This matters for a | |||
388 | // case such as: | |||
389 | // | |||
390 | // union U { int a, b; }; | |||
391 | // struct S { int a, b; }; | |||
392 | // void f(U), f(S); | |||
393 | // | |||
394 | // Here, f({.a = 1, .b = 2}) is required to call the struct overload. For | |||
395 | // consistency, we disallow all overriding of prior initializers in | |||
396 | // overload resolution, not only overriding of union members. | |||
397 | hadError = true; | |||
398 | } else if (OldInit->getType().isDestructedType() && !FullyOverwritten) { | |||
399 | // If we'll be keeping around the old initializer but overwriting part of | |||
400 | // the object it initialized, and that object is not trivially | |||
401 | // destructible, this can leak. Don't allow that, not even as an | |||
402 | // extension. | |||
403 | // | |||
404 | // FIXME: It might be reasonable to allow this in cases where the part of | |||
405 | // the initializer that we're overriding has trivial destruction. | |||
406 | DiagID = diag::err_initializer_overrides_destructed; | |||
407 | } else if (!OldInit->getSourceRange().isValid()) { | |||
408 | // We need to check on source range validity because the previous | |||
409 | // initializer does not have to be an explicit initializer. e.g., | |||
410 | // | |||
411 | // struct P { int a, b; }; | |||
412 | // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 }; | |||
413 | // | |||
414 | // There is an overwrite taking place because the first braced initializer | |||
415 | // list "{ .a = 2 }" already provides value for .p.b (which is zero). | |||
416 | // | |||
417 | // Such overwrites are harmless, so we don't diagnose them. (Note that in | |||
418 | // C++, this cannot be reached unless we've already seen and diagnosed a | |||
419 | // different conformance issue, such as a mixture of designated and | |||
420 | // non-designated initializers or a multi-level designator.) | |||
421 | return; | |||
422 | } | |||
423 | ||||
424 | if (!VerifyOnly) { | |||
425 | SemaRef.Diag(NewInitRange.getBegin(), DiagID) | |||
426 | << NewInitRange << FullyOverwritten << OldInit->getType(); | |||
427 | SemaRef.Diag(OldInit->getBeginLoc(), diag::note_previous_initializer) | |||
428 | << (OldInit->HasSideEffects(SemaRef.Context) && FullyOverwritten) | |||
429 | << OldInit->getSourceRange(); | |||
430 | } | |||
431 | } | |||
432 | ||||
433 | // Explanation on the "FillWithNoInit" mode: | |||
434 | // | |||
435 | // Assume we have the following definitions (Case#1): | |||
436 | // struct P { char x[6][6]; } xp = { .x[1] = "bar" }; | |||
437 | // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' }; | |||
438 | // | |||
439 | // l.lp.x[1][0..1] should not be filled with implicit initializers because the | |||
440 | // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf". | |||
441 | // | |||
442 | // But if we have (Case#2): | |||
443 | // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } }; | |||
444 | // | |||
445 | // l.lp.x[1][0..1] are implicitly initialized and do not use values from the | |||
446 | // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0". | |||
447 | // | |||
448 | // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes" | |||
449 | // in the InitListExpr, the "holes" in Case#1 are filled not with empty | |||
450 | // initializers but with special "NoInitExpr" place holders, which tells the | |||
451 | // CodeGen not to generate any initializers for these parts. | |||
452 | void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base, | |||
453 | const InitializedEntity &ParentEntity, | |||
454 | InitListExpr *ILE, bool &RequiresSecondPass, | |||
455 | bool FillWithNoInit); | |||
456 | void FillInEmptyInitForField(unsigned Init, FieldDecl *Field, | |||
457 | const InitializedEntity &ParentEntity, | |||
458 | InitListExpr *ILE, bool &RequiresSecondPass, | |||
459 | bool FillWithNoInit = false); | |||
460 | void FillInEmptyInitializations(const InitializedEntity &Entity, | |||
461 | InitListExpr *ILE, bool &RequiresSecondPass, | |||
462 | InitListExpr *OuterILE, unsigned OuterIndex, | |||
463 | bool FillWithNoInit = false); | |||
464 | bool CheckFlexibleArrayInit(const InitializedEntity &Entity, | |||
465 | Expr *InitExpr, FieldDecl *Field, | |||
466 | bool TopLevelObject); | |||
467 | void CheckEmptyInitializable(const InitializedEntity &Entity, | |||
468 | SourceLocation Loc); | |||
469 | ||||
470 | public: | |||
471 | InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL, | |||
472 | QualType &T, bool VerifyOnly, bool TreatUnavailableAsInvalid, | |||
473 | bool InOverloadResolution = false); | |||
474 | bool HadError() { return hadError; } | |||
475 | ||||
476 | // Retrieves the fully-structured initializer list used for | |||
477 | // semantic analysis and code generation. | |||
478 | InitListExpr *getFullyStructuredList() const { return FullyStructuredList; } | |||
479 | }; | |||
480 | ||||
481 | } // end anonymous namespace | |||
482 | ||||
483 | ExprResult InitListChecker::PerformEmptyInit(SourceLocation Loc, | |||
484 | const InitializedEntity &Entity) { | |||
485 | InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc, | |||
486 | true); | |||
487 | MultiExprArg SubInit; | |||
488 | Expr *InitExpr; | |||
489 | InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc); | |||
490 | ||||
491 | // C++ [dcl.init.aggr]p7: | |||
492 | // If there are fewer initializer-clauses in the list than there are | |||
493 | // members in the aggregate, then each member not explicitly initialized | |||
494 | // ... | |||
495 | bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 && | |||
496 | Entity.getType()->getBaseElementTypeUnsafe()->isRecordType(); | |||
497 | if (EmptyInitList) { | |||
498 | // C++1y / DR1070: | |||
499 | // shall be initialized [...] from an empty initializer list. | |||
500 | // | |||
501 | // We apply the resolution of this DR to C++11 but not C++98, since C++98 | |||
502 | // does not have useful semantics for initialization from an init list. | |||
503 | // We treat this as copy-initialization, because aggregate initialization | |||
504 | // always performs copy-initialization on its elements. | |||
505 | // | |||
506 | // Only do this if we're initializing a class type, to avoid filling in | |||
507 | // the initializer list where possible. | |||
508 | InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context) | |||
509 | InitListExpr(SemaRef.Context, Loc, None, Loc); | |||
510 | InitExpr->setType(SemaRef.Context.VoidTy); | |||
511 | SubInit = InitExpr; | |||
512 | Kind = InitializationKind::CreateCopy(Loc, Loc); | |||
513 | } else { | |||
514 | // C++03: | |||
515 | // shall be value-initialized. | |||
516 | } | |||
517 | ||||
518 | InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit); | |||
519 | // libstdc++4.6 marks the vector default constructor as explicit in | |||
520 | // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case. | |||
521 | // stlport does so too. Look for std::__debug for libstdc++, and for | |||
522 | // std:: for stlport. This is effectively a compiler-side implementation of | |||
523 | // LWG2193. | |||
524 | if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() == | |||
525 | InitializationSequence::FK_ExplicitConstructor) { | |||
526 | OverloadCandidateSet::iterator Best; | |||
527 | OverloadingResult O = | |||
528 | InitSeq.getFailedCandidateSet() | |||
529 | .BestViableFunction(SemaRef, Kind.getLocation(), Best); | |||
530 | (void)O; | |||
531 | assert(O == OR_Success && "Inconsistent overload resolution")((O == OR_Success && "Inconsistent overload resolution" ) ? static_cast<void> (0) : __assert_fail ("O == OR_Success && \"Inconsistent overload resolution\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 531, __PRETTY_FUNCTION__)); | |||
532 | CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function); | |||
533 | CXXRecordDecl *R = CtorDecl->getParent(); | |||
534 | ||||
535 | if (CtorDecl->getMinRequiredArguments() == 0 && | |||
536 | CtorDecl->isExplicit() && R->getDeclName() && | |||
537 | SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) { | |||
538 | bool IsInStd = false; | |||
539 | for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext()); | |||
540 | ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) { | |||
541 | if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND)) | |||
542 | IsInStd = true; | |||
543 | } | |||
544 | ||||
545 | if (IsInStd && llvm::StringSwitch<bool>(R->getName()) | |||
546 | .Cases("basic_string", "deque", "forward_list", true) | |||
547 | .Cases("list", "map", "multimap", "multiset", true) | |||
548 | .Cases("priority_queue", "queue", "set", "stack", true) | |||
549 | .Cases("unordered_map", "unordered_set", "vector", true) | |||
550 | .Default(false)) { | |||
551 | InitSeq.InitializeFrom( | |||
552 | SemaRef, Entity, | |||
553 | InitializationKind::CreateValue(Loc, Loc, Loc, true), | |||
554 | MultiExprArg(), /*TopLevelOfInitList=*/false, | |||
555 | TreatUnavailableAsInvalid); | |||
556 | // Emit a warning for this. System header warnings aren't shown | |||
557 | // by default, but people working on system headers should see it. | |||
558 | if (!VerifyOnly) { | |||
559 | SemaRef.Diag(CtorDecl->getLocation(), | |||
560 | diag::warn_invalid_initializer_from_system_header); | |||
561 | if (Entity.getKind() == InitializedEntity::EK_Member) | |||
562 | SemaRef.Diag(Entity.getDecl()->getLocation(), | |||
563 | diag::note_used_in_initialization_here); | |||
564 | else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) | |||
565 | SemaRef.Diag(Loc, diag::note_used_in_initialization_here); | |||
566 | } | |||
567 | } | |||
568 | } | |||
569 | } | |||
570 | if (!InitSeq) { | |||
571 | if (!VerifyOnly) { | |||
572 | InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit); | |||
573 | if (Entity.getKind() == InitializedEntity::EK_Member) | |||
574 | SemaRef.Diag(Entity.getDecl()->getLocation(), | |||
575 | diag::note_in_omitted_aggregate_initializer) | |||
576 | << /*field*/1 << Entity.getDecl(); | |||
577 | else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) { | |||
578 | bool IsTrailingArrayNewMember = | |||
579 | Entity.getParent() && | |||
580 | Entity.getParent()->isVariableLengthArrayNew(); | |||
581 | SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer) | |||
582 | << (IsTrailingArrayNewMember ? 2 : /*array element*/0) | |||
583 | << Entity.getElementIndex(); | |||
584 | } | |||
585 | } | |||
586 | hadError = true; | |||
587 | return ExprError(); | |||
588 | } | |||
589 | ||||
590 | return VerifyOnly ? ExprResult() | |||
591 | : InitSeq.Perform(SemaRef, Entity, Kind, SubInit); | |||
592 | } | |||
593 | ||||
594 | void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity, | |||
595 | SourceLocation Loc) { | |||
596 | // If we're building a fully-structured list, we'll check this at the end | |||
597 | // once we know which elements are actually initialized. Otherwise, we know | |||
598 | // that there are no designators so we can just check now. | |||
599 | if (FullyStructuredList) | |||
600 | return; | |||
601 | PerformEmptyInit(Loc, Entity); | |||
602 | } | |||
603 | ||||
604 | void InitListChecker::FillInEmptyInitForBase( | |||
605 | unsigned Init, const CXXBaseSpecifier &Base, | |||
606 | const InitializedEntity &ParentEntity, InitListExpr *ILE, | |||
607 | bool &RequiresSecondPass, bool FillWithNoInit) { | |||
608 | InitializedEntity BaseEntity = InitializedEntity::InitializeBase( | |||
609 | SemaRef.Context, &Base, false, &ParentEntity); | |||
610 | ||||
611 | if (Init >= ILE->getNumInits() || !ILE->getInit(Init)) { | |||
612 | ExprResult BaseInit = FillWithNoInit | |||
613 | ? new (SemaRef.Context) NoInitExpr(Base.getType()) | |||
614 | : PerformEmptyInit(ILE->getEndLoc(), BaseEntity); | |||
615 | if (BaseInit.isInvalid()) { | |||
616 | hadError = true; | |||
617 | return; | |||
618 | } | |||
619 | ||||
620 | if (!VerifyOnly) { | |||
621 | assert(Init < ILE->getNumInits() && "should have been expanded")((Init < ILE->getNumInits() && "should have been expanded" ) ? static_cast<void> (0) : __assert_fail ("Init < ILE->getNumInits() && \"should have been expanded\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 621, __PRETTY_FUNCTION__)); | |||
622 | ILE->setInit(Init, BaseInit.getAs<Expr>()); | |||
623 | } | |||
624 | } else if (InitListExpr *InnerILE = | |||
625 | dyn_cast<InitListExpr>(ILE->getInit(Init))) { | |||
626 | FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass, | |||
627 | ILE, Init, FillWithNoInit); | |||
628 | } else if (DesignatedInitUpdateExpr *InnerDIUE = | |||
629 | dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) { | |||
630 | FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(), | |||
631 | RequiresSecondPass, ILE, Init, | |||
632 | /*FillWithNoInit =*/true); | |||
633 | } | |||
634 | } | |||
635 | ||||
636 | void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field, | |||
637 | const InitializedEntity &ParentEntity, | |||
638 | InitListExpr *ILE, | |||
639 | bool &RequiresSecondPass, | |||
640 | bool FillWithNoInit) { | |||
641 | SourceLocation Loc = ILE->getEndLoc(); | |||
642 | unsigned NumInits = ILE->getNumInits(); | |||
643 | InitializedEntity MemberEntity | |||
644 | = InitializedEntity::InitializeMember(Field, &ParentEntity); | |||
645 | ||||
646 | if (Init >= NumInits || !ILE->getInit(Init)) { | |||
647 | if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) | |||
648 | if (!RType->getDecl()->isUnion()) | |||
649 | assert((Init < NumInits || VerifyOnly) &&(((Init < NumInits || VerifyOnly) && "This ILE should have been expanded" ) ? static_cast<void> (0) : __assert_fail ("(Init < NumInits || VerifyOnly) && \"This ILE should have been expanded\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 650, __PRETTY_FUNCTION__)) | |||
650 | "This ILE should have been expanded")(((Init < NumInits || VerifyOnly) && "This ILE should have been expanded" ) ? static_cast<void> (0) : __assert_fail ("(Init < NumInits || VerifyOnly) && \"This ILE should have been expanded\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 650, __PRETTY_FUNCTION__)); | |||
651 | ||||
652 | if (FillWithNoInit) { | |||
653 | assert(!VerifyOnly && "should not fill with no-init in verify-only mode")((!VerifyOnly && "should not fill with no-init in verify-only mode" ) ? static_cast<void> (0) : __assert_fail ("!VerifyOnly && \"should not fill with no-init in verify-only mode\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 653, __PRETTY_FUNCTION__)); | |||
654 | Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType()); | |||
655 | if (Init < NumInits) | |||
656 | ILE->setInit(Init, Filler); | |||
657 | else | |||
658 | ILE->updateInit(SemaRef.Context, Init, Filler); | |||
659 | return; | |||
660 | } | |||
661 | // C++1y [dcl.init.aggr]p7: | |||
662 | // If there are fewer initializer-clauses in the list than there are | |||
663 | // members in the aggregate, then each member not explicitly initialized | |||
664 | // shall be initialized from its brace-or-equal-initializer [...] | |||
665 | if (Field->hasInClassInitializer()) { | |||
666 | if (VerifyOnly) | |||
667 | return; | |||
668 | ||||
669 | ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field); | |||
670 | if (DIE.isInvalid()) { | |||
671 | hadError = true; | |||
672 | return; | |||
673 | } | |||
674 | SemaRef.checkInitializerLifetime(MemberEntity, DIE.get()); | |||
675 | if (Init < NumInits) | |||
676 | ILE->setInit(Init, DIE.get()); | |||
677 | else { | |||
678 | ILE->updateInit(SemaRef.Context, Init, DIE.get()); | |||
679 | RequiresSecondPass = true; | |||
680 | } | |||
681 | return; | |||
682 | } | |||
683 | ||||
684 | if (Field->getType()->isReferenceType()) { | |||
685 | if (!VerifyOnly) { | |||
686 | // C++ [dcl.init.aggr]p9: | |||
687 | // If an incomplete or empty initializer-list leaves a | |||
688 | // member of reference type uninitialized, the program is | |||
689 | // ill-formed. | |||
690 | SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized) | |||
691 | << Field->getType() | |||
692 | << ILE->getSyntacticForm()->getSourceRange(); | |||
693 | SemaRef.Diag(Field->getLocation(), | |||
694 | diag::note_uninit_reference_member); | |||
695 | } | |||
696 | hadError = true; | |||
697 | return; | |||
698 | } | |||
699 | ||||
700 | ExprResult MemberInit = PerformEmptyInit(Loc, MemberEntity); | |||
701 | if (MemberInit.isInvalid()) { | |||
702 | hadError = true; | |||
703 | return; | |||
704 | } | |||
705 | ||||
706 | if (hadError || VerifyOnly) { | |||
707 | // Do nothing | |||
708 | } else if (Init < NumInits) { | |||
709 | ILE->setInit(Init, MemberInit.getAs<Expr>()); | |||
710 | } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) { | |||
711 | // Empty initialization requires a constructor call, so | |||
712 | // extend the initializer list to include the constructor | |||
713 | // call and make a note that we'll need to take another pass | |||
714 | // through the initializer list. | |||
715 | ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>()); | |||
716 | RequiresSecondPass = true; | |||
717 | } | |||
718 | } else if (InitListExpr *InnerILE | |||
719 | = dyn_cast<InitListExpr>(ILE->getInit(Init))) { | |||
720 | FillInEmptyInitializations(MemberEntity, InnerILE, | |||
721 | RequiresSecondPass, ILE, Init, FillWithNoInit); | |||
722 | } else if (DesignatedInitUpdateExpr *InnerDIUE = | |||
723 | dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) { | |||
724 | FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(), | |||
725 | RequiresSecondPass, ILE, Init, | |||
726 | /*FillWithNoInit =*/true); | |||
727 | } | |||
728 | } | |||
729 | ||||
730 | /// Recursively replaces NULL values within the given initializer list | |||
731 | /// with expressions that perform value-initialization of the | |||
732 | /// appropriate type, and finish off the InitListExpr formation. | |||
733 | void | |||
734 | InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity, | |||
735 | InitListExpr *ILE, | |||
736 | bool &RequiresSecondPass, | |||
737 | InitListExpr *OuterILE, | |||
738 | unsigned OuterIndex, | |||
739 | bool FillWithNoInit) { | |||
740 | assert((ILE->getType() != SemaRef.Context.VoidTy) &&(((ILE->getType() != SemaRef.Context.VoidTy) && "Should not have void type" ) ? static_cast<void> (0) : __assert_fail ("(ILE->getType() != SemaRef.Context.VoidTy) && \"Should not have void type\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 741, __PRETTY_FUNCTION__)) | |||
741 | "Should not have void type")(((ILE->getType() != SemaRef.Context.VoidTy) && "Should not have void type" ) ? static_cast<void> (0) : __assert_fail ("(ILE->getType() != SemaRef.Context.VoidTy) && \"Should not have void type\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 741, __PRETTY_FUNCTION__)); | |||
742 | ||||
743 | // We don't need to do any checks when just filling NoInitExprs; that can't | |||
744 | // fail. | |||
745 | if (FillWithNoInit && VerifyOnly) | |||
746 | return; | |||
747 | ||||
748 | // If this is a nested initializer list, we might have changed its contents | |||
749 | // (and therefore some of its properties, such as instantiation-dependence) | |||
750 | // while filling it in. Inform the outer initializer list so that its state | |||
751 | // can be updated to match. | |||
752 | // FIXME: We should fully build the inner initializers before constructing | |||
753 | // the outer InitListExpr instead of mutating AST nodes after they have | |||
754 | // been used as subexpressions of other nodes. | |||
755 | struct UpdateOuterILEWithUpdatedInit { | |||
756 | InitListExpr *Outer; | |||
757 | unsigned OuterIndex; | |||
758 | ~UpdateOuterILEWithUpdatedInit() { | |||
759 | if (Outer) | |||
760 | Outer->setInit(OuterIndex, Outer->getInit(OuterIndex)); | |||
761 | } | |||
762 | } UpdateOuterRAII = {OuterILE, OuterIndex}; | |||
763 | ||||
764 | // A transparent ILE is not performing aggregate initialization and should | |||
765 | // not be filled in. | |||
766 | if (ILE->isTransparent()) | |||
767 | return; | |||
768 | ||||
769 | if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) { | |||
770 | const RecordDecl *RDecl = RType->getDecl(); | |||
771 | if (RDecl->isUnion() && ILE->getInitializedFieldInUnion()) | |||
772 | FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(), | |||
773 | Entity, ILE, RequiresSecondPass, FillWithNoInit); | |||
774 | else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) && | |||
775 | cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) { | |||
776 | for (auto *Field : RDecl->fields()) { | |||
777 | if (Field->hasInClassInitializer()) { | |||
778 | FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass, | |||
779 | FillWithNoInit); | |||
780 | break; | |||
781 | } | |||
782 | } | |||
783 | } else { | |||
784 | // The fields beyond ILE->getNumInits() are default initialized, so in | |||
785 | // order to leave them uninitialized, the ILE is expanded and the extra | |||
786 | // fields are then filled with NoInitExpr. | |||
787 | unsigned NumElems = numStructUnionElements(ILE->getType()); | |||
788 | if (RDecl->hasFlexibleArrayMember()) | |||
789 | ++NumElems; | |||
790 | if (!VerifyOnly && ILE->getNumInits() < NumElems) | |||
791 | ILE->resizeInits(SemaRef.Context, NumElems); | |||
792 | ||||
793 | unsigned Init = 0; | |||
794 | ||||
795 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) { | |||
796 | for (auto &Base : CXXRD->bases()) { | |||
797 | if (hadError) | |||
798 | return; | |||
799 | ||||
800 | FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass, | |||
801 | FillWithNoInit); | |||
802 | ++Init; | |||
803 | } | |||
804 | } | |||
805 | ||||
806 | for (auto *Field : RDecl->fields()) { | |||
807 | if (Field->isUnnamedBitfield()) | |||
808 | continue; | |||
809 | ||||
810 | if (hadError) | |||
811 | return; | |||
812 | ||||
813 | FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass, | |||
814 | FillWithNoInit); | |||
815 | if (hadError) | |||
816 | return; | |||
817 | ||||
818 | ++Init; | |||
819 | ||||
820 | // Only look at the first initialization of a union. | |||
821 | if (RDecl->isUnion()) | |||
822 | break; | |||
823 | } | |||
824 | } | |||
825 | ||||
826 | return; | |||
827 | } | |||
828 | ||||
829 | QualType ElementType; | |||
830 | ||||
831 | InitializedEntity ElementEntity = Entity; | |||
832 | unsigned NumInits = ILE->getNumInits(); | |||
833 | unsigned NumElements = NumInits; | |||
834 | if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) { | |||
835 | ElementType = AType->getElementType(); | |||
836 | if (const auto *CAType = dyn_cast<ConstantArrayType>(AType)) | |||
837 | NumElements = CAType->getSize().getZExtValue(); | |||
838 | // For an array new with an unknown bound, ask for one additional element | |||
839 | // in order to populate the array filler. | |||
840 | if (Entity.isVariableLengthArrayNew()) | |||
841 | ++NumElements; | |||
842 | ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context, | |||
843 | 0, Entity); | |||
844 | } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) { | |||
845 | ElementType = VType->getElementType(); | |||
846 | NumElements = VType->getNumElements(); | |||
847 | ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context, | |||
848 | 0, Entity); | |||
849 | } else | |||
850 | ElementType = ILE->getType(); | |||
851 | ||||
852 | bool SkipEmptyInitChecks = false; | |||
853 | for (unsigned Init = 0; Init != NumElements; ++Init) { | |||
854 | if (hadError) | |||
855 | return; | |||
856 | ||||
857 | if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement || | |||
858 | ElementEntity.getKind() == InitializedEntity::EK_VectorElement) | |||
859 | ElementEntity.setElementIndex(Init); | |||
860 | ||||
861 | if (Init >= NumInits && (ILE->hasArrayFiller() || SkipEmptyInitChecks)) | |||
862 | return; | |||
863 | ||||
864 | Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr); | |||
865 | if (!InitExpr && Init < NumInits && ILE->hasArrayFiller()) | |||
866 | ILE->setInit(Init, ILE->getArrayFiller()); | |||
867 | else if (!InitExpr && !ILE->hasArrayFiller()) { | |||
868 | // In VerifyOnly mode, there's no point performing empty initialization | |||
869 | // more than once. | |||
870 | if (SkipEmptyInitChecks) | |||
871 | continue; | |||
872 | ||||
873 | Expr *Filler = nullptr; | |||
874 | ||||
875 | if (FillWithNoInit) | |||
876 | Filler = new (SemaRef.Context) NoInitExpr(ElementType); | |||
877 | else { | |||
878 | ExprResult ElementInit = | |||
879 | PerformEmptyInit(ILE->getEndLoc(), ElementEntity); | |||
880 | if (ElementInit.isInvalid()) { | |||
881 | hadError = true; | |||
882 | return; | |||
883 | } | |||
884 | ||||
885 | Filler = ElementInit.getAs<Expr>(); | |||
886 | } | |||
887 | ||||
888 | if (hadError) { | |||
889 | // Do nothing | |||
890 | } else if (VerifyOnly) { | |||
891 | SkipEmptyInitChecks = true; | |||
892 | } else if (Init < NumInits) { | |||
893 | // For arrays, just set the expression used for value-initialization | |||
894 | // of the "holes" in the array. | |||
895 | if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) | |||
896 | ILE->setArrayFiller(Filler); | |||
897 | else | |||
898 | ILE->setInit(Init, Filler); | |||
899 | } else { | |||
900 | // For arrays, just set the expression used for value-initialization | |||
901 | // of the rest of elements and exit. | |||
902 | if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) { | |||
903 | ILE->setArrayFiller(Filler); | |||
904 | return; | |||
905 | } | |||
906 | ||||
907 | if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) { | |||
908 | // Empty initialization requires a constructor call, so | |||
909 | // extend the initializer list to include the constructor | |||
910 | // call and make a note that we'll need to take another pass | |||
911 | // through the initializer list. | |||
912 | ILE->updateInit(SemaRef.Context, Init, Filler); | |||
913 | RequiresSecondPass = true; | |||
914 | } | |||
915 | } | |||
916 | } else if (InitListExpr *InnerILE | |||
917 | = dyn_cast_or_null<InitListExpr>(InitExpr)) { | |||
918 | FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass, | |||
919 | ILE, Init, FillWithNoInit); | |||
920 | } else if (DesignatedInitUpdateExpr *InnerDIUE = | |||
921 | dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr)) { | |||
922 | FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(), | |||
923 | RequiresSecondPass, ILE, Init, | |||
924 | /*FillWithNoInit =*/true); | |||
925 | } | |||
926 | } | |||
927 | } | |||
928 | ||||
929 | static bool hasAnyDesignatedInits(const InitListExpr *IL) { | |||
930 | for (const Stmt *Init : *IL) | |||
931 | if (Init && isa<DesignatedInitExpr>(Init)) | |||
932 | return true; | |||
933 | return false; | |||
934 | } | |||
935 | ||||
936 | InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity, | |||
937 | InitListExpr *IL, QualType &T, bool VerifyOnly, | |||
938 | bool TreatUnavailableAsInvalid, | |||
939 | bool InOverloadResolution) | |||
940 | : SemaRef(S), VerifyOnly(VerifyOnly), | |||
941 | TreatUnavailableAsInvalid(TreatUnavailableAsInvalid), | |||
942 | InOverloadResolution(InOverloadResolution) { | |||
943 | if (!VerifyOnly || hasAnyDesignatedInits(IL)) { | |||
944 | FullyStructuredList = | |||
945 | createInitListExpr(T, IL->getSourceRange(), IL->getNumInits()); | |||
946 | ||||
947 | // FIXME: Check that IL isn't already the semantic form of some other | |||
948 | // InitListExpr. If it is, we'd create a broken AST. | |||
949 | if (!VerifyOnly) | |||
950 | FullyStructuredList->setSyntacticForm(IL); | |||
951 | } | |||
952 | ||||
953 | CheckExplicitInitList(Entity, IL, T, FullyStructuredList, | |||
954 | /*TopLevelObject=*/true); | |||
955 | ||||
956 | if (!hadError && FullyStructuredList) { | |||
957 | bool RequiresSecondPass = false; | |||
958 | FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass, | |||
959 | /*OuterILE=*/nullptr, /*OuterIndex=*/0); | |||
960 | if (RequiresSecondPass && !hadError) | |||
961 | FillInEmptyInitializations(Entity, FullyStructuredList, | |||
962 | RequiresSecondPass, nullptr, 0); | |||
963 | } | |||
964 | } | |||
965 | ||||
966 | int InitListChecker::numArrayElements(QualType DeclType) { | |||
967 | // FIXME: use a proper constant | |||
968 | int maxElements = 0x7FFFFFFF; | |||
969 | if (const ConstantArrayType *CAT = | |||
970 | SemaRef.Context.getAsConstantArrayType(DeclType)) { | |||
971 | maxElements = static_cast<int>(CAT->getSize().getZExtValue()); | |||
972 | } | |||
973 | return maxElements; | |||
974 | } | |||
975 | ||||
976 | int InitListChecker::numStructUnionElements(QualType DeclType) { | |||
977 | RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl(); | |||
978 | int InitializableMembers = 0; | |||
979 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl)) | |||
980 | InitializableMembers += CXXRD->getNumBases(); | |||
981 | for (const auto *Field : structDecl->fields()) | |||
982 | if (!Field->isUnnamedBitfield()) | |||
983 | ++InitializableMembers; | |||
984 | ||||
985 | if (structDecl->isUnion()) | |||
986 | return std::min(InitializableMembers, 1); | |||
987 | return InitializableMembers - structDecl->hasFlexibleArrayMember(); | |||
988 | } | |||
989 | ||||
990 | /// Determine whether Entity is an entity for which it is idiomatic to elide | |||
991 | /// the braces in aggregate initialization. | |||
992 | static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) { | |||
993 | // Recursive initialization of the one and only field within an aggregate | |||
994 | // class is considered idiomatic. This case arises in particular for | |||
995 | // initialization of std::array, where the C++ standard suggests the idiom of | |||
996 | // | |||
997 | // std::array<T, N> arr = {1, 2, 3}; | |||
998 | // | |||
999 | // (where std::array is an aggregate struct containing a single array field. | |||
1000 | ||||
1001 | // FIXME: Should aggregate initialization of a struct with a single | |||
1002 | // base class and no members also suppress the warning? | |||
1003 | if (Entity.getKind() != InitializedEntity::EK_Member || !Entity.getParent()) | |||
1004 | return false; | |||
1005 | ||||
1006 | auto *ParentRD = | |||
1007 | Entity.getParent()->getType()->castAs<RecordType>()->getDecl(); | |||
1008 | if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD)) | |||
1009 | if (CXXRD->getNumBases()) | |||
1010 | return false; | |||
1011 | ||||
1012 | auto FieldIt = ParentRD->field_begin(); | |||
1013 | assert(FieldIt != ParentRD->field_end() &&((FieldIt != ParentRD->field_end() && "no fields but have initializer for member?" ) ? static_cast<void> (0) : __assert_fail ("FieldIt != ParentRD->field_end() && \"no fields but have initializer for member?\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 1014, __PRETTY_FUNCTION__)) | |||
1014 | "no fields but have initializer for member?")((FieldIt != ParentRD->field_end() && "no fields but have initializer for member?" ) ? static_cast<void> (0) : __assert_fail ("FieldIt != ParentRD->field_end() && \"no fields but have initializer for member?\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 1014, __PRETTY_FUNCTION__)); | |||
1015 | return ++FieldIt == ParentRD->field_end(); | |||
1016 | } | |||
1017 | ||||
1018 | /// Check whether the range of the initializer \p ParentIList from element | |||
1019 | /// \p Index onwards can be used to initialize an object of type \p T. Update | |||
1020 | /// \p Index to indicate how many elements of the list were consumed. | |||
1021 | /// | |||
1022 | /// This also fills in \p StructuredList, from element \p StructuredIndex | |||
1023 | /// onwards, with the fully-braced, desugared form of the initialization. | |||
1024 | void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity, | |||
1025 | InitListExpr *ParentIList, | |||
1026 | QualType T, unsigned &Index, | |||
1027 | InitListExpr *StructuredList, | |||
1028 | unsigned &StructuredIndex) { | |||
1029 | int maxElements = 0; | |||
1030 | ||||
1031 | if (T->isArrayType()) | |||
1032 | maxElements = numArrayElements(T); | |||
1033 | else if (T->isRecordType()) | |||
1034 | maxElements = numStructUnionElements(T); | |||
1035 | else if (T->isVectorType()) | |||
1036 | maxElements = T->castAs<VectorType>()->getNumElements(); | |||
1037 | else | |||
1038 | llvm_unreachable("CheckImplicitInitList(): Illegal type")::llvm::llvm_unreachable_internal("CheckImplicitInitList(): Illegal type" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 1038); | |||
1039 | ||||
1040 | if (maxElements == 0) { | |||
1041 | if (!VerifyOnly) | |||
1042 | SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(), | |||
1043 | diag::err_implicit_empty_initializer); | |||
1044 | ++Index; | |||
1045 | hadError = true; | |||
1046 | return; | |||
1047 | } | |||
1048 | ||||
1049 | // Build a structured initializer list corresponding to this subobject. | |||
1050 | InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit( | |||
1051 | ParentIList, Index, T, StructuredList, StructuredIndex, | |||
1052 | SourceRange(ParentIList->getInit(Index)->getBeginLoc(), | |||
1053 | ParentIList->getSourceRange().getEnd())); | |||
1054 | unsigned StructuredSubobjectInitIndex = 0; | |||
1055 | ||||
1056 | // Check the element types and build the structural subobject. | |||
1057 | unsigned StartIndex = Index; | |||
1058 | CheckListElementTypes(Entity, ParentIList, T, | |||
1059 | /*SubobjectIsDesignatorContext=*/false, Index, | |||
1060 | StructuredSubobjectInitList, | |||
1061 | StructuredSubobjectInitIndex); | |||
1062 | ||||
1063 | if (StructuredSubobjectInitList) { | |||
1064 | StructuredSubobjectInitList->setType(T); | |||
1065 | ||||
1066 | unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1); | |||
1067 | // Update the structured sub-object initializer so that it's ending | |||
1068 | // range corresponds with the end of the last initializer it used. | |||
1069 | if (EndIndex < ParentIList->getNumInits() && | |||
1070 | ParentIList->getInit(EndIndex)) { | |||
1071 | SourceLocation EndLoc | |||
1072 | = ParentIList->getInit(EndIndex)->getSourceRange().getEnd(); | |||
1073 | StructuredSubobjectInitList->setRBraceLoc(EndLoc); | |||
1074 | } | |||
1075 | ||||
1076 | // Complain about missing braces. | |||
1077 | if (!VerifyOnly && (T->isArrayType() || T->isRecordType()) && | |||
1078 | !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) && | |||
1079 | !isIdiomaticBraceElisionEntity(Entity)) { | |||
1080 | SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(), | |||
1081 | diag::warn_missing_braces) | |||
1082 | << StructuredSubobjectInitList->getSourceRange() | |||
1083 | << FixItHint::CreateInsertion( | |||
1084 | StructuredSubobjectInitList->getBeginLoc(), "{") | |||
1085 | << FixItHint::CreateInsertion( | |||
1086 | SemaRef.getLocForEndOfToken( | |||
1087 | StructuredSubobjectInitList->getEndLoc()), | |||
1088 | "}"); | |||
1089 | } | |||
1090 | ||||
1091 | // Warn if this type won't be an aggregate in future versions of C++. | |||
1092 | auto *CXXRD = T->getAsCXXRecordDecl(); | |||
1093 | if (!VerifyOnly && CXXRD && CXXRD->hasUserDeclaredConstructor()) { | |||
1094 | SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(), | |||
1095 | diag::warn_cxx2a_compat_aggregate_init_with_ctors) | |||
1096 | << StructuredSubobjectInitList->getSourceRange() << T; | |||
1097 | } | |||
1098 | } | |||
1099 | } | |||
1100 | ||||
1101 | /// Warn that \p Entity was of scalar type and was initialized by a | |||
1102 | /// single-element braced initializer list. | |||
1103 | static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity, | |||
1104 | SourceRange Braces) { | |||
1105 | // Don't warn during template instantiation. If the initialization was | |||
1106 | // non-dependent, we warned during the initial parse; otherwise, the | |||
1107 | // type might not be scalar in some uses of the template. | |||
1108 | if (S.inTemplateInstantiation()) | |||
1109 | return; | |||
1110 | ||||
1111 | unsigned DiagID = 0; | |||
1112 | ||||
1113 | switch (Entity.getKind()) { | |||
1114 | case InitializedEntity::EK_VectorElement: | |||
1115 | case InitializedEntity::EK_ComplexElement: | |||
1116 | case InitializedEntity::EK_ArrayElement: | |||
1117 | case InitializedEntity::EK_Parameter: | |||
1118 | case InitializedEntity::EK_Parameter_CF_Audited: | |||
1119 | case InitializedEntity::EK_Result: | |||
1120 | // Extra braces here are suspicious. | |||
1121 | DiagID = diag::warn_braces_around_scalar_init; | |||
1122 | break; | |||
1123 | ||||
1124 | case InitializedEntity::EK_Member: | |||
1125 | // Warn on aggregate initialization but not on ctor init list or | |||
1126 | // default member initializer. | |||
1127 | if (Entity.getParent()) | |||
1128 | DiagID = diag::warn_braces_around_scalar_init; | |||
1129 | break; | |||
1130 | ||||
1131 | case InitializedEntity::EK_Variable: | |||
1132 | case InitializedEntity::EK_LambdaCapture: | |||
1133 | // No warning, might be direct-list-initialization. | |||
1134 | // FIXME: Should we warn for copy-list-initialization in these cases? | |||
1135 | break; | |||
1136 | ||||
1137 | case InitializedEntity::EK_New: | |||
1138 | case InitializedEntity::EK_Temporary: | |||
1139 | case InitializedEntity::EK_CompoundLiteralInit: | |||
1140 | // No warning, braces are part of the syntax of the underlying construct. | |||
1141 | break; | |||
1142 | ||||
1143 | case InitializedEntity::EK_RelatedResult: | |||
1144 | // No warning, we already warned when initializing the result. | |||
1145 | break; | |||
1146 | ||||
1147 | case InitializedEntity::EK_Exception: | |||
1148 | case InitializedEntity::EK_Base: | |||
1149 | case InitializedEntity::EK_Delegating: | |||
1150 | case InitializedEntity::EK_BlockElement: | |||
1151 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: | |||
1152 | case InitializedEntity::EK_Binding: | |||
1153 | case InitializedEntity::EK_StmtExprResult: | |||
1154 | llvm_unreachable("unexpected braced scalar init")::llvm::llvm_unreachable_internal("unexpected braced scalar init" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 1154); | |||
1155 | } | |||
1156 | ||||
1157 | if (DiagID) { | |||
1158 | S.Diag(Braces.getBegin(), DiagID) | |||
1159 | << Braces | |||
1160 | << FixItHint::CreateRemoval(Braces.getBegin()) | |||
1161 | << FixItHint::CreateRemoval(Braces.getEnd()); | |||
1162 | } | |||
1163 | } | |||
1164 | ||||
1165 | /// Check whether the initializer \p IList (that was written with explicit | |||
1166 | /// braces) can be used to initialize an object of type \p T. | |||
1167 | /// | |||
1168 | /// This also fills in \p StructuredList with the fully-braced, desugared | |||
1169 | /// form of the initialization. | |||
1170 | void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity, | |||
1171 | InitListExpr *IList, QualType &T, | |||
1172 | InitListExpr *StructuredList, | |||
1173 | bool TopLevelObject) { | |||
1174 | unsigned Index = 0, StructuredIndex = 0; | |||
1175 | CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true, | |||
1176 | Index, StructuredList, StructuredIndex, TopLevelObject); | |||
1177 | if (StructuredList) { | |||
1178 | QualType ExprTy = T; | |||
1179 | if (!ExprTy->isArrayType()) | |||
1180 | ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context); | |||
1181 | if (!VerifyOnly) | |||
1182 | IList->setType(ExprTy); | |||
1183 | StructuredList->setType(ExprTy); | |||
1184 | } | |||
1185 | if (hadError) | |||
1186 | return; | |||
1187 | ||||
1188 | // Don't complain for incomplete types, since we'll get an error elsewhere. | |||
1189 | if (Index < IList->getNumInits() && !T->isIncompleteType()) { | |||
1190 | // We have leftover initializers | |||
1191 | bool ExtraInitsIsError = SemaRef.getLangOpts().CPlusPlus || | |||
1192 | (SemaRef.getLangOpts().OpenCL && T->isVectorType()); | |||
1193 | hadError = ExtraInitsIsError; | |||
1194 | if (VerifyOnly) { | |||
1195 | return; | |||
1196 | } else if (StructuredIndex == 1 && | |||
1197 | IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) == | |||
1198 | SIF_None) { | |||
1199 | unsigned DK = | |||
1200 | ExtraInitsIsError | |||
1201 | ? diag::err_excess_initializers_in_char_array_initializer | |||
1202 | : diag::ext_excess_initializers_in_char_array_initializer; | |||
1203 | SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK) | |||
1204 | << IList->getInit(Index)->getSourceRange(); | |||
1205 | } else { | |||
1206 | int initKind = T->isArrayType() ? 0 : | |||
1207 | T->isVectorType() ? 1 : | |||
1208 | T->isScalarType() ? 2 : | |||
1209 | T->isUnionType() ? 3 : | |||
1210 | 4; | |||
1211 | ||||
1212 | unsigned DK = ExtraInitsIsError ? diag::err_excess_initializers | |||
1213 | : diag::ext_excess_initializers; | |||
1214 | SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK) | |||
1215 | << initKind << IList->getInit(Index)->getSourceRange(); | |||
1216 | } | |||
1217 | } | |||
1218 | ||||
1219 | if (!VerifyOnly) { | |||
1220 | if (T->isScalarType() && IList->getNumInits() == 1 && | |||
1221 | !isa<InitListExpr>(IList->getInit(0))) | |||
1222 | warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange()); | |||
1223 | ||||
1224 | // Warn if this is a class type that won't be an aggregate in future | |||
1225 | // versions of C++. | |||
1226 | auto *CXXRD = T->getAsCXXRecordDecl(); | |||
1227 | if (CXXRD && CXXRD->hasUserDeclaredConstructor()) { | |||
1228 | // Don't warn if there's an equivalent default constructor that would be | |||
1229 | // used instead. | |||
1230 | bool HasEquivCtor = false; | |||
1231 | if (IList->getNumInits() == 0) { | |||
1232 | auto *CD = SemaRef.LookupDefaultConstructor(CXXRD); | |||
1233 | HasEquivCtor = CD && !CD->isDeleted(); | |||
1234 | } | |||
1235 | ||||
1236 | if (!HasEquivCtor) { | |||
1237 | SemaRef.Diag(IList->getBeginLoc(), | |||
1238 | diag::warn_cxx2a_compat_aggregate_init_with_ctors) | |||
1239 | << IList->getSourceRange() << T; | |||
1240 | } | |||
1241 | } | |||
1242 | } | |||
1243 | } | |||
1244 | ||||
1245 | void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity, | |||
1246 | InitListExpr *IList, | |||
1247 | QualType &DeclType, | |||
1248 | bool SubobjectIsDesignatorContext, | |||
1249 | unsigned &Index, | |||
1250 | InitListExpr *StructuredList, | |||
1251 | unsigned &StructuredIndex, | |||
1252 | bool TopLevelObject) { | |||
1253 | if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) { | |||
1254 | // Explicitly braced initializer for complex type can be real+imaginary | |||
1255 | // parts. | |||
1256 | CheckComplexType(Entity, IList, DeclType, Index, | |||
1257 | StructuredList, StructuredIndex); | |||
1258 | } else if (DeclType->isScalarType()) { | |||
1259 | CheckScalarType(Entity, IList, DeclType, Index, | |||
1260 | StructuredList, StructuredIndex); | |||
1261 | } else if (DeclType->isVectorType()) { | |||
1262 | CheckVectorType(Entity, IList, DeclType, Index, | |||
1263 | StructuredList, StructuredIndex); | |||
1264 | } else if (DeclType->isRecordType()) { | |||
1265 | assert(DeclType->isAggregateType() &&((DeclType->isAggregateType() && "non-aggregate records should be handed in CheckSubElementType" ) ? static_cast<void> (0) : __assert_fail ("DeclType->isAggregateType() && \"non-aggregate records should be handed in CheckSubElementType\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 1266, __PRETTY_FUNCTION__)) | |||
1266 | "non-aggregate records should be handed in CheckSubElementType")((DeclType->isAggregateType() && "non-aggregate records should be handed in CheckSubElementType" ) ? static_cast<void> (0) : __assert_fail ("DeclType->isAggregateType() && \"non-aggregate records should be handed in CheckSubElementType\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 1266, __PRETTY_FUNCTION__)); | |||
1267 | RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl(); | |||
1268 | auto Bases = | |||
1269 | CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(), | |||
1270 | CXXRecordDecl::base_class_iterator()); | |||
1271 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) | |||
1272 | Bases = CXXRD->bases(); | |||
1273 | CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(), | |||
1274 | SubobjectIsDesignatorContext, Index, StructuredList, | |||
1275 | StructuredIndex, TopLevelObject); | |||
1276 | } else if (DeclType->isArrayType()) { | |||
1277 | llvm::APSInt Zero( | |||
1278 | SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()), | |||
1279 | false); | |||
1280 | CheckArrayType(Entity, IList, DeclType, Zero, | |||
1281 | SubobjectIsDesignatorContext, Index, | |||
1282 | StructuredList, StructuredIndex); | |||
1283 | } else if (DeclType->isVoidType() || DeclType->isFunctionType()) { | |||
1284 | // This type is invalid, issue a diagnostic. | |||
1285 | ++Index; | |||
1286 | if (!VerifyOnly) | |||
1287 | SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type) | |||
1288 | << DeclType; | |||
1289 | hadError = true; | |||
1290 | } else if (DeclType->isReferenceType()) { | |||
1291 | CheckReferenceType(Entity, IList, DeclType, Index, | |||
1292 | StructuredList, StructuredIndex); | |||
1293 | } else if (DeclType->isObjCObjectType()) { | |||
1294 | if (!VerifyOnly) | |||
1295 | SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType; | |||
1296 | hadError = true; | |||
1297 | } else if (DeclType->isOCLIntelSubgroupAVCType()) { | |||
1298 | // Checks for scalar type are sufficient for these types too. | |||
1299 | CheckScalarType(Entity, IList, DeclType, Index, StructuredList, | |||
1300 | StructuredIndex); | |||
1301 | } else { | |||
1302 | if (!VerifyOnly) | |||
1303 | SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type) | |||
1304 | << DeclType; | |||
1305 | hadError = true; | |||
1306 | } | |||
1307 | } | |||
1308 | ||||
1309 | void InitListChecker::CheckSubElementType(const InitializedEntity &Entity, | |||
1310 | InitListExpr *IList, | |||
1311 | QualType ElemType, | |||
1312 | unsigned &Index, | |||
1313 | InitListExpr *StructuredList, | |||
1314 | unsigned &StructuredIndex) { | |||
1315 | Expr *expr = IList->getInit(Index); | |||
1316 | ||||
1317 | if (ElemType->isReferenceType()) | |||
1318 | return CheckReferenceType(Entity, IList, ElemType, Index, | |||
1319 | StructuredList, StructuredIndex); | |||
1320 | ||||
1321 | if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) { | |||
1322 | if (SubInitList->getNumInits() == 1 && | |||
1323 | IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) == | |||
1324 | SIF_None) { | |||
1325 | // FIXME: It would be more faithful and no less correct to include an | |||
1326 | // InitListExpr in the semantic form of the initializer list in this case. | |||
1327 | expr = SubInitList->getInit(0); | |||
1328 | } | |||
1329 | // Nested aggregate initialization and C++ initialization are handled later. | |||
1330 | } else if (isa<ImplicitValueInitExpr>(expr)) { | |||
1331 | // This happens during template instantiation when we see an InitListExpr | |||
1332 | // that we've already checked once. | |||
1333 | assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&((SemaRef.Context.hasSameType(expr->getType(), ElemType) && "found implicit initialization for the wrong type") ? static_cast <void> (0) : __assert_fail ("SemaRef.Context.hasSameType(expr->getType(), ElemType) && \"found implicit initialization for the wrong type\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 1334, __PRETTY_FUNCTION__)) | |||
1334 | "found implicit initialization for the wrong type")((SemaRef.Context.hasSameType(expr->getType(), ElemType) && "found implicit initialization for the wrong type") ? static_cast <void> (0) : __assert_fail ("SemaRef.Context.hasSameType(expr->getType(), ElemType) && \"found implicit initialization for the wrong type\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 1334, __PRETTY_FUNCTION__)); | |||
1335 | UpdateStructuredListElement(StructuredList, StructuredIndex, expr); | |||
1336 | ++Index; | |||
1337 | return; | |||
1338 | } | |||
1339 | ||||
1340 | if (SemaRef.getLangOpts().CPlusPlus || isa<InitListExpr>(expr)) { | |||
1341 | // C++ [dcl.init.aggr]p2: | |||
1342 | // Each member is copy-initialized from the corresponding | |||
1343 | // initializer-clause. | |||
1344 | ||||
1345 | // FIXME: Better EqualLoc? | |||
1346 | InitializationKind Kind = | |||
1347 | InitializationKind::CreateCopy(expr->getBeginLoc(), SourceLocation()); | |||
1348 | ||||
1349 | // Vector elements can be initialized from other vectors in which case | |||
1350 | // we need initialization entity with a type of a vector (and not a vector | |||
1351 | // element!) initializing multiple vector elements. | |||
1352 | auto TmpEntity = | |||
1353 | (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType()) | |||
1354 | ? InitializedEntity::InitializeTemporary(ElemType) | |||
1355 | : Entity; | |||
1356 | ||||
1357 | InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr, | |||
1358 | /*TopLevelOfInitList*/ true); | |||
1359 | ||||
1360 | // C++14 [dcl.init.aggr]p13: | |||
1361 | // If the assignment-expression can initialize a member, the member is | |||
1362 | // initialized. Otherwise [...] brace elision is assumed | |||
1363 | // | |||
1364 | // Brace elision is never performed if the element is not an | |||
1365 | // assignment-expression. | |||
1366 | if (Seq || isa<InitListExpr>(expr)) { | |||
1367 | if (!VerifyOnly) { | |||
1368 | ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr); | |||
1369 | if (Result.isInvalid()) | |||
1370 | hadError = true; | |||
1371 | ||||
1372 | UpdateStructuredListElement(StructuredList, StructuredIndex, | |||
1373 | Result.getAs<Expr>()); | |||
1374 | } else if (!Seq) { | |||
1375 | hadError = true; | |||
1376 | } else if (StructuredList) { | |||
1377 | UpdateStructuredListElement(StructuredList, StructuredIndex, | |||
1378 | getDummyInit()); | |||
1379 | } | |||
1380 | ++Index; | |||
1381 | return; | |||
1382 | } | |||
1383 | ||||
1384 | // Fall through for subaggregate initialization | |||
1385 | } else if (ElemType->isScalarType() || ElemType->isAtomicType()) { | |||
1386 | // FIXME: Need to handle atomic aggregate types with implicit init lists. | |||
1387 | return CheckScalarType(Entity, IList, ElemType, Index, | |||
1388 | StructuredList, StructuredIndex); | |||
1389 | } else if (const ArrayType *arrayType = | |||
1390 | SemaRef.Context.getAsArrayType(ElemType)) { | |||
1391 | // arrayType can be incomplete if we're initializing a flexible | |||
1392 | // array member. There's nothing we can do with the completed | |||
1393 | // type here, though. | |||
1394 | ||||
1395 | if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) { | |||
1396 | // FIXME: Should we do this checking in verify-only mode? | |||
1397 | if (!VerifyOnly) | |||
1398 | CheckStringInit(expr, ElemType, arrayType, SemaRef); | |||
1399 | if (StructuredList) | |||
1400 | UpdateStructuredListElement(StructuredList, StructuredIndex, expr); | |||
1401 | ++Index; | |||
1402 | return; | |||
1403 | } | |||
1404 | ||||
1405 | // Fall through for subaggregate initialization. | |||
1406 | ||||
1407 | } else { | |||
1408 | assert((ElemType->isRecordType() || ElemType->isVectorType() ||(((ElemType->isRecordType() || ElemType->isVectorType() || ElemType->isOpenCLSpecificType()) && "Unexpected type" ) ? static_cast<void> (0) : __assert_fail ("(ElemType->isRecordType() || ElemType->isVectorType() || ElemType->isOpenCLSpecificType()) && \"Unexpected type\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 1409, __PRETTY_FUNCTION__)) | |||
1409 | ElemType->isOpenCLSpecificType()) && "Unexpected type")(((ElemType->isRecordType() || ElemType->isVectorType() || ElemType->isOpenCLSpecificType()) && "Unexpected type" ) ? static_cast<void> (0) : __assert_fail ("(ElemType->isRecordType() || ElemType->isVectorType() || ElemType->isOpenCLSpecificType()) && \"Unexpected type\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 1409, __PRETTY_FUNCTION__)); | |||
1410 | ||||
1411 | // C99 6.7.8p13: | |||
1412 | // | |||
1413 | // The initializer for a structure or union object that has | |||
1414 | // automatic storage duration shall be either an initializer | |||
1415 | // list as described below, or a single expression that has | |||
1416 | // compatible structure or union type. In the latter case, the | |||
1417 | // initial value of the object, including unnamed members, is | |||
1418 | // that of the expression. | |||
1419 | ExprResult ExprRes = expr; | |||
1420 | if (SemaRef.CheckSingleAssignmentConstraints( | |||
1421 | ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) { | |||
1422 | if (ExprRes.isInvalid()) | |||
1423 | hadError = true; | |||
1424 | else { | |||
1425 | ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get()); | |||
1426 | if (ExprRes.isInvalid()) | |||
1427 | hadError = true; | |||
1428 | } | |||
1429 | UpdateStructuredListElement(StructuredList, StructuredIndex, | |||
1430 | ExprRes.getAs<Expr>()); | |||
1431 | ++Index; | |||
1432 | return; | |||
1433 | } | |||
1434 | ExprRes.get(); | |||
1435 | // Fall through for subaggregate initialization | |||
1436 | } | |||
1437 | ||||
1438 | // C++ [dcl.init.aggr]p12: | |||
1439 | // | |||
1440 | // [...] Otherwise, if the member is itself a non-empty | |||
1441 | // subaggregate, brace elision is assumed and the initializer is | |||
1442 | // considered for the initialization of the first member of | |||
1443 | // the subaggregate. | |||
1444 | // OpenCL vector initializer is handled elsewhere. | |||
1445 | if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) || | |||
1446 | ElemType->isAggregateType()) { | |||
1447 | CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList, | |||
1448 | StructuredIndex); | |||
1449 | ++StructuredIndex; | |||
1450 | } else { | |||
1451 | if (!VerifyOnly) { | |||
1452 | // We cannot initialize this element, so let PerformCopyInitialization | |||
1453 | // produce the appropriate diagnostic. We already checked that this | |||
1454 | // initialization will fail. | |||
1455 | ExprResult Copy = | |||
1456 | SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr, | |||
1457 | /*TopLevelOfInitList=*/true); | |||
1458 | (void)Copy; | |||
1459 | assert(Copy.isInvalid() &&((Copy.isInvalid() && "expected non-aggregate initialization to fail" ) ? static_cast<void> (0) : __assert_fail ("Copy.isInvalid() && \"expected non-aggregate initialization to fail\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 1460, __PRETTY_FUNCTION__)) | |||
1460 | "expected non-aggregate initialization to fail")((Copy.isInvalid() && "expected non-aggregate initialization to fail" ) ? static_cast<void> (0) : __assert_fail ("Copy.isInvalid() && \"expected non-aggregate initialization to fail\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 1460, __PRETTY_FUNCTION__)); | |||
1461 | } | |||
1462 | hadError = true; | |||
1463 | ++Index; | |||
1464 | ++StructuredIndex; | |||
1465 | } | |||
1466 | } | |||
1467 | ||||
1468 | void InitListChecker::CheckComplexType(const InitializedEntity &Entity, | |||
1469 | InitListExpr *IList, QualType DeclType, | |||
1470 | unsigned &Index, | |||
1471 | InitListExpr *StructuredList, | |||
1472 | unsigned &StructuredIndex) { | |||
1473 | assert(Index == 0 && "Index in explicit init list must be zero")((Index == 0 && "Index in explicit init list must be zero" ) ? static_cast<void> (0) : __assert_fail ("Index == 0 && \"Index in explicit init list must be zero\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 1473, __PRETTY_FUNCTION__)); | |||
1474 | ||||
1475 | // As an extension, clang supports complex initializers, which initialize | |||
1476 | // a complex number component-wise. When an explicit initializer list for | |||
1477 | // a complex number contains two two initializers, this extension kicks in: | |||
1478 | // it exepcts the initializer list to contain two elements convertible to | |||
1479 | // the element type of the complex type. The first element initializes | |||
1480 | // the real part, and the second element intitializes the imaginary part. | |||
1481 | ||||
1482 | if (IList->getNumInits() != 2) | |||
1483 | return CheckScalarType(Entity, IList, DeclType, Index, StructuredList, | |||
1484 | StructuredIndex); | |||
1485 | ||||
1486 | // This is an extension in C. (The builtin _Complex type does not exist | |||
1487 | // in the C++ standard.) | |||
1488 | if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly) | |||
1489 | SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init) | |||
1490 | << IList->getSourceRange(); | |||
1491 | ||||
1492 | // Initialize the complex number. | |||
1493 | QualType elementType = DeclType->castAs<ComplexType>()->getElementType(); | |||
1494 | InitializedEntity ElementEntity = | |||
1495 | InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); | |||
1496 | ||||
1497 | for (unsigned i = 0; i < 2; ++i) { | |||
1498 | ElementEntity.setElementIndex(Index); | |||
1499 | CheckSubElementType(ElementEntity, IList, elementType, Index, | |||
1500 | StructuredList, StructuredIndex); | |||
1501 | } | |||
1502 | } | |||
1503 | ||||
1504 | void InitListChecker::CheckScalarType(const InitializedEntity &Entity, | |||
1505 | InitListExpr *IList, QualType DeclType, | |||
1506 | unsigned &Index, | |||
1507 | InitListExpr *StructuredList, | |||
1508 | unsigned &StructuredIndex) { | |||
1509 | if (Index >= IList->getNumInits()) { | |||
1510 | if (!VerifyOnly) | |||
1511 | SemaRef.Diag(IList->getBeginLoc(), | |||
1512 | SemaRef.getLangOpts().CPlusPlus11 | |||
1513 | ? diag::warn_cxx98_compat_empty_scalar_initializer | |||
1514 | : diag::err_empty_scalar_initializer) | |||
1515 | << IList->getSourceRange(); | |||
1516 | hadError = !SemaRef.getLangOpts().CPlusPlus11; | |||
1517 | ++Index; | |||
1518 | ++StructuredIndex; | |||
1519 | return; | |||
1520 | } | |||
1521 | ||||
1522 | Expr *expr = IList->getInit(Index); | |||
1523 | if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) { | |||
1524 | // FIXME: This is invalid, and accepting it causes overload resolution | |||
1525 | // to pick the wrong overload in some corner cases. | |||
1526 | if (!VerifyOnly) | |||
1527 | SemaRef.Diag(SubIList->getBeginLoc(), | |||
1528 | diag::ext_many_braces_around_scalar_init) | |||
1529 | << SubIList->getSourceRange(); | |||
1530 | ||||
1531 | CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList, | |||
1532 | StructuredIndex); | |||
1533 | return; | |||
1534 | } else if (isa<DesignatedInitExpr>(expr)) { | |||
1535 | if (!VerifyOnly) | |||
1536 | SemaRef.Diag(expr->getBeginLoc(), diag::err_designator_for_scalar_init) | |||
1537 | << DeclType << expr->getSourceRange(); | |||
1538 | hadError = true; | |||
1539 | ++Index; | |||
1540 | ++StructuredIndex; | |||
1541 | return; | |||
1542 | } | |||
1543 | ||||
1544 | ExprResult Result; | |||
1545 | if (VerifyOnly) { | |||
1546 | if (SemaRef.CanPerformCopyInitialization(Entity, expr)) | |||
1547 | Result = getDummyInit(); | |||
1548 | else | |||
1549 | Result = ExprError(); | |||
1550 | } else { | |||
1551 | Result = | |||
1552 | SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr, | |||
1553 | /*TopLevelOfInitList=*/true); | |||
1554 | } | |||
1555 | ||||
1556 | Expr *ResultExpr = nullptr; | |||
1557 | ||||
1558 | if (Result.isInvalid()) | |||
1559 | hadError = true; // types weren't compatible. | |||
1560 | else { | |||
1561 | ResultExpr = Result.getAs<Expr>(); | |||
1562 | ||||
1563 | if (ResultExpr != expr && !VerifyOnly) { | |||
1564 | // The type was promoted, update initializer list. | |||
1565 | // FIXME: Why are we updating the syntactic init list? | |||
1566 | IList->setInit(Index, ResultExpr); | |||
1567 | } | |||
1568 | } | |||
1569 | if (hadError) | |||
1570 | ++StructuredIndex; | |||
1571 | else | |||
1572 | UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr); | |||
1573 | ++Index; | |||
1574 | } | |||
1575 | ||||
1576 | void InitListChecker::CheckReferenceType(const InitializedEntity &Entity, | |||
1577 | InitListExpr *IList, QualType DeclType, | |||
1578 | unsigned &Index, | |||
1579 | InitListExpr *StructuredList, | |||
1580 | unsigned &StructuredIndex) { | |||
1581 | if (Index >= IList->getNumInits()) { | |||
1582 | // FIXME: It would be wonderful if we could point at the actual member. In | |||
1583 | // general, it would be useful to pass location information down the stack, | |||
1584 | // so that we know the location (or decl) of the "current object" being | |||
1585 | // initialized. | |||
1586 | if (!VerifyOnly) | |||
1587 | SemaRef.Diag(IList->getBeginLoc(), | |||
1588 | diag::err_init_reference_member_uninitialized) | |||
1589 | << DeclType << IList->getSourceRange(); | |||
1590 | hadError = true; | |||
1591 | ++Index; | |||
1592 | ++StructuredIndex; | |||
1593 | return; | |||
1594 | } | |||
1595 | ||||
1596 | Expr *expr = IList->getInit(Index); | |||
1597 | if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) { | |||
1598 | if (!VerifyOnly) | |||
1599 | SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list) | |||
1600 | << DeclType << IList->getSourceRange(); | |||
1601 | hadError = true; | |||
1602 | ++Index; | |||
1603 | ++StructuredIndex; | |||
1604 | return; | |||
1605 | } | |||
1606 | ||||
1607 | ExprResult Result; | |||
1608 | if (VerifyOnly) { | |||
1609 | if (SemaRef.CanPerformCopyInitialization(Entity,expr)) | |||
1610 | Result = getDummyInit(); | |||
1611 | else | |||
1612 | Result = ExprError(); | |||
1613 | } else { | |||
1614 | Result = | |||
1615 | SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr, | |||
1616 | /*TopLevelOfInitList=*/true); | |||
1617 | } | |||
1618 | ||||
1619 | if (Result.isInvalid()) | |||
1620 | hadError = true; | |||
1621 | ||||
1622 | expr = Result.getAs<Expr>(); | |||
1623 | // FIXME: Why are we updating the syntactic init list? | |||
1624 | if (!VerifyOnly) | |||
1625 | IList->setInit(Index, expr); | |||
1626 | ||||
1627 | if (hadError) | |||
1628 | ++StructuredIndex; | |||
1629 | else | |||
1630 | UpdateStructuredListElement(StructuredList, StructuredIndex, expr); | |||
1631 | ++Index; | |||
1632 | } | |||
1633 | ||||
1634 | void InitListChecker::CheckVectorType(const InitializedEntity &Entity, | |||
1635 | InitListExpr *IList, QualType DeclType, | |||
1636 | unsigned &Index, | |||
1637 | InitListExpr *StructuredList, | |||
1638 | unsigned &StructuredIndex) { | |||
1639 | const VectorType *VT = DeclType->castAs<VectorType>(); | |||
1640 | unsigned maxElements = VT->getNumElements(); | |||
1641 | unsigned numEltsInit = 0; | |||
1642 | QualType elementType = VT->getElementType(); | |||
1643 | ||||
1644 | if (Index >= IList->getNumInits()) { | |||
1645 | // Make sure the element type can be value-initialized. | |||
1646 | CheckEmptyInitializable( | |||
1647 | InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity), | |||
1648 | IList->getEndLoc()); | |||
1649 | return; | |||
1650 | } | |||
1651 | ||||
1652 | if (!SemaRef.getLangOpts().OpenCL) { | |||
1653 | // If the initializing element is a vector, try to copy-initialize | |||
1654 | // instead of breaking it apart (which is doomed to failure anyway). | |||
1655 | Expr *Init = IList->getInit(Index); | |||
1656 | if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) { | |||
1657 | ExprResult Result; | |||
1658 | if (VerifyOnly) { | |||
1659 | if (SemaRef.CanPerformCopyInitialization(Entity, Init)) | |||
1660 | Result = getDummyInit(); | |||
1661 | else | |||
1662 | Result = ExprError(); | |||
1663 | } else { | |||
1664 | Result = | |||
1665 | SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init, | |||
1666 | /*TopLevelOfInitList=*/true); | |||
1667 | } | |||
1668 | ||||
1669 | Expr *ResultExpr = nullptr; | |||
1670 | if (Result.isInvalid()) | |||
1671 | hadError = true; // types weren't compatible. | |||
1672 | else { | |||
1673 | ResultExpr = Result.getAs<Expr>(); | |||
1674 | ||||
1675 | if (ResultExpr != Init && !VerifyOnly) { | |||
1676 | // The type was promoted, update initializer list. | |||
1677 | // FIXME: Why are we updating the syntactic init list? | |||
1678 | IList->setInit(Index, ResultExpr); | |||
1679 | } | |||
1680 | } | |||
1681 | if (hadError) | |||
1682 | ++StructuredIndex; | |||
1683 | else | |||
1684 | UpdateStructuredListElement(StructuredList, StructuredIndex, | |||
1685 | ResultExpr); | |||
1686 | ++Index; | |||
1687 | return; | |||
1688 | } | |||
1689 | ||||
1690 | InitializedEntity ElementEntity = | |||
1691 | InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); | |||
1692 | ||||
1693 | for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) { | |||
1694 | // Don't attempt to go past the end of the init list | |||
1695 | if (Index >= IList->getNumInits()) { | |||
1696 | CheckEmptyInitializable(ElementEntity, IList->getEndLoc()); | |||
1697 | break; | |||
1698 | } | |||
1699 | ||||
1700 | ElementEntity.setElementIndex(Index); | |||
1701 | CheckSubElementType(ElementEntity, IList, elementType, Index, | |||
1702 | StructuredList, StructuredIndex); | |||
1703 | } | |||
1704 | ||||
1705 | if (VerifyOnly) | |||
1706 | return; | |||
1707 | ||||
1708 | bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian(); | |||
1709 | const VectorType *T = Entity.getType()->castAs<VectorType>(); | |||
1710 | if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector || | |||
1711 | T->getVectorKind() == VectorType::NeonPolyVector)) { | |||
1712 | // The ability to use vector initializer lists is a GNU vector extension | |||
1713 | // and is unrelated to the NEON intrinsics in arm_neon.h. On little | |||
1714 | // endian machines it works fine, however on big endian machines it | |||
1715 | // exhibits surprising behaviour: | |||
1716 | // | |||
1717 | // uint32x2_t x = {42, 64}; | |||
1718 | // return vget_lane_u32(x, 0); // Will return 64. | |||
1719 | // | |||
1720 | // Because of this, explicitly call out that it is non-portable. | |||
1721 | // | |||
1722 | SemaRef.Diag(IList->getBeginLoc(), | |||
1723 | diag::warn_neon_vector_initializer_non_portable); | |||
1724 | ||||
1725 | const char *typeCode; | |||
1726 | unsigned typeSize = SemaRef.Context.getTypeSize(elementType); | |||
1727 | ||||
1728 | if (elementType->isFloatingType()) | |||
1729 | typeCode = "f"; | |||
1730 | else if (elementType->isSignedIntegerType()) | |||
1731 | typeCode = "s"; | |||
1732 | else if (elementType->isUnsignedIntegerType()) | |||
1733 | typeCode = "u"; | |||
1734 | else | |||
1735 | llvm_unreachable("Invalid element type!")::llvm::llvm_unreachable_internal("Invalid element type!", "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 1735); | |||
1736 | ||||
1737 | SemaRef.Diag(IList->getBeginLoc(), | |||
1738 | SemaRef.Context.getTypeSize(VT) > 64 | |||
1739 | ? diag::note_neon_vector_initializer_non_portable_q | |||
1740 | : diag::note_neon_vector_initializer_non_portable) | |||
1741 | << typeCode << typeSize; | |||
1742 | } | |||
1743 | ||||
1744 | return; | |||
1745 | } | |||
1746 | ||||
1747 | InitializedEntity ElementEntity = | |||
1748 | InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); | |||
1749 | ||||
1750 | // OpenCL initializers allows vectors to be constructed from vectors. | |||
1751 | for (unsigned i = 0; i < maxElements; ++i) { | |||
1752 | // Don't attempt to go past the end of the init list | |||
1753 | if (Index >= IList->getNumInits()) | |||
1754 | break; | |||
1755 | ||||
1756 | ElementEntity.setElementIndex(Index); | |||
1757 | ||||
1758 | QualType IType = IList->getInit(Index)->getType(); | |||
1759 | if (!IType->isVectorType()) { | |||
1760 | CheckSubElementType(ElementEntity, IList, elementType, Index, | |||
1761 | StructuredList, StructuredIndex); | |||
1762 | ++numEltsInit; | |||
1763 | } else { | |||
1764 | QualType VecType; | |||
1765 | const VectorType *IVT = IType->castAs<VectorType>(); | |||
1766 | unsigned numIElts = IVT->getNumElements(); | |||
1767 | ||||
1768 | if (IType->isExtVectorType()) | |||
1769 | VecType = SemaRef.Context.getExtVectorType(elementType, numIElts); | |||
1770 | else | |||
1771 | VecType = SemaRef.Context.getVectorType(elementType, numIElts, | |||
1772 | IVT->getVectorKind()); | |||
1773 | CheckSubElementType(ElementEntity, IList, VecType, Index, | |||
1774 | StructuredList, StructuredIndex); | |||
1775 | numEltsInit += numIElts; | |||
1776 | } | |||
1777 | } | |||
1778 | ||||
1779 | // OpenCL requires all elements to be initialized. | |||
1780 | if (numEltsInit != maxElements) { | |||
1781 | if (!VerifyOnly) | |||
1782 | SemaRef.Diag(IList->getBeginLoc(), | |||
1783 | diag::err_vector_incorrect_num_initializers) | |||
1784 | << (numEltsInit < maxElements) << maxElements << numEltsInit; | |||
1785 | hadError = true; | |||
1786 | } | |||
1787 | } | |||
1788 | ||||
1789 | /// Check if the type of a class element has an accessible destructor, and marks | |||
1790 | /// it referenced. Returns true if we shouldn't form a reference to the | |||
1791 | /// destructor. | |||
1792 | /// | |||
1793 | /// Aggregate initialization requires a class element's destructor be | |||
1794 | /// accessible per 11.6.1 [dcl.init.aggr]: | |||
1795 | /// | |||
1796 | /// The destructor for each element of class type is potentially invoked | |||
1797 | /// (15.4 [class.dtor]) from the context where the aggregate initialization | |||
1798 | /// occurs. | |||
1799 | static bool checkDestructorReference(QualType ElementType, SourceLocation Loc, | |||
1800 | Sema &SemaRef) { | |||
1801 | auto *CXXRD = ElementType->getAsCXXRecordDecl(); | |||
1802 | if (!CXXRD) | |||
1803 | return false; | |||
1804 | ||||
1805 | CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(CXXRD); | |||
1806 | SemaRef.CheckDestructorAccess(Loc, Destructor, | |||
1807 | SemaRef.PDiag(diag::err_access_dtor_temp) | |||
1808 | << ElementType); | |||
1809 | SemaRef.MarkFunctionReferenced(Loc, Destructor); | |||
1810 | return SemaRef.DiagnoseUseOfDecl(Destructor, Loc); | |||
1811 | } | |||
1812 | ||||
1813 | void InitListChecker::CheckArrayType(const InitializedEntity &Entity, | |||
1814 | InitListExpr *IList, QualType &DeclType, | |||
1815 | llvm::APSInt elementIndex, | |||
1816 | bool SubobjectIsDesignatorContext, | |||
1817 | unsigned &Index, | |||
1818 | InitListExpr *StructuredList, | |||
1819 | unsigned &StructuredIndex) { | |||
1820 | const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType); | |||
1821 | ||||
1822 | if (!VerifyOnly) { | |||
1823 | if (checkDestructorReference(arrayType->getElementType(), | |||
1824 | IList->getEndLoc(), SemaRef)) { | |||
1825 | hadError = true; | |||
1826 | return; | |||
1827 | } | |||
1828 | } | |||
1829 | ||||
1830 | // Check for the special-case of initializing an array with a string. | |||
1831 | if (Index < IList->getNumInits()) { | |||
1832 | if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) == | |||
1833 | SIF_None) { | |||
1834 | // We place the string literal directly into the resulting | |||
1835 | // initializer list. This is the only place where the structure | |||
1836 | // of the structured initializer list doesn't match exactly, | |||
1837 | // because doing so would involve allocating one character | |||
1838 | // constant for each string. | |||
1839 | // FIXME: Should we do these checks in verify-only mode too? | |||
1840 | if (!VerifyOnly) | |||
1841 | CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef); | |||
1842 | if (StructuredList) { | |||
1843 | UpdateStructuredListElement(StructuredList, StructuredIndex, | |||
1844 | IList->getInit(Index)); | |||
1845 | StructuredList->resizeInits(SemaRef.Context, StructuredIndex); | |||
1846 | } | |||
1847 | ++Index; | |||
1848 | return; | |||
1849 | } | |||
1850 | } | |||
1851 | if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) { | |||
1852 | // Check for VLAs; in standard C it would be possible to check this | |||
1853 | // earlier, but I don't know where clang accepts VLAs (gcc accepts | |||
1854 | // them in all sorts of strange places). | |||
1855 | if (!VerifyOnly) | |||
1856 | SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(), | |||
1857 | diag::err_variable_object_no_init) | |||
1858 | << VAT->getSizeExpr()->getSourceRange(); | |||
1859 | hadError = true; | |||
1860 | ++Index; | |||
1861 | ++StructuredIndex; | |||
1862 | return; | |||
1863 | } | |||
1864 | ||||
1865 | // We might know the maximum number of elements in advance. | |||
1866 | llvm::APSInt maxElements(elementIndex.getBitWidth(), | |||
1867 | elementIndex.isUnsigned()); | |||
1868 | bool maxElementsKnown = false; | |||
1869 | if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) { | |||
1870 | maxElements = CAT->getSize(); | |||
1871 | elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth()); | |||
1872 | elementIndex.setIsUnsigned(maxElements.isUnsigned()); | |||
1873 | maxElementsKnown = true; | |||
1874 | } | |||
1875 | ||||
1876 | QualType elementType = arrayType->getElementType(); | |||
1877 | while (Index < IList->getNumInits()) { | |||
1878 | Expr *Init = IList->getInit(Index); | |||
1879 | if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) { | |||
1880 | // If we're not the subobject that matches up with the '{' for | |||
1881 | // the designator, we shouldn't be handling the | |||
1882 | // designator. Return immediately. | |||
1883 | if (!SubobjectIsDesignatorContext) | |||
1884 | return; | |||
1885 | ||||
1886 | // Handle this designated initializer. elementIndex will be | |||
1887 | // updated to be the next array element we'll initialize. | |||
1888 | if (CheckDesignatedInitializer(Entity, IList, DIE, 0, | |||
1889 | DeclType, nullptr, &elementIndex, Index, | |||
1890 | StructuredList, StructuredIndex, true, | |||
1891 | false)) { | |||
1892 | hadError = true; | |||
1893 | continue; | |||
1894 | } | |||
1895 | ||||
1896 | if (elementIndex.getBitWidth() > maxElements.getBitWidth()) | |||
1897 | maxElements = maxElements.extend(elementIndex.getBitWidth()); | |||
1898 | else if (elementIndex.getBitWidth() < maxElements.getBitWidth()) | |||
1899 | elementIndex = elementIndex.extend(maxElements.getBitWidth()); | |||
1900 | elementIndex.setIsUnsigned(maxElements.isUnsigned()); | |||
1901 | ||||
1902 | // If the array is of incomplete type, keep track of the number of | |||
1903 | // elements in the initializer. | |||
1904 | if (!maxElementsKnown && elementIndex > maxElements) | |||
1905 | maxElements = elementIndex; | |||
1906 | ||||
1907 | continue; | |||
1908 | } | |||
1909 | ||||
1910 | // If we know the maximum number of elements, and we've already | |||
1911 | // hit it, stop consuming elements in the initializer list. | |||
1912 | if (maxElementsKnown && elementIndex == maxElements) | |||
1913 | break; | |||
1914 | ||||
1915 | InitializedEntity ElementEntity = | |||
1916 | InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex, | |||
1917 | Entity); | |||
1918 | // Check this element. | |||
1919 | CheckSubElementType(ElementEntity, IList, elementType, Index, | |||
1920 | StructuredList, StructuredIndex); | |||
1921 | ++elementIndex; | |||
1922 | ||||
1923 | // If the array is of incomplete type, keep track of the number of | |||
1924 | // elements in the initializer. | |||
1925 | if (!maxElementsKnown && elementIndex > maxElements) | |||
1926 | maxElements = elementIndex; | |||
1927 | } | |||
1928 | if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) { | |||
1929 | // If this is an incomplete array type, the actual type needs to | |||
1930 | // be calculated here. | |||
1931 | llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned()); | |||
1932 | if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) { | |||
1933 | // Sizing an array implicitly to zero is not allowed by ISO C, | |||
1934 | // but is supported by GNU. | |||
1935 | SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size); | |||
1936 | } | |||
1937 | ||||
1938 | DeclType = SemaRef.Context.getConstantArrayType( | |||
1939 | elementType, maxElements, nullptr, ArrayType::Normal, 0); | |||
1940 | } | |||
1941 | if (!hadError) { | |||
1942 | // If there are any members of the array that get value-initialized, check | |||
1943 | // that is possible. That happens if we know the bound and don't have | |||
1944 | // enough elements, or if we're performing an array new with an unknown | |||
1945 | // bound. | |||
1946 | if ((maxElementsKnown && elementIndex < maxElements) || | |||
1947 | Entity.isVariableLengthArrayNew()) | |||
1948 | CheckEmptyInitializable( | |||
1949 | InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity), | |||
1950 | IList->getEndLoc()); | |||
1951 | } | |||
1952 | } | |||
1953 | ||||
1954 | bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity, | |||
1955 | Expr *InitExpr, | |||
1956 | FieldDecl *Field, | |||
1957 | bool TopLevelObject) { | |||
1958 | // Handle GNU flexible array initializers. | |||
1959 | unsigned FlexArrayDiag; | |||
1960 | if (isa<InitListExpr>(InitExpr) && | |||
1961 | cast<InitListExpr>(InitExpr)->getNumInits() == 0) { | |||
1962 | // Empty flexible array init always allowed as an extension | |||
1963 | FlexArrayDiag = diag::ext_flexible_array_init; | |||
1964 | } else if (SemaRef.getLangOpts().CPlusPlus) { | |||
1965 | // Disallow flexible array init in C++; it is not required for gcc | |||
1966 | // compatibility, and it needs work to IRGen correctly in general. | |||
1967 | FlexArrayDiag = diag::err_flexible_array_init; | |||
1968 | } else if (!TopLevelObject) { | |||
1969 | // Disallow flexible array init on non-top-level object | |||
1970 | FlexArrayDiag = diag::err_flexible_array_init; | |||
1971 | } else if (Entity.getKind() != InitializedEntity::EK_Variable) { | |||
1972 | // Disallow flexible array init on anything which is not a variable. | |||
1973 | FlexArrayDiag = diag::err_flexible_array_init; | |||
1974 | } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) { | |||
1975 | // Disallow flexible array init on local variables. | |||
1976 | FlexArrayDiag = diag::err_flexible_array_init; | |||
1977 | } else { | |||
1978 | // Allow other cases. | |||
1979 | FlexArrayDiag = diag::ext_flexible_array_init; | |||
1980 | } | |||
1981 | ||||
1982 | if (!VerifyOnly) { | |||
1983 | SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag) | |||
1984 | << InitExpr->getBeginLoc(); | |||
1985 | SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) | |||
1986 | << Field; | |||
1987 | } | |||
1988 | ||||
1989 | return FlexArrayDiag != diag::ext_flexible_array_init; | |||
1990 | } | |||
1991 | ||||
1992 | void InitListChecker::CheckStructUnionTypes( | |||
1993 | const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType, | |||
1994 | CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field, | |||
1995 | bool SubobjectIsDesignatorContext, unsigned &Index, | |||
1996 | InitListExpr *StructuredList, unsigned &StructuredIndex, | |||
1997 | bool TopLevelObject) { | |||
1998 | RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl(); | |||
1999 | ||||
2000 | // If the record is invalid, some of it's members are invalid. To avoid | |||
2001 | // confusion, we forgo checking the intializer for the entire record. | |||
2002 | if (structDecl->isInvalidDecl()) { | |||
2003 | // Assume it was supposed to consume a single initializer. | |||
2004 | ++Index; | |||
2005 | hadError = true; | |||
2006 | return; | |||
2007 | } | |||
2008 | ||||
2009 | if (DeclType->isUnionType() && IList->getNumInits() == 0) { | |||
2010 | RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl(); | |||
2011 | ||||
2012 | if (!VerifyOnly) | |||
2013 | for (FieldDecl *FD : RD->fields()) { | |||
2014 | QualType ET = SemaRef.Context.getBaseElementType(FD->getType()); | |||
2015 | if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) { | |||
2016 | hadError = true; | |||
2017 | return; | |||
2018 | } | |||
2019 | } | |||
2020 | ||||
2021 | // If there's a default initializer, use it. | |||
2022 | if (isa<CXXRecordDecl>(RD) && | |||
2023 | cast<CXXRecordDecl>(RD)->hasInClassInitializer()) { | |||
2024 | if (!StructuredList) | |||
2025 | return; | |||
2026 | for (RecordDecl::field_iterator FieldEnd = RD->field_end(); | |||
2027 | Field != FieldEnd; ++Field) { | |||
2028 | if (Field->hasInClassInitializer()) { | |||
2029 | StructuredList->setInitializedFieldInUnion(*Field); | |||
2030 | // FIXME: Actually build a CXXDefaultInitExpr? | |||
2031 | return; | |||
2032 | } | |||
2033 | } | |||
2034 | } | |||
2035 | ||||
2036 | // Value-initialize the first member of the union that isn't an unnamed | |||
2037 | // bitfield. | |||
2038 | for (RecordDecl::field_iterator FieldEnd = RD->field_end(); | |||
2039 | Field != FieldEnd; ++Field) { | |||
2040 | if (!Field->isUnnamedBitfield()) { | |||
2041 | CheckEmptyInitializable( | |||
2042 | InitializedEntity::InitializeMember(*Field, &Entity), | |||
2043 | IList->getEndLoc()); | |||
2044 | if (StructuredList) | |||
2045 | StructuredList->setInitializedFieldInUnion(*Field); | |||
2046 | break; | |||
2047 | } | |||
2048 | } | |||
2049 | return; | |||
2050 | } | |||
2051 | ||||
2052 | bool InitializedSomething = false; | |||
2053 | ||||
2054 | // If we have any base classes, they are initialized prior to the fields. | |||
2055 | for (auto &Base : Bases) { | |||
2056 | Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr; | |||
2057 | ||||
2058 | // Designated inits always initialize fields, so if we see one, all | |||
2059 | // remaining base classes have no explicit initializer. | |||
2060 | if (Init && isa<DesignatedInitExpr>(Init)) | |||
2061 | Init = nullptr; | |||
2062 | ||||
2063 | SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc(); | |||
2064 | InitializedEntity BaseEntity = InitializedEntity::InitializeBase( | |||
2065 | SemaRef.Context, &Base, false, &Entity); | |||
2066 | if (Init) { | |||
2067 | CheckSubElementType(BaseEntity, IList, Base.getType(), Index, | |||
2068 | StructuredList, StructuredIndex); | |||
2069 | InitializedSomething = true; | |||
2070 | } else { | |||
2071 | CheckEmptyInitializable(BaseEntity, InitLoc); | |||
2072 | } | |||
2073 | ||||
2074 | if (!VerifyOnly) | |||
2075 | if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) { | |||
2076 | hadError = true; | |||
2077 | return; | |||
2078 | } | |||
2079 | } | |||
2080 | ||||
2081 | // If structDecl is a forward declaration, this loop won't do | |||
2082 | // anything except look at designated initializers; That's okay, | |||
2083 | // because an error should get printed out elsewhere. It might be | |||
2084 | // worthwhile to skip over the rest of the initializer, though. | |||
2085 | RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl(); | |||
2086 | RecordDecl::field_iterator FieldEnd = RD->field_end(); | |||
2087 | bool CheckForMissingFields = | |||
2088 | !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()); | |||
2089 | bool HasDesignatedInit = false; | |||
2090 | ||||
2091 | while (Index < IList->getNumInits()) { | |||
2092 | Expr *Init = IList->getInit(Index); | |||
2093 | SourceLocation InitLoc = Init->getBeginLoc(); | |||
2094 | ||||
2095 | if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) { | |||
2096 | // If we're not the subobject that matches up with the '{' for | |||
2097 | // the designator, we shouldn't be handling the | |||
2098 | // designator. Return immediately. | |||
2099 | if (!SubobjectIsDesignatorContext) | |||
2100 | return; | |||
2101 | ||||
2102 | HasDesignatedInit = true; | |||
2103 | ||||
2104 | // Handle this designated initializer. Field will be updated to | |||
2105 | // the next field that we'll be initializing. | |||
2106 | if (CheckDesignatedInitializer(Entity, IList, DIE, 0, | |||
2107 | DeclType, &Field, nullptr, Index, | |||
2108 | StructuredList, StructuredIndex, | |||
2109 | true, TopLevelObject)) | |||
2110 | hadError = true; | |||
2111 | else if (!VerifyOnly) { | |||
2112 | // Find the field named by the designated initializer. | |||
2113 | RecordDecl::field_iterator F = RD->field_begin(); | |||
2114 | while (std::next(F) != Field) | |||
2115 | ++F; | |||
2116 | QualType ET = SemaRef.Context.getBaseElementType(F->getType()); | |||
2117 | if (checkDestructorReference(ET, InitLoc, SemaRef)) { | |||
2118 | hadError = true; | |||
2119 | return; | |||
2120 | } | |||
2121 | } | |||
2122 | ||||
2123 | InitializedSomething = true; | |||
2124 | ||||
2125 | // Disable check for missing fields when designators are used. | |||
2126 | // This matches gcc behaviour. | |||
2127 | CheckForMissingFields = false; | |||
2128 | continue; | |||
2129 | } | |||
2130 | ||||
2131 | if (Field == FieldEnd) { | |||
2132 | // We've run out of fields. We're done. | |||
2133 | break; | |||
2134 | } | |||
2135 | ||||
2136 | // We've already initialized a member of a union. We're done. | |||
2137 | if (InitializedSomething && DeclType->isUnionType()) | |||
2138 | break; | |||
2139 | ||||
2140 | // If we've hit the flexible array member at the end, we're done. | |||
2141 | if (Field->getType()->isIncompleteArrayType()) | |||
2142 | break; | |||
2143 | ||||
2144 | if (Field->isUnnamedBitfield()) { | |||
2145 | // Don't initialize unnamed bitfields, e.g. "int : 20;" | |||
2146 | ++Field; | |||
2147 | continue; | |||
2148 | } | |||
2149 | ||||
2150 | // Make sure we can use this declaration. | |||
2151 | bool InvalidUse; | |||
2152 | if (VerifyOnly) | |||
2153 | InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid); | |||
2154 | else | |||
2155 | InvalidUse = SemaRef.DiagnoseUseOfDecl( | |||
2156 | *Field, IList->getInit(Index)->getBeginLoc()); | |||
2157 | if (InvalidUse) { | |||
2158 | ++Index; | |||
2159 | ++Field; | |||
2160 | hadError = true; | |||
2161 | continue; | |||
2162 | } | |||
2163 | ||||
2164 | if (!VerifyOnly) { | |||
2165 | QualType ET = SemaRef.Context.getBaseElementType(Field->getType()); | |||
2166 | if (checkDestructorReference(ET, InitLoc, SemaRef)) { | |||
2167 | hadError = true; | |||
2168 | return; | |||
2169 | } | |||
2170 | } | |||
2171 | ||||
2172 | InitializedEntity MemberEntity = | |||
2173 | InitializedEntity::InitializeMember(*Field, &Entity); | |||
2174 | CheckSubElementType(MemberEntity, IList, Field->getType(), Index, | |||
2175 | StructuredList, StructuredIndex); | |||
2176 | InitializedSomething = true; | |||
2177 | ||||
2178 | if (DeclType->isUnionType() && StructuredList) { | |||
2179 | // Initialize the first field within the union. | |||
2180 | StructuredList->setInitializedFieldInUnion(*Field); | |||
2181 | } | |||
2182 | ||||
2183 | ++Field; | |||
2184 | } | |||
2185 | ||||
2186 | // Emit warnings for missing struct field initializers. | |||
2187 | if (!VerifyOnly && InitializedSomething && CheckForMissingFields && | |||
2188 | Field != FieldEnd && !Field->getType()->isIncompleteArrayType() && | |||
2189 | !DeclType->isUnionType()) { | |||
2190 | // It is possible we have one or more unnamed bitfields remaining. | |||
2191 | // Find first (if any) named field and emit warning. | |||
2192 | for (RecordDecl::field_iterator it = Field, end = RD->field_end(); | |||
2193 | it != end; ++it) { | |||
2194 | if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) { | |||
2195 | SemaRef.Diag(IList->getSourceRange().getEnd(), | |||
2196 | diag::warn_missing_field_initializers) << *it; | |||
2197 | break; | |||
2198 | } | |||
2199 | } | |||
2200 | } | |||
2201 | ||||
2202 | // Check that any remaining fields can be value-initialized if we're not | |||
2203 | // building a structured list. (If we are, we'll check this later.) | |||
2204 | if (!StructuredList && Field != FieldEnd && !DeclType->isUnionType() && | |||
2205 | !Field->getType()->isIncompleteArrayType()) { | |||
2206 | for (; Field != FieldEnd && !hadError; ++Field) { | |||
2207 | if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer()) | |||
2208 | CheckEmptyInitializable( | |||
2209 | InitializedEntity::InitializeMember(*Field, &Entity), | |||
2210 | IList->getEndLoc()); | |||
2211 | } | |||
2212 | } | |||
2213 | ||||
2214 | // Check that the types of the remaining fields have accessible destructors. | |||
2215 | if (!VerifyOnly) { | |||
2216 | // If the initializer expression has a designated initializer, check the | |||
2217 | // elements for which a designated initializer is not provided too. | |||
2218 | RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin() | |||
2219 | : Field; | |||
2220 | for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) { | |||
2221 | QualType ET = SemaRef.Context.getBaseElementType(I->getType()); | |||
2222 | if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) { | |||
2223 | hadError = true; | |||
2224 | return; | |||
2225 | } | |||
2226 | } | |||
2227 | } | |||
2228 | ||||
2229 | if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() || | |||
2230 | Index >= IList->getNumInits()) | |||
2231 | return; | |||
2232 | ||||
2233 | if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field, | |||
2234 | TopLevelObject)) { | |||
2235 | hadError = true; | |||
2236 | ++Index; | |||
2237 | return; | |||
2238 | } | |||
2239 | ||||
2240 | InitializedEntity MemberEntity = | |||
2241 | InitializedEntity::InitializeMember(*Field, &Entity); | |||
2242 | ||||
2243 | if (isa<InitListExpr>(IList->getInit(Index))) | |||
2244 | CheckSubElementType(MemberEntity, IList, Field->getType(), Index, | |||
2245 | StructuredList, StructuredIndex); | |||
2246 | else | |||
2247 | CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index, | |||
2248 | StructuredList, StructuredIndex); | |||
2249 | } | |||
2250 | ||||
2251 | /// Expand a field designator that refers to a member of an | |||
2252 | /// anonymous struct or union into a series of field designators that | |||
2253 | /// refers to the field within the appropriate subobject. | |||
2254 | /// | |||
2255 | static void ExpandAnonymousFieldDesignator(Sema &SemaRef, | |||
2256 | DesignatedInitExpr *DIE, | |||
2257 | unsigned DesigIdx, | |||
2258 | IndirectFieldDecl *IndirectField) { | |||
2259 | typedef DesignatedInitExpr::Designator Designator; | |||
2260 | ||||
2261 | // Build the replacement designators. | |||
2262 | SmallVector<Designator, 4> Replacements; | |||
2263 | for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(), | |||
2264 | PE = IndirectField->chain_end(); PI != PE; ++PI) { | |||
2265 | if (PI + 1 == PE) | |||
2266 | Replacements.push_back(Designator((IdentifierInfo *)nullptr, | |||
2267 | DIE->getDesignator(DesigIdx)->getDotLoc(), | |||
2268 | DIE->getDesignator(DesigIdx)->getFieldLoc())); | |||
2269 | else | |||
2270 | Replacements.push_back(Designator((IdentifierInfo *)nullptr, | |||
2271 | SourceLocation(), SourceLocation())); | |||
2272 | assert(isa<FieldDecl>(*PI))((isa<FieldDecl>(*PI)) ? static_cast<void> (0) : __assert_fail ("isa<FieldDecl>(*PI)", "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 2272, __PRETTY_FUNCTION__)); | |||
2273 | Replacements.back().setField(cast<FieldDecl>(*PI)); | |||
2274 | } | |||
2275 | ||||
2276 | // Expand the current designator into the set of replacement | |||
2277 | // designators, so we have a full subobject path down to where the | |||
2278 | // member of the anonymous struct/union is actually stored. | |||
2279 | DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0], | |||
2280 | &Replacements[0] + Replacements.size()); | |||
2281 | } | |||
2282 | ||||
2283 | static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef, | |||
2284 | DesignatedInitExpr *DIE) { | |||
2285 | unsigned NumIndexExprs = DIE->getNumSubExprs() - 1; | |||
2286 | SmallVector<Expr*, 4> IndexExprs(NumIndexExprs); | |||
2287 | for (unsigned I = 0; I < NumIndexExprs; ++I) | |||
2288 | IndexExprs[I] = DIE->getSubExpr(I + 1); | |||
2289 | return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(), | |||
2290 | IndexExprs, | |||
2291 | DIE->getEqualOrColonLoc(), | |||
2292 | DIE->usesGNUSyntax(), DIE->getInit()); | |||
2293 | } | |||
2294 | ||||
2295 | namespace { | |||
2296 | ||||
2297 | // Callback to only accept typo corrections that are for field members of | |||
2298 | // the given struct or union. | |||
2299 | class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback { | |||
2300 | public: | |||
2301 | explicit FieldInitializerValidatorCCC(RecordDecl *RD) | |||
2302 | : Record(RD) {} | |||
2303 | ||||
2304 | bool ValidateCandidate(const TypoCorrection &candidate) override { | |||
2305 | FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>(); | |||
2306 | return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record); | |||
2307 | } | |||
2308 | ||||
2309 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | |||
2310 | return std::make_unique<FieldInitializerValidatorCCC>(*this); | |||
2311 | } | |||
2312 | ||||
2313 | private: | |||
2314 | RecordDecl *Record; | |||
2315 | }; | |||
2316 | ||||
2317 | } // end anonymous namespace | |||
2318 | ||||
2319 | /// Check the well-formedness of a C99 designated initializer. | |||
2320 | /// | |||
2321 | /// Determines whether the designated initializer @p DIE, which | |||
2322 | /// resides at the given @p Index within the initializer list @p | |||
2323 | /// IList, is well-formed for a current object of type @p DeclType | |||
2324 | /// (C99 6.7.8). The actual subobject that this designator refers to | |||
2325 | /// within the current subobject is returned in either | |||
2326 | /// @p NextField or @p NextElementIndex (whichever is appropriate). | |||
2327 | /// | |||
2328 | /// @param IList The initializer list in which this designated | |||
2329 | /// initializer occurs. | |||
2330 | /// | |||
2331 | /// @param DIE The designated initializer expression. | |||
2332 | /// | |||
2333 | /// @param DesigIdx The index of the current designator. | |||
2334 | /// | |||
2335 | /// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17), | |||
2336 | /// into which the designation in @p DIE should refer. | |||
2337 | /// | |||
2338 | /// @param NextField If non-NULL and the first designator in @p DIE is | |||
2339 | /// a field, this will be set to the field declaration corresponding | |||
2340 | /// to the field named by the designator. On input, this is expected to be | |||
2341 | /// the next field that would be initialized in the absence of designation, | |||
2342 | /// if the complete object being initialized is a struct. | |||
2343 | /// | |||
2344 | /// @param NextElementIndex If non-NULL and the first designator in @p | |||
2345 | /// DIE is an array designator or GNU array-range designator, this | |||
2346 | /// will be set to the last index initialized by this designator. | |||
2347 | /// | |||
2348 | /// @param Index Index into @p IList where the designated initializer | |||
2349 | /// @p DIE occurs. | |||
2350 | /// | |||
2351 | /// @param StructuredList The initializer list expression that | |||
2352 | /// describes all of the subobject initializers in the order they'll | |||
2353 | /// actually be initialized. | |||
2354 | /// | |||
2355 | /// @returns true if there was an error, false otherwise. | |||
2356 | bool | |||
2357 | InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity, | |||
2358 | InitListExpr *IList, | |||
2359 | DesignatedInitExpr *DIE, | |||
2360 | unsigned DesigIdx, | |||
2361 | QualType &CurrentObjectType, | |||
2362 | RecordDecl::field_iterator *NextField, | |||
2363 | llvm::APSInt *NextElementIndex, | |||
2364 | unsigned &Index, | |||
2365 | InitListExpr *StructuredList, | |||
2366 | unsigned &StructuredIndex, | |||
2367 | bool FinishSubobjectInit, | |||
2368 | bool TopLevelObject) { | |||
2369 | if (DesigIdx == DIE->size()) { | |||
2370 | // C++20 designated initialization can result in direct-list-initialization | |||
2371 | // of the designated subobject. This is the only way that we can end up | |||
2372 | // performing direct initialization as part of aggregate initialization, so | |||
2373 | // it needs special handling. | |||
2374 | if (DIE->isDirectInit()) { | |||
2375 | Expr *Init = DIE->getInit(); | |||
2376 | assert(isa<InitListExpr>(Init) &&((isa<InitListExpr>(Init) && "designator result in direct non-list initialization?" ) ? static_cast<void> (0) : __assert_fail ("isa<InitListExpr>(Init) && \"designator result in direct non-list initialization?\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 2377, __PRETTY_FUNCTION__)) | |||
2377 | "designator result in direct non-list initialization?")((isa<InitListExpr>(Init) && "designator result in direct non-list initialization?" ) ? static_cast<void> (0) : __assert_fail ("isa<InitListExpr>(Init) && \"designator result in direct non-list initialization?\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 2377, __PRETTY_FUNCTION__)); | |||
2378 | InitializationKind Kind = InitializationKind::CreateDirectList( | |||
2379 | DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc()); | |||
2380 | InitializationSequence Seq(SemaRef, Entity, Kind, Init, | |||
2381 | /*TopLevelOfInitList*/ true); | |||
2382 | if (StructuredList) { | |||
2383 | ExprResult Result = VerifyOnly | |||
2384 | ? getDummyInit() | |||
2385 | : Seq.Perform(SemaRef, Entity, Kind, Init); | |||
2386 | UpdateStructuredListElement(StructuredList, StructuredIndex, | |||
2387 | Result.get()); | |||
2388 | } | |||
2389 | ++Index; | |||
2390 | return !Seq; | |||
2391 | } | |||
2392 | ||||
2393 | // Check the actual initialization for the designated object type. | |||
2394 | bool prevHadError = hadError; | |||
2395 | ||||
2396 | // Temporarily remove the designator expression from the | |||
2397 | // initializer list that the child calls see, so that we don't try | |||
2398 | // to re-process the designator. | |||
2399 | unsigned OldIndex = Index; | |||
2400 | IList->setInit(OldIndex, DIE->getInit()); | |||
2401 | ||||
2402 | CheckSubElementType(Entity, IList, CurrentObjectType, Index, | |||
2403 | StructuredList, StructuredIndex); | |||
2404 | ||||
2405 | // Restore the designated initializer expression in the syntactic | |||
2406 | // form of the initializer list. | |||
2407 | if (IList->getInit(OldIndex) != DIE->getInit()) | |||
2408 | DIE->setInit(IList->getInit(OldIndex)); | |||
2409 | IList->setInit(OldIndex, DIE); | |||
2410 | ||||
2411 | return hadError && !prevHadError; | |||
2412 | } | |||
2413 | ||||
2414 | DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx); | |||
2415 | bool IsFirstDesignator = (DesigIdx == 0); | |||
2416 | if (IsFirstDesignator ? FullyStructuredList : StructuredList) { | |||
2417 | // Determine the structural initializer list that corresponds to the | |||
2418 | // current subobject. | |||
2419 | if (IsFirstDesignator) | |||
2420 | StructuredList = FullyStructuredList; | |||
2421 | else { | |||
2422 | Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ? | |||
2423 | StructuredList->getInit(StructuredIndex) : nullptr; | |||
2424 | if (!ExistingInit && StructuredList->hasArrayFiller()) | |||
2425 | ExistingInit = StructuredList->getArrayFiller(); | |||
2426 | ||||
2427 | if (!ExistingInit) | |||
2428 | StructuredList = getStructuredSubobjectInit( | |||
2429 | IList, Index, CurrentObjectType, StructuredList, StructuredIndex, | |||
2430 | SourceRange(D->getBeginLoc(), DIE->getEndLoc())); | |||
2431 | else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit)) | |||
2432 | StructuredList = Result; | |||
2433 | else { | |||
2434 | // We are creating an initializer list that initializes the | |||
2435 | // subobjects of the current object, but there was already an | |||
2436 | // initialization that completely initialized the current | |||
2437 | // subobject, e.g., by a compound literal: | |||
2438 | // | |||
2439 | // struct X { int a, b; }; | |||
2440 | // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 }; | |||
2441 | // | |||
2442 | // Here, xs[0].a == 1 and xs[0].b == 3, since the second, | |||
2443 | // designated initializer re-initializes only its current object | |||
2444 | // subobject [0].b. | |||
2445 | diagnoseInitOverride(ExistingInit, | |||
2446 | SourceRange(D->getBeginLoc(), DIE->getEndLoc()), | |||
2447 | /*FullyOverwritten=*/false); | |||
2448 | ||||
2449 | if (!VerifyOnly) { | |||
2450 | if (DesignatedInitUpdateExpr *E = | |||
2451 | dyn_cast<DesignatedInitUpdateExpr>(ExistingInit)) | |||
2452 | StructuredList = E->getUpdater(); | |||
2453 | else { | |||
2454 | DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context) | |||
2455 | DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(), | |||
2456 | ExistingInit, DIE->getEndLoc()); | |||
2457 | StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE); | |||
2458 | StructuredList = DIUE->getUpdater(); | |||
2459 | } | |||
2460 | } else { | |||
2461 | // We don't need to track the structured representation of a | |||
2462 | // designated init update of an already-fully-initialized object in | |||
2463 | // verify-only mode. The only reason we would need the structure is | |||
2464 | // to determine where the uninitialized "holes" are, and in this | |||
2465 | // case, we know there aren't any and we can't introduce any. | |||
2466 | StructuredList = nullptr; | |||
2467 | } | |||
2468 | } | |||
2469 | } | |||
2470 | } | |||
2471 | ||||
2472 | if (D->isFieldDesignator()) { | |||
2473 | // C99 6.7.8p7: | |||
2474 | // | |||
2475 | // If a designator has the form | |||
2476 | // | |||
2477 | // . identifier | |||
2478 | // | |||
2479 | // then the current object (defined below) shall have | |||
2480 | // structure or union type and the identifier shall be the | |||
2481 | // name of a member of that type. | |||
2482 | const RecordType *RT = CurrentObjectType->getAs<RecordType>(); | |||
2483 | if (!RT) { | |||
2484 | SourceLocation Loc = D->getDotLoc(); | |||
2485 | if (Loc.isInvalid()) | |||
2486 | Loc = D->getFieldLoc(); | |||
2487 | if (!VerifyOnly) | |||
2488 | SemaRef.Diag(Loc, diag::err_field_designator_non_aggr) | |||
2489 | << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType; | |||
2490 | ++Index; | |||
2491 | return true; | |||
2492 | } | |||
2493 | ||||
2494 | FieldDecl *KnownField = D->getField(); | |||
2495 | if (!KnownField) { | |||
2496 | IdentifierInfo *FieldName = D->getFieldName(); | |||
2497 | DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName); | |||
2498 | for (NamedDecl *ND : Lookup) { | |||
2499 | if (auto *FD = dyn_cast<FieldDecl>(ND)) { | |||
2500 | KnownField = FD; | |||
2501 | break; | |||
2502 | } | |||
2503 | if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) { | |||
2504 | // In verify mode, don't modify the original. | |||
2505 | if (VerifyOnly) | |||
2506 | DIE = CloneDesignatedInitExpr(SemaRef, DIE); | |||
2507 | ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD); | |||
2508 | D = DIE->getDesignator(DesigIdx); | |||
2509 | KnownField = cast<FieldDecl>(*IFD->chain_begin()); | |||
2510 | break; | |||
2511 | } | |||
2512 | } | |||
2513 | if (!KnownField) { | |||
2514 | if (VerifyOnly) { | |||
2515 | ++Index; | |||
2516 | return true; // No typo correction when just trying this out. | |||
2517 | } | |||
2518 | ||||
2519 | // Name lookup found something, but it wasn't a field. | |||
2520 | if (!Lookup.empty()) { | |||
2521 | SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield) | |||
2522 | << FieldName; | |||
2523 | SemaRef.Diag(Lookup.front()->getLocation(), | |||
2524 | diag::note_field_designator_found); | |||
2525 | ++Index; | |||
2526 | return true; | |||
2527 | } | |||
2528 | ||||
2529 | // Name lookup didn't find anything. | |||
2530 | // Determine whether this was a typo for another field name. | |||
2531 | FieldInitializerValidatorCCC CCC(RT->getDecl()); | |||
2532 | if (TypoCorrection Corrected = SemaRef.CorrectTypo( | |||
2533 | DeclarationNameInfo(FieldName, D->getFieldLoc()), | |||
2534 | Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC, | |||
2535 | Sema::CTK_ErrorRecovery, RT->getDecl())) { | |||
2536 | SemaRef.diagnoseTypo( | |||
2537 | Corrected, | |||
2538 | SemaRef.PDiag(diag::err_field_designator_unknown_suggest) | |||
2539 | << FieldName << CurrentObjectType); | |||
2540 | KnownField = Corrected.getCorrectionDeclAs<FieldDecl>(); | |||
2541 | hadError = true; | |||
2542 | } else { | |||
2543 | // Typo correction didn't find anything. | |||
2544 | SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown) | |||
2545 | << FieldName << CurrentObjectType; | |||
2546 | ++Index; | |||
2547 | return true; | |||
2548 | } | |||
2549 | } | |||
2550 | } | |||
2551 | ||||
2552 | unsigned NumBases = 0; | |||
2553 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) | |||
2554 | NumBases = CXXRD->getNumBases(); | |||
2555 | ||||
2556 | unsigned FieldIndex = NumBases; | |||
2557 | ||||
2558 | for (auto *FI : RT->getDecl()->fields()) { | |||
2559 | if (FI->isUnnamedBitfield()) | |||
2560 | continue; | |||
2561 | if (declaresSameEntity(KnownField, FI)) { | |||
2562 | KnownField = FI; | |||
2563 | break; | |||
2564 | } | |||
2565 | ++FieldIndex; | |||
2566 | } | |||
2567 | ||||
2568 | RecordDecl::field_iterator Field = | |||
2569 | RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField)); | |||
2570 | ||||
2571 | // All of the fields of a union are located at the same place in | |||
2572 | // the initializer list. | |||
2573 | if (RT->getDecl()->isUnion()) { | |||
2574 | FieldIndex = 0; | |||
2575 | if (StructuredList) { | |||
2576 | FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion(); | |||
2577 | if (CurrentField && !declaresSameEntity(CurrentField, *Field)) { | |||
2578 | assert(StructuredList->getNumInits() == 1((StructuredList->getNumInits() == 1 && "A union should never have more than one initializer!" ) ? static_cast<void> (0) : __assert_fail ("StructuredList->getNumInits() == 1 && \"A union should never have more than one initializer!\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 2579, __PRETTY_FUNCTION__)) | |||
2579 | && "A union should never have more than one initializer!")((StructuredList->getNumInits() == 1 && "A union should never have more than one initializer!" ) ? static_cast<void> (0) : __assert_fail ("StructuredList->getNumInits() == 1 && \"A union should never have more than one initializer!\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 2579, __PRETTY_FUNCTION__)); | |||
2580 | ||||
2581 | Expr *ExistingInit = StructuredList->getInit(0); | |||
2582 | if (ExistingInit) { | |||
2583 | // We're about to throw away an initializer, emit warning. | |||
2584 | diagnoseInitOverride( | |||
2585 | ExistingInit, SourceRange(D->getBeginLoc(), DIE->getEndLoc())); | |||
2586 | } | |||
2587 | ||||
2588 | // remove existing initializer | |||
2589 | StructuredList->resizeInits(SemaRef.Context, 0); | |||
2590 | StructuredList->setInitializedFieldInUnion(nullptr); | |||
2591 | } | |||
2592 | ||||
2593 | StructuredList->setInitializedFieldInUnion(*Field); | |||
2594 | } | |||
2595 | } | |||
2596 | ||||
2597 | // Make sure we can use this declaration. | |||
2598 | bool InvalidUse; | |||
2599 | if (VerifyOnly) | |||
2600 | InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid); | |||
2601 | else | |||
2602 | InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc()); | |||
2603 | if (InvalidUse) { | |||
2604 | ++Index; | |||
2605 | return true; | |||
2606 | } | |||
2607 | ||||
2608 | // C++20 [dcl.init.list]p3: | |||
2609 | // The ordered identifiers in the designators of the designated- | |||
2610 | // initializer-list shall form a subsequence of the ordered identifiers | |||
2611 | // in the direct non-static data members of T. | |||
2612 | // | |||
2613 | // Note that this is not a condition on forming the aggregate | |||
2614 | // initialization, only on actually performing initialization, | |||
2615 | // so it is not checked in VerifyOnly mode. | |||
2616 | // | |||
2617 | // FIXME: This is the only reordering diagnostic we produce, and it only | |||
2618 | // catches cases where we have a top-level field designator that jumps | |||
2619 | // backwards. This is the only such case that is reachable in an | |||
2620 | // otherwise-valid C++20 program, so is the only case that's required for | |||
2621 | // conformance, but for consistency, we should diagnose all the other | |||
2622 | // cases where a designator takes us backwards too. | |||
2623 | if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus && | |||
2624 | NextField && | |||
2625 | (*NextField == RT->getDecl()->field_end() || | |||
2626 | (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) { | |||
2627 | // Find the field that we just initialized. | |||
2628 | FieldDecl *PrevField = nullptr; | |||
2629 | for (auto FI = RT->getDecl()->field_begin(); | |||
2630 | FI != RT->getDecl()->field_end(); ++FI) { | |||
2631 | if (FI->isUnnamedBitfield()) | |||
2632 | continue; | |||
2633 | if (*NextField != RT->getDecl()->field_end() && | |||
2634 | declaresSameEntity(*FI, **NextField)) | |||
2635 | break; | |||
2636 | PrevField = *FI; | |||
2637 | } | |||
2638 | ||||
2639 | if (PrevField && | |||
2640 | PrevField->getFieldIndex() > KnownField->getFieldIndex()) { | |||
2641 | SemaRef.Diag(DIE->getBeginLoc(), diag::ext_designated_init_reordered) | |||
2642 | << KnownField << PrevField << DIE->getSourceRange(); | |||
2643 | ||||
2644 | unsigned OldIndex = NumBases + PrevField->getFieldIndex(); | |||
2645 | if (StructuredList && OldIndex <= StructuredList->getNumInits()) { | |||
2646 | if (Expr *PrevInit = StructuredList->getInit(OldIndex)) { | |||
2647 | SemaRef.Diag(PrevInit->getBeginLoc(), | |||
2648 | diag::note_previous_field_init) | |||
2649 | << PrevField << PrevInit->getSourceRange(); | |||
2650 | } | |||
2651 | } | |||
2652 | } | |||
2653 | } | |||
2654 | ||||
2655 | ||||
2656 | // Update the designator with the field declaration. | |||
2657 | if (!VerifyOnly) | |||
2658 | D->setField(*Field); | |||
2659 | ||||
2660 | // Make sure that our non-designated initializer list has space | |||
2661 | // for a subobject corresponding to this field. | |||
2662 | if (StructuredList && FieldIndex >= StructuredList->getNumInits()) | |||
2663 | StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1); | |||
2664 | ||||
2665 | // This designator names a flexible array member. | |||
2666 | if (Field->getType()->isIncompleteArrayType()) { | |||
2667 | bool Invalid = false; | |||
2668 | if ((DesigIdx + 1) != DIE->size()) { | |||
2669 | // We can't designate an object within the flexible array | |||
2670 | // member (because GCC doesn't allow it). | |||
2671 | if (!VerifyOnly) { | |||
2672 | DesignatedInitExpr::Designator *NextD | |||
2673 | = DIE->getDesignator(DesigIdx + 1); | |||
2674 | SemaRef.Diag(NextD->getBeginLoc(), | |||
2675 | diag::err_designator_into_flexible_array_member) | |||
2676 | << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc()); | |||
2677 | SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) | |||
2678 | << *Field; | |||
2679 | } | |||
2680 | Invalid = true; | |||
2681 | } | |||
2682 | ||||
2683 | if (!hadError && !isa<InitListExpr>(DIE->getInit()) && | |||
2684 | !isa<StringLiteral>(DIE->getInit())) { | |||
2685 | // The initializer is not an initializer list. | |||
2686 | if (!VerifyOnly) { | |||
2687 | SemaRef.Diag(DIE->getInit()->getBeginLoc(), | |||
2688 | diag::err_flexible_array_init_needs_braces) | |||
2689 | << DIE->getInit()->getSourceRange(); | |||
2690 | SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) | |||
2691 | << *Field; | |||
2692 | } | |||
2693 | Invalid = true; | |||
2694 | } | |||
2695 | ||||
2696 | // Check GNU flexible array initializer. | |||
2697 | if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field, | |||
2698 | TopLevelObject)) | |||
2699 | Invalid = true; | |||
2700 | ||||
2701 | if (Invalid) { | |||
2702 | ++Index; | |||
2703 | return true; | |||
2704 | } | |||
2705 | ||||
2706 | // Initialize the array. | |||
2707 | bool prevHadError = hadError; | |||
2708 | unsigned newStructuredIndex = FieldIndex; | |||
2709 | unsigned OldIndex = Index; | |||
2710 | IList->setInit(Index, DIE->getInit()); | |||
2711 | ||||
2712 | InitializedEntity MemberEntity = | |||
2713 | InitializedEntity::InitializeMember(*Field, &Entity); | |||
2714 | CheckSubElementType(MemberEntity, IList, Field->getType(), Index, | |||
2715 | StructuredList, newStructuredIndex); | |||
2716 | ||||
2717 | IList->setInit(OldIndex, DIE); | |||
2718 | if (hadError && !prevHadError) { | |||
2719 | ++Field; | |||
2720 | ++FieldIndex; | |||
2721 | if (NextField) | |||
2722 | *NextField = Field; | |||
2723 | StructuredIndex = FieldIndex; | |||
2724 | return true; | |||
2725 | } | |||
2726 | } else { | |||
2727 | // Recurse to check later designated subobjects. | |||
2728 | QualType FieldType = Field->getType(); | |||
2729 | unsigned newStructuredIndex = FieldIndex; | |||
2730 | ||||
2731 | InitializedEntity MemberEntity = | |||
2732 | InitializedEntity::InitializeMember(*Field, &Entity); | |||
2733 | if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1, | |||
2734 | FieldType, nullptr, nullptr, Index, | |||
2735 | StructuredList, newStructuredIndex, | |||
2736 | FinishSubobjectInit, false)) | |||
2737 | return true; | |||
2738 | } | |||
2739 | ||||
2740 | // Find the position of the next field to be initialized in this | |||
2741 | // subobject. | |||
2742 | ++Field; | |||
2743 | ++FieldIndex; | |||
2744 | ||||
2745 | // If this the first designator, our caller will continue checking | |||
2746 | // the rest of this struct/class/union subobject. | |||
2747 | if (IsFirstDesignator) { | |||
2748 | if (NextField) | |||
2749 | *NextField = Field; | |||
2750 | StructuredIndex = FieldIndex; | |||
2751 | return false; | |||
2752 | } | |||
2753 | ||||
2754 | if (!FinishSubobjectInit) | |||
2755 | return false; | |||
2756 | ||||
2757 | // We've already initialized something in the union; we're done. | |||
2758 | if (RT->getDecl()->isUnion()) | |||
2759 | return hadError; | |||
2760 | ||||
2761 | // Check the remaining fields within this class/struct/union subobject. | |||
2762 | bool prevHadError = hadError; | |||
2763 | ||||
2764 | auto NoBases = | |||
2765 | CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(), | |||
2766 | CXXRecordDecl::base_class_iterator()); | |||
2767 | CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field, | |||
2768 | false, Index, StructuredList, FieldIndex); | |||
2769 | return hadError && !prevHadError; | |||
2770 | } | |||
2771 | ||||
2772 | // C99 6.7.8p6: | |||
2773 | // | |||
2774 | // If a designator has the form | |||
2775 | // | |||
2776 | // [ constant-expression ] | |||
2777 | // | |||
2778 | // then the current object (defined below) shall have array | |||
2779 | // type and the expression shall be an integer constant | |||
2780 | // expression. If the array is of unknown size, any | |||
2781 | // nonnegative value is valid. | |||
2782 | // | |||
2783 | // Additionally, cope with the GNU extension that permits | |||
2784 | // designators of the form | |||
2785 | // | |||
2786 | // [ constant-expression ... constant-expression ] | |||
2787 | const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType); | |||
2788 | if (!AT) { | |||
2789 | if (!VerifyOnly) | |||
2790 | SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array) | |||
2791 | << CurrentObjectType; | |||
2792 | ++Index; | |||
2793 | return true; | |||
2794 | } | |||
2795 | ||||
2796 | Expr *IndexExpr = nullptr; | |||
2797 | llvm::APSInt DesignatedStartIndex, DesignatedEndIndex; | |||
2798 | if (D->isArrayDesignator()) { | |||
2799 | IndexExpr = DIE->getArrayIndex(*D); | |||
2800 | DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context); | |||
2801 | DesignatedEndIndex = DesignatedStartIndex; | |||
2802 | } else { | |||
2803 | assert(D->isArrayRangeDesignator() && "Need array-range designator")((D->isArrayRangeDesignator() && "Need array-range designator" ) ? static_cast<void> (0) : __assert_fail ("D->isArrayRangeDesignator() && \"Need array-range designator\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 2803, __PRETTY_FUNCTION__)); | |||
2804 | ||||
2805 | DesignatedStartIndex = | |||
2806 | DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context); | |||
2807 | DesignatedEndIndex = | |||
2808 | DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context); | |||
2809 | IndexExpr = DIE->getArrayRangeEnd(*D); | |||
2810 | ||||
2811 | // Codegen can't handle evaluating array range designators that have side | |||
2812 | // effects, because we replicate the AST value for each initialized element. | |||
2813 | // As such, set the sawArrayRangeDesignator() bit if we initialize multiple | |||
2814 | // elements with something that has a side effect, so codegen can emit an | |||
2815 | // "error unsupported" error instead of miscompiling the app. | |||
2816 | if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&& | |||
2817 | DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly) | |||
2818 | FullyStructuredList->sawArrayRangeDesignator(); | |||
2819 | } | |||
2820 | ||||
2821 | if (isa<ConstantArrayType>(AT)) { | |||
2822 | llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false); | |||
2823 | DesignatedStartIndex | |||
2824 | = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth()); | |||
2825 | DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned()); | |||
2826 | DesignatedEndIndex | |||
2827 | = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth()); | |||
2828 | DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned()); | |||
2829 | if (DesignatedEndIndex >= MaxElements) { | |||
2830 | if (!VerifyOnly) | |||
2831 | SemaRef.Diag(IndexExpr->getBeginLoc(), | |||
2832 | diag::err_array_designator_too_large) | |||
2833 | << DesignatedEndIndex.toString(10) << MaxElements.toString(10) | |||
2834 | << IndexExpr->getSourceRange(); | |||
2835 | ++Index; | |||
2836 | return true; | |||
2837 | } | |||
2838 | } else { | |||
2839 | unsigned DesignatedIndexBitWidth = | |||
2840 | ConstantArrayType::getMaxSizeBits(SemaRef.Context); | |||
2841 | DesignatedStartIndex = | |||
2842 | DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth); | |||
2843 | DesignatedEndIndex = | |||
2844 | DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth); | |||
2845 | DesignatedStartIndex.setIsUnsigned(true); | |||
2846 | DesignatedEndIndex.setIsUnsigned(true); | |||
2847 | } | |||
2848 | ||||
2849 | bool IsStringLiteralInitUpdate = | |||
2850 | StructuredList && StructuredList->isStringLiteralInit(); | |||
2851 | if (IsStringLiteralInitUpdate && VerifyOnly) { | |||
2852 | // We're just verifying an update to a string literal init. We don't need | |||
2853 | // to split the string up into individual characters to do that. | |||
2854 | StructuredList = nullptr; | |||
2855 | } else if (IsStringLiteralInitUpdate) { | |||
2856 | // We're modifying a string literal init; we have to decompose the string | |||
2857 | // so we can modify the individual characters. | |||
2858 | ASTContext &Context = SemaRef.Context; | |||
2859 | Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens(); | |||
2860 | ||||
2861 | // Compute the character type | |||
2862 | QualType CharTy = AT->getElementType(); | |||
2863 | ||||
2864 | // Compute the type of the integer literals. | |||
2865 | QualType PromotedCharTy = CharTy; | |||
2866 | if (CharTy->isPromotableIntegerType()) | |||
2867 | PromotedCharTy = Context.getPromotedIntegerType(CharTy); | |||
2868 | unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy); | |||
2869 | ||||
2870 | if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) { | |||
2871 | // Get the length of the string. | |||
2872 | uint64_t StrLen = SL->getLength(); | |||
2873 | if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen)) | |||
2874 | StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue(); | |||
2875 | StructuredList->resizeInits(Context, StrLen); | |||
2876 | ||||
2877 | // Build a literal for each character in the string, and put them into | |||
2878 | // the init list. | |||
2879 | for (unsigned i = 0, e = StrLen; i != e; ++i) { | |||
2880 | llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i)); | |||
2881 | Expr *Init = new (Context) IntegerLiteral( | |||
2882 | Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc()); | |||
2883 | if (CharTy != PromotedCharTy) | |||
2884 | Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast, | |||
2885 | Init, nullptr, VK_RValue); | |||
2886 | StructuredList->updateInit(Context, i, Init); | |||
2887 | } | |||
2888 | } else { | |||
2889 | ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr); | |||
2890 | std::string Str; | |||
2891 | Context.getObjCEncodingForType(E->getEncodedType(), Str); | |||
2892 | ||||
2893 | // Get the length of the string. | |||
2894 | uint64_t StrLen = Str.size(); | |||
2895 | if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen)) | |||
2896 | StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue(); | |||
2897 | StructuredList->resizeInits(Context, StrLen); | |||
2898 | ||||
2899 | // Build a literal for each character in the string, and put them into | |||
2900 | // the init list. | |||
2901 | for (unsigned i = 0, e = StrLen; i != e; ++i) { | |||
2902 | llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]); | |||
2903 | Expr *Init = new (Context) IntegerLiteral( | |||
2904 | Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc()); | |||
2905 | if (CharTy != PromotedCharTy) | |||
2906 | Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast, | |||
2907 | Init, nullptr, VK_RValue); | |||
2908 | StructuredList->updateInit(Context, i, Init); | |||
2909 | } | |||
2910 | } | |||
2911 | } | |||
2912 | ||||
2913 | // Make sure that our non-designated initializer list has space | |||
2914 | // for a subobject corresponding to this array element. | |||
2915 | if (StructuredList && | |||
2916 | DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits()) | |||
2917 | StructuredList->resizeInits(SemaRef.Context, | |||
2918 | DesignatedEndIndex.getZExtValue() + 1); | |||
2919 | ||||
2920 | // Repeatedly perform subobject initializations in the range | |||
2921 | // [DesignatedStartIndex, DesignatedEndIndex]. | |||
2922 | ||||
2923 | // Move to the next designator | |||
2924 | unsigned ElementIndex = DesignatedStartIndex.getZExtValue(); | |||
2925 | unsigned OldIndex = Index; | |||
2926 | ||||
2927 | InitializedEntity ElementEntity = | |||
2928 | InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); | |||
2929 | ||||
2930 | while (DesignatedStartIndex <= DesignatedEndIndex) { | |||
2931 | // Recurse to check later designated subobjects. | |||
2932 | QualType ElementType = AT->getElementType(); | |||
2933 | Index = OldIndex; | |||
2934 | ||||
2935 | ElementEntity.setElementIndex(ElementIndex); | |||
2936 | if (CheckDesignatedInitializer( | |||
2937 | ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr, | |||
2938 | nullptr, Index, StructuredList, ElementIndex, | |||
2939 | FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex), | |||
2940 | false)) | |||
2941 | return true; | |||
2942 | ||||
2943 | // Move to the next index in the array that we'll be initializing. | |||
2944 | ++DesignatedStartIndex; | |||
2945 | ElementIndex = DesignatedStartIndex.getZExtValue(); | |||
2946 | } | |||
2947 | ||||
2948 | // If this the first designator, our caller will continue checking | |||
2949 | // the rest of this array subobject. | |||
2950 | if (IsFirstDesignator) { | |||
2951 | if (NextElementIndex) | |||
2952 | *NextElementIndex = DesignatedStartIndex; | |||
2953 | StructuredIndex = ElementIndex; | |||
2954 | return false; | |||
2955 | } | |||
2956 | ||||
2957 | if (!FinishSubobjectInit) | |||
2958 | return false; | |||
2959 | ||||
2960 | // Check the remaining elements within this array subobject. | |||
2961 | bool prevHadError = hadError; | |||
2962 | CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex, | |||
2963 | /*SubobjectIsDesignatorContext=*/false, Index, | |||
2964 | StructuredList, ElementIndex); | |||
2965 | return hadError && !prevHadError; | |||
2966 | } | |||
2967 | ||||
2968 | // Get the structured initializer list for a subobject of type | |||
2969 | // @p CurrentObjectType. | |||
2970 | InitListExpr * | |||
2971 | InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, | |||
2972 | QualType CurrentObjectType, | |||
2973 | InitListExpr *StructuredList, | |||
2974 | unsigned StructuredIndex, | |||
2975 | SourceRange InitRange, | |||
2976 | bool IsFullyOverwritten) { | |||
2977 | if (!StructuredList) | |||
2978 | return nullptr; | |||
2979 | ||||
2980 | Expr *ExistingInit = nullptr; | |||
2981 | if (StructuredIndex < StructuredList->getNumInits()) | |||
2982 | ExistingInit = StructuredList->getInit(StructuredIndex); | |||
2983 | ||||
2984 | if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit)) | |||
2985 | // There might have already been initializers for subobjects of the current | |||
2986 | // object, but a subsequent initializer list will overwrite the entirety | |||
2987 | // of the current object. (See DR 253 and C99 6.7.8p21). e.g., | |||
2988 | // | |||
2989 | // struct P { char x[6]; }; | |||
2990 | // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } }; | |||
2991 | // | |||
2992 | // The first designated initializer is ignored, and l.x is just "f". | |||
2993 | if (!IsFullyOverwritten) | |||
2994 | return Result; | |||
2995 | ||||
2996 | if (ExistingInit) { | |||
2997 | // We are creating an initializer list that initializes the | |||
2998 | // subobjects of the current object, but there was already an | |||
2999 | // initialization that completely initialized the current | |||
3000 | // subobject: | |||
3001 | // | |||
3002 | // struct X { int a, b; }; | |||
3003 | // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 }; | |||
3004 | // | |||
3005 | // Here, xs[0].a == 1 and xs[0].b == 3, since the second, | |||
3006 | // designated initializer overwrites the [0].b initializer | |||
3007 | // from the prior initialization. | |||
3008 | // | |||
3009 | // When the existing initializer is an expression rather than an | |||
3010 | // initializer list, we cannot decompose and update it in this way. | |||
3011 | // For example: | |||
3012 | // | |||
3013 | // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 }; | |||
3014 | // | |||
3015 | // This case is handled by CheckDesignatedInitializer. | |||
3016 | diagnoseInitOverride(ExistingInit, InitRange); | |||
3017 | } | |||
3018 | ||||
3019 | unsigned ExpectedNumInits = 0; | |||
3020 | if (Index < IList->getNumInits()) { | |||
3021 | if (auto *Init = dyn_cast_or_null<InitListExpr>(IList->getInit(Index))) | |||
3022 | ExpectedNumInits = Init->getNumInits(); | |||
3023 | else | |||
3024 | ExpectedNumInits = IList->getNumInits() - Index; | |||
3025 | } | |||
3026 | ||||
3027 | InitListExpr *Result = | |||
3028 | createInitListExpr(CurrentObjectType, InitRange, ExpectedNumInits); | |||
3029 | ||||
3030 | // Link this new initializer list into the structured initializer | |||
3031 | // lists. | |||
3032 | StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result); | |||
3033 | return Result; | |||
3034 | } | |||
3035 | ||||
3036 | InitListExpr * | |||
3037 | InitListChecker::createInitListExpr(QualType CurrentObjectType, | |||
3038 | SourceRange InitRange, | |||
3039 | unsigned ExpectedNumInits) { | |||
3040 | InitListExpr *Result | |||
3041 | = new (SemaRef.Context) InitListExpr(SemaRef.Context, | |||
3042 | InitRange.getBegin(), None, | |||
3043 | InitRange.getEnd()); | |||
3044 | ||||
3045 | QualType ResultType = CurrentObjectType; | |||
3046 | if (!ResultType->isArrayType()) | |||
3047 | ResultType = ResultType.getNonLValueExprType(SemaRef.Context); | |||
3048 | Result->setType(ResultType); | |||
3049 | ||||
3050 | // Pre-allocate storage for the structured initializer list. | |||
3051 | unsigned NumElements = 0; | |||
3052 | ||||
3053 | if (const ArrayType *AType | |||
3054 | = SemaRef.Context.getAsArrayType(CurrentObjectType)) { | |||
3055 | if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) { | |||
3056 | NumElements = CAType->getSize().getZExtValue(); | |||
3057 | // Simple heuristic so that we don't allocate a very large | |||
3058 | // initializer with many empty entries at the end. | |||
3059 | if (NumElements > ExpectedNumInits) | |||
3060 | NumElements = 0; | |||
3061 | } | |||
3062 | } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) { | |||
3063 | NumElements = VType->getNumElements(); | |||
3064 | } else if (CurrentObjectType->isRecordType()) { | |||
3065 | NumElements = numStructUnionElements(CurrentObjectType); | |||
3066 | } | |||
3067 | ||||
3068 | Result->reserveInits(SemaRef.Context, NumElements); | |||
3069 | ||||
3070 | return Result; | |||
3071 | } | |||
3072 | ||||
3073 | /// Update the initializer at index @p StructuredIndex within the | |||
3074 | /// structured initializer list to the value @p expr. | |||
3075 | void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList, | |||
3076 | unsigned &StructuredIndex, | |||
3077 | Expr *expr) { | |||
3078 | // No structured initializer list to update | |||
3079 | if (!StructuredList) | |||
3080 | return; | |||
3081 | ||||
3082 | if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context, | |||
3083 | StructuredIndex, expr)) { | |||
3084 | // This initializer overwrites a previous initializer. Warn. | |||
3085 | diagnoseInitOverride(PrevInit, expr->getSourceRange()); | |||
3086 | } | |||
3087 | ||||
3088 | ++StructuredIndex; | |||
3089 | } | |||
3090 | ||||
3091 | /// Determine whether we can perform aggregate initialization for the purposes | |||
3092 | /// of overload resolution. | |||
3093 | bool Sema::CanPerformAggregateInitializationForOverloadResolution( | |||
3094 | const InitializedEntity &Entity, InitListExpr *From) { | |||
3095 | QualType Type = Entity.getType(); | |||
3096 | InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true, | |||
3097 | /*TreatUnavailableAsInvalid=*/false, | |||
3098 | /*InOverloadResolution=*/true); | |||
3099 | return !Check.HadError(); | |||
3100 | } | |||
3101 | ||||
3102 | /// Check that the given Index expression is a valid array designator | |||
3103 | /// value. This is essentially just a wrapper around | |||
3104 | /// VerifyIntegerConstantExpression that also checks for negative values | |||
3105 | /// and produces a reasonable diagnostic if there is a | |||
3106 | /// failure. Returns the index expression, possibly with an implicit cast | |||
3107 | /// added, on success. If everything went okay, Value will receive the | |||
3108 | /// value of the constant expression. | |||
3109 | static ExprResult | |||
3110 | CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) { | |||
3111 | SourceLocation Loc = Index->getBeginLoc(); | |||
3112 | ||||
3113 | // Make sure this is an integer constant expression. | |||
3114 | ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value); | |||
3115 | if (Result.isInvalid()) | |||
3116 | return Result; | |||
3117 | ||||
3118 | if (Value.isSigned() && Value.isNegative()) | |||
3119 | return S.Diag(Loc, diag::err_array_designator_negative) | |||
3120 | << Value.toString(10) << Index->getSourceRange(); | |||
3121 | ||||
3122 | Value.setIsUnsigned(true); | |||
3123 | return Result; | |||
3124 | } | |||
3125 | ||||
3126 | ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig, | |||
3127 | SourceLocation EqualOrColonLoc, | |||
3128 | bool GNUSyntax, | |||
3129 | ExprResult Init) { | |||
3130 | typedef DesignatedInitExpr::Designator ASTDesignator; | |||
3131 | ||||
3132 | bool Invalid = false; | |||
3133 | SmallVector<ASTDesignator, 32> Designators; | |||
3134 | SmallVector<Expr *, 32> InitExpressions; | |||
3135 | ||||
3136 | // Build designators and check array designator expressions. | |||
3137 | for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) { | |||
3138 | const Designator &D = Desig.getDesignator(Idx); | |||
3139 | switch (D.getKind()) { | |||
3140 | case Designator::FieldDesignator: | |||
3141 | Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(), | |||
3142 | D.getFieldLoc())); | |||
3143 | break; | |||
3144 | ||||
3145 | case Designator::ArrayDesignator: { | |||
3146 | Expr *Index = static_cast<Expr *>(D.getArrayIndex()); | |||
3147 | llvm::APSInt IndexValue; | |||
3148 | if (!Index->isTypeDependent() && !Index->isValueDependent()) | |||
3149 | Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get(); | |||
3150 | if (!Index) | |||
3151 | Invalid = true; | |||
3152 | else { | |||
3153 | Designators.push_back(ASTDesignator(InitExpressions.size(), | |||
3154 | D.getLBracketLoc(), | |||
3155 | D.getRBracketLoc())); | |||
3156 | InitExpressions.push_back(Index); | |||
3157 | } | |||
3158 | break; | |||
3159 | } | |||
3160 | ||||
3161 | case Designator::ArrayRangeDesignator: { | |||
3162 | Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart()); | |||
3163 | Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd()); | |||
3164 | llvm::APSInt StartValue; | |||
3165 | llvm::APSInt EndValue; | |||
3166 | bool StartDependent = StartIndex->isTypeDependent() || | |||
3167 | StartIndex->isValueDependent(); | |||
3168 | bool EndDependent = EndIndex->isTypeDependent() || | |||
3169 | EndIndex->isValueDependent(); | |||
3170 | if (!StartDependent) | |||
3171 | StartIndex = | |||
3172 | CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get(); | |||
3173 | if (!EndDependent) | |||
3174 | EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get(); | |||
3175 | ||||
3176 | if (!StartIndex || !EndIndex) | |||
3177 | Invalid = true; | |||
3178 | else { | |||
3179 | // Make sure we're comparing values with the same bit width. | |||
3180 | if (StartDependent || EndDependent) { | |||
3181 | // Nothing to compute. | |||
3182 | } else if (StartValue.getBitWidth() > EndValue.getBitWidth()) | |||
3183 | EndValue = EndValue.extend(StartValue.getBitWidth()); | |||
3184 | else if (StartValue.getBitWidth() < EndValue.getBitWidth()) | |||
3185 | StartValue = StartValue.extend(EndValue.getBitWidth()); | |||
3186 | ||||
3187 | if (!StartDependent && !EndDependent && EndValue < StartValue) { | |||
3188 | Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range) | |||
3189 | << StartValue.toString(10) << EndValue.toString(10) | |||
3190 | << StartIndex->getSourceRange() << EndIndex->getSourceRange(); | |||
3191 | Invalid = true; | |||
3192 | } else { | |||
3193 | Designators.push_back(ASTDesignator(InitExpressions.size(), | |||
3194 | D.getLBracketLoc(), | |||
3195 | D.getEllipsisLoc(), | |||
3196 | D.getRBracketLoc())); | |||
3197 | InitExpressions.push_back(StartIndex); | |||
3198 | InitExpressions.push_back(EndIndex); | |||
3199 | } | |||
3200 | } | |||
3201 | break; | |||
3202 | } | |||
3203 | } | |||
3204 | } | |||
3205 | ||||
3206 | if (Invalid || Init.isInvalid()) | |||
3207 | return ExprError(); | |||
3208 | ||||
3209 | // Clear out the expressions within the designation. | |||
3210 | Desig.ClearExprs(*this); | |||
3211 | ||||
3212 | return DesignatedInitExpr::Create(Context, Designators, InitExpressions, | |||
3213 | EqualOrColonLoc, GNUSyntax, | |||
3214 | Init.getAs<Expr>()); | |||
3215 | } | |||
3216 | ||||
3217 | //===----------------------------------------------------------------------===// | |||
3218 | // Initialization entity | |||
3219 | //===----------------------------------------------------------------------===// | |||
3220 | ||||
3221 | InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index, | |||
3222 | const InitializedEntity &Parent) | |||
3223 | : Parent(&Parent), Index(Index) | |||
3224 | { | |||
3225 | if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) { | |||
3226 | Kind = EK_ArrayElement; | |||
3227 | Type = AT->getElementType(); | |||
3228 | } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) { | |||
3229 | Kind = EK_VectorElement; | |||
3230 | Type = VT->getElementType(); | |||
3231 | } else { | |||
3232 | const ComplexType *CT = Parent.getType()->getAs<ComplexType>(); | |||
3233 | assert(CT && "Unexpected type")((CT && "Unexpected type") ? static_cast<void> ( 0) : __assert_fail ("CT && \"Unexpected type\"", "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 3233, __PRETTY_FUNCTION__)); | |||
3234 | Kind = EK_ComplexElement; | |||
3235 | Type = CT->getElementType(); | |||
3236 | } | |||
3237 | } | |||
3238 | ||||
3239 | InitializedEntity | |||
3240 | InitializedEntity::InitializeBase(ASTContext &Context, | |||
3241 | const CXXBaseSpecifier *Base, | |||
3242 | bool IsInheritedVirtualBase, | |||
3243 | const InitializedEntity *Parent) { | |||
3244 | InitializedEntity Result; | |||
3245 | Result.Kind = EK_Base; | |||
3246 | Result.Parent = Parent; | |||
3247 | Result.Base = reinterpret_cast<uintptr_t>(Base); | |||
3248 | if (IsInheritedVirtualBase) | |||
3249 | Result.Base |= 0x01; | |||
3250 | ||||
3251 | Result.Type = Base->getType(); | |||
3252 | return Result; | |||
3253 | } | |||
3254 | ||||
3255 | DeclarationName InitializedEntity::getName() const { | |||
3256 | switch (getKind()) { | |||
3257 | case EK_Parameter: | |||
3258 | case EK_Parameter_CF_Audited: { | |||
3259 | ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1); | |||
3260 | return (D ? D->getDeclName() : DeclarationName()); | |||
3261 | } | |||
3262 | ||||
3263 | case EK_Variable: | |||
3264 | case EK_Member: | |||
3265 | case EK_Binding: | |||
3266 | return Variable.VariableOrMember->getDeclName(); | |||
3267 | ||||
3268 | case EK_LambdaCapture: | |||
3269 | return DeclarationName(Capture.VarID); | |||
3270 | ||||
3271 | case EK_Result: | |||
3272 | case EK_StmtExprResult: | |||
3273 | case EK_Exception: | |||
3274 | case EK_New: | |||
3275 | case EK_Temporary: | |||
3276 | case EK_Base: | |||
3277 | case EK_Delegating: | |||
3278 | case EK_ArrayElement: | |||
3279 | case EK_VectorElement: | |||
3280 | case EK_ComplexElement: | |||
3281 | case EK_BlockElement: | |||
3282 | case EK_LambdaToBlockConversionBlockElement: | |||
3283 | case EK_CompoundLiteralInit: | |||
3284 | case EK_RelatedResult: | |||
3285 | return DeclarationName(); | |||
3286 | } | |||
3287 | ||||
3288 | llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 3288); | |||
3289 | } | |||
3290 | ||||
3291 | ValueDecl *InitializedEntity::getDecl() const { | |||
3292 | switch (getKind()) { | |||
3293 | case EK_Variable: | |||
3294 | case EK_Member: | |||
3295 | case EK_Binding: | |||
3296 | return Variable.VariableOrMember; | |||
3297 | ||||
3298 | case EK_Parameter: | |||
3299 | case EK_Parameter_CF_Audited: | |||
3300 | return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1); | |||
3301 | ||||
3302 | case EK_Result: | |||
3303 | case EK_StmtExprResult: | |||
3304 | case EK_Exception: | |||
3305 | case EK_New: | |||
3306 | case EK_Temporary: | |||
3307 | case EK_Base: | |||
3308 | case EK_Delegating: | |||
3309 | case EK_ArrayElement: | |||
3310 | case EK_VectorElement: | |||
3311 | case EK_ComplexElement: | |||
3312 | case EK_BlockElement: | |||
3313 | case EK_LambdaToBlockConversionBlockElement: | |||
3314 | case EK_LambdaCapture: | |||
3315 | case EK_CompoundLiteralInit: | |||
3316 | case EK_RelatedResult: | |||
3317 | return nullptr; | |||
3318 | } | |||
3319 | ||||
3320 | llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 3320); | |||
3321 | } | |||
3322 | ||||
3323 | bool InitializedEntity::allowsNRVO() const { | |||
3324 | switch (getKind()) { | |||
3325 | case EK_Result: | |||
3326 | case EK_Exception: | |||
3327 | return LocAndNRVO.NRVO; | |||
3328 | ||||
3329 | case EK_StmtExprResult: | |||
3330 | case EK_Variable: | |||
3331 | case EK_Parameter: | |||
3332 | case EK_Parameter_CF_Audited: | |||
3333 | case EK_Member: | |||
3334 | case EK_Binding: | |||
3335 | case EK_New: | |||
3336 | case EK_Temporary: | |||
3337 | case EK_CompoundLiteralInit: | |||
3338 | case EK_Base: | |||
3339 | case EK_Delegating: | |||
3340 | case EK_ArrayElement: | |||
3341 | case EK_VectorElement: | |||
3342 | case EK_ComplexElement: | |||
3343 | case EK_BlockElement: | |||
3344 | case EK_LambdaToBlockConversionBlockElement: | |||
3345 | case EK_LambdaCapture: | |||
3346 | case EK_RelatedResult: | |||
3347 | break; | |||
3348 | } | |||
3349 | ||||
3350 | return false; | |||
3351 | } | |||
3352 | ||||
3353 | unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const { | |||
3354 | assert(getParent() != this)((getParent() != this) ? static_cast<void> (0) : __assert_fail ("getParent() != this", "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 3354, __PRETTY_FUNCTION__)); | |||
3355 | unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0; | |||
3356 | for (unsigned I = 0; I != Depth; ++I) | |||
3357 | OS << "`-"; | |||
3358 | ||||
3359 | switch (getKind()) { | |||
3360 | case EK_Variable: OS << "Variable"; break; | |||
3361 | case EK_Parameter: OS << "Parameter"; break; | |||
3362 | case EK_Parameter_CF_Audited: OS << "CF audited function Parameter"; | |||
3363 | break; | |||
3364 | case EK_Result: OS << "Result"; break; | |||
3365 | case EK_StmtExprResult: OS << "StmtExprResult"; break; | |||
3366 | case EK_Exception: OS << "Exception"; break; | |||
3367 | case EK_Member: OS << "Member"; break; | |||
3368 | case EK_Binding: OS << "Binding"; break; | |||
3369 | case EK_New: OS << "New"; break; | |||
3370 | case EK_Temporary: OS << "Temporary"; break; | |||
3371 | case EK_CompoundLiteralInit: OS << "CompoundLiteral";break; | |||
3372 | case EK_RelatedResult: OS << "RelatedResult"; break; | |||
3373 | case EK_Base: OS << "Base"; break; | |||
3374 | case EK_Delegating: OS << "Delegating"; break; | |||
3375 | case EK_ArrayElement: OS << "ArrayElement " << Index; break; | |||
3376 | case EK_VectorElement: OS << "VectorElement " << Index; break; | |||
3377 | case EK_ComplexElement: OS << "ComplexElement " << Index; break; | |||
3378 | case EK_BlockElement: OS << "Block"; break; | |||
3379 | case EK_LambdaToBlockConversionBlockElement: | |||
3380 | OS << "Block (lambda)"; | |||
3381 | break; | |||
3382 | case EK_LambdaCapture: | |||
3383 | OS << "LambdaCapture "; | |||
3384 | OS << DeclarationName(Capture.VarID); | |||
3385 | break; | |||
3386 | } | |||
3387 | ||||
3388 | if (auto *D = getDecl()) { | |||
3389 | OS << " "; | |||
3390 | D->printQualifiedName(OS); | |||
3391 | } | |||
3392 | ||||
3393 | OS << " '" << getType().getAsString() << "'\n"; | |||
3394 | ||||
3395 | return Depth + 1; | |||
3396 | } | |||
3397 | ||||
3398 | LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void InitializedEntity::dump() const { | |||
3399 | dumpImpl(llvm::errs()); | |||
3400 | } | |||
3401 | ||||
3402 | //===----------------------------------------------------------------------===// | |||
3403 | // Initialization sequence | |||
3404 | //===----------------------------------------------------------------------===// | |||
3405 | ||||
3406 | void InitializationSequence::Step::Destroy() { | |||
3407 | switch (Kind) { | |||
3408 | case SK_ResolveAddressOfOverloadedFunction: | |||
3409 | case SK_CastDerivedToBaseRValue: | |||
3410 | case SK_CastDerivedToBaseXValue: | |||
3411 | case SK_CastDerivedToBaseLValue: | |||
3412 | case SK_BindReference: | |||
3413 | case SK_BindReferenceToTemporary: | |||
3414 | case SK_FinalCopy: | |||
3415 | case SK_ExtraneousCopyToTemporary: | |||
3416 | case SK_UserConversion: | |||
3417 | case SK_QualificationConversionRValue: | |||
3418 | case SK_QualificationConversionXValue: | |||
3419 | case SK_QualificationConversionLValue: | |||
3420 | case SK_AtomicConversion: | |||
3421 | case SK_ListInitialization: | |||
3422 | case SK_UnwrapInitList: | |||
3423 | case SK_RewrapInitList: | |||
3424 | case SK_ConstructorInitialization: | |||
3425 | case SK_ConstructorInitializationFromList: | |||
3426 | case SK_ZeroInitialization: | |||
3427 | case SK_CAssignment: | |||
3428 | case SK_StringInit: | |||
3429 | case SK_ObjCObjectConversion: | |||
3430 | case SK_ArrayLoopIndex: | |||
3431 | case SK_ArrayLoopInit: | |||
3432 | case SK_ArrayInit: | |||
3433 | case SK_GNUArrayInit: | |||
3434 | case SK_ParenthesizedArrayInit: | |||
3435 | case SK_PassByIndirectCopyRestore: | |||
3436 | case SK_PassByIndirectRestore: | |||
3437 | case SK_ProduceObjCObject: | |||
3438 | case SK_StdInitializerList: | |||
3439 | case SK_StdInitializerListConstructorCall: | |||
3440 | case SK_OCLSamplerInit: | |||
3441 | case SK_OCLZeroOpaqueType: | |||
3442 | break; | |||
3443 | ||||
3444 | case SK_ConversionSequence: | |||
3445 | case SK_ConversionSequenceNoNarrowing: | |||
3446 | delete ICS; | |||
3447 | } | |||
3448 | } | |||
3449 | ||||
3450 | bool InitializationSequence::isDirectReferenceBinding() const { | |||
3451 | // There can be some lvalue adjustments after the SK_BindReference step. | |||
3452 | for (auto I = Steps.rbegin(); I != Steps.rend(); ++I) { | |||
3453 | if (I->Kind == SK_BindReference) | |||
3454 | return true; | |||
3455 | if (I->Kind == SK_BindReferenceToTemporary) | |||
3456 | return false; | |||
3457 | } | |||
3458 | return false; | |||
3459 | } | |||
3460 | ||||
3461 | bool InitializationSequence::isAmbiguous() const { | |||
3462 | if (!Failed()) | |||
3463 | return false; | |||
3464 | ||||
3465 | switch (getFailureKind()) { | |||
3466 | case FK_TooManyInitsForReference: | |||
3467 | case FK_ParenthesizedListInitForReference: | |||
3468 | case FK_ArrayNeedsInitList: | |||
3469 | case FK_ArrayNeedsInitListOrStringLiteral: | |||
3470 | case FK_ArrayNeedsInitListOrWideStringLiteral: | |||
3471 | case FK_NarrowStringIntoWideCharArray: | |||
3472 | case FK_WideStringIntoCharArray: | |||
3473 | case FK_IncompatWideStringIntoWideChar: | |||
3474 | case FK_PlainStringIntoUTF8Char: | |||
3475 | case FK_UTF8StringIntoPlainChar: | |||
3476 | case FK_AddressOfOverloadFailed: // FIXME: Could do better | |||
3477 | case FK_NonConstLValueReferenceBindingToTemporary: | |||
3478 | case FK_NonConstLValueReferenceBindingToBitfield: | |||
3479 | case FK_NonConstLValueReferenceBindingToVectorElement: | |||
3480 | case FK_NonConstLValueReferenceBindingToUnrelated: | |||
3481 | case FK_RValueReferenceBindingToLValue: | |||
3482 | case FK_ReferenceAddrspaceMismatchTemporary: | |||
3483 | case FK_ReferenceInitDropsQualifiers: | |||
3484 | case FK_ReferenceInitFailed: | |||
3485 | case FK_ConversionFailed: | |||
3486 | case FK_ConversionFromPropertyFailed: | |||
3487 | case FK_TooManyInitsForScalar: | |||
3488 | case FK_ParenthesizedListInitForScalar: | |||
3489 | case FK_ReferenceBindingToInitList: | |||
3490 | case FK_InitListBadDestinationType: | |||
3491 | case FK_DefaultInitOfConst: | |||
3492 | case FK_Incomplete: | |||
3493 | case FK_ArrayTypeMismatch: | |||
3494 | case FK_NonConstantArrayInit: | |||
3495 | case FK_ListInitializationFailed: | |||
3496 | case FK_VariableLengthArrayHasInitializer: | |||
3497 | case FK_PlaceholderType: | |||
3498 | case FK_ExplicitConstructor: | |||
3499 | case FK_AddressOfUnaddressableFunction: | |||
3500 | return false; | |||
3501 | ||||
3502 | case FK_ReferenceInitOverloadFailed: | |||
3503 | case FK_UserConversionOverloadFailed: | |||
3504 | case FK_ConstructorOverloadFailed: | |||
3505 | case FK_ListConstructorOverloadFailed: | |||
3506 | return FailedOverloadResult == OR_Ambiguous; | |||
3507 | } | |||
3508 | ||||
3509 | llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 3509); | |||
3510 | } | |||
3511 | ||||
3512 | bool InitializationSequence::isConstructorInitialization() const { | |||
3513 | return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization; | |||
3514 | } | |||
3515 | ||||
3516 | void | |||
3517 | InitializationSequence | |||
3518 | ::AddAddressOverloadResolutionStep(FunctionDecl *Function, | |||
3519 | DeclAccessPair Found, | |||
3520 | bool HadMultipleCandidates) { | |||
3521 | Step S; | |||
3522 | S.Kind = SK_ResolveAddressOfOverloadedFunction; | |||
3523 | S.Type = Function->getType(); | |||
3524 | S.Function.HadMultipleCandidates = HadMultipleCandidates; | |||
3525 | S.Function.Function = Function; | |||
3526 | S.Function.FoundDecl = Found; | |||
3527 | Steps.push_back(S); | |||
3528 | } | |||
3529 | ||||
3530 | void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType, | |||
3531 | ExprValueKind VK) { | |||
3532 | Step S; | |||
3533 | switch (VK) { | |||
3534 | case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break; | |||
3535 | case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break; | |||
3536 | case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break; | |||
3537 | } | |||
3538 | S.Type = BaseType; | |||
3539 | Steps.push_back(S); | |||
3540 | } | |||
3541 | ||||
3542 | void InitializationSequence::AddReferenceBindingStep(QualType T, | |||
3543 | bool BindingTemporary) { | |||
3544 | Step S; | |||
3545 | S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference; | |||
3546 | S.Type = T; | |||
3547 | Steps.push_back(S); | |||
3548 | } | |||
3549 | ||||
3550 | void InitializationSequence::AddFinalCopy(QualType T) { | |||
3551 | Step S; | |||
3552 | S.Kind = SK_FinalCopy; | |||
3553 | S.Type = T; | |||
3554 | Steps.push_back(S); | |||
3555 | } | |||
3556 | ||||
3557 | void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) { | |||
3558 | Step S; | |||
3559 | S.Kind = SK_ExtraneousCopyToTemporary; | |||
3560 | S.Type = T; | |||
3561 | Steps.push_back(S); | |||
3562 | } | |||
3563 | ||||
3564 | void | |||
3565 | InitializationSequence::AddUserConversionStep(FunctionDecl *Function, | |||
3566 | DeclAccessPair FoundDecl, | |||
3567 | QualType T, | |||
3568 | bool HadMultipleCandidates) { | |||
3569 | Step S; | |||
3570 | S.Kind = SK_UserConversion; | |||
3571 | S.Type = T; | |||
3572 | S.Function.HadMultipleCandidates = HadMultipleCandidates; | |||
3573 | S.Function.Function = Function; | |||
3574 | S.Function.FoundDecl = FoundDecl; | |||
3575 | Steps.push_back(S); | |||
3576 | } | |||
3577 | ||||
3578 | void InitializationSequence::AddQualificationConversionStep(QualType Ty, | |||
3579 | ExprValueKind VK) { | |||
3580 | Step S; | |||
3581 | S.Kind = SK_QualificationConversionRValue; // work around a gcc warning | |||
3582 | switch (VK) { | |||
3583 | case VK_RValue: | |||
3584 | S.Kind = SK_QualificationConversionRValue; | |||
3585 | break; | |||
3586 | case VK_XValue: | |||
3587 | S.Kind = SK_QualificationConversionXValue; | |||
3588 | break; | |||
3589 | case VK_LValue: | |||
3590 | S.Kind = SK_QualificationConversionLValue; | |||
3591 | break; | |||
3592 | } | |||
3593 | S.Type = Ty; | |||
3594 | Steps.push_back(S); | |||
3595 | } | |||
3596 | ||||
3597 | void InitializationSequence::AddAtomicConversionStep(QualType Ty) { | |||
3598 | Step S; | |||
3599 | S.Kind = SK_AtomicConversion; | |||
3600 | S.Type = Ty; | |||
3601 | Steps.push_back(S); | |||
3602 | } | |||
3603 | ||||
3604 | void InitializationSequence::AddConversionSequenceStep( | |||
3605 | const ImplicitConversionSequence &ICS, QualType T, | |||
3606 | bool TopLevelOfInitList) { | |||
3607 | Step S; | |||
3608 | S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing | |||
3609 | : SK_ConversionSequence; | |||
3610 | S.Type = T; | |||
3611 | S.ICS = new ImplicitConversionSequence(ICS); | |||
3612 | Steps.push_back(S); | |||
3613 | } | |||
3614 | ||||
3615 | void InitializationSequence::AddListInitializationStep(QualType T) { | |||
3616 | Step S; | |||
3617 | S.Kind = SK_ListInitialization; | |||
3618 | S.Type = T; | |||
3619 | Steps.push_back(S); | |||
3620 | } | |||
3621 | ||||
3622 | void InitializationSequence::AddConstructorInitializationStep( | |||
3623 | DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T, | |||
3624 | bool HadMultipleCandidates, bool FromInitList, bool AsInitList) { | |||
3625 | Step S; | |||
3626 | S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall | |||
3627 | : SK_ConstructorInitializationFromList | |||
3628 | : SK_ConstructorInitialization; | |||
3629 | S.Type = T; | |||
3630 | S.Function.HadMultipleCandidates = HadMultipleCandidates; | |||
3631 | S.Function.Function = Constructor; | |||
3632 | S.Function.FoundDecl = FoundDecl; | |||
3633 | Steps.push_back(S); | |||
3634 | } | |||
3635 | ||||
3636 | void InitializationSequence::AddZeroInitializationStep(QualType T) { | |||
3637 | Step S; | |||
3638 | S.Kind = SK_ZeroInitialization; | |||
3639 | S.Type = T; | |||
3640 | Steps.push_back(S); | |||
3641 | } | |||
3642 | ||||
3643 | void InitializationSequence::AddCAssignmentStep(QualType T) { | |||
3644 | Step S; | |||
3645 | S.Kind = SK_CAssignment; | |||
3646 | S.Type = T; | |||
3647 | Steps.push_back(S); | |||
3648 | } | |||
3649 | ||||
3650 | void InitializationSequence::AddStringInitStep(QualType T) { | |||
3651 | Step S; | |||
3652 | S.Kind = SK_StringInit; | |||
3653 | S.Type = T; | |||
3654 | Steps.push_back(S); | |||
3655 | } | |||
3656 | ||||
3657 | void InitializationSequence::AddObjCObjectConversionStep(QualType T) { | |||
3658 | Step S; | |||
3659 | S.Kind = SK_ObjCObjectConversion; | |||
3660 | S.Type = T; | |||
3661 | Steps.push_back(S); | |||
3662 | } | |||
3663 | ||||
3664 | void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) { | |||
3665 | Step S; | |||
3666 | S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit; | |||
3667 | S.Type = T; | |||
3668 | Steps.push_back(S); | |||
3669 | } | |||
3670 | ||||
3671 | void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) { | |||
3672 | Step S; | |||
3673 | S.Kind = SK_ArrayLoopIndex; | |||
3674 | S.Type = EltT; | |||
3675 | Steps.insert(Steps.begin(), S); | |||
3676 | ||||
3677 | S.Kind = SK_ArrayLoopInit; | |||
3678 | S.Type = T; | |||
3679 | Steps.push_back(S); | |||
3680 | } | |||
3681 | ||||
3682 | void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) { | |||
3683 | Step S; | |||
3684 | S.Kind = SK_ParenthesizedArrayInit; | |||
3685 | S.Type = T; | |||
3686 | Steps.push_back(S); | |||
3687 | } | |||
3688 | ||||
3689 | void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type, | |||
3690 | bool shouldCopy) { | |||
3691 | Step s; | |||
3692 | s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore | |||
3693 | : SK_PassByIndirectRestore); | |||
3694 | s.Type = type; | |||
3695 | Steps.push_back(s); | |||
3696 | } | |||
3697 | ||||
3698 | void InitializationSequence::AddProduceObjCObjectStep(QualType T) { | |||
3699 | Step S; | |||
3700 | S.Kind = SK_ProduceObjCObject; | |||
3701 | S.Type = T; | |||
3702 | Steps.push_back(S); | |||
3703 | } | |||
3704 | ||||
3705 | void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) { | |||
3706 | Step S; | |||
3707 | S.Kind = SK_StdInitializerList; | |||
3708 | S.Type = T; | |||
3709 | Steps.push_back(S); | |||
3710 | } | |||
3711 | ||||
3712 | void InitializationSequence::AddOCLSamplerInitStep(QualType T) { | |||
3713 | Step S; | |||
3714 | S.Kind = SK_OCLSamplerInit; | |||
3715 | S.Type = T; | |||
3716 | Steps.push_back(S); | |||
3717 | } | |||
3718 | ||||
3719 | void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T) { | |||
3720 | Step S; | |||
3721 | S.Kind = SK_OCLZeroOpaqueType; | |||
3722 | S.Type = T; | |||
3723 | Steps.push_back(S); | |||
3724 | } | |||
3725 | ||||
3726 | void InitializationSequence::RewrapReferenceInitList(QualType T, | |||
3727 | InitListExpr *Syntactic) { | |||
3728 | assert(Syntactic->getNumInits() == 1 &&((Syntactic->getNumInits() == 1 && "Can only rewrap trivial init lists." ) ? static_cast<void> (0) : __assert_fail ("Syntactic->getNumInits() == 1 && \"Can only rewrap trivial init lists.\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 3729, __PRETTY_FUNCTION__)) | |||
3729 | "Can only rewrap trivial init lists.")((Syntactic->getNumInits() == 1 && "Can only rewrap trivial init lists." ) ? static_cast<void> (0) : __assert_fail ("Syntactic->getNumInits() == 1 && \"Can only rewrap trivial init lists.\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 3729, __PRETTY_FUNCTION__)); | |||
3730 | Step S; | |||
3731 | S.Kind = SK_UnwrapInitList; | |||
3732 | S.Type = Syntactic->getInit(0)->getType(); | |||
3733 | Steps.insert(Steps.begin(), S); | |||
3734 | ||||
3735 | S.Kind = SK_RewrapInitList; | |||
3736 | S.Type = T; | |||
3737 | S.WrappingSyntacticList = Syntactic; | |||
3738 | Steps.push_back(S); | |||
3739 | } | |||
3740 | ||||
3741 | void InitializationSequence::SetOverloadFailure(FailureKind Failure, | |||
3742 | OverloadingResult Result) { | |||
3743 | setSequenceKind(FailedSequence); | |||
3744 | this->Failure = Failure; | |||
3745 | this->FailedOverloadResult = Result; | |||
3746 | } | |||
3747 | ||||
3748 | //===----------------------------------------------------------------------===// | |||
3749 | // Attempt initialization | |||
3750 | //===----------------------------------------------------------------------===// | |||
3751 | ||||
3752 | /// Tries to add a zero initializer. Returns true if that worked. | |||
3753 | static bool | |||
3754 | maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence, | |||
3755 | const InitializedEntity &Entity) { | |||
3756 | if (Entity.getKind() != InitializedEntity::EK_Variable) | |||
3757 | return false; | |||
3758 | ||||
3759 | VarDecl *VD = cast<VarDecl>(Entity.getDecl()); | |||
3760 | if (VD->getInit() || VD->getEndLoc().isMacroID()) | |||
3761 | return false; | |||
3762 | ||||
3763 | QualType VariableTy = VD->getType().getCanonicalType(); | |||
3764 | SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc()); | |||
3765 | std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc); | |||
3766 | if (!Init.empty()) { | |||
3767 | Sequence.AddZeroInitializationStep(Entity.getType()); | |||
3768 | Sequence.SetZeroInitializationFixit(Init, Loc); | |||
3769 | return true; | |||
3770 | } | |||
3771 | return false; | |||
3772 | } | |||
3773 | ||||
3774 | static void MaybeProduceObjCObject(Sema &S, | |||
3775 | InitializationSequence &Sequence, | |||
3776 | const InitializedEntity &Entity) { | |||
3777 | if (!S.getLangOpts().ObjCAutoRefCount) return; | |||
3778 | ||||
3779 | /// When initializing a parameter, produce the value if it's marked | |||
3780 | /// __attribute__((ns_consumed)). | |||
3781 | if (Entity.isParameterKind()) { | |||
3782 | if (!Entity.isParameterConsumed()) | |||
3783 | return; | |||
3784 | ||||
3785 | assert(Entity.getType()->isObjCRetainableType() &&((Entity.getType()->isObjCRetainableType() && "consuming an object of unretainable type?" ) ? static_cast<void> (0) : __assert_fail ("Entity.getType()->isObjCRetainableType() && \"consuming an object of unretainable type?\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 3786, __PRETTY_FUNCTION__)) | |||
3786 | "consuming an object of unretainable type?")((Entity.getType()->isObjCRetainableType() && "consuming an object of unretainable type?" ) ? static_cast<void> (0) : __assert_fail ("Entity.getType()->isObjCRetainableType() && \"consuming an object of unretainable type?\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 3786, __PRETTY_FUNCTION__)); | |||
3787 | Sequence.AddProduceObjCObjectStep(Entity.getType()); | |||
3788 | ||||
3789 | /// When initializing a return value, if the return type is a | |||
3790 | /// retainable type, then returns need to immediately retain the | |||
3791 | /// object. If an autorelease is required, it will be done at the | |||
3792 | /// last instant. | |||
3793 | } else if (Entity.getKind() == InitializedEntity::EK_Result || | |||
3794 | Entity.getKind() == InitializedEntity::EK_StmtExprResult) { | |||
3795 | if (!Entity.getType()->isObjCRetainableType()) | |||
3796 | return; | |||
3797 | ||||
3798 | Sequence.AddProduceObjCObjectStep(Entity.getType()); | |||
3799 | } | |||
3800 | } | |||
3801 | ||||
3802 | static void TryListInitialization(Sema &S, | |||
3803 | const InitializedEntity &Entity, | |||
3804 | const InitializationKind &Kind, | |||
3805 | InitListExpr *InitList, | |||
3806 | InitializationSequence &Sequence, | |||
3807 | bool TreatUnavailableAsInvalid); | |||
3808 | ||||
3809 | /// When initializing from init list via constructor, handle | |||
3810 | /// initialization of an object of type std::initializer_list<T>. | |||
3811 | /// | |||
3812 | /// \return true if we have handled initialization of an object of type | |||
3813 | /// std::initializer_list<T>, false otherwise. | |||
3814 | static bool TryInitializerListConstruction(Sema &S, | |||
3815 | InitListExpr *List, | |||
3816 | QualType DestType, | |||
3817 | InitializationSequence &Sequence, | |||
3818 | bool TreatUnavailableAsInvalid) { | |||
3819 | QualType E; | |||
3820 | if (!S.isStdInitializerList(DestType, &E)) | |||
3821 | return false; | |||
3822 | ||||
3823 | if (!S.isCompleteType(List->getExprLoc(), E)) { | |||
3824 | Sequence.setIncompleteTypeFailure(E); | |||
3825 | return true; | |||
3826 | } | |||
3827 | ||||
3828 | // Try initializing a temporary array from the init list. | |||
3829 | QualType ArrayType = S.Context.getConstantArrayType( | |||
3830 | E.withConst(), | |||
3831 | llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()), | |||
3832 | List->getNumInits()), | |||
3833 | nullptr, clang::ArrayType::Normal, 0); | |||
3834 | InitializedEntity HiddenArray = | |||
3835 | InitializedEntity::InitializeTemporary(ArrayType); | |||
3836 | InitializationKind Kind = InitializationKind::CreateDirectList( | |||
3837 | List->getExprLoc(), List->getBeginLoc(), List->getEndLoc()); | |||
3838 | TryListInitialization(S, HiddenArray, Kind, List, Sequence, | |||
3839 | TreatUnavailableAsInvalid); | |||
3840 | if (Sequence) | |||
3841 | Sequence.AddStdInitializerListConstructionStep(DestType); | |||
3842 | return true; | |||
3843 | } | |||
3844 | ||||
3845 | /// Determine if the constructor has the signature of a copy or move | |||
3846 | /// constructor for the type T of the class in which it was found. That is, | |||
3847 | /// determine if its first parameter is of type T or reference to (possibly | |||
3848 | /// cv-qualified) T. | |||
3849 | static bool hasCopyOrMoveCtorParam(ASTContext &Ctx, | |||
3850 | const ConstructorInfo &Info) { | |||
3851 | if (Info.Constructor->getNumParams() == 0) | |||
3852 | return false; | |||
3853 | ||||
3854 | QualType ParmT = | |||
3855 | Info.Constructor->getParamDecl(0)->getType().getNonReferenceType(); | |||
3856 | QualType ClassT = | |||
3857 | Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext())); | |||
3858 | ||||
3859 | return Ctx.hasSameUnqualifiedType(ParmT, ClassT); | |||
3860 | } | |||
3861 | ||||
3862 | static OverloadingResult | |||
3863 | ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc, | |||
3864 | MultiExprArg Args, | |||
3865 | OverloadCandidateSet &CandidateSet, | |||
3866 | QualType DestType, | |||
3867 | DeclContext::lookup_result Ctors, | |||
3868 | OverloadCandidateSet::iterator &Best, | |||
3869 | bool CopyInitializing, bool AllowExplicit, | |||
3870 | bool OnlyListConstructors, bool IsListInit, | |||
3871 | bool SecondStepOfCopyInit = false) { | |||
3872 | CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor); | |||
3873 | CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace()); | |||
3874 | ||||
3875 | for (NamedDecl *D : Ctors) { | |||
3876 | auto Info = getConstructorInfo(D); | |||
3877 | if (!Info.Constructor || Info.Constructor->isInvalidDecl()) | |||
3878 | continue; | |||
3879 | ||||
3880 | if (!AllowExplicit && Info.Constructor->isExplicit()) | |||
3881 | continue; | |||
3882 | ||||
3883 | if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor)) | |||
3884 | continue; | |||
3885 | ||||
3886 | // C++11 [over.best.ics]p4: | |||
3887 | // ... and the constructor or user-defined conversion function is a | |||
3888 | // candidate by | |||
3889 | // - 13.3.1.3, when the argument is the temporary in the second step | |||
3890 | // of a class copy-initialization, or | |||
3891 | // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here] | |||
3892 | // - the second phase of 13.3.1.7 when the initializer list has exactly | |||
3893 | // one element that is itself an initializer list, and the target is | |||
3894 | // the first parameter of a constructor of class X, and the conversion | |||
3895 | // is to X or reference to (possibly cv-qualified X), | |||
3896 | // user-defined conversion sequences are not considered. | |||
3897 | bool SuppressUserConversions = | |||
3898 | SecondStepOfCopyInit || | |||
3899 | (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) && | |||
3900 | hasCopyOrMoveCtorParam(S.Context, Info)); | |||
3901 | ||||
3902 | if (Info.ConstructorTmpl) | |||
3903 | S.AddTemplateOverloadCandidate( | |||
3904 | Info.ConstructorTmpl, Info.FoundDecl, | |||
3905 | /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions, | |||
3906 | /*PartialOverloading=*/false, AllowExplicit); | |||
3907 | else { | |||
3908 | // C++ [over.match.copy]p1: | |||
3909 | // - When initializing a temporary to be bound to the first parameter | |||
3910 | // of a constructor [for type T] that takes a reference to possibly | |||
3911 | // cv-qualified T as its first argument, called with a single | |||
3912 | // argument in the context of direct-initialization, explicit | |||
3913 | // conversion functions are also considered. | |||
3914 | // FIXME: What if a constructor template instantiates to such a signature? | |||
3915 | bool AllowExplicitConv = AllowExplicit && !CopyInitializing && | |||
3916 | Args.size() == 1 && | |||
3917 | hasCopyOrMoveCtorParam(S.Context, Info); | |||
3918 | S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args, | |||
3919 | CandidateSet, SuppressUserConversions, | |||
3920 | /*PartialOverloading=*/false, AllowExplicit, | |||
3921 | AllowExplicitConv); | |||
3922 | } | |||
3923 | } | |||
3924 | ||||
3925 | // FIXME: Work around a bug in C++17 guaranteed copy elision. | |||
3926 | // | |||
3927 | // When initializing an object of class type T by constructor | |||
3928 | // ([over.match.ctor]) or by list-initialization ([over.match.list]) | |||
3929 | // from a single expression of class type U, conversion functions of | |||
3930 | // U that convert to the non-reference type cv T are candidates. | |||
3931 | // Explicit conversion functions are only candidates during | |||
3932 | // direct-initialization. | |||
3933 | // | |||
3934 | // Note: SecondStepOfCopyInit is only ever true in this case when | |||
3935 | // evaluating whether to produce a C++98 compatibility warning. | |||
3936 | if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 && | |||
3937 | !SecondStepOfCopyInit) { | |||
3938 | Expr *Initializer = Args[0]; | |||
3939 | auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl(); | |||
3940 | if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) { | |||
3941 | const auto &Conversions = SourceRD->getVisibleConversionFunctions(); | |||
3942 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { | |||
3943 | NamedDecl *D = *I; | |||
3944 | CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); | |||
3945 | D = D->getUnderlyingDecl(); | |||
3946 | ||||
3947 | FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); | |||
3948 | CXXConversionDecl *Conv; | |||
3949 | if (ConvTemplate) | |||
3950 | Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); | |||
3951 | else | |||
3952 | Conv = cast<CXXConversionDecl>(D); | |||
3953 | ||||
3954 | if (AllowExplicit || !Conv->isExplicit()) { | |||
3955 | if (ConvTemplate) | |||
3956 | S.AddTemplateConversionCandidate( | |||
3957 | ConvTemplate, I.getPair(), ActingDC, Initializer, DestType, | |||
3958 | CandidateSet, AllowExplicit, AllowExplicit, | |||
3959 | /*AllowResultConversion*/ false); | |||
3960 | else | |||
3961 | S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer, | |||
3962 | DestType, CandidateSet, AllowExplicit, | |||
3963 | AllowExplicit, | |||
3964 | /*AllowResultConversion*/ false); | |||
3965 | } | |||
3966 | } | |||
3967 | } | |||
3968 | } | |||
3969 | ||||
3970 | // Perform overload resolution and return the result. | |||
3971 | return CandidateSet.BestViableFunction(S, DeclLoc, Best); | |||
3972 | } | |||
3973 | ||||
3974 | /// Attempt initialization by constructor (C++ [dcl.init]), which | |||
3975 | /// enumerates the constructors of the initialized entity and performs overload | |||
3976 | /// resolution to select the best. | |||
3977 | /// \param DestType The destination class type. | |||
3978 | /// \param DestArrayType The destination type, which is either DestType or | |||
3979 | /// a (possibly multidimensional) array of DestType. | |||
3980 | /// \param IsListInit Is this list-initialization? | |||
3981 | /// \param IsInitListCopy Is this non-list-initialization resulting from a | |||
3982 | /// list-initialization from {x} where x is the same | |||
3983 | /// type as the entity? | |||
3984 | static void TryConstructorInitialization(Sema &S, | |||
3985 | const InitializedEntity &Entity, | |||
3986 | const InitializationKind &Kind, | |||
3987 | MultiExprArg Args, QualType DestType, | |||
3988 | QualType DestArrayType, | |||
3989 | InitializationSequence &Sequence, | |||
3990 | bool IsListInit = false, | |||
3991 | bool IsInitListCopy = false) { | |||
3992 | assert(((!IsListInit && !IsInitListCopy) ||((((!IsListInit && !IsInitListCopy) || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && "IsListInit/IsInitListCopy must come with a single initializer list " "argument.") ? static_cast<void> (0) : __assert_fail ( "((!IsListInit && !IsInitListCopy) || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && \"IsListInit/IsInitListCopy must come with a single initializer list \" \"argument.\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 3995, __PRETTY_FUNCTION__)) | |||
3993 | (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&((((!IsListInit && !IsInitListCopy) || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && "IsListInit/IsInitListCopy must come with a single initializer list " "argument.") ? static_cast<void> (0) : __assert_fail ( "((!IsListInit && !IsInitListCopy) || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && \"IsListInit/IsInitListCopy must come with a single initializer list \" \"argument.\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 3995, __PRETTY_FUNCTION__)) | |||
3994 | "IsListInit/IsInitListCopy must come with a single initializer list "((((!IsListInit && !IsInitListCopy) || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && "IsListInit/IsInitListCopy must come with a single initializer list " "argument.") ? static_cast<void> (0) : __assert_fail ( "((!IsListInit && !IsInitListCopy) || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && \"IsListInit/IsInitListCopy must come with a single initializer list \" \"argument.\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 3995, __PRETTY_FUNCTION__)) | |||
3995 | "argument.")((((!IsListInit && !IsInitListCopy) || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && "IsListInit/IsInitListCopy must come with a single initializer list " "argument.") ? static_cast<void> (0) : __assert_fail ( "((!IsListInit && !IsInitListCopy) || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && \"IsListInit/IsInitListCopy must come with a single initializer list \" \"argument.\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 3995, __PRETTY_FUNCTION__)); | |||
3996 | InitListExpr *ILE = | |||
3997 | (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr; | |||
3998 | MultiExprArg UnwrappedArgs = | |||
3999 | ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args; | |||
4000 | ||||
4001 | // The type we're constructing needs to be complete. | |||
4002 | if (!S.isCompleteType(Kind.getLocation(), DestType)) { | |||
4003 | Sequence.setIncompleteTypeFailure(DestType); | |||
4004 | return; | |||
4005 | } | |||
4006 | ||||
4007 | // C++17 [dcl.init]p17: | |||
4008 | // - If the initializer expression is a prvalue and the cv-unqualified | |||
4009 | // version of the source type is the same class as the class of the | |||
4010 | // destination, the initializer expression is used to initialize the | |||
4011 | // destination object. | |||
4012 | // Per DR (no number yet), this does not apply when initializing a base | |||
4013 | // class or delegating to another constructor from a mem-initializer. | |||
4014 | // ObjC++: Lambda captured by the block in the lambda to block conversion | |||
4015 | // should avoid copy elision. | |||
4016 | if (S.getLangOpts().CPlusPlus17 && | |||
4017 | Entity.getKind() != InitializedEntity::EK_Base && | |||
4018 | Entity.getKind() != InitializedEntity::EK_Delegating && | |||
4019 | Entity.getKind() != | |||
4020 | InitializedEntity::EK_LambdaToBlockConversionBlockElement && | |||
4021 | UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isRValue() && | |||
4022 | S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) { | |||
4023 | // Convert qualifications if necessary. | |||
4024 | Sequence.AddQualificationConversionStep(DestType, VK_RValue); | |||
4025 | if (ILE) | |||
4026 | Sequence.RewrapReferenceInitList(DestType, ILE); | |||
4027 | return; | |||
4028 | } | |||
4029 | ||||
4030 | const RecordType *DestRecordType = DestType->getAs<RecordType>(); | |||
4031 | assert(DestRecordType && "Constructor initialization requires record type")((DestRecordType && "Constructor initialization requires record type" ) ? static_cast<void> (0) : __assert_fail ("DestRecordType && \"Constructor initialization requires record type\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 4031, __PRETTY_FUNCTION__)); | |||
4032 | CXXRecordDecl *DestRecordDecl | |||
4033 | = cast<CXXRecordDecl>(DestRecordType->getDecl()); | |||
4034 | ||||
4035 | // Build the candidate set directly in the initialization sequence | |||
4036 | // structure, so that it will persist if we fail. | |||
4037 | OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); | |||
4038 | ||||
4039 | // Determine whether we are allowed to call explicit constructors or | |||
4040 | // explicit conversion operators. | |||
4041 | bool AllowExplicit = Kind.AllowExplicit() || IsListInit; | |||
4042 | bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy; | |||
4043 | ||||
4044 | // - Otherwise, if T is a class type, constructors are considered. The | |||
4045 | // applicable constructors are enumerated, and the best one is chosen | |||
4046 | // through overload resolution. | |||
4047 | DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl); | |||
4048 | ||||
4049 | OverloadingResult Result = OR_No_Viable_Function; | |||
4050 | OverloadCandidateSet::iterator Best; | |||
4051 | bool AsInitializerList = false; | |||
4052 | ||||
4053 | // C++11 [over.match.list]p1, per DR1467: | |||
4054 | // When objects of non-aggregate type T are list-initialized, such that | |||
4055 | // 8.5.4 [dcl.init.list] specifies that overload resolution is performed | |||
4056 | // according to the rules in this section, overload resolution selects | |||
4057 | // the constructor in two phases: | |||
4058 | // | |||
4059 | // - Initially, the candidate functions are the initializer-list | |||
4060 | // constructors of the class T and the argument list consists of the | |||
4061 | // initializer list as a single argument. | |||
4062 | if (IsListInit) { | |||
4063 | AsInitializerList = true; | |||
4064 | ||||
4065 | // If the initializer list has no elements and T has a default constructor, | |||
4066 | // the first phase is omitted. | |||
4067 | if (!(UnwrappedArgs.empty() && DestRecordDecl->hasDefaultConstructor())) | |||
4068 | Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, | |||
4069 | CandidateSet, DestType, Ctors, Best, | |||
4070 | CopyInitialization, AllowExplicit, | |||
4071 | /*OnlyListConstructors=*/true, | |||
4072 | IsListInit); | |||
4073 | } | |||
4074 | ||||
4075 | // C++11 [over.match.list]p1: | |||
4076 | // - If no viable initializer-list constructor is found, overload resolution | |||
4077 | // is performed again, where the candidate functions are all the | |||
4078 | // constructors of the class T and the argument list consists of the | |||
4079 | // elements of the initializer list. | |||
4080 | if (Result == OR_No_Viable_Function) { | |||
4081 | AsInitializerList = false; | |||
4082 | Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs, | |||
4083 | CandidateSet, DestType, Ctors, Best, | |||
4084 | CopyInitialization, AllowExplicit, | |||
4085 | /*OnlyListConstructors=*/false, | |||
4086 | IsListInit); | |||
4087 | } | |||
4088 | if (Result) { | |||
4089 | Sequence.SetOverloadFailure(IsListInit ? | |||
4090 | InitializationSequence::FK_ListConstructorOverloadFailed : | |||
4091 | InitializationSequence::FK_ConstructorOverloadFailed, | |||
4092 | Result); | |||
4093 | return; | |||
4094 | } | |||
4095 | ||||
4096 | bool HadMultipleCandidates = (CandidateSet.size() > 1); | |||
4097 | ||||
4098 | // In C++17, ResolveConstructorOverload can select a conversion function | |||
4099 | // instead of a constructor. | |||
4100 | if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) { | |||
4101 | // Add the user-defined conversion step that calls the conversion function. | |||
4102 | QualType ConvType = CD->getConversionType(); | |||
4103 | assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&((S.Context.hasSameUnqualifiedType(ConvType, DestType) && "should not have selected this conversion function") ? static_cast <void> (0) : __assert_fail ("S.Context.hasSameUnqualifiedType(ConvType, DestType) && \"should not have selected this conversion function\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 4104, __PRETTY_FUNCTION__)) | |||
4104 | "should not have selected this conversion function")((S.Context.hasSameUnqualifiedType(ConvType, DestType) && "should not have selected this conversion function") ? static_cast <void> (0) : __assert_fail ("S.Context.hasSameUnqualifiedType(ConvType, DestType) && \"should not have selected this conversion function\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 4104, __PRETTY_FUNCTION__)); | |||
4105 | Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType, | |||
4106 | HadMultipleCandidates); | |||
4107 | if (!S.Context.hasSameType(ConvType, DestType)) | |||
4108 | Sequence.AddQualificationConversionStep(DestType, VK_RValue); | |||
4109 | if (IsListInit) | |||
4110 | Sequence.RewrapReferenceInitList(Entity.getType(), ILE); | |||
4111 | return; | |||
4112 | } | |||
4113 | ||||
4114 | // C++11 [dcl.init]p6: | |||
4115 | // If a program calls for the default initialization of an object | |||
4116 | // of a const-qualified type T, T shall be a class type with a | |||
4117 | // user-provided default constructor. | |||
4118 | // C++ core issue 253 proposal: | |||
4119 | // If the implicit default constructor initializes all subobjects, no | |||
4120 | // initializer should be required. | |||
4121 | // The 253 proposal is for example needed to process libstdc++ headers in 5.x. | |||
4122 | CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function); | |||
4123 | if (Kind.getKind() == InitializationKind::IK_Default && | |||
4124 | Entity.getType().isConstQualified()) { | |||
4125 | if (!CtorDecl->getParent()->allowConstDefaultInit()) { | |||
4126 | if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity)) | |||
4127 | Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); | |||
4128 | return; | |||
4129 | } | |||
4130 | } | |||
4131 | ||||
4132 | // C++11 [over.match.list]p1: | |||
4133 | // In copy-list-initialization, if an explicit constructor is chosen, the | |||
4134 | // initializer is ill-formed. | |||
4135 | if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) { | |||
4136 | Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor); | |||
4137 | return; | |||
4138 | } | |||
4139 | ||||
4140 | // Add the constructor initialization step. Any cv-qualification conversion is | |||
4141 | // subsumed by the initialization. | |||
4142 | Sequence.AddConstructorInitializationStep( | |||
4143 | Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates, | |||
4144 | IsListInit | IsInitListCopy, AsInitializerList); | |||
4145 | } | |||
4146 | ||||
4147 | static bool | |||
4148 | ResolveOverloadedFunctionForReferenceBinding(Sema &S, | |||
4149 | Expr *Initializer, | |||
4150 | QualType &SourceType, | |||
4151 | QualType &UnqualifiedSourceType, | |||
4152 | QualType UnqualifiedTargetType, | |||
4153 | InitializationSequence &Sequence) { | |||
4154 | if (S.Context.getCanonicalType(UnqualifiedSourceType) == | |||
4155 | S.Context.OverloadTy) { | |||
4156 | DeclAccessPair Found; | |||
4157 | bool HadMultipleCandidates = false; | |||
4158 | if (FunctionDecl *Fn | |||
4159 | = S.ResolveAddressOfOverloadedFunction(Initializer, | |||
4160 | UnqualifiedTargetType, | |||
4161 | false, Found, | |||
4162 | &HadMultipleCandidates)) { | |||
4163 | Sequence.AddAddressOverloadResolutionStep(Fn, Found, | |||
4164 | HadMultipleCandidates); | |||
4165 | SourceType = Fn->getType(); | |||
4166 | UnqualifiedSourceType = SourceType.getUnqualifiedType(); | |||
4167 | } else if (!UnqualifiedTargetType->isRecordType()) { | |||
4168 | Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); | |||
4169 | return true; | |||
4170 | } | |||
4171 | } | |||
4172 | return false; | |||
4173 | } | |||
4174 | ||||
4175 | static void TryReferenceInitializationCore(Sema &S, | |||
4176 | const InitializedEntity &Entity, | |||
4177 | const InitializationKind &Kind, | |||
4178 | Expr *Initializer, | |||
4179 | QualType cv1T1, QualType T1, | |||
4180 | Qualifiers T1Quals, | |||
4181 | QualType cv2T2, QualType T2, | |||
4182 | Qualifiers T2Quals, | |||
4183 | InitializationSequence &Sequence); | |||
4184 | ||||
4185 | static void TryValueInitialization(Sema &S, | |||
4186 | const InitializedEntity &Entity, | |||
4187 | const InitializationKind &Kind, | |||
4188 | InitializationSequence &Sequence, | |||
4189 | InitListExpr *InitList = nullptr); | |||
4190 | ||||
4191 | /// Attempt list initialization of a reference. | |||
4192 | static void TryReferenceListInitialization(Sema &S, | |||
4193 | const InitializedEntity &Entity, | |||
4194 | const InitializationKind &Kind, | |||
4195 | InitListExpr *InitList, | |||
4196 | InitializationSequence &Sequence, | |||
4197 | bool TreatUnavailableAsInvalid) { | |||
4198 | // First, catch C++03 where this isn't possible. | |||
4199 | if (!S.getLangOpts().CPlusPlus11) { | |||
4200 | Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList); | |||
4201 | return; | |||
4202 | } | |||
4203 | // Can't reference initialize a compound literal. | |||
4204 | if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) { | |||
4205 | Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList); | |||
4206 | return; | |||
4207 | } | |||
4208 | ||||
4209 | QualType DestType = Entity.getType(); | |||
4210 | QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType(); | |||
4211 | Qualifiers T1Quals; | |||
4212 | QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals); | |||
4213 | ||||
4214 | // Reference initialization via an initializer list works thus: | |||
4215 | // If the initializer list consists of a single element that is | |||
4216 | // reference-related to the referenced type, bind directly to that element | |||
4217 | // (possibly creating temporaries). | |||
4218 | // Otherwise, initialize a temporary with the initializer list and | |||
4219 | // bind to that. | |||
4220 | if (InitList->getNumInits() == 1) { | |||
4221 | Expr *Initializer = InitList->getInit(0); | |||
4222 | QualType cv2T2 = Initializer->getType(); | |||
4223 | Qualifiers T2Quals; | |||
4224 | QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals); | |||
4225 | ||||
4226 | // If this fails, creating a temporary wouldn't work either. | |||
4227 | if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2, | |||
4228 | T1, Sequence)) | |||
4229 | return; | |||
4230 | ||||
4231 | SourceLocation DeclLoc = Initializer->getBeginLoc(); | |||
4232 | Sema::ReferenceCompareResult RefRelationship | |||
4233 | = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2); | |||
4234 | if (RefRelationship >= Sema::Ref_Related) { | |||
4235 | // Try to bind the reference here. | |||
4236 | TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1, | |||
4237 | T1Quals, cv2T2, T2, T2Quals, Sequence); | |||
4238 | if (Sequence) | |||
4239 | Sequence.RewrapReferenceInitList(cv1T1, InitList); | |||
4240 | return; | |||
4241 | } | |||
4242 | ||||
4243 | // Update the initializer if we've resolved an overloaded function. | |||
4244 | if (Sequence.step_begin() != Sequence.step_end()) | |||
4245 | Sequence.RewrapReferenceInitList(cv1T1, InitList); | |||
4246 | } | |||
4247 | ||||
4248 | // Not reference-related. Create a temporary and bind to that. | |||
4249 | InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1); | |||
4250 | ||||
4251 | TryListInitialization(S, TempEntity, Kind, InitList, Sequence, | |||
4252 | TreatUnavailableAsInvalid); | |||
4253 | if (Sequence) { | |||
4254 | if (DestType->isRValueReferenceType() || | |||
4255 | (T1Quals.hasConst() && !T1Quals.hasVolatile())) | |||
4256 | Sequence.AddReferenceBindingStep(cv1T1, /*BindingTemporary=*/true); | |||
4257 | else | |||
4258 | Sequence.SetFailed( | |||
4259 | InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary); | |||
4260 | } | |||
4261 | } | |||
4262 | ||||
4263 | /// Attempt list initialization (C++0x [dcl.init.list]) | |||
4264 | static void TryListInitialization(Sema &S, | |||
4265 | const InitializedEntity &Entity, | |||
4266 | const InitializationKind &Kind, | |||
4267 | InitListExpr *InitList, | |||
4268 | InitializationSequence &Sequence, | |||
4269 | bool TreatUnavailableAsInvalid) { | |||
4270 | QualType DestType = Entity.getType(); | |||
4271 | ||||
4272 | // C++ doesn't allow scalar initialization with more than one argument. | |||
4273 | // But C99 complex numbers are scalars and it makes sense there. | |||
4274 | if (S.getLangOpts().CPlusPlus && DestType->isScalarType() && | |||
4275 | !DestType->isAnyComplexType() && InitList->getNumInits() > 1) { | |||
4276 | Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar); | |||
4277 | return; | |||
4278 | } | |||
4279 | if (DestType->isReferenceType()) { | |||
4280 | TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence, | |||
4281 | TreatUnavailableAsInvalid); | |||
4282 | return; | |||
4283 | } | |||
4284 | ||||
4285 | if (DestType->isRecordType() && | |||
4286 | !S.isCompleteType(InitList->getBeginLoc(), DestType)) { | |||
4287 | Sequence.setIncompleteTypeFailure(DestType); | |||
4288 | return; | |||
4289 | } | |||
4290 | ||||
4291 | // C++11 [dcl.init.list]p3, per DR1467: | |||
4292 | // - If T is a class type and the initializer list has a single element of | |||
4293 | // type cv U, where U is T or a class derived from T, the object is | |||
4294 | // initialized from that element (by copy-initialization for | |||
4295 | // copy-list-initialization, or by direct-initialization for | |||
4296 | // direct-list-initialization). | |||
4297 | // - Otherwise, if T is a character array and the initializer list has a | |||
4298 | // single element that is an appropriately-typed string literal | |||
4299 | // (8.5.2 [dcl.init.string]), initialization is performed as described | |||
4300 | // in that section. | |||
4301 | // - Otherwise, if T is an aggregate, [...] (continue below). | |||
4302 | if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) { | |||
4303 | if (DestType->isRecordType()) { | |||
4304 | QualType InitType = InitList->getInit(0)->getType(); | |||
4305 | if (S.Context.hasSameUnqualifiedType(InitType, DestType) || | |||
4306 | S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) { | |||
4307 | Expr *InitListAsExpr = InitList; | |||
4308 | TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType, | |||
4309 | DestType, Sequence, | |||
4310 | /*InitListSyntax*/false, | |||
4311 | /*IsInitListCopy*/true); | |||
4312 | return; | |||
4313 | } | |||
4314 | } | |||
4315 | if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) { | |||
4316 | Expr *SubInit[1] = {InitList->getInit(0)}; | |||
4317 | if (!isa<VariableArrayType>(DestAT) && | |||
4318 | IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) { | |||
4319 | InitializationKind SubKind = | |||
4320 | Kind.getKind() == InitializationKind::IK_DirectList | |||
4321 | ? InitializationKind::CreateDirect(Kind.getLocation(), | |||
4322 | InitList->getLBraceLoc(), | |||
4323 | InitList->getRBraceLoc()) | |||
4324 | : Kind; | |||
4325 | Sequence.InitializeFrom(S, Entity, SubKind, SubInit, | |||
4326 | /*TopLevelOfInitList*/ true, | |||
4327 | TreatUnavailableAsInvalid); | |||
4328 | ||||
4329 | // TryStringLiteralInitialization() (in InitializeFrom()) will fail if | |||
4330 | // the element is not an appropriately-typed string literal, in which | |||
4331 | // case we should proceed as in C++11 (below). | |||
4332 | if (Sequence) { | |||
4333 | Sequence.RewrapReferenceInitList(Entity.getType(), InitList); | |||
4334 | return; | |||
4335 | } | |||
4336 | } | |||
4337 | } | |||
4338 | } | |||
4339 | ||||
4340 | // C++11 [dcl.init.list]p3: | |||
4341 | // - If T is an aggregate, aggregate initialization is performed. | |||
4342 | if ((DestType->isRecordType() && !DestType->isAggregateType()) || | |||
4343 | (S.getLangOpts().CPlusPlus11 && | |||
4344 | S.isStdInitializerList(DestType, nullptr))) { | |||
4345 | if (S.getLangOpts().CPlusPlus11) { | |||
4346 | // - Otherwise, if the initializer list has no elements and T is a | |||
4347 | // class type with a default constructor, the object is | |||
4348 | // value-initialized. | |||
4349 | if (InitList->getNumInits() == 0) { | |||
4350 | CXXRecordDecl *RD = DestType->getAsCXXRecordDecl(); | |||
4351 | if (RD->hasDefaultConstructor()) { | |||
4352 | TryValueInitialization(S, Entity, Kind, Sequence, InitList); | |||
4353 | return; | |||
4354 | } | |||
4355 | } | |||
4356 | ||||
4357 | // - Otherwise, if T is a specialization of std::initializer_list<E>, | |||
4358 | // an initializer_list object constructed [...] | |||
4359 | if (TryInitializerListConstruction(S, InitList, DestType, Sequence, | |||
4360 | TreatUnavailableAsInvalid)) | |||
4361 | return; | |||
4362 | ||||
4363 | // - Otherwise, if T is a class type, constructors are considered. | |||
4364 | Expr *InitListAsExpr = InitList; | |||
4365 | TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType, | |||
4366 | DestType, Sequence, /*InitListSyntax*/true); | |||
4367 | } else | |||
4368 | Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType); | |||
4369 | return; | |||
4370 | } | |||
4371 | ||||
4372 | if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() && | |||
4373 | InitList->getNumInits() == 1) { | |||
4374 | Expr *E = InitList->getInit(0); | |||
4375 | ||||
4376 | // - Otherwise, if T is an enumeration with a fixed underlying type, | |||
4377 | // the initializer-list has a single element v, and the initialization | |||
4378 | // is direct-list-initialization, the object is initialized with the | |||
4379 | // value T(v); if a narrowing conversion is required to convert v to | |||
4380 | // the underlying type of T, the program is ill-formed. | |||
4381 | auto *ET = DestType->getAs<EnumType>(); | |||
4382 | if (S.getLangOpts().CPlusPlus17 && | |||
4383 | Kind.getKind() == InitializationKind::IK_DirectList && | |||
4384 | ET && ET->getDecl()->isFixed() && | |||
4385 | !S.Context.hasSameUnqualifiedType(E->getType(), DestType) && | |||
4386 | (E->getType()->isIntegralOrEnumerationType() || | |||
4387 | E->getType()->isFloatingType())) { | |||
4388 | // There are two ways that T(v) can work when T is an enumeration type. | |||
4389 | // If there is either an implicit conversion sequence from v to T or | |||
4390 | // a conversion function that can convert from v to T, then we use that. | |||
4391 | // Otherwise, if v is of integral, enumeration, or floating-point type, | |||
4392 | // it is converted to the enumeration type via its underlying type. | |||
4393 | // There is no overlap possible between these two cases (except when the | |||
4394 | // source value is already of the destination type), and the first | |||
4395 | // case is handled by the general case for single-element lists below. | |||
4396 | ImplicitConversionSequence ICS; | |||
4397 | ICS.setStandard(); | |||
4398 | ICS.Standard.setAsIdentityConversion(); | |||
4399 | if (!E->isRValue()) | |||
4400 | ICS.Standard.First = ICK_Lvalue_To_Rvalue; | |||
4401 | // If E is of a floating-point type, then the conversion is ill-formed | |||
4402 | // due to narrowing, but go through the motions in order to produce the | |||
4403 | // right diagnostic. | |||
4404 | ICS.Standard.Second = E->getType()->isFloatingType() | |||
4405 | ? ICK_Floating_Integral | |||
4406 | : ICK_Integral_Conversion; | |||
4407 | ICS.Standard.setFromType(E->getType()); | |||
4408 | ICS.Standard.setToType(0, E->getType()); | |||
4409 | ICS.Standard.setToType(1, DestType); | |||
4410 | ICS.Standard.setToType(2, DestType); | |||
4411 | Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2), | |||
4412 | /*TopLevelOfInitList*/true); | |||
4413 | Sequence.RewrapReferenceInitList(Entity.getType(), InitList); | |||
4414 | return; | |||
4415 | } | |||
4416 | ||||
4417 | // - Otherwise, if the initializer list has a single element of type E | |||
4418 | // [...references are handled above...], the object or reference is | |||
4419 | // initialized from that element (by copy-initialization for | |||
4420 | // copy-list-initialization, or by direct-initialization for | |||
4421 | // direct-list-initialization); if a narrowing conversion is required | |||
4422 | // to convert the element to T, the program is ill-formed. | |||
4423 | // | |||
4424 | // Per core-24034, this is direct-initialization if we were performing | |||
4425 | // direct-list-initialization and copy-initialization otherwise. | |||
4426 | // We can't use InitListChecker for this, because it always performs | |||
4427 | // copy-initialization. This only matters if we might use an 'explicit' | |||
4428 | // conversion operator, so we only need to handle the cases where the source | |||
4429 | // is of record type. | |||
4430 | if (InitList->getInit(0)->getType()->isRecordType()) { | |||
4431 | InitializationKind SubKind = | |||
4432 | Kind.getKind() == InitializationKind::IK_DirectList | |||
4433 | ? InitializationKind::CreateDirect(Kind.getLocation(), | |||
4434 | InitList->getLBraceLoc(), | |||
4435 | InitList->getRBraceLoc()) | |||
4436 | : Kind; | |||
4437 | Expr *SubInit[1] = { InitList->getInit(0) }; | |||
4438 | Sequence.InitializeFrom(S, Entity, SubKind, SubInit, | |||
4439 | /*TopLevelOfInitList*/true, | |||
4440 | TreatUnavailableAsInvalid); | |||
4441 | if (Sequence) | |||
4442 | Sequence.RewrapReferenceInitList(Entity.getType(), InitList); | |||
4443 | return; | |||
4444 | } | |||
4445 | } | |||
4446 | ||||
4447 | InitListChecker CheckInitList(S, Entity, InitList, | |||
4448 | DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid); | |||
4449 | if (CheckInitList.HadError()) { | |||
4450 | Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed); | |||
4451 | return; | |||
4452 | } | |||
4453 | ||||
4454 | // Add the list initialization step with the built init list. | |||
4455 | Sequence.AddListInitializationStep(DestType); | |||
4456 | } | |||
4457 | ||||
4458 | /// Try a reference initialization that involves calling a conversion | |||
4459 | /// function. | |||
4460 | static OverloadingResult TryRefInitWithConversionFunction( | |||
4461 | Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, | |||
4462 | Expr *Initializer, bool AllowRValues, bool IsLValueRef, | |||
4463 | InitializationSequence &Sequence) { | |||
4464 | QualType DestType = Entity.getType(); | |||
4465 | QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType(); | |||
4466 | QualType T1 = cv1T1.getUnqualifiedType(); | |||
4467 | QualType cv2T2 = Initializer->getType(); | |||
4468 | QualType T2 = cv2T2.getUnqualifiedType(); | |||
4469 | ||||
4470 | assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) &&((!S.CompareReferenceRelationship(Initializer->getBeginLoc (), T1, T2) && "Must have incompatible references when binding via conversion" ) ? static_cast<void> (0) : __assert_fail ("!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) && \"Must have incompatible references when binding via conversion\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 4471, __PRETTY_FUNCTION__)) | |||
4471 | "Must have incompatible references when binding via conversion")((!S.CompareReferenceRelationship(Initializer->getBeginLoc (), T1, T2) && "Must have incompatible references when binding via conversion" ) ? static_cast<void> (0) : __assert_fail ("!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) && \"Must have incompatible references when binding via conversion\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 4471, __PRETTY_FUNCTION__)); | |||
4472 | ||||
4473 | // Build the candidate set directly in the initialization sequence | |||
4474 | // structure, so that it will persist if we fail. | |||
4475 | OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); | |||
4476 | CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); | |||
4477 | ||||
4478 | // Determine whether we are allowed to call explicit conversion operators. | |||
4479 | // Note that none of [over.match.copy], [over.match.conv], nor | |||
4480 | // [over.match.ref] permit an explicit constructor to be chosen when | |||
4481 | // initializing a reference, not even for direct-initialization. | |||
4482 | bool AllowExplicitCtors = false; | |||
4483 | bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding(); | |||
4484 | ||||
4485 | const RecordType *T1RecordType = nullptr; | |||
4486 | if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) && | |||
4487 | S.isCompleteType(Kind.getLocation(), T1)) { | |||
4488 | // The type we're converting to is a class type. Enumerate its constructors | |||
4489 | // to see if there is a suitable conversion. | |||
4490 | CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl()); | |||
4491 | ||||
4492 | for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) { | |||
4493 | auto Info = getConstructorInfo(D); | |||
4494 | if (!Info.Constructor) | |||
4495 | continue; | |||
4496 | ||||
4497 | if (!Info.Constructor->isInvalidDecl() && | |||
4498 | Info.Constructor->isConvertingConstructor(AllowExplicitCtors)) { | |||
4499 | if (Info.ConstructorTmpl) | |||
4500 | S.AddTemplateOverloadCandidate( | |||
4501 | Info.ConstructorTmpl, Info.FoundDecl, | |||
4502 | /*ExplicitArgs*/ nullptr, Initializer, CandidateSet, | |||
4503 | /*SuppressUserConversions=*/true, | |||
4504 | /*PartialOverloading*/ false, AllowExplicitCtors); | |||
4505 | else | |||
4506 | S.AddOverloadCandidate( | |||
4507 | Info.Constructor, Info.FoundDecl, Initializer, CandidateSet, | |||
4508 | /*SuppressUserConversions=*/true, | |||
4509 | /*PartialOverloading*/ false, AllowExplicitCtors); | |||
4510 | } | |||
4511 | } | |||
4512 | } | |||
4513 | if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl()) | |||
4514 | return OR_No_Viable_Function; | |||
4515 | ||||
4516 | const RecordType *T2RecordType = nullptr; | |||
4517 | if ((T2RecordType = T2->getAs<RecordType>()) && | |||
4518 | S.isCompleteType(Kind.getLocation(), T2)) { | |||
4519 | // The type we're converting from is a class type, enumerate its conversion | |||
4520 | // functions. | |||
4521 | CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl()); | |||
4522 | ||||
4523 | const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); | |||
4524 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { | |||
4525 | NamedDecl *D = *I; | |||
4526 | CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); | |||
4527 | if (isa<UsingShadowDecl>(D)) | |||
4528 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); | |||
4529 | ||||
4530 | FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); | |||
4531 | CXXConversionDecl *Conv; | |||
4532 | if (ConvTemplate) | |||
4533 | Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); | |||
4534 | else | |||
4535 | Conv = cast<CXXConversionDecl>(D); | |||
4536 | ||||
4537 | // If the conversion function doesn't return a reference type, | |||
4538 | // it can't be considered for this conversion unless we're allowed to | |||
4539 | // consider rvalues. | |||
4540 | // FIXME: Do we need to make sure that we only consider conversion | |||
4541 | // candidates with reference-compatible results? That might be needed to | |||
4542 | // break recursion. | |||
4543 | if ((AllowExplicitConvs || !Conv->isExplicit()) && | |||
4544 | (AllowRValues || | |||
4545 | Conv->getConversionType()->isLValueReferenceType())) { | |||
4546 | if (ConvTemplate) | |||
4547 | S.AddTemplateConversionCandidate( | |||
4548 | ConvTemplate, I.getPair(), ActingDC, Initializer, DestType, | |||
4549 | CandidateSet, | |||
4550 | /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs); | |||
4551 | else | |||
4552 | S.AddConversionCandidate( | |||
4553 | Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet, | |||
4554 | /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs); | |||
4555 | } | |||
4556 | } | |||
4557 | } | |||
4558 | if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl()) | |||
4559 | return OR_No_Viable_Function; | |||
4560 | ||||
4561 | SourceLocation DeclLoc = Initializer->getBeginLoc(); | |||
4562 | ||||
4563 | // Perform overload resolution. If it fails, return the failed result. | |||
4564 | OverloadCandidateSet::iterator Best; | |||
4565 | if (OverloadingResult Result | |||
4566 | = CandidateSet.BestViableFunction(S, DeclLoc, Best)) | |||
4567 | return Result; | |||
4568 | ||||
4569 | FunctionDecl *Function = Best->Function; | |||
4570 | // This is the overload that will be used for this initialization step if we | |||
4571 | // use this initialization. Mark it as referenced. | |||
4572 | Function->setReferenced(); | |||
4573 | ||||
4574 | // Compute the returned type and value kind of the conversion. | |||
4575 | QualType cv3T3; | |||
4576 | if (isa<CXXConversionDecl>(Function)) | |||
4577 | cv3T3 = Function->getReturnType(); | |||
4578 | else | |||
4579 | cv3T3 = T1; | |||
4580 | ||||
4581 | ExprValueKind VK = VK_RValue; | |||
4582 | if (cv3T3->isLValueReferenceType()) | |||
4583 | VK = VK_LValue; | |||
4584 | else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>()) | |||
4585 | VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue; | |||
4586 | cv3T3 = cv3T3.getNonLValueExprType(S.Context); | |||
4587 | ||||
4588 | // Add the user-defined conversion step. | |||
4589 | bool HadMultipleCandidates = (CandidateSet.size() > 1); | |||
4590 | Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3, | |||
4591 | HadMultipleCandidates); | |||
4592 | ||||
4593 | // Determine whether we'll need to perform derived-to-base adjustments or | |||
4594 | // other conversions. | |||
4595 | Sema::ReferenceConversions RefConv; | |||
4596 | Sema::ReferenceCompareResult NewRefRelationship = | |||
4597 | S.CompareReferenceRelationship(DeclLoc, T1, cv3T3, &RefConv); | |||
4598 | ||||
4599 | // Add the final conversion sequence, if necessary. | |||
4600 | if (NewRefRelationship == Sema::Ref_Incompatible) { | |||
4601 | assert(!isa<CXXConstructorDecl>(Function) &&((!isa<CXXConstructorDecl>(Function) && "should not have conversion after constructor" ) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Function) && \"should not have conversion after constructor\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 4602, __PRETTY_FUNCTION__)) | |||
4602 | "should not have conversion after constructor")((!isa<CXXConstructorDecl>(Function) && "should not have conversion after constructor" ) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Function) && \"should not have conversion after constructor\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 4602, __PRETTY_FUNCTION__)); | |||
4603 | ||||
4604 | ImplicitConversionSequence ICS; | |||
4605 | ICS.setStandard(); | |||
4606 | ICS.Standard = Best->FinalConversion; | |||
4607 | Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2)); | |||
4608 | ||||
4609 | // Every implicit conversion results in a prvalue, except for a glvalue | |||
4610 | // derived-to-base conversion, which we handle below. | |||
4611 | cv3T3 = ICS.Standard.getToType(2); | |||
4612 | VK = VK_RValue; | |||
4613 | } | |||
4614 | ||||
4615 | // If the converted initializer is a prvalue, its type T4 is adjusted to | |||
4616 | // type "cv1 T4" and the temporary materialization conversion is applied. | |||
4617 | // | |||
4618 | // We adjust the cv-qualifications to match the reference regardless of | |||
4619 | // whether we have a prvalue so that the AST records the change. In this | |||
4620 | // case, T4 is "cv3 T3". | |||
4621 | QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers()); | |||
4622 | if (cv1T4.getQualifiers() != cv3T3.getQualifiers()) | |||
4623 | Sequence.AddQualificationConversionStep(cv1T4, VK); | |||
4624 | Sequence.AddReferenceBindingStep(cv1T4, VK == VK_RValue); | |||
4625 | VK = IsLValueRef ? VK_LValue : VK_XValue; | |||
4626 | ||||
4627 | if (RefConv & Sema::ReferenceConversions::DerivedToBase) | |||
4628 | Sequence.AddDerivedToBaseCastStep(cv1T1, VK); | |||
4629 | else if (RefConv & Sema::ReferenceConversions::ObjC) | |||
4630 | Sequence.AddObjCObjectConversionStep(cv1T1); | |||
4631 | else if (RefConv & Sema::ReferenceConversions::Function) | |||
4632 | Sequence.AddQualificationConversionStep(cv1T1, VK); | |||
4633 | else if (RefConv & Sema::ReferenceConversions::Qualification) { | |||
4634 | if (!S.Context.hasSameType(cv1T4, cv1T1)) | |||
4635 | Sequence.AddQualificationConversionStep(cv1T1, VK); | |||
4636 | } | |||
4637 | ||||
4638 | return OR_Success; | |||
4639 | } | |||
4640 | ||||
4641 | static void CheckCXX98CompatAccessibleCopy(Sema &S, | |||
4642 | const InitializedEntity &Entity, | |||
4643 | Expr *CurInitExpr); | |||
4644 | ||||
4645 | /// Attempt reference initialization (C++0x [dcl.init.ref]) | |||
4646 | static void TryReferenceInitialization(Sema &S, | |||
4647 | const InitializedEntity &Entity, | |||
4648 | const InitializationKind &Kind, | |||
4649 | Expr *Initializer, | |||
4650 | InitializationSequence &Sequence) { | |||
4651 | QualType DestType = Entity.getType(); | |||
4652 | QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType(); | |||
4653 | Qualifiers T1Quals; | |||
4654 | QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals); | |||
4655 | QualType cv2T2 = Initializer->getType(); | |||
4656 | Qualifiers T2Quals; | |||
4657 | QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals); | |||
4658 | ||||
4659 | // If the initializer is the address of an overloaded function, try | |||
4660 | // to resolve the overloaded function. If all goes well, T2 is the | |||
4661 | // type of the resulting function. | |||
4662 | if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2, | |||
4663 | T1, Sequence)) | |||
4664 | return; | |||
4665 | ||||
4666 | // Delegate everything else to a subfunction. | |||
4667 | TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1, | |||
4668 | T1Quals, cv2T2, T2, T2Quals, Sequence); | |||
4669 | } | |||
4670 | ||||
4671 | /// Determine whether an expression is a non-referenceable glvalue (one to | |||
4672 | /// which a reference can never bind). Attempting to bind a reference to | |||
4673 | /// such a glvalue will always create a temporary. | |||
4674 | static bool isNonReferenceableGLValue(Expr *E) { | |||
4675 | return E->refersToBitField() || E->refersToVectorElement(); | |||
4676 | } | |||
4677 | ||||
4678 | /// Reference initialization without resolving overloaded functions. | |||
4679 | static void TryReferenceInitializationCore(Sema &S, | |||
4680 | const InitializedEntity &Entity, | |||
4681 | const InitializationKind &Kind, | |||
4682 | Expr *Initializer, | |||
4683 | QualType cv1T1, QualType T1, | |||
4684 | Qualifiers T1Quals, | |||
4685 | QualType cv2T2, QualType T2, | |||
4686 | Qualifiers T2Quals, | |||
4687 | InitializationSequence &Sequence) { | |||
4688 | QualType DestType = Entity.getType(); | |||
4689 | SourceLocation DeclLoc = Initializer->getBeginLoc(); | |||
4690 | ||||
4691 | // Compute some basic properties of the types and the initializer. | |||
4692 | bool isLValueRef = DestType->isLValueReferenceType(); | |||
4693 | bool isRValueRef = !isLValueRef; | |||
4694 | Expr::Classification InitCategory = Initializer->Classify(S.Context); | |||
4695 | ||||
4696 | Sema::ReferenceConversions RefConv; | |||
4697 | Sema::ReferenceCompareResult RefRelationship = | |||
4698 | S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, &RefConv); | |||
4699 | ||||
4700 | // C++0x [dcl.init.ref]p5: | |||
4701 | // A reference to type "cv1 T1" is initialized by an expression of type | |||
4702 | // "cv2 T2" as follows: | |||
4703 | // | |||
4704 | // - If the reference is an lvalue reference and the initializer | |||
4705 | // expression | |||
4706 | // Note the analogous bullet points for rvalue refs to functions. Because | |||
4707 | // there are no function rvalues in C++, rvalue refs to functions are treated | |||
4708 | // like lvalue refs. | |||
4709 | OverloadingResult ConvOvlResult = OR_Success; | |||
4710 | bool T1Function = T1->isFunctionType(); | |||
4711 | if (isLValueRef || T1Function) { | |||
4712 | if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) && | |||
4713 | (RefRelationship == Sema::Ref_Compatible || | |||
4714 | (Kind.isCStyleOrFunctionalCast() && | |||
4715 | RefRelationship == Sema::Ref_Related))) { | |||
4716 | // - is an lvalue (but is not a bit-field), and "cv1 T1" is | |||
4717 | // reference-compatible with "cv2 T2," or | |||
4718 | if (RefConv & (Sema::ReferenceConversions::DerivedToBase | | |||
4719 | Sema::ReferenceConversions::ObjC)) { | |||
4720 | // If we're converting the pointee, add any qualifiers first; | |||
4721 | // these qualifiers must all be top-level, so just convert to "cv1 T2". | |||
4722 | if (RefConv & (Sema::ReferenceConversions::Qualification)) | |||
4723 | Sequence.AddQualificationConversionStep( | |||
4724 | S.Context.getQualifiedType(T2, T1Quals), | |||
4725 | Initializer->getValueKind()); | |||
4726 | if (RefConv & Sema::ReferenceConversions::DerivedToBase) | |||
4727 | Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue); | |||
4728 | else | |||
4729 | Sequence.AddObjCObjectConversionStep(cv1T1); | |||
4730 | } else if (RefConv & (Sema::ReferenceConversions::Qualification | | |||
4731 | Sema::ReferenceConversions::Function)) { | |||
4732 | // Perform a (possibly multi-level) qualification conversion. | |||
4733 | // FIXME: Should we use a different step kind for function conversions? | |||
4734 | Sequence.AddQualificationConversionStep(cv1T1, | |||
4735 | Initializer->getValueKind()); | |||
4736 | } | |||
4737 | ||||
4738 | // We only create a temporary here when binding a reference to a | |||
4739 | // bit-field or vector element. Those cases are't supposed to be | |||
4740 | // handled by this bullet, but the outcome is the same either way. | |||
4741 | Sequence.AddReferenceBindingStep(cv1T1, false); | |||
4742 | return; | |||
4743 | } | |||
4744 | ||||
4745 | // - has a class type (i.e., T2 is a class type), where T1 is not | |||
4746 | // reference-related to T2, and can be implicitly converted to an | |||
4747 | // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible | |||
4748 | // with "cv3 T3" (this conversion is selected by enumerating the | |||
4749 | // applicable conversion functions (13.3.1.6) and choosing the best | |||
4750 | // one through overload resolution (13.3)), | |||
4751 | // If we have an rvalue ref to function type here, the rhs must be | |||
4752 | // an rvalue. DR1287 removed the "implicitly" here. | |||
4753 | if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() && | |||
4754 | (isLValueRef || InitCategory.isRValue())) { | |||
4755 | ConvOvlResult = TryRefInitWithConversionFunction( | |||
4756 | S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef, | |||
4757 | /*IsLValueRef*/ isLValueRef, Sequence); | |||
4758 | if (ConvOvlResult == OR_Success) | |||
4759 | return; | |||
4760 | if (ConvOvlResult != OR_No_Viable_Function) | |||
4761 | Sequence.SetOverloadFailure( | |||
4762 | InitializationSequence::FK_ReferenceInitOverloadFailed, | |||
4763 | ConvOvlResult); | |||
4764 | } | |||
4765 | } | |||
4766 | ||||
4767 | // - Otherwise, the reference shall be an lvalue reference to a | |||
4768 | // non-volatile const type (i.e., cv1 shall be const), or the reference | |||
4769 | // shall be an rvalue reference. | |||
4770 | // For address spaces, we interpret this to mean that an addr space | |||
4771 | // of a reference "cv1 T1" is a superset of addr space of "cv2 T2". | |||
4772 | if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile() && | |||
4773 | T1Quals.isAddressSpaceSupersetOf(T2Quals))) { | |||
4774 | if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) | |||
4775 | Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); | |||
4776 | else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) | |||
4777 | Sequence.SetOverloadFailure( | |||
4778 | InitializationSequence::FK_ReferenceInitOverloadFailed, | |||
4779 | ConvOvlResult); | |||
4780 | else if (!InitCategory.isLValue()) | |||
4781 | Sequence.SetFailed( | |||
4782 | T1Quals.isAddressSpaceSupersetOf(T2Quals) | |||
4783 | ? InitializationSequence:: | |||
4784 | FK_NonConstLValueReferenceBindingToTemporary | |||
4785 | : InitializationSequence::FK_ReferenceInitDropsQualifiers); | |||
4786 | else { | |||
4787 | InitializationSequence::FailureKind FK; | |||
4788 | switch (RefRelationship) { | |||
4789 | case Sema::Ref_Compatible: | |||
4790 | if (Initializer->refersToBitField()) | |||
4791 | FK = InitializationSequence:: | |||
4792 | FK_NonConstLValueReferenceBindingToBitfield; | |||
4793 | else if (Initializer->refersToVectorElement()) | |||
4794 | FK = InitializationSequence:: | |||
4795 | FK_NonConstLValueReferenceBindingToVectorElement; | |||
4796 | else | |||
4797 | llvm_unreachable("unexpected kind of compatible initializer")::llvm::llvm_unreachable_internal("unexpected kind of compatible initializer" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 4797); | |||
4798 | break; | |||
4799 | case Sema::Ref_Related: | |||
4800 | FK = InitializationSequence::FK_ReferenceInitDropsQualifiers; | |||
4801 | break; | |||
4802 | case Sema::Ref_Incompatible: | |||
4803 | FK = InitializationSequence:: | |||
4804 | FK_NonConstLValueReferenceBindingToUnrelated; | |||
4805 | break; | |||
4806 | } | |||
4807 | Sequence.SetFailed(FK); | |||
4808 | } | |||
4809 | return; | |||
4810 | } | |||
4811 | ||||
4812 | // - If the initializer expression | |||
4813 | // - is an | |||
4814 | // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or | |||
4815 | // [1z] rvalue (but not a bit-field) or | |||
4816 | // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2" | |||
4817 | // | |||
4818 | // Note: functions are handled above and below rather than here... | |||
4819 | if (!T1Function && | |||
4820 | (RefRelationship == Sema::Ref_Compatible || | |||
4821 | (Kind.isCStyleOrFunctionalCast() && | |||
4822 | RefRelationship == Sema::Ref_Related)) && | |||
4823 | ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) || | |||
4824 | (InitCategory.isPRValue() && | |||
4825 | (S.getLangOpts().CPlusPlus17 || T2->isRecordType() || | |||
4826 | T2->isArrayType())))) { | |||
4827 | ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_RValue; | |||
4828 | if (InitCategory.isPRValue() && T2->isRecordType()) { | |||
4829 | // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the | |||
4830 | // compiler the freedom to perform a copy here or bind to the | |||
4831 | // object, while C++0x requires that we bind directly to the | |||
4832 | // object. Hence, we always bind to the object without making an | |||
4833 | // extra copy. However, in C++03 requires that we check for the | |||
4834 | // presence of a suitable copy constructor: | |||
4835 | // | |||
4836 | // The constructor that would be used to make the copy shall | |||
4837 | // be callable whether or not the copy is actually done. | |||
4838 | if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt) | |||
4839 | Sequence.AddExtraneousCopyToTemporary(cv2T2); | |||
4840 | else if (S.getLangOpts().CPlusPlus11) | |||
4841 | CheckCXX98CompatAccessibleCopy(S, Entity, Initializer); | |||
4842 | } | |||
4843 | ||||
4844 | // C++1z [dcl.init.ref]/5.2.1.2: | |||
4845 | // If the converted initializer is a prvalue, its type T4 is adjusted | |||
4846 | // to type "cv1 T4" and the temporary materialization conversion is | |||
4847 | // applied. | |||
4848 | // Postpone address space conversions to after the temporary materialization | |||
4849 | // conversion to allow creating temporaries in the alloca address space. | |||
4850 | auto T1QualsIgnoreAS = T1Quals; | |||
4851 | auto T2QualsIgnoreAS = T2Quals; | |||
4852 | if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) { | |||
4853 | T1QualsIgnoreAS.removeAddressSpace(); | |||
4854 | T2QualsIgnoreAS.removeAddressSpace(); | |||
4855 | } | |||
4856 | QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1QualsIgnoreAS); | |||
4857 | if (T1QualsIgnoreAS != T2QualsIgnoreAS) | |||
4858 | Sequence.AddQualificationConversionStep(cv1T4, ValueKind); | |||
4859 | Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_RValue); | |||
4860 | ValueKind = isLValueRef ? VK_LValue : VK_XValue; | |||
4861 | // Add addr space conversion if required. | |||
4862 | if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) { | |||
4863 | auto T4Quals = cv1T4.getQualifiers(); | |||
4864 | T4Quals.addAddressSpace(T1Quals.getAddressSpace()); | |||
4865 | QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals); | |||
4866 | Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind); | |||
4867 | cv1T4 = cv1T4WithAS; | |||
4868 | } | |||
4869 | ||||
4870 | // In any case, the reference is bound to the resulting glvalue (or to | |||
4871 | // an appropriate base class subobject). | |||
4872 | if (RefConv & Sema::ReferenceConversions::DerivedToBase) | |||
4873 | Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind); | |||
4874 | else if (RefConv & Sema::ReferenceConversions::ObjC) | |||
4875 | Sequence.AddObjCObjectConversionStep(cv1T1); | |||
4876 | else if (RefConv & Sema::ReferenceConversions::Qualification) { | |||
4877 | if (!S.Context.hasSameType(cv1T4, cv1T1)) | |||
4878 | Sequence.AddQualificationConversionStep(cv1T1, ValueKind); | |||
4879 | } | |||
4880 | return; | |||
4881 | } | |||
4882 | ||||
4883 | // - has a class type (i.e., T2 is a class type), where T1 is not | |||
4884 | // reference-related to T2, and can be implicitly converted to an | |||
4885 | // xvalue, class prvalue, or function lvalue of type "cv3 T3", | |||
4886 | // where "cv1 T1" is reference-compatible with "cv3 T3", | |||
4887 | // | |||
4888 | // DR1287 removes the "implicitly" here. | |||
4889 | if (T2->isRecordType()) { | |||
4890 | if (RefRelationship == Sema::Ref_Incompatible) { | |||
4891 | ConvOvlResult = TryRefInitWithConversionFunction( | |||
4892 | S, Entity, Kind, Initializer, /*AllowRValues*/ true, | |||
4893 | /*IsLValueRef*/ isLValueRef, Sequence); | |||
4894 | if (ConvOvlResult) | |||
4895 | Sequence.SetOverloadFailure( | |||
4896 | InitializationSequence::FK_ReferenceInitOverloadFailed, | |||
4897 | ConvOvlResult); | |||
4898 | ||||
4899 | return; | |||
4900 | } | |||
4901 | ||||
4902 | if (RefRelationship == Sema::Ref_Compatible && | |||
4903 | isRValueRef && InitCategory.isLValue()) { | |||
4904 | Sequence.SetFailed( | |||
4905 | InitializationSequence::FK_RValueReferenceBindingToLValue); | |||
4906 | return; | |||
4907 | } | |||
4908 | ||||
4909 | Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); | |||
4910 | return; | |||
4911 | } | |||
4912 | ||||
4913 | // - Otherwise, a temporary of type "cv1 T1" is created and initialized | |||
4914 | // from the initializer expression using the rules for a non-reference | |||
4915 | // copy-initialization (8.5). The reference is then bound to the | |||
4916 | // temporary. [...] | |||
4917 | ||||
4918 | // Ignore address space of reference type at this point and perform address | |||
4919 | // space conversion after the reference binding step. | |||
4920 | QualType cv1T1IgnoreAS = | |||
4921 | T1Quals.hasAddressSpace() | |||
4922 | ? S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace()) | |||
4923 | : cv1T1; | |||
4924 | ||||
4925 | InitializedEntity TempEntity = | |||
4926 | InitializedEntity::InitializeTemporary(cv1T1IgnoreAS); | |||
4927 | ||||
4928 | // FIXME: Why do we use an implicit conversion here rather than trying | |||
4929 | // copy-initialization? | |||
4930 | ImplicitConversionSequence ICS | |||
4931 | = S.TryImplicitConversion(Initializer, TempEntity.getType(), | |||
4932 | /*SuppressUserConversions=*/false, | |||
4933 | /*AllowExplicit=*/false, | |||
4934 | /*FIXME:InOverloadResolution=*/false, | |||
4935 | /*CStyle=*/Kind.isCStyleOrFunctionalCast(), | |||
4936 | /*AllowObjCWritebackConversion=*/false); | |||
4937 | ||||
4938 | if (ICS.isBad()) { | |||
4939 | // FIXME: Use the conversion function set stored in ICS to turn | |||
4940 | // this into an overloading ambiguity diagnostic. However, we need | |||
4941 | // to keep that set as an OverloadCandidateSet rather than as some | |||
4942 | // other kind of set. | |||
4943 | if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) | |||
4944 | Sequence.SetOverloadFailure( | |||
4945 | InitializationSequence::FK_ReferenceInitOverloadFailed, | |||
4946 | ConvOvlResult); | |||
4947 | else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) | |||
4948 | Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); | |||
4949 | else | |||
4950 | Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed); | |||
4951 | return; | |||
4952 | } else { | |||
4953 | Sequence.AddConversionSequenceStep(ICS, TempEntity.getType()); | |||
4954 | } | |||
4955 | ||||
4956 | // [...] If T1 is reference-related to T2, cv1 must be the | |||
4957 | // same cv-qualification as, or greater cv-qualification | |||
4958 | // than, cv2; otherwise, the program is ill-formed. | |||
4959 | unsigned T1CVRQuals = T1Quals.getCVRQualifiers(); | |||
4960 | unsigned T2CVRQuals = T2Quals.getCVRQualifiers(); | |||
4961 | if ((RefRelationship == Sema::Ref_Related && | |||
4962 | (T1CVRQuals | T2CVRQuals) != T1CVRQuals) || | |||
4963 | !T1Quals.isAddressSpaceSupersetOf(T2Quals)) { | |||
4964 | Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); | |||
4965 | return; | |||
4966 | } | |||
4967 | ||||
4968 | // [...] If T1 is reference-related to T2 and the reference is an rvalue | |||
4969 | // reference, the initializer expression shall not be an lvalue. | |||
4970 | if (RefRelationship >= Sema::Ref_Related && !isLValueRef && | |||
4971 | InitCategory.isLValue()) { | |||
4972 | Sequence.SetFailed( | |||
4973 | InitializationSequence::FK_RValueReferenceBindingToLValue); | |||
4974 | return; | |||
4975 | } | |||
4976 | ||||
4977 | Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true); | |||
4978 | ||||
4979 | if (T1Quals.hasAddressSpace()) { | |||
4980 | if (!Qualifiers::isAddressSpaceSupersetOf(T1Quals.getAddressSpace(), | |||
4981 | LangAS::Default)) { | |||
4982 | Sequence.SetFailed( | |||
4983 | InitializationSequence::FK_ReferenceAddrspaceMismatchTemporary); | |||
4984 | return; | |||
4985 | } | |||
4986 | Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue | |||
4987 | : VK_XValue); | |||
4988 | } | |||
4989 | } | |||
4990 | ||||
4991 | /// Attempt character array initialization from a string literal | |||
4992 | /// (C++ [dcl.init.string], C99 6.7.8). | |||
4993 | static void TryStringLiteralInitialization(Sema &S, | |||
4994 | const InitializedEntity &Entity, | |||
4995 | const InitializationKind &Kind, | |||
4996 | Expr *Initializer, | |||
4997 | InitializationSequence &Sequence) { | |||
4998 | Sequence.AddStringInitStep(Entity.getType()); | |||
4999 | } | |||
5000 | ||||
5001 | /// Attempt value initialization (C++ [dcl.init]p7). | |||
5002 | static void TryValueInitialization(Sema &S, | |||
5003 | const InitializedEntity &Entity, | |||
5004 | const InitializationKind &Kind, | |||
5005 | InitializationSequence &Sequence, | |||
5006 | InitListExpr *InitList) { | |||
5007 | assert((!InitList || InitList->getNumInits() == 0) &&(((!InitList || InitList->getNumInits() == 0) && "Shouldn't use value-init for non-empty init lists" ) ? static_cast<void> (0) : __assert_fail ("(!InitList || InitList->getNumInits() == 0) && \"Shouldn't use value-init for non-empty init lists\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 5008, __PRETTY_FUNCTION__)) | |||
5008 | "Shouldn't use value-init for non-empty init lists")(((!InitList || InitList->getNumInits() == 0) && "Shouldn't use value-init for non-empty init lists" ) ? static_cast<void> (0) : __assert_fail ("(!InitList || InitList->getNumInits() == 0) && \"Shouldn't use value-init for non-empty init lists\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 5008, __PRETTY_FUNCTION__)); | |||
5009 | ||||
5010 | // C++98 [dcl.init]p5, C++11 [dcl.init]p7: | |||
5011 | // | |||
5012 | // To value-initialize an object of type T means: | |||
5013 | QualType T = Entity.getType(); | |||
5014 | ||||
5015 | // -- if T is an array type, then each element is value-initialized; | |||
5016 | T = S.Context.getBaseElementType(T); | |||
5017 | ||||
5018 | if (const RecordType *RT = T->getAs<RecordType>()) { | |||
5019 | if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) { | |||
5020 | bool NeedZeroInitialization = true; | |||
5021 | // C++98: | |||
5022 | // -- if T is a class type (clause 9) with a user-declared constructor | |||
5023 | // (12.1), then the default constructor for T is called (and the | |||
5024 | // initialization is ill-formed if T has no accessible default | |||
5025 | // constructor); | |||
5026 | // C++11: | |||
5027 | // -- if T is a class type (clause 9) with either no default constructor | |||
5028 | // (12.1 [class.ctor]) or a default constructor that is user-provided | |||
5029 | // or deleted, then the object is default-initialized; | |||
5030 | // | |||
5031 | // Note that the C++11 rule is the same as the C++98 rule if there are no | |||
5032 | // defaulted or deleted constructors, so we just use it unconditionally. | |||
5033 | CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl); | |||
5034 | if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted()) | |||
5035 | NeedZeroInitialization = false; | |||
5036 | ||||
5037 | // -- if T is a (possibly cv-qualified) non-union class type without a | |||
5038 | // user-provided or deleted default constructor, then the object is | |||
5039 | // zero-initialized and, if T has a non-trivial default constructor, | |||
5040 | // default-initialized; | |||
5041 | // The 'non-union' here was removed by DR1502. The 'non-trivial default | |||
5042 | // constructor' part was removed by DR1507. | |||
5043 | if (NeedZeroInitialization) | |||
5044 | Sequence.AddZeroInitializationStep(Entity.getType()); | |||
5045 | ||||
5046 | // C++03: | |||
5047 | // -- if T is a non-union class type without a user-declared constructor, | |||
5048 | // then every non-static data member and base class component of T is | |||
5049 | // value-initialized; | |||
5050 | // [...] A program that calls for [...] value-initialization of an | |||
5051 | // entity of reference type is ill-formed. | |||
5052 | // | |||
5053 | // C++11 doesn't need this handling, because value-initialization does not | |||
5054 | // occur recursively there, and the implicit default constructor is | |||
5055 | // defined as deleted in the problematic cases. | |||
5056 | if (!S.getLangOpts().CPlusPlus11 && | |||
5057 | ClassDecl->hasUninitializedReferenceMember()) { | |||
5058 | Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference); | |||
5059 | return; | |||
5060 | } | |||
5061 | ||||
5062 | // If this is list-value-initialization, pass the empty init list on when | |||
5063 | // building the constructor call. This affects the semantics of a few | |||
5064 | // things (such as whether an explicit default constructor can be called). | |||
5065 | Expr *InitListAsExpr = InitList; | |||
5066 | MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0); | |||
5067 | bool InitListSyntax = InitList; | |||
5068 | ||||
5069 | // FIXME: Instead of creating a CXXConstructExpr of array type here, | |||
5070 | // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr. | |||
5071 | return TryConstructorInitialization( | |||
5072 | S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax); | |||
5073 | } | |||
5074 | } | |||
5075 | ||||
5076 | Sequence.AddZeroInitializationStep(Entity.getType()); | |||
5077 | } | |||
5078 | ||||
5079 | /// Attempt default initialization (C++ [dcl.init]p6). | |||
5080 | static void TryDefaultInitialization(Sema &S, | |||
5081 | const InitializedEntity &Entity, | |||
5082 | const InitializationKind &Kind, | |||
5083 | InitializationSequence &Sequence) { | |||
5084 | assert(Kind.getKind() == InitializationKind::IK_Default)((Kind.getKind() == InitializationKind::IK_Default) ? static_cast <void> (0) : __assert_fail ("Kind.getKind() == InitializationKind::IK_Default" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 5084, __PRETTY_FUNCTION__)); | |||
5085 | ||||
5086 | // C++ [dcl.init]p6: | |||
5087 | // To default-initialize an object of type T means: | |||
5088 | // - if T is an array type, each element is default-initialized; | |||
5089 | QualType DestType = S.Context.getBaseElementType(Entity.getType()); | |||
5090 | ||||
5091 | // - if T is a (possibly cv-qualified) class type (Clause 9), the default | |||
5092 | // constructor for T is called (and the initialization is ill-formed if | |||
5093 | // T has no accessible default constructor); | |||
5094 | if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) { | |||
5095 | TryConstructorInitialization(S, Entity, Kind, None, DestType, | |||
5096 | Entity.getType(), Sequence); | |||
5097 | return; | |||
5098 | } | |||
5099 | ||||
5100 | // - otherwise, no initialization is performed. | |||
5101 | ||||
5102 | // If a program calls for the default initialization of an object of | |||
5103 | // a const-qualified type T, T shall be a class type with a user-provided | |||
5104 | // default constructor. | |||
5105 | if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) { | |||
5106 | if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity)) | |||
5107 | Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); | |||
5108 | return; | |||
5109 | } | |||
5110 | ||||
5111 | // If the destination type has a lifetime property, zero-initialize it. | |||
5112 | if (DestType.getQualifiers().hasObjCLifetime()) { | |||
5113 | Sequence.AddZeroInitializationStep(Entity.getType()); | |||
5114 | return; | |||
5115 | } | |||
5116 | } | |||
5117 | ||||
5118 | /// Attempt a user-defined conversion between two types (C++ [dcl.init]), | |||
5119 | /// which enumerates all conversion functions and performs overload resolution | |||
5120 | /// to select the best. | |||
5121 | static void TryUserDefinedConversion(Sema &S, | |||
5122 | QualType DestType, | |||
5123 | const InitializationKind &Kind, | |||
5124 | Expr *Initializer, | |||
5125 | InitializationSequence &Sequence, | |||
5126 | bool TopLevelOfInitList) { | |||
5127 | assert(!DestType->isReferenceType() && "References are handled elsewhere")((!DestType->isReferenceType() && "References are handled elsewhere" ) ? static_cast<void> (0) : __assert_fail ("!DestType->isReferenceType() && \"References are handled elsewhere\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 5127, __PRETTY_FUNCTION__)); | |||
5128 | QualType SourceType = Initializer->getType(); | |||
5129 | assert((DestType->isRecordType() || SourceType->isRecordType()) &&(((DestType->isRecordType() || SourceType->isRecordType ()) && "Must have a class type to perform a user-defined conversion" ) ? static_cast<void> (0) : __assert_fail ("(DestType->isRecordType() || SourceType->isRecordType()) && \"Must have a class type to perform a user-defined conversion\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 5130, __PRETTY_FUNCTION__)) | |||
5130 | "Must have a class type to perform a user-defined conversion")(((DestType->isRecordType() || SourceType->isRecordType ()) && "Must have a class type to perform a user-defined conversion" ) ? static_cast<void> (0) : __assert_fail ("(DestType->isRecordType() || SourceType->isRecordType()) && \"Must have a class type to perform a user-defined conversion\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 5130, __PRETTY_FUNCTION__)); | |||
5131 | ||||
5132 | // Build the candidate set directly in the initialization sequence | |||
5133 | // structure, so that it will persist if we fail. | |||
5134 | OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); | |||
5135 | CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); | |||
5136 | CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace()); | |||
5137 | ||||
5138 | // Determine whether we are allowed to call explicit constructors or | |||
5139 | // explicit conversion operators. | |||
5140 | bool AllowExplicit = Kind.AllowExplicit(); | |||
5141 | ||||
5142 | if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) { | |||
5143 | // The type we're converting to is a class type. Enumerate its constructors | |||
5144 | // to see if there is a suitable conversion. | |||
5145 | CXXRecordDecl *DestRecordDecl | |||
5146 | = cast<CXXRecordDecl>(DestRecordType->getDecl()); | |||
5147 | ||||
5148 | // Try to complete the type we're converting to. | |||
5149 | if (S.isCompleteType(Kind.getLocation(), DestType)) { | |||
5150 | for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) { | |||
5151 | auto Info = getConstructorInfo(D); | |||
5152 | if (!Info.Constructor) | |||
5153 | continue; | |||
5154 | ||||
5155 | if (!Info.Constructor->isInvalidDecl() && | |||
5156 | Info.Constructor->isConvertingConstructor(AllowExplicit)) { | |||
5157 | if (Info.ConstructorTmpl) | |||
5158 | S.AddTemplateOverloadCandidate( | |||
5159 | Info.ConstructorTmpl, Info.FoundDecl, | |||
5160 | /*ExplicitArgs*/ nullptr, Initializer, CandidateSet, | |||
5161 | /*SuppressUserConversions=*/true, | |||
5162 | /*PartialOverloading*/ false, AllowExplicit); | |||
5163 | else | |||
5164 | S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, | |||
5165 | Initializer, CandidateSet, | |||
5166 | /*SuppressUserConversions=*/true, | |||
5167 | /*PartialOverloading*/ false, AllowExplicit); | |||
5168 | } | |||
5169 | } | |||
5170 | } | |||
5171 | } | |||
5172 | ||||
5173 | SourceLocation DeclLoc = Initializer->getBeginLoc(); | |||
5174 | ||||
5175 | if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) { | |||
5176 | // The type we're converting from is a class type, enumerate its conversion | |||
5177 | // functions. | |||
5178 | ||||
5179 | // We can only enumerate the conversion functions for a complete type; if | |||
5180 | // the type isn't complete, simply skip this step. | |||
5181 | if (S.isCompleteType(DeclLoc, SourceType)) { | |||
5182 | CXXRecordDecl *SourceRecordDecl | |||
5183 | = cast<CXXRecordDecl>(SourceRecordType->getDecl()); | |||
5184 | ||||
5185 | const auto &Conversions = | |||
5186 | SourceRecordDecl->getVisibleConversionFunctions(); | |||
5187 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { | |||
5188 | NamedDecl *D = *I; | |||
5189 | CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); | |||
5190 | if (isa<UsingShadowDecl>(D)) | |||
5191 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); | |||
5192 | ||||
5193 | FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); | |||
5194 | CXXConversionDecl *Conv; | |||
5195 | if (ConvTemplate) | |||
5196 | Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); | |||
5197 | else | |||
5198 | Conv = cast<CXXConversionDecl>(D); | |||
5199 | ||||
5200 | if (AllowExplicit || !Conv->isExplicit()) { | |||
5201 | if (ConvTemplate) | |||
5202 | S.AddTemplateConversionCandidate( | |||
5203 | ConvTemplate, I.getPair(), ActingDC, Initializer, DestType, | |||
5204 | CandidateSet, AllowExplicit, AllowExplicit); | |||
5205 | else | |||
5206 | S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer, | |||
5207 | DestType, CandidateSet, AllowExplicit, | |||
5208 | AllowExplicit); | |||
5209 | } | |||
5210 | } | |||
5211 | } | |||
5212 | } | |||
5213 | ||||
5214 | // Perform overload resolution. If it fails, return the failed result. | |||
5215 | OverloadCandidateSet::iterator Best; | |||
5216 | if (OverloadingResult Result | |||
5217 | = CandidateSet.BestViableFunction(S, DeclLoc, Best)) { | |||
5218 | Sequence.SetOverloadFailure( | |||
5219 | InitializationSequence::FK_UserConversionOverloadFailed, | |||
5220 | Result); | |||
5221 | return; | |||
5222 | } | |||
5223 | ||||
5224 | FunctionDecl *Function = Best->Function; | |||
5225 | Function->setReferenced(); | |||
5226 | bool HadMultipleCandidates = (CandidateSet.size() > 1); | |||
5227 | ||||
5228 | if (isa<CXXConstructorDecl>(Function)) { | |||
5229 | // Add the user-defined conversion step. Any cv-qualification conversion is | |||
5230 | // subsumed by the initialization. Per DR5, the created temporary is of the | |||
5231 | // cv-unqualified type of the destination. | |||
5232 | Sequence.AddUserConversionStep(Function, Best->FoundDecl, | |||
5233 | DestType.getUnqualifiedType(), | |||
5234 | HadMultipleCandidates); | |||
5235 | ||||
5236 | // C++14 and before: | |||
5237 | // - if the function is a constructor, the call initializes a temporary | |||
5238 | // of the cv-unqualified version of the destination type. The [...] | |||
5239 | // temporary [...] is then used to direct-initialize, according to the | |||
5240 | // rules above, the object that is the destination of the | |||
5241 | // copy-initialization. | |||
5242 | // Note that this just performs a simple object copy from the temporary. | |||
5243 | // | |||
5244 | // C++17: | |||
5245 | // - if the function is a constructor, the call is a prvalue of the | |||
5246 | // cv-unqualified version of the destination type whose return object | |||
5247 | // is initialized by the constructor. The call is used to | |||
5248 | // direct-initialize, according to the rules above, the object that | |||
5249 | // is the destination of the copy-initialization. | |||
5250 | // Therefore we need to do nothing further. | |||
5251 | // | |||
5252 | // FIXME: Mark this copy as extraneous. | |||
5253 | if (!S.getLangOpts().CPlusPlus17) | |||
5254 | Sequence.AddFinalCopy(DestType); | |||
5255 | else if (DestType.hasQualifiers()) | |||
5256 | Sequence.AddQualificationConversionStep(DestType, VK_RValue); | |||
5257 | return; | |||
5258 | } | |||
5259 | ||||
5260 | // Add the user-defined conversion step that calls the conversion function. | |||
5261 | QualType ConvType = Function->getCallResultType(); | |||
5262 | Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType, | |||
5263 | HadMultipleCandidates); | |||
5264 | ||||
5265 | if (ConvType->getAs<RecordType>()) { | |||
5266 | // The call is used to direct-initialize [...] the object that is the | |||
5267 | // destination of the copy-initialization. | |||
5268 | // | |||
5269 | // In C++17, this does not call a constructor if we enter /17.6.1: | |||
5270 | // - If the initializer expression is a prvalue and the cv-unqualified | |||
5271 | // version of the source type is the same as the class of the | |||
5272 | // destination [... do not make an extra copy] | |||
5273 | // | |||
5274 | // FIXME: Mark this copy as extraneous. | |||
5275 | if (!S.getLangOpts().CPlusPlus17 || | |||
5276 | Function->getReturnType()->isReferenceType() || | |||
5277 | !S.Context.hasSameUnqualifiedType(ConvType, DestType)) | |||
5278 | Sequence.AddFinalCopy(DestType); | |||
5279 | else if (!S.Context.hasSameType(ConvType, DestType)) | |||
5280 | Sequence.AddQualificationConversionStep(DestType, VK_RValue); | |||
5281 | return; | |||
5282 | } | |||
5283 | ||||
5284 | // If the conversion following the call to the conversion function | |||
5285 | // is interesting, add it as a separate step. | |||
5286 | if (Best->FinalConversion.First || Best->FinalConversion.Second || | |||
5287 | Best->FinalConversion.Third) { | |||
5288 | ImplicitConversionSequence ICS; | |||
5289 | ICS.setStandard(); | |||
5290 | ICS.Standard = Best->FinalConversion; | |||
5291 | Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList); | |||
5292 | } | |||
5293 | } | |||
5294 | ||||
5295 | /// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>, | |||
5296 | /// a function with a pointer return type contains a 'return false;' statement. | |||
5297 | /// In C++11, 'false' is not a null pointer, so this breaks the build of any | |||
5298 | /// code using that header. | |||
5299 | /// | |||
5300 | /// Work around this by treating 'return false;' as zero-initializing the result | |||
5301 | /// if it's used in a pointer-returning function in a system header. | |||
5302 | static bool isLibstdcxxPointerReturnFalseHack(Sema &S, | |||
5303 | const InitializedEntity &Entity, | |||
5304 | const Expr *Init) { | |||
5305 | return S.getLangOpts().CPlusPlus11 && | |||
5306 | Entity.getKind() == InitializedEntity::EK_Result && | |||
5307 | Entity.getType()->isPointerType() && | |||
5308 | isa<CXXBoolLiteralExpr>(Init) && | |||
5309 | !cast<CXXBoolLiteralExpr>(Init)->getValue() && | |||
5310 | S.getSourceManager().isInSystemHeader(Init->getExprLoc()); | |||
5311 | } | |||
5312 | ||||
5313 | /// The non-zero enum values here are indexes into diagnostic alternatives. | |||
5314 | enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar }; | |||
5315 | ||||
5316 | /// Determines whether this expression is an acceptable ICR source. | |||
5317 | static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e, | |||
5318 | bool isAddressOf, bool &isWeakAccess) { | |||
5319 | // Skip parens. | |||
5320 | e = e->IgnoreParens(); | |||
5321 | ||||
5322 | // Skip address-of nodes. | |||
5323 | if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) { | |||
5324 | if (op->getOpcode() == UO_AddrOf) | |||
5325 | return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true, | |||
5326 | isWeakAccess); | |||
5327 | ||||
5328 | // Skip certain casts. | |||
5329 | } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) { | |||
5330 | switch (ce->getCastKind()) { | |||
5331 | case CK_Dependent: | |||
5332 | case CK_BitCast: | |||
5333 | case CK_LValueBitCast: | |||
5334 | case CK_NoOp: | |||
5335 | return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess); | |||
5336 | ||||
5337 | case CK_ArrayToPointerDecay: | |||
5338 | return IIK_nonscalar; | |||
5339 | ||||
5340 | case CK_NullToPointer: | |||
5341 | return IIK_okay; | |||
5342 | ||||
5343 | default: | |||
5344 | break; | |||
5345 | } | |||
5346 | ||||
5347 | // If we have a declaration reference, it had better be a local variable. | |||
5348 | } else if (isa<DeclRefExpr>(e)) { | |||
5349 | // set isWeakAccess to true, to mean that there will be an implicit | |||
5350 | // load which requires a cleanup. | |||
5351 | if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak) | |||
5352 | isWeakAccess = true; | |||
5353 | ||||
5354 | if (!isAddressOf) return IIK_nonlocal; | |||
5355 | ||||
5356 | VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl()); | |||
5357 | if (!var) return IIK_nonlocal; | |||
5358 | ||||
5359 | return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal); | |||
5360 | ||||
5361 | // If we have a conditional operator, check both sides. | |||
5362 | } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) { | |||
5363 | if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf, | |||
5364 | isWeakAccess)) | |||
5365 | return iik; | |||
5366 | ||||
5367 | return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess); | |||
5368 | ||||
5369 | // These are never scalar. | |||
5370 | } else if (isa<ArraySubscriptExpr>(e)) { | |||
5371 | return IIK_nonscalar; | |||
5372 | ||||
5373 | // Otherwise, it needs to be a null pointer constant. | |||
5374 | } else { | |||
5375 | return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull) | |||
5376 | ? IIK_okay : IIK_nonlocal); | |||
5377 | } | |||
5378 | ||||
5379 | return IIK_nonlocal; | |||
5380 | } | |||
5381 | ||||
5382 | /// Check whether the given expression is a valid operand for an | |||
5383 | /// indirect copy/restore. | |||
5384 | static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) { | |||
5385 | assert(src->isRValue())((src->isRValue()) ? static_cast<void> (0) : __assert_fail ("src->isRValue()", "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 5385, __PRETTY_FUNCTION__)); | |||
5386 | bool isWeakAccess = false; | |||
5387 | InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess); | |||
5388 | // If isWeakAccess to true, there will be an implicit | |||
5389 | // load which requires a cleanup. | |||
5390 | if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess) | |||
5391 | S.Cleanup.setExprNeedsCleanups(true); | |||
5392 | ||||
5393 | if (iik == IIK_okay) return; | |||
5394 | ||||
5395 | S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback) | |||
5396 | << ((unsigned) iik - 1) // shift index into diagnostic explanations | |||
5397 | << src->getSourceRange(); | |||
5398 | } | |||
5399 | ||||
5400 | /// Determine whether we have compatible array types for the | |||
5401 | /// purposes of GNU by-copy array initialization. | |||
5402 | static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest, | |||
5403 | const ArrayType *Source) { | |||
5404 | // If the source and destination array types are equivalent, we're | |||
5405 | // done. | |||
5406 | if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0))) | |||
5407 | return true; | |||
5408 | ||||
5409 | // Make sure that the element types are the same. | |||
5410 | if (!Context.hasSameType(Dest->getElementType(), Source->getElementType())) | |||
5411 | return false; | |||
5412 | ||||
5413 | // The only mismatch we allow is when the destination is an | |||
5414 | // incomplete array type and the source is a constant array type. | |||
5415 | return Source->isConstantArrayType() && Dest->isIncompleteArrayType(); | |||
5416 | } | |||
5417 | ||||
5418 | static bool tryObjCWritebackConversion(Sema &S, | |||
5419 | InitializationSequence &Sequence, | |||
5420 | const InitializedEntity &Entity, | |||
5421 | Expr *Initializer) { | |||
5422 | bool ArrayDecay = false; | |||
5423 | QualType ArgType = Initializer->getType(); | |||
5424 | QualType ArgPointee; | |||
5425 | if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) { | |||
5426 | ArrayDecay = true; | |||
5427 | ArgPointee = ArgArrayType->getElementType(); | |||
5428 | ArgType = S.Context.getPointerType(ArgPointee); | |||
5429 | } | |||
5430 | ||||
5431 | // Handle write-back conversion. | |||
5432 | QualType ConvertedArgType; | |||
5433 | if (!S.isObjCWritebackConversion(ArgType, Entity.getType(), | |||
5434 | ConvertedArgType)) | |||
5435 | return false; | |||
5436 | ||||
5437 | // We should copy unless we're passing to an argument explicitly | |||
5438 | // marked 'out'. | |||
5439 | bool ShouldCopy = true; | |||
5440 | if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl())) | |||
5441 | ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); | |||
5442 | ||||
5443 | // Do we need an lvalue conversion? | |||
5444 | if (ArrayDecay || Initializer->isGLValue()) { | |||
5445 | ImplicitConversionSequence ICS; | |||
5446 | ICS.setStandard(); | |||
5447 | ICS.Standard.setAsIdentityConversion(); | |||
5448 | ||||
5449 | QualType ResultType; | |||
5450 | if (ArrayDecay) { | |||
5451 | ICS.Standard.First = ICK_Array_To_Pointer; | |||
5452 | ResultType = S.Context.getPointerType(ArgPointee); | |||
5453 | } else { | |||
5454 | ICS.Standard.First = ICK_Lvalue_To_Rvalue; | |||
5455 | ResultType = Initializer->getType().getNonLValueExprType(S.Context); | |||
5456 | } | |||
5457 | ||||
5458 | Sequence.AddConversionSequenceStep(ICS, ResultType); | |||
5459 | } | |||
5460 | ||||
5461 | Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy); | |||
5462 | return true; | |||
5463 | } | |||
5464 | ||||
5465 | static bool TryOCLSamplerInitialization(Sema &S, | |||
5466 | InitializationSequence &Sequence, | |||
5467 | QualType DestType, | |||
5468 | Expr *Initializer) { | |||
5469 | if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() || | |||
5470 | (!Initializer->isIntegerConstantExpr(S.Context) && | |||
5471 | !Initializer->getType()->isSamplerT())) | |||
5472 | return false; | |||
5473 | ||||
5474 | Sequence.AddOCLSamplerInitStep(DestType); | |||
5475 | return true; | |||
5476 | } | |||
5477 | ||||
5478 | static bool IsZeroInitializer(Expr *Initializer, Sema &S) { | |||
5479 | return Initializer->isIntegerConstantExpr(S.getASTContext()) && | |||
5480 | (Initializer->EvaluateKnownConstInt(S.getASTContext()) == 0); | |||
5481 | } | |||
5482 | ||||
5483 | static bool TryOCLZeroOpaqueTypeInitialization(Sema &S, | |||
5484 | InitializationSequence &Sequence, | |||
5485 | QualType DestType, | |||
5486 | Expr *Initializer) { | |||
5487 | if (!S.getLangOpts().OpenCL) | |||
5488 | return false; | |||
5489 | ||||
5490 | // | |||
5491 | // OpenCL 1.2 spec, s6.12.10 | |||
5492 | // | |||
5493 | // The event argument can also be used to associate the | |||
5494 | // async_work_group_copy with a previous async copy allowing | |||
5495 | // an event to be shared by multiple async copies; otherwise | |||
5496 | // event should be zero. | |||
5497 | // | |||
5498 | if (DestType->isEventT() || DestType->isQueueT()) { | |||
5499 | if (!IsZeroInitializer(Initializer, S)) | |||
5500 | return false; | |||
5501 | ||||
5502 | Sequence.AddOCLZeroOpaqueTypeStep(DestType); | |||
5503 | return true; | |||
5504 | } | |||
5505 | ||||
5506 | // We should allow zero initialization for all types defined in the | |||
5507 | // cl_intel_device_side_avc_motion_estimation extension, except | |||
5508 | // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t. | |||
5509 | if (S.getOpenCLOptions().isEnabled( | |||
5510 | "cl_intel_device_side_avc_motion_estimation") && | |||
5511 | DestType->isOCLIntelSubgroupAVCType()) { | |||
5512 | if (DestType->isOCLIntelSubgroupAVCMcePayloadType() || | |||
5513 | DestType->isOCLIntelSubgroupAVCMceResultType()) | |||
5514 | return false; | |||
5515 | if (!IsZeroInitializer(Initializer, S)) | |||
5516 | return false; | |||
5517 | ||||
5518 | Sequence.AddOCLZeroOpaqueTypeStep(DestType); | |||
5519 | return true; | |||
5520 | } | |||
5521 | ||||
5522 | return false; | |||
5523 | } | |||
5524 | ||||
5525 | InitializationSequence::InitializationSequence(Sema &S, | |||
5526 | const InitializedEntity &Entity, | |||
5527 | const InitializationKind &Kind, | |||
5528 | MultiExprArg Args, | |||
5529 | bool TopLevelOfInitList, | |||
5530 | bool TreatUnavailableAsInvalid) | |||
5531 | : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) { | |||
5532 | InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList, | |||
5533 | TreatUnavailableAsInvalid); | |||
5534 | } | |||
5535 | ||||
5536 | /// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the | |||
5537 | /// address of that function, this returns true. Otherwise, it returns false. | |||
5538 | static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) { | |||
5539 | auto *DRE = dyn_cast<DeclRefExpr>(E); | |||
5540 | if (!DRE || !isa<FunctionDecl>(DRE->getDecl())) | |||
5541 | return false; | |||
5542 | ||||
5543 | return !S.checkAddressOfFunctionIsAvailable( | |||
5544 | cast<FunctionDecl>(DRE->getDecl())); | |||
5545 | } | |||
5546 | ||||
5547 | /// Determine whether we can perform an elementwise array copy for this kind | |||
5548 | /// of entity. | |||
5549 | static bool canPerformArrayCopy(const InitializedEntity &Entity) { | |||
5550 | switch (Entity.getKind()) { | |||
5551 | case InitializedEntity::EK_LambdaCapture: | |||
5552 | // C++ [expr.prim.lambda]p24: | |||
5553 | // For array members, the array elements are direct-initialized in | |||
5554 | // increasing subscript order. | |||
5555 | return true; | |||
5556 | ||||
5557 | case InitializedEntity::EK_Variable: | |||
5558 | // C++ [dcl.decomp]p1: | |||
5559 | // [...] each element is copy-initialized or direct-initialized from the | |||
5560 | // corresponding element of the assignment-expression [...] | |||
5561 | return isa<DecompositionDecl>(Entity.getDecl()); | |||
5562 | ||||
5563 | case InitializedEntity::EK_Member: | |||
5564 | // C++ [class.copy.ctor]p14: | |||
5565 | // - if the member is an array, each element is direct-initialized with | |||
5566 | // the corresponding subobject of x | |||
5567 | return Entity.isImplicitMemberInitializer(); | |||
5568 | ||||
5569 | case InitializedEntity::EK_ArrayElement: | |||
5570 | // All the above cases are intended to apply recursively, even though none | |||
5571 | // of them actually say that. | |||
5572 | if (auto *E = Entity.getParent()) | |||
5573 | return canPerformArrayCopy(*E); | |||
5574 | break; | |||
5575 | ||||
5576 | default: | |||
5577 | break; | |||
5578 | } | |||
5579 | ||||
5580 | return false; | |||
5581 | } | |||
5582 | ||||
5583 | void InitializationSequence::InitializeFrom(Sema &S, | |||
5584 | const InitializedEntity &Entity, | |||
5585 | const InitializationKind &Kind, | |||
5586 | MultiExprArg Args, | |||
5587 | bool TopLevelOfInitList, | |||
5588 | bool TreatUnavailableAsInvalid) { | |||
5589 | ASTContext &Context = S.Context; | |||
5590 | ||||
5591 | // Eliminate non-overload placeholder types in the arguments. We | |||
5592 | // need to do this before checking whether types are dependent | |||
5593 | // because lowering a pseudo-object expression might well give us | |||
5594 | // something of dependent type. | |||
5595 | for (unsigned I = 0, E = Args.size(); I != E; ++I) | |||
5596 | if (Args[I]->getType()->isNonOverloadPlaceholderType()) { | |||
5597 | // FIXME: should we be doing this here? | |||
5598 | ExprResult result = S.CheckPlaceholderExpr(Args[I]); | |||
5599 | if (result.isInvalid()) { | |||
5600 | SetFailed(FK_PlaceholderType); | |||
5601 | return; | |||
5602 | } | |||
5603 | Args[I] = result.get(); | |||
5604 | } | |||
5605 | ||||
5606 | // C++0x [dcl.init]p16: | |||
5607 | // The semantics of initializers are as follows. The destination type is | |||
5608 | // the type of the object or reference being initialized and the source | |||
5609 | // type is the type of the initializer expression. The source type is not | |||
5610 | // defined when the initializer is a braced-init-list or when it is a | |||
5611 | // parenthesized list of expressions. | |||
5612 | QualType DestType = Entity.getType(); | |||
5613 | ||||
5614 | if (DestType->isDependentType() || | |||
5615 | Expr::hasAnyTypeDependentArguments(Args)) { | |||
5616 | SequenceKind = DependentSequence; | |||
5617 | return; | |||
5618 | } | |||
5619 | ||||
5620 | // Almost everything is a normal sequence. | |||
5621 | setSequenceKind(NormalSequence); | |||
5622 | ||||
5623 | QualType SourceType; | |||
5624 | Expr *Initializer = nullptr; | |||
5625 | if (Args.size() == 1) { | |||
5626 | Initializer = Args[0]; | |||
5627 | if (S.getLangOpts().ObjC) { | |||
5628 | if (S.CheckObjCBridgeRelatedConversions(Initializer->getBeginLoc(), | |||
5629 | DestType, Initializer->getType(), | |||
5630 | Initializer) || | |||
5631 | S.ConversionToObjCStringLiteralCheck(DestType, Initializer)) | |||
5632 | Args[0] = Initializer; | |||
5633 | } | |||
5634 | if (!isa<InitListExpr>(Initializer)) | |||
5635 | SourceType = Initializer->getType(); | |||
5636 | } | |||
5637 | ||||
5638 | // - If the initializer is a (non-parenthesized) braced-init-list, the | |||
5639 | // object is list-initialized (8.5.4). | |||
5640 | if (Kind.getKind() != InitializationKind::IK_Direct) { | |||
5641 | if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) { | |||
5642 | TryListInitialization(S, Entity, Kind, InitList, *this, | |||
5643 | TreatUnavailableAsInvalid); | |||
5644 | return; | |||
5645 | } | |||
5646 | } | |||
5647 | ||||
5648 | // - If the destination type is a reference type, see 8.5.3. | |||
5649 | if (DestType->isReferenceType()) { | |||
5650 | // C++0x [dcl.init.ref]p1: | |||
5651 | // A variable declared to be a T& or T&&, that is, "reference to type T" | |||
5652 | // (8.3.2), shall be initialized by an object, or function, of type T or | |||
5653 | // by an object that can be converted into a T. | |||
5654 | // (Therefore, multiple arguments are not permitted.) | |||
5655 | if (Args.size() != 1) | |||
5656 | SetFailed(FK_TooManyInitsForReference); | |||
5657 | // C++17 [dcl.init.ref]p5: | |||
5658 | // A reference [...] is initialized by an expression [...] as follows: | |||
5659 | // If the initializer is not an expression, presumably we should reject, | |||
5660 | // but the standard fails to actually say so. | |||
5661 | else if (isa<InitListExpr>(Args[0])) | |||
5662 | SetFailed(FK_ParenthesizedListInitForReference); | |||
5663 | else | |||
5664 | TryReferenceInitialization(S, Entity, Kind, Args[0], *this); | |||
5665 | return; | |||
5666 | } | |||
5667 | ||||
5668 | // - If the initializer is (), the object is value-initialized. | |||
5669 | if (Kind.getKind() == InitializationKind::IK_Value || | |||
5670 | (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) { | |||
5671 | TryValueInitialization(S, Entity, Kind, *this); | |||
5672 | return; | |||
5673 | } | |||
5674 | ||||
5675 | // Handle default initialization. | |||
5676 | if (Kind.getKind() == InitializationKind::IK_Default) { | |||
5677 | TryDefaultInitialization(S, Entity, Kind, *this); | |||
5678 | return; | |||
5679 | } | |||
5680 | ||||
5681 | // - If the destination type is an array of characters, an array of | |||
5682 | // char16_t, an array of char32_t, or an array of wchar_t, and the | |||
5683 | // initializer is a string literal, see 8.5.2. | |||
5684 | // - Otherwise, if the destination type is an array, the program is | |||
5685 | // ill-formed. | |||
5686 | if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) { | |||
5687 | if (Initializer && isa<VariableArrayType>(DestAT)) { | |||
5688 | SetFailed(FK_VariableLengthArrayHasInitializer); | |||
5689 | return; | |||
5690 | } | |||
5691 | ||||
5692 | if (Initializer) { | |||
5693 | switch (IsStringInit(Initializer, DestAT, Context)) { | |||
5694 | case SIF_None: | |||
5695 | TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this); | |||
5696 | return; | |||
5697 | case SIF_NarrowStringIntoWideChar: | |||
5698 | SetFailed(FK_NarrowStringIntoWideCharArray); | |||
5699 | return; | |||
5700 | case SIF_WideStringIntoChar: | |||
5701 | SetFailed(FK_WideStringIntoCharArray); | |||
5702 | return; | |||
5703 | case SIF_IncompatWideStringIntoWideChar: | |||
5704 | SetFailed(FK_IncompatWideStringIntoWideChar); | |||
5705 | return; | |||
5706 | case SIF_PlainStringIntoUTF8Char: | |||
5707 | SetFailed(FK_PlainStringIntoUTF8Char); | |||
5708 | return; | |||
5709 | case SIF_UTF8StringIntoPlainChar: | |||
5710 | SetFailed(FK_UTF8StringIntoPlainChar); | |||
5711 | return; | |||
5712 | case SIF_Other: | |||
5713 | break; | |||
5714 | } | |||
5715 | } | |||
5716 | ||||
5717 | // Some kinds of initialization permit an array to be initialized from | |||
5718 | // another array of the same type, and perform elementwise initialization. | |||
5719 | if (Initializer && isa<ConstantArrayType>(DestAT) && | |||
5720 | S.Context.hasSameUnqualifiedType(Initializer->getType(), | |||
5721 | Entity.getType()) && | |||
5722 | canPerformArrayCopy(Entity)) { | |||
5723 | // If source is a prvalue, use it directly. | |||
5724 | if (Initializer->getValueKind() == VK_RValue) { | |||
5725 | AddArrayInitStep(DestType, /*IsGNUExtension*/false); | |||
5726 | return; | |||
5727 | } | |||
5728 | ||||
5729 | // Emit element-at-a-time copy loop. | |||
5730 | InitializedEntity Element = | |||
5731 | InitializedEntity::InitializeElement(S.Context, 0, Entity); | |||
5732 | QualType InitEltT = | |||
5733 | Context.getAsArrayType(Initializer->getType())->getElementType(); | |||
5734 | OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT, | |||
5735 | Initializer->getValueKind(), | |||
5736 | Initializer->getObjectKind()); | |||
5737 | Expr *OVEAsExpr = &OVE; | |||
5738 | InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList, | |||
5739 | TreatUnavailableAsInvalid); | |||
5740 | if (!Failed()) | |||
5741 | AddArrayInitLoopStep(Entity.getType(), InitEltT); | |||
5742 | return; | |||
5743 | } | |||
5744 | ||||
5745 | // Note: as an GNU C extension, we allow initialization of an | |||
5746 | // array from a compound literal that creates an array of the same | |||
5747 | // type, so long as the initializer has no side effects. | |||
5748 | if (!S.getLangOpts().CPlusPlus && Initializer && | |||
5749 | isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) && | |||
5750 | Initializer->getType()->isArrayType()) { | |||
5751 | const ArrayType *SourceAT | |||
5752 | = Context.getAsArrayType(Initializer->getType()); | |||
5753 | if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT)) | |||
5754 | SetFailed(FK_ArrayTypeMismatch); | |||
5755 | else if (Initializer->HasSideEffects(S.Context)) | |||
5756 | SetFailed(FK_NonConstantArrayInit); | |||
5757 | else { | |||
5758 | AddArrayInitStep(DestType, /*IsGNUExtension*/true); | |||
5759 | } | |||
5760 | } | |||
5761 | // Note: as a GNU C++ extension, we allow list-initialization of a | |||
5762 | // class member of array type from a parenthesized initializer list. | |||
5763 | else if (S.getLangOpts().CPlusPlus && | |||
5764 | Entity.getKind() == InitializedEntity::EK_Member && | |||
5765 | Initializer && isa<InitListExpr>(Initializer)) { | |||
5766 | TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer), | |||
5767 | *this, TreatUnavailableAsInvalid); | |||
5768 | AddParenthesizedArrayInitStep(DestType); | |||
5769 | } else if (DestAT->getElementType()->isCharType()) | |||
5770 | SetFailed(FK_ArrayNeedsInitListOrStringLiteral); | |||
5771 | else if (IsWideCharCompatible(DestAT->getElementType(), Context)) | |||
5772 | SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral); | |||
5773 | else | |||
5774 | SetFailed(FK_ArrayNeedsInitList); | |||
5775 | ||||
5776 | return; | |||
5777 | } | |||
5778 | ||||
5779 | // Determine whether we should consider writeback conversions for | |||
5780 | // Objective-C ARC. | |||
5781 | bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount && | |||
5782 | Entity.isParameterKind(); | |||
5783 | ||||
5784 | if (TryOCLSamplerInitialization(S, *this, DestType, Initializer)) | |||
5785 | return; | |||
5786 | ||||
5787 | // We're at the end of the line for C: it's either a write-back conversion | |||
5788 | // or it's a C assignment. There's no need to check anything else. | |||
5789 | if (!S.getLangOpts().CPlusPlus) { | |||
5790 | // If allowed, check whether this is an Objective-C writeback conversion. | |||
5791 | if (allowObjCWritebackConversion && | |||
5792 | tryObjCWritebackConversion(S, *this, Entity, Initializer)) { | |||
5793 | return; | |||
5794 | } | |||
5795 | ||||
5796 | if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer)) | |||
5797 | return; | |||
5798 | ||||
5799 | // Handle initialization in C | |||
5800 | AddCAssignmentStep(DestType); | |||
5801 | MaybeProduceObjCObject(S, *this, Entity); | |||
5802 | return; | |||
5803 | } | |||
5804 | ||||
5805 | assert(S.getLangOpts().CPlusPlus)((S.getLangOpts().CPlusPlus) ? static_cast<void> (0) : __assert_fail ("S.getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 5805, __PRETTY_FUNCTION__)); | |||
5806 | ||||
5807 | // - If the destination type is a (possibly cv-qualified) class type: | |||
5808 | if (DestType->isRecordType()) { | |||
5809 | // - If the initialization is direct-initialization, or if it is | |||
5810 | // copy-initialization where the cv-unqualified version of the | |||
5811 | // source type is the same class as, or a derived class of, the | |||
5812 | // class of the destination, constructors are considered. [...] | |||
5813 | if (Kind.getKind() == InitializationKind::IK_Direct || | |||
5814 | (Kind.getKind() == InitializationKind::IK_Copy && | |||
5815 | (Context.hasSameUnqualifiedType(SourceType, DestType) || | |||
5816 | S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType, DestType)))) | |||
5817 | TryConstructorInitialization(S, Entity, Kind, Args, | |||
5818 | DestType, DestType, *this); | |||
5819 | // - Otherwise (i.e., for the remaining copy-initialization cases), | |||
5820 | // user-defined conversion sequences that can convert from the source | |||
5821 | // type to the destination type or (when a conversion function is | |||
5822 | // used) to a derived class thereof are enumerated as described in | |||
5823 | // 13.3.1.4, and the best one is chosen through overload resolution | |||
5824 | // (13.3). | |||
5825 | else | |||
5826 | TryUserDefinedConversion(S, DestType, Kind, Initializer, *this, | |||
5827 | TopLevelOfInitList); | |||
5828 | return; | |||
5829 | } | |||
5830 | ||||
5831 | assert(Args.size() >= 1 && "Zero-argument case handled above")((Args.size() >= 1 && "Zero-argument case handled above" ) ? static_cast<void> (0) : __assert_fail ("Args.size() >= 1 && \"Zero-argument case handled above\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 5831, __PRETTY_FUNCTION__)); | |||
5832 | ||||
5833 | // The remaining cases all need a source type. | |||
5834 | if (Args.size() > 1) { | |||
5835 | SetFailed(FK_TooManyInitsForScalar); | |||
5836 | return; | |||
5837 | } else if (isa<InitListExpr>(Args[0])) { | |||
5838 | SetFailed(FK_ParenthesizedListInitForScalar); | |||
5839 | return; | |||
5840 | } | |||
5841 | ||||
5842 | // - Otherwise, if the source type is a (possibly cv-qualified) class | |||
5843 | // type, conversion functions are considered. | |||
5844 | if (!SourceType.isNull() && SourceType->isRecordType()) { | |||
5845 | // For a conversion to _Atomic(T) from either T or a class type derived | |||
5846 | // from T, initialize the T object then convert to _Atomic type. | |||
5847 | bool NeedAtomicConversion = false; | |||
5848 | if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) { | |||
5849 | if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) || | |||
5850 | S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType, | |||
5851 | Atomic->getValueType())) { | |||
5852 | DestType = Atomic->getValueType(); | |||
5853 | NeedAtomicConversion = true; | |||
5854 | } | |||
5855 | } | |||
5856 | ||||
5857 | TryUserDefinedConversion(S, DestType, Kind, Initializer, *this, | |||
5858 | TopLevelOfInitList); | |||
5859 | MaybeProduceObjCObject(S, *this, Entity); | |||
5860 | if (!Failed() && NeedAtomicConversion) | |||
5861 | AddAtomicConversionStep(Entity.getType()); | |||
5862 | return; | |||
5863 | } | |||
5864 | ||||
5865 | // - Otherwise, the initial value of the object being initialized is the | |||
5866 | // (possibly converted) value of the initializer expression. Standard | |||
5867 | // conversions (Clause 4) will be used, if necessary, to convert the | |||
5868 | // initializer expression to the cv-unqualified version of the | |||
5869 | // destination type; no user-defined conversions are considered. | |||
5870 | ||||
5871 | ImplicitConversionSequence ICS | |||
5872 | = S.TryImplicitConversion(Initializer, DestType, | |||
5873 | /*SuppressUserConversions*/true, | |||
5874 | /*AllowExplicitConversions*/ false, | |||
5875 | /*InOverloadResolution*/ false, | |||
5876 | /*CStyle=*/Kind.isCStyleOrFunctionalCast(), | |||
5877 | allowObjCWritebackConversion); | |||
5878 | ||||
5879 | if (ICS.isStandard() && | |||
5880 | ICS.Standard.Second == ICK_Writeback_Conversion) { | |||
5881 | // Objective-C ARC writeback conversion. | |||
5882 | ||||
5883 | // We should copy unless we're passing to an argument explicitly | |||
5884 | // marked 'out'. | |||
5885 | bool ShouldCopy = true; | |||
5886 | if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl())) | |||
5887 | ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); | |||
5888 | ||||
5889 | // If there was an lvalue adjustment, add it as a separate conversion. | |||
5890 | if (ICS.Standard.First == ICK_Array_To_Pointer || | |||
5891 | ICS.Standard.First == ICK_Lvalue_To_Rvalue) { | |||
5892 | ImplicitConversionSequence LvalueICS; | |||
5893 | LvalueICS.setStandard(); | |||
5894 | LvalueICS.Standard.setAsIdentityConversion(); | |||
5895 | LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0)); | |||
5896 | LvalueICS.Standard.First = ICS.Standard.First; | |||
5897 | AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0)); | |||
5898 | } | |||
5899 | ||||
5900 | AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy); | |||
5901 | } else if (ICS.isBad()) { | |||
5902 | DeclAccessPair dap; | |||
5903 | if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) { | |||
5904 | AddZeroInitializationStep(Entity.getType()); | |||
5905 | } else if (Initializer->getType() == Context.OverloadTy && | |||
5906 | !S.ResolveAddressOfOverloadedFunction(Initializer, DestType, | |||
5907 | false, dap)) | |||
5908 | SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); | |||
5909 | else if (Initializer->getType()->isFunctionType() && | |||
5910 | isExprAnUnaddressableFunction(S, Initializer)) | |||
5911 | SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction); | |||
5912 | else | |||
5913 | SetFailed(InitializationSequence::FK_ConversionFailed); | |||
5914 | } else { | |||
5915 | AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList); | |||
5916 | ||||
5917 | MaybeProduceObjCObject(S, *this, Entity); | |||
5918 | } | |||
5919 | } | |||
5920 | ||||
5921 | InitializationSequence::~InitializationSequence() { | |||
5922 | for (auto &S : Steps) | |||
5923 | S.Destroy(); | |||
5924 | } | |||
5925 | ||||
5926 | //===----------------------------------------------------------------------===// | |||
5927 | // Perform initialization | |||
5928 | //===----------------------------------------------------------------------===// | |||
5929 | static Sema::AssignmentAction | |||
5930 | getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) { | |||
5931 | switch(Entity.getKind()) { | |||
5932 | case InitializedEntity::EK_Variable: | |||
5933 | case InitializedEntity::EK_New: | |||
5934 | case InitializedEntity::EK_Exception: | |||
5935 | case InitializedEntity::EK_Base: | |||
5936 | case InitializedEntity::EK_Delegating: | |||
5937 | return Sema::AA_Initializing; | |||
5938 | ||||
5939 | case InitializedEntity::EK_Parameter: | |||
5940 | if (Entity.getDecl() && | |||
5941 | isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext())) | |||
5942 | return Sema::AA_Sending; | |||
5943 | ||||
5944 | return Sema::AA_Passing; | |||
5945 | ||||
5946 | case InitializedEntity::EK_Parameter_CF_Audited: | |||
5947 | if (Entity.getDecl() && | |||
5948 | isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext())) | |||
5949 | return Sema::AA_Sending; | |||
5950 | ||||
5951 | return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited; | |||
5952 | ||||
5953 | case InitializedEntity::EK_Result: | |||
5954 | case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right. | |||
5955 | return Sema::AA_Returning; | |||
5956 | ||||
5957 | case InitializedEntity::EK_Temporary: | |||
5958 | case InitializedEntity::EK_RelatedResult: | |||
5959 | // FIXME: Can we tell apart casting vs. converting? | |||
5960 | return Sema::AA_Casting; | |||
5961 | ||||
5962 | case InitializedEntity::EK_Member: | |||
5963 | case InitializedEntity::EK_Binding: | |||
5964 | case InitializedEntity::EK_ArrayElement: | |||
5965 | case InitializedEntity::EK_VectorElement: | |||
5966 | case InitializedEntity::EK_ComplexElement: | |||
5967 | case InitializedEntity::EK_BlockElement: | |||
5968 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: | |||
5969 | case InitializedEntity::EK_LambdaCapture: | |||
5970 | case InitializedEntity::EK_CompoundLiteralInit: | |||
5971 | return Sema::AA_Initializing; | |||
5972 | } | |||
5973 | ||||
5974 | llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 5974); | |||
5975 | } | |||
5976 | ||||
5977 | /// Whether we should bind a created object as a temporary when | |||
5978 | /// initializing the given entity. | |||
5979 | static bool shouldBindAsTemporary(const InitializedEntity &Entity) { | |||
5980 | switch (Entity.getKind()) { | |||
5981 | case InitializedEntity::EK_ArrayElement: | |||
5982 | case InitializedEntity::EK_Member: | |||
5983 | case InitializedEntity::EK_Result: | |||
5984 | case InitializedEntity::EK_StmtExprResult: | |||
5985 | case InitializedEntity::EK_New: | |||
5986 | case InitializedEntity::EK_Variable: | |||
5987 | case InitializedEntity::EK_Base: | |||
5988 | case InitializedEntity::EK_Delegating: | |||
5989 | case InitializedEntity::EK_VectorElement: | |||
5990 | case InitializedEntity::EK_ComplexElement: | |||
5991 | case InitializedEntity::EK_Exception: | |||
5992 | case InitializedEntity::EK_BlockElement: | |||
5993 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: | |||
5994 | case InitializedEntity::EK_LambdaCapture: | |||
5995 | case InitializedEntity::EK_CompoundLiteralInit: | |||
5996 | return false; | |||
5997 | ||||
5998 | case InitializedEntity::EK_Parameter: | |||
5999 | case InitializedEntity::EK_Parameter_CF_Audited: | |||
6000 | case InitializedEntity::EK_Temporary: | |||
6001 | case InitializedEntity::EK_RelatedResult: | |||
6002 | case InitializedEntity::EK_Binding: | |||
6003 | return true; | |||
6004 | } | |||
6005 | ||||
6006 | llvm_unreachable("missed an InitializedEntity kind?")::llvm::llvm_unreachable_internal("missed an InitializedEntity kind?" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 6006); | |||
6007 | } | |||
6008 | ||||
6009 | /// Whether the given entity, when initialized with an object | |||
6010 | /// created for that initialization, requires destruction. | |||
6011 | static bool shouldDestroyEntity(const InitializedEntity &Entity) { | |||
6012 | switch (Entity.getKind()) { | |||
6013 | case InitializedEntity::EK_Result: | |||
6014 | case InitializedEntity::EK_StmtExprResult: | |||
6015 | case InitializedEntity::EK_New: | |||
6016 | case InitializedEntity::EK_Base: | |||
6017 | case InitializedEntity::EK_Delegating: | |||
6018 | case InitializedEntity::EK_VectorElement: | |||
6019 | case InitializedEntity::EK_ComplexElement: | |||
6020 | case InitializedEntity::EK_BlockElement: | |||
6021 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: | |||
6022 | case InitializedEntity::EK_LambdaCapture: | |||
6023 | return false; | |||
6024 | ||||
6025 | case InitializedEntity::EK_Member: | |||
6026 | case InitializedEntity::EK_Binding: | |||
6027 | case InitializedEntity::EK_Variable: | |||
6028 | case InitializedEntity::EK_Parameter: | |||
6029 | case InitializedEntity::EK_Parameter_CF_Audited: | |||
6030 | case InitializedEntity::EK_Temporary: | |||
6031 | case InitializedEntity::EK_ArrayElement: | |||
6032 | case InitializedEntity::EK_Exception: | |||
6033 | case InitializedEntity::EK_CompoundLiteralInit: | |||
6034 | case InitializedEntity::EK_RelatedResult: | |||
6035 | return true; | |||
6036 | } | |||
6037 | ||||
6038 | llvm_unreachable("missed an InitializedEntity kind?")::llvm::llvm_unreachable_internal("missed an InitializedEntity kind?" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 6038); | |||
6039 | } | |||
6040 | ||||
6041 | /// Get the location at which initialization diagnostics should appear. | |||
6042 | static SourceLocation getInitializationLoc(const InitializedEntity &Entity, | |||
6043 | Expr *Initializer) { | |||
6044 | switch (Entity.getKind()) { | |||
6045 | case InitializedEntity::EK_Result: | |||
6046 | case InitializedEntity::EK_StmtExprResult: | |||
6047 | return Entity.getReturnLoc(); | |||
6048 | ||||
6049 | case InitializedEntity::EK_Exception: | |||
6050 | return Entity.getThrowLoc(); | |||
6051 | ||||
6052 | case InitializedEntity::EK_Variable: | |||
6053 | case InitializedEntity::EK_Binding: | |||
6054 | return Entity.getDecl()->getLocation(); | |||
6055 | ||||
6056 | case InitializedEntity::EK_LambdaCapture: | |||
6057 | return Entity.getCaptureLoc(); | |||
6058 | ||||
6059 | case InitializedEntity::EK_ArrayElement: | |||
6060 | case InitializedEntity::EK_Member: | |||
6061 | case InitializedEntity::EK_Parameter: | |||
6062 | case InitializedEntity::EK_Parameter_CF_Audited: | |||
6063 | case InitializedEntity::EK_Temporary: | |||
6064 | case InitializedEntity::EK_New: | |||
6065 | case InitializedEntity::EK_Base: | |||
6066 | case InitializedEntity::EK_Delegating: | |||
6067 | case InitializedEntity::EK_VectorElement: | |||
6068 | case InitializedEntity::EK_ComplexElement: | |||
6069 | case InitializedEntity::EK_BlockElement: | |||
6070 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: | |||
6071 | case InitializedEntity::EK_CompoundLiteralInit: | |||
6072 | case InitializedEntity::EK_RelatedResult: | |||
6073 | return Initializer->getBeginLoc(); | |||
6074 | } | |||
6075 | llvm_unreachable("missed an InitializedEntity kind?")::llvm::llvm_unreachable_internal("missed an InitializedEntity kind?" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 6075); | |||
6076 | } | |||
6077 | ||||
6078 | /// Make a (potentially elidable) temporary copy of the object | |||
6079 | /// provided by the given initializer by calling the appropriate copy | |||
6080 | /// constructor. | |||
6081 | /// | |||
6082 | /// \param S The Sema object used for type-checking. | |||
6083 | /// | |||
6084 | /// \param T The type of the temporary object, which must either be | |||
6085 | /// the type of the initializer expression or a superclass thereof. | |||
6086 | /// | |||
6087 | /// \param Entity The entity being initialized. | |||
6088 | /// | |||
6089 | /// \param CurInit The initializer expression. | |||
6090 | /// | |||
6091 | /// \param IsExtraneousCopy Whether this is an "extraneous" copy that | |||
6092 | /// is permitted in C++03 (but not C++0x) when binding a reference to | |||
6093 | /// an rvalue. | |||
6094 | /// | |||
6095 | /// \returns An expression that copies the initializer expression into | |||
6096 | /// a temporary object, or an error expression if a copy could not be | |||
6097 | /// created. | |||
6098 | static ExprResult CopyObject(Sema &S, | |||
6099 | QualType T, | |||
6100 | const InitializedEntity &Entity, | |||
6101 | ExprResult CurInit, | |||
6102 | bool IsExtraneousCopy) { | |||
6103 | if (CurInit.isInvalid()) | |||
6104 | return CurInit; | |||
6105 | // Determine which class type we're copying to. | |||
6106 | Expr *CurInitExpr = (Expr *)CurInit.get(); | |||
6107 | CXXRecordDecl *Class = nullptr; | |||
6108 | if (const RecordType *Record = T->getAs<RecordType>()) | |||
6109 | Class = cast<CXXRecordDecl>(Record->getDecl()); | |||
6110 | if (!Class) | |||
6111 | return CurInit; | |||
6112 | ||||
6113 | SourceLocation Loc = getInitializationLoc(Entity, CurInit.get()); | |||
6114 | ||||
6115 | // Make sure that the type we are copying is complete. | |||
6116 | if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete)) | |||
6117 | return CurInit; | |||
6118 | ||||
6119 | // Perform overload resolution using the class's constructors. Per | |||
6120 | // C++11 [dcl.init]p16, second bullet for class types, this initialization | |||
6121 | // is direct-initialization. | |||
6122 | OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); | |||
6123 | DeclContext::lookup_result Ctors = S.LookupConstructors(Class); | |||
6124 | ||||
6125 | OverloadCandidateSet::iterator Best; | |||
6126 | switch (ResolveConstructorOverload( | |||
6127 | S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best, | |||
6128 | /*CopyInitializing=*/false, /*AllowExplicit=*/true, | |||
6129 | /*OnlyListConstructors=*/false, /*IsListInit=*/false, | |||
6130 | /*SecondStepOfCopyInit=*/true)) { | |||
6131 | case OR_Success: | |||
6132 | break; | |||
6133 | ||||
6134 | case OR_No_Viable_Function: | |||
6135 | CandidateSet.NoteCandidates( | |||
6136 | PartialDiagnosticAt( | |||
6137 | Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext() | |||
6138 | ? diag::ext_rvalue_to_reference_temp_copy_no_viable | |||
6139 | : diag::err_temp_copy_no_viable) | |||
6140 | << (int)Entity.getKind() << CurInitExpr->getType() | |||
6141 | << CurInitExpr->getSourceRange()), | |||
6142 | S, OCD_AllCandidates, CurInitExpr); | |||
6143 | if (!IsExtraneousCopy || S.isSFINAEContext()) | |||
6144 | return ExprError(); | |||
6145 | return CurInit; | |||
6146 | ||||
6147 | case OR_Ambiguous: | |||
6148 | CandidateSet.NoteCandidates( | |||
6149 | PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous) | |||
6150 | << (int)Entity.getKind() | |||
6151 | << CurInitExpr->getType() | |||
6152 | << CurInitExpr->getSourceRange()), | |||
6153 | S, OCD_AmbiguousCandidates, CurInitExpr); | |||
6154 | return ExprError(); | |||
6155 | ||||
6156 | case OR_Deleted: | |||
6157 | S.Diag(Loc, diag::err_temp_copy_deleted) | |||
6158 | << (int)Entity.getKind() << CurInitExpr->getType() | |||
6159 | << CurInitExpr->getSourceRange(); | |||
6160 | S.NoteDeletedFunction(Best->Function); | |||
6161 | return ExprError(); | |||
6162 | } | |||
6163 | ||||
6164 | bool HadMultipleCandidates = CandidateSet.size() > 1; | |||
6165 | ||||
6166 | CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); | |||
6167 | SmallVector<Expr*, 8> ConstructorArgs; | |||
6168 | CurInit.get(); // Ownership transferred into MultiExprArg, below. | |||
6169 | ||||
6170 | S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity, | |||
6171 | IsExtraneousCopy); | |||
6172 | ||||
6173 | if (IsExtraneousCopy) { | |||
6174 | // If this is a totally extraneous copy for C++03 reference | |||
6175 | // binding purposes, just return the original initialization | |||
6176 | // expression. We don't generate an (elided) copy operation here | |||
6177 | // because doing so would require us to pass down a flag to avoid | |||
6178 | // infinite recursion, where each step adds another extraneous, | |||
6179 | // elidable copy. | |||
6180 | ||||
6181 | // Instantiate the default arguments of any extra parameters in | |||
6182 | // the selected copy constructor, as if we were going to create a | |||
6183 | // proper call to the copy constructor. | |||
6184 | for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) { | |||
6185 | ParmVarDecl *Parm = Constructor->getParamDecl(I); | |||
6186 | if (S.RequireCompleteType(Loc, Parm->getType(), | |||
6187 | diag::err_call_incomplete_argument)) | |||
6188 | break; | |||
6189 | ||||
6190 | // Build the default argument expression; we don't actually care | |||
6191 | // if this succeeds or not, because this routine will complain | |||
6192 | // if there was a problem. | |||
6193 | S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm); | |||
6194 | } | |||
6195 | ||||
6196 | return CurInitExpr; | |||
6197 | } | |||
6198 | ||||
6199 | // Determine the arguments required to actually perform the | |||
6200 | // constructor call (we might have derived-to-base conversions, or | |||
6201 | // the copy constructor may have default arguments). | |||
6202 | if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs)) | |||
6203 | return ExprError(); | |||
6204 | ||||
6205 | // C++0x [class.copy]p32: | |||
6206 | // When certain criteria are met, an implementation is allowed to | |||
6207 | // omit the copy/move construction of a class object, even if the | |||
6208 | // copy/move constructor and/or destructor for the object have | |||
6209 | // side effects. [...] | |||
6210 | // - when a temporary class object that has not been bound to a | |||
6211 | // reference (12.2) would be copied/moved to a class object | |||
6212 | // with the same cv-unqualified type, the copy/move operation | |||
6213 | // can be omitted by constructing the temporary object | |||
6214 | // directly into the target of the omitted copy/move | |||
6215 | // | |||
6216 | // Note that the other three bullets are handled elsewhere. Copy | |||
6217 | // elision for return statements and throw expressions are handled as part | |||
6218 | // of constructor initialization, while copy elision for exception handlers | |||
6219 | // is handled by the run-time. | |||
6220 | // | |||
6221 | // FIXME: If the function parameter is not the same type as the temporary, we | |||
6222 | // should still be able to elide the copy, but we don't have a way to | |||
6223 | // represent in the AST how much should be elided in this case. | |||
6224 | bool Elidable = | |||
6225 | CurInitExpr->isTemporaryObject(S.Context, Class) && | |||
6226 | S.Context.hasSameUnqualifiedType( | |||
6227 | Best->Function->getParamDecl(0)->getType().getNonReferenceType(), | |||
6228 | CurInitExpr->getType()); | |||
6229 | ||||
6230 | // Actually perform the constructor call. | |||
6231 | CurInit = S.BuildCXXConstructExpr(Loc, T, Best->FoundDecl, Constructor, | |||
6232 | Elidable, | |||
6233 | ConstructorArgs, | |||
6234 | HadMultipleCandidates, | |||
6235 | /*ListInit*/ false, | |||
6236 | /*StdInitListInit*/ false, | |||
6237 | /*ZeroInit*/ false, | |||
6238 | CXXConstructExpr::CK_Complete, | |||
6239 | SourceRange()); | |||
6240 | ||||
6241 | // If we're supposed to bind temporaries, do so. | |||
6242 | if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity)) | |||
6243 | CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>()); | |||
6244 | return CurInit; | |||
6245 | } | |||
6246 | ||||
6247 | /// Check whether elidable copy construction for binding a reference to | |||
6248 | /// a temporary would have succeeded if we were building in C++98 mode, for | |||
6249 | /// -Wc++98-compat. | |||
6250 | static void CheckCXX98CompatAccessibleCopy(Sema &S, | |||
6251 | const InitializedEntity &Entity, | |||
6252 | Expr *CurInitExpr) { | |||
6253 | assert(S.getLangOpts().CPlusPlus11)((S.getLangOpts().CPlusPlus11) ? static_cast<void> (0) : __assert_fail ("S.getLangOpts().CPlusPlus11", "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 6253, __PRETTY_FUNCTION__)); | |||
6254 | ||||
6255 | const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>(); | |||
6256 | if (!Record) | |||
6257 | return; | |||
6258 | ||||
6259 | SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr); | |||
6260 | if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc)) | |||
6261 | return; | |||
6262 | ||||
6263 | // Find constructors which would have been considered. | |||
6264 | OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); | |||
6265 | DeclContext::lookup_result Ctors = | |||
6266 | S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl())); | |||
6267 | ||||
6268 | // Perform overload resolution. | |||
6269 | OverloadCandidateSet::iterator Best; | |||
6270 | OverloadingResult OR = ResolveConstructorOverload( | |||
6271 | S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best, | |||
6272 | /*CopyInitializing=*/false, /*AllowExplicit=*/true, | |||
6273 | /*OnlyListConstructors=*/false, /*IsListInit=*/false, | |||
6274 | /*SecondStepOfCopyInit=*/true); | |||
6275 | ||||
6276 | PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy) | |||
6277 | << OR << (int)Entity.getKind() << CurInitExpr->getType() | |||
6278 | << CurInitExpr->getSourceRange(); | |||
6279 | ||||
6280 | switch (OR) { | |||
6281 | case OR_Success: | |||
6282 | S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function), | |||
6283 | Best->FoundDecl, Entity, Diag); | |||
6284 | // FIXME: Check default arguments as far as that's possible. | |||
6285 | break; | |||
6286 | ||||
6287 | case OR_No_Viable_Function: | |||
6288 | CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, | |||
6289 | OCD_AllCandidates, CurInitExpr); | |||
6290 | break; | |||
6291 | ||||
6292 | case OR_Ambiguous: | |||
6293 | CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, | |||
6294 | OCD_AmbiguousCandidates, CurInitExpr); | |||
6295 | break; | |||
6296 | ||||
6297 | case OR_Deleted: | |||
6298 | S.Diag(Loc, Diag); | |||
6299 | S.NoteDeletedFunction(Best->Function); | |||
6300 | break; | |||
6301 | } | |||
6302 | } | |||
6303 | ||||
6304 | void InitializationSequence::PrintInitLocationNote(Sema &S, | |||
6305 | const InitializedEntity &Entity) { | |||
6306 | if (Entity.isParameterKind() && Entity.getDecl()) { | |||
6307 | if (Entity.getDecl()->getLocation().isInvalid()) | |||
6308 | return; | |||
6309 | ||||
6310 | if (Entity.getDecl()->getDeclName()) | |||
6311 | S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here) | |||
6312 | << Entity.getDecl()->getDeclName(); | |||
6313 | else | |||
6314 | S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here); | |||
6315 | } | |||
6316 | else if (Entity.getKind() == InitializedEntity::EK_RelatedResult && | |||
6317 | Entity.getMethodDecl()) | |||
6318 | S.Diag(Entity.getMethodDecl()->getLocation(), | |||
6319 | diag::note_method_return_type_change) | |||
6320 | << Entity.getMethodDecl()->getDeclName(); | |||
6321 | } | |||
6322 | ||||
6323 | /// Returns true if the parameters describe a constructor initialization of | |||
6324 | /// an explicit temporary object, e.g. "Point(x, y)". | |||
6325 | static bool isExplicitTemporary(const InitializedEntity &Entity, | |||
6326 | const InitializationKind &Kind, | |||
6327 | unsigned NumArgs) { | |||
6328 | switch (Entity.getKind()) { | |||
6329 | case InitializedEntity::EK_Temporary: | |||
6330 | case InitializedEntity::EK_CompoundLiteralInit: | |||
6331 | case InitializedEntity::EK_RelatedResult: | |||
6332 | break; | |||
6333 | default: | |||
6334 | return false; | |||
6335 | } | |||
6336 | ||||
6337 | switch (Kind.getKind()) { | |||
6338 | case InitializationKind::IK_DirectList: | |||
6339 | return true; | |||
6340 | // FIXME: Hack to work around cast weirdness. | |||
6341 | case InitializationKind::IK_Direct: | |||
6342 | case InitializationKind::IK_Value: | |||
6343 | return NumArgs != 1; | |||
6344 | default: | |||
6345 | return false; | |||
6346 | } | |||
6347 | } | |||
6348 | ||||
6349 | static ExprResult | |||
6350 | PerformConstructorInitialization(Sema &S, | |||
6351 | const InitializedEntity &Entity, | |||
6352 | const InitializationKind &Kind, | |||
6353 | MultiExprArg Args, | |||
6354 | const InitializationSequence::Step& Step, | |||
6355 | bool &ConstructorInitRequiresZeroInit, | |||
6356 | bool IsListInitialization, | |||
6357 | bool IsStdInitListInitialization, | |||
6358 | SourceLocation LBraceLoc, | |||
6359 | SourceLocation RBraceLoc) { | |||
6360 | unsigned NumArgs = Args.size(); | |||
6361 | CXXConstructorDecl *Constructor | |||
6362 | = cast<CXXConstructorDecl>(Step.Function.Function); | |||
6363 | bool HadMultipleCandidates = Step.Function.HadMultipleCandidates; | |||
6364 | ||||
6365 | // Build a call to the selected constructor. | |||
6366 | SmallVector<Expr*, 8> ConstructorArgs; | |||
6367 | SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid()) | |||
6368 | ? Kind.getEqualLoc() | |||
6369 | : Kind.getLocation(); | |||
6370 | ||||
6371 | if (Kind.getKind() == InitializationKind::IK_Default) { | |||
6372 | // Force even a trivial, implicit default constructor to be | |||
6373 | // semantically checked. We do this explicitly because we don't build | |||
6374 | // the definition for completely trivial constructors. | |||
6375 | assert(Constructor->getParent() && "No parent class for constructor.")((Constructor->getParent() && "No parent class for constructor." ) ? static_cast<void> (0) : __assert_fail ("Constructor->getParent() && \"No parent class for constructor.\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 6375, __PRETTY_FUNCTION__)); | |||
6376 | if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() && | |||
6377 | Constructor->isTrivial() && !Constructor->isUsed(false)) { | |||
6378 | S.runWithSufficientStackSpace(Loc, [&] { | |||
6379 | S.DefineImplicitDefaultConstructor(Loc, Constructor); | |||
6380 | }); | |||
6381 | } | |||
6382 | } | |||
6383 | ||||
6384 | ExprResult CurInit((Expr *)nullptr); | |||
6385 | ||||
6386 | // C++ [over.match.copy]p1: | |||
6387 | // - When initializing a temporary to be bound to the first parameter | |||
6388 | // of a constructor that takes a reference to possibly cv-qualified | |||
6389 | // T as its first argument, called with a single argument in the | |||
6390 | // context of direct-initialization, explicit conversion functions | |||
6391 | // are also considered. | |||
6392 | bool AllowExplicitConv = | |||
6393 | Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 && | |||
6394 | hasCopyOrMoveCtorParam(S.Context, | |||
6395 | getConstructorInfo(Step.Function.FoundDecl)); | |||
6396 | ||||
6397 | // Determine the arguments required to actually perform the constructor | |||
6398 | // call. | |||
6399 | if (S.CompleteConstructorCall(Constructor, Args, | |||
6400 | Loc, ConstructorArgs, | |||
6401 | AllowExplicitConv, | |||
6402 | IsListInitialization)) | |||
6403 | return ExprError(); | |||
6404 | ||||
6405 | ||||
6406 | if (isExplicitTemporary(Entity, Kind, NumArgs)) { | |||
6407 | // An explicitly-constructed temporary, e.g., X(1, 2). | |||
6408 | if (S.DiagnoseUseOfDecl(Constructor, Loc)) | |||
6409 | return ExprError(); | |||
6410 | ||||
6411 | TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo(); | |||
6412 | if (!TSInfo) | |||
6413 | TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc); | |||
6414 | SourceRange ParenOrBraceRange = | |||
6415 | (Kind.getKind() == InitializationKind::IK_DirectList) | |||
6416 | ? SourceRange(LBraceLoc, RBraceLoc) | |||
6417 | : Kind.getParenOrBraceRange(); | |||
6418 | ||||
6419 | if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>( | |||
6420 | Step.Function.FoundDecl.getDecl())) { | |||
6421 | Constructor = S.findInheritingConstructor(Loc, Constructor, Shadow); | |||
6422 | if (S.DiagnoseUseOfDecl(Constructor, Loc)) | |||
6423 | return ExprError(); | |||
6424 | } | |||
6425 | S.MarkFunctionReferenced(Loc, Constructor); | |||
6426 | ||||
6427 | CurInit = CXXTemporaryObjectExpr::Create( | |||
6428 | S.Context, Constructor, | |||
6429 | Entity.getType().getNonLValueExprType(S.Context), TSInfo, | |||
6430 | ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates, | |||
6431 | IsListInitialization, IsStdInitListInitialization, | |||
6432 | ConstructorInitRequiresZeroInit); | |||
6433 | } else { | |||
6434 | CXXConstructExpr::ConstructionKind ConstructKind = | |||
6435 | CXXConstructExpr::CK_Complete; | |||
6436 | ||||
6437 | if (Entity.getKind() == InitializedEntity::EK_Base) { | |||
6438 | ConstructKind = Entity.getBaseSpecifier()->isVirtual() ? | |||
6439 | CXXConstructExpr::CK_VirtualBase : | |||
6440 | CXXConstructExpr::CK_NonVirtualBase; | |||
6441 | } else if (Entity.getKind() == InitializedEntity::EK_Delegating) { | |||
6442 | ConstructKind = CXXConstructExpr::CK_Delegating; | |||
6443 | } | |||
6444 | ||||
6445 | // Only get the parenthesis or brace range if it is a list initialization or | |||
6446 | // direct construction. | |||
6447 | SourceRange ParenOrBraceRange; | |||
6448 | if (IsListInitialization) | |||
6449 | ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc); | |||
6450 | else if (Kind.getKind() == InitializationKind::IK_Direct) | |||
6451 | ParenOrBraceRange = Kind.getParenOrBraceRange(); | |||
6452 | ||||
6453 | // If the entity allows NRVO, mark the construction as elidable | |||
6454 | // unconditionally. | |||
6455 | if (Entity.allowsNRVO()) | |||
6456 | CurInit = S.BuildCXXConstructExpr(Loc, Step.Type, | |||
6457 | Step.Function.FoundDecl, | |||
6458 | Constructor, /*Elidable=*/true, | |||
6459 | ConstructorArgs, | |||
6460 | HadMultipleCandidates, | |||
6461 | IsListInitialization, | |||
6462 | IsStdInitListInitialization, | |||
6463 | ConstructorInitRequiresZeroInit, | |||
6464 | ConstructKind, | |||
6465 | ParenOrBraceRange); | |||
6466 | else | |||
6467 | CurInit = S.BuildCXXConstructExpr(Loc, Step.Type, | |||
6468 | Step.Function.FoundDecl, | |||
6469 | Constructor, | |||
6470 | ConstructorArgs, | |||
6471 | HadMultipleCandidates, | |||
6472 | IsListInitialization, | |||
6473 | IsStdInitListInitialization, | |||
6474 | ConstructorInitRequiresZeroInit, | |||
6475 | ConstructKind, | |||
6476 | ParenOrBraceRange); | |||
6477 | } | |||
6478 | if (CurInit.isInvalid()) | |||
6479 | return ExprError(); | |||
6480 | ||||
6481 | // Only check access if all of that succeeded. | |||
6482 | S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity); | |||
6483 | if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc)) | |||
6484 | return ExprError(); | |||
6485 | ||||
6486 | if (const ArrayType *AT = S.Context.getAsArrayType(Entity.getType())) | |||
6487 | if (checkDestructorReference(S.Context.getBaseElementType(AT), Loc, S)) | |||
6488 | return ExprError(); | |||
6489 | ||||
6490 | if (shouldBindAsTemporary(Entity)) | |||
6491 | CurInit = S.MaybeBindToTemporary(CurInit.get()); | |||
6492 | ||||
6493 | return CurInit; | |||
6494 | } | |||
6495 | ||||
6496 | namespace { | |||
6497 | enum LifetimeKind { | |||
6498 | /// The lifetime of a temporary bound to this entity ends at the end of the | |||
6499 | /// full-expression, and that's (probably) fine. | |||
6500 | LK_FullExpression, | |||
6501 | ||||
6502 | /// The lifetime of a temporary bound to this entity is extended to the | |||
6503 | /// lifeitme of the entity itself. | |||
6504 | LK_Extended, | |||
6505 | ||||
6506 | /// The lifetime of a temporary bound to this entity probably ends too soon, | |||
6507 | /// because the entity is allocated in a new-expression. | |||
6508 | LK_New, | |||
6509 | ||||
6510 | /// The lifetime of a temporary bound to this entity ends too soon, because | |||
6511 | /// the entity is a return object. | |||
6512 | LK_Return, | |||
6513 | ||||
6514 | /// The lifetime of a temporary bound to this entity ends too soon, because | |||
6515 | /// the entity is the result of a statement expression. | |||
6516 | LK_StmtExprResult, | |||
6517 | ||||
6518 | /// This is a mem-initializer: if it would extend a temporary (other than via | |||
6519 | /// a default member initializer), the program is ill-formed. | |||
6520 | LK_MemInitializer, | |||
6521 | }; | |||
6522 | using LifetimeResult = | |||
6523 | llvm::PointerIntPair<const InitializedEntity *, 3, LifetimeKind>; | |||
6524 | } | |||
6525 | ||||
6526 | /// Determine the declaration which an initialized entity ultimately refers to, | |||
6527 | /// for the purpose of lifetime-extending a temporary bound to a reference in | |||
6528 | /// the initialization of \p Entity. | |||
6529 | static LifetimeResult getEntityLifetime( | |||
6530 | const InitializedEntity *Entity, | |||
6531 | const InitializedEntity *InitField = nullptr) { | |||
6532 | // C++11 [class.temporary]p5: | |||
6533 | switch (Entity->getKind()) { | |||
6534 | case InitializedEntity::EK_Variable: | |||
6535 | // The temporary [...] persists for the lifetime of the reference | |||
6536 | return {Entity, LK_Extended}; | |||
6537 | ||||
6538 | case InitializedEntity::EK_Member: | |||
6539 | // For subobjects, we look at the complete object. | |||
6540 | if (Entity->getParent()) | |||
6541 | return getEntityLifetime(Entity->getParent(), Entity); | |||
6542 | ||||
6543 | // except: | |||
6544 | // C++17 [class.base.init]p8: | |||
6545 | // A temporary expression bound to a reference member in a | |||
6546 | // mem-initializer is ill-formed. | |||
6547 | // C++17 [class.base.init]p11: | |||
6548 | // A temporary expression bound to a reference member from a | |||
6549 | // default member initializer is ill-formed. | |||
6550 | // | |||
6551 | // The context of p11 and its example suggest that it's only the use of a | |||
6552 | // default member initializer from a constructor that makes the program | |||
6553 | // ill-formed, not its mere existence, and that it can even be used by | |||
6554 | // aggregate initialization. | |||
6555 | return {Entity, Entity->isDefaultMemberInitializer() ? LK_Extended | |||
6556 | : LK_MemInitializer}; | |||
6557 | ||||
6558 | case InitializedEntity::EK_Binding: | |||
6559 | // Per [dcl.decomp]p3, the binding is treated as a variable of reference | |||
6560 | // type. | |||
6561 | return {Entity, LK_Extended}; | |||
6562 | ||||
6563 | case InitializedEntity::EK_Parameter: | |||
6564 | case InitializedEntity::EK_Parameter_CF_Audited: | |||
6565 | // -- A temporary bound to a reference parameter in a function call | |||
6566 | // persists until the completion of the full-expression containing | |||
6567 | // the call. | |||
6568 | return {nullptr, LK_FullExpression}; | |||
6569 | ||||
6570 | case InitializedEntity::EK_Result: | |||
6571 | // -- The lifetime of a temporary bound to the returned value in a | |||
6572 | // function return statement is not extended; the temporary is | |||
6573 | // destroyed at the end of the full-expression in the return statement. | |||
6574 | return {nullptr, LK_Return}; | |||
6575 | ||||
6576 | case InitializedEntity::EK_StmtExprResult: | |||
6577 | // FIXME: Should we lifetime-extend through the result of a statement | |||
6578 | // expression? | |||
6579 | return {nullptr, LK_StmtExprResult}; | |||
6580 | ||||
6581 | case InitializedEntity::EK_New: | |||
6582 | // -- A temporary bound to a reference in a new-initializer persists | |||
6583 | // until the completion of the full-expression containing the | |||
6584 | // new-initializer. | |||
6585 | return {nullptr, LK_New}; | |||
6586 | ||||
6587 | case InitializedEntity::EK_Temporary: | |||
6588 | case InitializedEntity::EK_CompoundLiteralInit: | |||
6589 | case InitializedEntity::EK_RelatedResult: | |||
6590 | // We don't yet know the storage duration of the surrounding temporary. | |||
6591 | // Assume it's got full-expression duration for now, it will patch up our | |||
6592 | // storage duration if that's not correct. | |||
6593 | return {nullptr, LK_FullExpression}; | |||
6594 | ||||
6595 | case InitializedEntity::EK_ArrayElement: | |||
6596 | // For subobjects, we look at the complete object. | |||
6597 | return getEntityLifetime(Entity->getParent(), InitField); | |||
6598 | ||||
6599 | case InitializedEntity::EK_Base: | |||
6600 | // For subobjects, we look at the complete object. | |||
6601 | if (Entity->getParent()) | |||
6602 | return getEntityLifetime(Entity->getParent(), InitField); | |||
6603 | return {InitField, LK_MemInitializer}; | |||
6604 | ||||
6605 | case InitializedEntity::EK_Delegating: | |||
6606 | // We can reach this case for aggregate initialization in a constructor: | |||
6607 | // struct A { int &&r; }; | |||
6608 | // struct B : A { B() : A{0} {} }; | |||
6609 | // In this case, use the outermost field decl as the context. | |||
6610 | return {InitField, LK_MemInitializer}; | |||
6611 | ||||
6612 | case InitializedEntity::EK_BlockElement: | |||
6613 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: | |||
6614 | case InitializedEntity::EK_LambdaCapture: | |||
6615 | case InitializedEntity::EK_VectorElement: | |||
6616 | case InitializedEntity::EK_ComplexElement: | |||
6617 | return {nullptr, LK_FullExpression}; | |||
6618 | ||||
6619 | case InitializedEntity::EK_Exception: | |||
6620 | // FIXME: Can we diagnose lifetime problems with exceptions? | |||
6621 | return {nullptr, LK_FullExpression}; | |||
6622 | } | |||
6623 | llvm_unreachable("unknown entity kind")::llvm::llvm_unreachable_internal("unknown entity kind", "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 6623); | |||
6624 | } | |||
6625 | ||||
6626 | namespace { | |||
6627 | enum ReferenceKind { | |||
6628 | /// Lifetime would be extended by a reference binding to a temporary. | |||
6629 | RK_ReferenceBinding, | |||
6630 | /// Lifetime would be extended by a std::initializer_list object binding to | |||
6631 | /// its backing array. | |||
6632 | RK_StdInitializerList, | |||
6633 | }; | |||
6634 | ||||
6635 | /// A temporary or local variable. This will be one of: | |||
6636 | /// * A MaterializeTemporaryExpr. | |||
6637 | /// * A DeclRefExpr whose declaration is a local. | |||
6638 | /// * An AddrLabelExpr. | |||
6639 | /// * A BlockExpr for a block with captures. | |||
6640 | using Local = Expr*; | |||
6641 | ||||
6642 | /// Expressions we stepped over when looking for the local state. Any steps | |||
6643 | /// that would inhibit lifetime extension or take us out of subexpressions of | |||
6644 | /// the initializer are included. | |||
6645 | struct IndirectLocalPathEntry { | |||
6646 | enum EntryKind { | |||
6647 | DefaultInit, | |||
6648 | AddressOf, | |||
6649 | VarInit, | |||
6650 | LValToRVal, | |||
6651 | LifetimeBoundCall, | |||
6652 | GslReferenceInit, | |||
6653 | GslPointerInit | |||
6654 | } Kind; | |||
6655 | Expr *E; | |||
6656 | const Decl *D = nullptr; | |||
6657 | IndirectLocalPathEntry() {} | |||
6658 | IndirectLocalPathEntry(EntryKind K, Expr *E) : Kind(K), E(E) {} | |||
6659 | IndirectLocalPathEntry(EntryKind K, Expr *E, const Decl *D) | |||
6660 | : Kind(K), E(E), D(D) {} | |||
6661 | }; | |||
6662 | ||||
6663 | using IndirectLocalPath = llvm::SmallVectorImpl<IndirectLocalPathEntry>; | |||
6664 | ||||
6665 | struct RevertToOldSizeRAII { | |||
6666 | IndirectLocalPath &Path; | |||
6667 | unsigned OldSize = Path.size(); | |||
6668 | RevertToOldSizeRAII(IndirectLocalPath &Path) : Path(Path) {} | |||
6669 | ~RevertToOldSizeRAII() { Path.resize(OldSize); } | |||
6670 | }; | |||
6671 | ||||
6672 | using LocalVisitor = llvm::function_ref<bool(IndirectLocalPath &Path, Local L, | |||
6673 | ReferenceKind RK)>; | |||
6674 | } | |||
6675 | ||||
6676 | static bool isVarOnPath(IndirectLocalPath &Path, VarDecl *VD) { | |||
6677 | for (auto E : Path) | |||
6678 | if (E.Kind == IndirectLocalPathEntry::VarInit && E.D == VD) | |||
6679 | return true; | |||
6680 | return false; | |||
6681 | } | |||
6682 | ||||
6683 | static bool pathContainsInit(IndirectLocalPath &Path) { | |||
6684 | return llvm::any_of(Path, [=](IndirectLocalPathEntry E) { | |||
6685 | return E.Kind == IndirectLocalPathEntry::DefaultInit || | |||
6686 | E.Kind == IndirectLocalPathEntry::VarInit; | |||
6687 | }); | |||
6688 | } | |||
6689 | ||||
6690 | static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path, | |||
6691 | Expr *Init, LocalVisitor Visit, | |||
6692 | bool RevisitSubinits, | |||
6693 | bool EnableLifetimeWarnings); | |||
6694 | ||||
6695 | static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path, | |||
6696 | Expr *Init, ReferenceKind RK, | |||
6697 | LocalVisitor Visit, | |||
6698 | bool EnableLifetimeWarnings); | |||
6699 | ||||
6700 | template <typename T> static bool isRecordWithAttr(QualType Type) { | |||
6701 | if (auto *RD = Type->getAsCXXRecordDecl()) | |||
6702 | return RD->hasAttr<T>(); | |||
6703 | return false; | |||
6704 | } | |||
6705 | ||||
6706 | // Decl::isInStdNamespace will return false for iterators in some STL | |||
6707 | // implementations due to them being defined in a namespace outside of the std | |||
6708 | // namespace. | |||
6709 | static bool isInStlNamespace(const Decl *D) { | |||
6710 | const DeclContext *DC = D->getDeclContext(); | |||
6711 | if (!DC) | |||
6712 | return false; | |||
6713 | if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) | |||
6714 | if (const IdentifierInfo *II = ND->getIdentifier()) { | |||
6715 | StringRef Name = II->getName(); | |||
6716 | if (Name.size() >= 2 && Name.front() == '_' && | |||
6717 | (Name[1] == '_' || isUppercase(Name[1]))) | |||
6718 | return true; | |||
6719 | } | |||
6720 | ||||
6721 | return DC->isStdNamespace(); | |||
6722 | } | |||
6723 | ||||
6724 | static bool shouldTrackImplicitObjectArg(const CXXMethodDecl *Callee) { | |||
6725 | if (auto *Conv = dyn_cast_or_null<CXXConversionDecl>(Callee)) | |||
6726 | if (isRecordWithAttr<PointerAttr>(Conv->getConversionType())) | |||
6727 | return true; | |||
6728 | if (!isInStlNamespace(Callee->getParent())) | |||
6729 | return false; | |||
6730 | if (!isRecordWithAttr<PointerAttr>(Callee->getThisObjectType()) && | |||
6731 | !isRecordWithAttr<OwnerAttr>(Callee->getThisObjectType())) | |||
6732 | return false; | |||
6733 | if (Callee->getReturnType()->isPointerType() || | |||
6734 | isRecordWithAttr<PointerAttr>(Callee->getReturnType())) { | |||
6735 | if (!Callee->getIdentifier()) | |||
6736 | return false; | |||
6737 | return llvm::StringSwitch<bool>(Callee->getName()) | |||
6738 | .Cases("begin", "rbegin", "cbegin", "crbegin", true) | |||
6739 | .Cases("end", "rend", "cend", "crend", true) | |||
6740 | .Cases("c_str", "data", "get", true) | |||
6741 | // Map and set types. | |||
6742 | .Cases("find", "equal_range", "lower_bound", "upper_bound", true) | |||
6743 | .Default(false); | |||
6744 | } else if (Callee->getReturnType()->isReferenceType()) { | |||
6745 | if (!Callee->getIdentifier()) { | |||
6746 | auto OO = Callee->getOverloadedOperator(); | |||
6747 | return OO == OverloadedOperatorKind::OO_Subscript || | |||
6748 | OO == OverloadedOperatorKind::OO_Star; | |||
6749 | } | |||
6750 | return llvm::StringSwitch<bool>(Callee->getName()) | |||
6751 | .Cases("front", "back", "at", "top", "value", true) | |||
6752 | .Default(false); | |||
6753 | } | |||
6754 | return false; | |||
6755 | } | |||
6756 | ||||
6757 | static bool shouldTrackFirstArgument(const FunctionDecl *FD) { | |||
6758 | if (!FD->getIdentifier() || FD->getNumParams() != 1) | |||
6759 | return false; | |||
6760 | const auto *RD = FD->getParamDecl(0)->getType()->getPointeeCXXRecordDecl(); | |||
6761 | if (!FD->isInStdNamespace() || !RD || !RD->isInStdNamespace()) | |||
6762 | return false; | |||
6763 | if (!isRecordWithAttr<PointerAttr>(QualType(RD->getTypeForDecl(), 0)) && | |||
6764 | !isRecordWithAttr<OwnerAttr>(QualType(RD->getTypeForDecl(), 0))) | |||
6765 | return false; | |||
6766 | if (FD->getReturnType()->isPointerType() || | |||
6767 | isRecordWithAttr<PointerAttr>(FD->getReturnType())) { | |||
6768 | return llvm::StringSwitch<bool>(FD->getName()) | |||
6769 | .Cases("begin", "rbegin", "cbegin", "crbegin", true) | |||
6770 | .Cases("end", "rend", "cend", "crend", true) | |||
6771 | .Case("data", true) | |||
6772 | .Default(false); | |||
6773 | } else if (FD->getReturnType()->isReferenceType()) { | |||
6774 | return llvm::StringSwitch<bool>(FD->getName()) | |||
6775 | .Cases("get", "any_cast", true) | |||
6776 | .Default(false); | |||
6777 | } | |||
6778 | return false; | |||
6779 | } | |||
6780 | ||||
6781 | static void handleGslAnnotatedTypes(IndirectLocalPath &Path, Expr *Call, | |||
6782 | LocalVisitor Visit) { | |||
6783 | auto VisitPointerArg = [&](const Decl *D, Expr *Arg, bool Value) { | |||
6784 | // We are not interested in the temporary base objects of gsl Pointers: | |||
6785 | // Temp().ptr; // Here ptr might not dangle. | |||
6786 | if (isa<MemberExpr>(Arg->IgnoreImpCasts())) | |||
6787 | return; | |||
6788 | // Once we initialized a value with a reference, it can no longer dangle. | |||
6789 | if (!Value) { | |||
6790 | for (auto It = Path.rbegin(), End = Path.rend(); It != End; ++It) { | |||
6791 | if (It->Kind == IndirectLocalPathEntry::GslReferenceInit) | |||
6792 | continue; | |||
6793 | if (It->Kind == IndirectLocalPathEntry::GslPointerInit) | |||
6794 | return; | |||
6795 | break; | |||
6796 | } | |||
6797 | } | |||
6798 | Path.push_back({Value ? IndirectLocalPathEntry::GslPointerInit | |||
6799 | : IndirectLocalPathEntry::GslReferenceInit, | |||
6800 | Arg, D}); | |||
6801 | if (Arg->isGLValue()) | |||
6802 | visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding, | |||
6803 | Visit, | |||
6804 | /*EnableLifetimeWarnings=*/true); | |||
6805 | else | |||
6806 | visitLocalsRetainedByInitializer(Path, Arg, Visit, true, | |||
6807 | /*EnableLifetimeWarnings=*/true); | |||
6808 | Path.pop_back(); | |||
6809 | }; | |||
6810 | ||||
6811 | if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) { | |||
6812 | const auto *MD = cast_or_null<CXXMethodDecl>(MCE->getDirectCallee()); | |||
6813 | if (MD && shouldTrackImplicitObjectArg(MD)) | |||
6814 | VisitPointerArg(MD, MCE->getImplicitObjectArgument(), | |||
6815 | !MD->getReturnType()->isReferenceType()); | |||
6816 | return; | |||
6817 | } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(Call)) { | |||
6818 | FunctionDecl *Callee = OCE->getDirectCallee(); | |||
6819 | if (Callee && Callee->isCXXInstanceMember() && | |||
6820 | shouldTrackImplicitObjectArg(cast<CXXMethodDecl>(Callee))) | |||
6821 | VisitPointerArg(Callee, OCE->getArg(0), | |||
6822 | !Callee->getReturnType()->isReferenceType()); | |||
6823 | return; | |||
6824 | } else if (auto *CE = dyn_cast<CallExpr>(Call)) { | |||
6825 | FunctionDecl *Callee = CE->getDirectCallee(); | |||
6826 | if (Callee && shouldTrackFirstArgument(Callee)) | |||
6827 | VisitPointerArg(Callee, CE->getArg(0), | |||
6828 | !Callee->getReturnType()->isReferenceType()); | |||
6829 | return; | |||
6830 | } | |||
6831 | ||||
6832 | if (auto *CCE = dyn_cast<CXXConstructExpr>(Call)) { | |||
6833 | const auto *Ctor = CCE->getConstructor(); | |||
6834 | const CXXRecordDecl *RD = Ctor->getParent(); | |||
6835 | if (CCE->getNumArgs() > 0 && RD->hasAttr<PointerAttr>()) | |||
6836 | VisitPointerArg(Ctor->getParamDecl(0), CCE->getArgs()[0], true); | |||
6837 | } | |||
6838 | } | |||
6839 | ||||
6840 | static bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD) { | |||
6841 | const TypeSourceInfo *TSI = FD->getTypeSourceInfo(); | |||
6842 | if (!TSI) | |||
6843 | return false; | |||
6844 | // Don't declare this variable in the second operand of the for-statement; | |||
6845 | // GCC miscompiles that by ending its lifetime before evaluating the | |||
6846 | // third operand. See gcc.gnu.org/PR86769. | |||
6847 | AttributedTypeLoc ATL; | |||
6848 | for (TypeLoc TL = TSI->getTypeLoc(); | |||
6849 | (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); | |||
6850 | TL = ATL.getModifiedLoc()) { | |||
6851 | if (ATL.getAttrAs<LifetimeBoundAttr>()) | |||
6852 | return true; | |||
6853 | } | |||
6854 | return false; | |||
6855 | } | |||
6856 | ||||
6857 | static void visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call, | |||
6858 | LocalVisitor Visit) { | |||
6859 | const FunctionDecl *Callee; | |||
6860 | ArrayRef<Expr*> Args; | |||
6861 | ||||
6862 | if (auto *CE = dyn_cast<CallExpr>(Call)) { | |||
6863 | Callee = CE->getDirectCallee(); | |||
6864 | Args = llvm::makeArrayRef(CE->getArgs(), CE->getNumArgs()); | |||
6865 | } else { | |||
6866 | auto *CCE = cast<CXXConstructExpr>(Call); | |||
6867 | Callee = CCE->getConstructor(); | |||
6868 | Args = llvm::makeArrayRef(CCE->getArgs(), CCE->getNumArgs()); | |||
6869 | } | |||
6870 | if (!Callee) | |||
6871 | return; | |||
6872 | ||||
6873 | Expr *ObjectArg = nullptr; | |||
6874 | if (isa<CXXOperatorCallExpr>(Call) && Callee->isCXXInstanceMember()) { | |||
6875 | ObjectArg = Args[0]; | |||
6876 | Args = Args.slice(1); | |||
6877 | } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) { | |||
6878 | ObjectArg = MCE->getImplicitObjectArgument(); | |||
6879 | } | |||
6880 | ||||
6881 | auto VisitLifetimeBoundArg = [&](const Decl *D, Expr *Arg) { | |||
6882 | Path.push_back({IndirectLocalPathEntry::LifetimeBoundCall, Arg, D}); | |||
6883 | if (Arg->isGLValue()) | |||
6884 | visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding, | |||
6885 | Visit, | |||
6886 | /*EnableLifetimeWarnings=*/false); | |||
6887 | else | |||
6888 | visitLocalsRetainedByInitializer(Path, Arg, Visit, true, | |||
6889 | /*EnableLifetimeWarnings=*/false); | |||
6890 | Path.pop_back(); | |||
6891 | }; | |||
6892 | ||||
6893 | if (ObjectArg && implicitObjectParamIsLifetimeBound(Callee)) | |||
6894 | VisitLifetimeBoundArg(Callee, ObjectArg); | |||
6895 | ||||
6896 | for (unsigned I = 0, | |||
6897 | N = std::min<unsigned>(Callee->getNumParams(), Args.size()); | |||
6898 | I != N; ++I) { | |||
6899 | if (Callee->getParamDecl(I)->hasAttr<LifetimeBoundAttr>()) | |||
6900 | VisitLifetimeBoundArg(Callee->getParamDecl(I), Args[I]); | |||
6901 | } | |||
6902 | } | |||
6903 | ||||
6904 | /// Visit the locals that would be reachable through a reference bound to the | |||
6905 | /// glvalue expression \c Init. | |||
6906 | static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path, | |||
6907 | Expr *Init, ReferenceKind RK, | |||
6908 | LocalVisitor Visit, | |||
6909 | bool EnableLifetimeWarnings) { | |||
6910 | RevertToOldSizeRAII RAII(Path); | |||
6911 | ||||
6912 | // Walk past any constructs which we can lifetime-extend across. | |||
6913 | Expr *Old; | |||
6914 | do { | |||
6915 | Old = Init; | |||
6916 | ||||
6917 | if (auto *FE = dyn_cast<FullExpr>(Init)) | |||
6918 | Init = FE->getSubExpr(); | |||
6919 | ||||
6920 | if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) { | |||
6921 | // If this is just redundant braces around an initializer, step over it. | |||
6922 | if (ILE->isTransparent()) | |||
6923 | Init = ILE->getInit(0); | |||
6924 | } | |||
6925 | ||||
6926 | // Step over any subobject adjustments; we may have a materialized | |||
6927 | // temporary inside them. | |||
6928 | Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments()); | |||
6929 | ||||
6930 | // Per current approach for DR1376, look through casts to reference type | |||
6931 | // when performing lifetime extension. | |||
6932 | if (CastExpr *CE = dyn_cast<CastExpr>(Init)) | |||
6933 | if (CE->getSubExpr()->isGLValue()) | |||
6934 | Init = CE->getSubExpr(); | |||
6935 | ||||
6936 | // Per the current approach for DR1299, look through array element access | |||
6937 | // on array glvalues when performing lifetime extension. | |||
6938 | if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init)) { | |||
6939 | Init = ASE->getBase(); | |||
6940 | auto *ICE = dyn_cast<ImplicitCastExpr>(Init); | |||
6941 | if (ICE && ICE->getCastKind() == CK_ArrayToPointerDecay) | |||
6942 | Init = ICE->getSubExpr(); | |||
6943 | else | |||
6944 | // We can't lifetime extend through this but we might still find some | |||
6945 | // retained temporaries. | |||
6946 | return visitLocalsRetainedByInitializer(Path, Init, Visit, true, | |||
6947 | EnableLifetimeWarnings); | |||
6948 | } | |||
6949 | ||||
6950 | // Step into CXXDefaultInitExprs so we can diagnose cases where a | |||
6951 | // constructor inherits one as an implicit mem-initializer. | |||
6952 | if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) { | |||
6953 | Path.push_back( | |||
6954 | {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()}); | |||
6955 | Init = DIE->getExpr(); | |||
6956 | } | |||
6957 | } while (Init != Old); | |||
6958 | ||||
6959 | if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) { | |||
6960 | if (Visit(Path, Local(MTE), RK)) | |||
6961 | visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit, true, | |||
6962 | EnableLifetimeWarnings); | |||
6963 | } | |||
6964 | ||||
6965 | if (isa<CallExpr>(Init)) { | |||
6966 | if (EnableLifetimeWarnings) | |||
6967 | handleGslAnnotatedTypes(Path, Init, Visit); | |||
6968 | return visitLifetimeBoundArguments(Path, Init, Visit); | |||
6969 | } | |||
6970 | ||||
6971 | switch (Init->getStmtClass()) { | |||
6972 | case Stmt::DeclRefExprClass: { | |||
6973 | // If we find the name of a local non-reference parameter, we could have a | |||
6974 | // lifetime problem. | |||
6975 | auto *DRE = cast<DeclRefExpr>(Init); | |||
6976 | auto *VD = dyn_cast<VarDecl>(DRE->getDecl()); | |||
6977 | if (VD && VD->hasLocalStorage() && | |||
6978 | !DRE->refersToEnclosingVariableOrCapture()) { | |||
6979 | if (!VD->getType()->isReferenceType()) { | |||
6980 | Visit(Path, Local(DRE), RK); | |||
6981 | } else if (isa<ParmVarDecl>(DRE->getDecl())) { | |||
6982 | // The lifetime of a reference parameter is unknown; assume it's OK | |||
6983 | // for now. | |||
6984 | break; | |||
6985 | } else if (VD->getInit() && !isVarOnPath(Path, VD)) { | |||
6986 | Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD}); | |||
6987 | visitLocalsRetainedByReferenceBinding(Path, VD->getInit(), | |||
6988 | RK_ReferenceBinding, Visit, | |||
6989 | EnableLifetimeWarnings); | |||
6990 | } | |||
6991 | } | |||
6992 | break; | |||
6993 | } | |||
6994 | ||||
6995 | case Stmt::UnaryOperatorClass: { | |||
6996 | // The only unary operator that make sense to handle here | |||
6997 | // is Deref. All others don't resolve to a "name." This includes | |||
6998 | // handling all sorts of rvalues passed to a unary operator. | |||
6999 | const UnaryOperator *U = cast<UnaryOperator>(Init); | |||
7000 | if (U->getOpcode() == UO_Deref) | |||
7001 | visitLocalsRetainedByInitializer(Path, U->getSubExpr(), Visit, true, | |||
7002 | EnableLifetimeWarnings); | |||
7003 | break; | |||
7004 | } | |||
7005 | ||||
7006 | case Stmt::OMPArraySectionExprClass: { | |||
7007 | visitLocalsRetainedByInitializer(Path, | |||
7008 | cast<OMPArraySectionExpr>(Init)->getBase(), | |||
7009 | Visit, true, EnableLifetimeWarnings); | |||
7010 | break; | |||
7011 | } | |||
7012 | ||||
7013 | case Stmt::ConditionalOperatorClass: | |||
7014 | case Stmt::BinaryConditionalOperatorClass: { | |||
7015 | auto *C = cast<AbstractConditionalOperator>(Init); | |||
7016 | if (!C->getTrueExpr()->getType()->isVoidType()) | |||
7017 | visitLocalsRetainedByReferenceBinding(Path, C->getTrueExpr(), RK, Visit, | |||
7018 | EnableLifetimeWarnings); | |||
7019 | if (!C->getFalseExpr()->getType()->isVoidType()) | |||
7020 | visitLocalsRetainedByReferenceBinding(Path, C->getFalseExpr(), RK, Visit, | |||
7021 | EnableLifetimeWarnings); | |||
7022 | break; | |||
7023 | } | |||
7024 | ||||
7025 | // FIXME: Visit the left-hand side of an -> or ->*. | |||
7026 | ||||
7027 | default: | |||
7028 | break; | |||
7029 | } | |||
7030 | } | |||
7031 | ||||
7032 | /// Visit the locals that would be reachable through an object initialized by | |||
7033 | /// the prvalue expression \c Init. | |||
7034 | static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path, | |||
7035 | Expr *Init, LocalVisitor Visit, | |||
7036 | bool RevisitSubinits, | |||
7037 | bool EnableLifetimeWarnings) { | |||
7038 | RevertToOldSizeRAII RAII(Path); | |||
7039 | ||||
7040 | Expr *Old; | |||
7041 | do { | |||
7042 | Old = Init; | |||
7043 | ||||
7044 | // Step into CXXDefaultInitExprs so we can diagnose cases where a | |||
7045 | // constructor inherits one as an implicit mem-initializer. | |||
7046 | if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) { | |||
7047 | Path.push_back({IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()}); | |||
7048 | Init = DIE->getExpr(); | |||
7049 | } | |||
7050 | ||||
7051 | if (auto *FE = dyn_cast<FullExpr>(Init)) | |||
7052 | Init = FE->getSubExpr(); | |||
7053 | ||||
7054 | // Dig out the expression which constructs the extended temporary. | |||
7055 | Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments()); | |||
7056 | ||||
7057 | if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init)) | |||
7058 | Init = BTE->getSubExpr(); | |||
7059 | ||||
7060 | Init = Init->IgnoreParens(); | |||
7061 | ||||
7062 | // Step over value-preserving rvalue casts. | |||
7063 | if (auto *CE = dyn_cast<CastExpr>(Init)) { | |||
7064 | switch (CE->getCastKind()) { | |||
7065 | case CK_LValueToRValue: | |||
7066 | // If we can match the lvalue to a const object, we can look at its | |||
7067 | // initializer. | |||
7068 | Path.push_back({IndirectLocalPathEntry::LValToRVal, CE}); | |||
7069 | return visitLocalsRetainedByReferenceBinding( | |||
7070 | Path, Init, RK_ReferenceBinding, | |||
7071 | [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool { | |||
7072 | if (auto *DRE = dyn_cast<DeclRefExpr>(L)) { | |||
7073 | auto *VD = dyn_cast<VarDecl>(DRE->getDecl()); | |||
7074 | if (VD && VD->getType().isConstQualified() && VD->getInit() && | |||
7075 | !isVarOnPath(Path, VD)) { | |||
7076 | Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD}); | |||
7077 | visitLocalsRetainedByInitializer(Path, VD->getInit(), Visit, true, | |||
7078 | EnableLifetimeWarnings); | |||
7079 | } | |||
7080 | } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L)) { | |||
7081 | if (MTE->getType().isConstQualified()) | |||
7082 | visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit, | |||
7083 | true, EnableLifetimeWarnings); | |||
7084 | } | |||
7085 | return false; | |||
7086 | }, EnableLifetimeWarnings); | |||
7087 | ||||
7088 | // We assume that objects can be retained by pointers cast to integers, | |||
7089 | // but not if the integer is cast to floating-point type or to _Complex. | |||
7090 | // We assume that casts to 'bool' do not preserve enough information to | |||
7091 | // retain a local object. | |||
7092 | case CK_NoOp: | |||
7093 | case CK_BitCast: | |||
7094 | case CK_BaseToDerived: | |||
7095 | case CK_DerivedToBase: | |||
7096 | case CK_UncheckedDerivedToBase: | |||
7097 | case CK_Dynamic: | |||
7098 | case CK_ToUnion: | |||
7099 | case CK_UserDefinedConversion: | |||
7100 | case CK_ConstructorConversion: | |||
7101 | case CK_IntegralToPointer: | |||
7102 | case CK_PointerToIntegral: | |||
7103 | case CK_VectorSplat: | |||
7104 | case CK_IntegralCast: | |||
7105 | case CK_CPointerToObjCPointerCast: | |||
7106 | case CK_BlockPointerToObjCPointerCast: | |||
7107 | case CK_AnyPointerToBlockPointerCast: | |||
7108 | case CK_AddressSpaceConversion: | |||
7109 | break; | |||
7110 | ||||
7111 | case CK_ArrayToPointerDecay: | |||
7112 | // Model array-to-pointer decay as taking the address of the array | |||
7113 | // lvalue. | |||
7114 | Path.push_back({IndirectLocalPathEntry::AddressOf, CE}); | |||
7115 | return visitLocalsRetainedByReferenceBinding(Path, CE->getSubExpr(), | |||
7116 | RK_ReferenceBinding, Visit, | |||
7117 | EnableLifetimeWarnings); | |||
7118 | ||||
7119 | default: | |||
7120 | return; | |||
7121 | } | |||
7122 | ||||
7123 | Init = CE->getSubExpr(); | |||
7124 | } | |||
7125 | } while (Old != Init); | |||
7126 | ||||
7127 | // C++17 [dcl.init.list]p6: | |||
7128 | // initializing an initializer_list object from the array extends the | |||
7129 | // lifetime of the array exactly like binding a reference to a temporary. | |||
7130 | if (auto *ILE = dyn_cast<CXXStdInitializerListExpr>(Init)) | |||
7131 | return visitLocalsRetainedByReferenceBinding(Path, ILE->getSubExpr(), | |||
7132 | RK_StdInitializerList, Visit, | |||
7133 | EnableLifetimeWarnings); | |||
7134 | ||||
7135 | if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) { | |||
7136 | // We already visited the elements of this initializer list while | |||
7137 | // performing the initialization. Don't visit them again unless we've | |||
7138 | // changed the lifetime of the initialized entity. | |||
7139 | if (!RevisitSubinits) | |||
7140 | return; | |||
7141 | ||||
7142 | if (ILE->isTransparent()) | |||
7143 | return visitLocalsRetainedByInitializer(Path, ILE->getInit(0), Visit, | |||
7144 | RevisitSubinits, | |||
7145 | EnableLifetimeWarnings); | |||
7146 | ||||
7147 | if (ILE->getType()->isArrayType()) { | |||
7148 | for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I) | |||
7149 | visitLocalsRetainedByInitializer(Path, ILE->getInit(I), Visit, | |||
7150 | RevisitSubinits, | |||
7151 | EnableLifetimeWarnings); | |||
7152 | return; | |||
7153 | } | |||
7154 | ||||
7155 | if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) { | |||
7156 | assert(RD->isAggregate() && "aggregate init on non-aggregate")((RD->isAggregate() && "aggregate init on non-aggregate" ) ? static_cast<void> (0) : __assert_fail ("RD->isAggregate() && \"aggregate init on non-aggregate\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 7156, __PRETTY_FUNCTION__)); | |||
7157 | ||||
7158 | // If we lifetime-extend a braced initializer which is initializing an | |||
7159 | // aggregate, and that aggregate contains reference members which are | |||
7160 | // bound to temporaries, those temporaries are also lifetime-extended. | |||
7161 | if (RD->isUnion() && ILE->getInitializedFieldInUnion() && | |||
7162 | ILE->getInitializedFieldInUnion()->getType()->isReferenceType()) | |||
7163 | visitLocalsRetainedByReferenceBinding(Path, ILE->getInit(0), | |||
7164 | RK_ReferenceBinding, Visit, | |||
7165 | EnableLifetimeWarnings); | |||
7166 | else { | |||
7167 | unsigned Index = 0; | |||
7168 | for (; Index < RD->getNumBases() && Index < ILE->getNumInits(); ++Index) | |||
7169 | visitLocalsRetainedByInitializer(Path, ILE->getInit(Index), Visit, | |||
7170 | RevisitSubinits, | |||
7171 | EnableLifetimeWarnings); | |||
7172 | for (const auto *I : RD->fields()) { | |||
7173 | if (Index >= ILE->getNumInits()) | |||
7174 | break; | |||
7175 | if (I->isUnnamedBitfield()) | |||
7176 | continue; | |||
7177 | Expr *SubInit = ILE->getInit(Index); | |||
7178 | if (I->getType()->isReferenceType()) | |||
7179 | visitLocalsRetainedByReferenceBinding(Path, SubInit, | |||
7180 | RK_ReferenceBinding, Visit, | |||
7181 | EnableLifetimeWarnings); | |||
7182 | else | |||
7183 | // This might be either aggregate-initialization of a member or | |||
7184 | // initialization of a std::initializer_list object. Regardless, | |||
7185 | // we should recursively lifetime-extend that initializer. | |||
7186 | visitLocalsRetainedByInitializer(Path, SubInit, Visit, | |||
7187 | RevisitSubinits, | |||
7188 | EnableLifetimeWarnings); | |||
7189 | ++Index; | |||
7190 | } | |||
7191 | } | |||
7192 | } | |||
7193 | return; | |||
7194 | } | |||
7195 | ||||
7196 | // The lifetime of an init-capture is that of the closure object constructed | |||
7197 | // by a lambda-expression. | |||
7198 | if (auto *LE = dyn_cast<LambdaExpr>(Init)) { | |||
7199 | for (Expr *E : LE->capture_inits()) { | |||
7200 | if (!E) | |||
7201 | continue; | |||
7202 | if (E->isGLValue()) | |||
7203 | visitLocalsRetainedByReferenceBinding(Path, E, RK_ReferenceBinding, | |||
7204 | Visit, EnableLifetimeWarnings); | |||
7205 | else | |||
7206 | visitLocalsRetainedByInitializer(Path, E, Visit, true, | |||
7207 | EnableLifetimeWarnings); | |||
7208 | } | |||
7209 | } | |||
7210 | ||||
7211 | if (isa<CallExpr>(Init) || isa<CXXConstructExpr>(Init)) { | |||
7212 | if (EnableLifetimeWarnings) | |||
7213 | handleGslAnnotatedTypes(Path, Init, Visit); | |||
7214 | return visitLifetimeBoundArguments(Path, Init, Visit); | |||
7215 | } | |||
7216 | ||||
7217 | switch (Init->getStmtClass()) { | |||
7218 | case Stmt::UnaryOperatorClass: { | |||
7219 | auto *UO = cast<UnaryOperator>(Init); | |||
7220 | // If the initializer is the address of a local, we could have a lifetime | |||
7221 | // problem. | |||
7222 | if (UO->getOpcode() == UO_AddrOf) { | |||
7223 | // If this is &rvalue, then it's ill-formed and we have already diagnosed | |||
7224 | // it. Don't produce a redundant warning about the lifetime of the | |||
7225 | // temporary. | |||
7226 | if (isa<MaterializeTemporaryExpr>(UO->getSubExpr())) | |||
7227 | return; | |||
7228 | ||||
7229 | Path.push_back({IndirectLocalPathEntry::AddressOf, UO}); | |||
7230 | visitLocalsRetainedByReferenceBinding(Path, UO->getSubExpr(), | |||
7231 | RK_ReferenceBinding, Visit, | |||
7232 | EnableLifetimeWarnings); | |||
7233 | } | |||
7234 | break; | |||
7235 | } | |||
7236 | ||||
7237 | case Stmt::BinaryOperatorClass: { | |||
7238 | // Handle pointer arithmetic. | |||
7239 | auto *BO = cast<BinaryOperator>(Init); | |||
7240 | BinaryOperatorKind BOK = BO->getOpcode(); | |||
7241 | if (!BO->getType()->isPointerType() || (BOK != BO_Add && BOK != BO_Sub)) | |||
7242 | break; | |||
7243 | ||||
7244 | if (BO->getLHS()->getType()->isPointerType()) | |||
7245 | visitLocalsRetainedByInitializer(Path, BO->getLHS(), Visit, true, | |||
7246 | EnableLifetimeWarnings); | |||
7247 | else if (BO->getRHS()->getType()->isPointerType()) | |||
7248 | visitLocalsRetainedByInitializer(Path, BO->getRHS(), Visit, true, | |||
7249 | EnableLifetimeWarnings); | |||
7250 | break; | |||
7251 | } | |||
7252 | ||||
7253 | case Stmt::ConditionalOperatorClass: | |||
7254 | case Stmt::BinaryConditionalOperatorClass: { | |||
7255 | auto *C = cast<AbstractConditionalOperator>(Init); | |||
7256 | // In C++, we can have a throw-expression operand, which has 'void' type | |||
7257 | // and isn't interesting from a lifetime perspective. | |||
7258 | if (!C->getTrueExpr()->getType()->isVoidType()) | |||
7259 | visitLocalsRetainedByInitializer(Path, C->getTrueExpr(), Visit, true, | |||
7260 | EnableLifetimeWarnings); | |||
7261 | if (!C->getFalseExpr()->getType()->isVoidType()) | |||
7262 | visitLocalsRetainedByInitializer(Path, C->getFalseExpr(), Visit, true, | |||
7263 | EnableLifetimeWarnings); | |||
7264 | break; | |||
7265 | } | |||
7266 | ||||
7267 | case Stmt::BlockExprClass: | |||
7268 | if (cast<BlockExpr>(Init)->getBlockDecl()->hasCaptures()) { | |||
7269 | // This is a local block, whose lifetime is that of the function. | |||
7270 | Visit(Path, Local(cast<BlockExpr>(Init)), RK_ReferenceBinding); | |||
7271 | } | |||
7272 | break; | |||
7273 | ||||
7274 | case Stmt::AddrLabelExprClass: | |||
7275 | // We want to warn if the address of a label would escape the function. | |||
7276 | Visit(Path, Local(cast<AddrLabelExpr>(Init)), RK_ReferenceBinding); | |||
7277 | break; | |||
7278 | ||||
7279 | default: | |||
7280 | break; | |||
7281 | } | |||
7282 | } | |||
7283 | ||||
7284 | /// Determine whether this is an indirect path to a temporary that we are | |||
7285 | /// supposed to lifetime-extend along (but don't). | |||
7286 | static bool shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path) { | |||
7287 | for (auto Elem : Path) { | |||
7288 | if (Elem.Kind != IndirectLocalPathEntry::DefaultInit) | |||
7289 | return false; | |||
7290 | } | |||
7291 | return true; | |||
7292 | } | |||
7293 | ||||
7294 | /// Find the range for the first interesting entry in the path at or after I. | |||
7295 | static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I, | |||
7296 | Expr *E) { | |||
7297 | for (unsigned N = Path.size(); I != N; ++I) { | |||
7298 | switch (Path[I].Kind) { | |||
7299 | case IndirectLocalPathEntry::AddressOf: | |||
7300 | case IndirectLocalPathEntry::LValToRVal: | |||
7301 | case IndirectLocalPathEntry::LifetimeBoundCall: | |||
7302 | case IndirectLocalPathEntry::GslReferenceInit: | |||
7303 | case IndirectLocalPathEntry::GslPointerInit: | |||
7304 | // These exist primarily to mark the path as not permitting or | |||
7305 | // supporting lifetime extension. | |||
7306 | break; | |||
7307 | ||||
7308 | case IndirectLocalPathEntry::VarInit: | |||
7309 | if (cast<VarDecl>(Path[I].D)->isImplicit()) | |||
7310 | return SourceRange(); | |||
7311 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
7312 | case IndirectLocalPathEntry::DefaultInit: | |||
7313 | return Path[I].E->getSourceRange(); | |||
7314 | } | |||
7315 | } | |||
7316 | return E->getSourceRange(); | |||
7317 | } | |||
7318 | ||||
7319 | static bool pathOnlyInitializesGslPointer(IndirectLocalPath &Path) { | |||
7320 | for (auto It = Path.rbegin(), End = Path.rend(); It != End; ++It) { | |||
7321 | if (It->Kind == IndirectLocalPathEntry::VarInit) | |||
7322 | continue; | |||
7323 | if (It->Kind == IndirectLocalPathEntry::AddressOf) | |||
7324 | continue; | |||
7325 | return It->Kind == IndirectLocalPathEntry::GslPointerInit || | |||
7326 | It->Kind == IndirectLocalPathEntry::GslReferenceInit; | |||
7327 | } | |||
7328 | return false; | |||
7329 | } | |||
7330 | ||||
7331 | void Sema::checkInitializerLifetime(const InitializedEntity &Entity, | |||
7332 | Expr *Init) { | |||
7333 | LifetimeResult LR = getEntityLifetime(&Entity); | |||
7334 | LifetimeKind LK = LR.getInt(); | |||
7335 | const InitializedEntity *ExtendingEntity = LR.getPointer(); | |||
7336 | ||||
7337 | // If this entity doesn't have an interesting lifetime, don't bother looking | |||
7338 | // for temporaries within its initializer. | |||
7339 | if (LK == LK_FullExpression) | |||
7340 | return; | |||
7341 | ||||
7342 | auto TemporaryVisitor = [&](IndirectLocalPath &Path, Local L, | |||
7343 | ReferenceKind RK) -> bool { | |||
7344 | SourceRange DiagRange = nextPathEntryRange(Path, 0, L); | |||
7345 | SourceLocation DiagLoc = DiagRange.getBegin(); | |||
7346 | ||||
7347 | auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L); | |||
7348 | ||||
7349 | bool IsGslPtrInitWithGslTempOwner = false; | |||
7350 | bool IsLocalGslOwner = false; | |||
7351 | if (pathOnlyInitializesGslPointer(Path)) { | |||
7352 | if (isa<DeclRefExpr>(L)) { | |||
7353 | // We do not want to follow the references when returning a pointer originating | |||
7354 | // from a local owner to avoid the following false positive: | |||
7355 | // int &p = *localUniquePtr; | |||
7356 | // someContainer.add(std::move(localUniquePtr)); | |||
7357 | // return p; | |||
7358 | IsLocalGslOwner = isRecordWithAttr<OwnerAttr>(L->getType()); | |||
7359 | if (pathContainsInit(Path) || !IsLocalGslOwner) | |||
7360 | return false; | |||
7361 | } else { | |||
7362 | IsGslPtrInitWithGslTempOwner = MTE && !MTE->getExtendingDecl() && | |||
7363 | isRecordWithAttr<OwnerAttr>(MTE->getType()); | |||
7364 | // Skipping a chain of initializing gsl::Pointer annotated objects. | |||
7365 | // We are looking only for the final source to find out if it was | |||
7366 | // a local or temporary owner or the address of a local variable/param. | |||
7367 | if (!IsGslPtrInitWithGslTempOwner) | |||
7368 | return true; | |||
7369 | } | |||
7370 | } | |||
7371 | ||||
7372 | switch (LK) { | |||
7373 | case LK_FullExpression: | |||
7374 | llvm_unreachable("already handled this")::llvm::llvm_unreachable_internal("already handled this", "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 7374); | |||
7375 | ||||
7376 | case LK_Extended: { | |||
7377 | if (!MTE) { | |||
7378 | // The initialized entity has lifetime beyond the full-expression, | |||
7379 | // and the local entity does too, so don't warn. | |||
7380 | // | |||
7381 | // FIXME: We should consider warning if a static / thread storage | |||
7382 | // duration variable retains an automatic storage duration local. | |||
7383 | return false; | |||
7384 | } | |||
7385 | ||||
7386 | if (IsGslPtrInitWithGslTempOwner && DiagLoc.isValid()) { | |||
7387 | Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange; | |||
7388 | return false; | |||
7389 | } | |||
7390 | ||||
7391 | // Lifetime-extend the temporary. | |||
7392 | if (Path.empty()) { | |||
7393 | // Update the storage duration of the materialized temporary. | |||
7394 | // FIXME: Rebuild the expression instead of mutating it. | |||
7395 | MTE->setExtendingDecl(ExtendingEntity->getDecl(), | |||
7396 | ExtendingEntity->allocateManglingNumber()); | |||
7397 | // Also visit the temporaries lifetime-extended by this initializer. | |||
7398 | return true; | |||
7399 | } | |||
7400 | ||||
7401 | if (shouldLifetimeExtendThroughPath(Path)) { | |||
7402 | // We're supposed to lifetime-extend the temporary along this path (per | |||
7403 | // the resolution of DR1815), but we don't support that yet. | |||
7404 | // | |||
7405 | // FIXME: Properly handle this situation. Perhaps the easiest approach | |||
7406 | // would be to clone the initializer expression on each use that would | |||
7407 | // lifetime extend its temporaries. | |||
7408 | Diag(DiagLoc, diag::warn_unsupported_lifetime_extension) | |||
7409 | << RK << DiagRange; | |||
7410 | } else { | |||
7411 | // If the path goes through the initialization of a variable or field, | |||
7412 | // it can't possibly reach a temporary created in this full-expression. | |||
7413 | // We will have already diagnosed any problems with the initializer. | |||
7414 | if (pathContainsInit(Path)) | |||
7415 | return false; | |||
7416 | ||||
7417 | Diag(DiagLoc, diag::warn_dangling_variable) | |||
7418 | << RK << !Entity.getParent() | |||
7419 | << ExtendingEntity->getDecl()->isImplicit() | |||
7420 | << ExtendingEntity->getDecl() << Init->isGLValue() << DiagRange; | |||
7421 | } | |||
7422 | break; | |||
7423 | } | |||
7424 | ||||
7425 | case LK_MemInitializer: { | |||
7426 | if (isa<MaterializeTemporaryExpr>(L)) { | |||
7427 | // Under C++ DR1696, if a mem-initializer (or a default member | |||
7428 | // initializer used by the absence of one) would lifetime-extend a | |||
7429 | // temporary, the program is ill-formed. | |||
7430 | if (auto *ExtendingDecl = | |||
7431 | ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) { | |||
7432 | if (IsGslPtrInitWithGslTempOwner) { | |||
7433 | Diag(DiagLoc, diag::warn_dangling_lifetime_pointer_member) | |||
7434 | << ExtendingDecl << DiagRange; | |||
7435 | Diag(ExtendingDecl->getLocation(), | |||
7436 | diag::note_ref_or_ptr_member_declared_here) | |||
7437 | << true; | |||
7438 | return false; | |||
7439 | } | |||
7440 | bool IsSubobjectMember = ExtendingEntity != &Entity; | |||
7441 | Diag(DiagLoc, shouldLifetimeExtendThroughPath(Path) | |||
7442 | ? diag::err_dangling_member | |||
7443 | : diag::warn_dangling_member) | |||
7444 | << ExtendingDecl << IsSubobjectMember << RK << DiagRange; | |||
7445 | // Don't bother adding a note pointing to the field if we're inside | |||
7446 | // its default member initializer; our primary diagnostic points to | |||
7447 | // the same place in that case. | |||
7448 | if (Path.empty() || | |||
7449 | Path.back().Kind != IndirectLocalPathEntry::DefaultInit) { | |||
7450 | Diag(ExtendingDecl->getLocation(), | |||
7451 | diag::note_lifetime_extending_member_declared_here) | |||
7452 | << RK << IsSubobjectMember; | |||
7453 | } | |||
7454 | } else { | |||
7455 | // We have a mem-initializer but no particular field within it; this | |||
7456 | // is either a base class or a delegating initializer directly | |||
7457 | // initializing the base-class from something that doesn't live long | |||
7458 | // enough. | |||
7459 | // | |||
7460 | // FIXME: Warn on this. | |||
7461 | return false; | |||
7462 | } | |||
7463 | } else { | |||
7464 | // Paths via a default initializer can only occur during error recovery | |||
7465 | // (there's no other way that a default initializer can refer to a | |||
7466 | // local). Don't produce a bogus warning on those cases. | |||
7467 | if (pathContainsInit(Path)) | |||
7468 | return false; | |||
7469 | ||||
7470 | // Suppress false positives for code like the one below: | |||
7471 | // Ctor(unique_ptr<T> up) : member(*up), member2(move(up)) {} | |||
7472 | if (IsLocalGslOwner && pathOnlyInitializesGslPointer(Path)) | |||
7473 | return false; | |||
7474 | ||||
7475 | auto *DRE = dyn_cast<DeclRefExpr>(L); | |||
7476 | auto *VD = DRE ? dyn_cast<VarDecl>(DRE->getDecl()) : nullptr; | |||
7477 | if (!VD) { | |||
7478 | // A member was initialized to a local block. | |||
7479 | // FIXME: Warn on this. | |||
7480 | return false; | |||
7481 | } | |||
7482 | ||||
7483 | if (auto *Member = | |||
7484 | ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) { | |||
7485 | bool IsPointer = !Member->getType()->isReferenceType(); | |||
7486 | Diag(DiagLoc, IsPointer ? diag::warn_init_ptr_member_to_parameter_addr | |||
7487 | : diag::warn_bind_ref_member_to_parameter) | |||
7488 | << Member << VD << isa<ParmVarDecl>(VD) << DiagRange; | |||
7489 | Diag(Member->getLocation(), | |||
7490 | diag::note_ref_or_ptr_member_declared_here) | |||
7491 | << (unsigned)IsPointer; | |||
7492 | } | |||
7493 | } | |||
7494 | break; | |||
7495 | } | |||
7496 | ||||
7497 | case LK_New: | |||
7498 | if (isa<MaterializeTemporaryExpr>(L)) { | |||
7499 | if (IsGslPtrInitWithGslTempOwner) | |||
7500 | Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange; | |||
7501 | else | |||
7502 | Diag(DiagLoc, RK == RK_ReferenceBinding | |||
7503 | ? diag::warn_new_dangling_reference | |||
7504 | : diag::warn_new_dangling_initializer_list) | |||
7505 | << !Entity.getParent() << DiagRange; | |||
7506 | } else { | |||
7507 | // We can't determine if the allocation outlives the local declaration. | |||
7508 | return false; | |||
7509 | } | |||
7510 | break; | |||
7511 | ||||
7512 | case LK_Return: | |||
7513 | case LK_StmtExprResult: | |||
7514 | if (auto *DRE = dyn_cast<DeclRefExpr>(L)) { | |||
7515 | // We can't determine if the local variable outlives the statement | |||
7516 | // expression. | |||
7517 | if (LK == LK_StmtExprResult) | |||
7518 | return false; | |||
7519 | Diag(DiagLoc, diag::warn_ret_stack_addr_ref) | |||
7520 | << Entity.getType()->isReferenceType() << DRE->getDecl() | |||
7521 | << isa<ParmVarDecl>(DRE->getDecl()) << DiagRange; | |||
7522 | } else if (isa<BlockExpr>(L)) { | |||
7523 | Diag(DiagLoc, diag::err_ret_local_block) << DiagRange; | |||
7524 | } else if (isa<AddrLabelExpr>(L)) { | |||
7525 | // Don't warn when returning a label from a statement expression. | |||
7526 | // Leaving the scope doesn't end its lifetime. | |||
7527 | if (LK == LK_StmtExprResult) | |||
7528 | return false; | |||
7529 | Diag(DiagLoc, diag::warn_ret_addr_label) << DiagRange; | |||
7530 | } else { | |||
7531 | Diag(DiagLoc, diag::warn_ret_local_temp_addr_ref) | |||
7532 | << Entity.getType()->isReferenceType() << DiagRange; | |||
7533 | } | |||
7534 | break; | |||
7535 | } | |||
7536 | ||||
7537 | for (unsigned I = 0; I != Path.size(); ++I) { | |||
7538 | auto Elem = Path[I]; | |||
7539 | ||||
7540 | switch (Elem.Kind) { | |||
7541 | case IndirectLocalPathEntry::AddressOf: | |||
7542 | case IndirectLocalPathEntry::LValToRVal: | |||
7543 | // These exist primarily to mark the path as not permitting or | |||
7544 | // supporting lifetime extension. | |||
7545 | break; | |||
7546 | ||||
7547 | case IndirectLocalPathEntry::LifetimeBoundCall: | |||
7548 | case IndirectLocalPathEntry::GslPointerInit: | |||
7549 | case IndirectLocalPathEntry::GslReferenceInit: | |||
7550 | // FIXME: Consider adding a note for these. | |||
7551 | break; | |||
7552 | ||||
7553 | case IndirectLocalPathEntry::DefaultInit: { | |||
7554 | auto *FD = cast<FieldDecl>(Elem.D); | |||
7555 | Diag(FD->getLocation(), diag::note_init_with_default_member_initalizer) | |||
7556 | << FD << nextPathEntryRange(Path, I + 1, L); | |||
7557 | break; | |||
7558 | } | |||
7559 | ||||
7560 | case IndirectLocalPathEntry::VarInit: | |||
7561 | const VarDecl *VD = cast<VarDecl>(Elem.D); | |||
7562 | Diag(VD->getLocation(), diag::note_local_var_initializer) | |||
7563 | << VD->getType()->isReferenceType() | |||
7564 | << VD->isImplicit() << VD->getDeclName() | |||
7565 | << nextPathEntryRange(Path, I + 1, L); | |||
7566 | break; | |||
7567 | } | |||
7568 | } | |||
7569 | ||||
7570 | // We didn't lifetime-extend, so don't go any further; we don't need more | |||
7571 | // warnings or errors on inner temporaries within this one's initializer. | |||
7572 | return false; | |||
7573 | }; | |||
7574 | ||||
7575 | bool EnableLifetimeWarnings = !getDiagnostics().isIgnored( | |||
7576 | diag::warn_dangling_lifetime_pointer, SourceLocation()); | |||
7577 | llvm::SmallVector<IndirectLocalPathEntry, 8> Path; | |||
7578 | if (Init->isGLValue()) | |||
7579 | visitLocalsRetainedByReferenceBinding(Path, Init, RK_ReferenceBinding, | |||
7580 | TemporaryVisitor, | |||
7581 | EnableLifetimeWarnings); | |||
7582 | else | |||
7583 | visitLocalsRetainedByInitializer(Path, Init, TemporaryVisitor, false, | |||
7584 | EnableLifetimeWarnings); | |||
7585 | } | |||
7586 | ||||
7587 | static void DiagnoseNarrowingInInitList(Sema &S, | |||
7588 | const ImplicitConversionSequence &ICS, | |||
7589 | QualType PreNarrowingType, | |||
7590 | QualType EntityType, | |||
7591 | const Expr *PostInit); | |||
7592 | ||||
7593 | /// Provide warnings when std::move is used on construction. | |||
7594 | static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr, | |||
7595 | bool IsReturnStmt) { | |||
7596 | if (!InitExpr) | |||
7597 | return; | |||
7598 | ||||
7599 | if (S.inTemplateInstantiation()) | |||
7600 | return; | |||
7601 | ||||
7602 | QualType DestType = InitExpr->getType(); | |||
7603 | if (!DestType->isRecordType()) | |||
7604 | return; | |||
7605 | ||||
7606 | unsigned DiagID = 0; | |||
7607 | if (IsReturnStmt) { | |||
7608 | const CXXConstructExpr *CCE = | |||
7609 | dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens()); | |||
7610 | if (!CCE || CCE->getNumArgs() != 1) | |||
7611 | return; | |||
7612 | ||||
7613 | if (!CCE->getConstructor()->isCopyOrMoveConstructor()) | |||
7614 | return; | |||
7615 | ||||
7616 | InitExpr = CCE->getArg(0)->IgnoreImpCasts(); | |||
7617 | } | |||
7618 | ||||
7619 | // Find the std::move call and get the argument. | |||
7620 | const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens()); | |||
7621 | if (!CE || !CE->isCallToStdMove()) | |||
7622 | return; | |||
7623 | ||||
7624 | const Expr *Arg = CE->getArg(0)->IgnoreImplicit(); | |||
7625 | ||||
7626 | if (IsReturnStmt) { | |||
7627 | const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts()); | |||
7628 | if (!DRE || DRE->refersToEnclosingVariableOrCapture()) | |||
7629 | return; | |||
7630 | ||||
7631 | const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()); | |||
7632 | if (!VD || !VD->hasLocalStorage()) | |||
7633 | return; | |||
7634 | ||||
7635 | // __block variables are not moved implicitly. | |||
7636 | if (VD->hasAttr<BlocksAttr>()) | |||
7637 | return; | |||
7638 | ||||
7639 | QualType SourceType = VD->getType(); | |||
7640 | if (!SourceType->isRecordType()) | |||
7641 | return; | |||
7642 | ||||
7643 | if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) { | |||
7644 | return; | |||
7645 | } | |||
7646 | ||||
7647 | // If we're returning a function parameter, copy elision | |||
7648 | // is not possible. | |||
7649 | if (isa<ParmVarDecl>(VD)) | |||
7650 | DiagID = diag::warn_redundant_move_on_return; | |||
7651 | else | |||
7652 | DiagID = diag::warn_pessimizing_move_on_return; | |||
7653 | } else { | |||
7654 | DiagID = diag::warn_pessimizing_move_on_initialization; | |||
7655 | const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens(); | |||
7656 | if (!ArgStripped->isRValue() || !ArgStripped->getType()->isRecordType()) | |||
7657 | return; | |||
7658 | } | |||
7659 | ||||
7660 | S.Diag(CE->getBeginLoc(), DiagID); | |||
7661 | ||||
7662 | // Get all the locations for a fix-it. Don't emit the fix-it if any location | |||
7663 | // is within a macro. | |||
7664 | SourceLocation CallBegin = CE->getCallee()->getBeginLoc(); | |||
7665 | if (CallBegin.isMacroID()) | |||
7666 | return; | |||
7667 | SourceLocation RParen = CE->getRParenLoc(); | |||
7668 | if (RParen.isMacroID()) | |||
7669 | return; | |||
7670 | SourceLocation LParen; | |||
7671 | SourceLocation ArgLoc = Arg->getBeginLoc(); | |||
7672 | ||||
7673 | // Special testing for the argument location. Since the fix-it needs the | |||
7674 | // location right before the argument, the argument location can be in a | |||
7675 | // macro only if it is at the beginning of the macro. | |||
7676 | while (ArgLoc.isMacroID() && | |||
7677 | S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) { | |||
7678 | ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).getBegin(); | |||
7679 | } | |||
7680 | ||||
7681 | if (LParen.isMacroID()) | |||
7682 | return; | |||
7683 | ||||
7684 | LParen = ArgLoc.getLocWithOffset(-1); | |||
7685 | ||||
7686 | S.Diag(CE->getBeginLoc(), diag::note_remove_move) | |||
7687 | << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen)) | |||
7688 | << FixItHint::CreateRemoval(SourceRange(RParen, RParen)); | |||
7689 | } | |||
7690 | ||||
7691 | static void CheckForNullPointerDereference(Sema &S, const Expr *E) { | |||
7692 | // Check to see if we are dereferencing a null pointer. If so, this is | |||
7693 | // undefined behavior, so warn about it. This only handles the pattern | |||
7694 | // "*null", which is a very syntactic check. | |||
7695 | if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) | |||
7696 | if (UO->getOpcode() == UO_Deref && | |||
7697 | UO->getSubExpr()->IgnoreParenCasts()-> | |||
7698 | isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) { | |||
7699 | S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, | |||
7700 | S.PDiag(diag::warn_binding_null_to_reference) | |||
7701 | << UO->getSubExpr()->getSourceRange()); | |||
7702 | } | |||
7703 | } | |||
7704 | ||||
7705 | MaterializeTemporaryExpr * | |||
7706 | Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, | |||
7707 | bool BoundToLvalueReference) { | |||
7708 | auto MTE = new (Context) | |||
7709 | MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference); | |||
7710 | ||||
7711 | // Order an ExprWithCleanups for lifetime marks. | |||
7712 | // | |||
7713 | // TODO: It'll be good to have a single place to check the access of the | |||
7714 | // destructor and generate ExprWithCleanups for various uses. Currently these | |||
7715 | // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary, | |||
7716 | // but there may be a chance to merge them. | |||
7717 | Cleanup.setExprNeedsCleanups(false); | |||
7718 | return MTE; | |||
7719 | } | |||
7720 | ||||
7721 | ExprResult Sema::TemporaryMaterializationConversion(Expr *E) { | |||
7722 | // In C++98, we don't want to implicitly create an xvalue. | |||
7723 | // FIXME: This means that AST consumers need to deal with "prvalues" that | |||
7724 | // denote materialized temporaries. Maybe we should add another ValueKind | |||
7725 | // for "xvalue pretending to be a prvalue" for C++98 support. | |||
7726 | if (!E->isRValue() || !getLangOpts().CPlusPlus11) | |||
7727 | return E; | |||
7728 | ||||
7729 | // C++1z [conv.rval]/1: T shall be a complete type. | |||
7730 | // FIXME: Does this ever matter (can we form a prvalue of incomplete type)? | |||
7731 | // If so, we should check for a non-abstract class type here too. | |||
7732 | QualType T = E->getType(); | |||
7733 | if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type)) | |||
7734 | return ExprError(); | |||
7735 | ||||
7736 | return CreateMaterializeTemporaryExpr(E->getType(), E, false); | |||
7737 | } | |||
7738 | ||||
7739 | ExprResult Sema::PerformQualificationConversion(Expr *E, QualType Ty, | |||
7740 | ExprValueKind VK, | |||
7741 | CheckedConversionKind CCK) { | |||
7742 | ||||
7743 | CastKind CK = CK_NoOp; | |||
7744 | ||||
7745 | if (VK == VK_RValue) { | |||
7746 | auto PointeeTy = Ty->getPointeeType(); | |||
7747 | auto ExprPointeeTy = E->getType()->getPointeeType(); | |||
7748 | if (!PointeeTy.isNull() && | |||
7749 | PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace()) | |||
7750 | CK = CK_AddressSpaceConversion; | |||
7751 | } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) { | |||
7752 | CK = CK_AddressSpaceConversion; | |||
7753 | } | |||
7754 | ||||
7755 | return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK); | |||
7756 | } | |||
7757 | ||||
7758 | ExprResult InitializationSequence::Perform(Sema &S, | |||
7759 | const InitializedEntity &Entity, | |||
7760 | const InitializationKind &Kind, | |||
7761 | MultiExprArg Args, | |||
7762 | QualType *ResultType) { | |||
7763 | if (Failed()) { | |||
7764 | Diagnose(S, Entity, Kind, Args); | |||
7765 | return ExprError(); | |||
7766 | } | |||
7767 | if (!ZeroInitializationFixit.empty()) { | |||
7768 | unsigned DiagID = diag::err_default_init_const; | |||
7769 | if (Decl *D = Entity.getDecl()) | |||
7770 | if (S.getLangOpts().MSVCCompat && D->hasAttr<SelectAnyAttr>()) | |||
7771 | DiagID = diag::ext_default_init_const; | |||
7772 | ||||
7773 | // The initialization would have succeeded with this fixit. Since the fixit | |||
7774 | // is on the error, we need to build a valid AST in this case, so this isn't | |||
7775 | // handled in the Failed() branch above. | |||
7776 | QualType DestType = Entity.getType(); | |||
7777 | S.Diag(Kind.getLocation(), DiagID) | |||
7778 | << DestType << (bool)DestType->getAs<RecordType>() | |||
7779 | << FixItHint::CreateInsertion(ZeroInitializationFixitLoc, | |||
7780 | ZeroInitializationFixit); | |||
7781 | } | |||
7782 | ||||
7783 | if (getKind() == DependentSequence) { | |||
7784 | // If the declaration is a non-dependent, incomplete array type | |||
7785 | // that has an initializer, then its type will be completed once | |||
7786 | // the initializer is instantiated. | |||
7787 | if (ResultType && !Entity.getType()->isDependentType() && | |||
7788 | Args.size() == 1) { | |||
7789 | QualType DeclType = Entity.getType(); | |||
7790 | if (const IncompleteArrayType *ArrayT | |||
7791 | = S.Context.getAsIncompleteArrayType(DeclType)) { | |||
7792 | // FIXME: We don't currently have the ability to accurately | |||
7793 | // compute the length of an initializer list without | |||
7794 | // performing full type-checking of the initializer list | |||
7795 | // (since we have to determine where braces are implicitly | |||
7796 | // introduced and such). So, we fall back to making the array | |||
7797 | // type a dependently-sized array type with no specified | |||
7798 | // bound. | |||
7799 | if (isa<InitListExpr>((Expr *)Args[0])) { | |||
7800 | SourceRange Brackets; | |||
7801 | ||||
7802 | // Scavange the location of the brackets from the entity, if we can. | |||
7803 | if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) { | |||
7804 | if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) { | |||
7805 | TypeLoc TL = TInfo->getTypeLoc(); | |||
7806 | if (IncompleteArrayTypeLoc ArrayLoc = | |||
7807 | TL.getAs<IncompleteArrayTypeLoc>()) | |||
7808 | Brackets = ArrayLoc.getBracketsRange(); | |||
7809 | } | |||
7810 | } | |||
7811 | ||||
7812 | *ResultType | |||
7813 | = S.Context.getDependentSizedArrayType(ArrayT->getElementType(), | |||
7814 | /*NumElts=*/nullptr, | |||
7815 | ArrayT->getSizeModifier(), | |||
7816 | ArrayT->getIndexTypeCVRQualifiers(), | |||
7817 | Brackets); | |||
7818 | } | |||
7819 | ||||
7820 | } | |||
7821 | } | |||
7822 | if (Kind.getKind() == InitializationKind::IK_Direct && | |||
7823 | !Kind.isExplicitCast()) { | |||
7824 | // Rebuild the ParenListExpr. | |||
7825 | SourceRange ParenRange = Kind.getParenOrBraceRange(); | |||
7826 | return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(), | |||
7827 | Args); | |||
7828 | } | |||
7829 | assert(Kind.getKind() == InitializationKind::IK_Copy ||((Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast () || Kind.getKind() == InitializationKind::IK_DirectList) ? static_cast <void> (0) : __assert_fail ("Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast() || Kind.getKind() == InitializationKind::IK_DirectList" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 7831, __PRETTY_FUNCTION__)) | |||
7830 | Kind.isExplicitCast() ||((Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast () || Kind.getKind() == InitializationKind::IK_DirectList) ? static_cast <void> (0) : __assert_fail ("Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast() || Kind.getKind() == InitializationKind::IK_DirectList" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 7831, __PRETTY_FUNCTION__)) | |||
7831 | Kind.getKind() == InitializationKind::IK_DirectList)((Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast () || Kind.getKind() == InitializationKind::IK_DirectList) ? static_cast <void> (0) : __assert_fail ("Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast() || Kind.getKind() == InitializationKind::IK_DirectList" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 7831, __PRETTY_FUNCTION__)); | |||
7832 | return ExprResult(Args[0]); | |||
7833 | } | |||
7834 | ||||
7835 | // No steps means no initialization. | |||
7836 | if (Steps.empty()) | |||
7837 | return ExprResult((Expr *)nullptr); | |||
7838 | ||||
7839 | if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() && | |||
7840 | Args.size() == 1 && isa<InitListExpr>(Args[0]) && | |||
7841 | !Entity.isParameterKind()) { | |||
7842 | // Produce a C++98 compatibility warning if we are initializing a reference | |||
7843 | // from an initializer list. For parameters, we produce a better warning | |||
7844 | // elsewhere. | |||
7845 | Expr *Init = Args[0]; | |||
7846 | S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init) | |||
7847 | << Init->getSourceRange(); | |||
7848 | } | |||
7849 | ||||
7850 | // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope | |||
7851 | QualType ETy = Entity.getType(); | |||
7852 | bool HasGlobalAS = ETy.hasAddressSpace() && | |||
7853 | ETy.getAddressSpace() == LangAS::opencl_global; | |||
7854 | ||||
7855 | if (S.getLangOpts().OpenCLVersion >= 200 && | |||
7856 | ETy->isAtomicType() && !HasGlobalAS && | |||
7857 | Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) { | |||
7858 | S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init) | |||
7859 | << 1 | |||
7860 | << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc()); | |||
7861 | return ExprError(); | |||
7862 | } | |||
7863 | ||||
7864 | QualType DestType = Entity.getType().getNonReferenceType(); | |||
7865 | // FIXME: Ugly hack around the fact that Entity.getType() is not | |||
7866 | // the same as Entity.getDecl()->getType() in cases involving type merging, | |||
7867 | // and we want latter when it makes sense. | |||
7868 | if (ResultType) | |||
7869 | *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() : | |||
7870 | Entity.getType(); | |||
7871 | ||||
7872 | ExprResult CurInit((Expr *)nullptr); | |||
7873 | SmallVector<Expr*, 4> ArrayLoopCommonExprs; | |||
7874 | ||||
7875 | // For initialization steps that start with a single initializer, | |||
7876 | // grab the only argument out the Args and place it into the "current" | |||
7877 | // initializer. | |||
7878 | switch (Steps.front().Kind) { | |||
7879 | case SK_ResolveAddressOfOverloadedFunction: | |||
7880 | case SK_CastDerivedToBaseRValue: | |||
7881 | case SK_CastDerivedToBaseXValue: | |||
7882 | case SK_CastDerivedToBaseLValue: | |||
7883 | case SK_BindReference: | |||
7884 | case SK_BindReferenceToTemporary: | |||
7885 | case SK_FinalCopy: | |||
7886 | case SK_ExtraneousCopyToTemporary: | |||
7887 | case SK_UserConversion: | |||
7888 | case SK_QualificationConversionLValue: | |||
7889 | case SK_QualificationConversionXValue: | |||
7890 | case SK_QualificationConversionRValue: | |||
7891 | case SK_AtomicConversion: | |||
7892 | case SK_ConversionSequence: | |||
7893 | case SK_ConversionSequenceNoNarrowing: | |||
7894 | case SK_ListInitialization: | |||
7895 | case SK_UnwrapInitList: | |||
7896 | case SK_RewrapInitList: | |||
7897 | case SK_CAssignment: | |||
7898 | case SK_StringInit: | |||
7899 | case SK_ObjCObjectConversion: | |||
7900 | case SK_ArrayLoopIndex: | |||
7901 | case SK_ArrayLoopInit: | |||
7902 | case SK_ArrayInit: | |||
7903 | case SK_GNUArrayInit: | |||
7904 | case SK_ParenthesizedArrayInit: | |||
7905 | case SK_PassByIndirectCopyRestore: | |||
7906 | case SK_PassByIndirectRestore: | |||
7907 | case SK_ProduceObjCObject: | |||
7908 | case SK_StdInitializerList: | |||
7909 | case SK_OCLSamplerInit: | |||
7910 | case SK_OCLZeroOpaqueType: { | |||
7911 | assert(Args.size() == 1)((Args.size() == 1) ? static_cast<void> (0) : __assert_fail ("Args.size() == 1", "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 7911, __PRETTY_FUNCTION__)); | |||
7912 | CurInit = Args[0]; | |||
7913 | if (!CurInit.get()) return ExprError(); | |||
7914 | break; | |||
7915 | } | |||
7916 | ||||
7917 | case SK_ConstructorInitialization: | |||
7918 | case SK_ConstructorInitializationFromList: | |||
7919 | case SK_StdInitializerListConstructorCall: | |||
7920 | case SK_ZeroInitialization: | |||
7921 | break; | |||
7922 | } | |||
7923 | ||||
7924 | // Promote from an unevaluated context to an unevaluated list context in | |||
7925 | // C++11 list-initialization; we need to instantiate entities usable in | |||
7926 | // constant expressions here in order to perform narrowing checks =( | |||
7927 | EnterExpressionEvaluationContext Evaluated( | |||
7928 | S, EnterExpressionEvaluationContext::InitList, | |||
7929 | CurInit.get() && isa<InitListExpr>(CurInit.get())); | |||
7930 | ||||
7931 | // C++ [class.abstract]p2: | |||
7932 | // no objects of an abstract class can be created except as subobjects | |||
7933 | // of a class derived from it | |||
7934 | auto checkAbstractType = [&](QualType T) -> bool { | |||
7935 | if (Entity.getKind() == InitializedEntity::EK_Base || | |||
7936 | Entity.getKind() == InitializedEntity::EK_Delegating) | |||
7937 | return false; | |||
7938 | return S.RequireNonAbstractType(Kind.getLocation(), T, | |||
7939 | diag::err_allocation_of_abstract_type); | |||
7940 | }; | |||
7941 | ||||
7942 | // Walk through the computed steps for the initialization sequence, | |||
7943 | // performing the specified conversions along the way. | |||
7944 | bool ConstructorInitRequiresZeroInit = false; | |||
7945 | for (step_iterator Step = step_begin(), StepEnd = step_end(); | |||
7946 | Step != StepEnd; ++Step) { | |||
7947 | if (CurInit.isInvalid()) | |||
7948 | return ExprError(); | |||
7949 | ||||
7950 | QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType(); | |||
7951 | ||||
7952 | switch (Step->Kind) { | |||
7953 | case SK_ResolveAddressOfOverloadedFunction: | |||
7954 | // Overload resolution determined which function invoke; update the | |||
7955 | // initializer to reflect that choice. | |||
7956 | S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl); | |||
7957 | if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation())) | |||
7958 | return ExprError(); | |||
7959 | CurInit = S.FixOverloadedFunctionReference(CurInit, | |||
7960 | Step->Function.FoundDecl, | |||
7961 | Step->Function.Function); | |||
7962 | break; | |||
7963 | ||||
7964 | case SK_CastDerivedToBaseRValue: | |||
7965 | case SK_CastDerivedToBaseXValue: | |||
7966 | case SK_CastDerivedToBaseLValue: { | |||
7967 | // We have a derived-to-base cast that produces either an rvalue or an | |||
7968 | // lvalue. Perform that cast. | |||
7969 | ||||
7970 | CXXCastPath BasePath; | |||
7971 | ||||
7972 | // Casts to inaccessible base classes are allowed with C-style casts. | |||
7973 | bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast(); | |||
7974 | if (S.CheckDerivedToBaseConversion( | |||
7975 | SourceType, Step->Type, CurInit.get()->getBeginLoc(), | |||
7976 | CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess)) | |||
7977 | return ExprError(); | |||
7978 | ||||
7979 | ExprValueKind VK = | |||
7980 | Step->Kind == SK_CastDerivedToBaseLValue ? | |||
7981 | VK_LValue : | |||
7982 | (Step->Kind == SK_CastDerivedToBaseXValue ? | |||
7983 | VK_XValue : | |||
7984 | VK_RValue); | |||
7985 | CurInit = | |||
7986 | ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase, | |||
7987 | CurInit.get(), &BasePath, VK); | |||
7988 | break; | |||
7989 | } | |||
7990 | ||||
7991 | case SK_BindReference: | |||
7992 | // Reference binding does not have any corresponding ASTs. | |||
7993 | ||||
7994 | // Check exception specifications | |||
7995 | if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType)) | |||
7996 | return ExprError(); | |||
7997 | ||||
7998 | // We don't check for e.g. function pointers here, since address | |||
7999 | // availability checks should only occur when the function first decays | |||
8000 | // into a pointer or reference. | |||
8001 | if (CurInit.get()->getType()->isFunctionProtoType()) { | |||
8002 | if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) { | |||
8003 | if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) { | |||
8004 | if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, | |||
8005 | DRE->getBeginLoc())) | |||
8006 | return ExprError(); | |||
8007 | } | |||
8008 | } | |||
8009 | } | |||
8010 | ||||
8011 | CheckForNullPointerDereference(S, CurInit.get()); | |||
8012 | break; | |||
8013 | ||||
8014 | case SK_BindReferenceToTemporary: { | |||
8015 | // Make sure the "temporary" is actually an rvalue. | |||
8016 | assert(CurInit.get()->isRValue() && "not a temporary")((CurInit.get()->isRValue() && "not a temporary") ? static_cast<void> (0) : __assert_fail ("CurInit.get()->isRValue() && \"not a temporary\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 8016, __PRETTY_FUNCTION__)); | |||
8017 | ||||
8018 | // Check exception specifications | |||
8019 | if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType)) | |||
8020 | return ExprError(); | |||
8021 | ||||
8022 | // Materialize the temporary into memory. | |||
8023 | MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr( | |||
8024 | Step->Type, CurInit.get(), Entity.getType()->isLValueReferenceType()); | |||
8025 | CurInit = MTE; | |||
8026 | ||||
8027 | // If we're extending this temporary to automatic storage duration -- we | |||
8028 | // need to register its cleanup during the full-expression's cleanups. | |||
8029 | if (MTE->getStorageDuration() == SD_Automatic && | |||
8030 | MTE->getType().isDestructedType()) | |||
8031 | S.Cleanup.setExprNeedsCleanups(true); | |||
8032 | break; | |||
8033 | } | |||
8034 | ||||
8035 | case SK_FinalCopy: | |||
8036 | if (checkAbstractType(Step->Type)) | |||
8037 | return ExprError(); | |||
8038 | ||||
8039 | // If the overall initialization is initializing a temporary, we already | |||
8040 | // bound our argument if it was necessary to do so. If not (if we're | |||
8041 | // ultimately initializing a non-temporary), our argument needs to be | |||
8042 | // bound since it's initializing a function parameter. | |||
8043 | // FIXME: This is a mess. Rationalize temporary destruction. | |||
8044 | if (!shouldBindAsTemporary(Entity)) | |||
8045 | CurInit = S.MaybeBindToTemporary(CurInit.get()); | |||
8046 | CurInit = CopyObject(S, Step->Type, Entity, CurInit, | |||
8047 | /*IsExtraneousCopy=*/false); | |||
8048 | break; | |||
8049 | ||||
8050 | case SK_ExtraneousCopyToTemporary: | |||
8051 | CurInit = CopyObject(S, Step->Type, Entity, CurInit, | |||
8052 | /*IsExtraneousCopy=*/true); | |||
8053 | break; | |||
8054 | ||||
8055 | case SK_UserConversion: { | |||
8056 | // We have a user-defined conversion that invokes either a constructor | |||
8057 | // or a conversion function. | |||
8058 | CastKind CastKind; | |||
8059 | FunctionDecl *Fn = Step->Function.Function; | |||
8060 | DeclAccessPair FoundFn = Step->Function.FoundDecl; | |||
8061 | bool HadMultipleCandidates = Step->Function.HadMultipleCandidates; | |||
8062 | bool CreatedObject = false; | |||
8063 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) { | |||
8064 | // Build a call to the selected constructor. | |||
8065 | SmallVector<Expr*, 8> ConstructorArgs; | |||
8066 | SourceLocation Loc = CurInit.get()->getBeginLoc(); | |||
8067 | ||||
8068 | // Determine the arguments required to actually perform the constructor | |||
8069 | // call. | |||
8070 | Expr *Arg = CurInit.get(); | |||
8071 | if (S.CompleteConstructorCall(Constructor, | |||
8072 | MultiExprArg(&Arg, 1), | |||
8073 | Loc, ConstructorArgs)) | |||
8074 | return ExprError(); | |||
8075 | ||||
8076 | // Build an expression that constructs a temporary. | |||
8077 | CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, | |||
8078 | FoundFn, Constructor, | |||
8079 | ConstructorArgs, | |||
8080 | HadMultipleCandidates, | |||
8081 | /*ListInit*/ false, | |||
8082 | /*StdInitListInit*/ false, | |||
8083 | /*ZeroInit*/ false, | |||
8084 | CXXConstructExpr::CK_Complete, | |||
8085 | SourceRange()); | |||
8086 | if (CurInit.isInvalid()) | |||
8087 | return ExprError(); | |||
8088 | ||||
8089 | S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn, | |||
8090 | Entity); | |||
8091 | if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation())) | |||
8092 | return ExprError(); | |||
8093 | ||||
8094 | CastKind = CK_ConstructorConversion; | |||
8095 | CreatedObject = true; | |||
8096 | } else { | |||
8097 | // Build a call to the conversion function. | |||
8098 | CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn); | |||
8099 | S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr, | |||
8100 | FoundFn); | |||
8101 | if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation())) | |||
8102 | return ExprError(); | |||
8103 | ||||
8104 | CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion, | |||
8105 | HadMultipleCandidates); | |||
8106 | if (CurInit.isInvalid()) | |||
8107 | return ExprError(); | |||
8108 | ||||
8109 | CastKind = CK_UserDefinedConversion; | |||
8110 | CreatedObject = Conversion->getReturnType()->isRecordType(); | |||
8111 | } | |||
8112 | ||||
8113 | if (CreatedObject && checkAbstractType(CurInit.get()->getType())) | |||
8114 | return ExprError(); | |||
8115 | ||||
8116 | CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(), | |||
8117 | CastKind, CurInit.get(), nullptr, | |||
8118 | CurInit.get()->getValueKind()); | |||
8119 | ||||
8120 | if (shouldBindAsTemporary(Entity)) | |||
8121 | // The overall entity is temporary, so this expression should be | |||
8122 | // destroyed at the end of its full-expression. | |||
8123 | CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>()); | |||
8124 | else if (CreatedObject && shouldDestroyEntity(Entity)) { | |||
8125 | // The object outlasts the full-expression, but we need to prepare for | |||
8126 | // a destructor being run on it. | |||
8127 | // FIXME: It makes no sense to do this here. This should happen | |||
8128 | // regardless of how we initialized the entity. | |||
8129 | QualType T = CurInit.get()->getType(); | |||
8130 | if (const RecordType *Record = T->getAs<RecordType>()) { | |||
8131 | CXXDestructorDecl *Destructor | |||
8132 | = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl())); | |||
8133 | S.CheckDestructorAccess(CurInit.get()->getBeginLoc(), Destructor, | |||
8134 | S.PDiag(diag::err_access_dtor_temp) << T); | |||
8135 | S.MarkFunctionReferenced(CurInit.get()->getBeginLoc(), Destructor); | |||
8136 | if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc())) | |||
8137 | return ExprError(); | |||
8138 | } | |||
8139 | } | |||
8140 | break; | |||
8141 | } | |||
8142 | ||||
8143 | case SK_QualificationConversionLValue: | |||
8144 | case SK_QualificationConversionXValue: | |||
8145 | case SK_QualificationConversionRValue: { | |||
8146 | // Perform a qualification conversion; these can never go wrong. | |||
8147 | ExprValueKind VK = | |||
8148 | Step->Kind == SK_QualificationConversionLValue | |||
8149 | ? VK_LValue | |||
8150 | : (Step->Kind == SK_QualificationConversionXValue ? VK_XValue | |||
8151 | : VK_RValue); | |||
8152 | CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK); | |||
8153 | break; | |||
8154 | } | |||
8155 | ||||
8156 | case SK_AtomicConversion: { | |||
8157 | assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic")((CurInit.get()->isRValue() && "cannot convert glvalue to atomic" ) ? static_cast<void> (0) : __assert_fail ("CurInit.get()->isRValue() && \"cannot convert glvalue to atomic\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 8157, __PRETTY_FUNCTION__)); | |||
8158 | CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, | |||
8159 | CK_NonAtomicToAtomic, VK_RValue); | |||
8160 | break; | |||
8161 | } | |||
8162 | ||||
8163 | case SK_ConversionSequence: | |||
8164 | case SK_ConversionSequenceNoNarrowing: { | |||
8165 | if (const auto *FromPtrType = | |||
8166 | CurInit.get()->getType()->getAs<PointerType>()) { | |||
8167 | if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) { | |||
8168 | if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) && | |||
8169 | !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { | |||
8170 | S.Diag(CurInit.get()->getExprLoc(), | |||
8171 | diag::warn_noderef_to_dereferenceable_pointer) | |||
8172 | << CurInit.get()->getSourceRange(); | |||
8173 | } | |||
8174 | } | |||
8175 | } | |||
8176 | ||||
8177 | Sema::CheckedConversionKind CCK | |||
8178 | = Kind.isCStyleCast()? Sema::CCK_CStyleCast | |||
8179 | : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast | |||
8180 | : Kind.isExplicitCast()? Sema::CCK_OtherCast | |||
8181 | : Sema::CCK_ImplicitConversion; | |||
8182 | ExprResult CurInitExprRes = | |||
8183 | S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS, | |||
8184 | getAssignmentAction(Entity), CCK); | |||
8185 | if (CurInitExprRes.isInvalid()) | |||
8186 | return ExprError(); | |||
8187 | ||||
8188 | S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), CurInit.get()); | |||
8189 | ||||
8190 | CurInit = CurInitExprRes; | |||
8191 | ||||
8192 | if (Step->Kind == SK_ConversionSequenceNoNarrowing && | |||
8193 | S.getLangOpts().CPlusPlus) | |||
8194 | DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(), | |||
8195 | CurInit.get()); | |||
8196 | ||||
8197 | break; | |||
8198 | } | |||
8199 | ||||
8200 | case SK_ListInitialization: { | |||
8201 | if (checkAbstractType(Step->Type)) | |||
8202 | return ExprError(); | |||
8203 | ||||
8204 | InitListExpr *InitList = cast<InitListExpr>(CurInit.get()); | |||
8205 | // If we're not initializing the top-level entity, we need to create an | |||
8206 | // InitializeTemporary entity for our target type. | |||
8207 | QualType Ty = Step->Type; | |||
8208 | bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty); | |||
8209 | InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty); | |||
8210 | InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity; | |||
8211 | InitListChecker PerformInitList(S, InitEntity, | |||
8212 | InitList, Ty, /*VerifyOnly=*/false, | |||
8213 | /*TreatUnavailableAsInvalid=*/false); | |||
8214 | if (PerformInitList.HadError()) | |||
8215 | return ExprError(); | |||
8216 | ||||
8217 | // Hack: We must update *ResultType if available in order to set the | |||
8218 | // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'. | |||
8219 | // Worst case: 'const int (&arref)[] = {1, 2, 3};'. | |||
8220 | if (ResultType && | |||
8221 | ResultType->getNonReferenceType()->isIncompleteArrayType()) { | |||
8222 | if ((*ResultType)->isRValueReferenceType()) | |||
8223 | Ty = S.Context.getRValueReferenceType(Ty); | |||
8224 | else if ((*ResultType)->isLValueReferenceType()) | |||
8225 | Ty = S.Context.getLValueReferenceType(Ty, | |||
8226 | (*ResultType)->castAs<LValueReferenceType>()->isSpelledAsLValue()); | |||
8227 | *ResultType = Ty; | |||
8228 | } | |||
8229 | ||||
8230 | InitListExpr *StructuredInitList = | |||
8231 | PerformInitList.getFullyStructuredList(); | |||
8232 | CurInit.get(); | |||
8233 | CurInit = shouldBindAsTemporary(InitEntity) | |||
8234 | ? S.MaybeBindToTemporary(StructuredInitList) | |||
8235 | : StructuredInitList; | |||
8236 | break; | |||
8237 | } | |||
8238 | ||||
8239 | case SK_ConstructorInitializationFromList: { | |||
8240 | if (checkAbstractType(Step->Type)) | |||
8241 | return ExprError(); | |||
8242 | ||||
8243 | // When an initializer list is passed for a parameter of type "reference | |||
8244 | // to object", we don't get an EK_Temporary entity, but instead an | |||
8245 | // EK_Parameter entity with reference type. | |||
8246 | // FIXME: This is a hack. What we really should do is create a user | |||
8247 | // conversion step for this case, but this makes it considerably more | |||
8248 | // complicated. For now, this will do. | |||
8249 | InitializedEntity TempEntity = InitializedEntity::InitializeTemporary( | |||
8250 | Entity.getType().getNonReferenceType()); | |||
8251 | bool UseTemporary = Entity.getType()->isReferenceType(); | |||
8252 | assert(Args.size() == 1 && "expected a single argument for list init")((Args.size() == 1 && "expected a single argument for list init" ) ? static_cast<void> (0) : __assert_fail ("Args.size() == 1 && \"expected a single argument for list init\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 8252, __PRETTY_FUNCTION__)); | |||
8253 | InitListExpr *InitList = cast<InitListExpr>(Args[0]); | |||
8254 | S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init) | |||
8255 | << InitList->getSourceRange(); | |||
8256 | MultiExprArg Arg(InitList->getInits(), InitList->getNumInits()); | |||
8257 | CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity : | |||
8258 | Entity, | |||
8259 | Kind, Arg, *Step, | |||
8260 | ConstructorInitRequiresZeroInit, | |||
8261 | /*IsListInitialization*/true, | |||
8262 | /*IsStdInitListInit*/false, | |||
8263 | InitList->getLBraceLoc(), | |||
8264 | InitList->getRBraceLoc()); | |||
8265 | break; | |||
8266 | } | |||
8267 | ||||
8268 | case SK_UnwrapInitList: | |||
8269 | CurInit = cast<InitListExpr>(CurInit.get())->getInit(0); | |||
8270 | break; | |||
8271 | ||||
8272 | case SK_RewrapInitList: { | |||
8273 | Expr *E = CurInit.get(); | |||
8274 | InitListExpr *Syntactic = Step->WrappingSyntacticList; | |||
8275 | InitListExpr *ILE = new (S.Context) InitListExpr(S.Context, | |||
8276 | Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc()); | |||
8277 | ILE->setSyntacticForm(Syntactic); | |||
8278 | ILE->setType(E->getType()); | |||
8279 | ILE->setValueKind(E->getValueKind()); | |||
8280 | CurInit = ILE; | |||
8281 | break; | |||
8282 | } | |||
8283 | ||||
8284 | case SK_ConstructorInitialization: | |||
8285 | case SK_StdInitializerListConstructorCall: { | |||
8286 | if (checkAbstractType(Step->Type)) | |||
8287 | return ExprError(); | |||
8288 | ||||
8289 | // When an initializer list is passed for a parameter of type "reference | |||
8290 | // to object", we don't get an EK_Temporary entity, but instead an | |||
8291 | // EK_Parameter entity with reference type. | |||
8292 | // FIXME: This is a hack. What we really should do is create a user | |||
8293 | // conversion step for this case, but this makes it considerably more | |||
8294 | // complicated. For now, this will do. | |||
8295 | InitializedEntity TempEntity = InitializedEntity::InitializeTemporary( | |||
8296 | Entity.getType().getNonReferenceType()); | |||
8297 | bool UseTemporary = Entity.getType()->isReferenceType(); | |||
8298 | bool IsStdInitListInit = | |||
8299 | Step->Kind == SK_StdInitializerListConstructorCall; | |||
8300 | Expr *Source = CurInit.get(); | |||
8301 | SourceRange Range = Kind.hasParenOrBraceRange() | |||
8302 | ? Kind.getParenOrBraceRange() | |||
8303 | : SourceRange(); | |||
8304 | CurInit = PerformConstructorInitialization( | |||
8305 | S, UseTemporary ? TempEntity : Entity, Kind, | |||
8306 | Source ? MultiExprArg(Source) : Args, *Step, | |||
8307 | ConstructorInitRequiresZeroInit, | |||
8308 | /*IsListInitialization*/ IsStdInitListInit, | |||
8309 | /*IsStdInitListInitialization*/ IsStdInitListInit, | |||
8310 | /*LBraceLoc*/ Range.getBegin(), | |||
8311 | /*RBraceLoc*/ Range.getEnd()); | |||
8312 | break; | |||
8313 | } | |||
8314 | ||||
8315 | case SK_ZeroInitialization: { | |||
8316 | step_iterator NextStep = Step; | |||
8317 | ++NextStep; | |||
8318 | if (NextStep != StepEnd && | |||
8319 | (NextStep->Kind == SK_ConstructorInitialization || | |||
8320 | NextStep->Kind == SK_ConstructorInitializationFromList)) { | |||
8321 | // The need for zero-initialization is recorded directly into | |||
8322 | // the call to the object's constructor within the next step. | |||
8323 | ConstructorInitRequiresZeroInit = true; | |||
8324 | } else if (Kind.getKind() == InitializationKind::IK_Value && | |||
8325 | S.getLangOpts().CPlusPlus && | |||
8326 | !Kind.isImplicitValueInit()) { | |||
8327 | TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo(); | |||
8328 | if (!TSInfo) | |||
8329 | TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type, | |||
8330 | Kind.getRange().getBegin()); | |||
8331 | ||||
8332 | CurInit = new (S.Context) CXXScalarValueInitExpr( | |||
8333 | Entity.getType().getNonLValueExprType(S.Context), TSInfo, | |||
8334 | Kind.getRange().getEnd()); | |||
8335 | } else { | |||
8336 | CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type); | |||
8337 | } | |||
8338 | break; | |||
8339 | } | |||
8340 | ||||
8341 | case SK_CAssignment: { | |||
8342 | QualType SourceType = CurInit.get()->getType(); | |||
8343 | ||||
8344 | // Save off the initial CurInit in case we need to emit a diagnostic | |||
8345 | ExprResult InitialCurInit = CurInit; | |||
8346 | ExprResult Result = CurInit; | |||
8347 | Sema::AssignConvertType ConvTy = | |||
8348 | S.CheckSingleAssignmentConstraints(Step->Type, Result, true, | |||
8349 | Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited); | |||
8350 | if (Result.isInvalid()) | |||
8351 | return ExprError(); | |||
8352 | CurInit = Result; | |||
8353 | ||||
8354 | // If this is a call, allow conversion to a transparent union. | |||
8355 | ExprResult CurInitExprRes = CurInit; | |||
8356 | if (ConvTy != Sema::Compatible && | |||
8357 | Entity.isParameterKind() && | |||
8358 | S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes) | |||
8359 | == Sema::Compatible) | |||
8360 | ConvTy = Sema::Compatible; | |||
8361 | if (CurInitExprRes.isInvalid()) | |||
8362 | return ExprError(); | |||
8363 | CurInit = CurInitExprRes; | |||
8364 | ||||
8365 | bool Complained; | |||
8366 | if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(), | |||
8367 | Step->Type, SourceType, | |||
8368 | InitialCurInit.get(), | |||
8369 | getAssignmentAction(Entity, true), | |||
8370 | &Complained)) { | |||
8371 | PrintInitLocationNote(S, Entity); | |||
8372 | return ExprError(); | |||
8373 | } else if (Complained) | |||
8374 | PrintInitLocationNote(S, Entity); | |||
8375 | break; | |||
8376 | } | |||
8377 | ||||
8378 | case SK_StringInit: { | |||
8379 | QualType Ty = Step->Type; | |||
8380 | CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty, | |||
8381 | S.Context.getAsArrayType(Ty), S); | |||
8382 | break; | |||
8383 | } | |||
8384 | ||||
8385 | case SK_ObjCObjectConversion: | |||
8386 | CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, | |||
8387 | CK_ObjCObjectLValueCast, | |||
8388 | CurInit.get()->getValueKind()); | |||
8389 | break; | |||
8390 | ||||
8391 | case SK_ArrayLoopIndex: { | |||
8392 | Expr *Cur = CurInit.get(); | |||
8393 | Expr *BaseExpr = new (S.Context) | |||
8394 | OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(), | |||
8395 | Cur->getValueKind(), Cur->getObjectKind(), Cur); | |||
8396 | Expr *IndexExpr = | |||
8397 | new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType()); | |||
8398 | CurInit = S.CreateBuiltinArraySubscriptExpr( | |||
8399 | BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation()); | |||
8400 | ArrayLoopCommonExprs.push_back(BaseExpr); | |||
8401 | break; | |||
8402 | } | |||
8403 | ||||
8404 | case SK_ArrayLoopInit: { | |||
8405 | assert(!ArrayLoopCommonExprs.empty() &&((!ArrayLoopCommonExprs.empty() && "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit" ) ? static_cast<void> (0) : __assert_fail ("!ArrayLoopCommonExprs.empty() && \"mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 8406, __PRETTY_FUNCTION__)) | |||
8406 | "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit")((!ArrayLoopCommonExprs.empty() && "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit" ) ? static_cast<void> (0) : __assert_fail ("!ArrayLoopCommonExprs.empty() && \"mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 8406, __PRETTY_FUNCTION__)); | |||
8407 | Expr *Common = ArrayLoopCommonExprs.pop_back_val(); | |||
8408 | CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common, | |||
8409 | CurInit.get()); | |||
8410 | break; | |||
8411 | } | |||
8412 | ||||
8413 | case SK_GNUArrayInit: | |||
8414 | // Okay: we checked everything before creating this step. Note that | |||
8415 | // this is a GNU extension. | |||
8416 | S.Diag(Kind.getLocation(), diag::ext_array_init_copy) | |||
8417 | << Step->Type << CurInit.get()->getType() | |||
8418 | << CurInit.get()->getSourceRange(); | |||
8419 | updateGNUCompoundLiteralRValue(CurInit.get()); | |||
8420 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
8421 | case SK_ArrayInit: | |||
8422 | // If the destination type is an incomplete array type, update the | |||
8423 | // type accordingly. | |||
8424 | if (ResultType) { | |||
8425 | if (const IncompleteArrayType *IncompleteDest | |||
8426 | = S.Context.getAsIncompleteArrayType(Step->Type)) { | |||
8427 | if (const ConstantArrayType *ConstantSource | |||
8428 | = S.Context.getAsConstantArrayType(CurInit.get()->getType())) { | |||
8429 | *ResultType = S.Context.getConstantArrayType( | |||
8430 | IncompleteDest->getElementType(), | |||
8431 | ConstantSource->getSize(), | |||
8432 | ConstantSource->getSizeExpr(), | |||
8433 | ArrayType::Normal, 0); | |||
8434 | } | |||
8435 | } | |||
8436 | } | |||
8437 | break; | |||
8438 | ||||
8439 | case SK_ParenthesizedArrayInit: | |||
8440 | // Okay: we checked everything before creating this step. Note that | |||
8441 | // this is a GNU extension. | |||
8442 | S.Diag(Kind.getLocation(), diag::ext_array_init_parens) | |||
8443 | << CurInit.get()->getSourceRange(); | |||
8444 | break; | |||
8445 | ||||
8446 | case SK_PassByIndirectCopyRestore: | |||
8447 | case SK_PassByIndirectRestore: | |||
8448 | checkIndirectCopyRestoreSource(S, CurInit.get()); | |||
8449 | CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr( | |||
8450 | CurInit.get(), Step->Type, | |||
8451 | Step->Kind == SK_PassByIndirectCopyRestore); | |||
8452 | break; | |||
8453 | ||||
8454 | case SK_ProduceObjCObject: | |||
8455 | CurInit = | |||
8456 | ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject, | |||
8457 | CurInit.get(), nullptr, VK_RValue); | |||
8458 | break; | |||
8459 | ||||
8460 | case SK_StdInitializerList: { | |||
8461 | S.Diag(CurInit.get()->getExprLoc(), | |||
8462 | diag::warn_cxx98_compat_initializer_list_init) | |||
8463 | << CurInit.get()->getSourceRange(); | |||
8464 | ||||
8465 | // Materialize the temporary into memory. | |||
8466 | MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr( | |||
8467 | CurInit.get()->getType(), CurInit.get(), | |||
8468 | /*BoundToLvalueReference=*/false); | |||
8469 | ||||
8470 | // Wrap it in a construction of a std::initializer_list<T>. | |||
8471 | CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE); | |||
8472 | ||||
8473 | // Bind the result, in case the library has given initializer_list a | |||
8474 | // non-trivial destructor. | |||
8475 | if (shouldBindAsTemporary(Entity)) | |||
8476 | CurInit = S.MaybeBindToTemporary(CurInit.get()); | |||
8477 | break; | |||
8478 | } | |||
8479 | ||||
8480 | case SK_OCLSamplerInit: { | |||
8481 | // Sampler initialization have 5 cases: | |||
8482 | // 1. function argument passing | |||
8483 | // 1a. argument is a file-scope variable | |||
8484 | // 1b. argument is a function-scope variable | |||
8485 | // 1c. argument is one of caller function's parameters | |||
8486 | // 2. variable initialization | |||
8487 | // 2a. initializing a file-scope variable | |||
8488 | // 2b. initializing a function-scope variable | |||
8489 | // | |||
8490 | // For file-scope variables, since they cannot be initialized by function | |||
8491 | // call of __translate_sampler_initializer in LLVM IR, their references | |||
8492 | // need to be replaced by a cast from their literal initializers to | |||
8493 | // sampler type. Since sampler variables can only be used in function | |||
8494 | // calls as arguments, we only need to replace them when handling the | |||
8495 | // argument passing. | |||
8496 | assert(Step->Type->isSamplerT() &&((Step->Type->isSamplerT() && "Sampler initialization on non-sampler type." ) ? static_cast<void> (0) : __assert_fail ("Step->Type->isSamplerT() && \"Sampler initialization on non-sampler type.\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 8497, __PRETTY_FUNCTION__)) | |||
8497 | "Sampler initialization on non-sampler type.")((Step->Type->isSamplerT() && "Sampler initialization on non-sampler type." ) ? static_cast<void> (0) : __assert_fail ("Step->Type->isSamplerT() && \"Sampler initialization on non-sampler type.\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 8497, __PRETTY_FUNCTION__)); | |||
8498 | Expr *Init = CurInit.get()->IgnoreParens(); | |||
8499 | QualType SourceType = Init->getType(); | |||
8500 | // Case 1 | |||
8501 | if (Entity.isParameterKind()) { | |||
8502 | if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) { | |||
8503 | S.Diag(Kind.getLocation(), diag::err_sampler_argument_required) | |||
8504 | << SourceType; | |||
8505 | break; | |||
8506 | } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) { | |||
8507 | auto Var = cast<VarDecl>(DRE->getDecl()); | |||
8508 | // Case 1b and 1c | |||
8509 | // No cast from integer to sampler is needed. | |||
8510 | if (!Var->hasGlobalStorage()) { | |||
8511 | CurInit = ImplicitCastExpr::Create(S.Context, Step->Type, | |||
8512 | CK_LValueToRValue, Init, | |||
8513 | /*BasePath=*/nullptr, VK_RValue); | |||
8514 | break; | |||
8515 | } | |||
8516 | // Case 1a | |||
8517 | // For function call with a file-scope sampler variable as argument, | |||
8518 | // get the integer literal. | |||
8519 | // Do not diagnose if the file-scope variable does not have initializer | |||
8520 | // since this has already been diagnosed when parsing the variable | |||
8521 | // declaration. | |||
8522 | if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit())) | |||
8523 | break; | |||
8524 | Init = cast<ImplicitCastExpr>(const_cast<Expr*>( | |||
8525 | Var->getInit()))->getSubExpr(); | |||
8526 | SourceType = Init->getType(); | |||
8527 | } | |||
8528 | } else { | |||
8529 | // Case 2 | |||
8530 | // Check initializer is 32 bit integer constant. | |||
8531 | // If the initializer is taken from global variable, do not diagnose since | |||
8532 | // this has already been done when parsing the variable declaration. | |||
8533 | if (!Init->isConstantInitializer(S.Context, false)) | |||
8534 | break; | |||
8535 | ||||
8536 | if (!SourceType->isIntegerType() || | |||
8537 | 32 != S.Context.getIntWidth(SourceType)) { | |||
8538 | S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer) | |||
8539 | << SourceType; | |||
8540 | break; | |||
8541 | } | |||
8542 | ||||
8543 | Expr::EvalResult EVResult; | |||
8544 | Init->EvaluateAsInt(EVResult, S.Context); | |||
8545 | llvm::APSInt Result = EVResult.Val.getInt(); | |||
8546 | const uint64_t SamplerValue = Result.getLimitedValue(); | |||
8547 | // 32-bit value of sampler's initializer is interpreted as | |||
8548 | // bit-field with the following structure: | |||
8549 | // |unspecified|Filter|Addressing Mode| Normalized Coords| | |||
8550 | // |31 6|5 4|3 1| 0| | |||
8551 | // This structure corresponds to enum values of sampler properties | |||
8552 | // defined in SPIR spec v1.2 and also opencl-c.h | |||
8553 | unsigned AddressingMode = (0x0E & SamplerValue) >> 1; | |||
8554 | unsigned FilterMode = (0x30 & SamplerValue) >> 4; | |||
8555 | if (FilterMode != 1 && FilterMode != 2 && | |||
8556 | !S.getOpenCLOptions().isEnabled( | |||
8557 | "cl_intel_device_side_avc_motion_estimation")) | |||
8558 | S.Diag(Kind.getLocation(), | |||
8559 | diag::warn_sampler_initializer_invalid_bits) | |||
8560 | << "Filter Mode"; | |||
8561 | if (AddressingMode > 4) | |||
8562 | S.Diag(Kind.getLocation(), | |||
8563 | diag::warn_sampler_initializer_invalid_bits) | |||
8564 | << "Addressing Mode"; | |||
8565 | } | |||
8566 | ||||
8567 | // Cases 1a, 2a and 2b | |||
8568 | // Insert cast from integer to sampler. | |||
8569 | CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy, | |||
8570 | CK_IntToOCLSampler); | |||
8571 | break; | |||
8572 | } | |||
8573 | case SK_OCLZeroOpaqueType: { | |||
8574 | assert((Step->Type->isEventT() || Step->Type->isQueueT() ||(((Step->Type->isEventT() || Step->Type->isQueueT () || Step->Type->isOCLIntelSubgroupAVCType()) && "Wrong type for initialization of OpenCL opaque type.") ? static_cast <void> (0) : __assert_fail ("(Step->Type->isEventT() || Step->Type->isQueueT() || Step->Type->isOCLIntelSubgroupAVCType()) && \"Wrong type for initialization of OpenCL opaque type.\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 8576, __PRETTY_FUNCTION__)) | |||
8575 | Step->Type->isOCLIntelSubgroupAVCType()) &&(((Step->Type->isEventT() || Step->Type->isQueueT () || Step->Type->isOCLIntelSubgroupAVCType()) && "Wrong type for initialization of OpenCL opaque type.") ? static_cast <void> (0) : __assert_fail ("(Step->Type->isEventT() || Step->Type->isQueueT() || Step->Type->isOCLIntelSubgroupAVCType()) && \"Wrong type for initialization of OpenCL opaque type.\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 8576, __PRETTY_FUNCTION__)) | |||
8576 | "Wrong type for initialization of OpenCL opaque type.")(((Step->Type->isEventT() || Step->Type->isQueueT () || Step->Type->isOCLIntelSubgroupAVCType()) && "Wrong type for initialization of OpenCL opaque type.") ? static_cast <void> (0) : __assert_fail ("(Step->Type->isEventT() || Step->Type->isQueueT() || Step->Type->isOCLIntelSubgroupAVCType()) && \"Wrong type for initialization of OpenCL opaque type.\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 8576, __PRETTY_FUNCTION__)); | |||
8577 | ||||
8578 | CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, | |||
8579 | CK_ZeroToOCLOpaqueType, | |||
8580 | CurInit.get()->getValueKind()); | |||
8581 | break; | |||
8582 | } | |||
8583 | } | |||
8584 | } | |||
8585 | ||||
8586 | // Check whether the initializer has a shorter lifetime than the initialized | |||
8587 | // entity, and if not, either lifetime-extend or warn as appropriate. | |||
8588 | if (auto *Init = CurInit.get()) | |||
8589 | S.checkInitializerLifetime(Entity, Init); | |||
8590 | ||||
8591 | // Diagnose non-fatal problems with the completed initialization. | |||
8592 | if (Entity.getKind() == InitializedEntity::EK_Member && | |||
8593 | cast<FieldDecl>(Entity.getDecl())->isBitField()) | |||
8594 | S.CheckBitFieldInitialization(Kind.getLocation(), | |||
8595 | cast<FieldDecl>(Entity.getDecl()), | |||
8596 | CurInit.get()); | |||
8597 | ||||
8598 | // Check for std::move on construction. | |||
8599 | if (const Expr *E = CurInit.get()) { | |||
8600 | CheckMoveOnConstruction(S, E, | |||
8601 | Entity.getKind() == InitializedEntity::EK_Result); | |||
8602 | } | |||
8603 | ||||
8604 | return CurInit; | |||
8605 | } | |||
8606 | ||||
8607 | /// Somewhere within T there is an uninitialized reference subobject. | |||
8608 | /// Dig it out and diagnose it. | |||
8609 | static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc, | |||
8610 | QualType T) { | |||
8611 | if (T->isReferenceType()) { | |||
8612 | S.Diag(Loc, diag::err_reference_without_init) | |||
8613 | << T.getNonReferenceType(); | |||
8614 | return true; | |||
8615 | } | |||
8616 | ||||
8617 | CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); | |||
8618 | if (!RD || !RD->hasUninitializedReferenceMember()) | |||
8619 | return false; | |||
8620 | ||||
8621 | for (const auto *FI : RD->fields()) { | |||
8622 | if (FI->isUnnamedBitfield()) | |||
8623 | continue; | |||
8624 | ||||
8625 | if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) { | |||
8626 | S.Diag(Loc, diag::note_value_initialization_here) << RD; | |||
8627 | return true; | |||
8628 | } | |||
8629 | } | |||
8630 | ||||
8631 | for (const auto &BI : RD->bases()) { | |||
8632 | if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) { | |||
8633 | S.Diag(Loc, diag::note_value_initialization_here) << RD; | |||
8634 | return true; | |||
8635 | } | |||
8636 | } | |||
8637 | ||||
8638 | return false; | |||
8639 | } | |||
8640 | ||||
8641 | ||||
8642 | //===----------------------------------------------------------------------===// | |||
8643 | // Diagnose initialization failures | |||
8644 | //===----------------------------------------------------------------------===// | |||
8645 | ||||
8646 | /// Emit notes associated with an initialization that failed due to a | |||
8647 | /// "simple" conversion failure. | |||
8648 | static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity, | |||
8649 | Expr *op) { | |||
8650 | QualType destType = entity.getType(); | |||
8651 | if (destType.getNonReferenceType()->isObjCObjectPointerType() && | |||
8652 | op->getType()->isObjCObjectPointerType()) { | |||
8653 | ||||
8654 | // Emit a possible note about the conversion failing because the | |||
8655 | // operand is a message send with a related result type. | |||
8656 | S.EmitRelatedResultTypeNote(op); | |||
8657 | ||||
8658 | // Emit a possible note about a return failing because we're | |||
8659 | // expecting a related result type. | |||
8660 | if (entity.getKind() == InitializedEntity::EK_Result) | |||
8661 | S.EmitRelatedResultTypeNoteForReturn(destType); | |||
8662 | } | |||
8663 | } | |||
8664 | ||||
8665 | static void diagnoseListInit(Sema &S, const InitializedEntity &Entity, | |||
8666 | InitListExpr *InitList) { | |||
8667 | QualType DestType = Entity.getType(); | |||
8668 | ||||
8669 | QualType E; | |||
8670 | if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) { | |||
8671 | QualType ArrayType = S.Context.getConstantArrayType( | |||
8672 | E.withConst(), | |||
8673 | llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()), | |||
8674 | InitList->getNumInits()), | |||
8675 | nullptr, clang::ArrayType::Normal, 0); | |||
8676 | InitializedEntity HiddenArray = | |||
8677 | InitializedEntity::InitializeTemporary(ArrayType); | |||
8678 | return diagnoseListInit(S, HiddenArray, InitList); | |||
8679 | } | |||
8680 | ||||
8681 | if (DestType->isReferenceType()) { | |||
8682 | // A list-initialization failure for a reference means that we tried to | |||
8683 | // create a temporary of the inner type (per [dcl.init.list]p3.6) and the | |||
8684 | // inner initialization failed. | |||
8685 | QualType T = DestType->castAs<ReferenceType>()->getPointeeType(); | |||
8686 | diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList); | |||
8687 | SourceLocation Loc = InitList->getBeginLoc(); | |||
8688 | if (auto *D = Entity.getDecl()) | |||
8689 | Loc = D->getLocation(); | |||
8690 | S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T; | |||
8691 | return; | |||
8692 | } | |||
8693 | ||||
8694 | InitListChecker DiagnoseInitList(S, Entity, InitList, DestType, | |||
8695 | /*VerifyOnly=*/false, | |||
8696 | /*TreatUnavailableAsInvalid=*/false); | |||
8697 | assert(DiagnoseInitList.HadError() &&((DiagnoseInitList.HadError() && "Inconsistent init list check result." ) ? static_cast<void> (0) : __assert_fail ("DiagnoseInitList.HadError() && \"Inconsistent init list check result.\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 8698, __PRETTY_FUNCTION__)) | |||
8698 | "Inconsistent init list check result.")((DiagnoseInitList.HadError() && "Inconsistent init list check result." ) ? static_cast<void> (0) : __assert_fail ("DiagnoseInitList.HadError() && \"Inconsistent init list check result.\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 8698, __PRETTY_FUNCTION__)); | |||
8699 | } | |||
8700 | ||||
8701 | bool InitializationSequence::Diagnose(Sema &S, | |||
8702 | const InitializedEntity &Entity, | |||
8703 | const InitializationKind &Kind, | |||
8704 | ArrayRef<Expr *> Args) { | |||
8705 | if (!Failed()) | |||
| ||||
8706 | return false; | |||
8707 | ||||
8708 | // When we want to diagnose only one element of a braced-init-list, | |||
8709 | // we need to factor it out. | |||
8710 | Expr *OnlyArg; | |||
8711 | if (Args.size() == 1) { | |||
8712 | auto *List = dyn_cast<InitListExpr>(Args[0]); | |||
8713 | if (List && List->getNumInits() == 1) | |||
8714 | OnlyArg = List->getInit(0); | |||
8715 | else | |||
8716 | OnlyArg = Args[0]; | |||
8717 | } | |||
8718 | else | |||
8719 | OnlyArg = nullptr; | |||
8720 | ||||
8721 | QualType DestType = Entity.getType(); | |||
8722 | switch (Failure) { | |||
8723 | case FK_TooManyInitsForReference: | |||
8724 | // FIXME: Customize for the initialized entity? | |||
8725 | if (Args.empty()) { | |||
8726 | // Dig out the reference subobject which is uninitialized and diagnose it. | |||
8727 | // If this is value-initialization, this could be nested some way within | |||
8728 | // the target type. | |||
8729 | assert(Kind.getKind() == InitializationKind::IK_Value ||((Kind.getKind() == InitializationKind::IK_Value || DestType-> isReferenceType()) ? static_cast<void> (0) : __assert_fail ("Kind.getKind() == InitializationKind::IK_Value || DestType->isReferenceType()" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 8730, __PRETTY_FUNCTION__)) | |||
8730 | DestType->isReferenceType())((Kind.getKind() == InitializationKind::IK_Value || DestType-> isReferenceType()) ? static_cast<void> (0) : __assert_fail ("Kind.getKind() == InitializationKind::IK_Value || DestType->isReferenceType()" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 8730, __PRETTY_FUNCTION__)); | |||
8731 | bool Diagnosed = | |||
8732 | DiagnoseUninitializedReference(S, Kind.getLocation(), DestType); | |||
8733 | assert(Diagnosed && "couldn't find uninitialized reference to diagnose")((Diagnosed && "couldn't find uninitialized reference to diagnose" ) ? static_cast<void> (0) : __assert_fail ("Diagnosed && \"couldn't find uninitialized reference to diagnose\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 8733, __PRETTY_FUNCTION__)); | |||
8734 | (void)Diagnosed; | |||
8735 | } else // FIXME: diagnostic below could be better! | |||
8736 | S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits) | |||
8737 | << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc()); | |||
8738 | break; | |||
8739 | case FK_ParenthesizedListInitForReference: | |||
8740 | S.Diag(Kind.getLocation(), diag::err_list_init_in_parens) | |||
8741 | << 1 << Entity.getType() << Args[0]->getSourceRange(); | |||
8742 | break; | |||
8743 | ||||
8744 | case FK_ArrayNeedsInitList: | |||
8745 | S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0; | |||
8746 | break; | |||
8747 | case FK_ArrayNeedsInitListOrStringLiteral: | |||
8748 | S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1; | |||
8749 | break; | |||
8750 | case FK_ArrayNeedsInitListOrWideStringLiteral: | |||
8751 | S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2; | |||
8752 | break; | |||
8753 | case FK_NarrowStringIntoWideCharArray: | |||
8754 | S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar); | |||
8755 | break; | |||
8756 | case FK_WideStringIntoCharArray: | |||
8757 | S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char); | |||
8758 | break; | |||
8759 | case FK_IncompatWideStringIntoWideChar: | |||
8760 | S.Diag(Kind.getLocation(), | |||
8761 | diag::err_array_init_incompat_wide_string_into_wchar); | |||
8762 | break; | |||
8763 | case FK_PlainStringIntoUTF8Char: | |||
8764 | S.Diag(Kind.getLocation(), | |||
8765 | diag::err_array_init_plain_string_into_char8_t); | |||
8766 | S.Diag(Args.front()->getBeginLoc(), | |||
8767 | diag::note_array_init_plain_string_into_char8_t) | |||
8768 | << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8"); | |||
8769 | break; | |||
8770 | case FK_UTF8StringIntoPlainChar: | |||
8771 | S.Diag(Kind.getLocation(), | |||
8772 | diag::err_array_init_utf8_string_into_char) | |||
8773 | << S.getLangOpts().CPlusPlus2a; | |||
8774 | break; | |||
8775 | case FK_ArrayTypeMismatch: | |||
8776 | case FK_NonConstantArrayInit: | |||
8777 | S.Diag(Kind.getLocation(), | |||
8778 | (Failure == FK_ArrayTypeMismatch | |||
8779 | ? diag::err_array_init_different_type | |||
8780 | : diag::err_array_init_non_constant_array)) | |||
8781 | << DestType.getNonReferenceType() | |||
8782 | << OnlyArg->getType() | |||
8783 | << Args[0]->getSourceRange(); | |||
8784 | break; | |||
8785 | ||||
8786 | case FK_VariableLengthArrayHasInitializer: | |||
8787 | S.Diag(Kind.getLocation(), diag::err_variable_object_no_init) | |||
8788 | << Args[0]->getSourceRange(); | |||
8789 | break; | |||
8790 | ||||
8791 | case FK_AddressOfOverloadFailed: { | |||
8792 | DeclAccessPair Found; | |||
8793 | S.ResolveAddressOfOverloadedFunction(OnlyArg, | |||
8794 | DestType.getNonReferenceType(), | |||
8795 | true, | |||
8796 | Found); | |||
8797 | break; | |||
8798 | } | |||
8799 | ||||
8800 | case FK_AddressOfUnaddressableFunction: { | |||
8801 | auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl()); | |||
8802 | S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, | |||
8803 | OnlyArg->getBeginLoc()); | |||
8804 | break; | |||
8805 | } | |||
8806 | ||||
8807 | case FK_ReferenceInitOverloadFailed: | |||
8808 | case FK_UserConversionOverloadFailed: | |||
8809 | switch (FailedOverloadResult) { | |||
8810 | case OR_Ambiguous: | |||
8811 | ||||
8812 | FailedCandidateSet.NoteCandidates( | |||
8813 | PartialDiagnosticAt( | |||
8814 | Kind.getLocation(), | |||
8815 | Failure == FK_UserConversionOverloadFailed | |||
8816 | ? (S.PDiag(diag::err_typecheck_ambiguous_condition) | |||
8817 | << OnlyArg->getType() << DestType | |||
8818 | << Args[0]->getSourceRange()) | |||
8819 | : (S.PDiag(diag::err_ref_init_ambiguous) | |||
8820 | << DestType << OnlyArg->getType() | |||
8821 | << Args[0]->getSourceRange())), | |||
8822 | S, OCD_AmbiguousCandidates, Args); | |||
8823 | break; | |||
8824 | ||||
8825 | case OR_No_Viable_Function: { | |||
8826 | auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args); | |||
8827 | if (!S.RequireCompleteType(Kind.getLocation(), | |||
8828 | DestType.getNonReferenceType(), | |||
8829 | diag::err_typecheck_nonviable_condition_incomplete, | |||
8830 | OnlyArg->getType(), Args[0]->getSourceRange())) | |||
8831 | S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition) | |||
8832 | << (Entity.getKind() == InitializedEntity::EK_Result) | |||
8833 | << OnlyArg->getType() << Args[0]->getSourceRange() | |||
8834 | << DestType.getNonReferenceType(); | |||
8835 | ||||
8836 | FailedCandidateSet.NoteCandidates(S, Args, Cands); | |||
8837 | break; | |||
8838 | } | |||
8839 | case OR_Deleted: { | |||
8840 | S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function) | |||
8841 | << OnlyArg->getType() << DestType.getNonReferenceType() | |||
8842 | << Args[0]->getSourceRange(); | |||
8843 | OverloadCandidateSet::iterator Best; | |||
8844 | OverloadingResult Ovl | |||
8845 | = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best); | |||
8846 | if (Ovl == OR_Deleted) { | |||
8847 | S.NoteDeletedFunction(Best->Function); | |||
8848 | } else { | |||
8849 | llvm_unreachable("Inconsistent overload resolution?")::llvm::llvm_unreachable_internal("Inconsistent overload resolution?" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 8849); | |||
8850 | } | |||
8851 | break; | |||
8852 | } | |||
8853 | ||||
8854 | case OR_Success: | |||
8855 | llvm_unreachable("Conversion did not fail!")::llvm::llvm_unreachable_internal("Conversion did not fail!", "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 8855); | |||
8856 | } | |||
8857 | break; | |||
8858 | ||||
8859 | case FK_NonConstLValueReferenceBindingToTemporary: | |||
8860 | if (isa<InitListExpr>(Args[0])) { | |||
8861 | S.Diag(Kind.getLocation(), | |||
8862 | diag::err_lvalue_reference_bind_to_initlist) | |||
8863 | << DestType.getNonReferenceType().isVolatileQualified() | |||
8864 | << DestType.getNonReferenceType() | |||
8865 | << Args[0]->getSourceRange(); | |||
8866 | break; | |||
8867 | } | |||
8868 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
8869 | ||||
8870 | case FK_NonConstLValueReferenceBindingToUnrelated: | |||
8871 | S.Diag(Kind.getLocation(), | |||
8872 | Failure == FK_NonConstLValueReferenceBindingToTemporary | |||
8873 | ? diag::err_lvalue_reference_bind_to_temporary | |||
8874 | : diag::err_lvalue_reference_bind_to_unrelated) | |||
8875 | << DestType.getNonReferenceType().isVolatileQualified() | |||
8876 | << DestType.getNonReferenceType() | |||
8877 | << OnlyArg->getType() | |||
8878 | << Args[0]->getSourceRange(); | |||
8879 | break; | |||
8880 | ||||
8881 | case FK_NonConstLValueReferenceBindingToBitfield: { | |||
8882 | // We don't necessarily have an unambiguous source bit-field. | |||
8883 | FieldDecl *BitField = Args[0]->getSourceBitField(); | |||
8884 | S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield) | |||
8885 | << DestType.isVolatileQualified() | |||
8886 | << (BitField ? BitField->getDeclName() : DeclarationName()) | |||
8887 | << (BitField != nullptr) | |||
8888 | << Args[0]->getSourceRange(); | |||
8889 | if (BitField) | |||
8890 | S.Diag(BitField->getLocation(), diag::note_bitfield_decl); | |||
8891 | break; | |||
8892 | } | |||
8893 | ||||
8894 | case FK_NonConstLValueReferenceBindingToVectorElement: | |||
8895 | S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element) | |||
8896 | << DestType.isVolatileQualified() | |||
8897 | << Args[0]->getSourceRange(); | |||
8898 | break; | |||
8899 | ||||
8900 | case FK_RValueReferenceBindingToLValue: | |||
8901 | S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref) | |||
8902 | << DestType.getNonReferenceType() << OnlyArg->getType() | |||
8903 | << Args[0]->getSourceRange(); | |||
8904 | break; | |||
8905 | ||||
8906 | case FK_ReferenceAddrspaceMismatchTemporary: | |||
8907 | S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace) | |||
8908 | << DestType << Args[0]->getSourceRange(); | |||
8909 | break; | |||
8910 | ||||
8911 | case FK_ReferenceInitDropsQualifiers: { | |||
8912 | QualType SourceType = OnlyArg->getType(); | |||
8913 | QualType NonRefType = DestType.getNonReferenceType(); | |||
8914 | Qualifiers DroppedQualifiers = | |||
8915 | SourceType.getQualifiers() - NonRefType.getQualifiers(); | |||
8916 | ||||
8917 | if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf( | |||
8918 | SourceType.getQualifiers())) | |||
8919 | S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals) | |||
8920 | << NonRefType << SourceType << 1 /*addr space*/ | |||
8921 | << Args[0]->getSourceRange(); | |||
8922 | else | |||
8923 | S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals) | |||
8924 | << NonRefType << SourceType << 0 /*cv quals*/ | |||
8925 | << Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers()) | |||
8926 | << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange(); | |||
8927 | break; | |||
8928 | } | |||
8929 | ||||
8930 | case FK_ReferenceInitFailed: | |||
8931 | S.Diag(Kind.getLocation(), diag::err_reference_bind_failed) | |||
8932 | << DestType.getNonReferenceType() | |||
8933 | << DestType.getNonReferenceType()->isIncompleteType() | |||
8934 | << OnlyArg->isLValue() | |||
8935 | << OnlyArg->getType() | |||
8936 | << Args[0]->getSourceRange(); | |||
8937 | emitBadConversionNotes(S, Entity, Args[0]); | |||
8938 | break; | |||
8939 | ||||
8940 | case FK_ConversionFailed: { | |||
8941 | QualType FromType = OnlyArg->getType(); | |||
| ||||
8942 | PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed) | |||
8943 | << (int)Entity.getKind() | |||
8944 | << DestType | |||
8945 | << OnlyArg->isLValue() | |||
8946 | << FromType | |||
8947 | << Args[0]->getSourceRange(); | |||
8948 | S.HandleFunctionTypeMismatch(PDiag, FromType, DestType); | |||
8949 | S.Diag(Kind.getLocation(), PDiag); | |||
8950 | emitBadConversionNotes(S, Entity, Args[0]); | |||
8951 | break; | |||
8952 | } | |||
8953 | ||||
8954 | case FK_ConversionFromPropertyFailed: | |||
8955 | // No-op. This error has already been reported. | |||
8956 | break; | |||
8957 | ||||
8958 | case FK_TooManyInitsForScalar: { | |||
8959 | SourceRange R; | |||
8960 | ||||
8961 | auto *InitList = dyn_cast<InitListExpr>(Args[0]); | |||
8962 | if (InitList && InitList->getNumInits() >= 1) { | |||
8963 | R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc()); | |||
8964 | } else { | |||
8965 | assert(Args.size() > 1 && "Expected multiple initializers!")((Args.size() > 1 && "Expected multiple initializers!" ) ? static_cast<void> (0) : __assert_fail ("Args.size() > 1 && \"Expected multiple initializers!\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 8965, __PRETTY_FUNCTION__)); | |||
8966 | R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc()); | |||
8967 | } | |||
8968 | ||||
8969 | R.setBegin(S.getLocForEndOfToken(R.getBegin())); | |||
8970 | if (Kind.isCStyleOrFunctionalCast()) | |||
8971 | S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg) | |||
8972 | << R; | |||
8973 | else | |||
8974 | S.Diag(Kind.getLocation(), diag::err_excess_initializers) | |||
8975 | << /*scalar=*/2 << R; | |||
8976 | break; | |||
8977 | } | |||
8978 | ||||
8979 | case FK_ParenthesizedListInitForScalar: | |||
8980 | S.Diag(Kind.getLocation(), diag::err_list_init_in_parens) | |||
8981 | << 0 << Entity.getType() << Args[0]->getSourceRange(); | |||
8982 | break; | |||
8983 | ||||
8984 | case FK_ReferenceBindingToInitList: | |||
8985 | S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list) | |||
8986 | << DestType.getNonReferenceType() << Args[0]->getSourceRange(); | |||
8987 | break; | |||
8988 | ||||
8989 | case FK_InitListBadDestinationType: | |||
8990 | S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type) | |||
8991 | << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange(); | |||
8992 | break; | |||
8993 | ||||
8994 | case FK_ListConstructorOverloadFailed: | |||
8995 | case FK_ConstructorOverloadFailed: { | |||
8996 | SourceRange ArgsRange; | |||
8997 | if (Args.size()) | |||
8998 | ArgsRange = | |||
8999 | SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc()); | |||
9000 | ||||
9001 | if (Failure == FK_ListConstructorOverloadFailed) { | |||
9002 | assert(Args.size() == 1 &&((Args.size() == 1 && "List construction from other than 1 argument." ) ? static_cast<void> (0) : __assert_fail ("Args.size() == 1 && \"List construction from other than 1 argument.\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 9003, __PRETTY_FUNCTION__)) | |||
9003 | "List construction from other than 1 argument.")((Args.size() == 1 && "List construction from other than 1 argument." ) ? static_cast<void> (0) : __assert_fail ("Args.size() == 1 && \"List construction from other than 1 argument.\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 9003, __PRETTY_FUNCTION__)); | |||
9004 | InitListExpr *InitList = cast<InitListExpr>(Args[0]); | |||
9005 | Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); | |||
9006 | } | |||
9007 | ||||
9008 | // FIXME: Using "DestType" for the entity we're printing is probably | |||
9009 | // bad. | |||
9010 | switch (FailedOverloadResult) { | |||
9011 | case OR_Ambiguous: | |||
9012 | FailedCandidateSet.NoteCandidates( | |||
9013 | PartialDiagnosticAt(Kind.getLocation(), | |||
9014 | S.PDiag(diag::err_ovl_ambiguous_init) | |||
9015 | << DestType << ArgsRange), | |||
9016 | S, OCD_AmbiguousCandidates, Args); | |||
9017 | break; | |||
9018 | ||||
9019 | case OR_No_Viable_Function: | |||
9020 | if (Kind.getKind() == InitializationKind::IK_Default && | |||
9021 | (Entity.getKind() == InitializedEntity::EK_Base || | |||
9022 | Entity.getKind() == InitializedEntity::EK_Member) && | |||
9023 | isa<CXXConstructorDecl>(S.CurContext)) { | |||
9024 | // This is implicit default initialization of a member or | |||
9025 | // base within a constructor. If no viable function was | |||
9026 | // found, notify the user that they need to explicitly | |||
9027 | // initialize this base/member. | |||
9028 | CXXConstructorDecl *Constructor | |||
9029 | = cast<CXXConstructorDecl>(S.CurContext); | |||
9030 | const CXXRecordDecl *InheritedFrom = nullptr; | |||
9031 | if (auto Inherited = Constructor->getInheritedConstructor()) | |||
9032 | InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass(); | |||
9033 | if (Entity.getKind() == InitializedEntity::EK_Base) { | |||
9034 | S.Diag(Kind.getLocation(), diag::err_missing_default_ctor) | |||
9035 | << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0) | |||
9036 | << S.Context.getTypeDeclType(Constructor->getParent()) | |||
9037 | << /*base=*/0 | |||
9038 | << Entity.getType() | |||
9039 | << InheritedFrom; | |||
9040 | ||||
9041 | RecordDecl *BaseDecl | |||
9042 | = Entity.getBaseSpecifier()->getType()->castAs<RecordType>() | |||
9043 | ->getDecl(); | |||
9044 | S.Diag(BaseDecl->getLocation(), diag::note_previous_decl) | |||
9045 | << S.Context.getTagDeclType(BaseDecl); | |||
9046 | } else { | |||
9047 | S.Diag(Kind.getLocation(), diag::err_missing_default_ctor) | |||
9048 | << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0) | |||
9049 | << S.Context.getTypeDeclType(Constructor->getParent()) | |||
9050 | << /*member=*/1 | |||
9051 | << Entity.getName() | |||
9052 | << InheritedFrom; | |||
9053 | S.Diag(Entity.getDecl()->getLocation(), | |||
9054 | diag::note_member_declared_at); | |||
9055 | ||||
9056 | if (const RecordType *Record | |||
9057 | = Entity.getType()->getAs<RecordType>()) | |||
9058 | S.Diag(Record->getDecl()->getLocation(), | |||
9059 | diag::note_previous_decl) | |||
9060 | << S.Context.getTagDeclType(Record->getDecl()); | |||
9061 | } | |||
9062 | break; | |||
9063 | } | |||
9064 | ||||
9065 | FailedCandidateSet.NoteCandidates( | |||
9066 | PartialDiagnosticAt( | |||
9067 | Kind.getLocation(), | |||
9068 | S.PDiag(diag::err_ovl_no_viable_function_in_init) | |||
9069 | << DestType << ArgsRange), | |||
9070 | S, OCD_AllCandidates, Args); | |||
9071 | break; | |||
9072 | ||||
9073 | case OR_Deleted: { | |||
9074 | OverloadCandidateSet::iterator Best; | |||
9075 | OverloadingResult Ovl | |||
9076 | = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best); | |||
9077 | if (Ovl != OR_Deleted) { | |||
9078 | S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init) | |||
9079 | << DestType << ArgsRange; | |||
9080 | llvm_unreachable("Inconsistent overload resolution?")::llvm::llvm_unreachable_internal("Inconsistent overload resolution?" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 9080); | |||
9081 | break; | |||
9082 | } | |||
9083 | ||||
9084 | // If this is a defaulted or implicitly-declared function, then | |||
9085 | // it was implicitly deleted. Make it clear that the deletion was | |||
9086 | // implicit. | |||
9087 | if (S.isImplicitlyDeleted(Best->Function)) | |||
9088 | S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init) | |||
9089 | << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function)) | |||
9090 | << DestType << ArgsRange; | |||
9091 | else | |||
9092 | S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init) | |||
9093 | << DestType << ArgsRange; | |||
9094 | ||||
9095 | S.NoteDeletedFunction(Best->Function); | |||
9096 | break; | |||
9097 | } | |||
9098 | ||||
9099 | case OR_Success: | |||
9100 | llvm_unreachable("Conversion did not fail!")::llvm::llvm_unreachable_internal("Conversion did not fail!", "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 9100); | |||
9101 | } | |||
9102 | } | |||
9103 | break; | |||
9104 | ||||
9105 | case FK_DefaultInitOfConst: | |||
9106 | if (Entity.getKind() == InitializedEntity::EK_Member && | |||
9107 | isa<CXXConstructorDecl>(S.CurContext)) { | |||
9108 | // This is implicit default-initialization of a const member in | |||
9109 | // a constructor. Complain that it needs to be explicitly | |||
9110 | // initialized. | |||
9111 | CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext); | |||
9112 | S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor) | |||
9113 | << (Constructor->getInheritedConstructor() ? 2 : | |||
9114 | Constructor->isImplicit() ? 1 : 0) | |||
9115 | << S.Context.getTypeDeclType(Constructor->getParent()) | |||
9116 | << /*const=*/1 | |||
9117 | << Entity.getName(); | |||
9118 | S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl) | |||
9119 | << Entity.getName(); | |||
9120 | } else { | |||
9121 | S.Diag(Kind.getLocation(), diag::err_default_init_const) | |||
9122 | << DestType << (bool)DestType->getAs<RecordType>(); | |||
9123 | } | |||
9124 | break; | |||
9125 | ||||
9126 | case FK_Incomplete: | |||
9127 | S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType, | |||
9128 | diag::err_init_incomplete_type); | |||
9129 | break; | |||
9130 | ||||
9131 | case FK_ListInitializationFailed: { | |||
9132 | // Run the init list checker again to emit diagnostics. | |||
9133 | InitListExpr *InitList = cast<InitListExpr>(Args[0]); | |||
9134 | diagnoseListInit(S, Entity, InitList); | |||
9135 | break; | |||
9136 | } | |||
9137 | ||||
9138 | case FK_PlaceholderType: { | |||
9139 | // FIXME: Already diagnosed! | |||
9140 | break; | |||
9141 | } | |||
9142 | ||||
9143 | case FK_ExplicitConstructor: { | |||
9144 | S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor) | |||
9145 | << Args[0]->getSourceRange(); | |||
9146 | OverloadCandidateSet::iterator Best; | |||
9147 | OverloadingResult Ovl | |||
9148 | = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best); | |||
9149 | (void)Ovl; | |||
9150 | assert(Ovl == OR_Success && "Inconsistent overload resolution")((Ovl == OR_Success && "Inconsistent overload resolution" ) ? static_cast<void> (0) : __assert_fail ("Ovl == OR_Success && \"Inconsistent overload resolution\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 9150, __PRETTY_FUNCTION__)); | |||
9151 | CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function); | |||
9152 | S.Diag(CtorDecl->getLocation(), | |||
9153 | diag::note_explicit_ctor_deduction_guide_here) << false; | |||
9154 | break; | |||
9155 | } | |||
9156 | } | |||
9157 | ||||
9158 | PrintInitLocationNote(S, Entity); | |||
9159 | return true; | |||
9160 | } | |||
9161 | ||||
9162 | void InitializationSequence::dump(raw_ostream &OS) const { | |||
9163 | switch (SequenceKind) { | |||
9164 | case FailedSequence: { | |||
9165 | OS << "Failed sequence: "; | |||
9166 | switch (Failure) { | |||
9167 | case FK_TooManyInitsForReference: | |||
9168 | OS << "too many initializers for reference"; | |||
9169 | break; | |||
9170 | ||||
9171 | case FK_ParenthesizedListInitForReference: | |||
9172 | OS << "parenthesized list init for reference"; | |||
9173 | break; | |||
9174 | ||||
9175 | case FK_ArrayNeedsInitList: | |||
9176 | OS << "array requires initializer list"; | |||
9177 | break; | |||
9178 | ||||
9179 | case FK_AddressOfUnaddressableFunction: | |||
9180 | OS << "address of unaddressable function was taken"; | |||
9181 | break; | |||
9182 | ||||
9183 | case FK_ArrayNeedsInitListOrStringLiteral: | |||
9184 | OS << "array requires initializer list or string literal"; | |||
9185 | break; | |||
9186 | ||||
9187 | case FK_ArrayNeedsInitListOrWideStringLiteral: | |||
9188 | OS << "array requires initializer list or wide string literal"; | |||
9189 | break; | |||
9190 | ||||
9191 | case FK_NarrowStringIntoWideCharArray: | |||
9192 | OS << "narrow string into wide char array"; | |||
9193 | break; | |||
9194 | ||||
9195 | case FK_WideStringIntoCharArray: | |||
9196 | OS << "wide string into char array"; | |||
9197 | break; | |||
9198 | ||||
9199 | case FK_IncompatWideStringIntoWideChar: | |||
9200 | OS << "incompatible wide string into wide char array"; | |||
9201 | break; | |||
9202 | ||||
9203 | case FK_PlainStringIntoUTF8Char: | |||
9204 | OS << "plain string literal into char8_t array"; | |||
9205 | break; | |||
9206 | ||||
9207 | case FK_UTF8StringIntoPlainChar: | |||
9208 | OS << "u8 string literal into char array"; | |||
9209 | break; | |||
9210 | ||||
9211 | case FK_ArrayTypeMismatch: | |||
9212 | OS << "array type mismatch"; | |||
9213 | break; | |||
9214 | ||||
9215 | case FK_NonConstantArrayInit: | |||
9216 | OS << "non-constant array initializer"; | |||
9217 | break; | |||
9218 | ||||
9219 | case FK_AddressOfOverloadFailed: | |||
9220 | OS << "address of overloaded function failed"; | |||
9221 | break; | |||
9222 | ||||
9223 | case FK_ReferenceInitOverloadFailed: | |||
9224 | OS << "overload resolution for reference initialization failed"; | |||
9225 | break; | |||
9226 | ||||
9227 | case FK_NonConstLValueReferenceBindingToTemporary: | |||
9228 | OS << "non-const lvalue reference bound to temporary"; | |||
9229 | break; | |||
9230 | ||||
9231 | case FK_NonConstLValueReferenceBindingToBitfield: | |||
9232 | OS << "non-const lvalue reference bound to bit-field"; | |||
9233 | break; | |||
9234 | ||||
9235 | case FK_NonConstLValueReferenceBindingToVectorElement: | |||
9236 | OS << "non-const lvalue reference bound to vector element"; | |||
9237 | break; | |||
9238 | ||||
9239 | case FK_NonConstLValueReferenceBindingToUnrelated: | |||
9240 | OS << "non-const lvalue reference bound to unrelated type"; | |||
9241 | break; | |||
9242 | ||||
9243 | case FK_RValueReferenceBindingToLValue: | |||
9244 | OS << "rvalue reference bound to an lvalue"; | |||
9245 | break; | |||
9246 | ||||
9247 | case FK_ReferenceInitDropsQualifiers: | |||
9248 | OS << "reference initialization drops qualifiers"; | |||
9249 | break; | |||
9250 | ||||
9251 | case FK_ReferenceAddrspaceMismatchTemporary: | |||
9252 | OS << "reference with mismatching address space bound to temporary"; | |||
9253 | break; | |||
9254 | ||||
9255 | case FK_ReferenceInitFailed: | |||
9256 | OS << "reference initialization failed"; | |||
9257 | break; | |||
9258 | ||||
9259 | case FK_ConversionFailed: | |||
9260 | OS << "conversion failed"; | |||
9261 | break; | |||
9262 | ||||
9263 | case FK_ConversionFromPropertyFailed: | |||
9264 | OS << "conversion from property failed"; | |||
9265 | break; | |||
9266 | ||||
9267 | case FK_TooManyInitsForScalar: | |||
9268 | OS << "too many initializers for scalar"; | |||
9269 | break; | |||
9270 | ||||
9271 | case FK_ParenthesizedListInitForScalar: | |||
9272 | OS << "parenthesized list init for reference"; | |||
9273 | break; | |||
9274 | ||||
9275 | case FK_ReferenceBindingToInitList: | |||
9276 | OS << "referencing binding to initializer list"; | |||
9277 | break; | |||
9278 | ||||
9279 | case FK_InitListBadDestinationType: | |||
9280 | OS << "initializer list for non-aggregate, non-scalar type"; | |||
9281 | break; | |||
9282 | ||||
9283 | case FK_UserConversionOverloadFailed: | |||
9284 | OS << "overloading failed for user-defined conversion"; | |||
9285 | break; | |||
9286 | ||||
9287 | case FK_ConstructorOverloadFailed: | |||
9288 | OS << "constructor overloading failed"; | |||
9289 | break; | |||
9290 | ||||
9291 | case FK_DefaultInitOfConst: | |||
9292 | OS << "default initialization of a const variable"; | |||
9293 | break; | |||
9294 | ||||
9295 | case FK_Incomplete: | |||
9296 | OS << "initialization of incomplete type"; | |||
9297 | break; | |||
9298 | ||||
9299 | case FK_ListInitializationFailed: | |||
9300 | OS << "list initialization checker failure"; | |||
9301 | break; | |||
9302 | ||||
9303 | case FK_VariableLengthArrayHasInitializer: | |||
9304 | OS << "variable length array has an initializer"; | |||
9305 | break; | |||
9306 | ||||
9307 | case FK_PlaceholderType: | |||
9308 | OS << "initializer expression isn't contextually valid"; | |||
9309 | break; | |||
9310 | ||||
9311 | case FK_ListConstructorOverloadFailed: | |||
9312 | OS << "list constructor overloading failed"; | |||
9313 | break; | |||
9314 | ||||
9315 | case FK_ExplicitConstructor: | |||
9316 | OS << "list copy initialization chose explicit constructor"; | |||
9317 | break; | |||
9318 | } | |||
9319 | OS << '\n'; | |||
9320 | return; | |||
9321 | } | |||
9322 | ||||
9323 | case DependentSequence: | |||
9324 | OS << "Dependent sequence\n"; | |||
9325 | return; | |||
9326 | ||||
9327 | case NormalSequence: | |||
9328 | OS << "Normal sequence: "; | |||
9329 | break; | |||
9330 | } | |||
9331 | ||||
9332 | for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) { | |||
9333 | if (S != step_begin()) { | |||
9334 | OS << " -> "; | |||
9335 | } | |||
9336 | ||||
9337 | switch (S->Kind) { | |||
9338 | case SK_ResolveAddressOfOverloadedFunction: | |||
9339 | OS << "resolve address of overloaded function"; | |||
9340 | break; | |||
9341 | ||||
9342 | case SK_CastDerivedToBaseRValue: | |||
9343 | OS << "derived-to-base (rvalue)"; | |||
9344 | break; | |||
9345 | ||||
9346 | case SK_CastDerivedToBaseXValue: | |||
9347 | OS << "derived-to-base (xvalue)"; | |||
9348 | break; | |||
9349 | ||||
9350 | case SK_CastDerivedToBaseLValue: | |||
9351 | OS << "derived-to-base (lvalue)"; | |||
9352 | break; | |||
9353 | ||||
9354 | case SK_BindReference: | |||
9355 | OS << "bind reference to lvalue"; | |||
9356 | break; | |||
9357 | ||||
9358 | case SK_BindReferenceToTemporary: | |||
9359 | OS << "bind reference to a temporary"; | |||
9360 | break; | |||
9361 | ||||
9362 | case SK_FinalCopy: | |||
9363 | OS << "final copy in class direct-initialization"; | |||
9364 | break; | |||
9365 | ||||
9366 | case SK_ExtraneousCopyToTemporary: | |||
9367 | OS << "extraneous C++03 copy to temporary"; | |||
9368 | break; | |||
9369 | ||||
9370 | case SK_UserConversion: | |||
9371 | OS << "user-defined conversion via " << *S->Function.Function; | |||
9372 | break; | |||
9373 | ||||
9374 | case SK_QualificationConversionRValue: | |||
9375 | OS << "qualification conversion (rvalue)"; | |||
9376 | break; | |||
9377 | ||||
9378 | case SK_QualificationConversionXValue: | |||
9379 | OS << "qualification conversion (xvalue)"; | |||
9380 | break; | |||
9381 | ||||
9382 | case SK_QualificationConversionLValue: | |||
9383 | OS << "qualification conversion (lvalue)"; | |||
9384 | break; | |||
9385 | ||||
9386 | case SK_AtomicConversion: | |||
9387 | OS << "non-atomic-to-atomic conversion"; | |||
9388 | break; | |||
9389 | ||||
9390 | case SK_ConversionSequence: | |||
9391 | OS << "implicit conversion sequence ("; | |||
9392 | S->ICS->dump(); // FIXME: use OS | |||
9393 | OS << ")"; | |||
9394 | break; | |||
9395 | ||||
9396 | case SK_ConversionSequenceNoNarrowing: | |||
9397 | OS << "implicit conversion sequence with narrowing prohibited ("; | |||
9398 | S->ICS->dump(); // FIXME: use OS | |||
9399 | OS << ")"; | |||
9400 | break; | |||
9401 | ||||
9402 | case SK_ListInitialization: | |||
9403 | OS << "list aggregate initialization"; | |||
9404 | break; | |||
9405 | ||||
9406 | case SK_UnwrapInitList: | |||
9407 | OS << "unwrap reference initializer list"; | |||
9408 | break; | |||
9409 | ||||
9410 | case SK_RewrapInitList: | |||
9411 | OS << "rewrap reference initializer list"; | |||
9412 | break; | |||
9413 | ||||
9414 | case SK_ConstructorInitialization: | |||
9415 | OS << "constructor initialization"; | |||
9416 | break; | |||
9417 | ||||
9418 | case SK_ConstructorInitializationFromList: | |||
9419 | OS << "list initialization via constructor"; | |||
9420 | break; | |||
9421 | ||||
9422 | case SK_ZeroInitialization: | |||
9423 | OS << "zero initialization"; | |||
9424 | break; | |||
9425 | ||||
9426 | case SK_CAssignment: | |||
9427 | OS << "C assignment"; | |||
9428 | break; | |||
9429 | ||||
9430 | case SK_StringInit: | |||
9431 | OS << "string initialization"; | |||
9432 | break; | |||
9433 | ||||
9434 | case SK_ObjCObjectConversion: | |||
9435 | OS << "Objective-C object conversion"; | |||
9436 | break; | |||
9437 | ||||
9438 | case SK_ArrayLoopIndex: | |||
9439 | OS << "indexing for array initialization loop"; | |||
9440 | break; | |||
9441 | ||||
9442 | case SK_ArrayLoopInit: | |||
9443 | OS << "array initialization loop"; | |||
9444 | break; | |||
9445 | ||||
9446 | case SK_ArrayInit: | |||
9447 | OS << "array initialization"; | |||
9448 | break; | |||
9449 | ||||
9450 | case SK_GNUArrayInit: | |||
9451 | OS << "array initialization (GNU extension)"; | |||
9452 | break; | |||
9453 | ||||
9454 | case SK_ParenthesizedArrayInit: | |||
9455 | OS << "parenthesized array initialization"; | |||
9456 | break; | |||
9457 | ||||
9458 | case SK_PassByIndirectCopyRestore: | |||
9459 | OS << "pass by indirect copy and restore"; | |||
9460 | break; | |||
9461 | ||||
9462 | case SK_PassByIndirectRestore: | |||
9463 | OS << "pass by indirect restore"; | |||
9464 | break; | |||
9465 | ||||
9466 | case SK_ProduceObjCObject: | |||
9467 | OS << "Objective-C object retension"; | |||
9468 | break; | |||
9469 | ||||
9470 | case SK_StdInitializerList: | |||
9471 | OS << "std::initializer_list from initializer list"; | |||
9472 | break; | |||
9473 | ||||
9474 | case SK_StdInitializerListConstructorCall: | |||
9475 | OS << "list initialization from std::initializer_list"; | |||
9476 | break; | |||
9477 | ||||
9478 | case SK_OCLSamplerInit: | |||
9479 | OS << "OpenCL sampler_t from integer constant"; | |||
9480 | break; | |||
9481 | ||||
9482 | case SK_OCLZeroOpaqueType: | |||
9483 | OS << "OpenCL opaque type from zero"; | |||
9484 | break; | |||
9485 | } | |||
9486 | ||||
9487 | OS << " [" << S->Type.getAsString() << ']'; | |||
9488 | } | |||
9489 | ||||
9490 | OS << '\n'; | |||
9491 | } | |||
9492 | ||||
9493 | void InitializationSequence::dump() const { | |||
9494 | dump(llvm::errs()); | |||
9495 | } | |||
9496 | ||||
9497 | static bool NarrowingErrs(const LangOptions &L) { | |||
9498 | return L.CPlusPlus11 && | |||
9499 | (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015)); | |||
9500 | } | |||
9501 | ||||
9502 | static void DiagnoseNarrowingInInitList(Sema &S, | |||
9503 | const ImplicitConversionSequence &ICS, | |||
9504 | QualType PreNarrowingType, | |||
9505 | QualType EntityType, | |||
9506 | const Expr *PostInit) { | |||
9507 | const StandardConversionSequence *SCS = nullptr; | |||
9508 | switch (ICS.getKind()) { | |||
9509 | case ImplicitConversionSequence::StandardConversion: | |||
9510 | SCS = &ICS.Standard; | |||
9511 | break; | |||
9512 | case ImplicitConversionSequence::UserDefinedConversion: | |||
9513 | SCS = &ICS.UserDefined.After; | |||
9514 | break; | |||
9515 | case ImplicitConversionSequence::AmbiguousConversion: | |||
9516 | case ImplicitConversionSequence::EllipsisConversion: | |||
9517 | case ImplicitConversionSequence::BadConversion: | |||
9518 | return; | |||
9519 | } | |||
9520 | ||||
9521 | // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion. | |||
9522 | APValue ConstantValue; | |||
9523 | QualType ConstantType; | |||
9524 | switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue, | |||
9525 | ConstantType)) { | |||
9526 | case NK_Not_Narrowing: | |||
9527 | case NK_Dependent_Narrowing: | |||
9528 | // No narrowing occurred. | |||
9529 | return; | |||
9530 | ||||
9531 | case NK_Type_Narrowing: | |||
9532 | // This was a floating-to-integer conversion, which is always considered a | |||
9533 | // narrowing conversion even if the value is a constant and can be | |||
9534 | // represented exactly as an integer. | |||
9535 | S.Diag(PostInit->getBeginLoc(), NarrowingErrs(S.getLangOpts()) | |||
9536 | ? diag::ext_init_list_type_narrowing | |||
9537 | : diag::warn_init_list_type_narrowing) | |||
9538 | << PostInit->getSourceRange() | |||
9539 | << PreNarrowingType.getLocalUnqualifiedType() | |||
9540 | << EntityType.getLocalUnqualifiedType(); | |||
9541 | break; | |||
9542 | ||||
9543 | case NK_Constant_Narrowing: | |||
9544 | // A constant value was narrowed. | |||
9545 | S.Diag(PostInit->getBeginLoc(), | |||
9546 | NarrowingErrs(S.getLangOpts()) | |||
9547 | ? diag::ext_init_list_constant_narrowing | |||
9548 | : diag::warn_init_list_constant_narrowing) | |||
9549 | << PostInit->getSourceRange() | |||
9550 | << ConstantValue.getAsString(S.getASTContext(), ConstantType) | |||
9551 | << EntityType.getLocalUnqualifiedType(); | |||
9552 | break; | |||
9553 | ||||
9554 | case NK_Variable_Narrowing: | |||
9555 | // A variable's value may have been narrowed. | |||
9556 | S.Diag(PostInit->getBeginLoc(), | |||
9557 | NarrowingErrs(S.getLangOpts()) | |||
9558 | ? diag::ext_init_list_variable_narrowing | |||
9559 | : diag::warn_init_list_variable_narrowing) | |||
9560 | << PostInit->getSourceRange() | |||
9561 | << PreNarrowingType.getLocalUnqualifiedType() | |||
9562 | << EntityType.getLocalUnqualifiedType(); | |||
9563 | break; | |||
9564 | } | |||
9565 | ||||
9566 | SmallString<128> StaticCast; | |||
9567 | llvm::raw_svector_ostream OS(StaticCast); | |||
9568 | OS << "static_cast<"; | |||
9569 | if (const TypedefType *TT = EntityType->getAs<TypedefType>()) { | |||
9570 | // It's important to use the typedef's name if there is one so that the | |||
9571 | // fixit doesn't break code using types like int64_t. | |||
9572 | // | |||
9573 | // FIXME: This will break if the typedef requires qualification. But | |||
9574 | // getQualifiedNameAsString() includes non-machine-parsable components. | |||
9575 | OS << *TT->getDecl(); | |||
9576 | } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>()) | |||
9577 | OS << BT->getName(S.getLangOpts()); | |||
9578 | else { | |||
9579 | // Oops, we didn't find the actual type of the variable. Don't emit a fixit | |||
9580 | // with a broken cast. | |||
9581 | return; | |||
9582 | } | |||
9583 | OS << ">("; | |||
9584 | S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence) | |||
9585 | << PostInit->getSourceRange() | |||
9586 | << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str()) | |||
9587 | << FixItHint::CreateInsertion( | |||
9588 | S.getLocForEndOfToken(PostInit->getEndLoc()), ")"); | |||
9589 | } | |||
9590 | ||||
9591 | //===----------------------------------------------------------------------===// | |||
9592 | // Initialization helper functions | |||
9593 | //===----------------------------------------------------------------------===// | |||
9594 | bool | |||
9595 | Sema::CanPerformCopyInitialization(const InitializedEntity &Entity, | |||
9596 | ExprResult Init) { | |||
9597 | if (Init.isInvalid()) | |||
9598 | return false; | |||
9599 | ||||
9600 | Expr *InitE = Init.get(); | |||
9601 | assert(InitE && "No initialization expression")((InitE && "No initialization expression") ? static_cast <void> (0) : __assert_fail ("InitE && \"No initialization expression\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 9601, __PRETTY_FUNCTION__)); | |||
9602 | ||||
9603 | InitializationKind Kind = | |||
9604 | InitializationKind::CreateCopy(InitE->getBeginLoc(), SourceLocation()); | |||
9605 | InitializationSequence Seq(*this, Entity, Kind, InitE); | |||
9606 | return !Seq.Failed(); | |||
9607 | } | |||
9608 | ||||
9609 | ExprResult | |||
9610 | Sema::PerformCopyInitialization(const InitializedEntity &Entity, | |||
9611 | SourceLocation EqualLoc, | |||
9612 | ExprResult Init, | |||
9613 | bool TopLevelOfInitList, | |||
9614 | bool AllowExplicit) { | |||
9615 | if (Init.isInvalid()) | |||
9616 | return ExprError(); | |||
9617 | ||||
9618 | Expr *InitE = Init.get(); | |||
9619 | assert(InitE && "No initialization expression?")((InitE && "No initialization expression?") ? static_cast <void> (0) : __assert_fail ("InitE && \"No initialization expression?\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 9619, __PRETTY_FUNCTION__)); | |||
9620 | ||||
9621 | if (EqualLoc.isInvalid()) | |||
9622 | EqualLoc = InitE->getBeginLoc(); | |||
9623 | ||||
9624 | InitializationKind Kind = InitializationKind::CreateCopy( | |||
9625 | InitE->getBeginLoc(), EqualLoc, AllowExplicit); | |||
9626 | InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList); | |||
9627 | ||||
9628 | // Prevent infinite recursion when performing parameter copy-initialization. | |||
9629 | const bool ShouldTrackCopy = | |||
9630 | Entity.isParameterKind() && Seq.isConstructorInitialization(); | |||
9631 | if (ShouldTrackCopy) { | |||
9632 | if (llvm::find(CurrentParameterCopyTypes, Entity.getType()) != | |||
9633 | CurrentParameterCopyTypes.end()) { | |||
9634 | Seq.SetOverloadFailure( | |||
9635 | InitializationSequence::FK_ConstructorOverloadFailed, | |||
9636 | OR_No_Viable_Function); | |||
9637 | ||||
9638 | // Try to give a meaningful diagnostic note for the problematic | |||
9639 | // constructor. | |||
9640 | const auto LastStep = Seq.step_end() - 1; | |||
9641 | assert(LastStep->Kind ==((LastStep->Kind == InitializationSequence::SK_ConstructorInitialization ) ? static_cast<void> (0) : __assert_fail ("LastStep->Kind == InitializationSequence::SK_ConstructorInitialization" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 9642, __PRETTY_FUNCTION__)) | |||
9642 | InitializationSequence::SK_ConstructorInitialization)((LastStep->Kind == InitializationSequence::SK_ConstructorInitialization ) ? static_cast<void> (0) : __assert_fail ("LastStep->Kind == InitializationSequence::SK_ConstructorInitialization" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 9642, __PRETTY_FUNCTION__)); | |||
9643 | const FunctionDecl *Function = LastStep->Function.Function; | |||
9644 | auto Candidate = | |||
9645 | llvm::find_if(Seq.getFailedCandidateSet(), | |||
9646 | [Function](const OverloadCandidate &Candidate) -> bool { | |||
9647 | return Candidate.Viable && | |||
9648 | Candidate.Function == Function && | |||
9649 | Candidate.Conversions.size() > 0; | |||
9650 | }); | |||
9651 | if (Candidate != Seq.getFailedCandidateSet().end() && | |||
9652 | Function->getNumParams() > 0) { | |||
9653 | Candidate->Viable = false; | |||
9654 | Candidate->FailureKind = ovl_fail_bad_conversion; | |||
9655 | Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion, | |||
9656 | InitE, | |||
9657 | Function->getParamDecl(0)->getType()); | |||
9658 | } | |||
9659 | } | |||
9660 | CurrentParameterCopyTypes.push_back(Entity.getType()); | |||
9661 | } | |||
9662 | ||||
9663 | ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE); | |||
9664 | ||||
9665 | if (ShouldTrackCopy) | |||
9666 | CurrentParameterCopyTypes.pop_back(); | |||
9667 | ||||
9668 | return Result; | |||
9669 | } | |||
9670 | ||||
9671 | /// Determine whether RD is, or is derived from, a specialization of CTD. | |||
9672 | static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD, | |||
9673 | ClassTemplateDecl *CTD) { | |||
9674 | auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) { | |||
9675 | auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate); | |||
9676 | return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD); | |||
9677 | }; | |||
9678 | return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization)); | |||
9679 | } | |||
9680 | ||||
9681 | QualType Sema::DeduceTemplateSpecializationFromInitializer( | |||
9682 | TypeSourceInfo *TSInfo, const InitializedEntity &Entity, | |||
9683 | const InitializationKind &Kind, MultiExprArg Inits) { | |||
9684 | auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>( | |||
9685 | TSInfo->getType()->getContainedDeducedType()); | |||
9686 | assert(DeducedTST && "not a deduced template specialization type")((DeducedTST && "not a deduced template specialization type" ) ? static_cast<void> (0) : __assert_fail ("DeducedTST && \"not a deduced template specialization type\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/lib/Sema/SemaInit.cpp" , 9686, __PRETTY_FUNCTION__)); | |||
9687 | ||||
9688 | auto TemplateName = DeducedTST->getTemplateName(); | |||
9689 | if (TemplateName.isDependent()) | |||
9690 | return Context.DependentTy; | |||
9691 | ||||
9692 | // We can only perform deduction for class templates. | |||
9693 | auto *Template = | |||
9694 | dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl()); | |||
9695 | if (!Template) { | |||
9696 | Diag(Kind.getLocation(), | |||
9697 | diag::err_deduced_non_class_template_specialization_type) | |||
9698 | << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName; | |||
9699 | if (auto *TD = TemplateName.getAsTemplateDecl()) | |||
9700 | Diag(TD->getLocation(), diag::note_template_decl_here); | |||
9701 | return QualType(); | |||
9702 | } | |||
9703 | ||||
9704 | // Can't deduce from dependent arguments. | |||
9705 | if (Expr::hasAnyTypeDependentArguments(Inits)) { | |||
9706 | Diag(TSInfo->getTypeLoc().getBeginLoc(), | |||
9707 | diag::warn_cxx14_compat_class_template_argument_deduction) | |||
9708 | << TSInfo->getTypeLoc().getSourceRange() << 0; | |||
9709 | return Context.DependentTy; | |||
9710 | } | |||
9711 | ||||
9712 | // FIXME: Perform "exact type" matching first, per CWG discussion? | |||
9713 | // Or implement this via an implied 'T(T) -> T' deduction guide? | |||
9714 | ||||
9715 | // FIXME: Do we need/want a std::initializer_list<T> special case? | |||
9716 | ||||
9717 | // Look up deduction guides, including those synthesized from constructors. | |||
9718 | // | |||
9719 | // C++1z [over.match.class.deduct]p1: | |||
9720 | // A set of functions and function templates is formed comprising: | |||
9721 | // - For each constructor of the class template designated by the | |||
9722 | // template-name, a function template [...] | |||
9723 | // - For each deduction-guide, a function or function template [...] | |||
9724 | DeclarationNameInfo NameInfo( | |||
9725 | Context.DeclarationNames.getCXXDeductionGuideName(Template), | |||
9726 | TSInfo->getTypeLoc().getEndLoc()); | |||
9727 | LookupResult Guides(*this, NameInfo, LookupOrdinaryName); | |||
9728 | LookupQualifiedName(Guides, Template->getDeclContext()); | |||
9729 | ||||
9730 | // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't | |||
9731 | // clear on this, but they're not found by name so access does not apply. | |||
9732 | Guides.suppressDiagnostics(); | |||
9733 | ||||
9734 | // Figure out if this is list-initialization. | |||
9735 | InitListExpr *ListInit = | |||
9736 | (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct) | |||
9737 | ? dyn_cast<InitListExpr>(Inits[0]) | |||
9738 | : nullptr; | |||
9739 | ||||
9740 | // C++1z [over.match.class.deduct]p1: | |||
9741 | // Initialization and overload resolution are performed as described in | |||
9742 | // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list] | |||
9743 | // (as appropriate for the type of initialization performed) for an object | |||
9744 | // of a hypothetical class type, where the selected functions and function | |||
9745 | // templates are considered to be the constructors of that class type | |||
9746 | // | |||
9747 | // Since we know we're initializing a class type of a type unrelated to that | |||
9748 | // of the initializer, this reduces to something fairly reasonable. | |||
9749 | OverloadCandidateSet Candidates(Kind.getLocation(), | |||
9750 | OverloadCandidateSet::CSK_Normal); | |||
9751 | OverloadCandidateSet::iterator Best; | |||
9752 | ||||
9753 | bool HasAnyDeductionGuide = false; | |||
9754 | bool AllowExplicit = !Kind.isCopyInit() || ListInit; | |||
9755 | ||||
9756 | auto tryToResolveOverload = | |||
9757 | [&](bool OnlyListConstructors) -> OverloadingResult { | |||
9758 | Candidates.clear(OverloadCandidateSet::CSK_Normal); | |||
9759 | HasAnyDeductionGuide = false; | |||
9760 | ||||
9761 | for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) { | |||
9762 | NamedDecl *D = (*I)->getUnderlyingDecl(); | |||
9763 | if (D->isInvalidDecl()) | |||
9764 | continue; | |||
9765 | ||||
9766 | auto *TD = dyn_cast<FunctionTemplateDecl>(D); | |||
9767 | auto *GD = dyn_cast_or_null<CXXDeductionGuideDecl>( | |||
9768 | TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D)); | |||
9769 | if (!GD) | |||
9770 | continue; | |||
9771 | ||||
9772 | if (!GD->isImplicit()) | |||
9773 | HasAnyDeductionGuide = true; | |||
9774 | ||||
9775 | // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class) | |||
9776 | // For copy-initialization, the candidate functions are all the | |||
9777 | // converting constructors (12.3.1) of that class. | |||
9778 | // C++ [over.match.copy]p1: (non-list copy-initialization from class) | |||
9779 | // The converting constructors of T are candidate functions. | |||
9780 | if (!AllowExplicit) { | |||
9781 | // Only consider converting constructors. | |||
9782 | if (GD->isExplicit()) | |||
9783 | continue; | |||
9784 | ||||
9785 | // When looking for a converting constructor, deduction guides that | |||
9786 | // could never be called with one argument are not interesting to | |||
9787 | // check or note. | |||
9788 | if (GD->getMinRequiredArguments() > 1 || | |||
9789 | (GD->getNumParams() == 0 && !GD->isVariadic())) | |||
9790 | continue; | |||
9791 | } | |||
9792 | ||||
9793 | // C++ [over.match.list]p1.1: (first phase list initialization) | |||
9794 | // Initially, the candidate functions are the initializer-list | |||
9795 | // constructors of the class T | |||
9796 | if (OnlyListConstructors && !isInitListConstructor(GD)) | |||
9797 | continue; | |||
9798 | ||||
9799 | // C++ [over.match.list]p1.2: (second phase list initialization) | |||
9800 | // the candidate functions are all the constructors of the class T | |||
9801 | // C++ [over.match.ctor]p1: (all other cases) | |||
9802 | // the candidate functions are all the constructors of the class of | |||
9803 | // the object being initialized | |||
9804 | ||||
9805 | // C++ [over.best.ics]p4: | |||
9806 | // When [...] the constructor [...] is a candidate by | |||
9807 | // - [over.match.copy] (in all cases) | |||
9808 | // FIXME: The "second phase of [over.match.list] case can also | |||
9809 | // theoretically happen here, but it's not clear whether we can | |||
9810 | // ever have a parameter of the right type. | |||
9811 | bool SuppressUserConversions = Kind.isCopyInit(); | |||
9812 | ||||
9813 | if (TD) | |||
9814 | AddTemplateOverloadCandidate(TD, I.getPair(), /*ExplicitArgs*/ nullptr, | |||
9815 | Inits, Candidates, SuppressUserConversions, | |||
9816 | /*PartialOverloading*/ false, | |||
9817 | AllowExplicit); | |||
9818 | else | |||
9819 | AddOverloadCandidate(GD, I.getPair(), Inits, Candidates, | |||
9820 | SuppressUserConversions, | |||
9821 | /*PartialOverloading*/ false, AllowExplicit); | |||
9822 | } | |||
9823 | return Candidates.BestViableFunction(*this, Kind.getLocation(), Best); | |||
9824 | }; | |||
9825 | ||||
9826 | OverloadingResult Result = OR_No_Viable_Function; | |||
9827 | ||||
9828 | // C++11 [over.match.list]p1, per DR1467: for list-initialization, first | |||
9829 | // try initializer-list constructors. | |||
9830 | if (ListInit) { | |||
9831 | bool TryListConstructors = true; | |||
9832 | ||||
9833 | // Try list constructors unless the list is empty and the class has one or | |||
9834 | // more default constructors, in which case those constructors win. | |||
9835 | if (!ListInit->getNumInits()) { | |||
9836 | for (NamedDecl *D : Guides) { | |||
9837 | auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl()); | |||
9838 | if (FD && FD->getMinRequiredArguments() == 0) { | |||
9839 | TryListConstructors = false; | |||
9840 | break; | |||
9841 | } | |||
9842 | } | |||
9843 | } else if (ListInit->getNumInits() == 1) { | |||
9844 | // C++ [over.match.class.deduct]: | |||
9845 | // As an exception, the first phase in [over.match.list] (considering | |||
9846 | // initializer-list constructors) is omitted if the initializer list | |||
9847 | // consists of a single expression of type cv U, where U is a | |||
9848 | // specialization of C or a class derived from a specialization of C. | |||
9849 | Expr *E = ListInit->getInit(0); | |||
9850 | auto *RD = E->getType()->getAsCXXRecordDecl(); | |||
9851 | if (!isa<InitListExpr>(E) && RD && | |||
9852 | isCompleteType(Kind.getLocation(), E->getType()) && | |||
9853 | isOrIsDerivedFromSpecializationOf(RD, Template)) | |||
9854 | TryListConstructors = false; | |||
9855 | } | |||
9856 | ||||
9857 | if (TryListConstructors) | |||
9858 | Result = tryToResolveOverload(/*OnlyListConstructor*/true); | |||
9859 | // Then unwrap the initializer list and try again considering all | |||
9860 | // constructors. | |||
9861 | Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits()); | |||
9862 | } | |||
9863 | ||||
9864 | // If list-initialization fails, or if we're doing any other kind of | |||
9865 | // initialization, we (eventually) consider constructors. | |||
9866 | if (Result == OR_No_Viable_Function) | |||
9867 | Result = tryToResolveOverload(/*OnlyListConstructor*/false); | |||
9868 | ||||
9869 | switch (Result) { | |||
9870 | case OR_Ambiguous: | |||
9871 | // FIXME: For list-initialization candidates, it'd usually be better to | |||
9872 | // list why they were not viable when given the initializer list itself as | |||
9873 | // an argument. | |||
9874 | Candidates.NoteCandidates( | |||
9875 | PartialDiagnosticAt( | |||
9876 | Kind.getLocation(), | |||
9877 | PDiag(diag::err_deduced_class_template_ctor_ambiguous) | |||
9878 | << TemplateName), | |||
9879 | *this, OCD_AmbiguousCandidates, Inits); | |||
9880 | return QualType(); | |||
9881 | ||||
9882 | case OR_No_Viable_Function: { | |||
9883 | CXXRecordDecl *Primary = | |||
9884 | cast<ClassTemplateDecl>(Template)->getTemplatedDecl(); | |||
9885 | bool Complete = | |||
9886 | isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary)); | |||
9887 | Candidates.NoteCandidates( | |||
9888 | PartialDiagnosticAt( | |||
9889 | Kind.getLocation(), | |||
9890 | PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable | |||
9891 | : diag::err_deduced_class_template_incomplete) | |||
9892 | << TemplateName << !Guides.empty()), | |||
9893 | *this, OCD_AllCandidates, Inits); | |||
9894 | return QualType(); | |||
9895 | } | |||
9896 | ||||
9897 | case OR_Deleted: { | |||
9898 | Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted) | |||
9899 | << TemplateName; | |||
9900 | NoteDeletedFunction(Best->Function); | |||
9901 | return QualType(); | |||
9902 | } | |||
9903 | ||||
9904 | case OR_Success: | |||
9905 | // C++ [over.match.list]p1: | |||
9906 | // In copy-list-initialization, if an explicit constructor is chosen, the | |||
9907 | // initialization is ill-formed. | |||
9908 | if (Kind.isCopyInit() && ListInit && | |||
9909 | cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) { | |||
9910 | bool IsDeductionGuide = !Best->Function->isImplicit(); | |||
9911 | Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit) | |||
9912 | << TemplateName << IsDeductionGuide; | |||
9913 | Diag(Best->Function->getLocation(), | |||
9914 | diag::note_explicit_ctor_deduction_guide_here) | |||
9915 | << IsDeductionGuide; | |||
9916 | return QualType(); | |||
9917 | } | |||
9918 | ||||
9919 | // Make sure we didn't select an unusable deduction guide, and mark it | |||
9920 | // as referenced. | |||
9921 | DiagnoseUseOfDecl(Best->Function, Kind.getLocation()); | |||
9922 | MarkFunctionReferenced(Kind.getLocation(), Best->Function); | |||
9923 | break; | |||
9924 | } | |||
9925 | ||||
9926 | // C++ [dcl.type.class.deduct]p1: | |||
9927 | // The placeholder is replaced by the return type of the function selected | |||
9928 | // by overload resolution for class template deduction. | |||
9929 | QualType DeducedType = | |||
9930 | SubstAutoType(TSInfo->getType(), Best->Function->getReturnType()); | |||
9931 | Diag(TSInfo->getTypeLoc().getBeginLoc(), | |||
9932 | diag::warn_cxx14_compat_class_template_argument_deduction) | |||
9933 | << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType; | |||
9934 | ||||
9935 | // Warn if CTAD was used on a type that does not have any user-defined | |||
9936 | // deduction guides. | |||
9937 | if (!HasAnyDeductionGuide) { | |||
9938 | Diag(TSInfo->getTypeLoc().getBeginLoc(), | |||
9939 | diag::warn_ctad_maybe_unsupported) | |||
9940 | << TemplateName; | |||
9941 | Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported); | |||
9942 | } | |||
9943 | ||||
9944 | return DeducedType; | |||
9945 | } |
1 | //===- Initialization.h - Semantic Analysis for Initializers ----*- C++ -*-===// |
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 provides supporting data types for initialization of objects. |
10 | // |
11 | //===----------------------------------------------------------------------===// |
12 | |
13 | #ifndef LLVM_CLANG_SEMA_INITIALIZATION_H |
14 | #define LLVM_CLANG_SEMA_INITIALIZATION_H |
15 | |
16 | #include "clang/AST/ASTContext.h" |
17 | #include "clang/AST/Attr.h" |
18 | #include "clang/AST/Decl.h" |
19 | #include "clang/AST/DeclAccessPair.h" |
20 | #include "clang/AST/DeclarationName.h" |
21 | #include "clang/AST/Expr.h" |
22 | #include "clang/AST/Type.h" |
23 | #include "clang/Basic/IdentifierTable.h" |
24 | #include "clang/Basic/LLVM.h" |
25 | #include "clang/Basic/LangOptions.h" |
26 | #include "clang/Basic/SourceLocation.h" |
27 | #include "clang/Basic/Specifiers.h" |
28 | #include "clang/Sema/Overload.h" |
29 | #include "clang/Sema/Ownership.h" |
30 | #include "llvm/ADT/ArrayRef.h" |
31 | #include "llvm/ADT/SmallVector.h" |
32 | #include "llvm/ADT/StringRef.h" |
33 | #include "llvm/ADT/iterator_range.h" |
34 | #include "llvm/Support/Casting.h" |
35 | #include <cassert> |
36 | #include <cstdint> |
37 | #include <string> |
38 | |
39 | namespace clang { |
40 | |
41 | class APValue; |
42 | class CXXBaseSpecifier; |
43 | class CXXConstructorDecl; |
44 | class ObjCMethodDecl; |
45 | class Sema; |
46 | |
47 | /// Describes an entity that is being initialized. |
48 | class alignas(8) InitializedEntity { |
49 | public: |
50 | /// Specifies the kind of entity being initialized. |
51 | enum EntityKind { |
52 | /// The entity being initialized is a variable. |
53 | EK_Variable, |
54 | |
55 | /// The entity being initialized is a function parameter. |
56 | EK_Parameter, |
57 | |
58 | /// The entity being initialized is the result of a function call. |
59 | EK_Result, |
60 | |
61 | /// The entity being initialized is the result of a statement expression. |
62 | EK_StmtExprResult, |
63 | |
64 | /// The entity being initialized is an exception object that |
65 | /// is being thrown. |
66 | EK_Exception, |
67 | |
68 | /// The entity being initialized is a non-static data member |
69 | /// subobject. |
70 | EK_Member, |
71 | |
72 | /// The entity being initialized is an element of an array. |
73 | EK_ArrayElement, |
74 | |
75 | /// The entity being initialized is an object (or array of |
76 | /// objects) allocated via new. |
77 | EK_New, |
78 | |
79 | /// The entity being initialized is a temporary object. |
80 | EK_Temporary, |
81 | |
82 | /// The entity being initialized is a base member subobject. |
83 | EK_Base, |
84 | |
85 | /// The initialization is being done by a delegating constructor. |
86 | EK_Delegating, |
87 | |
88 | /// The entity being initialized is an element of a vector. |
89 | /// or vector. |
90 | EK_VectorElement, |
91 | |
92 | /// The entity being initialized is a field of block descriptor for |
93 | /// the copied-in c++ object. |
94 | EK_BlockElement, |
95 | |
96 | /// The entity being initialized is a field of block descriptor for the |
97 | /// copied-in lambda object that's used in the lambda to block conversion. |
98 | EK_LambdaToBlockConversionBlockElement, |
99 | |
100 | /// The entity being initialized is the real or imaginary part of a |
101 | /// complex number. |
102 | EK_ComplexElement, |
103 | |
104 | /// The entity being initialized is the field that captures a |
105 | /// variable in a lambda. |
106 | EK_LambdaCapture, |
107 | |
108 | /// The entity being initialized is the initializer for a compound |
109 | /// literal. |
110 | EK_CompoundLiteralInit, |
111 | |
112 | /// The entity being implicitly initialized back to the formal |
113 | /// result type. |
114 | EK_RelatedResult, |
115 | |
116 | /// The entity being initialized is a function parameter; function |
117 | /// is member of group of audited CF APIs. |
118 | EK_Parameter_CF_Audited, |
119 | |
120 | /// The entity being initialized is a structured binding of a |
121 | /// decomposition declaration. |
122 | EK_Binding, |
123 | |
124 | // Note: err_init_conversion_failed in DiagnosticSemaKinds.td uses this |
125 | // enum as an index for its first %select. When modifying this list, |
126 | // that diagnostic text needs to be updated as well. |
127 | }; |
128 | |
129 | private: |
130 | /// The kind of entity being initialized. |
131 | EntityKind Kind; |
132 | |
133 | /// If non-NULL, the parent entity in which this |
134 | /// initialization occurs. |
135 | const InitializedEntity *Parent = nullptr; |
136 | |
137 | /// The type of the object or reference being initialized. |
138 | QualType Type; |
139 | |
140 | /// The mangling number for the next reference temporary to be created. |
141 | mutable unsigned ManglingNumber = 0; |
142 | |
143 | struct LN { |
144 | /// When Kind == EK_Result, EK_Exception, EK_New, the |
145 | /// location of the 'return', 'throw', or 'new' keyword, |
146 | /// respectively. When Kind == EK_Temporary, the location where |
147 | /// the temporary is being created. |
148 | unsigned Location; |
149 | |
150 | /// Whether the entity being initialized may end up using the |
151 | /// named return value optimization (NRVO). |
152 | bool NRVO; |
153 | }; |
154 | |
155 | struct VD { |
156 | /// The VarDecl, FieldDecl, or BindingDecl being initialized. |
157 | ValueDecl *VariableOrMember; |
158 | |
159 | /// When Kind == EK_Member, whether this is an implicit member |
160 | /// initialization in a copy or move constructor. These can perform array |
161 | /// copies. |
162 | bool IsImplicitFieldInit; |
163 | |
164 | /// When Kind == EK_Member, whether this is the initial initialization |
165 | /// check for a default member initializer. |
166 | bool IsDefaultMemberInit; |
167 | }; |
168 | |
169 | struct C { |
170 | /// The name of the variable being captured by an EK_LambdaCapture. |
171 | IdentifierInfo *VarID; |
172 | |
173 | /// The source location at which the capture occurs. |
174 | unsigned Location; |
175 | }; |
176 | |
177 | union { |
178 | /// When Kind == EK_Variable, EK_Member or EK_Binding, the variable. |
179 | VD Variable; |
180 | |
181 | /// When Kind == EK_RelatedResult, the ObjectiveC method where |
182 | /// result type was implicitly changed to accommodate ARC semantics. |
183 | ObjCMethodDecl *MethodDecl; |
184 | |
185 | /// When Kind == EK_Parameter, the ParmVarDecl, with the |
186 | /// low bit indicating whether the parameter is "consumed". |
187 | uintptr_t Parameter; |
188 | |
189 | /// When Kind == EK_Temporary or EK_CompoundLiteralInit, the type |
190 | /// source information for the temporary. |
191 | TypeSourceInfo *TypeInfo; |
192 | |
193 | struct LN LocAndNRVO; |
194 | |
195 | /// When Kind == EK_Base, the base specifier that provides the |
196 | /// base class. The lower bit specifies whether the base is an inherited |
197 | /// virtual base. |
198 | uintptr_t Base; |
199 | |
200 | /// When Kind == EK_ArrayElement, EK_VectorElement, or |
201 | /// EK_ComplexElement, the index of the array or vector element being |
202 | /// initialized. |
203 | unsigned Index; |
204 | |
205 | struct C Capture; |
206 | }; |
207 | |
208 | InitializedEntity() = default; |
209 | |
210 | /// Create the initialization entity for a variable. |
211 | InitializedEntity(VarDecl *Var, EntityKind EK = EK_Variable) |
212 | : Kind(EK), Type(Var->getType()), Variable{Var, false, false} {} |
213 | |
214 | /// Create the initialization entity for the result of a |
215 | /// function, throwing an object, performing an explicit cast, or |
216 | /// initializing a parameter for which there is no declaration. |
217 | InitializedEntity(EntityKind Kind, SourceLocation Loc, QualType Type, |
218 | bool NRVO = false) |
219 | : Kind(Kind), Type(Type) { |
220 | LocAndNRVO.Location = Loc.getRawEncoding(); |
221 | LocAndNRVO.NRVO = NRVO; |
222 | } |
223 | |
224 | /// Create the initialization entity for a member subobject. |
225 | InitializedEntity(FieldDecl *Member, const InitializedEntity *Parent, |
226 | bool Implicit, bool DefaultMemberInit) |
227 | : Kind(EK_Member), Parent(Parent), Type(Member->getType()), |
228 | Variable{Member, Implicit, DefaultMemberInit} {} |
229 | |
230 | /// Create the initialization entity for an array element. |
231 | InitializedEntity(ASTContext &Context, unsigned Index, |
232 | const InitializedEntity &Parent); |
233 | |
234 | /// Create the initialization entity for a lambda capture. |
235 | InitializedEntity(IdentifierInfo *VarID, QualType FieldType, SourceLocation Loc) |
236 | : Kind(EK_LambdaCapture), Type(FieldType) { |
237 | Capture.VarID = VarID; |
238 | Capture.Location = Loc.getRawEncoding(); |
239 | } |
240 | |
241 | public: |
242 | /// Create the initialization entity for a variable. |
243 | static InitializedEntity InitializeVariable(VarDecl *Var) { |
244 | return InitializedEntity(Var); |
245 | } |
246 | |
247 | /// Create the initialization entity for a parameter. |
248 | static InitializedEntity InitializeParameter(ASTContext &Context, |
249 | const ParmVarDecl *Parm) { |
250 | return InitializeParameter(Context, Parm, Parm->getType()); |
251 | } |
252 | |
253 | /// Create the initialization entity for a parameter, but use |
254 | /// another type. |
255 | static InitializedEntity InitializeParameter(ASTContext &Context, |
256 | const ParmVarDecl *Parm, |
257 | QualType Type) { |
258 | bool Consumed = (Context.getLangOpts().ObjCAutoRefCount && |
259 | Parm->hasAttr<NSConsumedAttr>()); |
260 | |
261 | InitializedEntity Entity; |
262 | Entity.Kind = EK_Parameter; |
263 | Entity.Type = |
264 | Context.getVariableArrayDecayedType(Type.getUnqualifiedType()); |
265 | Entity.Parent = nullptr; |
266 | Entity.Parameter |
267 | = (static_cast<uintptr_t>(Consumed) | reinterpret_cast<uintptr_t>(Parm)); |
268 | return Entity; |
269 | } |
270 | |
271 | /// Create the initialization entity for a parameter that is |
272 | /// only known by its type. |
273 | static InitializedEntity InitializeParameter(ASTContext &Context, |
274 | QualType Type, |
275 | bool Consumed) { |
276 | InitializedEntity Entity; |
277 | Entity.Kind = EK_Parameter; |
278 | Entity.Type = Context.getVariableArrayDecayedType(Type); |
279 | Entity.Parent = nullptr; |
280 | Entity.Parameter = (Consumed); |
281 | return Entity; |
282 | } |
283 | |
284 | /// Create the initialization entity for the result of a function. |
285 | static InitializedEntity InitializeResult(SourceLocation ReturnLoc, |
286 | QualType Type, bool NRVO) { |
287 | return InitializedEntity(EK_Result, ReturnLoc, Type, NRVO); |
288 | } |
289 | |
290 | static InitializedEntity InitializeStmtExprResult(SourceLocation ReturnLoc, |
291 | QualType Type) { |
292 | return InitializedEntity(EK_StmtExprResult, ReturnLoc, Type); |
293 | } |
294 | |
295 | static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc, |
296 | QualType Type, bool NRVO) { |
297 | return InitializedEntity(EK_BlockElement, BlockVarLoc, Type, NRVO); |
298 | } |
299 | |
300 | static InitializedEntity InitializeLambdaToBlock(SourceLocation BlockVarLoc, |
301 | QualType Type, bool NRVO) { |
302 | return InitializedEntity(EK_LambdaToBlockConversionBlockElement, |
303 | BlockVarLoc, Type, NRVO); |
304 | } |
305 | |
306 | /// Create the initialization entity for an exception object. |
307 | static InitializedEntity InitializeException(SourceLocation ThrowLoc, |
308 | QualType Type, bool NRVO) { |
309 | return InitializedEntity(EK_Exception, ThrowLoc, Type, NRVO); |
310 | } |
311 | |
312 | /// Create the initialization entity for an object allocated via new. |
313 | static InitializedEntity InitializeNew(SourceLocation NewLoc, QualType Type) { |
314 | return InitializedEntity(EK_New, NewLoc, Type); |
315 | } |
316 | |
317 | /// Create the initialization entity for a temporary. |
318 | static InitializedEntity InitializeTemporary(QualType Type) { |
319 | return InitializeTemporary(nullptr, Type); |
320 | } |
321 | |
322 | /// Create the initialization entity for a temporary. |
323 | static InitializedEntity InitializeTemporary(TypeSourceInfo *TypeInfo) { |
324 | return InitializeTemporary(TypeInfo, TypeInfo->getType()); |
325 | } |
326 | |
327 | /// Create the initialization entity for a temporary. |
328 | static InitializedEntity InitializeTemporary(TypeSourceInfo *TypeInfo, |
329 | QualType Type) { |
330 | InitializedEntity Result(EK_Temporary, SourceLocation(), Type); |
331 | Result.TypeInfo = TypeInfo; |
332 | return Result; |
333 | } |
334 | |
335 | /// Create the initialization entity for a related result. |
336 | static InitializedEntity InitializeRelatedResult(ObjCMethodDecl *MD, |
337 | QualType Type) { |
338 | InitializedEntity Result(EK_RelatedResult, SourceLocation(), Type); |
339 | Result.MethodDecl = MD; |
340 | return Result; |
341 | } |
342 | |
343 | /// Create the initialization entity for a base class subobject. |
344 | static InitializedEntity |
345 | InitializeBase(ASTContext &Context, const CXXBaseSpecifier *Base, |
346 | bool IsInheritedVirtualBase, |
347 | const InitializedEntity *Parent = nullptr); |
348 | |
349 | /// Create the initialization entity for a delegated constructor. |
350 | static InitializedEntity InitializeDelegation(QualType Type) { |
351 | return InitializedEntity(EK_Delegating, SourceLocation(), Type); |
352 | } |
353 | |
354 | /// Create the initialization entity for a member subobject. |
355 | static InitializedEntity |
356 | InitializeMember(FieldDecl *Member, |
357 | const InitializedEntity *Parent = nullptr, |
358 | bool Implicit = false) { |
359 | return InitializedEntity(Member, Parent, Implicit, false); |
360 | } |
361 | |
362 | /// Create the initialization entity for a member subobject. |
363 | static InitializedEntity |
364 | InitializeMember(IndirectFieldDecl *Member, |
365 | const InitializedEntity *Parent = nullptr, |
366 | bool Implicit = false) { |
367 | return InitializedEntity(Member->getAnonField(), Parent, Implicit, false); |
368 | } |
369 | |
370 | /// Create the initialization entity for a default member initializer. |
371 | static InitializedEntity |
372 | InitializeMemberFromDefaultMemberInitializer(FieldDecl *Member) { |
373 | return InitializedEntity(Member, nullptr, false, true); |
374 | } |
375 | |
376 | /// Create the initialization entity for an array element. |
377 | static InitializedEntity InitializeElement(ASTContext &Context, |
378 | unsigned Index, |
379 | const InitializedEntity &Parent) { |
380 | return InitializedEntity(Context, Index, Parent); |
381 | } |
382 | |
383 | /// Create the initialization entity for a structured binding. |
384 | static InitializedEntity InitializeBinding(VarDecl *Binding) { |
385 | return InitializedEntity(Binding, EK_Binding); |
386 | } |
387 | |
388 | /// Create the initialization entity for a lambda capture. |
389 | /// |
390 | /// \p VarID The name of the entity being captured, or nullptr for 'this'. |
391 | static InitializedEntity InitializeLambdaCapture(IdentifierInfo *VarID, |
392 | QualType FieldType, |
393 | SourceLocation Loc) { |
394 | return InitializedEntity(VarID, FieldType, Loc); |
395 | } |
396 | |
397 | /// Create the entity for a compound literal initializer. |
398 | static InitializedEntity InitializeCompoundLiteralInit(TypeSourceInfo *TSI) { |
399 | InitializedEntity Result(EK_CompoundLiteralInit, SourceLocation(), |
400 | TSI->getType()); |
401 | Result.TypeInfo = TSI; |
402 | return Result; |
403 | } |
404 | |
405 | /// Determine the kind of initialization. |
406 | EntityKind getKind() const { return Kind; } |
407 | |
408 | /// Retrieve the parent of the entity being initialized, when |
409 | /// the initialization itself is occurring within the context of a |
410 | /// larger initialization. |
411 | const InitializedEntity *getParent() const { return Parent; } |
412 | |
413 | /// Retrieve type being initialized. |
414 | QualType getType() const { return Type; } |
415 | |
416 | /// Retrieve complete type-source information for the object being |
417 | /// constructed, if known. |
418 | TypeSourceInfo *getTypeSourceInfo() const { |
419 | if (Kind == EK_Temporary || Kind == EK_CompoundLiteralInit) |
420 | return TypeInfo; |
421 | |
422 | return nullptr; |
423 | } |
424 | |
425 | /// Retrieve the name of the entity being initialized. |
426 | DeclarationName getName() const; |
427 | |
428 | /// Retrieve the variable, parameter, or field being |
429 | /// initialized. |
430 | ValueDecl *getDecl() const; |
431 | |
432 | /// Retrieve the ObjectiveC method being initialized. |
433 | ObjCMethodDecl *getMethodDecl() const { return MethodDecl; } |
434 | |
435 | /// Determine whether this initialization allows the named return |
436 | /// value optimization, which also applies to thrown objects. |
437 | bool allowsNRVO() const; |
438 | |
439 | bool isParameterKind() const { |
440 | return (getKind() == EK_Parameter || |
441 | getKind() == EK_Parameter_CF_Audited); |
442 | } |
443 | |
444 | /// Determine whether this initialization consumes the |
445 | /// parameter. |
446 | bool isParameterConsumed() const { |
447 | assert(isParameterKind() && "Not a parameter")((isParameterKind() && "Not a parameter") ? static_cast <void> (0) : __assert_fail ("isParameterKind() && \"Not a parameter\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/include/clang/Sema/Initialization.h" , 447, __PRETTY_FUNCTION__)); |
448 | return (Parameter & 1); |
449 | } |
450 | |
451 | /// Retrieve the base specifier. |
452 | const CXXBaseSpecifier *getBaseSpecifier() const { |
453 | assert(getKind() == EK_Base && "Not a base specifier")((getKind() == EK_Base && "Not a base specifier") ? static_cast <void> (0) : __assert_fail ("getKind() == EK_Base && \"Not a base specifier\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/include/clang/Sema/Initialization.h" , 453, __PRETTY_FUNCTION__)); |
454 | return reinterpret_cast<const CXXBaseSpecifier *>(Base & ~0x1); |
455 | } |
456 | |
457 | /// Return whether the base is an inherited virtual base. |
458 | bool isInheritedVirtualBase() const { |
459 | assert(getKind() == EK_Base && "Not a base specifier")((getKind() == EK_Base && "Not a base specifier") ? static_cast <void> (0) : __assert_fail ("getKind() == EK_Base && \"Not a base specifier\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/include/clang/Sema/Initialization.h" , 459, __PRETTY_FUNCTION__)); |
460 | return Base & 0x1; |
461 | } |
462 | |
463 | /// Determine whether this is an array new with an unknown bound. |
464 | bool isVariableLengthArrayNew() const { |
465 | return getKind() == EK_New && dyn_cast_or_null<IncompleteArrayType>( |
466 | getType()->getAsArrayTypeUnsafe()); |
467 | } |
468 | |
469 | /// Is this the implicit initialization of a member of a class from |
470 | /// a defaulted constructor? |
471 | bool isImplicitMemberInitializer() const { |
472 | return getKind() == EK_Member && Variable.IsImplicitFieldInit; |
473 | } |
474 | |
475 | /// Is this the default member initializer of a member (specified inside |
476 | /// the class definition)? |
477 | bool isDefaultMemberInitializer() const { |
478 | return getKind() == EK_Member && Variable.IsDefaultMemberInit; |
479 | } |
480 | |
481 | /// Determine the location of the 'return' keyword when initializing |
482 | /// the result of a function call. |
483 | SourceLocation getReturnLoc() const { |
484 | assert(getKind() == EK_Result && "No 'return' location!")((getKind() == EK_Result && "No 'return' location!") ? static_cast<void> (0) : __assert_fail ("getKind() == EK_Result && \"No 'return' location!\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/include/clang/Sema/Initialization.h" , 484, __PRETTY_FUNCTION__)); |
485 | return SourceLocation::getFromRawEncoding(LocAndNRVO.Location); |
486 | } |
487 | |
488 | /// Determine the location of the 'throw' keyword when initializing |
489 | /// an exception object. |
490 | SourceLocation getThrowLoc() const { |
491 | assert(getKind() == EK_Exception && "No 'throw' location!")((getKind() == EK_Exception && "No 'throw' location!" ) ? static_cast<void> (0) : __assert_fail ("getKind() == EK_Exception && \"No 'throw' location!\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/include/clang/Sema/Initialization.h" , 491, __PRETTY_FUNCTION__)); |
492 | return SourceLocation::getFromRawEncoding(LocAndNRVO.Location); |
493 | } |
494 | |
495 | /// If this is an array, vector, or complex number element, get the |
496 | /// element's index. |
497 | unsigned getElementIndex() const { |
498 | assert(getKind() == EK_ArrayElement || getKind() == EK_VectorElement ||((getKind() == EK_ArrayElement || getKind() == EK_VectorElement || getKind() == EK_ComplexElement) ? static_cast<void> (0) : __assert_fail ("getKind() == EK_ArrayElement || getKind() == EK_VectorElement || getKind() == EK_ComplexElement" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/include/clang/Sema/Initialization.h" , 499, __PRETTY_FUNCTION__)) |
499 | getKind() == EK_ComplexElement)((getKind() == EK_ArrayElement || getKind() == EK_VectorElement || getKind() == EK_ComplexElement) ? static_cast<void> (0) : __assert_fail ("getKind() == EK_ArrayElement || getKind() == EK_VectorElement || getKind() == EK_ComplexElement" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/include/clang/Sema/Initialization.h" , 499, __PRETTY_FUNCTION__)); |
500 | return Index; |
501 | } |
502 | |
503 | /// If this is already the initializer for an array or vector |
504 | /// element, sets the element index. |
505 | void setElementIndex(unsigned Index) { |
506 | assert(getKind() == EK_ArrayElement || getKind() == EK_VectorElement ||((getKind() == EK_ArrayElement || getKind() == EK_VectorElement || getKind() == EK_ComplexElement) ? static_cast<void> (0) : __assert_fail ("getKind() == EK_ArrayElement || getKind() == EK_VectorElement || getKind() == EK_ComplexElement" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/include/clang/Sema/Initialization.h" , 507, __PRETTY_FUNCTION__)) |
507 | getKind() == EK_ComplexElement)((getKind() == EK_ArrayElement || getKind() == EK_VectorElement || getKind() == EK_ComplexElement) ? static_cast<void> (0) : __assert_fail ("getKind() == EK_ArrayElement || getKind() == EK_VectorElement || getKind() == EK_ComplexElement" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/include/clang/Sema/Initialization.h" , 507, __PRETTY_FUNCTION__)); |
508 | this->Index = Index; |
509 | } |
510 | |
511 | /// For a lambda capture, return the capture's name. |
512 | StringRef getCapturedVarName() const { |
513 | assert(getKind() == EK_LambdaCapture && "Not a lambda capture!")((getKind() == EK_LambdaCapture && "Not a lambda capture!" ) ? static_cast<void> (0) : __assert_fail ("getKind() == EK_LambdaCapture && \"Not a lambda capture!\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/include/clang/Sema/Initialization.h" , 513, __PRETTY_FUNCTION__)); |
514 | return Capture.VarID ? Capture.VarID->getName() : "this"; |
515 | } |
516 | |
517 | /// Determine the location of the capture when initializing |
518 | /// field from a captured variable in a lambda. |
519 | SourceLocation getCaptureLoc() const { |
520 | assert(getKind() == EK_LambdaCapture && "Not a lambda capture!")((getKind() == EK_LambdaCapture && "Not a lambda capture!" ) ? static_cast<void> (0) : __assert_fail ("getKind() == EK_LambdaCapture && \"Not a lambda capture!\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/include/clang/Sema/Initialization.h" , 520, __PRETTY_FUNCTION__)); |
521 | return SourceLocation::getFromRawEncoding(Capture.Location); |
522 | } |
523 | |
524 | void setParameterCFAudited() { |
525 | Kind = EK_Parameter_CF_Audited; |
526 | } |
527 | |
528 | unsigned allocateManglingNumber() const { return ++ManglingNumber; } |
529 | |
530 | /// Dump a representation of the initialized entity to standard error, |
531 | /// for debugging purposes. |
532 | void dump() const; |
533 | |
534 | private: |
535 | unsigned dumpImpl(raw_ostream &OS) const; |
536 | }; |
537 | |
538 | /// Describes the kind of initialization being performed, along with |
539 | /// location information for tokens related to the initialization (equal sign, |
540 | /// parentheses). |
541 | class InitializationKind { |
542 | public: |
543 | /// The kind of initialization being performed. |
544 | enum InitKind { |
545 | /// Direct initialization |
546 | IK_Direct, |
547 | |
548 | /// Direct list-initialization |
549 | IK_DirectList, |
550 | |
551 | /// Copy initialization |
552 | IK_Copy, |
553 | |
554 | /// Default initialization |
555 | IK_Default, |
556 | |
557 | /// Value initialization |
558 | IK_Value |
559 | }; |
560 | |
561 | private: |
562 | /// The context of the initialization. |
563 | enum InitContext { |
564 | /// Normal context |
565 | IC_Normal, |
566 | |
567 | /// Normal context, but allows explicit conversion functionss |
568 | IC_ExplicitConvs, |
569 | |
570 | /// Implicit context (value initialization) |
571 | IC_Implicit, |
572 | |
573 | /// Static cast context |
574 | IC_StaticCast, |
575 | |
576 | /// C-style cast context |
577 | IC_CStyleCast, |
578 | |
579 | /// Functional cast context |
580 | IC_FunctionalCast |
581 | }; |
582 | |
583 | /// The kind of initialization being performed. |
584 | InitKind Kind : 8; |
585 | |
586 | /// The context of the initialization. |
587 | InitContext Context : 8; |
588 | |
589 | /// The source locations involved in the initialization. |
590 | SourceLocation Locations[3]; |
591 | |
592 | InitializationKind(InitKind Kind, InitContext Context, SourceLocation Loc1, |
593 | SourceLocation Loc2, SourceLocation Loc3) |
594 | : Kind(Kind), Context(Context) { |
595 | Locations[0] = Loc1; |
596 | Locations[1] = Loc2; |
597 | Locations[2] = Loc3; |
598 | } |
599 | |
600 | public: |
601 | /// Create a direct initialization. |
602 | static InitializationKind CreateDirect(SourceLocation InitLoc, |
603 | SourceLocation LParenLoc, |
604 | SourceLocation RParenLoc) { |
605 | return InitializationKind(IK_Direct, IC_Normal, |
606 | InitLoc, LParenLoc, RParenLoc); |
607 | } |
608 | |
609 | static InitializationKind CreateDirectList(SourceLocation InitLoc) { |
610 | return InitializationKind(IK_DirectList, IC_Normal, InitLoc, InitLoc, |
611 | InitLoc); |
612 | } |
613 | |
614 | static InitializationKind CreateDirectList(SourceLocation InitLoc, |
615 | SourceLocation LBraceLoc, |
616 | SourceLocation RBraceLoc) { |
617 | return InitializationKind(IK_DirectList, IC_Normal, InitLoc, LBraceLoc, |
618 | RBraceLoc); |
619 | } |
620 | |
621 | /// Create a direct initialization due to a cast that isn't a C-style |
622 | /// or functional cast. |
623 | static InitializationKind CreateCast(SourceRange TypeRange) { |
624 | return InitializationKind(IK_Direct, IC_StaticCast, TypeRange.getBegin(), |
625 | TypeRange.getBegin(), TypeRange.getEnd()); |
626 | } |
627 | |
628 | /// Create a direct initialization for a C-style cast. |
629 | static InitializationKind CreateCStyleCast(SourceLocation StartLoc, |
630 | SourceRange TypeRange, |
631 | bool InitList) { |
632 | // C++ cast syntax doesn't permit init lists, but C compound literals are |
633 | // exactly that. |
634 | return InitializationKind(InitList ? IK_DirectList : IK_Direct, |
635 | IC_CStyleCast, StartLoc, TypeRange.getBegin(), |
636 | TypeRange.getEnd()); |
637 | } |
638 | |
639 | /// Create a direct initialization for a functional cast. |
640 | static InitializationKind CreateFunctionalCast(SourceRange TypeRange, |
641 | bool InitList) { |
642 | return InitializationKind(InitList ? IK_DirectList : IK_Direct, |
643 | IC_FunctionalCast, TypeRange.getBegin(), |
644 | TypeRange.getBegin(), TypeRange.getEnd()); |
645 | } |
646 | |
647 | /// Create a copy initialization. |
648 | static InitializationKind CreateCopy(SourceLocation InitLoc, |
649 | SourceLocation EqualLoc, |
650 | bool AllowExplicitConvs = false) { |
651 | return InitializationKind(IK_Copy, |
652 | AllowExplicitConvs? IC_ExplicitConvs : IC_Normal, |
653 | InitLoc, EqualLoc, EqualLoc); |
654 | } |
655 | |
656 | /// Create a default initialization. |
657 | static InitializationKind CreateDefault(SourceLocation InitLoc) { |
658 | return InitializationKind(IK_Default, IC_Normal, InitLoc, InitLoc, InitLoc); |
659 | } |
660 | |
661 | /// Create a value initialization. |
662 | static InitializationKind CreateValue(SourceLocation InitLoc, |
663 | SourceLocation LParenLoc, |
664 | SourceLocation RParenLoc, |
665 | bool isImplicit = false) { |
666 | return InitializationKind(IK_Value, isImplicit ? IC_Implicit : IC_Normal, |
667 | InitLoc, LParenLoc, RParenLoc); |
668 | } |
669 | |
670 | /// Create an initialization from an initializer (which, for direct |
671 | /// initialization from a parenthesized list, will be a ParenListExpr). |
672 | static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit, |
673 | Expr *Init) { |
674 | if (!Init) return CreateDefault(Loc); |
675 | if (!DirectInit) |
676 | return CreateCopy(Loc, Init->getBeginLoc()); |
677 | if (isa<InitListExpr>(Init)) |
678 | return CreateDirectList(Loc, Init->getBeginLoc(), Init->getEndLoc()); |
679 | return CreateDirect(Loc, Init->getBeginLoc(), Init->getEndLoc()); |
680 | } |
681 | |
682 | /// Determine the initialization kind. |
683 | InitKind getKind() const { |
684 | return Kind; |
685 | } |
686 | |
687 | /// Determine whether this initialization is an explicit cast. |
688 | bool isExplicitCast() const { |
689 | return Context >= IC_StaticCast; |
690 | } |
691 | |
692 | /// Determine whether this initialization is a C-style cast. |
693 | bool isCStyleOrFunctionalCast() const { |
694 | return Context >= IC_CStyleCast; |
695 | } |
696 | |
697 | /// Determine whether this is a C-style cast. |
698 | bool isCStyleCast() const { |
699 | return Context == IC_CStyleCast; |
700 | } |
701 | |
702 | /// Determine whether this is a functional-style cast. |
703 | bool isFunctionalCast() const { |
704 | return Context == IC_FunctionalCast; |
705 | } |
706 | |
707 | /// Determine whether this initialization is an implicit |
708 | /// value-initialization, e.g., as occurs during aggregate |
709 | /// initialization. |
710 | bool isImplicitValueInit() const { return Context == IC_Implicit; } |
711 | |
712 | /// Retrieve the location at which initialization is occurring. |
713 | SourceLocation getLocation() const { return Locations[0]; } |
714 | |
715 | /// Retrieve the source range that covers the initialization. |
716 | SourceRange getRange() const { |
717 | return SourceRange(Locations[0], Locations[2]); |
718 | } |
719 | |
720 | /// Retrieve the location of the equal sign for copy initialization |
721 | /// (if present). |
722 | SourceLocation getEqualLoc() const { |
723 | assert(Kind == IK_Copy && "Only copy initialization has an '='")((Kind == IK_Copy && "Only copy initialization has an '='" ) ? static_cast<void> (0) : __assert_fail ("Kind == IK_Copy && \"Only copy initialization has an '='\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/include/clang/Sema/Initialization.h" , 723, __PRETTY_FUNCTION__)); |
724 | return Locations[1]; |
725 | } |
726 | |
727 | bool isCopyInit() const { return Kind == IK_Copy; } |
728 | |
729 | /// Retrieve whether this initialization allows the use of explicit |
730 | /// constructors. |
731 | bool AllowExplicit() const { return !isCopyInit(); } |
732 | |
733 | /// Retrieve whether this initialization allows the use of explicit |
734 | /// conversion functions when binding a reference. If the reference is the |
735 | /// first parameter in a copy or move constructor, such conversions are |
736 | /// permitted even though we are performing copy-initialization. |
737 | bool allowExplicitConversionFunctionsInRefBinding() const { |
738 | return !isCopyInit() || Context == IC_ExplicitConvs; |
739 | } |
740 | |
741 | /// Determine whether this initialization has a source range containing the |
742 | /// locations of open and closing parentheses or braces. |
743 | bool hasParenOrBraceRange() const { |
744 | return Kind == IK_Direct || Kind == IK_Value || Kind == IK_DirectList; |
745 | } |
746 | |
747 | /// Retrieve the source range containing the locations of the open |
748 | /// and closing parentheses or braces for value, direct, and direct list |
749 | /// initializations. |
750 | SourceRange getParenOrBraceRange() const { |
751 | assert(hasParenOrBraceRange() && "Only direct, value, and direct-list "((hasParenOrBraceRange() && "Only direct, value, and direct-list " "initialization have parentheses or " "braces") ? static_cast <void> (0) : __assert_fail ("hasParenOrBraceRange() && \"Only direct, value, and direct-list \" \"initialization have parentheses or \" \"braces\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/include/clang/Sema/Initialization.h" , 753, __PRETTY_FUNCTION__)) |
752 | "initialization have parentheses or "((hasParenOrBraceRange() && "Only direct, value, and direct-list " "initialization have parentheses or " "braces") ? static_cast <void> (0) : __assert_fail ("hasParenOrBraceRange() && \"Only direct, value, and direct-list \" \"initialization have parentheses or \" \"braces\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/include/clang/Sema/Initialization.h" , 753, __PRETTY_FUNCTION__)) |
753 | "braces")((hasParenOrBraceRange() && "Only direct, value, and direct-list " "initialization have parentheses or " "braces") ? static_cast <void> (0) : __assert_fail ("hasParenOrBraceRange() && \"Only direct, value, and direct-list \" \"initialization have parentheses or \" \"braces\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/include/clang/Sema/Initialization.h" , 753, __PRETTY_FUNCTION__)); |
754 | return SourceRange(Locations[1], Locations[2]); |
755 | } |
756 | }; |
757 | |
758 | /// Describes the sequence of initializations required to initialize |
759 | /// a given object or reference with a set of arguments. |
760 | class InitializationSequence { |
761 | public: |
762 | /// Describes the kind of initialization sequence computed. |
763 | enum SequenceKind { |
764 | /// A failed initialization sequence. The failure kind tells what |
765 | /// happened. |
766 | FailedSequence = 0, |
767 | |
768 | /// A dependent initialization, which could not be |
769 | /// type-checked due to the presence of dependent types or |
770 | /// dependently-typed expressions. |
771 | DependentSequence, |
772 | |
773 | /// A normal sequence. |
774 | NormalSequence |
775 | }; |
776 | |
777 | /// Describes the kind of a particular step in an initialization |
778 | /// sequence. |
779 | enum StepKind { |
780 | /// Resolve the address of an overloaded function to a specific |
781 | /// function declaration. |
782 | SK_ResolveAddressOfOverloadedFunction, |
783 | |
784 | /// Perform a derived-to-base cast, producing an rvalue. |
785 | SK_CastDerivedToBaseRValue, |
786 | |
787 | /// Perform a derived-to-base cast, producing an xvalue. |
788 | SK_CastDerivedToBaseXValue, |
789 | |
790 | /// Perform a derived-to-base cast, producing an lvalue. |
791 | SK_CastDerivedToBaseLValue, |
792 | |
793 | /// Reference binding to an lvalue. |
794 | SK_BindReference, |
795 | |
796 | /// Reference binding to a temporary. |
797 | SK_BindReferenceToTemporary, |
798 | |
799 | /// An optional copy of a temporary object to another |
800 | /// temporary object, which is permitted (but not required) by |
801 | /// C++98/03 but not C++0x. |
802 | SK_ExtraneousCopyToTemporary, |
803 | |
804 | /// Direct-initialization from a reference-related object in the |
805 | /// final stage of class copy-initialization. |
806 | SK_FinalCopy, |
807 | |
808 | /// Perform a user-defined conversion, either via a conversion |
809 | /// function or via a constructor. |
810 | SK_UserConversion, |
811 | |
812 | /// Perform a qualification conversion, producing an rvalue. |
813 | SK_QualificationConversionRValue, |
814 | |
815 | /// Perform a qualification conversion, producing an xvalue. |
816 | SK_QualificationConversionXValue, |
817 | |
818 | /// Perform a qualification conversion, producing an lvalue. |
819 | SK_QualificationConversionLValue, |
820 | |
821 | /// Perform a conversion adding _Atomic to a type. |
822 | SK_AtomicConversion, |
823 | |
824 | /// Perform an implicit conversion sequence. |
825 | SK_ConversionSequence, |
826 | |
827 | /// Perform an implicit conversion sequence without narrowing. |
828 | SK_ConversionSequenceNoNarrowing, |
829 | |
830 | /// Perform list-initialization without a constructor. |
831 | SK_ListInitialization, |
832 | |
833 | /// Unwrap the single-element initializer list for a reference. |
834 | SK_UnwrapInitList, |
835 | |
836 | /// Rewrap the single-element initializer list for a reference. |
837 | SK_RewrapInitList, |
838 | |
839 | /// Perform initialization via a constructor. |
840 | SK_ConstructorInitialization, |
841 | |
842 | /// Perform initialization via a constructor, taking arguments from |
843 | /// a single InitListExpr. |
844 | SK_ConstructorInitializationFromList, |
845 | |
846 | /// Zero-initialize the object |
847 | SK_ZeroInitialization, |
848 | |
849 | /// C assignment |
850 | SK_CAssignment, |
851 | |
852 | /// Initialization by string |
853 | SK_StringInit, |
854 | |
855 | /// An initialization that "converts" an Objective-C object |
856 | /// (not a point to an object) to another Objective-C object type. |
857 | SK_ObjCObjectConversion, |
858 | |
859 | /// Array indexing for initialization by elementwise copy. |
860 | SK_ArrayLoopIndex, |
861 | |
862 | /// Array initialization by elementwise copy. |
863 | SK_ArrayLoopInit, |
864 | |
865 | /// Array initialization (from an array rvalue). |
866 | SK_ArrayInit, |
867 | |
868 | /// Array initialization (from an array rvalue) as a GNU extension. |
869 | SK_GNUArrayInit, |
870 | |
871 | /// Array initialization from a parenthesized initializer list. |
872 | /// This is a GNU C++ extension. |
873 | SK_ParenthesizedArrayInit, |
874 | |
875 | /// Pass an object by indirect copy-and-restore. |
876 | SK_PassByIndirectCopyRestore, |
877 | |
878 | /// Pass an object by indirect restore. |
879 | SK_PassByIndirectRestore, |
880 | |
881 | /// Produce an Objective-C object pointer. |
882 | SK_ProduceObjCObject, |
883 | |
884 | /// Construct a std::initializer_list from an initializer list. |
885 | SK_StdInitializerList, |
886 | |
887 | /// Perform initialization via a constructor taking a single |
888 | /// std::initializer_list argument. |
889 | SK_StdInitializerListConstructorCall, |
890 | |
891 | /// Initialize an OpenCL sampler from an integer. |
892 | SK_OCLSamplerInit, |
893 | |
894 | /// Initialize an opaque OpenCL type (event_t, queue_t, etc.) with zero |
895 | SK_OCLZeroOpaqueType |
896 | }; |
897 | |
898 | /// A single step in the initialization sequence. |
899 | class Step { |
900 | public: |
901 | /// The kind of conversion or initialization step we are taking. |
902 | StepKind Kind; |
903 | |
904 | // The type that results from this initialization. |
905 | QualType Type; |
906 | |
907 | struct F { |
908 | bool HadMultipleCandidates; |
909 | FunctionDecl *Function; |
910 | DeclAccessPair FoundDecl; |
911 | }; |
912 | |
913 | union { |
914 | /// When Kind == SK_ResolvedOverloadedFunction or Kind == |
915 | /// SK_UserConversion, the function that the expression should be |
916 | /// resolved to or the conversion function to call, respectively. |
917 | /// When Kind == SK_ConstructorInitialization or SK_ListConstruction, |
918 | /// the constructor to be called. |
919 | /// |
920 | /// Always a FunctionDecl, plus a Boolean flag telling if it was |
921 | /// selected from an overloaded set having size greater than 1. |
922 | /// For conversion decls, the naming class is the source type. |
923 | /// For construct decls, the naming class is the target type. |
924 | struct F Function; |
925 | |
926 | /// When Kind = SK_ConversionSequence, the implicit conversion |
927 | /// sequence. |
928 | ImplicitConversionSequence *ICS; |
929 | |
930 | /// When Kind = SK_RewrapInitList, the syntactic form of the |
931 | /// wrapping list. |
932 | InitListExpr *WrappingSyntacticList; |
933 | }; |
934 | |
935 | void Destroy(); |
936 | }; |
937 | |
938 | private: |
939 | /// The kind of initialization sequence computed. |
940 | enum SequenceKind SequenceKind; |
941 | |
942 | /// Steps taken by this initialization. |
943 | SmallVector<Step, 4> Steps; |
944 | |
945 | public: |
946 | /// Describes why initialization failed. |
947 | enum FailureKind { |
948 | /// Too many initializers provided for a reference. |
949 | FK_TooManyInitsForReference, |
950 | |
951 | /// Reference initialized from a parenthesized initializer list. |
952 | FK_ParenthesizedListInitForReference, |
953 | |
954 | /// Array must be initialized with an initializer list. |
955 | FK_ArrayNeedsInitList, |
956 | |
957 | /// Array must be initialized with an initializer list or a |
958 | /// string literal. |
959 | FK_ArrayNeedsInitListOrStringLiteral, |
960 | |
961 | /// Array must be initialized with an initializer list or a |
962 | /// wide string literal. |
963 | FK_ArrayNeedsInitListOrWideStringLiteral, |
964 | |
965 | /// Initializing a wide char array with narrow string literal. |
966 | FK_NarrowStringIntoWideCharArray, |
967 | |
968 | /// Initializing char array with wide string literal. |
969 | FK_WideStringIntoCharArray, |
970 | |
971 | /// Initializing wide char array with incompatible wide string |
972 | /// literal. |
973 | FK_IncompatWideStringIntoWideChar, |
974 | |
975 | /// Initializing char8_t array with plain string literal. |
976 | FK_PlainStringIntoUTF8Char, |
977 | |
978 | /// Initializing char array with UTF-8 string literal. |
979 | FK_UTF8StringIntoPlainChar, |
980 | |
981 | /// Array type mismatch. |
982 | FK_ArrayTypeMismatch, |
983 | |
984 | /// Non-constant array initializer |
985 | FK_NonConstantArrayInit, |
986 | |
987 | /// Cannot resolve the address of an overloaded function. |
988 | FK_AddressOfOverloadFailed, |
989 | |
990 | /// Overloading due to reference initialization failed. |
991 | FK_ReferenceInitOverloadFailed, |
992 | |
993 | /// Non-const lvalue reference binding to a temporary. |
994 | FK_NonConstLValueReferenceBindingToTemporary, |
995 | |
996 | /// Non-const lvalue reference binding to a bit-field. |
997 | FK_NonConstLValueReferenceBindingToBitfield, |
998 | |
999 | /// Non-const lvalue reference binding to a vector element. |
1000 | FK_NonConstLValueReferenceBindingToVectorElement, |
1001 | |
1002 | /// Non-const lvalue reference binding to an lvalue of unrelated |
1003 | /// type. |
1004 | FK_NonConstLValueReferenceBindingToUnrelated, |
1005 | |
1006 | /// Rvalue reference binding to an lvalue. |
1007 | FK_RValueReferenceBindingToLValue, |
1008 | |
1009 | /// Reference binding drops qualifiers. |
1010 | FK_ReferenceInitDropsQualifiers, |
1011 | |
1012 | /// Reference with mismatching address space binding to temporary. |
1013 | FK_ReferenceAddrspaceMismatchTemporary, |
1014 | |
1015 | /// Reference binding failed. |
1016 | FK_ReferenceInitFailed, |
1017 | |
1018 | /// Implicit conversion failed. |
1019 | FK_ConversionFailed, |
1020 | |
1021 | /// Implicit conversion failed. |
1022 | FK_ConversionFromPropertyFailed, |
1023 | |
1024 | /// Too many initializers for scalar |
1025 | FK_TooManyInitsForScalar, |
1026 | |
1027 | /// Scalar initialized from a parenthesized initializer list. |
1028 | FK_ParenthesizedListInitForScalar, |
1029 | |
1030 | /// Reference initialization from an initializer list |
1031 | FK_ReferenceBindingToInitList, |
1032 | |
1033 | /// Initialization of some unused destination type with an |
1034 | /// initializer list. |
1035 | FK_InitListBadDestinationType, |
1036 | |
1037 | /// Overloading for a user-defined conversion failed. |
1038 | FK_UserConversionOverloadFailed, |
1039 | |
1040 | /// Overloading for initialization by constructor failed. |
1041 | FK_ConstructorOverloadFailed, |
1042 | |
1043 | /// Overloading for list-initialization by constructor failed. |
1044 | FK_ListConstructorOverloadFailed, |
1045 | |
1046 | /// Default-initialization of a 'const' object. |
1047 | FK_DefaultInitOfConst, |
1048 | |
1049 | /// Initialization of an incomplete type. |
1050 | FK_Incomplete, |
1051 | |
1052 | /// Variable-length array must not have an initializer. |
1053 | FK_VariableLengthArrayHasInitializer, |
1054 | |
1055 | /// List initialization failed at some point. |
1056 | FK_ListInitializationFailed, |
1057 | |
1058 | /// Initializer has a placeholder type which cannot be |
1059 | /// resolved by initialization. |
1060 | FK_PlaceholderType, |
1061 | |
1062 | /// Trying to take the address of a function that doesn't support |
1063 | /// having its address taken. |
1064 | FK_AddressOfUnaddressableFunction, |
1065 | |
1066 | /// List-copy-initialization chose an explicit constructor. |
1067 | FK_ExplicitConstructor, |
1068 | }; |
1069 | |
1070 | private: |
1071 | /// The reason why initialization failed. |
1072 | FailureKind Failure; |
1073 | |
1074 | /// The failed result of overload resolution. |
1075 | OverloadingResult FailedOverloadResult; |
1076 | |
1077 | /// The candidate set created when initialization failed. |
1078 | OverloadCandidateSet FailedCandidateSet; |
1079 | |
1080 | /// The incomplete type that caused a failure. |
1081 | QualType FailedIncompleteType; |
1082 | |
1083 | /// The fixit that needs to be applied to make this initialization |
1084 | /// succeed. |
1085 | std::string ZeroInitializationFixit; |
1086 | SourceLocation ZeroInitializationFixitLoc; |
1087 | |
1088 | public: |
1089 | /// Call for initializations are invalid but that would be valid |
1090 | /// zero initialzations if Fixit was applied. |
1091 | void SetZeroInitializationFixit(const std::string& Fixit, SourceLocation L) { |
1092 | ZeroInitializationFixit = Fixit; |
1093 | ZeroInitializationFixitLoc = L; |
1094 | } |
1095 | |
1096 | private: |
1097 | /// Prints a follow-up note that highlights the location of |
1098 | /// the initialized entity, if it's remote. |
1099 | void PrintInitLocationNote(Sema &S, const InitializedEntity &Entity); |
1100 | |
1101 | public: |
1102 | /// Try to perform initialization of the given entity, creating a |
1103 | /// record of the steps required to perform the initialization. |
1104 | /// |
1105 | /// The generated initialization sequence will either contain enough |
1106 | /// information to diagnose |
1107 | /// |
1108 | /// \param S the semantic analysis object. |
1109 | /// |
1110 | /// \param Entity the entity being initialized. |
1111 | /// |
1112 | /// \param Kind the kind of initialization being performed. |
1113 | /// |
1114 | /// \param Args the argument(s) provided for initialization. |
1115 | /// |
1116 | /// \param TopLevelOfInitList true if we are initializing from an expression |
1117 | /// at the top level inside an initializer list. This disallows |
1118 | /// narrowing conversions in C++11 onwards. |
1119 | /// \param TreatUnavailableAsInvalid true if we want to treat unavailable |
1120 | /// as invalid. |
1121 | InitializationSequence(Sema &S, |
1122 | const InitializedEntity &Entity, |
1123 | const InitializationKind &Kind, |
1124 | MultiExprArg Args, |
1125 | bool TopLevelOfInitList = false, |
1126 | bool TreatUnavailableAsInvalid = true); |
1127 | void InitializeFrom(Sema &S, const InitializedEntity &Entity, |
1128 | const InitializationKind &Kind, MultiExprArg Args, |
1129 | bool TopLevelOfInitList, bool TreatUnavailableAsInvalid); |
1130 | |
1131 | ~InitializationSequence(); |
1132 | |
1133 | /// Perform the actual initialization of the given entity based on |
1134 | /// the computed initialization sequence. |
1135 | /// |
1136 | /// \param S the semantic analysis object. |
1137 | /// |
1138 | /// \param Entity the entity being initialized. |
1139 | /// |
1140 | /// \param Kind the kind of initialization being performed. |
1141 | /// |
1142 | /// \param Args the argument(s) provided for initialization, ownership of |
1143 | /// which is transferred into the routine. |
1144 | /// |
1145 | /// \param ResultType if non-NULL, will be set to the type of the |
1146 | /// initialized object, which is the type of the declaration in most |
1147 | /// cases. However, when the initialized object is a variable of |
1148 | /// incomplete array type and the initializer is an initializer |
1149 | /// list, this type will be set to the completed array type. |
1150 | /// |
1151 | /// \returns an expression that performs the actual object initialization, if |
1152 | /// the initialization is well-formed. Otherwise, emits diagnostics |
1153 | /// and returns an invalid expression. |
1154 | ExprResult Perform(Sema &S, |
1155 | const InitializedEntity &Entity, |
1156 | const InitializationKind &Kind, |
1157 | MultiExprArg Args, |
1158 | QualType *ResultType = nullptr); |
1159 | |
1160 | /// Diagnose an potentially-invalid initialization sequence. |
1161 | /// |
1162 | /// \returns true if the initialization sequence was ill-formed, |
1163 | /// false otherwise. |
1164 | bool Diagnose(Sema &S, |
1165 | const InitializedEntity &Entity, |
1166 | const InitializationKind &Kind, |
1167 | ArrayRef<Expr *> Args); |
1168 | |
1169 | /// Determine the kind of initialization sequence computed. |
1170 | enum SequenceKind getKind() const { return SequenceKind; } |
1171 | |
1172 | /// Set the kind of sequence computed. |
1173 | void setSequenceKind(enum SequenceKind SK) { SequenceKind = SK; } |
1174 | |
1175 | /// Determine whether the initialization sequence is valid. |
1176 | explicit operator bool() const { return !Failed(); } |
1177 | |
1178 | /// Determine whether the initialization sequence is invalid. |
1179 | bool Failed() const { return SequenceKind == FailedSequence; } |
1180 | |
1181 | using step_iterator = SmallVectorImpl<Step>::const_iterator; |
1182 | |
1183 | step_iterator step_begin() const { return Steps.begin(); } |
1184 | step_iterator step_end() const { return Steps.end(); } |
1185 | |
1186 | using step_range = llvm::iterator_range<step_iterator>; |
1187 | |
1188 | step_range steps() const { return {step_begin(), step_end()}; } |
1189 | |
1190 | /// Determine whether this initialization is a direct reference |
1191 | /// binding (C++ [dcl.init.ref]). |
1192 | bool isDirectReferenceBinding() const; |
1193 | |
1194 | /// Determine whether this initialization failed due to an ambiguity. |
1195 | bool isAmbiguous() const; |
1196 | |
1197 | /// Determine whether this initialization is direct call to a |
1198 | /// constructor. |
1199 | bool isConstructorInitialization() const; |
1200 | |
1201 | /// Returns whether the last step in this initialization sequence is a |
1202 | /// narrowing conversion, defined by C++0x [dcl.init.list]p7. |
1203 | /// |
1204 | /// If this function returns true, *isInitializerConstant will be set to |
1205 | /// describe whether *Initializer was a constant expression. If |
1206 | /// *isInitializerConstant is set to true, *ConstantValue will be set to the |
1207 | /// evaluated value of *Initializer. |
1208 | bool endsWithNarrowing(ASTContext &Ctx, const Expr *Initializer, |
1209 | bool *isInitializerConstant, |
1210 | APValue *ConstantValue) const; |
1211 | |
1212 | /// Add a new step in the initialization that resolves the address |
1213 | /// of an overloaded function to a specific function declaration. |
1214 | /// |
1215 | /// \param Function the function to which the overloaded function reference |
1216 | /// resolves. |
1217 | void AddAddressOverloadResolutionStep(FunctionDecl *Function, |
1218 | DeclAccessPair Found, |
1219 | bool HadMultipleCandidates); |
1220 | |
1221 | /// Add a new step in the initialization that performs a derived-to- |
1222 | /// base cast. |
1223 | /// |
1224 | /// \param BaseType the base type to which we will be casting. |
1225 | /// |
1226 | /// \param Category Indicates whether the result will be treated as an |
1227 | /// rvalue, an xvalue, or an lvalue. |
1228 | void AddDerivedToBaseCastStep(QualType BaseType, |
1229 | ExprValueKind Category); |
1230 | |
1231 | /// Add a new step binding a reference to an object. |
1232 | /// |
1233 | /// \param BindingTemporary True if we are binding a reference to a temporary |
1234 | /// object (thereby extending its lifetime); false if we are binding to an |
1235 | /// lvalue or an lvalue treated as an rvalue. |
1236 | void AddReferenceBindingStep(QualType T, bool BindingTemporary); |
1237 | |
1238 | /// Add a new step that makes an extraneous copy of the input |
1239 | /// to a temporary of the same class type. |
1240 | /// |
1241 | /// This extraneous copy only occurs during reference binding in |
1242 | /// C++98/03, where we are permitted (but not required) to introduce |
1243 | /// an extra copy. At a bare minimum, we must check that we could |
1244 | /// call the copy constructor, and produce a diagnostic if the copy |
1245 | /// constructor is inaccessible or no copy constructor matches. |
1246 | // |
1247 | /// \param T The type of the temporary being created. |
1248 | void AddExtraneousCopyToTemporary(QualType T); |
1249 | |
1250 | /// Add a new step that makes a copy of the input to an object of |
1251 | /// the given type, as the final step in class copy-initialization. |
1252 | void AddFinalCopy(QualType T); |
1253 | |
1254 | /// Add a new step invoking a conversion function, which is either |
1255 | /// a constructor or a conversion function. |
1256 | void AddUserConversionStep(FunctionDecl *Function, |
1257 | DeclAccessPair FoundDecl, |
1258 | QualType T, |
1259 | bool HadMultipleCandidates); |
1260 | |
1261 | /// Add a new step that performs a qualification conversion to the |
1262 | /// given type. |
1263 | void AddQualificationConversionStep(QualType Ty, |
1264 | ExprValueKind Category); |
1265 | |
1266 | /// Add a new step that performs conversion from non-atomic to atomic |
1267 | /// type. |
1268 | void AddAtomicConversionStep(QualType Ty); |
1269 | |
1270 | /// Add a new step that applies an implicit conversion sequence. |
1271 | void AddConversionSequenceStep(const ImplicitConversionSequence &ICS, |
1272 | QualType T, bool TopLevelOfInitList = false); |
1273 | |
1274 | /// Add a list-initialization step. |
1275 | void AddListInitializationStep(QualType T); |
1276 | |
1277 | /// Add a constructor-initialization step. |
1278 | /// |
1279 | /// \param FromInitList The constructor call is syntactically an initializer |
1280 | /// list. |
1281 | /// \param AsInitList The constructor is called as an init list constructor. |
1282 | void AddConstructorInitializationStep(DeclAccessPair FoundDecl, |
1283 | CXXConstructorDecl *Constructor, |
1284 | QualType T, |
1285 | bool HadMultipleCandidates, |
1286 | bool FromInitList, bool AsInitList); |
1287 | |
1288 | /// Add a zero-initialization step. |
1289 | void AddZeroInitializationStep(QualType T); |
1290 | |
1291 | /// Add a C assignment step. |
1292 | // |
1293 | // FIXME: It isn't clear whether this should ever be needed; |
1294 | // ideally, we would handle everything needed in C in the common |
1295 | // path. However, that isn't the case yet. |
1296 | void AddCAssignmentStep(QualType T); |
1297 | |
1298 | /// Add a string init step. |
1299 | void AddStringInitStep(QualType T); |
1300 | |
1301 | /// Add an Objective-C object conversion step, which is |
1302 | /// always a no-op. |
1303 | void AddObjCObjectConversionStep(QualType T); |
1304 | |
1305 | /// Add an array initialization loop step. |
1306 | void AddArrayInitLoopStep(QualType T, QualType EltTy); |
1307 | |
1308 | /// Add an array initialization step. |
1309 | void AddArrayInitStep(QualType T, bool IsGNUExtension); |
1310 | |
1311 | /// Add a parenthesized array initialization step. |
1312 | void AddParenthesizedArrayInitStep(QualType T); |
1313 | |
1314 | /// Add a step to pass an object by indirect copy-restore. |
1315 | void AddPassByIndirectCopyRestoreStep(QualType T, bool shouldCopy); |
1316 | |
1317 | /// Add a step to "produce" an Objective-C object (by |
1318 | /// retaining it). |
1319 | void AddProduceObjCObjectStep(QualType T); |
1320 | |
1321 | /// Add a step to construct a std::initializer_list object from an |
1322 | /// initializer list. |
1323 | void AddStdInitializerListConstructionStep(QualType T); |
1324 | |
1325 | /// Add a step to initialize an OpenCL sampler from an integer |
1326 | /// constant. |
1327 | void AddOCLSamplerInitStep(QualType T); |
1328 | |
1329 | /// Add a step to initialzie an OpenCL opaque type (event_t, queue_t, etc.) |
1330 | /// from a zero constant. |
1331 | void AddOCLZeroOpaqueTypeStep(QualType T); |
1332 | |
1333 | /// Add a step to initialize by zero types defined in the |
1334 | /// cl_intel_device_side_avc_motion_estimation OpenCL extension |
1335 | void AddOCLIntelSubgroupAVCZeroInitStep(QualType T); |
1336 | |
1337 | /// Add steps to unwrap a initializer list for a reference around a |
1338 | /// single element and rewrap it at the end. |
1339 | void RewrapReferenceInitList(QualType T, InitListExpr *Syntactic); |
1340 | |
1341 | /// Note that this initialization sequence failed. |
1342 | void SetFailed(FailureKind Failure) { |
1343 | SequenceKind = FailedSequence; |
1344 | this->Failure = Failure; |
1345 | assert((Failure != FK_Incomplete || !FailedIncompleteType.isNull()) &&(((Failure != FK_Incomplete || !FailedIncompleteType.isNull() ) && "Incomplete type failure requires a type!") ? static_cast <void> (0) : __assert_fail ("(Failure != FK_Incomplete || !FailedIncompleteType.isNull()) && \"Incomplete type failure requires a type!\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/include/clang/Sema/Initialization.h" , 1346, __PRETTY_FUNCTION__)) |
1346 | "Incomplete type failure requires a type!")(((Failure != FK_Incomplete || !FailedIncompleteType.isNull() ) && "Incomplete type failure requires a type!") ? static_cast <void> (0) : __assert_fail ("(Failure != FK_Incomplete || !FailedIncompleteType.isNull()) && \"Incomplete type failure requires a type!\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/include/clang/Sema/Initialization.h" , 1346, __PRETTY_FUNCTION__)); |
1347 | } |
1348 | |
1349 | /// Note that this initialization sequence failed due to failed |
1350 | /// overload resolution. |
1351 | void SetOverloadFailure(FailureKind Failure, OverloadingResult Result); |
1352 | |
1353 | /// Retrieve a reference to the candidate set when overload |
1354 | /// resolution fails. |
1355 | OverloadCandidateSet &getFailedCandidateSet() { |
1356 | return FailedCandidateSet; |
1357 | } |
1358 | |
1359 | /// Get the overloading result, for when the initialization |
1360 | /// sequence failed due to a bad overload. |
1361 | OverloadingResult getFailedOverloadResult() const { |
1362 | return FailedOverloadResult; |
1363 | } |
1364 | |
1365 | /// Note that this initialization sequence failed due to an |
1366 | /// incomplete type. |
1367 | void setIncompleteTypeFailure(QualType IncompleteType) { |
1368 | FailedIncompleteType = IncompleteType; |
1369 | SetFailed(FK_Incomplete); |
1370 | } |
1371 | |
1372 | /// Determine why initialization failed. |
1373 | FailureKind getFailureKind() const { |
1374 | assert(Failed() && "Not an initialization failure!")((Failed() && "Not an initialization failure!") ? static_cast <void> (0) : __assert_fail ("Failed() && \"Not an initialization failure!\"" , "/build/llvm-toolchain-snapshot-10~++20200109111124+f0abe820eeb/clang/include/clang/Sema/Initialization.h" , 1374, __PRETTY_FUNCTION__)); |
1375 | return Failure; |
1376 | } |
1377 | |
1378 | /// Dump a representation of this initialization sequence to |
1379 | /// the given stream, for debugging purposes. |
1380 | void dump(raw_ostream &OS) const; |
1381 | |
1382 | /// Dump a representation of this initialization sequence to |
1383 | /// standard error, for debugging purposes. |
1384 | void dump() const; |
1385 | }; |
1386 | |
1387 | } // namespace clang |
1388 | |
1389 | #endif // LLVM_CLANG_SEMA_INITIALIZATION_H |