File: | clang/lib/Sema/SemaExprCXX.cpp |
Warning: | line 600, column 7 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===// | |||
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 | /// \file | |||
10 | /// Implements semantic analysis for C++ expressions. | |||
11 | /// | |||
12 | //===----------------------------------------------------------------------===// | |||
13 | ||||
14 | #include "clang/Sema/Template.h" | |||
15 | #include "clang/Sema/SemaInternal.h" | |||
16 | #include "TreeTransform.h" | |||
17 | #include "TypeLocBuilder.h" | |||
18 | #include "clang/AST/ASTContext.h" | |||
19 | #include "clang/AST/ASTLambda.h" | |||
20 | #include "clang/AST/CXXInheritance.h" | |||
21 | #include "clang/AST/CharUnits.h" | |||
22 | #include "clang/AST/DeclObjC.h" | |||
23 | #include "clang/AST/ExprCXX.h" | |||
24 | #include "clang/AST/ExprObjC.h" | |||
25 | #include "clang/AST/RecursiveASTVisitor.h" | |||
26 | #include "clang/AST/TypeLoc.h" | |||
27 | #include "clang/Basic/AlignedAllocation.h" | |||
28 | #include "clang/Basic/PartialDiagnostic.h" | |||
29 | #include "clang/Basic/TargetInfo.h" | |||
30 | #include "clang/Lex/Preprocessor.h" | |||
31 | #include "clang/Sema/DeclSpec.h" | |||
32 | #include "clang/Sema/Initialization.h" | |||
33 | #include "clang/Sema/Lookup.h" | |||
34 | #include "clang/Sema/ParsedTemplate.h" | |||
35 | #include "clang/Sema/Scope.h" | |||
36 | #include "clang/Sema/ScopeInfo.h" | |||
37 | #include "clang/Sema/SemaLambda.h" | |||
38 | #include "clang/Sema/TemplateDeduction.h" | |||
39 | #include "llvm/ADT/APInt.h" | |||
40 | #include "llvm/ADT/STLExtras.h" | |||
41 | #include "llvm/Support/ErrorHandling.h" | |||
42 | using namespace clang; | |||
43 | using namespace sema; | |||
44 | ||||
45 | /// Handle the result of the special case name lookup for inheriting | |||
46 | /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as | |||
47 | /// constructor names in member using declarations, even if 'X' is not the | |||
48 | /// name of the corresponding type. | |||
49 | ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS, | |||
50 | SourceLocation NameLoc, | |||
51 | IdentifierInfo &Name) { | |||
52 | NestedNameSpecifier *NNS = SS.getScopeRep(); | |||
53 | ||||
54 | // Convert the nested-name-specifier into a type. | |||
55 | QualType Type; | |||
56 | switch (NNS->getKind()) { | |||
57 | case NestedNameSpecifier::TypeSpec: | |||
58 | case NestedNameSpecifier::TypeSpecWithTemplate: | |||
59 | Type = QualType(NNS->getAsType(), 0); | |||
60 | break; | |||
61 | ||||
62 | case NestedNameSpecifier::Identifier: | |||
63 | // Strip off the last layer of the nested-name-specifier and build a | |||
64 | // typename type for it. | |||
65 | assert(NNS->getAsIdentifier() == &Name && "not a constructor name")(static_cast <bool> (NNS->getAsIdentifier() == & Name && "not a constructor name") ? void (0) : __assert_fail ("NNS->getAsIdentifier() == &Name && \"not a constructor name\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 65, __extension__ __PRETTY_FUNCTION__)); | |||
66 | Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(), | |||
67 | NNS->getAsIdentifier()); | |||
68 | break; | |||
69 | ||||
70 | case NestedNameSpecifier::Global: | |||
71 | case NestedNameSpecifier::Super: | |||
72 | case NestedNameSpecifier::Namespace: | |||
73 | case NestedNameSpecifier::NamespaceAlias: | |||
74 | llvm_unreachable("Nested name specifier is not a type for inheriting ctor")::llvm::llvm_unreachable_internal("Nested name specifier is not a type for inheriting ctor" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 74); | |||
75 | } | |||
76 | ||||
77 | // This reference to the type is located entirely at the location of the | |||
78 | // final identifier in the qualified-id. | |||
79 | return CreateParsedType(Type, | |||
80 | Context.getTrivialTypeSourceInfo(Type, NameLoc)); | |||
81 | } | |||
82 | ||||
83 | ParsedType Sema::getConstructorName(IdentifierInfo &II, | |||
84 | SourceLocation NameLoc, | |||
85 | Scope *S, CXXScopeSpec &SS, | |||
86 | bool EnteringContext) { | |||
87 | CXXRecordDecl *CurClass = getCurrentClass(S, &SS); | |||
88 | assert(CurClass && &II == CurClass->getIdentifier() &&(static_cast <bool> (CurClass && &II == CurClass ->getIdentifier() && "not a constructor name") ? void (0) : __assert_fail ("CurClass && &II == CurClass->getIdentifier() && \"not a constructor name\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 89, __extension__ __PRETTY_FUNCTION__)) | |||
89 | "not a constructor name")(static_cast <bool> (CurClass && &II == CurClass ->getIdentifier() && "not a constructor name") ? void (0) : __assert_fail ("CurClass && &II == CurClass->getIdentifier() && \"not a constructor name\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 89, __extension__ __PRETTY_FUNCTION__)); | |||
90 | ||||
91 | // When naming a constructor as a member of a dependent context (eg, in a | |||
92 | // friend declaration or an inherited constructor declaration), form an | |||
93 | // unresolved "typename" type. | |||
94 | if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) { | |||
95 | QualType T = Context.getDependentNameType(ETK_None, SS.getScopeRep(), &II); | |||
96 | return ParsedType::make(T); | |||
97 | } | |||
98 | ||||
99 | if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass)) | |||
100 | return ParsedType(); | |||
101 | ||||
102 | // Find the injected-class-name declaration. Note that we make no attempt to | |||
103 | // diagnose cases where the injected-class-name is shadowed: the only | |||
104 | // declaration that can validly shadow the injected-class-name is a | |||
105 | // non-static data member, and if the class contains both a non-static data | |||
106 | // member and a constructor then it is ill-formed (we check that in | |||
107 | // CheckCompletedCXXClass). | |||
108 | CXXRecordDecl *InjectedClassName = nullptr; | |||
109 | for (NamedDecl *ND : CurClass->lookup(&II)) { | |||
110 | auto *RD = dyn_cast<CXXRecordDecl>(ND); | |||
111 | if (RD && RD->isInjectedClassName()) { | |||
112 | InjectedClassName = RD; | |||
113 | break; | |||
114 | } | |||
115 | } | |||
116 | if (!InjectedClassName) { | |||
117 | if (!CurClass->isInvalidDecl()) { | |||
118 | // FIXME: RequireCompleteDeclContext doesn't check dependent contexts | |||
119 | // properly. Work around it here for now. | |||
120 | Diag(SS.getLastQualifierNameLoc(), | |||
121 | diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange(); | |||
122 | } | |||
123 | return ParsedType(); | |||
124 | } | |||
125 | ||||
126 | QualType T = Context.getTypeDeclType(InjectedClassName); | |||
127 | DiagnoseUseOfDecl(InjectedClassName, NameLoc); | |||
128 | MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false); | |||
129 | ||||
130 | return ParsedType::make(T); | |||
131 | } | |||
132 | ||||
133 | ParsedType Sema::getDestructorName(SourceLocation TildeLoc, | |||
134 | IdentifierInfo &II, | |||
135 | SourceLocation NameLoc, | |||
136 | Scope *S, CXXScopeSpec &SS, | |||
137 | ParsedType ObjectTypePtr, | |||
138 | bool EnteringContext) { | |||
139 | // Determine where to perform name lookup. | |||
140 | ||||
141 | // FIXME: This area of the standard is very messy, and the current | |||
142 | // wording is rather unclear about which scopes we search for the | |||
143 | // destructor name; see core issues 399 and 555. Issue 399 in | |||
144 | // particular shows where the current description of destructor name | |||
145 | // lookup is completely out of line with existing practice, e.g., | |||
146 | // this appears to be ill-formed: | |||
147 | // | |||
148 | // namespace N { | |||
149 | // template <typename T> struct S { | |||
150 | // ~S(); | |||
151 | // }; | |||
152 | // } | |||
153 | // | |||
154 | // void f(N::S<int>* s) { | |||
155 | // s->N::S<int>::~S(); | |||
156 | // } | |||
157 | // | |||
158 | // See also PR6358 and PR6359. | |||
159 | // | |||
160 | // For now, we accept all the cases in which the name given could plausibly | |||
161 | // be interpreted as a correct destructor name, issuing off-by-default | |||
162 | // extension diagnostics on the cases that don't strictly conform to the | |||
163 | // C++20 rules. This basically means we always consider looking in the | |||
164 | // nested-name-specifier prefix, the complete nested-name-specifier, and | |||
165 | // the scope, and accept if we find the expected type in any of the three | |||
166 | // places. | |||
167 | ||||
168 | if (SS.isInvalid()) | |||
169 | return nullptr; | |||
170 | ||||
171 | // Whether we've failed with a diagnostic already. | |||
172 | bool Failed = false; | |||
173 | ||||
174 | llvm::SmallVector<NamedDecl*, 8> FoundDecls; | |||
175 | llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 8> FoundDeclSet; | |||
176 | ||||
177 | // If we have an object type, it's because we are in a | |||
178 | // pseudo-destructor-expression or a member access expression, and | |||
179 | // we know what type we're looking for. | |||
180 | QualType SearchType = | |||
181 | ObjectTypePtr ? GetTypeFromParser(ObjectTypePtr) : QualType(); | |||
182 | ||||
183 | auto CheckLookupResult = [&](LookupResult &Found) -> ParsedType { | |||
184 | auto IsAcceptableResult = [&](NamedDecl *D) -> bool { | |||
185 | auto *Type = dyn_cast<TypeDecl>(D->getUnderlyingDecl()); | |||
186 | if (!Type) | |||
187 | return false; | |||
188 | ||||
189 | if (SearchType.isNull() || SearchType->isDependentType()) | |||
190 | return true; | |||
191 | ||||
192 | QualType T = Context.getTypeDeclType(Type); | |||
193 | return Context.hasSameUnqualifiedType(T, SearchType); | |||
194 | }; | |||
195 | ||||
196 | unsigned NumAcceptableResults = 0; | |||
197 | for (NamedDecl *D : Found) { | |||
198 | if (IsAcceptableResult(D)) | |||
199 | ++NumAcceptableResults; | |||
200 | ||||
201 | // Don't list a class twice in the lookup failure diagnostic if it's | |||
202 | // found by both its injected-class-name and by the name in the enclosing | |||
203 | // scope. | |||
204 | if (auto *RD = dyn_cast<CXXRecordDecl>(D)) | |||
205 | if (RD->isInjectedClassName()) | |||
206 | D = cast<NamedDecl>(RD->getParent()); | |||
207 | ||||
208 | if (FoundDeclSet.insert(D).second) | |||
209 | FoundDecls.push_back(D); | |||
210 | } | |||
211 | ||||
212 | // As an extension, attempt to "fix" an ambiguity by erasing all non-type | |||
213 | // results, and all non-matching results if we have a search type. It's not | |||
214 | // clear what the right behavior is if destructor lookup hits an ambiguity, | |||
215 | // but other compilers do generally accept at least some kinds of | |||
216 | // ambiguity. | |||
217 | if (Found.isAmbiguous() && NumAcceptableResults == 1) { | |||
218 | Diag(NameLoc, diag::ext_dtor_name_ambiguous); | |||
219 | LookupResult::Filter F = Found.makeFilter(); | |||
220 | while (F.hasNext()) { | |||
221 | NamedDecl *D = F.next(); | |||
222 | if (auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl())) | |||
223 | Diag(D->getLocation(), diag::note_destructor_type_here) | |||
224 | << Context.getTypeDeclType(TD); | |||
225 | else | |||
226 | Diag(D->getLocation(), diag::note_destructor_nontype_here); | |||
227 | ||||
228 | if (!IsAcceptableResult(D)) | |||
229 | F.erase(); | |||
230 | } | |||
231 | F.done(); | |||
232 | } | |||
233 | ||||
234 | if (Found.isAmbiguous()) | |||
235 | Failed = true; | |||
236 | ||||
237 | if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) { | |||
238 | if (IsAcceptableResult(Type)) { | |||
239 | QualType T = Context.getTypeDeclType(Type); | |||
240 | MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); | |||
241 | return CreateParsedType(T, | |||
242 | Context.getTrivialTypeSourceInfo(T, NameLoc)); | |||
243 | } | |||
244 | } | |||
245 | ||||
246 | return nullptr; | |||
247 | }; | |||
248 | ||||
249 | bool IsDependent = false; | |||
250 | ||||
251 | auto LookupInObjectType = [&]() -> ParsedType { | |||
252 | if (Failed || SearchType.isNull()) | |||
253 | return nullptr; | |||
254 | ||||
255 | IsDependent |= SearchType->isDependentType(); | |||
256 | ||||
257 | LookupResult Found(*this, &II, NameLoc, LookupDestructorName); | |||
258 | DeclContext *LookupCtx = computeDeclContext(SearchType); | |||
259 | if (!LookupCtx) | |||
260 | return nullptr; | |||
261 | LookupQualifiedName(Found, LookupCtx); | |||
262 | return CheckLookupResult(Found); | |||
263 | }; | |||
264 | ||||
265 | auto LookupInNestedNameSpec = [&](CXXScopeSpec &LookupSS) -> ParsedType { | |||
266 | if (Failed) | |||
267 | return nullptr; | |||
268 | ||||
269 | IsDependent |= isDependentScopeSpecifier(LookupSS); | |||
270 | DeclContext *LookupCtx = computeDeclContext(LookupSS, EnteringContext); | |||
271 | if (!LookupCtx) | |||
272 | return nullptr; | |||
273 | ||||
274 | LookupResult Found(*this, &II, NameLoc, LookupDestructorName); | |||
275 | if (RequireCompleteDeclContext(LookupSS, LookupCtx)) { | |||
276 | Failed = true; | |||
277 | return nullptr; | |||
278 | } | |||
279 | LookupQualifiedName(Found, LookupCtx); | |||
280 | return CheckLookupResult(Found); | |||
281 | }; | |||
282 | ||||
283 | auto LookupInScope = [&]() -> ParsedType { | |||
284 | if (Failed || !S) | |||
285 | return nullptr; | |||
286 | ||||
287 | LookupResult Found(*this, &II, NameLoc, LookupDestructorName); | |||
288 | LookupName(Found, S); | |||
289 | return CheckLookupResult(Found); | |||
290 | }; | |||
291 | ||||
292 | // C++2a [basic.lookup.qual]p6: | |||
293 | // In a qualified-id of the form | |||
294 | // | |||
295 | // nested-name-specifier[opt] type-name :: ~ type-name | |||
296 | // | |||
297 | // the second type-name is looked up in the same scope as the first. | |||
298 | // | |||
299 | // We interpret this as meaning that if you do a dual-scope lookup for the | |||
300 | // first name, you also do a dual-scope lookup for the second name, per | |||
301 | // C++ [basic.lookup.classref]p4: | |||
302 | // | |||
303 | // If the id-expression in a class member access is a qualified-id of the | |||
304 | // form | |||
305 | // | |||
306 | // class-name-or-namespace-name :: ... | |||
307 | // | |||
308 | // the class-name-or-namespace-name following the . or -> is first looked | |||
309 | // up in the class of the object expression and the name, if found, is used. | |||
310 | // Otherwise, it is looked up in the context of the entire | |||
311 | // postfix-expression. | |||
312 | // | |||
313 | // This looks in the same scopes as for an unqualified destructor name: | |||
314 | // | |||
315 | // C++ [basic.lookup.classref]p3: | |||
316 | // If the unqualified-id is ~ type-name, the type-name is looked up | |||
317 | // in the context of the entire postfix-expression. If the type T | |||
318 | // of the object expression is of a class type C, the type-name is | |||
319 | // also looked up in the scope of class C. At least one of the | |||
320 | // lookups shall find a name that refers to cv T. | |||
321 | // | |||
322 | // FIXME: The intent is unclear here. Should type-name::~type-name look in | |||
323 | // the scope anyway if it finds a non-matching name declared in the class? | |||
324 | // If both lookups succeed and find a dependent result, which result should | |||
325 | // we retain? (Same question for p->~type-name().) | |||
326 | ||||
327 | if (NestedNameSpecifier *Prefix = | |||
328 | SS.isSet() ? SS.getScopeRep()->getPrefix() : nullptr) { | |||
329 | // This is | |||
330 | // | |||
331 | // nested-name-specifier type-name :: ~ type-name | |||
332 | // | |||
333 | // Look for the second type-name in the nested-name-specifier. | |||
334 | CXXScopeSpec PrefixSS; | |||
335 | PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data())); | |||
336 | if (ParsedType T = LookupInNestedNameSpec(PrefixSS)) | |||
337 | return T; | |||
338 | } else { | |||
339 | // This is one of | |||
340 | // | |||
341 | // type-name :: ~ type-name | |||
342 | // ~ type-name | |||
343 | // | |||
344 | // Look in the scope and (if any) the object type. | |||
345 | if (ParsedType T = LookupInScope()) | |||
346 | return T; | |||
347 | if (ParsedType T = LookupInObjectType()) | |||
348 | return T; | |||
349 | } | |||
350 | ||||
351 | if (Failed) | |||
352 | return nullptr; | |||
353 | ||||
354 | if (IsDependent) { | |||
355 | // We didn't find our type, but that's OK: it's dependent anyway. | |||
356 | ||||
357 | // FIXME: What if we have no nested-name-specifier? | |||
358 | QualType T = CheckTypenameType(ETK_None, SourceLocation(), | |||
359 | SS.getWithLocInContext(Context), | |||
360 | II, NameLoc); | |||
361 | return ParsedType::make(T); | |||
362 | } | |||
363 | ||||
364 | // The remaining cases are all non-standard extensions imitating the behavior | |||
365 | // of various other compilers. | |||
366 | unsigned NumNonExtensionDecls = FoundDecls.size(); | |||
367 | ||||
368 | if (SS.isSet()) { | |||
369 | // For compatibility with older broken C++ rules and existing code, | |||
370 | // | |||
371 | // nested-name-specifier :: ~ type-name | |||
372 | // | |||
373 | // also looks for type-name within the nested-name-specifier. | |||
374 | if (ParsedType T = LookupInNestedNameSpec(SS)) { | |||
375 | Diag(SS.getEndLoc(), diag::ext_dtor_named_in_wrong_scope) | |||
376 | << SS.getRange() | |||
377 | << FixItHint::CreateInsertion(SS.getEndLoc(), | |||
378 | ("::" + II.getName()).str()); | |||
379 | return T; | |||
380 | } | |||
381 | ||||
382 | // For compatibility with other compilers and older versions of Clang, | |||
383 | // | |||
384 | // nested-name-specifier type-name :: ~ type-name | |||
385 | // | |||
386 | // also looks for type-name in the scope. Unfortunately, we can't | |||
387 | // reasonably apply this fallback for dependent nested-name-specifiers. | |||
388 | if (SS.getScopeRep()->getPrefix()) { | |||
389 | if (ParsedType T = LookupInScope()) { | |||
390 | Diag(SS.getEndLoc(), diag::ext_qualified_dtor_named_in_lexical_scope) | |||
391 | << FixItHint::CreateRemoval(SS.getRange()); | |||
392 | Diag(FoundDecls.back()->getLocation(), diag::note_destructor_type_here) | |||
393 | << GetTypeFromParser(T); | |||
394 | return T; | |||
395 | } | |||
396 | } | |||
397 | } | |||
398 | ||||
399 | // We didn't find anything matching; tell the user what we did find (if | |||
400 | // anything). | |||
401 | ||||
402 | // Don't tell the user about declarations we shouldn't have found. | |||
403 | FoundDecls.resize(NumNonExtensionDecls); | |||
404 | ||||
405 | // List types before non-types. | |||
406 | std::stable_sort(FoundDecls.begin(), FoundDecls.end(), | |||
407 | [](NamedDecl *A, NamedDecl *B) { | |||
408 | return isa<TypeDecl>(A->getUnderlyingDecl()) > | |||
409 | isa<TypeDecl>(B->getUnderlyingDecl()); | |||
410 | }); | |||
411 | ||||
412 | // Suggest a fixit to properly name the destroyed type. | |||
413 | auto MakeFixItHint = [&]{ | |||
414 | const CXXRecordDecl *Destroyed = nullptr; | |||
415 | // FIXME: If we have a scope specifier, suggest its last component? | |||
416 | if (!SearchType.isNull()) | |||
417 | Destroyed = SearchType->getAsCXXRecordDecl(); | |||
418 | else if (S) | |||
419 | Destroyed = dyn_cast_or_null<CXXRecordDecl>(S->getEntity()); | |||
420 | if (Destroyed) | |||
421 | return FixItHint::CreateReplacement(SourceRange(NameLoc), | |||
422 | Destroyed->getNameAsString()); | |||
423 | return FixItHint(); | |||
424 | }; | |||
425 | ||||
426 | if (FoundDecls.empty()) { | |||
427 | // FIXME: Attempt typo-correction? | |||
428 | Diag(NameLoc, diag::err_undeclared_destructor_name) | |||
429 | << &II << MakeFixItHint(); | |||
430 | } else if (!SearchType.isNull() && FoundDecls.size() == 1) { | |||
431 | if (auto *TD = dyn_cast<TypeDecl>(FoundDecls[0]->getUnderlyingDecl())) { | |||
432 | assert(!SearchType.isNull() &&(static_cast <bool> (!SearchType.isNull() && "should only reject a type result if we have a search type" ) ? void (0) : __assert_fail ("!SearchType.isNull() && \"should only reject a type result if we have a search type\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 433, __extension__ __PRETTY_FUNCTION__)) | |||
433 | "should only reject a type result if we have a search type")(static_cast <bool> (!SearchType.isNull() && "should only reject a type result if we have a search type" ) ? void (0) : __assert_fail ("!SearchType.isNull() && \"should only reject a type result if we have a search type\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 433, __extension__ __PRETTY_FUNCTION__)); | |||
434 | QualType T = Context.getTypeDeclType(TD); | |||
435 | Diag(NameLoc, diag::err_destructor_expr_type_mismatch) | |||
436 | << T << SearchType << MakeFixItHint(); | |||
437 | } else { | |||
438 | Diag(NameLoc, diag::err_destructor_expr_nontype) | |||
439 | << &II << MakeFixItHint(); | |||
440 | } | |||
441 | } else { | |||
442 | Diag(NameLoc, SearchType.isNull() ? diag::err_destructor_name_nontype | |||
443 | : diag::err_destructor_expr_mismatch) | |||
444 | << &II << SearchType << MakeFixItHint(); | |||
445 | } | |||
446 | ||||
447 | for (NamedDecl *FoundD : FoundDecls) { | |||
448 | if (auto *TD = dyn_cast<TypeDecl>(FoundD->getUnderlyingDecl())) | |||
449 | Diag(FoundD->getLocation(), diag::note_destructor_type_here) | |||
450 | << Context.getTypeDeclType(TD); | |||
451 | else | |||
452 | Diag(FoundD->getLocation(), diag::note_destructor_nontype_here) | |||
453 | << FoundD; | |||
454 | } | |||
455 | ||||
456 | return nullptr; | |||
457 | } | |||
458 | ||||
459 | ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS, | |||
460 | ParsedType ObjectType) { | |||
461 | if (DS.getTypeSpecType() == DeclSpec::TST_error) | |||
462 | return nullptr; | |||
463 | ||||
464 | if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) { | |||
465 | Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); | |||
466 | return nullptr; | |||
467 | } | |||
468 | ||||
469 | assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&(static_cast <bool> (DS.getTypeSpecType() == DeclSpec:: TST_decltype && "unexpected type in getDestructorType" ) ? void (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_decltype && \"unexpected type in getDestructorType\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 470, __extension__ __PRETTY_FUNCTION__)) | |||
470 | "unexpected type in getDestructorType")(static_cast <bool> (DS.getTypeSpecType() == DeclSpec:: TST_decltype && "unexpected type in getDestructorType" ) ? void (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_decltype && \"unexpected type in getDestructorType\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 470, __extension__ __PRETTY_FUNCTION__)); | |||
471 | QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); | |||
472 | ||||
473 | // If we know the type of the object, check that the correct destructor | |||
474 | // type was named now; we can give better diagnostics this way. | |||
475 | QualType SearchType = GetTypeFromParser(ObjectType); | |||
476 | if (!SearchType.isNull() && !SearchType->isDependentType() && | |||
477 | !Context.hasSameUnqualifiedType(T, SearchType)) { | |||
478 | Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch) | |||
479 | << T << SearchType; | |||
480 | return nullptr; | |||
481 | } | |||
482 | ||||
483 | return ParsedType::make(T); | |||
484 | } | |||
485 | ||||
486 | bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS, | |||
487 | const UnqualifiedId &Name) { | |||
488 | assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId)(static_cast <bool> (Name.getKind() == UnqualifiedIdKind ::IK_LiteralOperatorId) ? void (0) : __assert_fail ("Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 488, __extension__ __PRETTY_FUNCTION__)); | |||
489 | ||||
490 | if (!SS.isValid()) | |||
491 | return false; | |||
492 | ||||
493 | switch (SS.getScopeRep()->getKind()) { | |||
494 | case NestedNameSpecifier::Identifier: | |||
495 | case NestedNameSpecifier::TypeSpec: | |||
496 | case NestedNameSpecifier::TypeSpecWithTemplate: | |||
497 | // Per C++11 [over.literal]p2, literal operators can only be declared at | |||
498 | // namespace scope. Therefore, this unqualified-id cannot name anything. | |||
499 | // Reject it early, because we have no AST representation for this in the | |||
500 | // case where the scope is dependent. | |||
501 | Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace) | |||
502 | << SS.getScopeRep(); | |||
503 | return true; | |||
504 | ||||
505 | case NestedNameSpecifier::Global: | |||
506 | case NestedNameSpecifier::Super: | |||
507 | case NestedNameSpecifier::Namespace: | |||
508 | case NestedNameSpecifier::NamespaceAlias: | |||
509 | return false; | |||
510 | } | |||
511 | ||||
512 | llvm_unreachable("unknown nested name specifier kind")::llvm::llvm_unreachable_internal("unknown nested name specifier kind" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 512); | |||
513 | } | |||
514 | ||||
515 | /// Build a C++ typeid expression with a type operand. | |||
516 | ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, | |||
517 | SourceLocation TypeidLoc, | |||
518 | TypeSourceInfo *Operand, | |||
519 | SourceLocation RParenLoc) { | |||
520 | // C++ [expr.typeid]p4: | |||
521 | // The top-level cv-qualifiers of the lvalue expression or the type-id | |||
522 | // that is the operand of typeid are always ignored. | |||
523 | // If the type of the type-id is a class type or a reference to a class | |||
524 | // type, the class shall be completely-defined. | |||
525 | Qualifiers Quals; | |||
526 | QualType T | |||
527 | = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(), | |||
528 | Quals); | |||
529 | if (T->getAs<RecordType>() && | |||
530 | RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) | |||
531 | return ExprError(); | |||
532 | ||||
533 | if (T->isVariablyModifiedType()) | |||
534 | return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T); | |||
535 | ||||
536 | if (CheckQualifiedFunctionForTypeId(T, TypeidLoc)) | |||
537 | return ExprError(); | |||
538 | ||||
539 | return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand, | |||
540 | SourceRange(TypeidLoc, RParenLoc)); | |||
541 | } | |||
542 | ||||
543 | /// Build a C++ typeid expression with an expression operand. | |||
544 | ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, | |||
545 | SourceLocation TypeidLoc, | |||
546 | Expr *E, | |||
547 | SourceLocation RParenLoc) { | |||
548 | bool WasEvaluated = false; | |||
549 | if (E && !E->isTypeDependent()) { | |||
550 | if (E->getType()->isPlaceholderType()) { | |||
551 | ExprResult result = CheckPlaceholderExpr(E); | |||
552 | if (result.isInvalid()) return ExprError(); | |||
553 | E = result.get(); | |||
554 | } | |||
555 | ||||
556 | QualType T = E->getType(); | |||
557 | if (const RecordType *RecordT = T->getAs<RecordType>()) { | |||
558 | CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl()); | |||
559 | // C++ [expr.typeid]p3: | |||
560 | // [...] If the type of the expression is a class type, the class | |||
561 | // shall be completely-defined. | |||
562 | if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) | |||
563 | return ExprError(); | |||
564 | ||||
565 | // C++ [expr.typeid]p3: | |||
566 | // When typeid is applied to an expression other than an glvalue of a | |||
567 | // polymorphic class type [...] [the] expression is an unevaluated | |||
568 | // operand. [...] | |||
569 | if (RecordD->isPolymorphic() && E->isGLValue()) { | |||
570 | // The subexpression is potentially evaluated; switch the context | |||
571 | // and recheck the subexpression. | |||
572 | ExprResult Result = TransformToPotentiallyEvaluated(E); | |||
573 | if (Result.isInvalid()) return ExprError(); | |||
574 | E = Result.get(); | |||
575 | ||||
576 | // We require a vtable to query the type at run time. | |||
577 | MarkVTableUsed(TypeidLoc, RecordD); | |||
578 | WasEvaluated = true; | |||
579 | } | |||
580 | } | |||
581 | ||||
582 | ExprResult Result = CheckUnevaluatedOperand(E); | |||
583 | if (Result.isInvalid()) | |||
584 | return ExprError(); | |||
585 | E = Result.get(); | |||
586 | ||||
587 | // C++ [expr.typeid]p4: | |||
588 | // [...] If the type of the type-id is a reference to a possibly | |||
589 | // cv-qualified type, the result of the typeid expression refers to a | |||
590 | // std::type_info object representing the cv-unqualified referenced | |||
591 | // type. | |||
592 | Qualifiers Quals; | |||
593 | QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals); | |||
594 | if (!Context.hasSameType(T, UnqualT)) { | |||
595 | T = UnqualT; | |||
596 | E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get(); | |||
597 | } | |||
598 | } | |||
599 | ||||
600 | if (E->getType()->isVariablyModifiedType()) | |||
| ||||
601 | return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) | |||
602 | << E->getType()); | |||
603 | else if (!inTemplateInstantiation() && | |||
604 | E->HasSideEffects(Context, WasEvaluated)) { | |||
605 | // The expression operand for typeid is in an unevaluated expression | |||
606 | // context, so side effects could result in unintended consequences. | |||
607 | Diag(E->getExprLoc(), WasEvaluated | |||
608 | ? diag::warn_side_effects_typeid | |||
609 | : diag::warn_side_effects_unevaluated_context); | |||
610 | } | |||
611 | ||||
612 | return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E, | |||
613 | SourceRange(TypeidLoc, RParenLoc)); | |||
614 | } | |||
615 | ||||
616 | /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression); | |||
617 | ExprResult | |||
618 | Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, | |||
619 | bool isType, void *TyOrExpr, SourceLocation RParenLoc) { | |||
620 | // typeid is not supported in OpenCL. | |||
621 | if (getLangOpts().OpenCLCPlusPlus) { | |||
| ||||
622 | return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported) | |||
623 | << "typeid"); | |||
624 | } | |||
625 | ||||
626 | // Find the std::type_info type. | |||
627 | if (!getStdNamespace()) | |||
628 | return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); | |||
629 | ||||
630 | if (!CXXTypeInfoDecl) { | |||
631 | IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info"); | |||
632 | LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName); | |||
633 | LookupQualifiedName(R, getStdNamespace()); | |||
634 | CXXTypeInfoDecl = R.getAsSingle<RecordDecl>(); | |||
635 | // Microsoft's typeinfo doesn't have type_info in std but in the global | |||
636 | // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153. | |||
637 | if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) { | |||
638 | LookupQualifiedName(R, Context.getTranslationUnitDecl()); | |||
639 | CXXTypeInfoDecl = R.getAsSingle<RecordDecl>(); | |||
640 | } | |||
641 | if (!CXXTypeInfoDecl) | |||
642 | return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); | |||
643 | } | |||
644 | ||||
645 | if (!getLangOpts().RTTI) { | |||
646 | return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti)); | |||
647 | } | |||
648 | ||||
649 | QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl); | |||
650 | ||||
651 | if (isType) { | |||
652 | // The operand is a type; handle it as such. | |||
653 | TypeSourceInfo *TInfo = nullptr; | |||
654 | QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr), | |||
655 | &TInfo); | |||
656 | if (T.isNull()) | |||
657 | return ExprError(); | |||
658 | ||||
659 | if (!TInfo) | |||
660 | TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); | |||
661 | ||||
662 | return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc); | |||
663 | } | |||
664 | ||||
665 | // The operand is an expression. | |||
666 | ExprResult Result = | |||
667 | BuildCXXTypeId(TypeInfoType, OpLoc, (Expr *)TyOrExpr, RParenLoc); | |||
668 | ||||
669 | if (!getLangOpts().RTTIData && !Result.isInvalid()) | |||
670 | if (auto *CTE = dyn_cast<CXXTypeidExpr>(Result.get())) | |||
671 | if (CTE->isPotentiallyEvaluated() && !CTE->isMostDerived(Context)) | |||
672 | Diag(OpLoc, diag::warn_no_typeid_with_rtti_disabled) | |||
673 | << (getDiagnostics().getDiagnosticOptions().getFormat() == | |||
674 | DiagnosticOptions::MSVC); | |||
675 | return Result; | |||
676 | } | |||
677 | ||||
678 | /// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to | |||
679 | /// a single GUID. | |||
680 | static void | |||
681 | getUuidAttrOfType(Sema &SemaRef, QualType QT, | |||
682 | llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) { | |||
683 | // Optionally remove one level of pointer, reference or array indirection. | |||
684 | const Type *Ty = QT.getTypePtr(); | |||
685 | if (QT->isPointerType() || QT->isReferenceType()) | |||
686 | Ty = QT->getPointeeType().getTypePtr(); | |||
687 | else if (QT->isArrayType()) | |||
688 | Ty = Ty->getBaseElementTypeUnsafe(); | |||
689 | ||||
690 | const auto *TD = Ty->getAsTagDecl(); | |||
691 | if (!TD) | |||
692 | return; | |||
693 | ||||
694 | if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) { | |||
695 | UuidAttrs.insert(Uuid); | |||
696 | return; | |||
697 | } | |||
698 | ||||
699 | // __uuidof can grab UUIDs from template arguments. | |||
700 | if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) { | |||
701 | const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); | |||
702 | for (const TemplateArgument &TA : TAL.asArray()) { | |||
703 | const UuidAttr *UuidForTA = nullptr; | |||
704 | if (TA.getKind() == TemplateArgument::Type) | |||
705 | getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs); | |||
706 | else if (TA.getKind() == TemplateArgument::Declaration) | |||
707 | getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs); | |||
708 | ||||
709 | if (UuidForTA) | |||
710 | UuidAttrs.insert(UuidForTA); | |||
711 | } | |||
712 | } | |||
713 | } | |||
714 | ||||
715 | /// Build a Microsoft __uuidof expression with a type operand. | |||
716 | ExprResult Sema::BuildCXXUuidof(QualType Type, | |||
717 | SourceLocation TypeidLoc, | |||
718 | TypeSourceInfo *Operand, | |||
719 | SourceLocation RParenLoc) { | |||
720 | MSGuidDecl *Guid = nullptr; | |||
721 | if (!Operand->getType()->isDependentType()) { | |||
722 | llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs; | |||
723 | getUuidAttrOfType(*this, Operand->getType(), UuidAttrs); | |||
724 | if (UuidAttrs.empty()) | |||
725 | return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid)); | |||
726 | if (UuidAttrs.size() > 1) | |||
727 | return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids)); | |||
728 | Guid = UuidAttrs.back()->getGuidDecl(); | |||
729 | } | |||
730 | ||||
731 | return new (Context) | |||
732 | CXXUuidofExpr(Type, Operand, Guid, SourceRange(TypeidLoc, RParenLoc)); | |||
733 | } | |||
734 | ||||
735 | /// Build a Microsoft __uuidof expression with an expression operand. | |||
736 | ExprResult Sema::BuildCXXUuidof(QualType Type, SourceLocation TypeidLoc, | |||
737 | Expr *E, SourceLocation RParenLoc) { | |||
738 | MSGuidDecl *Guid = nullptr; | |||
739 | if (!E->getType()->isDependentType()) { | |||
740 | if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { | |||
741 | // A null pointer results in {00000000-0000-0000-0000-000000000000}. | |||
742 | Guid = Context.getMSGuidDecl(MSGuidDecl::Parts{}); | |||
743 | } else { | |||
744 | llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs; | |||
745 | getUuidAttrOfType(*this, E->getType(), UuidAttrs); | |||
746 | if (UuidAttrs.empty()) | |||
747 | return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid)); | |||
748 | if (UuidAttrs.size() > 1) | |||
749 | return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids)); | |||
750 | Guid = UuidAttrs.back()->getGuidDecl(); | |||
751 | } | |||
752 | } | |||
753 | ||||
754 | return new (Context) | |||
755 | CXXUuidofExpr(Type, E, Guid, SourceRange(TypeidLoc, RParenLoc)); | |||
756 | } | |||
757 | ||||
758 | /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression); | |||
759 | ExprResult | |||
760 | Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, | |||
761 | bool isType, void *TyOrExpr, SourceLocation RParenLoc) { | |||
762 | QualType GuidType = Context.getMSGuidType(); | |||
763 | GuidType.addConst(); | |||
764 | ||||
765 | if (isType) { | |||
766 | // The operand is a type; handle it as such. | |||
767 | TypeSourceInfo *TInfo = nullptr; | |||
768 | QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr), | |||
769 | &TInfo); | |||
770 | if (T.isNull()) | |||
771 | return ExprError(); | |||
772 | ||||
773 | if (!TInfo) | |||
774 | TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); | |||
775 | ||||
776 | return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc); | |||
777 | } | |||
778 | ||||
779 | // The operand is an expression. | |||
780 | return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc); | |||
781 | } | |||
782 | ||||
783 | /// ActOnCXXBoolLiteral - Parse {true,false} literals. | |||
784 | ExprResult | |||
785 | Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { | |||
786 | assert((Kind == tok::kw_true || Kind == tok::kw_false) &&(static_cast <bool> ((Kind == tok::kw_true || Kind == tok ::kw_false) && "Unknown C++ Boolean value!") ? void ( 0) : __assert_fail ("(Kind == tok::kw_true || Kind == tok::kw_false) && \"Unknown C++ Boolean value!\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 787, __extension__ __PRETTY_FUNCTION__)) | |||
787 | "Unknown C++ Boolean value!")(static_cast <bool> ((Kind == tok::kw_true || Kind == tok ::kw_false) && "Unknown C++ Boolean value!") ? void ( 0) : __assert_fail ("(Kind == tok::kw_true || Kind == tok::kw_false) && \"Unknown C++ Boolean value!\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 787, __extension__ __PRETTY_FUNCTION__)); | |||
788 | return new (Context) | |||
789 | CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc); | |||
790 | } | |||
791 | ||||
792 | /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. | |||
793 | ExprResult | |||
794 | Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) { | |||
795 | return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc); | |||
796 | } | |||
797 | ||||
798 | /// ActOnCXXThrow - Parse throw expressions. | |||
799 | ExprResult | |||
800 | Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) { | |||
801 | bool IsThrownVarInScope = false; | |||
802 | if (Ex) { | |||
803 | // C++0x [class.copymove]p31: | |||
804 | // When certain criteria are met, an implementation is allowed to omit the | |||
805 | // copy/move construction of a class object [...] | |||
806 | // | |||
807 | // - in a throw-expression, when the operand is the name of a | |||
808 | // non-volatile automatic object (other than a function or catch- | |||
809 | // clause parameter) whose scope does not extend beyond the end of the | |||
810 | // innermost enclosing try-block (if there is one), the copy/move | |||
811 | // operation from the operand to the exception object (15.1) can be | |||
812 | // omitted by constructing the automatic object directly into the | |||
813 | // exception object | |||
814 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens())) | |||
815 | if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { | |||
816 | if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) { | |||
817 | for( ; S; S = S->getParent()) { | |||
818 | if (S->isDeclScope(Var)) { | |||
819 | IsThrownVarInScope = true; | |||
820 | break; | |||
821 | } | |||
822 | ||||
823 | if (S->getFlags() & | |||
824 | (Scope::FnScope | Scope::ClassScope | Scope::BlockScope | | |||
825 | Scope::FunctionPrototypeScope | Scope::ObjCMethodScope | | |||
826 | Scope::TryScope)) | |||
827 | break; | |||
828 | } | |||
829 | } | |||
830 | } | |||
831 | } | |||
832 | ||||
833 | return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope); | |||
834 | } | |||
835 | ||||
836 | ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, | |||
837 | bool IsThrownVarInScope) { | |||
838 | // Don't report an error if 'throw' is used in system headers. | |||
839 | if (!getLangOpts().CXXExceptions && | |||
840 | !getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) { | |||
841 | // Delay error emission for the OpenMP device code. | |||
842 | targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw"; | |||
843 | } | |||
844 | ||||
845 | // Exceptions aren't allowed in CUDA device code. | |||
846 | if (getLangOpts().CUDA) | |||
847 | CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions) | |||
848 | << "throw" << CurrentCUDATarget(); | |||
849 | ||||
850 | if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope()) | |||
851 | Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw"; | |||
852 | ||||
853 | if (Ex && !Ex->isTypeDependent()) { | |||
854 | QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType()); | |||
855 | if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex)) | |||
856 | return ExprError(); | |||
857 | ||||
858 | // Initialize the exception result. This implicitly weeds out | |||
859 | // abstract types or types with inaccessible copy constructors. | |||
860 | ||||
861 | // C++0x [class.copymove]p31: | |||
862 | // When certain criteria are met, an implementation is allowed to omit the | |||
863 | // copy/move construction of a class object [...] | |||
864 | // | |||
865 | // - in a throw-expression, when the operand is the name of a | |||
866 | // non-volatile automatic object (other than a function or | |||
867 | // catch-clause | |||
868 | // parameter) whose scope does not extend beyond the end of the | |||
869 | // innermost enclosing try-block (if there is one), the copy/move | |||
870 | // operation from the operand to the exception object (15.1) can be | |||
871 | // omitted by constructing the automatic object directly into the | |||
872 | // exception object | |||
873 | const VarDecl *NRVOVariable = nullptr; | |||
874 | if (IsThrownVarInScope) | |||
875 | NRVOVariable = getCopyElisionCandidate(QualType(), Ex, CES_Strict); | |||
876 | ||||
877 | InitializedEntity Entity = InitializedEntity::InitializeException( | |||
878 | OpLoc, ExceptionObjectTy, | |||
879 | /*NRVO=*/NRVOVariable != nullptr); | |||
880 | ExprResult Res = PerformMoveOrCopyInitialization( | |||
881 | Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope); | |||
882 | if (Res.isInvalid()) | |||
883 | return ExprError(); | |||
884 | Ex = Res.get(); | |||
885 | } | |||
886 | ||||
887 | // PPC MMA non-pointer types are not allowed as throw expr types. | |||
888 | if (Ex && Context.getTargetInfo().getTriple().isPPC64()) | |||
889 | CheckPPCMMAType(Ex->getType(), Ex->getBeginLoc()); | |||
890 | ||||
891 | return new (Context) | |||
892 | CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope); | |||
893 | } | |||
894 | ||||
895 | static void | |||
896 | collectPublicBases(CXXRecordDecl *RD, | |||
897 | llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen, | |||
898 | llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases, | |||
899 | llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen, | |||
900 | bool ParentIsPublic) { | |||
901 | for (const CXXBaseSpecifier &BS : RD->bases()) { | |||
902 | CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); | |||
903 | bool NewSubobject; | |||
904 | // Virtual bases constitute the same subobject. Non-virtual bases are | |||
905 | // always distinct subobjects. | |||
906 | if (BS.isVirtual()) | |||
907 | NewSubobject = VBases.insert(BaseDecl).second; | |||
908 | else | |||
909 | NewSubobject = true; | |||
910 | ||||
911 | if (NewSubobject) | |||
912 | ++SubobjectsSeen[BaseDecl]; | |||
913 | ||||
914 | // Only add subobjects which have public access throughout the entire chain. | |||
915 | bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public; | |||
916 | if (PublicPath) | |||
917 | PublicSubobjectsSeen.insert(BaseDecl); | |||
918 | ||||
919 | // Recurse on to each base subobject. | |||
920 | collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen, | |||
921 | PublicPath); | |||
922 | } | |||
923 | } | |||
924 | ||||
925 | static void getUnambiguousPublicSubobjects( | |||
926 | CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) { | |||
927 | llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen; | |||
928 | llvm::SmallSet<CXXRecordDecl *, 2> VBases; | |||
929 | llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen; | |||
930 | SubobjectsSeen[RD] = 1; | |||
931 | PublicSubobjectsSeen.insert(RD); | |||
932 | collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen, | |||
933 | /*ParentIsPublic=*/true); | |||
934 | ||||
935 | for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) { | |||
936 | // Skip ambiguous objects. | |||
937 | if (SubobjectsSeen[PublicSubobject] > 1) | |||
938 | continue; | |||
939 | ||||
940 | Objects.push_back(PublicSubobject); | |||
941 | } | |||
942 | } | |||
943 | ||||
944 | /// CheckCXXThrowOperand - Validate the operand of a throw. | |||
945 | bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, | |||
946 | QualType ExceptionObjectTy, Expr *E) { | |||
947 | // If the type of the exception would be an incomplete type or a pointer | |||
948 | // to an incomplete type other than (cv) void the program is ill-formed. | |||
949 | QualType Ty = ExceptionObjectTy; | |||
950 | bool isPointer = false; | |||
951 | if (const PointerType* Ptr = Ty->getAs<PointerType>()) { | |||
952 | Ty = Ptr->getPointeeType(); | |||
953 | isPointer = true; | |||
954 | } | |||
955 | if (!isPointer || !Ty->isVoidType()) { | |||
956 | if (RequireCompleteType(ThrowLoc, Ty, | |||
957 | isPointer ? diag::err_throw_incomplete_ptr | |||
958 | : diag::err_throw_incomplete, | |||
959 | E->getSourceRange())) | |||
960 | return true; | |||
961 | ||||
962 | if (!isPointer && Ty->isSizelessType()) { | |||
963 | Diag(ThrowLoc, diag::err_throw_sizeless) << Ty << E->getSourceRange(); | |||
964 | return true; | |||
965 | } | |||
966 | ||||
967 | if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy, | |||
968 | diag::err_throw_abstract_type, E)) | |||
969 | return true; | |||
970 | } | |||
971 | ||||
972 | // If the exception has class type, we need additional handling. | |||
973 | CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); | |||
974 | if (!RD) | |||
975 | return false; | |||
976 | ||||
977 | // If we are throwing a polymorphic class type or pointer thereof, | |||
978 | // exception handling will make use of the vtable. | |||
979 | MarkVTableUsed(ThrowLoc, RD); | |||
980 | ||||
981 | // If a pointer is thrown, the referenced object will not be destroyed. | |||
982 | if (isPointer) | |||
983 | return false; | |||
984 | ||||
985 | // If the class has a destructor, we must be able to call it. | |||
986 | if (!RD->hasIrrelevantDestructor()) { | |||
987 | if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { | |||
988 | MarkFunctionReferenced(E->getExprLoc(), Destructor); | |||
989 | CheckDestructorAccess(E->getExprLoc(), Destructor, | |||
990 | PDiag(diag::err_access_dtor_exception) << Ty); | |||
991 | if (DiagnoseUseOfDecl(Destructor, E->getExprLoc())) | |||
992 | return true; | |||
993 | } | |||
994 | } | |||
995 | ||||
996 | // The MSVC ABI creates a list of all types which can catch the exception | |||
997 | // object. This list also references the appropriate copy constructor to call | |||
998 | // if the object is caught by value and has a non-trivial copy constructor. | |||
999 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { | |||
1000 | // We are only interested in the public, unambiguous bases contained within | |||
1001 | // the exception object. Bases which are ambiguous or otherwise | |||
1002 | // inaccessible are not catchable types. | |||
1003 | llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects; | |||
1004 | getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects); | |||
1005 | ||||
1006 | for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) { | |||
1007 | // Attempt to lookup the copy constructor. Various pieces of machinery | |||
1008 | // will spring into action, like template instantiation, which means this | |||
1009 | // cannot be a simple walk of the class's decls. Instead, we must perform | |||
1010 | // lookup and overload resolution. | |||
1011 | CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0); | |||
1012 | if (!CD || CD->isDeleted()) | |||
1013 | continue; | |||
1014 | ||||
1015 | // Mark the constructor referenced as it is used by this throw expression. | |||
1016 | MarkFunctionReferenced(E->getExprLoc(), CD); | |||
1017 | ||||
1018 | // Skip this copy constructor if it is trivial, we don't need to record it | |||
1019 | // in the catchable type data. | |||
1020 | if (CD->isTrivial()) | |||
1021 | continue; | |||
1022 | ||||
1023 | // The copy constructor is non-trivial, create a mapping from this class | |||
1024 | // type to this constructor. | |||
1025 | // N.B. The selection of copy constructor is not sensitive to this | |||
1026 | // particular throw-site. Lookup will be performed at the catch-site to | |||
1027 | // ensure that the copy constructor is, in fact, accessible (via | |||
1028 | // friendship or any other means). | |||
1029 | Context.addCopyConstructorForExceptionObject(Subobject, CD); | |||
1030 | ||||
1031 | // We don't keep the instantiated default argument expressions around so | |||
1032 | // we must rebuild them here. | |||
1033 | for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) { | |||
1034 | if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I))) | |||
1035 | return true; | |||
1036 | } | |||
1037 | } | |||
1038 | } | |||
1039 | ||||
1040 | // Under the Itanium C++ ABI, memory for the exception object is allocated by | |||
1041 | // the runtime with no ability for the compiler to request additional | |||
1042 | // alignment. Warn if the exception type requires alignment beyond the minimum | |||
1043 | // guaranteed by the target C++ runtime. | |||
1044 | if (Context.getTargetInfo().getCXXABI().isItaniumFamily()) { | |||
1045 | CharUnits TypeAlign = Context.getTypeAlignInChars(Ty); | |||
1046 | CharUnits ExnObjAlign = Context.getExnObjectAlignment(); | |||
1047 | if (ExnObjAlign < TypeAlign) { | |||
1048 | Diag(ThrowLoc, diag::warn_throw_underaligned_obj); | |||
1049 | Diag(ThrowLoc, diag::note_throw_underaligned_obj) | |||
1050 | << Ty << (unsigned)TypeAlign.getQuantity() | |||
1051 | << (unsigned)ExnObjAlign.getQuantity(); | |||
1052 | } | |||
1053 | } | |||
1054 | ||||
1055 | return false; | |||
1056 | } | |||
1057 | ||||
1058 | static QualType adjustCVQualifiersForCXXThisWithinLambda( | |||
1059 | ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy, | |||
1060 | DeclContext *CurSemaContext, ASTContext &ASTCtx) { | |||
1061 | ||||
1062 | QualType ClassType = ThisTy->getPointeeType(); | |||
1063 | LambdaScopeInfo *CurLSI = nullptr; | |||
1064 | DeclContext *CurDC = CurSemaContext; | |||
1065 | ||||
1066 | // Iterate through the stack of lambdas starting from the innermost lambda to | |||
1067 | // the outermost lambda, checking if '*this' is ever captured by copy - since | |||
1068 | // that could change the cv-qualifiers of the '*this' object. | |||
1069 | // The object referred to by '*this' starts out with the cv-qualifiers of its | |||
1070 | // member function. We then start with the innermost lambda and iterate | |||
1071 | // outward checking to see if any lambda performs a by-copy capture of '*this' | |||
1072 | // - and if so, any nested lambda must respect the 'constness' of that | |||
1073 | // capturing lamdbda's call operator. | |||
1074 | // | |||
1075 | ||||
1076 | // Since the FunctionScopeInfo stack is representative of the lexical | |||
1077 | // nesting of the lambda expressions during initial parsing (and is the best | |||
1078 | // place for querying information about captures about lambdas that are | |||
1079 | // partially processed) and perhaps during instantiation of function templates | |||
1080 | // that contain lambda expressions that need to be transformed BUT not | |||
1081 | // necessarily during instantiation of a nested generic lambda's function call | |||
1082 | // operator (which might even be instantiated at the end of the TU) - at which | |||
1083 | // time the DeclContext tree is mature enough to query capture information | |||
1084 | // reliably - we use a two pronged approach to walk through all the lexically | |||
1085 | // enclosing lambda expressions: | |||
1086 | // | |||
1087 | // 1) Climb down the FunctionScopeInfo stack as long as each item represents | |||
1088 | // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically | |||
1089 | // enclosed by the call-operator of the LSI below it on the stack (while | |||
1090 | // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on | |||
1091 | // the stack represents the innermost lambda. | |||
1092 | // | |||
1093 | // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext | |||
1094 | // represents a lambda's call operator. If it does, we must be instantiating | |||
1095 | // a generic lambda's call operator (represented by the Current LSI, and | |||
1096 | // should be the only scenario where an inconsistency between the LSI and the | |||
1097 | // DeclContext should occur), so climb out the DeclContexts if they | |||
1098 | // represent lambdas, while querying the corresponding closure types | |||
1099 | // regarding capture information. | |||
1100 | ||||
1101 | // 1) Climb down the function scope info stack. | |||
1102 | for (int I = FunctionScopes.size(); | |||
1103 | I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) && | |||
1104 | (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() == | |||
1105 | cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator); | |||
1106 | CurDC = getLambdaAwareParentOfDeclContext(CurDC)) { | |||
1107 | CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]); | |||
1108 | ||||
1109 | if (!CurLSI->isCXXThisCaptured()) | |||
1110 | continue; | |||
1111 | ||||
1112 | auto C = CurLSI->getCXXThisCapture(); | |||
1113 | ||||
1114 | if (C.isCopyCapture()) { | |||
1115 | ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask); | |||
1116 | if (CurLSI->CallOperator->isConst()) | |||
1117 | ClassType.addConst(); | |||
1118 | return ASTCtx.getPointerType(ClassType); | |||
1119 | } | |||
1120 | } | |||
1121 | ||||
1122 | // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can | |||
1123 | // happen during instantiation of its nested generic lambda call operator) | |||
1124 | if (isLambdaCallOperator(CurDC)) { | |||
1125 | assert(CurLSI && "While computing 'this' capture-type for a generic "(static_cast <bool> (CurLSI && "While computing 'this' capture-type for a generic " "lambda, we must have a corresponding LambdaScopeInfo") ? void (0) : __assert_fail ("CurLSI && \"While computing 'this' capture-type for a generic \" \"lambda, we must have a corresponding LambdaScopeInfo\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 1126, __extension__ __PRETTY_FUNCTION__)) | |||
1126 | "lambda, we must have a corresponding LambdaScopeInfo")(static_cast <bool> (CurLSI && "While computing 'this' capture-type for a generic " "lambda, we must have a corresponding LambdaScopeInfo") ? void (0) : __assert_fail ("CurLSI && \"While computing 'this' capture-type for a generic \" \"lambda, we must have a corresponding LambdaScopeInfo\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 1126, __extension__ __PRETTY_FUNCTION__)); | |||
1127 | assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&(static_cast <bool> (isGenericLambdaCallOperatorSpecialization (CurLSI->CallOperator) && "While computing 'this' capture-type for a generic lambda, when we " "run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic " "lambda call oeprator") ? void (0) : __assert_fail ("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 1131, __extension__ __PRETTY_FUNCTION__)) | |||
1128 | "While computing 'this' capture-type for a generic lambda, when we "(static_cast <bool> (isGenericLambdaCallOperatorSpecialization (CurLSI->CallOperator) && "While computing 'this' capture-type for a generic lambda, when we " "run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic " "lambda call oeprator") ? void (0) : __assert_fail ("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 1131, __extension__ __PRETTY_FUNCTION__)) | |||
1129 | "run out of enclosing LSI's, yet the enclosing DC is a "(static_cast <bool> (isGenericLambdaCallOperatorSpecialization (CurLSI->CallOperator) && "While computing 'this' capture-type for a generic lambda, when we " "run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic " "lambda call oeprator") ? void (0) : __assert_fail ("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 1131, __extension__ __PRETTY_FUNCTION__)) | |||
1130 | "lambda-call-operator we must be (i.e. Current LSI) in a generic "(static_cast <bool> (isGenericLambdaCallOperatorSpecialization (CurLSI->CallOperator) && "While computing 'this' capture-type for a generic lambda, when we " "run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic " "lambda call oeprator") ? void (0) : __assert_fail ("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 1131, __extension__ __PRETTY_FUNCTION__)) | |||
1131 | "lambda call oeprator")(static_cast <bool> (isGenericLambdaCallOperatorSpecialization (CurLSI->CallOperator) && "While computing 'this' capture-type for a generic lambda, when we " "run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic " "lambda call oeprator") ? void (0) : __assert_fail ("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 1131, __extension__ __PRETTY_FUNCTION__)); | |||
1132 | assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator))(static_cast <bool> (CurDC == getLambdaAwareParentOfDeclContext (CurLSI->CallOperator)) ? void (0) : __assert_fail ("CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator)" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 1132, __extension__ __PRETTY_FUNCTION__)); | |||
1133 | ||||
1134 | auto IsThisCaptured = | |||
1135 | [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) { | |||
1136 | IsConst = false; | |||
1137 | IsByCopy = false; | |||
1138 | for (auto &&C : Closure->captures()) { | |||
1139 | if (C.capturesThis()) { | |||
1140 | if (C.getCaptureKind() == LCK_StarThis) | |||
1141 | IsByCopy = true; | |||
1142 | if (Closure->getLambdaCallOperator()->isConst()) | |||
1143 | IsConst = true; | |||
1144 | return true; | |||
1145 | } | |||
1146 | } | |||
1147 | return false; | |||
1148 | }; | |||
1149 | ||||
1150 | bool IsByCopyCapture = false; | |||
1151 | bool IsConstCapture = false; | |||
1152 | CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent()); | |||
1153 | while (Closure && | |||
1154 | IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) { | |||
1155 | if (IsByCopyCapture) { | |||
1156 | ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask); | |||
1157 | if (IsConstCapture) | |||
1158 | ClassType.addConst(); | |||
1159 | return ASTCtx.getPointerType(ClassType); | |||
1160 | } | |||
1161 | Closure = isLambdaCallOperator(Closure->getParent()) | |||
1162 | ? cast<CXXRecordDecl>(Closure->getParent()->getParent()) | |||
1163 | : nullptr; | |||
1164 | } | |||
1165 | } | |||
1166 | return ASTCtx.getPointerType(ClassType); | |||
1167 | } | |||
1168 | ||||
1169 | QualType Sema::getCurrentThisType() { | |||
1170 | DeclContext *DC = getFunctionLevelDeclContext(); | |||
1171 | QualType ThisTy = CXXThisTypeOverride; | |||
1172 | ||||
1173 | if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) { | |||
1174 | if (method && method->isInstance()) | |||
1175 | ThisTy = method->getThisType(); | |||
1176 | } | |||
1177 | ||||
1178 | if (ThisTy.isNull() && isLambdaCallOperator(CurContext) && | |||
1179 | inTemplateInstantiation() && isa<CXXRecordDecl>(DC)) { | |||
1180 | ||||
1181 | // This is a lambda call operator that is being instantiated as a default | |||
1182 | // initializer. DC must point to the enclosing class type, so we can recover | |||
1183 | // the 'this' type from it. | |||
1184 | QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC)); | |||
1185 | // There are no cv-qualifiers for 'this' within default initializers, | |||
1186 | // per [expr.prim.general]p4. | |||
1187 | ThisTy = Context.getPointerType(ClassTy); | |||
1188 | } | |||
1189 | ||||
1190 | // If we are within a lambda's call operator, the cv-qualifiers of 'this' | |||
1191 | // might need to be adjusted if the lambda or any of its enclosing lambda's | |||
1192 | // captures '*this' by copy. | |||
1193 | if (!ThisTy.isNull() && isLambdaCallOperator(CurContext)) | |||
1194 | return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy, | |||
1195 | CurContext, Context); | |||
1196 | return ThisTy; | |||
1197 | } | |||
1198 | ||||
1199 | Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S, | |||
1200 | Decl *ContextDecl, | |||
1201 | Qualifiers CXXThisTypeQuals, | |||
1202 | bool Enabled) | |||
1203 | : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false) | |||
1204 | { | |||
1205 | if (!Enabled || !ContextDecl) | |||
1206 | return; | |||
1207 | ||||
1208 | CXXRecordDecl *Record = nullptr; | |||
1209 | if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl)) | |||
1210 | Record = Template->getTemplatedDecl(); | |||
1211 | else | |||
1212 | Record = cast<CXXRecordDecl>(ContextDecl); | |||
1213 | ||||
1214 | QualType T = S.Context.getRecordType(Record); | |||
1215 | T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals); | |||
1216 | ||||
1217 | S.CXXThisTypeOverride = S.Context.getPointerType(T); | |||
1218 | ||||
1219 | this->Enabled = true; | |||
1220 | } | |||
1221 | ||||
1222 | ||||
1223 | Sema::CXXThisScopeRAII::~CXXThisScopeRAII() { | |||
1224 | if (Enabled) { | |||
1225 | S.CXXThisTypeOverride = OldCXXThisTypeOverride; | |||
1226 | } | |||
1227 | } | |||
1228 | ||||
1229 | static void buildLambdaThisCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI) { | |||
1230 | SourceLocation DiagLoc = LSI->IntroducerRange.getEnd(); | |||
1231 | assert(!LSI->isCXXThisCaptured())(static_cast <bool> (!LSI->isCXXThisCaptured()) ? void (0) : __assert_fail ("!LSI->isCXXThisCaptured()", "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 1231, __extension__ __PRETTY_FUNCTION__)); | |||
1232 | // [=, this] {}; // until C++20: Error: this when = is the default | |||
1233 | if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval && | |||
1234 | !Sema.getLangOpts().CPlusPlus20) | |||
1235 | return; | |||
1236 | Sema.Diag(DiagLoc, diag::note_lambda_this_capture_fixit) | |||
1237 | << FixItHint::CreateInsertion( | |||
1238 | DiagLoc, LSI->NumExplicitCaptures > 0 ? ", this" : "this"); | |||
1239 | } | |||
1240 | ||||
1241 | bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit, | |||
1242 | bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt, | |||
1243 | const bool ByCopy) { | |||
1244 | // We don't need to capture this in an unevaluated context. | |||
1245 | if (isUnevaluatedContext() && !Explicit) | |||
1246 | return true; | |||
1247 | ||||
1248 | assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value")(static_cast <bool> ((!ByCopy || Explicit) && "cannot implicitly capture *this by value" ) ? void (0) : __assert_fail ("(!ByCopy || Explicit) && \"cannot implicitly capture *this by value\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 1248, __extension__ __PRETTY_FUNCTION__)); | |||
1249 | ||||
1250 | const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt | |||
1251 | ? *FunctionScopeIndexToStopAt | |||
1252 | : FunctionScopes.size() - 1; | |||
1253 | ||||
1254 | // Check that we can capture the *enclosing object* (referred to by '*this') | |||
1255 | // by the capturing-entity/closure (lambda/block/etc) at | |||
1256 | // MaxFunctionScopesIndex-deep on the FunctionScopes stack. | |||
1257 | ||||
1258 | // Note: The *enclosing object* can only be captured by-value by a | |||
1259 | // closure that is a lambda, using the explicit notation: | |||
1260 | // [*this] { ... }. | |||
1261 | // Every other capture of the *enclosing object* results in its by-reference | |||
1262 | // capture. | |||
1263 | ||||
1264 | // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes | |||
1265 | // stack), we can capture the *enclosing object* only if: | |||
1266 | // - 'L' has an explicit byref or byval capture of the *enclosing object* | |||
1267 | // - or, 'L' has an implicit capture. | |||
1268 | // AND | |||
1269 | // -- there is no enclosing closure | |||
1270 | // -- or, there is some enclosing closure 'E' that has already captured the | |||
1271 | // *enclosing object*, and every intervening closure (if any) between 'E' | |||
1272 | // and 'L' can implicitly capture the *enclosing object*. | |||
1273 | // -- or, every enclosing closure can implicitly capture the | |||
1274 | // *enclosing object* | |||
1275 | ||||
1276 | ||||
1277 | unsigned NumCapturingClosures = 0; | |||
1278 | for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) { | |||
1279 | if (CapturingScopeInfo *CSI = | |||
1280 | dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) { | |||
1281 | if (CSI->CXXThisCaptureIndex != 0) { | |||
1282 | // 'this' is already being captured; there isn't anything more to do. | |||
1283 | CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose); | |||
1284 | break; | |||
1285 | } | |||
1286 | LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI); | |||
1287 | if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) { | |||
1288 | // This context can't implicitly capture 'this'; fail out. | |||
1289 | if (BuildAndDiagnose) { | |||
1290 | Diag(Loc, diag::err_this_capture) | |||
1291 | << (Explicit && idx == MaxFunctionScopesIndex); | |||
1292 | if (!Explicit) | |||
1293 | buildLambdaThisCaptureFixit(*this, LSI); | |||
1294 | } | |||
1295 | return true; | |||
1296 | } | |||
1297 | if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref || | |||
1298 | CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval || | |||
1299 | CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block || | |||
1300 | CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion || | |||
1301 | (Explicit && idx == MaxFunctionScopesIndex)) { | |||
1302 | // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first | |||
1303 | // iteration through can be an explicit capture, all enclosing closures, | |||
1304 | // if any, must perform implicit captures. | |||
1305 | ||||
1306 | // This closure can capture 'this'; continue looking upwards. | |||
1307 | NumCapturingClosures++; | |||
1308 | continue; | |||
1309 | } | |||
1310 | // This context can't implicitly capture 'this'; fail out. | |||
1311 | if (BuildAndDiagnose) | |||
1312 | Diag(Loc, diag::err_this_capture) | |||
1313 | << (Explicit && idx == MaxFunctionScopesIndex); | |||
1314 | ||||
1315 | if (!Explicit) | |||
1316 | buildLambdaThisCaptureFixit(*this, LSI); | |||
1317 | return true; | |||
1318 | } | |||
1319 | break; | |||
1320 | } | |||
1321 | if (!BuildAndDiagnose) return false; | |||
1322 | ||||
1323 | // If we got here, then the closure at MaxFunctionScopesIndex on the | |||
1324 | // FunctionScopes stack, can capture the *enclosing object*, so capture it | |||
1325 | // (including implicit by-reference captures in any enclosing closures). | |||
1326 | ||||
1327 | // In the loop below, respect the ByCopy flag only for the closure requesting | |||
1328 | // the capture (i.e. first iteration through the loop below). Ignore it for | |||
1329 | // all enclosing closure's up to NumCapturingClosures (since they must be | |||
1330 | // implicitly capturing the *enclosing object* by reference (see loop | |||
1331 | // above)). | |||
1332 | assert((!ByCopy ||(static_cast <bool> ((!ByCopy || dyn_cast<LambdaScopeInfo >(FunctionScopes[MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by " "*this) by copy") ? void (0) : __assert_fail ("(!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 1335, __extension__ __PRETTY_FUNCTION__)) | |||
1333 | dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&(static_cast <bool> ((!ByCopy || dyn_cast<LambdaScopeInfo >(FunctionScopes[MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by " "*this) by copy") ? void (0) : __assert_fail ("(!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 1335, __extension__ __PRETTY_FUNCTION__)) | |||
1334 | "Only a lambda can capture the enclosing object (referred to by "(static_cast <bool> ((!ByCopy || dyn_cast<LambdaScopeInfo >(FunctionScopes[MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by " "*this) by copy") ? void (0) : __assert_fail ("(!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 1335, __extension__ __PRETTY_FUNCTION__)) | |||
1335 | "*this) by copy")(static_cast <bool> ((!ByCopy || dyn_cast<LambdaScopeInfo >(FunctionScopes[MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by " "*this) by copy") ? void (0) : __assert_fail ("(!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 1335, __extension__ __PRETTY_FUNCTION__)); | |||
1336 | QualType ThisTy = getCurrentThisType(); | |||
1337 | for (int idx = MaxFunctionScopesIndex; NumCapturingClosures; | |||
1338 | --idx, --NumCapturingClosures) { | |||
1339 | CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]); | |||
1340 | ||||
1341 | // The type of the corresponding data member (not a 'this' pointer if 'by | |||
1342 | // copy'). | |||
1343 | QualType CaptureType = ThisTy; | |||
1344 | if (ByCopy) { | |||
1345 | // If we are capturing the object referred to by '*this' by copy, ignore | |||
1346 | // any cv qualifiers inherited from the type of the member function for | |||
1347 | // the type of the closure-type's corresponding data member and any use | |||
1348 | // of 'this'. | |||
1349 | CaptureType = ThisTy->getPointeeType(); | |||
1350 | CaptureType.removeLocalCVRQualifiers(Qualifiers::CVRMask); | |||
1351 | } | |||
1352 | ||||
1353 | bool isNested = NumCapturingClosures > 1; | |||
1354 | CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy); | |||
1355 | } | |||
1356 | return false; | |||
1357 | } | |||
1358 | ||||
1359 | ExprResult Sema::ActOnCXXThis(SourceLocation Loc) { | |||
1360 | /// C++ 9.3.2: In the body of a non-static member function, the keyword this | |||
1361 | /// is a non-lvalue expression whose value is the address of the object for | |||
1362 | /// which the function is called. | |||
1363 | ||||
1364 | QualType ThisTy = getCurrentThisType(); | |||
1365 | if (ThisTy.isNull()) | |||
1366 | return Diag(Loc, diag::err_invalid_this_use); | |||
1367 | return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false); | |||
1368 | } | |||
1369 | ||||
1370 | Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type, | |||
1371 | bool IsImplicit) { | |||
1372 | auto *This = new (Context) CXXThisExpr(Loc, Type, IsImplicit); | |||
1373 | MarkThisReferenced(This); | |||
1374 | return This; | |||
1375 | } | |||
1376 | ||||
1377 | void Sema::MarkThisReferenced(CXXThisExpr *This) { | |||
1378 | CheckCXXThisCapture(This->getExprLoc()); | |||
1379 | } | |||
1380 | ||||
1381 | bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) { | |||
1382 | // If we're outside the body of a member function, then we'll have a specified | |||
1383 | // type for 'this'. | |||
1384 | if (CXXThisTypeOverride.isNull()) | |||
1385 | return false; | |||
1386 | ||||
1387 | // Determine whether we're looking into a class that's currently being | |||
1388 | // defined. | |||
1389 | CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl(); | |||
1390 | return Class && Class->isBeingDefined(); | |||
1391 | } | |||
1392 | ||||
1393 | /// Parse construction of a specified type. | |||
1394 | /// Can be interpreted either as function-style casting ("int(x)") | |||
1395 | /// or class type construction ("ClassType(x,y,z)") | |||
1396 | /// or creation of a value-initialized type ("int()"). | |||
1397 | ExprResult | |||
1398 | Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep, | |||
1399 | SourceLocation LParenOrBraceLoc, | |||
1400 | MultiExprArg exprs, | |||
1401 | SourceLocation RParenOrBraceLoc, | |||
1402 | bool ListInitialization) { | |||
1403 | if (!TypeRep) | |||
1404 | return ExprError(); | |||
1405 | ||||
1406 | TypeSourceInfo *TInfo; | |||
1407 | QualType Ty = GetTypeFromParser(TypeRep, &TInfo); | |||
1408 | if (!TInfo) | |||
1409 | TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation()); | |||
1410 | ||||
1411 | auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs, | |||
1412 | RParenOrBraceLoc, ListInitialization); | |||
1413 | // Avoid creating a non-type-dependent expression that contains typos. | |||
1414 | // Non-type-dependent expressions are liable to be discarded without | |||
1415 | // checking for embedded typos. | |||
1416 | if (!Result.isInvalid() && Result.get()->isInstantiationDependent() && | |||
1417 | !Result.get()->isTypeDependent()) | |||
1418 | Result = CorrectDelayedTyposInExpr(Result.get()); | |||
1419 | else if (Result.isInvalid()) | |||
1420 | Result = CreateRecoveryExpr(TInfo->getTypeLoc().getBeginLoc(), | |||
1421 | RParenOrBraceLoc, exprs, Ty); | |||
1422 | return Result; | |||
1423 | } | |||
1424 | ||||
1425 | ExprResult | |||
1426 | Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo, | |||
1427 | SourceLocation LParenOrBraceLoc, | |||
1428 | MultiExprArg Exprs, | |||
1429 | SourceLocation RParenOrBraceLoc, | |||
1430 | bool ListInitialization) { | |||
1431 | QualType Ty = TInfo->getType(); | |||
1432 | SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc(); | |||
1433 | ||||
1434 | assert((!ListInitialization ||(static_cast <bool> ((!ListInitialization || (Exprs.size () == 1 && isa<InitListExpr>(Exprs[0]))) && "List initialization must have initializer list as expression." ) ? void (0) : __assert_fail ("(!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) && \"List initialization must have initializer list as expression.\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 1436, __extension__ __PRETTY_FUNCTION__)) | |||
1435 | (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&(static_cast <bool> ((!ListInitialization || (Exprs.size () == 1 && isa<InitListExpr>(Exprs[0]))) && "List initialization must have initializer list as expression." ) ? void (0) : __assert_fail ("(!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) && \"List initialization must have initializer list as expression.\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 1436, __extension__ __PRETTY_FUNCTION__)) | |||
1436 | "List initialization must have initializer list as expression.")(static_cast <bool> ((!ListInitialization || (Exprs.size () == 1 && isa<InitListExpr>(Exprs[0]))) && "List initialization must have initializer list as expression." ) ? void (0) : __assert_fail ("(!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) && \"List initialization must have initializer list as expression.\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 1436, __extension__ __PRETTY_FUNCTION__)); | |||
1437 | SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc); | |||
1438 | ||||
1439 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo); | |||
1440 | InitializationKind Kind = | |||
1441 | Exprs.size() | |||
1442 | ? ListInitialization | |||
1443 | ? InitializationKind::CreateDirectList( | |||
1444 | TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc) | |||
1445 | : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc, | |||
1446 | RParenOrBraceLoc) | |||
1447 | : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc, | |||
1448 | RParenOrBraceLoc); | |||
1449 | ||||
1450 | // C++1z [expr.type.conv]p1: | |||
1451 | // If the type is a placeholder for a deduced class type, [...perform class | |||
1452 | // template argument deduction...] | |||
1453 | DeducedType *Deduced = Ty->getContainedDeducedType(); | |||
1454 | if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) { | |||
1455 | Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity, | |||
1456 | Kind, Exprs); | |||
1457 | if (Ty.isNull()) | |||
1458 | return ExprError(); | |||
1459 | Entity = InitializedEntity::InitializeTemporary(TInfo, Ty); | |||
1460 | } | |||
1461 | ||||
1462 | if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) { | |||
1463 | // FIXME: CXXUnresolvedConstructExpr does not model list-initialization | |||
1464 | // directly. We work around this by dropping the locations of the braces. | |||
1465 | SourceRange Locs = ListInitialization | |||
1466 | ? SourceRange() | |||
1467 | : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc); | |||
1468 | return CXXUnresolvedConstructExpr::Create(Context, Ty.getNonReferenceType(), | |||
1469 | TInfo, Locs.getBegin(), Exprs, | |||
1470 | Locs.getEnd()); | |||
1471 | } | |||
1472 | ||||
1473 | // C++ [expr.type.conv]p1: | |||
1474 | // If the expression list is a parenthesized single expression, the type | |||
1475 | // conversion expression is equivalent (in definedness, and if defined in | |||
1476 | // meaning) to the corresponding cast expression. | |||
1477 | if (Exprs.size() == 1 && !ListInitialization && | |||
1478 | !isa<InitListExpr>(Exprs[0])) { | |||
1479 | Expr *Arg = Exprs[0]; | |||
1480 | return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg, | |||
1481 | RParenOrBraceLoc); | |||
1482 | } | |||
1483 | ||||
1484 | // For an expression of the form T(), T shall not be an array type. | |||
1485 | QualType ElemTy = Ty; | |||
1486 | if (Ty->isArrayType()) { | |||
1487 | if (!ListInitialization) | |||
1488 | return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type) | |||
1489 | << FullRange); | |||
1490 | ElemTy = Context.getBaseElementType(Ty); | |||
1491 | } | |||
1492 | ||||
1493 | // There doesn't seem to be an explicit rule against this but sanity demands | |||
1494 | // we only construct objects with object types. | |||
1495 | if (Ty->isFunctionType()) | |||
1496 | return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type) | |||
1497 | << Ty << FullRange); | |||
1498 | ||||
1499 | // C++17 [expr.type.conv]p2: | |||
1500 | // If the type is cv void and the initializer is (), the expression is a | |||
1501 | // prvalue of the specified type that performs no initialization. | |||
1502 | if (!Ty->isVoidType() && | |||
1503 | RequireCompleteType(TyBeginLoc, ElemTy, | |||
1504 | diag::err_invalid_incomplete_type_use, FullRange)) | |||
1505 | return ExprError(); | |||
1506 | ||||
1507 | // Otherwise, the expression is a prvalue of the specified type whose | |||
1508 | // result object is direct-initialized (11.6) with the initializer. | |||
1509 | InitializationSequence InitSeq(*this, Entity, Kind, Exprs); | |||
1510 | ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs); | |||
1511 | ||||
1512 | if (Result.isInvalid()) | |||
1513 | return Result; | |||
1514 | ||||
1515 | Expr *Inner = Result.get(); | |||
1516 | if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner)) | |||
1517 | Inner = BTE->getSubExpr(); | |||
1518 | if (!isa<CXXTemporaryObjectExpr>(Inner) && | |||
1519 | !isa<CXXScalarValueInitExpr>(Inner)) { | |||
1520 | // If we created a CXXTemporaryObjectExpr, that node also represents the | |||
1521 | // functional cast. Otherwise, create an explicit cast to represent | |||
1522 | // the syntactic form of a functional-style cast that was used here. | |||
1523 | // | |||
1524 | // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr | |||
1525 | // would give a more consistent AST representation than using a | |||
1526 | // CXXTemporaryObjectExpr. It's also weird that the functional cast | |||
1527 | // is sometimes handled by initialization and sometimes not. | |||
1528 | QualType ResultType = Result.get()->getType(); | |||
1529 | SourceRange Locs = ListInitialization | |||
1530 | ? SourceRange() | |||
1531 | : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc); | |||
1532 | Result = CXXFunctionalCastExpr::Create( | |||
1533 | Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp, | |||
1534 | Result.get(), /*Path=*/nullptr, CurFPFeatureOverrides(), | |||
1535 | Locs.getBegin(), Locs.getEnd()); | |||
1536 | } | |||
1537 | ||||
1538 | return Result; | |||
1539 | } | |||
1540 | ||||
1541 | bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) { | |||
1542 | // [CUDA] Ignore this function, if we can't call it. | |||
1543 | const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext); | |||
1544 | if (getLangOpts().CUDA) { | |||
1545 | auto CallPreference = IdentifyCUDAPreference(Caller, Method); | |||
1546 | // If it's not callable at all, it's not the right function. | |||
1547 | if (CallPreference < CFP_WrongSide) | |||
1548 | return false; | |||
1549 | if (CallPreference == CFP_WrongSide) { | |||
1550 | // Maybe. We have to check if there are better alternatives. | |||
1551 | DeclContext::lookup_result R = | |||
1552 | Method->getDeclContext()->lookup(Method->getDeclName()); | |||
1553 | for (const auto *D : R) { | |||
1554 | if (const auto *FD = dyn_cast<FunctionDecl>(D)) { | |||
1555 | if (IdentifyCUDAPreference(Caller, FD) > CFP_WrongSide) | |||
1556 | return false; | |||
1557 | } | |||
1558 | } | |||
1559 | // We've found no better variants. | |||
1560 | } | |||
1561 | } | |||
1562 | ||||
1563 | SmallVector<const FunctionDecl*, 4> PreventedBy; | |||
1564 | bool Result = Method->isUsualDeallocationFunction(PreventedBy); | |||
1565 | ||||
1566 | if (Result || !getLangOpts().CUDA || PreventedBy.empty()) | |||
1567 | return Result; | |||
1568 | ||||
1569 | // In case of CUDA, return true if none of the 1-argument deallocator | |||
1570 | // functions are actually callable. | |||
1571 | return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) { | |||
1572 | assert(FD->getNumParams() == 1 &&(static_cast <bool> (FD->getNumParams() == 1 && "Only single-operand functions should be in PreventedBy") ? void (0) : __assert_fail ("FD->getNumParams() == 1 && \"Only single-operand functions should be in PreventedBy\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 1573, __extension__ __PRETTY_FUNCTION__)) | |||
1573 | "Only single-operand functions should be in PreventedBy")(static_cast <bool> (FD->getNumParams() == 1 && "Only single-operand functions should be in PreventedBy") ? void (0) : __assert_fail ("FD->getNumParams() == 1 && \"Only single-operand functions should be in PreventedBy\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 1573, __extension__ __PRETTY_FUNCTION__)); | |||
1574 | return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice; | |||
1575 | }); | |||
1576 | } | |||
1577 | ||||
1578 | /// Determine whether the given function is a non-placement | |||
1579 | /// deallocation function. | |||
1580 | static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) { | |||
1581 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD)) | |||
1582 | return S.isUsualDeallocationFunction(Method); | |||
1583 | ||||
1584 | if (FD->getOverloadedOperator() != OO_Delete && | |||
1585 | FD->getOverloadedOperator() != OO_Array_Delete) | |||
1586 | return false; | |||
1587 | ||||
1588 | unsigned UsualParams = 1; | |||
1589 | ||||
1590 | if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() && | |||
1591 | S.Context.hasSameUnqualifiedType( | |||
1592 | FD->getParamDecl(UsualParams)->getType(), | |||
1593 | S.Context.getSizeType())) | |||
1594 | ++UsualParams; | |||
1595 | ||||
1596 | if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() && | |||
1597 | S.Context.hasSameUnqualifiedType( | |||
1598 | FD->getParamDecl(UsualParams)->getType(), | |||
1599 | S.Context.getTypeDeclType(S.getStdAlignValT()))) | |||
1600 | ++UsualParams; | |||
1601 | ||||
1602 | return UsualParams == FD->getNumParams(); | |||
1603 | } | |||
1604 | ||||
1605 | namespace { | |||
1606 | struct UsualDeallocFnInfo { | |||
1607 | UsualDeallocFnInfo() : Found(), FD(nullptr) {} | |||
1608 | UsualDeallocFnInfo(Sema &S, DeclAccessPair Found) | |||
1609 | : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())), | |||
1610 | Destroying(false), HasSizeT(false), HasAlignValT(false), | |||
1611 | CUDAPref(Sema::CFP_Native) { | |||
1612 | // A function template declaration is never a usual deallocation function. | |||
1613 | if (!FD) | |||
1614 | return; | |||
1615 | unsigned NumBaseParams = 1; | |||
1616 | if (FD->isDestroyingOperatorDelete()) { | |||
1617 | Destroying = true; | |||
1618 | ++NumBaseParams; | |||
1619 | } | |||
1620 | ||||
1621 | if (NumBaseParams < FD->getNumParams() && | |||
1622 | S.Context.hasSameUnqualifiedType( | |||
1623 | FD->getParamDecl(NumBaseParams)->getType(), | |||
1624 | S.Context.getSizeType())) { | |||
1625 | ++NumBaseParams; | |||
1626 | HasSizeT = true; | |||
1627 | } | |||
1628 | ||||
1629 | if (NumBaseParams < FD->getNumParams() && | |||
1630 | FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) { | |||
1631 | ++NumBaseParams; | |||
1632 | HasAlignValT = true; | |||
1633 | } | |||
1634 | ||||
1635 | // In CUDA, determine how much we'd like / dislike to call this. | |||
1636 | if (S.getLangOpts().CUDA) | |||
1637 | if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext)) | |||
1638 | CUDAPref = S.IdentifyCUDAPreference(Caller, FD); | |||
1639 | } | |||
1640 | ||||
1641 | explicit operator bool() const { return FD; } | |||
1642 | ||||
1643 | bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize, | |||
1644 | bool WantAlign) const { | |||
1645 | // C++ P0722: | |||
1646 | // A destroying operator delete is preferred over a non-destroying | |||
1647 | // operator delete. | |||
1648 | if (Destroying != Other.Destroying) | |||
1649 | return Destroying; | |||
1650 | ||||
1651 | // C++17 [expr.delete]p10: | |||
1652 | // If the type has new-extended alignment, a function with a parameter | |||
1653 | // of type std::align_val_t is preferred; otherwise a function without | |||
1654 | // such a parameter is preferred | |||
1655 | if (HasAlignValT != Other.HasAlignValT) | |||
1656 | return HasAlignValT == WantAlign; | |||
1657 | ||||
1658 | if (HasSizeT != Other.HasSizeT) | |||
1659 | return HasSizeT == WantSize; | |||
1660 | ||||
1661 | // Use CUDA call preference as a tiebreaker. | |||
1662 | return CUDAPref > Other.CUDAPref; | |||
1663 | } | |||
1664 | ||||
1665 | DeclAccessPair Found; | |||
1666 | FunctionDecl *FD; | |||
1667 | bool Destroying, HasSizeT, HasAlignValT; | |||
1668 | Sema::CUDAFunctionPreference CUDAPref; | |||
1669 | }; | |||
1670 | } | |||
1671 | ||||
1672 | /// Determine whether a type has new-extended alignment. This may be called when | |||
1673 | /// the type is incomplete (for a delete-expression with an incomplete pointee | |||
1674 | /// type), in which case it will conservatively return false if the alignment is | |||
1675 | /// not known. | |||
1676 | static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) { | |||
1677 | return S.getLangOpts().AlignedAllocation && | |||
1678 | S.getASTContext().getTypeAlignIfKnown(AllocType) > | |||
1679 | S.getASTContext().getTargetInfo().getNewAlign(); | |||
1680 | } | |||
1681 | ||||
1682 | /// Select the correct "usual" deallocation function to use from a selection of | |||
1683 | /// deallocation functions (either global or class-scope). | |||
1684 | static UsualDeallocFnInfo resolveDeallocationOverload( | |||
1685 | Sema &S, LookupResult &R, bool WantSize, bool WantAlign, | |||
1686 | llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) { | |||
1687 | UsualDeallocFnInfo Best; | |||
1688 | ||||
1689 | for (auto I = R.begin(), E = R.end(); I != E; ++I) { | |||
1690 | UsualDeallocFnInfo Info(S, I.getPair()); | |||
1691 | if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) || | |||
1692 | Info.CUDAPref == Sema::CFP_Never) | |||
1693 | continue; | |||
1694 | ||||
1695 | if (!Best) { | |||
1696 | Best = Info; | |||
1697 | if (BestFns) | |||
1698 | BestFns->push_back(Info); | |||
1699 | continue; | |||
1700 | } | |||
1701 | ||||
1702 | if (Best.isBetterThan(Info, WantSize, WantAlign)) | |||
1703 | continue; | |||
1704 | ||||
1705 | // If more than one preferred function is found, all non-preferred | |||
1706 | // functions are eliminated from further consideration. | |||
1707 | if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign)) | |||
1708 | BestFns->clear(); | |||
1709 | ||||
1710 | Best = Info; | |||
1711 | if (BestFns) | |||
1712 | BestFns->push_back(Info); | |||
1713 | } | |||
1714 | ||||
1715 | return Best; | |||
1716 | } | |||
1717 | ||||
1718 | /// Determine whether a given type is a class for which 'delete[]' would call | |||
1719 | /// a member 'operator delete[]' with a 'size_t' parameter. This implies that | |||
1720 | /// we need to store the array size (even if the type is | |||
1721 | /// trivially-destructible). | |||
1722 | static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc, | |||
1723 | QualType allocType) { | |||
1724 | const RecordType *record = | |||
1725 | allocType->getBaseElementTypeUnsafe()->getAs<RecordType>(); | |||
1726 | if (!record) return false; | |||
1727 | ||||
1728 | // Try to find an operator delete[] in class scope. | |||
1729 | ||||
1730 | DeclarationName deleteName = | |||
1731 | S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete); | |||
1732 | LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName); | |||
1733 | S.LookupQualifiedName(ops, record->getDecl()); | |||
1734 | ||||
1735 | // We're just doing this for information. | |||
1736 | ops.suppressDiagnostics(); | |||
1737 | ||||
1738 | // Very likely: there's no operator delete[]. | |||
1739 | if (ops.empty()) return false; | |||
1740 | ||||
1741 | // If it's ambiguous, it should be illegal to call operator delete[] | |||
1742 | // on this thing, so it doesn't matter if we allocate extra space or not. | |||
1743 | if (ops.isAmbiguous()) return false; | |||
1744 | ||||
1745 | // C++17 [expr.delete]p10: | |||
1746 | // If the deallocation functions have class scope, the one without a | |||
1747 | // parameter of type std::size_t is selected. | |||
1748 | auto Best = resolveDeallocationOverload( | |||
1749 | S, ops, /*WantSize*/false, | |||
1750 | /*WantAlign*/hasNewExtendedAlignment(S, allocType)); | |||
1751 | return Best && Best.HasSizeT; | |||
1752 | } | |||
1753 | ||||
1754 | /// Parsed a C++ 'new' expression (C++ 5.3.4). | |||
1755 | /// | |||
1756 | /// E.g.: | |||
1757 | /// @code new (memory) int[size][4] @endcode | |||
1758 | /// or | |||
1759 | /// @code ::new Foo(23, "hello") @endcode | |||
1760 | /// | |||
1761 | /// \param StartLoc The first location of the expression. | |||
1762 | /// \param UseGlobal True if 'new' was prefixed with '::'. | |||
1763 | /// \param PlacementLParen Opening paren of the placement arguments. | |||
1764 | /// \param PlacementArgs Placement new arguments. | |||
1765 | /// \param PlacementRParen Closing paren of the placement arguments. | |||
1766 | /// \param TypeIdParens If the type is in parens, the source range. | |||
1767 | /// \param D The type to be allocated, as well as array dimensions. | |||
1768 | /// \param Initializer The initializing expression or initializer-list, or null | |||
1769 | /// if there is none. | |||
1770 | ExprResult | |||
1771 | Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, | |||
1772 | SourceLocation PlacementLParen, MultiExprArg PlacementArgs, | |||
1773 | SourceLocation PlacementRParen, SourceRange TypeIdParens, | |||
1774 | Declarator &D, Expr *Initializer) { | |||
1775 | Optional<Expr *> ArraySize; | |||
1776 | // If the specified type is an array, unwrap it and save the expression. | |||
1777 | if (D.getNumTypeObjects() > 0 && | |||
1778 | D.getTypeObject(0).Kind == DeclaratorChunk::Array) { | |||
1779 | DeclaratorChunk &Chunk = D.getTypeObject(0); | |||
1780 | if (D.getDeclSpec().hasAutoTypeSpec()) | |||
1781 | return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto) | |||
1782 | << D.getSourceRange()); | |||
1783 | if (Chunk.Arr.hasStatic) | |||
1784 | return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new) | |||
1785 | << D.getSourceRange()); | |||
1786 | if (!Chunk.Arr.NumElts && !Initializer) | |||
1787 | return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size) | |||
1788 | << D.getSourceRange()); | |||
1789 | ||||
1790 | ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts); | |||
1791 | D.DropFirstTypeObject(); | |||
1792 | } | |||
1793 | ||||
1794 | // Every dimension shall be of constant size. | |||
1795 | if (ArraySize) { | |||
1796 | for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) { | |||
1797 | if (D.getTypeObject(I).Kind != DeclaratorChunk::Array) | |||
1798 | break; | |||
1799 | ||||
1800 | DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr; | |||
1801 | if (Expr *NumElts = (Expr *)Array.NumElts) { | |||
1802 | if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) { | |||
1803 | // FIXME: GCC permits constant folding here. We should either do so consistently | |||
1804 | // or not do so at all, rather than changing behavior in C++14 onwards. | |||
1805 | if (getLangOpts().CPlusPlus14) { | |||
1806 | // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator | |||
1807 | // shall be a converted constant expression (5.19) of type std::size_t | |||
1808 | // and shall evaluate to a strictly positive value. | |||
1809 | llvm::APSInt Value(Context.getIntWidth(Context.getSizeType())); | |||
1810 | Array.NumElts | |||
1811 | = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value, | |||
1812 | CCEK_ArrayBound) | |||
1813 | .get(); | |||
1814 | } else { | |||
1815 | Array.NumElts = | |||
1816 | VerifyIntegerConstantExpression( | |||
1817 | NumElts, nullptr, diag::err_new_array_nonconst, AllowFold) | |||
1818 | .get(); | |||
1819 | } | |||
1820 | if (!Array.NumElts) | |||
1821 | return ExprError(); | |||
1822 | } | |||
1823 | } | |||
1824 | } | |||
1825 | } | |||
1826 | ||||
1827 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr); | |||
1828 | QualType AllocType = TInfo->getType(); | |||
1829 | if (D.isInvalidType()) | |||
1830 | return ExprError(); | |||
1831 | ||||
1832 | SourceRange DirectInitRange; | |||
1833 | if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) | |||
1834 | DirectInitRange = List->getSourceRange(); | |||
1835 | ||||
1836 | return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal, | |||
1837 | PlacementLParen, PlacementArgs, PlacementRParen, | |||
1838 | TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange, | |||
1839 | Initializer); | |||
1840 | } | |||
1841 | ||||
1842 | static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style, | |||
1843 | Expr *Init) { | |||
1844 | if (!Init) | |||
1845 | return true; | |||
1846 | if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) | |||
1847 | return PLE->getNumExprs() == 0; | |||
1848 | if (isa<ImplicitValueInitExpr>(Init)) | |||
1849 | return true; | |||
1850 | else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) | |||
1851 | return !CCE->isListInitialization() && | |||
1852 | CCE->getConstructor()->isDefaultConstructor(); | |||
1853 | else if (Style == CXXNewExpr::ListInit) { | |||
1854 | assert(isa<InitListExpr>(Init) &&(static_cast <bool> (isa<InitListExpr>(Init) && "Shouldn't create list CXXConstructExprs for arrays.") ? void (0) : __assert_fail ("isa<InitListExpr>(Init) && \"Shouldn't create list CXXConstructExprs for arrays.\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 1855, __extension__ __PRETTY_FUNCTION__)) | |||
1855 | "Shouldn't create list CXXConstructExprs for arrays.")(static_cast <bool> (isa<InitListExpr>(Init) && "Shouldn't create list CXXConstructExprs for arrays.") ? void (0) : __assert_fail ("isa<InitListExpr>(Init) && \"Shouldn't create list CXXConstructExprs for arrays.\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 1855, __extension__ __PRETTY_FUNCTION__)); | |||
1856 | return true; | |||
1857 | } | |||
1858 | return false; | |||
1859 | } | |||
1860 | ||||
1861 | bool | |||
1862 | Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const { | |||
1863 | if (!getLangOpts().AlignedAllocationUnavailable) | |||
1864 | return false; | |||
1865 | if (FD.isDefined()) | |||
1866 | return false; | |||
1867 | Optional<unsigned> AlignmentParam; | |||
1868 | if (FD.isReplaceableGlobalAllocationFunction(&AlignmentParam) && | |||
1869 | AlignmentParam.hasValue()) | |||
1870 | return true; | |||
1871 | return false; | |||
1872 | } | |||
1873 | ||||
1874 | // Emit a diagnostic if an aligned allocation/deallocation function that is not | |||
1875 | // implemented in the standard library is selected. | |||
1876 | void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, | |||
1877 | SourceLocation Loc) { | |||
1878 | if (isUnavailableAlignedAllocationFunction(FD)) { | |||
1879 | const llvm::Triple &T = getASTContext().getTargetInfo().getTriple(); | |||
1880 | StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling( | |||
1881 | getASTContext().getTargetInfo().getPlatformName()); | |||
1882 | VersionTuple OSVersion = alignedAllocMinVersion(T.getOS()); | |||
1883 | ||||
1884 | OverloadedOperatorKind Kind = FD.getDeclName().getCXXOverloadedOperator(); | |||
1885 | bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete; | |||
1886 | Diag(Loc, diag::err_aligned_allocation_unavailable) | |||
1887 | << IsDelete << FD.getType().getAsString() << OSName | |||
1888 | << OSVersion.getAsString() << OSVersion.empty(); | |||
1889 | Diag(Loc, diag::note_silence_aligned_allocation_unavailable); | |||
1890 | } | |||
1891 | } | |||
1892 | ||||
1893 | ExprResult | |||
1894 | Sema::BuildCXXNew(SourceRange Range, bool UseGlobal, | |||
1895 | SourceLocation PlacementLParen, | |||
1896 | MultiExprArg PlacementArgs, | |||
1897 | SourceLocation PlacementRParen, | |||
1898 | SourceRange TypeIdParens, | |||
1899 | QualType AllocType, | |||
1900 | TypeSourceInfo *AllocTypeInfo, | |||
1901 | Optional<Expr *> ArraySize, | |||
1902 | SourceRange DirectInitRange, | |||
1903 | Expr *Initializer) { | |||
1904 | SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange(); | |||
1905 | SourceLocation StartLoc = Range.getBegin(); | |||
1906 | ||||
1907 | CXXNewExpr::InitializationStyle initStyle; | |||
1908 | if (DirectInitRange.isValid()) { | |||
1909 | assert(Initializer && "Have parens but no initializer.")(static_cast <bool> (Initializer && "Have parens but no initializer." ) ? void (0) : __assert_fail ("Initializer && \"Have parens but no initializer.\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 1909, __extension__ __PRETTY_FUNCTION__)); | |||
1910 | initStyle = CXXNewExpr::CallInit; | |||
1911 | } else if (Initializer && isa<InitListExpr>(Initializer)) | |||
1912 | initStyle = CXXNewExpr::ListInit; | |||
1913 | else { | |||
1914 | assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||(static_cast <bool> ((!Initializer || isa<ImplicitValueInitExpr >(Initializer) || isa<CXXConstructExpr>(Initializer) ) && "Initializer expression that cannot have been implicitly created." ) ? void (0) : __assert_fail ("(!Initializer || isa<ImplicitValueInitExpr>(Initializer) || isa<CXXConstructExpr>(Initializer)) && \"Initializer expression that cannot have been implicitly created.\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 1916, __extension__ __PRETTY_FUNCTION__)) | |||
1915 | isa<CXXConstructExpr>(Initializer)) &&(static_cast <bool> ((!Initializer || isa<ImplicitValueInitExpr >(Initializer) || isa<CXXConstructExpr>(Initializer) ) && "Initializer expression that cannot have been implicitly created." ) ? void (0) : __assert_fail ("(!Initializer || isa<ImplicitValueInitExpr>(Initializer) || isa<CXXConstructExpr>(Initializer)) && \"Initializer expression that cannot have been implicitly created.\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 1916, __extension__ __PRETTY_FUNCTION__)) | |||
1916 | "Initializer expression that cannot have been implicitly created.")(static_cast <bool> ((!Initializer || isa<ImplicitValueInitExpr >(Initializer) || isa<CXXConstructExpr>(Initializer) ) && "Initializer expression that cannot have been implicitly created." ) ? void (0) : __assert_fail ("(!Initializer || isa<ImplicitValueInitExpr>(Initializer) || isa<CXXConstructExpr>(Initializer)) && \"Initializer expression that cannot have been implicitly created.\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 1916, __extension__ __PRETTY_FUNCTION__)); | |||
1917 | initStyle = CXXNewExpr::NoInit; | |||
1918 | } | |||
1919 | ||||
1920 | Expr **Inits = &Initializer; | |||
1921 | unsigned NumInits = Initializer ? 1 : 0; | |||
1922 | if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) { | |||
1923 | assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init")(static_cast <bool> (initStyle == CXXNewExpr::CallInit && "paren init for non-call init") ? void (0) : __assert_fail ( "initStyle == CXXNewExpr::CallInit && \"paren init for non-call init\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 1923, __extension__ __PRETTY_FUNCTION__)); | |||
1924 | Inits = List->getExprs(); | |||
1925 | NumInits = List->getNumExprs(); | |||
1926 | } | |||
1927 | ||||
1928 | // C++11 [expr.new]p15: | |||
1929 | // A new-expression that creates an object of type T initializes that | |||
1930 | // object as follows: | |||
1931 | InitializationKind Kind | |||
1932 | // - If the new-initializer is omitted, the object is default- | |||
1933 | // initialized (8.5); if no initialization is performed, | |||
1934 | // the object has indeterminate value | |||
1935 | = initStyle == CXXNewExpr::NoInit | |||
1936 | ? InitializationKind::CreateDefault(TypeRange.getBegin()) | |||
1937 | // - Otherwise, the new-initializer is interpreted according to | |||
1938 | // the | |||
1939 | // initialization rules of 8.5 for direct-initialization. | |||
1940 | : initStyle == CXXNewExpr::ListInit | |||
1941 | ? InitializationKind::CreateDirectList( | |||
1942 | TypeRange.getBegin(), Initializer->getBeginLoc(), | |||
1943 | Initializer->getEndLoc()) | |||
1944 | : InitializationKind::CreateDirect(TypeRange.getBegin(), | |||
1945 | DirectInitRange.getBegin(), | |||
1946 | DirectInitRange.getEnd()); | |||
1947 | ||||
1948 | // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for. | |||
1949 | auto *Deduced = AllocType->getContainedDeducedType(); | |||
1950 | if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) { | |||
1951 | if (ArraySize) | |||
1952 | return ExprError( | |||
1953 | Diag(ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(), | |||
1954 | diag::err_deduced_class_template_compound_type) | |||
1955 | << /*array*/ 2 | |||
1956 | << (ArraySize ? (*ArraySize)->getSourceRange() : TypeRange)); | |||
1957 | ||||
1958 | InitializedEntity Entity | |||
1959 | = InitializedEntity::InitializeNew(StartLoc, AllocType); | |||
1960 | AllocType = DeduceTemplateSpecializationFromInitializer( | |||
1961 | AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits)); | |||
1962 | if (AllocType.isNull()) | |||
1963 | return ExprError(); | |||
1964 | } else if (Deduced) { | |||
1965 | bool Braced = (initStyle == CXXNewExpr::ListInit); | |||
1966 | if (NumInits == 1) { | |||
1967 | if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) { | |||
1968 | Inits = p->getInits(); | |||
1969 | NumInits = p->getNumInits(); | |||
1970 | Braced = true; | |||
1971 | } | |||
1972 | } | |||
1973 | ||||
1974 | if (initStyle == CXXNewExpr::NoInit || NumInits == 0) | |||
1975 | return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg) | |||
1976 | << AllocType << TypeRange); | |||
1977 | if (NumInits > 1) { | |||
1978 | Expr *FirstBad = Inits[1]; | |||
1979 | return ExprError(Diag(FirstBad->getBeginLoc(), | |||
1980 | diag::err_auto_new_ctor_multiple_expressions) | |||
1981 | << AllocType << TypeRange); | |||
1982 | } | |||
1983 | if (Braced && !getLangOpts().CPlusPlus17) | |||
1984 | Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init) | |||
1985 | << AllocType << TypeRange; | |||
1986 | Expr *Deduce = Inits[0]; | |||
1987 | QualType DeducedType; | |||
1988 | if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed) | |||
1989 | return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure) | |||
1990 | << AllocType << Deduce->getType() | |||
1991 | << TypeRange << Deduce->getSourceRange()); | |||
1992 | if (DeducedType.isNull()) | |||
1993 | return ExprError(); | |||
1994 | AllocType = DeducedType; | |||
1995 | } | |||
1996 | ||||
1997 | // Per C++0x [expr.new]p5, the type being constructed may be a | |||
1998 | // typedef of an array type. | |||
1999 | if (!ArraySize) { | |||
2000 | if (const ConstantArrayType *Array | |||
2001 | = Context.getAsConstantArrayType(AllocType)) { | |||
2002 | ArraySize = IntegerLiteral::Create(Context, Array->getSize(), | |||
2003 | Context.getSizeType(), | |||
2004 | TypeRange.getEnd()); | |||
2005 | AllocType = Array->getElementType(); | |||
2006 | } | |||
2007 | } | |||
2008 | ||||
2009 | if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange)) | |||
2010 | return ExprError(); | |||
2011 | ||||
2012 | // In ARC, infer 'retaining' for the allocated | |||
2013 | if (getLangOpts().ObjCAutoRefCount && | |||
2014 | AllocType.getObjCLifetime() == Qualifiers::OCL_None && | |||
2015 | AllocType->isObjCLifetimeType()) { | |||
2016 | AllocType = Context.getLifetimeQualifiedType(AllocType, | |||
2017 | AllocType->getObjCARCImplicitLifetime()); | |||
2018 | } | |||
2019 | ||||
2020 | QualType ResultType = Context.getPointerType(AllocType); | |||
2021 | ||||
2022 | if (ArraySize && *ArraySize && | |||
2023 | (*ArraySize)->getType()->isNonOverloadPlaceholderType()) { | |||
2024 | ExprResult result = CheckPlaceholderExpr(*ArraySize); | |||
2025 | if (result.isInvalid()) return ExprError(); | |||
2026 | ArraySize = result.get(); | |||
2027 | } | |||
2028 | // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have | |||
2029 | // integral or enumeration type with a non-negative value." | |||
2030 | // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped | |||
2031 | // enumeration type, or a class type for which a single non-explicit | |||
2032 | // conversion function to integral or unscoped enumeration type exists. | |||
2033 | // C++1y [expr.new]p6: The expression [...] is implicitly converted to | |||
2034 | // std::size_t. | |||
2035 | llvm::Optional<uint64_t> KnownArraySize; | |||
2036 | if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) { | |||
2037 | ExprResult ConvertedSize; | |||
2038 | if (getLangOpts().CPlusPlus14) { | |||
2039 | assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?")(static_cast <bool> (Context.getTargetInfo().getIntWidth () && "Builtin type of size 0?") ? void (0) : __assert_fail ("Context.getTargetInfo().getIntWidth() && \"Builtin type of size 0?\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 2039, __extension__ __PRETTY_FUNCTION__)); | |||
2040 | ||||
2041 | ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(), | |||
2042 | AA_Converting); | |||
2043 | ||||
2044 | if (!ConvertedSize.isInvalid() && | |||
2045 | (*ArraySize)->getType()->getAs<RecordType>()) | |||
2046 | // Diagnose the compatibility of this conversion. | |||
2047 | Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion) | |||
2048 | << (*ArraySize)->getType() << 0 << "'size_t'"; | |||
2049 | } else { | |||
2050 | class SizeConvertDiagnoser : public ICEConvertDiagnoser { | |||
2051 | protected: | |||
2052 | Expr *ArraySize; | |||
2053 | ||||
2054 | public: | |||
2055 | SizeConvertDiagnoser(Expr *ArraySize) | |||
2056 | : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false), | |||
2057 | ArraySize(ArraySize) {} | |||
2058 | ||||
2059 | SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, | |||
2060 | QualType T) override { | |||
2061 | return S.Diag(Loc, diag::err_array_size_not_integral) | |||
2062 | << S.getLangOpts().CPlusPlus11 << T; | |||
2063 | } | |||
2064 | ||||
2065 | SemaDiagnosticBuilder diagnoseIncomplete( | |||
2066 | Sema &S, SourceLocation Loc, QualType T) override { | |||
2067 | return S.Diag(Loc, diag::err_array_size_incomplete_type) | |||
2068 | << T << ArraySize->getSourceRange(); | |||
2069 | } | |||
2070 | ||||
2071 | SemaDiagnosticBuilder diagnoseExplicitConv( | |||
2072 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { | |||
2073 | return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy; | |||
2074 | } | |||
2075 | ||||
2076 | SemaDiagnosticBuilder noteExplicitConv( | |||
2077 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { | |||
2078 | return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) | |||
2079 | << ConvTy->isEnumeralType() << ConvTy; | |||
2080 | } | |||
2081 | ||||
2082 | SemaDiagnosticBuilder diagnoseAmbiguous( | |||
2083 | Sema &S, SourceLocation Loc, QualType T) override { | |||
2084 | return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T; | |||
2085 | } | |||
2086 | ||||
2087 | SemaDiagnosticBuilder noteAmbiguous( | |||
2088 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { | |||
2089 | return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) | |||
2090 | << ConvTy->isEnumeralType() << ConvTy; | |||
2091 | } | |||
2092 | ||||
2093 | SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, | |||
2094 | QualType T, | |||
2095 | QualType ConvTy) override { | |||
2096 | return S.Diag(Loc, | |||
2097 | S.getLangOpts().CPlusPlus11 | |||
2098 | ? diag::warn_cxx98_compat_array_size_conversion | |||
2099 | : diag::ext_array_size_conversion) | |||
2100 | << T << ConvTy->isEnumeralType() << ConvTy; | |||
2101 | } | |||
2102 | } SizeDiagnoser(*ArraySize); | |||
2103 | ||||
2104 | ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize, | |||
2105 | SizeDiagnoser); | |||
2106 | } | |||
2107 | if (ConvertedSize.isInvalid()) | |||
2108 | return ExprError(); | |||
2109 | ||||
2110 | ArraySize = ConvertedSize.get(); | |||
2111 | QualType SizeType = (*ArraySize)->getType(); | |||
2112 | ||||
2113 | if (!SizeType->isIntegralOrUnscopedEnumerationType()) | |||
2114 | return ExprError(); | |||
2115 | ||||
2116 | // C++98 [expr.new]p7: | |||
2117 | // The expression in a direct-new-declarator shall have integral type | |||
2118 | // with a non-negative value. | |||
2119 | // | |||
2120 | // Let's see if this is a constant < 0. If so, we reject it out of hand, | |||
2121 | // per CWG1464. Otherwise, if it's not a constant, we must have an | |||
2122 | // unparenthesized array type. | |||
2123 | if (!(*ArraySize)->isValueDependent()) { | |||
2124 | // We've already performed any required implicit conversion to integer or | |||
2125 | // unscoped enumeration type. | |||
2126 | // FIXME: Per CWG1464, we are required to check the value prior to | |||
2127 | // converting to size_t. This will never find a negative array size in | |||
2128 | // C++14 onwards, because Value is always unsigned here! | |||
2129 | if (Optional<llvm::APSInt> Value = | |||
2130 | (*ArraySize)->getIntegerConstantExpr(Context)) { | |||
2131 | if (Value->isSigned() && Value->isNegative()) { | |||
2132 | return ExprError(Diag((*ArraySize)->getBeginLoc(), | |||
2133 | diag::err_typecheck_negative_array_size) | |||
2134 | << (*ArraySize)->getSourceRange()); | |||
2135 | } | |||
2136 | ||||
2137 | if (!AllocType->isDependentType()) { | |||
2138 | unsigned ActiveSizeBits = ConstantArrayType::getNumAddressingBits( | |||
2139 | Context, AllocType, *Value); | |||
2140 | if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) | |||
2141 | return ExprError( | |||
2142 | Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large) | |||
2143 | << Value->toString(10) << (*ArraySize)->getSourceRange()); | |||
2144 | } | |||
2145 | ||||
2146 | KnownArraySize = Value->getZExtValue(); | |||
2147 | } else if (TypeIdParens.isValid()) { | |||
2148 | // Can't have dynamic array size when the type-id is in parentheses. | |||
2149 | Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst) | |||
2150 | << (*ArraySize)->getSourceRange() | |||
2151 | << FixItHint::CreateRemoval(TypeIdParens.getBegin()) | |||
2152 | << FixItHint::CreateRemoval(TypeIdParens.getEnd()); | |||
2153 | ||||
2154 | TypeIdParens = SourceRange(); | |||
2155 | } | |||
2156 | } | |||
2157 | ||||
2158 | // Note that we do *not* convert the argument in any way. It can | |||
2159 | // be signed, larger than size_t, whatever. | |||
2160 | } | |||
2161 | ||||
2162 | FunctionDecl *OperatorNew = nullptr; | |||
2163 | FunctionDecl *OperatorDelete = nullptr; | |||
2164 | unsigned Alignment = | |||
2165 | AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType); | |||
2166 | unsigned NewAlignment = Context.getTargetInfo().getNewAlign(); | |||
2167 | bool PassAlignment = getLangOpts().AlignedAllocation && | |||
2168 | Alignment > NewAlignment; | |||
2169 | ||||
2170 | AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both; | |||
2171 | if (!AllocType->isDependentType() && | |||
2172 | !Expr::hasAnyTypeDependentArguments(PlacementArgs) && | |||
2173 | FindAllocationFunctions( | |||
2174 | StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope, | |||
2175 | AllocType, ArraySize.hasValue(), PassAlignment, PlacementArgs, | |||
2176 | OperatorNew, OperatorDelete)) | |||
2177 | return ExprError(); | |||
2178 | ||||
2179 | // If this is an array allocation, compute whether the usual array | |||
2180 | // deallocation function for the type has a size_t parameter. | |||
2181 | bool UsualArrayDeleteWantsSize = false; | |||
2182 | if (ArraySize && !AllocType->isDependentType()) | |||
2183 | UsualArrayDeleteWantsSize = | |||
2184 | doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType); | |||
2185 | ||||
2186 | SmallVector<Expr *, 8> AllPlaceArgs; | |||
2187 | if (OperatorNew) { | |||
2188 | auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>(); | |||
2189 | VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction | |||
2190 | : VariadicDoesNotApply; | |||
2191 | ||||
2192 | // We've already converted the placement args, just fill in any default | |||
2193 | // arguments. Skip the first parameter because we don't have a corresponding | |||
2194 | // argument. Skip the second parameter too if we're passing in the | |||
2195 | // alignment; we've already filled it in. | |||
2196 | unsigned NumImplicitArgs = PassAlignment ? 2 : 1; | |||
2197 | if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto, | |||
2198 | NumImplicitArgs, PlacementArgs, AllPlaceArgs, | |||
2199 | CallType)) | |||
2200 | return ExprError(); | |||
2201 | ||||
2202 | if (!AllPlaceArgs.empty()) | |||
2203 | PlacementArgs = AllPlaceArgs; | |||
2204 | ||||
2205 | // We would like to perform some checking on the given `operator new` call, | |||
2206 | // but the PlacementArgs does not contain the implicit arguments, | |||
2207 | // namely allocation size and maybe allocation alignment, | |||
2208 | // so we need to conjure them. | |||
2209 | ||||
2210 | QualType SizeTy = Context.getSizeType(); | |||
2211 | unsigned SizeTyWidth = Context.getTypeSize(SizeTy); | |||
2212 | ||||
2213 | llvm::APInt SingleEltSize( | |||
2214 | SizeTyWidth, Context.getTypeSizeInChars(AllocType).getQuantity()); | |||
2215 | ||||
2216 | // How many bytes do we want to allocate here? | |||
2217 | llvm::Optional<llvm::APInt> AllocationSize; | |||
2218 | if (!ArraySize.hasValue() && !AllocType->isDependentType()) { | |||
2219 | // For non-array operator new, we only want to allocate one element. | |||
2220 | AllocationSize = SingleEltSize; | |||
2221 | } else if (KnownArraySize.hasValue() && !AllocType->isDependentType()) { | |||
2222 | // For array operator new, only deal with static array size case. | |||
2223 | bool Overflow; | |||
2224 | AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize) | |||
2225 | .umul_ov(SingleEltSize, Overflow); | |||
2226 | (void)Overflow; | |||
2227 | assert((static_cast <bool> (!Overflow && "Expected that all the overflows would have been handled already." ) ? void (0) : __assert_fail ("!Overflow && \"Expected that all the overflows would have been handled already.\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 2229, __extension__ __PRETTY_FUNCTION__)) | |||
2228 | !Overflow &&(static_cast <bool> (!Overflow && "Expected that all the overflows would have been handled already." ) ? void (0) : __assert_fail ("!Overflow && \"Expected that all the overflows would have been handled already.\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 2229, __extension__ __PRETTY_FUNCTION__)) | |||
2229 | "Expected that all the overflows would have been handled already.")(static_cast <bool> (!Overflow && "Expected that all the overflows would have been handled already." ) ? void (0) : __assert_fail ("!Overflow && \"Expected that all the overflows would have been handled already.\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 2229, __extension__ __PRETTY_FUNCTION__)); | |||
2230 | } | |||
2231 | ||||
2232 | IntegerLiteral AllocationSizeLiteral( | |||
2233 | Context, | |||
2234 | AllocationSize.getValueOr(llvm::APInt::getNullValue(SizeTyWidth)), | |||
2235 | SizeTy, SourceLocation()); | |||
2236 | // Otherwise, if we failed to constant-fold the allocation size, we'll | |||
2237 | // just give up and pass-in something opaque, that isn't a null pointer. | |||
2238 | OpaqueValueExpr OpaqueAllocationSize(SourceLocation(), SizeTy, VK_RValue, | |||
2239 | OK_Ordinary, /*SourceExpr=*/nullptr); | |||
2240 | ||||
2241 | // Let's synthesize the alignment argument in case we will need it. | |||
2242 | // Since we *really* want to allocate these on stack, this is slightly ugly | |||
2243 | // because there might not be a `std::align_val_t` type. | |||
2244 | EnumDecl *StdAlignValT = getStdAlignValT(); | |||
2245 | QualType AlignValT = | |||
2246 | StdAlignValT ? Context.getTypeDeclType(StdAlignValT) : SizeTy; | |||
2247 | IntegerLiteral AlignmentLiteral( | |||
2248 | Context, | |||
2249 | llvm::APInt(Context.getTypeSize(SizeTy), | |||
2250 | Alignment / Context.getCharWidth()), | |||
2251 | SizeTy, SourceLocation()); | |||
2252 | ImplicitCastExpr DesiredAlignment(ImplicitCastExpr::OnStack, AlignValT, | |||
2253 | CK_IntegralCast, &AlignmentLiteral, | |||
2254 | VK_RValue, FPOptionsOverride()); | |||
2255 | ||||
2256 | // Adjust placement args by prepending conjured size and alignment exprs. | |||
2257 | llvm::SmallVector<Expr *, 8> CallArgs; | |||
2258 | CallArgs.reserve(NumImplicitArgs + PlacementArgs.size()); | |||
2259 | CallArgs.emplace_back(AllocationSize.hasValue() | |||
2260 | ? static_cast<Expr *>(&AllocationSizeLiteral) | |||
2261 | : &OpaqueAllocationSize); | |||
2262 | if (PassAlignment) | |||
2263 | CallArgs.emplace_back(&DesiredAlignment); | |||
2264 | CallArgs.insert(CallArgs.end(), PlacementArgs.begin(), PlacementArgs.end()); | |||
2265 | ||||
2266 | DiagnoseSentinelCalls(OperatorNew, PlacementLParen, CallArgs); | |||
2267 | ||||
2268 | checkCall(OperatorNew, Proto, /*ThisArg=*/nullptr, CallArgs, | |||
2269 | /*IsMemberFunction=*/false, StartLoc, Range, CallType); | |||
2270 | ||||
2271 | // Warn if the type is over-aligned and is being allocated by (unaligned) | |||
2272 | // global operator new. | |||
2273 | if (PlacementArgs.empty() && !PassAlignment && | |||
2274 | (OperatorNew->isImplicit() || | |||
2275 | (OperatorNew->getBeginLoc().isValid() && | |||
2276 | getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) { | |||
2277 | if (Alignment > NewAlignment) | |||
2278 | Diag(StartLoc, diag::warn_overaligned_type) | |||
2279 | << AllocType | |||
2280 | << unsigned(Alignment / Context.getCharWidth()) | |||
2281 | << unsigned(NewAlignment / Context.getCharWidth()); | |||
2282 | } | |||
2283 | } | |||
2284 | ||||
2285 | // Array 'new' can't have any initializers except empty parentheses. | |||
2286 | // Initializer lists are also allowed, in C++11. Rely on the parser for the | |||
2287 | // dialect distinction. | |||
2288 | if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) { | |||
2289 | SourceRange InitRange(Inits[0]->getBeginLoc(), | |||
2290 | Inits[NumInits - 1]->getEndLoc()); | |||
2291 | Diag(StartLoc, diag::err_new_array_init_args) << InitRange; | |||
2292 | return ExprError(); | |||
2293 | } | |||
2294 | ||||
2295 | // If we can perform the initialization, and we've not already done so, | |||
2296 | // do it now. | |||
2297 | if (!AllocType->isDependentType() && | |||
2298 | !Expr::hasAnyTypeDependentArguments( | |||
2299 | llvm::makeArrayRef(Inits, NumInits))) { | |||
2300 | // The type we initialize is the complete type, including the array bound. | |||
2301 | QualType InitType; | |||
2302 | if (KnownArraySize) | |||
2303 | InitType = Context.getConstantArrayType( | |||
2304 | AllocType, | |||
2305 | llvm::APInt(Context.getTypeSize(Context.getSizeType()), | |||
2306 | *KnownArraySize), | |||
2307 | *ArraySize, ArrayType::Normal, 0); | |||
2308 | else if (ArraySize) | |||
2309 | InitType = | |||
2310 | Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0); | |||
2311 | else | |||
2312 | InitType = AllocType; | |||
2313 | ||||
2314 | InitializedEntity Entity | |||
2315 | = InitializedEntity::InitializeNew(StartLoc, InitType); | |||
2316 | InitializationSequence InitSeq(*this, Entity, Kind, | |||
2317 | MultiExprArg(Inits, NumInits)); | |||
2318 | ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, | |||
2319 | MultiExprArg(Inits, NumInits)); | |||
2320 | if (FullInit.isInvalid()) | |||
2321 | return ExprError(); | |||
2322 | ||||
2323 | // FullInit is our initializer; strip off CXXBindTemporaryExprs, because | |||
2324 | // we don't want the initialized object to be destructed. | |||
2325 | // FIXME: We should not create these in the first place. | |||
2326 | if (CXXBindTemporaryExpr *Binder = | |||
2327 | dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get())) | |||
2328 | FullInit = Binder->getSubExpr(); | |||
2329 | ||||
2330 | Initializer = FullInit.get(); | |||
2331 | ||||
2332 | // FIXME: If we have a KnownArraySize, check that the array bound of the | |||
2333 | // initializer is no greater than that constant value. | |||
2334 | ||||
2335 | if (ArraySize && !*ArraySize) { | |||
2336 | auto *CAT = Context.getAsConstantArrayType(Initializer->getType()); | |||
2337 | if (CAT) { | |||
2338 | // FIXME: Track that the array size was inferred rather than explicitly | |||
2339 | // specified. | |||
2340 | ArraySize = IntegerLiteral::Create( | |||
2341 | Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd()); | |||
2342 | } else { | |||
2343 | Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init) | |||
2344 | << Initializer->getSourceRange(); | |||
2345 | } | |||
2346 | } | |||
2347 | } | |||
2348 | ||||
2349 | // Mark the new and delete operators as referenced. | |||
2350 | if (OperatorNew) { | |||
2351 | if (DiagnoseUseOfDecl(OperatorNew, StartLoc)) | |||
2352 | return ExprError(); | |||
2353 | MarkFunctionReferenced(StartLoc, OperatorNew); | |||
2354 | } | |||
2355 | if (OperatorDelete) { | |||
2356 | if (DiagnoseUseOfDecl(OperatorDelete, StartLoc)) | |||
2357 | return ExprError(); | |||
2358 | MarkFunctionReferenced(StartLoc, OperatorDelete); | |||
2359 | } | |||
2360 | ||||
2361 | return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete, | |||
2362 | PassAlignment, UsualArrayDeleteWantsSize, | |||
2363 | PlacementArgs, TypeIdParens, ArraySize, initStyle, | |||
2364 | Initializer, ResultType, AllocTypeInfo, Range, | |||
2365 | DirectInitRange); | |||
2366 | } | |||
2367 | ||||
2368 | /// Checks that a type is suitable as the allocated type | |||
2369 | /// in a new-expression. | |||
2370 | bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc, | |||
2371 | SourceRange R) { | |||
2372 | // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an | |||
2373 | // abstract class type or array thereof. | |||
2374 | if (AllocType->isFunctionType()) | |||
2375 | return Diag(Loc, diag::err_bad_new_type) | |||
2376 | << AllocType << 0 << R; | |||
2377 | else if (AllocType->isReferenceType()) | |||
2378 | return Diag(Loc, diag::err_bad_new_type) | |||
2379 | << AllocType << 1 << R; | |||
2380 | else if (!AllocType->isDependentType() && | |||
2381 | RequireCompleteSizedType( | |||
2382 | Loc, AllocType, diag::err_new_incomplete_or_sizeless_type, R)) | |||
2383 | return true; | |||
2384 | else if (RequireNonAbstractType(Loc, AllocType, | |||
2385 | diag::err_allocation_of_abstract_type)) | |||
2386 | return true; | |||
2387 | else if (AllocType->isVariablyModifiedType()) | |||
2388 | return Diag(Loc, diag::err_variably_modified_new_type) | |||
2389 | << AllocType; | |||
2390 | else if (AllocType.getAddressSpace() != LangAS::Default && | |||
2391 | !getLangOpts().OpenCLCPlusPlus) | |||
2392 | return Diag(Loc, diag::err_address_space_qualified_new) | |||
2393 | << AllocType.getUnqualifiedType() | |||
2394 | << AllocType.getQualifiers().getAddressSpaceAttributePrintValue(); | |||
2395 | else if (getLangOpts().ObjCAutoRefCount) { | |||
2396 | if (const ArrayType *AT = Context.getAsArrayType(AllocType)) { | |||
2397 | QualType BaseAllocType = Context.getBaseElementType(AT); | |||
2398 | if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None && | |||
2399 | BaseAllocType->isObjCLifetimeType()) | |||
2400 | return Diag(Loc, diag::err_arc_new_array_without_ownership) | |||
2401 | << BaseAllocType; | |||
2402 | } | |||
2403 | } | |||
2404 | ||||
2405 | return false; | |||
2406 | } | |||
2407 | ||||
2408 | static bool resolveAllocationOverload( | |||
2409 | Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args, | |||
2410 | bool &PassAlignment, FunctionDecl *&Operator, | |||
2411 | OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) { | |||
2412 | OverloadCandidateSet Candidates(R.getNameLoc(), | |||
2413 | OverloadCandidateSet::CSK_Normal); | |||
2414 | for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end(); | |||
2415 | Alloc != AllocEnd; ++Alloc) { | |||
2416 | // Even member operator new/delete are implicitly treated as | |||
2417 | // static, so don't use AddMemberCandidate. | |||
2418 | NamedDecl *D = (*Alloc)->getUnderlyingDecl(); | |||
2419 | ||||
2420 | if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { | |||
2421 | S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(), | |||
2422 | /*ExplicitTemplateArgs=*/nullptr, Args, | |||
2423 | Candidates, | |||
2424 | /*SuppressUserConversions=*/false); | |||
2425 | continue; | |||
2426 | } | |||
2427 | ||||
2428 | FunctionDecl *Fn = cast<FunctionDecl>(D); | |||
2429 | S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates, | |||
2430 | /*SuppressUserConversions=*/false); | |||
2431 | } | |||
2432 | ||||
2433 | // Do the resolution. | |||
2434 | OverloadCandidateSet::iterator Best; | |||
2435 | switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) { | |||
2436 | case OR_Success: { | |||
2437 | // Got one! | |||
2438 | FunctionDecl *FnDecl = Best->Function; | |||
2439 | if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(), | |||
2440 | Best->FoundDecl) == Sema::AR_inaccessible) | |||
2441 | return true; | |||
2442 | ||||
2443 | Operator = FnDecl; | |||
2444 | return false; | |||
2445 | } | |||
2446 | ||||
2447 | case OR_No_Viable_Function: | |||
2448 | // C++17 [expr.new]p13: | |||
2449 | // If no matching function is found and the allocated object type has | |||
2450 | // new-extended alignment, the alignment argument is removed from the | |||
2451 | // argument list, and overload resolution is performed again. | |||
2452 | if (PassAlignment) { | |||
2453 | PassAlignment = false; | |||
2454 | AlignArg = Args[1]; | |||
2455 | Args.erase(Args.begin() + 1); | |||
2456 | return resolveAllocationOverload(S, R, Range, Args, PassAlignment, | |||
2457 | Operator, &Candidates, AlignArg, | |||
2458 | Diagnose); | |||
2459 | } | |||
2460 | ||||
2461 | // MSVC will fall back on trying to find a matching global operator new | |||
2462 | // if operator new[] cannot be found. Also, MSVC will leak by not | |||
2463 | // generating a call to operator delete or operator delete[], but we | |||
2464 | // will not replicate that bug. | |||
2465 | // FIXME: Find out how this interacts with the std::align_val_t fallback | |||
2466 | // once MSVC implements it. | |||
2467 | if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New && | |||
2468 | S.Context.getLangOpts().MSVCCompat) { | |||
2469 | R.clear(); | |||
2470 | R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New)); | |||
2471 | S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl()); | |||
2472 | // FIXME: This will give bad diagnostics pointing at the wrong functions. | |||
2473 | return resolveAllocationOverload(S, R, Range, Args, PassAlignment, | |||
2474 | Operator, /*Candidates=*/nullptr, | |||
2475 | /*AlignArg=*/nullptr, Diagnose); | |||
2476 | } | |||
2477 | ||||
2478 | if (Diagnose) { | |||
2479 | // If this is an allocation of the form 'new (p) X' for some object | |||
2480 | // pointer p (or an expression that will decay to such a pointer), | |||
2481 | // diagnose the missing inclusion of <new>. | |||
2482 | if (!R.isClassLookup() && Args.size() == 2 && | |||
2483 | (Args[1]->getType()->isObjectPointerType() || | |||
2484 | Args[1]->getType()->isArrayType())) { | |||
2485 | S.Diag(R.getNameLoc(), diag::err_need_header_before_placement_new) | |||
2486 | << R.getLookupName() << Range; | |||
2487 | // Listing the candidates is unlikely to be useful; skip it. | |||
2488 | return true; | |||
2489 | } | |||
2490 | ||||
2491 | // Finish checking all candidates before we note any. This checking can | |||
2492 | // produce additional diagnostics so can't be interleaved with our | |||
2493 | // emission of notes. | |||
2494 | // | |||
2495 | // For an aligned allocation, separately check the aligned and unaligned | |||
2496 | // candidates with their respective argument lists. | |||
2497 | SmallVector<OverloadCandidate*, 32> Cands; | |||
2498 | SmallVector<OverloadCandidate*, 32> AlignedCands; | |||
2499 | llvm::SmallVector<Expr*, 4> AlignedArgs; | |||
2500 | if (AlignedCandidates) { | |||
2501 | auto IsAligned = [](OverloadCandidate &C) { | |||
2502 | return C.Function->getNumParams() > 1 && | |||
2503 | C.Function->getParamDecl(1)->getType()->isAlignValT(); | |||
2504 | }; | |||
2505 | auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); }; | |||
2506 | ||||
2507 | AlignedArgs.reserve(Args.size() + 1); | |||
2508 | AlignedArgs.push_back(Args[0]); | |||
2509 | AlignedArgs.push_back(AlignArg); | |||
2510 | AlignedArgs.append(Args.begin() + 1, Args.end()); | |||
2511 | AlignedCands = AlignedCandidates->CompleteCandidates( | |||
2512 | S, OCD_AllCandidates, AlignedArgs, R.getNameLoc(), IsAligned); | |||
2513 | ||||
2514 | Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args, | |||
2515 | R.getNameLoc(), IsUnaligned); | |||
2516 | } else { | |||
2517 | Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args, | |||
2518 | R.getNameLoc()); | |||
2519 | } | |||
2520 | ||||
2521 | S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call) | |||
2522 | << R.getLookupName() << Range; | |||
2523 | if (AlignedCandidates) | |||
2524 | AlignedCandidates->NoteCandidates(S, AlignedArgs, AlignedCands, "", | |||
2525 | R.getNameLoc()); | |||
2526 | Candidates.NoteCandidates(S, Args, Cands, "", R.getNameLoc()); | |||
2527 | } | |||
2528 | return true; | |||
2529 | ||||
2530 | case OR_Ambiguous: | |||
2531 | if (Diagnose) { | |||
2532 | Candidates.NoteCandidates( | |||
2533 | PartialDiagnosticAt(R.getNameLoc(), | |||
2534 | S.PDiag(diag::err_ovl_ambiguous_call) | |||
2535 | << R.getLookupName() << Range), | |||
2536 | S, OCD_AmbiguousCandidates, Args); | |||
2537 | } | |||
2538 | return true; | |||
2539 | ||||
2540 | case OR_Deleted: { | |||
2541 | if (Diagnose) { | |||
2542 | Candidates.NoteCandidates( | |||
2543 | PartialDiagnosticAt(R.getNameLoc(), | |||
2544 | S.PDiag(diag::err_ovl_deleted_call) | |||
2545 | << R.getLookupName() << Range), | |||
2546 | S, OCD_AllCandidates, Args); | |||
2547 | } | |||
2548 | return true; | |||
2549 | } | |||
2550 | } | |||
2551 | llvm_unreachable("Unreachable, bad result from BestViableFunction")::llvm::llvm_unreachable_internal("Unreachable, bad result from BestViableFunction" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 2551); | |||
2552 | } | |||
2553 | ||||
2554 | bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, | |||
2555 | AllocationFunctionScope NewScope, | |||
2556 | AllocationFunctionScope DeleteScope, | |||
2557 | QualType AllocType, bool IsArray, | |||
2558 | bool &PassAlignment, MultiExprArg PlaceArgs, | |||
2559 | FunctionDecl *&OperatorNew, | |||
2560 | FunctionDecl *&OperatorDelete, | |||
2561 | bool Diagnose) { | |||
2562 | // --- Choosing an allocation function --- | |||
2563 | // C++ 5.3.4p8 - 14 & 18 | |||
2564 | // 1) If looking in AFS_Global scope for allocation functions, only look in | |||
2565 | // the global scope. Else, if AFS_Class, only look in the scope of the | |||
2566 | // allocated class. If AFS_Both, look in both. | |||
2567 | // 2) If an array size is given, look for operator new[], else look for | |||
2568 | // operator new. | |||
2569 | // 3) The first argument is always size_t. Append the arguments from the | |||
2570 | // placement form. | |||
2571 | ||||
2572 | SmallVector<Expr*, 8> AllocArgs; | |||
2573 | AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size()); | |||
2574 | ||||
2575 | // We don't care about the actual value of these arguments. | |||
2576 | // FIXME: Should the Sema create the expression and embed it in the syntax | |||
2577 | // tree? Or should the consumer just recalculate the value? | |||
2578 | // FIXME: Using a dummy value will interact poorly with attribute enable_if. | |||
2579 | IntegerLiteral Size(Context, llvm::APInt::getNullValue( | |||
2580 | Context.getTargetInfo().getPointerWidth(0)), | |||
2581 | Context.getSizeType(), | |||
2582 | SourceLocation()); | |||
2583 | AllocArgs.push_back(&Size); | |||
2584 | ||||
2585 | QualType AlignValT = Context.VoidTy; | |||
2586 | if (PassAlignment) { | |||
2587 | DeclareGlobalNewDelete(); | |||
2588 | AlignValT = Context.getTypeDeclType(getStdAlignValT()); | |||
2589 | } | |||
2590 | CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation()); | |||
2591 | if (PassAlignment) | |||
2592 | AllocArgs.push_back(&Align); | |||
2593 | ||||
2594 | AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end()); | |||
2595 | ||||
2596 | // C++ [expr.new]p8: | |||
2597 | // If the allocated type is a non-array type, the allocation | |||
2598 | // function's name is operator new and the deallocation function's | |||
2599 | // name is operator delete. If the allocated type is an array | |||
2600 | // type, the allocation function's name is operator new[] and the | |||
2601 | // deallocation function's name is operator delete[]. | |||
2602 | DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName( | |||
2603 | IsArray ? OO_Array_New : OO_New); | |||
2604 | ||||
2605 | QualType AllocElemType = Context.getBaseElementType(AllocType); | |||
2606 | ||||
2607 | // Find the allocation function. | |||
2608 | { | |||
2609 | LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName); | |||
2610 | ||||
2611 | // C++1z [expr.new]p9: | |||
2612 | // If the new-expression begins with a unary :: operator, the allocation | |||
2613 | // function's name is looked up in the global scope. Otherwise, if the | |||
2614 | // allocated type is a class type T or array thereof, the allocation | |||
2615 | // function's name is looked up in the scope of T. | |||
2616 | if (AllocElemType->isRecordType() && NewScope != AFS_Global) | |||
2617 | LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl()); | |||
2618 | ||||
2619 | // We can see ambiguity here if the allocation function is found in | |||
2620 | // multiple base classes. | |||
2621 | if (R.isAmbiguous()) | |||
2622 | return true; | |||
2623 | ||||
2624 | // If this lookup fails to find the name, or if the allocated type is not | |||
2625 | // a class type, the allocation function's name is looked up in the | |||
2626 | // global scope. | |||
2627 | if (R.empty()) { | |||
2628 | if (NewScope == AFS_Class) | |||
2629 | return true; | |||
2630 | ||||
2631 | LookupQualifiedName(R, Context.getTranslationUnitDecl()); | |||
2632 | } | |||
2633 | ||||
2634 | if (getLangOpts().OpenCLCPlusPlus && R.empty()) { | |||
2635 | if (PlaceArgs.empty()) { | |||
2636 | Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new"; | |||
2637 | } else { | |||
2638 | Diag(StartLoc, diag::err_openclcxx_placement_new); | |||
2639 | } | |||
2640 | return true; | |||
2641 | } | |||
2642 | ||||
2643 | assert(!R.empty() && "implicitly declared allocation functions not found")(static_cast <bool> (!R.empty() && "implicitly declared allocation functions not found" ) ? void (0) : __assert_fail ("!R.empty() && \"implicitly declared allocation functions not found\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 2643, __extension__ __PRETTY_FUNCTION__)); | |||
2644 | assert(!R.isAmbiguous() && "global allocation functions are ambiguous")(static_cast <bool> (!R.isAmbiguous() && "global allocation functions are ambiguous" ) ? void (0) : __assert_fail ("!R.isAmbiguous() && \"global allocation functions are ambiguous\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 2644, __extension__ __PRETTY_FUNCTION__)); | |||
2645 | ||||
2646 | // We do our own custom access checks below. | |||
2647 | R.suppressDiagnostics(); | |||
2648 | ||||
2649 | if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment, | |||
2650 | OperatorNew, /*Candidates=*/nullptr, | |||
2651 | /*AlignArg=*/nullptr, Diagnose)) | |||
2652 | return true; | |||
2653 | } | |||
2654 | ||||
2655 | // We don't need an operator delete if we're running under -fno-exceptions. | |||
2656 | if (!getLangOpts().Exceptions) { | |||
2657 | OperatorDelete = nullptr; | |||
2658 | return false; | |||
2659 | } | |||
2660 | ||||
2661 | // Note, the name of OperatorNew might have been changed from array to | |||
2662 | // non-array by resolveAllocationOverload. | |||
2663 | DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( | |||
2664 | OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New | |||
2665 | ? OO_Array_Delete | |||
2666 | : OO_Delete); | |||
2667 | ||||
2668 | // C++ [expr.new]p19: | |||
2669 | // | |||
2670 | // If the new-expression begins with a unary :: operator, the | |||
2671 | // deallocation function's name is looked up in the global | |||
2672 | // scope. Otherwise, if the allocated type is a class type T or an | |||
2673 | // array thereof, the deallocation function's name is looked up in | |||
2674 | // the scope of T. If this lookup fails to find the name, or if | |||
2675 | // the allocated type is not a class type or array thereof, the | |||
2676 | // deallocation function's name is looked up in the global scope. | |||
2677 | LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName); | |||
2678 | if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) { | |||
2679 | auto *RD = | |||
2680 | cast<CXXRecordDecl>(AllocElemType->castAs<RecordType>()->getDecl()); | |||
2681 | LookupQualifiedName(FoundDelete, RD); | |||
2682 | } | |||
2683 | if (FoundDelete.isAmbiguous()) | |||
2684 | return true; // FIXME: clean up expressions? | |||
2685 | ||||
2686 | // Filter out any destroying operator deletes. We can't possibly call such a | |||
2687 | // function in this context, because we're handling the case where the object | |||
2688 | // was not successfully constructed. | |||
2689 | // FIXME: This is not covered by the language rules yet. | |||
2690 | { | |||
2691 | LookupResult::Filter Filter = FoundDelete.makeFilter(); | |||
2692 | while (Filter.hasNext()) { | |||
2693 | auto *FD = dyn_cast<FunctionDecl>(Filter.next()->getUnderlyingDecl()); | |||
2694 | if (FD && FD->isDestroyingOperatorDelete()) | |||
2695 | Filter.erase(); | |||
2696 | } | |||
2697 | Filter.done(); | |||
2698 | } | |||
2699 | ||||
2700 | bool FoundGlobalDelete = FoundDelete.empty(); | |||
2701 | if (FoundDelete.empty()) { | |||
2702 | FoundDelete.clear(LookupOrdinaryName); | |||
2703 | ||||
2704 | if (DeleteScope == AFS_Class) | |||
2705 | return true; | |||
2706 | ||||
2707 | DeclareGlobalNewDelete(); | |||
2708 | LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); | |||
2709 | } | |||
2710 | ||||
2711 | FoundDelete.suppressDiagnostics(); | |||
2712 | ||||
2713 | SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches; | |||
2714 | ||||
2715 | // Whether we're looking for a placement operator delete is dictated | |||
2716 | // by whether we selected a placement operator new, not by whether | |||
2717 | // we had explicit placement arguments. This matters for things like | |||
2718 | // struct A { void *operator new(size_t, int = 0); ... }; | |||
2719 | // A *a = new A() | |||
2720 | // | |||
2721 | // We don't have any definition for what a "placement allocation function" | |||
2722 | // is, but we assume it's any allocation function whose | |||
2723 | // parameter-declaration-clause is anything other than (size_t). | |||
2724 | // | |||
2725 | // FIXME: Should (size_t, std::align_val_t) also be considered non-placement? | |||
2726 | // This affects whether an exception from the constructor of an overaligned | |||
2727 | // type uses the sized or non-sized form of aligned operator delete. | |||
2728 | bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 || | |||
2729 | OperatorNew->isVariadic(); | |||
2730 | ||||
2731 | if (isPlacementNew) { | |||
2732 | // C++ [expr.new]p20: | |||
2733 | // A declaration of a placement deallocation function matches the | |||
2734 | // declaration of a placement allocation function if it has the | |||
2735 | // same number of parameters and, after parameter transformations | |||
2736 | // (8.3.5), all parameter types except the first are | |||
2737 | // identical. [...] | |||
2738 | // | |||
2739 | // To perform this comparison, we compute the function type that | |||
2740 | // the deallocation function should have, and use that type both | |||
2741 | // for template argument deduction and for comparison purposes. | |||
2742 | QualType ExpectedFunctionType; | |||
2743 | { | |||
2744 | auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>(); | |||
2745 | ||||
2746 | SmallVector<QualType, 4> ArgTypes; | |||
2747 | ArgTypes.push_back(Context.VoidPtrTy); | |||
2748 | for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I) | |||
2749 | ArgTypes.push_back(Proto->getParamType(I)); | |||
2750 | ||||
2751 | FunctionProtoType::ExtProtoInfo EPI; | |||
2752 | // FIXME: This is not part of the standard's rule. | |||
2753 | EPI.Variadic = Proto->isVariadic(); | |||
2754 | ||||
2755 | ExpectedFunctionType | |||
2756 | = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI); | |||
2757 | } | |||
2758 | ||||
2759 | for (LookupResult::iterator D = FoundDelete.begin(), | |||
2760 | DEnd = FoundDelete.end(); | |||
2761 | D != DEnd; ++D) { | |||
2762 | FunctionDecl *Fn = nullptr; | |||
2763 | if (FunctionTemplateDecl *FnTmpl = | |||
2764 | dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) { | |||
2765 | // Perform template argument deduction to try to match the | |||
2766 | // expected function type. | |||
2767 | TemplateDeductionInfo Info(StartLoc); | |||
2768 | if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn, | |||
2769 | Info)) | |||
2770 | continue; | |||
2771 | } else | |||
2772 | Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl()); | |||
2773 | ||||
2774 | if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(), | |||
2775 | ExpectedFunctionType, | |||
2776 | /*AdjustExcpetionSpec*/true), | |||
2777 | ExpectedFunctionType)) | |||
2778 | Matches.push_back(std::make_pair(D.getPair(), Fn)); | |||
2779 | } | |||
2780 | ||||
2781 | if (getLangOpts().CUDA) | |||
2782 | EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches); | |||
2783 | } else { | |||
2784 | // C++1y [expr.new]p22: | |||
2785 | // For a non-placement allocation function, the normal deallocation | |||
2786 | // function lookup is used | |||
2787 | // | |||
2788 | // Per [expr.delete]p10, this lookup prefers a member operator delete | |||
2789 | // without a size_t argument, but prefers a non-member operator delete | |||
2790 | // with a size_t where possible (which it always is in this case). | |||
2791 | llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns; | |||
2792 | UsualDeallocFnInfo Selected = resolveDeallocationOverload( | |||
2793 | *this, FoundDelete, /*WantSize*/ FoundGlobalDelete, | |||
2794 | /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType), | |||
2795 | &BestDeallocFns); | |||
2796 | if (Selected) | |||
2797 | Matches.push_back(std::make_pair(Selected.Found, Selected.FD)); | |||
2798 | else { | |||
2799 | // If we failed to select an operator, all remaining functions are viable | |||
2800 | // but ambiguous. | |||
2801 | for (auto Fn : BestDeallocFns) | |||
2802 | Matches.push_back(std::make_pair(Fn.Found, Fn.FD)); | |||
2803 | } | |||
2804 | } | |||
2805 | ||||
2806 | // C++ [expr.new]p20: | |||
2807 | // [...] If the lookup finds a single matching deallocation | |||
2808 | // function, that function will be called; otherwise, no | |||
2809 | // deallocation function will be called. | |||
2810 | if (Matches.size() == 1) { | |||
2811 | OperatorDelete = Matches[0].second; | |||
2812 | ||||
2813 | // C++1z [expr.new]p23: | |||
2814 | // If the lookup finds a usual deallocation function (3.7.4.2) | |||
2815 | // with a parameter of type std::size_t and that function, considered | |||
2816 | // as a placement deallocation function, would have been | |||
2817 | // selected as a match for the allocation function, the program | |||
2818 | // is ill-formed. | |||
2819 | if (getLangOpts().CPlusPlus11 && isPlacementNew && | |||
2820 | isNonPlacementDeallocationFunction(*this, OperatorDelete)) { | |||
2821 | UsualDeallocFnInfo Info(*this, | |||
2822 | DeclAccessPair::make(OperatorDelete, AS_public)); | |||
2823 | // Core issue, per mail to core reflector, 2016-10-09: | |||
2824 | // If this is a member operator delete, and there is a corresponding | |||
2825 | // non-sized member operator delete, this isn't /really/ a sized | |||
2826 | // deallocation function, it just happens to have a size_t parameter. | |||
2827 | bool IsSizedDelete = Info.HasSizeT; | |||
2828 | if (IsSizedDelete && !FoundGlobalDelete) { | |||
2829 | auto NonSizedDelete = | |||
2830 | resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false, | |||
2831 | /*WantAlign*/Info.HasAlignValT); | |||
2832 | if (NonSizedDelete && !NonSizedDelete.HasSizeT && | |||
2833 | NonSizedDelete.HasAlignValT == Info.HasAlignValT) | |||
2834 | IsSizedDelete = false; | |||
2835 | } | |||
2836 | ||||
2837 | if (IsSizedDelete) { | |||
2838 | SourceRange R = PlaceArgs.empty() | |||
2839 | ? SourceRange() | |||
2840 | : SourceRange(PlaceArgs.front()->getBeginLoc(), | |||
2841 | PlaceArgs.back()->getEndLoc()); | |||
2842 | Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R; | |||
2843 | if (!OperatorDelete->isImplicit()) | |||
2844 | Diag(OperatorDelete->getLocation(), diag::note_previous_decl) | |||
2845 | << DeleteName; | |||
2846 | } | |||
2847 | } | |||
2848 | ||||
2849 | CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(), | |||
2850 | Matches[0].first); | |||
2851 | } else if (!Matches.empty()) { | |||
2852 | // We found multiple suitable operators. Per [expr.new]p20, that means we | |||
2853 | // call no 'operator delete' function, but we should at least warn the user. | |||
2854 | // FIXME: Suppress this warning if the construction cannot throw. | |||
2855 | Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found) | |||
2856 | << DeleteName << AllocElemType; | |||
2857 | ||||
2858 | for (auto &Match : Matches) | |||
2859 | Diag(Match.second->getLocation(), | |||
2860 | diag::note_member_declared_here) << DeleteName; | |||
2861 | } | |||
2862 | ||||
2863 | return false; | |||
2864 | } | |||
2865 | ||||
2866 | /// DeclareGlobalNewDelete - Declare the global forms of operator new and | |||
2867 | /// delete. These are: | |||
2868 | /// @code | |||
2869 | /// // C++03: | |||
2870 | /// void* operator new(std::size_t) throw(std::bad_alloc); | |||
2871 | /// void* operator new[](std::size_t) throw(std::bad_alloc); | |||
2872 | /// void operator delete(void *) throw(); | |||
2873 | /// void operator delete[](void *) throw(); | |||
2874 | /// // C++11: | |||
2875 | /// void* operator new(std::size_t); | |||
2876 | /// void* operator new[](std::size_t); | |||
2877 | /// void operator delete(void *) noexcept; | |||
2878 | /// void operator delete[](void *) noexcept; | |||
2879 | /// // C++1y: | |||
2880 | /// void* operator new(std::size_t); | |||
2881 | /// void* operator new[](std::size_t); | |||
2882 | /// void operator delete(void *) noexcept; | |||
2883 | /// void operator delete[](void *) noexcept; | |||
2884 | /// void operator delete(void *, std::size_t) noexcept; | |||
2885 | /// void operator delete[](void *, std::size_t) noexcept; | |||
2886 | /// @endcode | |||
2887 | /// Note that the placement and nothrow forms of new are *not* implicitly | |||
2888 | /// declared. Their use requires including \<new\>. | |||
2889 | void Sema::DeclareGlobalNewDelete() { | |||
2890 | if (GlobalNewDeleteDeclared) | |||
2891 | return; | |||
2892 | ||||
2893 | // The implicitly declared new and delete operators | |||
2894 | // are not supported in OpenCL. | |||
2895 | if (getLangOpts().OpenCLCPlusPlus) | |||
2896 | return; | |||
2897 | ||||
2898 | // C++ [basic.std.dynamic]p2: | |||
2899 | // [...] The following allocation and deallocation functions (18.4) are | |||
2900 | // implicitly declared in global scope in each translation unit of a | |||
2901 | // program | |||
2902 | // | |||
2903 | // C++03: | |||
2904 | // void* operator new(std::size_t) throw(std::bad_alloc); | |||
2905 | // void* operator new[](std::size_t) throw(std::bad_alloc); | |||
2906 | // void operator delete(void*) throw(); | |||
2907 | // void operator delete[](void*) throw(); | |||
2908 | // C++11: | |||
2909 | // void* operator new(std::size_t); | |||
2910 | // void* operator new[](std::size_t); | |||
2911 | // void operator delete(void*) noexcept; | |||
2912 | // void operator delete[](void*) noexcept; | |||
2913 | // C++1y: | |||
2914 | // void* operator new(std::size_t); | |||
2915 | // void* operator new[](std::size_t); | |||
2916 | // void operator delete(void*) noexcept; | |||
2917 | // void operator delete[](void*) noexcept; | |||
2918 | // void operator delete(void*, std::size_t) noexcept; | |||
2919 | // void operator delete[](void*, std::size_t) noexcept; | |||
2920 | // | |||
2921 | // These implicit declarations introduce only the function names operator | |||
2922 | // new, operator new[], operator delete, operator delete[]. | |||
2923 | // | |||
2924 | // Here, we need to refer to std::bad_alloc, so we will implicitly declare | |||
2925 | // "std" or "bad_alloc" as necessary to form the exception specification. | |||
2926 | // However, we do not make these implicit declarations visible to name | |||
2927 | // lookup. | |||
2928 | if (!StdBadAlloc && !getLangOpts().CPlusPlus11) { | |||
2929 | // The "std::bad_alloc" class has not yet been declared, so build it | |||
2930 | // implicitly. | |||
2931 | StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class, | |||
2932 | getOrCreateStdNamespace(), | |||
2933 | SourceLocation(), SourceLocation(), | |||
2934 | &PP.getIdentifierTable().get("bad_alloc"), | |||
2935 | nullptr); | |||
2936 | getStdBadAlloc()->setImplicit(true); | |||
2937 | } | |||
2938 | if (!StdAlignValT && getLangOpts().AlignedAllocation) { | |||
2939 | // The "std::align_val_t" enum class has not yet been declared, so build it | |||
2940 | // implicitly. | |||
2941 | auto *AlignValT = EnumDecl::Create( | |||
2942 | Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(), | |||
2943 | &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true); | |||
2944 | AlignValT->setIntegerType(Context.getSizeType()); | |||
2945 | AlignValT->setPromotionType(Context.getSizeType()); | |||
2946 | AlignValT->setImplicit(true); | |||
2947 | StdAlignValT = AlignValT; | |||
2948 | } | |||
2949 | ||||
2950 | GlobalNewDeleteDeclared = true; | |||
2951 | ||||
2952 | QualType VoidPtr = Context.getPointerType(Context.VoidTy); | |||
2953 | QualType SizeT = Context.getSizeType(); | |||
2954 | ||||
2955 | auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind, | |||
2956 | QualType Return, QualType Param) { | |||
2957 | llvm::SmallVector<QualType, 3> Params; | |||
2958 | Params.push_back(Param); | |||
2959 | ||||
2960 | // Create up to four variants of the function (sized/aligned). | |||
2961 | bool HasSizedVariant = getLangOpts().SizedDeallocation && | |||
2962 | (Kind == OO_Delete || Kind == OO_Array_Delete); | |||
2963 | bool HasAlignedVariant = getLangOpts().AlignedAllocation; | |||
2964 | ||||
2965 | int NumSizeVariants = (HasSizedVariant ? 2 : 1); | |||
2966 | int NumAlignVariants = (HasAlignedVariant ? 2 : 1); | |||
2967 | for (int Sized = 0; Sized < NumSizeVariants; ++Sized) { | |||
2968 | if (Sized) | |||
2969 | Params.push_back(SizeT); | |||
2970 | ||||
2971 | for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) { | |||
2972 | if (Aligned) | |||
2973 | Params.push_back(Context.getTypeDeclType(getStdAlignValT())); | |||
2974 | ||||
2975 | DeclareGlobalAllocationFunction( | |||
2976 | Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params); | |||
2977 | ||||
2978 | if (Aligned) | |||
2979 | Params.pop_back(); | |||
2980 | } | |||
2981 | } | |||
2982 | }; | |||
2983 | ||||
2984 | DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT); | |||
2985 | DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT); | |||
2986 | DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr); | |||
2987 | DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr); | |||
2988 | } | |||
2989 | ||||
2990 | /// DeclareGlobalAllocationFunction - Declares a single implicit global | |||
2991 | /// allocation function if it doesn't already exist. | |||
2992 | void Sema::DeclareGlobalAllocationFunction(DeclarationName Name, | |||
2993 | QualType Return, | |||
2994 | ArrayRef<QualType> Params) { | |||
2995 | DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); | |||
2996 | ||||
2997 | // Check if this function is already declared. | |||
2998 | DeclContext::lookup_result R = GlobalCtx->lookup(Name); | |||
2999 | for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end(); | |||
3000 | Alloc != AllocEnd; ++Alloc) { | |||
3001 | // Only look at non-template functions, as it is the predefined, | |||
3002 | // non-templated allocation function we are trying to declare here. | |||
3003 | if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) { | |||
3004 | if (Func->getNumParams() == Params.size()) { | |||
3005 | llvm::SmallVector<QualType, 3> FuncParams; | |||
3006 | for (auto *P : Func->parameters()) | |||
3007 | FuncParams.push_back( | |||
3008 | Context.getCanonicalType(P->getType().getUnqualifiedType())); | |||
3009 | if (llvm::makeArrayRef(FuncParams) == Params) { | |||
3010 | // Make the function visible to name lookup, even if we found it in | |||
3011 | // an unimported module. It either is an implicitly-declared global | |||
3012 | // allocation function, or is suppressing that function. | |||
3013 | Func->setVisibleDespiteOwningModule(); | |||
3014 | return; | |||
3015 | } | |||
3016 | } | |||
3017 | } | |||
3018 | } | |||
3019 | ||||
3020 | FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention( | |||
3021 | /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true)); | |||
3022 | ||||
3023 | QualType BadAllocType; | |||
3024 | bool HasBadAllocExceptionSpec | |||
3025 | = (Name.getCXXOverloadedOperator() == OO_New || | |||
3026 | Name.getCXXOverloadedOperator() == OO_Array_New); | |||
3027 | if (HasBadAllocExceptionSpec) { | |||
3028 | if (!getLangOpts().CPlusPlus11) { | |||
3029 | BadAllocType = Context.getTypeDeclType(getStdBadAlloc()); | |||
3030 | assert(StdBadAlloc && "Must have std::bad_alloc declared")(static_cast <bool> (StdBadAlloc && "Must have std::bad_alloc declared" ) ? void (0) : __assert_fail ("StdBadAlloc && \"Must have std::bad_alloc declared\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 3030, __extension__ __PRETTY_FUNCTION__)); | |||
3031 | EPI.ExceptionSpec.Type = EST_Dynamic; | |||
3032 | EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType); | |||
3033 | } | |||
3034 | } else { | |||
3035 | EPI.ExceptionSpec = | |||
3036 | getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone; | |||
3037 | } | |||
3038 | ||||
3039 | auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) { | |||
3040 | QualType FnType = Context.getFunctionType(Return, Params, EPI); | |||
3041 | FunctionDecl *Alloc = FunctionDecl::Create( | |||
3042 | Context, GlobalCtx, SourceLocation(), SourceLocation(), Name, | |||
3043 | FnType, /*TInfo=*/nullptr, SC_None, false, true); | |||
3044 | Alloc->setImplicit(); | |||
3045 | // Global allocation functions should always be visible. | |||
3046 | Alloc->setVisibleDespiteOwningModule(); | |||
3047 | ||||
3048 | Alloc->addAttr(VisibilityAttr::CreateImplicit( | |||
3049 | Context, LangOpts.GlobalAllocationFunctionVisibilityHidden | |||
3050 | ? VisibilityAttr::Hidden | |||
3051 | : VisibilityAttr::Default)); | |||
3052 | ||||
3053 | llvm::SmallVector<ParmVarDecl *, 3> ParamDecls; | |||
3054 | for (QualType T : Params) { | |||
3055 | ParamDecls.push_back(ParmVarDecl::Create( | |||
3056 | Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T, | |||
3057 | /*TInfo=*/nullptr, SC_None, nullptr)); | |||
3058 | ParamDecls.back()->setImplicit(); | |||
3059 | } | |||
3060 | Alloc->setParams(ParamDecls); | |||
3061 | if (ExtraAttr) | |||
3062 | Alloc->addAttr(ExtraAttr); | |||
3063 | AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(Alloc); | |||
3064 | Context.getTranslationUnitDecl()->addDecl(Alloc); | |||
3065 | IdResolver.tryAddTopLevelDecl(Alloc, Name); | |||
3066 | }; | |||
3067 | ||||
3068 | if (!LangOpts.CUDA) | |||
3069 | CreateAllocationFunctionDecl(nullptr); | |||
3070 | else { | |||
3071 | // Host and device get their own declaration so each can be | |||
3072 | // defined or re-declared independently. | |||
3073 | CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context)); | |||
3074 | CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context)); | |||
3075 | } | |||
3076 | } | |||
3077 | ||||
3078 | FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc, | |||
3079 | bool CanProvideSize, | |||
3080 | bool Overaligned, | |||
3081 | DeclarationName Name) { | |||
3082 | DeclareGlobalNewDelete(); | |||
3083 | ||||
3084 | LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName); | |||
3085 | LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); | |||
3086 | ||||
3087 | // FIXME: It's possible for this to result in ambiguity, through a | |||
3088 | // user-declared variadic operator delete or the enable_if attribute. We | |||
3089 | // should probably not consider those cases to be usual deallocation | |||
3090 | // functions. But for now we just make an arbitrary choice in that case. | |||
3091 | auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize, | |||
3092 | Overaligned); | |||
3093 | assert(Result.FD && "operator delete missing from global scope?")(static_cast <bool> (Result.FD && "operator delete missing from global scope?" ) ? void (0) : __assert_fail ("Result.FD && \"operator delete missing from global scope?\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 3093, __extension__ __PRETTY_FUNCTION__)); | |||
3094 | return Result.FD; | |||
3095 | } | |||
3096 | ||||
3097 | FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc, | |||
3098 | CXXRecordDecl *RD) { | |||
3099 | DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete); | |||
3100 | ||||
3101 | FunctionDecl *OperatorDelete = nullptr; | |||
3102 | if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) | |||
3103 | return nullptr; | |||
3104 | if (OperatorDelete) | |||
3105 | return OperatorDelete; | |||
3106 | ||||
3107 | // If there's no class-specific operator delete, look up the global | |||
3108 | // non-array delete. | |||
3109 | return FindUsualDeallocationFunction( | |||
3110 | Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)), | |||
3111 | Name); | |||
3112 | } | |||
3113 | ||||
3114 | bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, | |||
3115 | DeclarationName Name, | |||
3116 | FunctionDecl *&Operator, bool Diagnose) { | |||
3117 | LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName); | |||
3118 | // Try to find operator delete/operator delete[] in class scope. | |||
3119 | LookupQualifiedName(Found, RD); | |||
3120 | ||||
3121 | if (Found.isAmbiguous()) | |||
3122 | return true; | |||
3123 | ||||
3124 | Found.suppressDiagnostics(); | |||
3125 | ||||
3126 | bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD)); | |||
3127 | ||||
3128 | // C++17 [expr.delete]p10: | |||
3129 | // If the deallocation functions have class scope, the one without a | |||
3130 | // parameter of type std::size_t is selected. | |||
3131 | llvm::SmallVector<UsualDeallocFnInfo, 4> Matches; | |||
3132 | resolveDeallocationOverload(*this, Found, /*WantSize*/ false, | |||
3133 | /*WantAlign*/ Overaligned, &Matches); | |||
3134 | ||||
3135 | // If we could find an overload, use it. | |||
3136 | if (Matches.size() == 1) { | |||
3137 | Operator = cast<CXXMethodDecl>(Matches[0].FD); | |||
3138 | ||||
3139 | // FIXME: DiagnoseUseOfDecl? | |||
3140 | if (Operator->isDeleted()) { | |||
3141 | if (Diagnose) { | |||
3142 | Diag(StartLoc, diag::err_deleted_function_use); | |||
3143 | NoteDeletedFunction(Operator); | |||
3144 | } | |||
3145 | return true; | |||
3146 | } | |||
3147 | ||||
3148 | if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(), | |||
3149 | Matches[0].Found, Diagnose) == AR_inaccessible) | |||
3150 | return true; | |||
3151 | ||||
3152 | return false; | |||
3153 | } | |||
3154 | ||||
3155 | // We found multiple suitable operators; complain about the ambiguity. | |||
3156 | // FIXME: The standard doesn't say to do this; it appears that the intent | |||
3157 | // is that this should never happen. | |||
3158 | if (!Matches.empty()) { | |||
3159 | if (Diagnose) { | |||
3160 | Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found) | |||
3161 | << Name << RD; | |||
3162 | for (auto &Match : Matches) | |||
3163 | Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name; | |||
3164 | } | |||
3165 | return true; | |||
3166 | } | |||
3167 | ||||
3168 | // We did find operator delete/operator delete[] declarations, but | |||
3169 | // none of them were suitable. | |||
3170 | if (!Found.empty()) { | |||
3171 | if (Diagnose) { | |||
3172 | Diag(StartLoc, diag::err_no_suitable_delete_member_function_found) | |||
3173 | << Name << RD; | |||
3174 | ||||
3175 | for (NamedDecl *D : Found) | |||
3176 | Diag(D->getUnderlyingDecl()->getLocation(), | |||
3177 | diag::note_member_declared_here) << Name; | |||
3178 | } | |||
3179 | return true; | |||
3180 | } | |||
3181 | ||||
3182 | Operator = nullptr; | |||
3183 | return false; | |||
3184 | } | |||
3185 | ||||
3186 | namespace { | |||
3187 | /// Checks whether delete-expression, and new-expression used for | |||
3188 | /// initializing deletee have the same array form. | |||
3189 | class MismatchingNewDeleteDetector { | |||
3190 | public: | |||
3191 | enum MismatchResult { | |||
3192 | /// Indicates that there is no mismatch or a mismatch cannot be proven. | |||
3193 | NoMismatch, | |||
3194 | /// Indicates that variable is initialized with mismatching form of \a new. | |||
3195 | VarInitMismatches, | |||
3196 | /// Indicates that member is initialized with mismatching form of \a new. | |||
3197 | MemberInitMismatches, | |||
3198 | /// Indicates that 1 or more constructors' definitions could not been | |||
3199 | /// analyzed, and they will be checked again at the end of translation unit. | |||
3200 | AnalyzeLater | |||
3201 | }; | |||
3202 | ||||
3203 | /// \param EndOfTU True, if this is the final analysis at the end of | |||
3204 | /// translation unit. False, if this is the initial analysis at the point | |||
3205 | /// delete-expression was encountered. | |||
3206 | explicit MismatchingNewDeleteDetector(bool EndOfTU) | |||
3207 | : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU), | |||
3208 | HasUndefinedConstructors(false) {} | |||
3209 | ||||
3210 | /// Checks whether pointee of a delete-expression is initialized with | |||
3211 | /// matching form of new-expression. | |||
3212 | /// | |||
3213 | /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the | |||
3214 | /// point where delete-expression is encountered, then a warning will be | |||
3215 | /// issued immediately. If return value is \c AnalyzeLater at the point where | |||
3216 | /// delete-expression is seen, then member will be analyzed at the end of | |||
3217 | /// translation unit. \c AnalyzeLater is returned iff at least one constructor | |||
3218 | /// couldn't be analyzed. If at least one constructor initializes the member | |||
3219 | /// with matching type of new, the return value is \c NoMismatch. | |||
3220 | MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE); | |||
3221 | /// Analyzes a class member. | |||
3222 | /// \param Field Class member to analyze. | |||
3223 | /// \param DeleteWasArrayForm Array form-ness of the delete-expression used | |||
3224 | /// for deleting the \p Field. | |||
3225 | MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm); | |||
3226 | FieldDecl *Field; | |||
3227 | /// List of mismatching new-expressions used for initialization of the pointee | |||
3228 | llvm::SmallVector<const CXXNewExpr *, 4> NewExprs; | |||
3229 | /// Indicates whether delete-expression was in array form. | |||
3230 | bool IsArrayForm; | |||
3231 | ||||
3232 | private: | |||
3233 | const bool EndOfTU; | |||
3234 | /// Indicates that there is at least one constructor without body. | |||
3235 | bool HasUndefinedConstructors; | |||
3236 | /// Returns \c CXXNewExpr from given initialization expression. | |||
3237 | /// \param E Expression used for initializing pointee in delete-expression. | |||
3238 | /// E can be a single-element \c InitListExpr consisting of new-expression. | |||
3239 | const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E); | |||
3240 | /// Returns whether member is initialized with mismatching form of | |||
3241 | /// \c new either by the member initializer or in-class initialization. | |||
3242 | /// | |||
3243 | /// If bodies of all constructors are not visible at the end of translation | |||
3244 | /// unit or at least one constructor initializes member with the matching | |||
3245 | /// form of \c new, mismatch cannot be proven, and this function will return | |||
3246 | /// \c NoMismatch. | |||
3247 | MismatchResult analyzeMemberExpr(const MemberExpr *ME); | |||
3248 | /// Returns whether variable is initialized with mismatching form of | |||
3249 | /// \c new. | |||
3250 | /// | |||
3251 | /// If variable is initialized with matching form of \c new or variable is not | |||
3252 | /// initialized with a \c new expression, this function will return true. | |||
3253 | /// If variable is initialized with mismatching form of \c new, returns false. | |||
3254 | /// \param D Variable to analyze. | |||
3255 | bool hasMatchingVarInit(const DeclRefExpr *D); | |||
3256 | /// Checks whether the constructor initializes pointee with mismatching | |||
3257 | /// form of \c new. | |||
3258 | /// | |||
3259 | /// Returns true, if member is initialized with matching form of \c new in | |||
3260 | /// member initializer list. Returns false, if member is initialized with the | |||
3261 | /// matching form of \c new in this constructor's initializer or given | |||
3262 | /// constructor isn't defined at the point where delete-expression is seen, or | |||
3263 | /// member isn't initialized by the constructor. | |||
3264 | bool hasMatchingNewInCtor(const CXXConstructorDecl *CD); | |||
3265 | /// Checks whether member is initialized with matching form of | |||
3266 | /// \c new in member initializer list. | |||
3267 | bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI); | |||
3268 | /// Checks whether member is initialized with mismatching form of \c new by | |||
3269 | /// in-class initializer. | |||
3270 | MismatchResult analyzeInClassInitializer(); | |||
3271 | }; | |||
3272 | } | |||
3273 | ||||
3274 | MismatchingNewDeleteDetector::MismatchResult | |||
3275 | MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) { | |||
3276 | NewExprs.clear(); | |||
3277 | assert(DE && "Expected delete-expression")(static_cast <bool> (DE && "Expected delete-expression" ) ? void (0) : __assert_fail ("DE && \"Expected delete-expression\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 3277, __extension__ __PRETTY_FUNCTION__)); | |||
3278 | IsArrayForm = DE->isArrayForm(); | |||
3279 | const Expr *E = DE->getArgument()->IgnoreParenImpCasts(); | |||
3280 | if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) { | |||
3281 | return analyzeMemberExpr(ME); | |||
3282 | } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) { | |||
3283 | if (!hasMatchingVarInit(D)) | |||
3284 | return VarInitMismatches; | |||
3285 | } | |||
3286 | return NoMismatch; | |||
3287 | } | |||
3288 | ||||
3289 | const CXXNewExpr * | |||
3290 | MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) { | |||
3291 | assert(E != nullptr && "Expected a valid initializer expression")(static_cast <bool> (E != nullptr && "Expected a valid initializer expression" ) ? void (0) : __assert_fail ("E != nullptr && \"Expected a valid initializer expression\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 3291, __extension__ __PRETTY_FUNCTION__)); | |||
3292 | E = E->IgnoreParenImpCasts(); | |||
3293 | if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) { | |||
3294 | if (ILE->getNumInits() == 1) | |||
3295 | E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts()); | |||
3296 | } | |||
3297 | ||||
3298 | return dyn_cast_or_null<const CXXNewExpr>(E); | |||
3299 | } | |||
3300 | ||||
3301 | bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit( | |||
3302 | const CXXCtorInitializer *CI) { | |||
3303 | const CXXNewExpr *NE = nullptr; | |||
3304 | if (Field == CI->getMember() && | |||
3305 | (NE = getNewExprFromInitListOrExpr(CI->getInit()))) { | |||
3306 | if (NE->isArray() == IsArrayForm) | |||
3307 | return true; | |||
3308 | else | |||
3309 | NewExprs.push_back(NE); | |||
3310 | } | |||
3311 | return false; | |||
3312 | } | |||
3313 | ||||
3314 | bool MismatchingNewDeleteDetector::hasMatchingNewInCtor( | |||
3315 | const CXXConstructorDecl *CD) { | |||
3316 | if (CD->isImplicit()) | |||
3317 | return false; | |||
3318 | const FunctionDecl *Definition = CD; | |||
3319 | if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) { | |||
3320 | HasUndefinedConstructors = true; | |||
3321 | return EndOfTU; | |||
3322 | } | |||
3323 | for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) { | |||
3324 | if (hasMatchingNewInCtorInit(CI)) | |||
3325 | return true; | |||
3326 | } | |||
3327 | return false; | |||
3328 | } | |||
3329 | ||||
3330 | MismatchingNewDeleteDetector::MismatchResult | |||
3331 | MismatchingNewDeleteDetector::analyzeInClassInitializer() { | |||
3332 | assert(Field != nullptr && "This should be called only for members")(static_cast <bool> (Field != nullptr && "This should be called only for members" ) ? void (0) : __assert_fail ("Field != nullptr && \"This should be called only for members\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 3332, __extension__ __PRETTY_FUNCTION__)); | |||
3333 | const Expr *InitExpr = Field->getInClassInitializer(); | |||
3334 | if (!InitExpr) | |||
3335 | return EndOfTU ? NoMismatch : AnalyzeLater; | |||
3336 | if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) { | |||
3337 | if (NE->isArray() != IsArrayForm) { | |||
3338 | NewExprs.push_back(NE); | |||
3339 | return MemberInitMismatches; | |||
3340 | } | |||
3341 | } | |||
3342 | return NoMismatch; | |||
3343 | } | |||
3344 | ||||
3345 | MismatchingNewDeleteDetector::MismatchResult | |||
3346 | MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field, | |||
3347 | bool DeleteWasArrayForm) { | |||
3348 | assert(Field != nullptr && "Analysis requires a valid class member.")(static_cast <bool> (Field != nullptr && "Analysis requires a valid class member." ) ? void (0) : __assert_fail ("Field != nullptr && \"Analysis requires a valid class member.\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 3348, __extension__ __PRETTY_FUNCTION__)); | |||
3349 | this->Field = Field; | |||
3350 | IsArrayForm = DeleteWasArrayForm; | |||
3351 | const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent()); | |||
3352 | for (const auto *CD : RD->ctors()) { | |||
3353 | if (hasMatchingNewInCtor(CD)) | |||
3354 | return NoMismatch; | |||
3355 | } | |||
3356 | if (HasUndefinedConstructors) | |||
3357 | return EndOfTU ? NoMismatch : AnalyzeLater; | |||
3358 | if (!NewExprs.empty()) | |||
3359 | return MemberInitMismatches; | |||
3360 | return Field->hasInClassInitializer() ? analyzeInClassInitializer() | |||
3361 | : NoMismatch; | |||
3362 | } | |||
3363 | ||||
3364 | MismatchingNewDeleteDetector::MismatchResult | |||
3365 | MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) { | |||
3366 | assert(ME != nullptr && "Expected a member expression")(static_cast <bool> (ME != nullptr && "Expected a member expression" ) ? void (0) : __assert_fail ("ME != nullptr && \"Expected a member expression\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 3366, __extension__ __PRETTY_FUNCTION__)); | |||
3367 | if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl())) | |||
3368 | return analyzeField(F, IsArrayForm); | |||
3369 | return NoMismatch; | |||
3370 | } | |||
3371 | ||||
3372 | bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) { | |||
3373 | const CXXNewExpr *NE = nullptr; | |||
3374 | if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) { | |||
3375 | if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) && | |||
3376 | NE->isArray() != IsArrayForm) { | |||
3377 | NewExprs.push_back(NE); | |||
3378 | } | |||
3379 | } | |||
3380 | return NewExprs.empty(); | |||
3381 | } | |||
3382 | ||||
3383 | static void | |||
3384 | DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc, | |||
3385 | const MismatchingNewDeleteDetector &Detector) { | |||
3386 | SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc); | |||
3387 | FixItHint H; | |||
3388 | if (!Detector.IsArrayForm) | |||
3389 | H = FixItHint::CreateInsertion(EndOfDelete, "[]"); | |||
3390 | else { | |||
3391 | SourceLocation RSquare = Lexer::findLocationAfterToken( | |||
3392 | DeleteLoc, tok::l_square, SemaRef.getSourceManager(), | |||
3393 | SemaRef.getLangOpts(), true); | |||
3394 | if (RSquare.isValid()) | |||
3395 | H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare)); | |||
3396 | } | |||
3397 | SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new) | |||
3398 | << Detector.IsArrayForm << H; | |||
3399 | ||||
3400 | for (const auto *NE : Detector.NewExprs) | |||
3401 | SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here) | |||
3402 | << Detector.IsArrayForm; | |||
3403 | } | |||
3404 | ||||
3405 | void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) { | |||
3406 | if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) | |||
3407 | return; | |||
3408 | MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false); | |||
3409 | switch (Detector.analyzeDeleteExpr(DE)) { | |||
3410 | case MismatchingNewDeleteDetector::VarInitMismatches: | |||
3411 | case MismatchingNewDeleteDetector::MemberInitMismatches: { | |||
3412 | DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector); | |||
3413 | break; | |||
3414 | } | |||
3415 | case MismatchingNewDeleteDetector::AnalyzeLater: { | |||
3416 | DeleteExprs[Detector.Field].push_back( | |||
3417 | std::make_pair(DE->getBeginLoc(), DE->isArrayForm())); | |||
3418 | break; | |||
3419 | } | |||
3420 | case MismatchingNewDeleteDetector::NoMismatch: | |||
3421 | break; | |||
3422 | } | |||
3423 | } | |||
3424 | ||||
3425 | void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, | |||
3426 | bool DeleteWasArrayForm) { | |||
3427 | MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true); | |||
3428 | switch (Detector.analyzeField(Field, DeleteWasArrayForm)) { | |||
3429 | case MismatchingNewDeleteDetector::VarInitMismatches: | |||
3430 | llvm_unreachable("This analysis should have been done for class members.")::llvm::llvm_unreachable_internal("This analysis should have been done for class members." , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 3430); | |||
3431 | case MismatchingNewDeleteDetector::AnalyzeLater: | |||
3432 | llvm_unreachable("Analysis cannot be postponed any point beyond end of "::llvm::llvm_unreachable_internal("Analysis cannot be postponed any point beyond end of " "translation unit.", "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 3433) | |||
3433 | "translation unit.")::llvm::llvm_unreachable_internal("Analysis cannot be postponed any point beyond end of " "translation unit.", "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 3433); | |||
3434 | case MismatchingNewDeleteDetector::MemberInitMismatches: | |||
3435 | DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector); | |||
3436 | break; | |||
3437 | case MismatchingNewDeleteDetector::NoMismatch: | |||
3438 | break; | |||
3439 | } | |||
3440 | } | |||
3441 | ||||
3442 | /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in: | |||
3443 | /// @code ::delete ptr; @endcode | |||
3444 | /// or | |||
3445 | /// @code delete [] ptr; @endcode | |||
3446 | ExprResult | |||
3447 | Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, | |||
3448 | bool ArrayForm, Expr *ExE) { | |||
3449 | // C++ [expr.delete]p1: | |||
3450 | // The operand shall have a pointer type, or a class type having a single | |||
3451 | // non-explicit conversion function to a pointer type. The result has type | |||
3452 | // void. | |||
3453 | // | |||
3454 | // DR599 amends "pointer type" to "pointer to object type" in both cases. | |||
3455 | ||||
3456 | ExprResult Ex = ExE; | |||
3457 | FunctionDecl *OperatorDelete = nullptr; | |||
3458 | bool ArrayFormAsWritten = ArrayForm; | |||
3459 | bool UsualArrayDeleteWantsSize = false; | |||
3460 | ||||
3461 | if (!Ex.get()->isTypeDependent()) { | |||
3462 | // Perform lvalue-to-rvalue cast, if needed. | |||
3463 | Ex = DefaultLvalueConversion(Ex.get()); | |||
3464 | if (Ex.isInvalid()) | |||
3465 | return ExprError(); | |||
3466 | ||||
3467 | QualType Type = Ex.get()->getType(); | |||
3468 | ||||
3469 | class DeleteConverter : public ContextualImplicitConverter { | |||
3470 | public: | |||
3471 | DeleteConverter() : ContextualImplicitConverter(false, true) {} | |||
3472 | ||||
3473 | bool match(QualType ConvType) override { | |||
3474 | // FIXME: If we have an operator T* and an operator void*, we must pick | |||
3475 | // the operator T*. | |||
3476 | if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) | |||
3477 | if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType()) | |||
3478 | return true; | |||
3479 | return false; | |||
3480 | } | |||
3481 | ||||
3482 | SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, | |||
3483 | QualType T) override { | |||
3484 | return S.Diag(Loc, diag::err_delete_operand) << T; | |||
3485 | } | |||
3486 | ||||
3487 | SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, | |||
3488 | QualType T) override { | |||
3489 | return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T; | |||
3490 | } | |||
3491 | ||||
3492 | SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, | |||
3493 | QualType T, | |||
3494 | QualType ConvTy) override { | |||
3495 | return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy; | |||
3496 | } | |||
3497 | ||||
3498 | SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, | |||
3499 | QualType ConvTy) override { | |||
3500 | return S.Diag(Conv->getLocation(), diag::note_delete_conversion) | |||
3501 | << ConvTy; | |||
3502 | } | |||
3503 | ||||
3504 | SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, | |||
3505 | QualType T) override { | |||
3506 | return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T; | |||
3507 | } | |||
3508 | ||||
3509 | SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, | |||
3510 | QualType ConvTy) override { | |||
3511 | return S.Diag(Conv->getLocation(), diag::note_delete_conversion) | |||
3512 | << ConvTy; | |||
3513 | } | |||
3514 | ||||
3515 | SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, | |||
3516 | QualType T, | |||
3517 | QualType ConvTy) override { | |||
3518 | llvm_unreachable("conversion functions are permitted")::llvm::llvm_unreachable_internal("conversion functions are permitted" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 3518); | |||
3519 | } | |||
3520 | } Converter; | |||
3521 | ||||
3522 | Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter); | |||
3523 | if (Ex.isInvalid()) | |||
3524 | return ExprError(); | |||
3525 | Type = Ex.get()->getType(); | |||
3526 | if (!Converter.match(Type)) | |||
3527 | // FIXME: PerformContextualImplicitConversion should return ExprError | |||
3528 | // itself in this case. | |||
3529 | return ExprError(); | |||
3530 | ||||
3531 | QualType Pointee = Type->castAs<PointerType>()->getPointeeType(); | |||
3532 | QualType PointeeElem = Context.getBaseElementType(Pointee); | |||
3533 | ||||
3534 | if (Pointee.getAddressSpace() != LangAS::Default && | |||
3535 | !getLangOpts().OpenCLCPlusPlus) | |||
3536 | return Diag(Ex.get()->getBeginLoc(), | |||
3537 | diag::err_address_space_qualified_delete) | |||
3538 | << Pointee.getUnqualifiedType() | |||
3539 | << Pointee.getQualifiers().getAddressSpaceAttributePrintValue(); | |||
3540 | ||||
3541 | CXXRecordDecl *PointeeRD = nullptr; | |||
3542 | if (Pointee->isVoidType() && !isSFINAEContext()) { | |||
3543 | // The C++ standard bans deleting a pointer to a non-object type, which | |||
3544 | // effectively bans deletion of "void*". However, most compilers support | |||
3545 | // this, so we treat it as a warning unless we're in a SFINAE context. | |||
3546 | Diag(StartLoc, diag::ext_delete_void_ptr_operand) | |||
3547 | << Type << Ex.get()->getSourceRange(); | |||
3548 | } else if (Pointee->isFunctionType() || Pointee->isVoidType() || | |||
3549 | Pointee->isSizelessType()) { | |||
3550 | return ExprError(Diag(StartLoc, diag::err_delete_operand) | |||
3551 | << Type << Ex.get()->getSourceRange()); | |||
3552 | } else if (!Pointee->isDependentType()) { | |||
3553 | // FIXME: This can result in errors if the definition was imported from a | |||
3554 | // module but is hidden. | |||
3555 | if (!RequireCompleteType(StartLoc, Pointee, | |||
3556 | diag::warn_delete_incomplete, Ex.get())) { | |||
3557 | if (const RecordType *RT = PointeeElem->getAs<RecordType>()) | |||
3558 | PointeeRD = cast<CXXRecordDecl>(RT->getDecl()); | |||
3559 | } | |||
3560 | } | |||
3561 | ||||
3562 | if (Pointee->isArrayType() && !ArrayForm) { | |||
3563 | Diag(StartLoc, diag::warn_delete_array_type) | |||
3564 | << Type << Ex.get()->getSourceRange() | |||
3565 | << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]"); | |||
3566 | ArrayForm = true; | |||
3567 | } | |||
3568 | ||||
3569 | DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( | |||
3570 | ArrayForm ? OO_Array_Delete : OO_Delete); | |||
3571 | ||||
3572 | if (PointeeRD) { | |||
3573 | if (!UseGlobal && | |||
3574 | FindDeallocationFunction(StartLoc, PointeeRD, DeleteName, | |||
3575 | OperatorDelete)) | |||
3576 | return ExprError(); | |||
3577 | ||||
3578 | // If we're allocating an array of records, check whether the | |||
3579 | // usual operator delete[] has a size_t parameter. | |||
3580 | if (ArrayForm) { | |||
3581 | // If the user specifically asked to use the global allocator, | |||
3582 | // we'll need to do the lookup into the class. | |||
3583 | if (UseGlobal) | |||
3584 | UsualArrayDeleteWantsSize = | |||
3585 | doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem); | |||
3586 | ||||
3587 | // Otherwise, the usual operator delete[] should be the | |||
3588 | // function we just found. | |||
3589 | else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete)) | |||
3590 | UsualArrayDeleteWantsSize = | |||
3591 | UsualDeallocFnInfo(*this, | |||
3592 | DeclAccessPair::make(OperatorDelete, AS_public)) | |||
3593 | .HasSizeT; | |||
3594 | } | |||
3595 | ||||
3596 | if (!PointeeRD->hasIrrelevantDestructor()) | |||
3597 | if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) { | |||
3598 | MarkFunctionReferenced(StartLoc, | |||
3599 | const_cast<CXXDestructorDecl*>(Dtor)); | |||
3600 | if (DiagnoseUseOfDecl(Dtor, StartLoc)) | |||
3601 | return ExprError(); | |||
3602 | } | |||
3603 | ||||
3604 | CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc, | |||
3605 | /*IsDelete=*/true, /*CallCanBeVirtual=*/true, | |||
3606 | /*WarnOnNonAbstractTypes=*/!ArrayForm, | |||
3607 | SourceLocation()); | |||
3608 | } | |||
3609 | ||||
3610 | if (!OperatorDelete) { | |||
3611 | if (getLangOpts().OpenCLCPlusPlus) { | |||
3612 | Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete"; | |||
3613 | return ExprError(); | |||
3614 | } | |||
3615 | ||||
3616 | bool IsComplete = isCompleteType(StartLoc, Pointee); | |||
3617 | bool CanProvideSize = | |||
3618 | IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize || | |||
3619 | Pointee.isDestructedType()); | |||
3620 | bool Overaligned = hasNewExtendedAlignment(*this, Pointee); | |||
3621 | ||||
3622 | // Look for a global declaration. | |||
3623 | OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize, | |||
3624 | Overaligned, DeleteName); | |||
3625 | } | |||
3626 | ||||
3627 | MarkFunctionReferenced(StartLoc, OperatorDelete); | |||
3628 | ||||
3629 | // Check access and ambiguity of destructor if we're going to call it. | |||
3630 | // Note that this is required even for a virtual delete. | |||
3631 | bool IsVirtualDelete = false; | |||
3632 | if (PointeeRD) { | |||
3633 | if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) { | |||
3634 | CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor, | |||
3635 | PDiag(diag::err_access_dtor) << PointeeElem); | |||
3636 | IsVirtualDelete = Dtor->isVirtual(); | |||
3637 | } | |||
3638 | } | |||
3639 | ||||
3640 | DiagnoseUseOfDecl(OperatorDelete, StartLoc); | |||
3641 | ||||
3642 | // Convert the operand to the type of the first parameter of operator | |||
3643 | // delete. This is only necessary if we selected a destroying operator | |||
3644 | // delete that we are going to call (non-virtually); converting to void* | |||
3645 | // is trivial and left to AST consumers to handle. | |||
3646 | QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); | |||
3647 | if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) { | |||
3648 | Qualifiers Qs = Pointee.getQualifiers(); | |||
3649 | if (Qs.hasCVRQualifiers()) { | |||
3650 | // Qualifiers are irrelevant to this conversion; we're only looking | |||
3651 | // for access and ambiguity. | |||
3652 | Qs.removeCVRQualifiers(); | |||
3653 | QualType Unqual = Context.getPointerType( | |||
3654 | Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs)); | |||
3655 | Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp); | |||
3656 | } | |||
3657 | Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing); | |||
3658 | if (Ex.isInvalid()) | |||
3659 | return ExprError(); | |||
3660 | } | |||
3661 | } | |||
3662 | ||||
3663 | CXXDeleteExpr *Result = new (Context) CXXDeleteExpr( | |||
3664 | Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten, | |||
3665 | UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc); | |||
3666 | AnalyzeDeleteExprMismatch(Result); | |||
3667 | return Result; | |||
3668 | } | |||
3669 | ||||
3670 | static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall, | |||
3671 | bool IsDelete, | |||
3672 | FunctionDecl *&Operator) { | |||
3673 | ||||
3674 | DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName( | |||
3675 | IsDelete ? OO_Delete : OO_New); | |||
3676 | ||||
3677 | LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName); | |||
3678 | S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl()); | |||
3679 | assert(!R.empty() && "implicitly declared allocation functions not found")(static_cast <bool> (!R.empty() && "implicitly declared allocation functions not found" ) ? void (0) : __assert_fail ("!R.empty() && \"implicitly declared allocation functions not found\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 3679, __extension__ __PRETTY_FUNCTION__)); | |||
3680 | assert(!R.isAmbiguous() && "global allocation functions are ambiguous")(static_cast <bool> (!R.isAmbiguous() && "global allocation functions are ambiguous" ) ? void (0) : __assert_fail ("!R.isAmbiguous() && \"global allocation functions are ambiguous\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 3680, __extension__ __PRETTY_FUNCTION__)); | |||
3681 | ||||
3682 | // We do our own custom access checks below. | |||
3683 | R.suppressDiagnostics(); | |||
3684 | ||||
3685 | SmallVector<Expr *, 8> Args(TheCall->arg_begin(), TheCall->arg_end()); | |||
3686 | OverloadCandidateSet Candidates(R.getNameLoc(), | |||
3687 | OverloadCandidateSet::CSK_Normal); | |||
3688 | for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end(); | |||
3689 | FnOvl != FnOvlEnd; ++FnOvl) { | |||
3690 | // Even member operator new/delete are implicitly treated as | |||
3691 | // static, so don't use AddMemberCandidate. | |||
3692 | NamedDecl *D = (*FnOvl)->getUnderlyingDecl(); | |||
3693 | ||||
3694 | if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { | |||
3695 | S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(), | |||
3696 | /*ExplicitTemplateArgs=*/nullptr, Args, | |||
3697 | Candidates, | |||
3698 | /*SuppressUserConversions=*/false); | |||
3699 | continue; | |||
3700 | } | |||
3701 | ||||
3702 | FunctionDecl *Fn = cast<FunctionDecl>(D); | |||
3703 | S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates, | |||
3704 | /*SuppressUserConversions=*/false); | |||
3705 | } | |||
3706 | ||||
3707 | SourceRange Range = TheCall->getSourceRange(); | |||
3708 | ||||
3709 | // Do the resolution. | |||
3710 | OverloadCandidateSet::iterator Best; | |||
3711 | switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) { | |||
3712 | case OR_Success: { | |||
3713 | // Got one! | |||
3714 | FunctionDecl *FnDecl = Best->Function; | |||
3715 | assert(R.getNamingClass() == nullptr &&(static_cast <bool> (R.getNamingClass() == nullptr && "class members should not be considered") ? void (0) : __assert_fail ("R.getNamingClass() == nullptr && \"class members should not be considered\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 3716, __extension__ __PRETTY_FUNCTION__)) | |||
3716 | "class members should not be considered")(static_cast <bool> (R.getNamingClass() == nullptr && "class members should not be considered") ? void (0) : __assert_fail ("R.getNamingClass() == nullptr && \"class members should not be considered\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 3716, __extension__ __PRETTY_FUNCTION__)); | |||
3717 | ||||
3718 | if (!FnDecl->isReplaceableGlobalAllocationFunction()) { | |||
3719 | S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual) | |||
3720 | << (IsDelete ? 1 : 0) << Range; | |||
3721 | S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here) | |||
3722 | << R.getLookupName() << FnDecl->getSourceRange(); | |||
3723 | return true; | |||
3724 | } | |||
3725 | ||||
3726 | Operator = FnDecl; | |||
3727 | return false; | |||
3728 | } | |||
3729 | ||||
3730 | case OR_No_Viable_Function: | |||
3731 | Candidates.NoteCandidates( | |||
3732 | PartialDiagnosticAt(R.getNameLoc(), | |||
3733 | S.PDiag(diag::err_ovl_no_viable_function_in_call) | |||
3734 | << R.getLookupName() << Range), | |||
3735 | S, OCD_AllCandidates, Args); | |||
3736 | return true; | |||
3737 | ||||
3738 | case OR_Ambiguous: | |||
3739 | Candidates.NoteCandidates( | |||
3740 | PartialDiagnosticAt(R.getNameLoc(), | |||
3741 | S.PDiag(diag::err_ovl_ambiguous_call) | |||
3742 | << R.getLookupName() << Range), | |||
3743 | S, OCD_AmbiguousCandidates, Args); | |||
3744 | return true; | |||
3745 | ||||
3746 | case OR_Deleted: { | |||
3747 | Candidates.NoteCandidates( | |||
3748 | PartialDiagnosticAt(R.getNameLoc(), S.PDiag(diag::err_ovl_deleted_call) | |||
3749 | << R.getLookupName() << Range), | |||
3750 | S, OCD_AllCandidates, Args); | |||
3751 | return true; | |||
3752 | } | |||
3753 | } | |||
3754 | llvm_unreachable("Unreachable, bad result from BestViableFunction")::llvm::llvm_unreachable_internal("Unreachable, bad result from BestViableFunction" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 3754); | |||
3755 | } | |||
3756 | ||||
3757 | ExprResult | |||
3758 | Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, | |||
3759 | bool IsDelete) { | |||
3760 | CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); | |||
3761 | if (!getLangOpts().CPlusPlus) { | |||
3762 | Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language) | |||
3763 | << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new") | |||
3764 | << "C++"; | |||
3765 | return ExprError(); | |||
3766 | } | |||
3767 | // CodeGen assumes it can find the global new and delete to call, | |||
3768 | // so ensure that they are declared. | |||
3769 | DeclareGlobalNewDelete(); | |||
3770 | ||||
3771 | FunctionDecl *OperatorNewOrDelete = nullptr; | |||
3772 | if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete, | |||
3773 | OperatorNewOrDelete)) | |||
3774 | return ExprError(); | |||
3775 | assert(OperatorNewOrDelete && "should be found")(static_cast <bool> (OperatorNewOrDelete && "should be found" ) ? void (0) : __assert_fail ("OperatorNewOrDelete && \"should be found\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 3775, __extension__ __PRETTY_FUNCTION__)); | |||
3776 | ||||
3777 | DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc()); | |||
3778 | MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete); | |||
3779 | ||||
3780 | TheCall->setType(OperatorNewOrDelete->getReturnType()); | |||
3781 | for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) { | |||
3782 | QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType(); | |||
3783 | InitializedEntity Entity = | |||
3784 | InitializedEntity::InitializeParameter(Context, ParamTy, false); | |||
3785 | ExprResult Arg = PerformCopyInitialization( | |||
3786 | Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i)); | |||
3787 | if (Arg.isInvalid()) | |||
3788 | return ExprError(); | |||
3789 | TheCall->setArg(i, Arg.get()); | |||
3790 | } | |||
3791 | auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee()); | |||
3792 | assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&(static_cast <bool> (Callee && Callee->getCastKind () == CK_BuiltinFnToFnPtr && "Callee expected to be implicit cast to a builtin function pointer" ) ? void (0) : __assert_fail ("Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr && \"Callee expected to be implicit cast to a builtin function pointer\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 3793, __extension__ __PRETTY_FUNCTION__)) | |||
3793 | "Callee expected to be implicit cast to a builtin function pointer")(static_cast <bool> (Callee && Callee->getCastKind () == CK_BuiltinFnToFnPtr && "Callee expected to be implicit cast to a builtin function pointer" ) ? void (0) : __assert_fail ("Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr && \"Callee expected to be implicit cast to a builtin function pointer\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 3793, __extension__ __PRETTY_FUNCTION__)); | |||
3794 | Callee->setType(OperatorNewOrDelete->getType()); | |||
3795 | ||||
3796 | return TheCallResult; | |||
3797 | } | |||
3798 | ||||
3799 | void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, | |||
3800 | bool IsDelete, bool CallCanBeVirtual, | |||
3801 | bool WarnOnNonAbstractTypes, | |||
3802 | SourceLocation DtorLoc) { | |||
3803 | if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext()) | |||
3804 | return; | |||
3805 | ||||
3806 | // C++ [expr.delete]p3: | |||
3807 | // In the first alternative (delete object), if the static type of the | |||
3808 | // object to be deleted is different from its dynamic type, the static | |||
3809 | // type shall be a base class of the dynamic type of the object to be | |||
3810 | // deleted and the static type shall have a virtual destructor or the | |||
3811 | // behavior is undefined. | |||
3812 | // | |||
3813 | const CXXRecordDecl *PointeeRD = dtor->getParent(); | |||
3814 | // Note: a final class cannot be derived from, no issue there | |||
3815 | if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>()) | |||
3816 | return; | |||
3817 | ||||
3818 | // If the superclass is in a system header, there's nothing that can be done. | |||
3819 | // The `delete` (where we emit the warning) can be in a system header, | |||
3820 | // what matters for this warning is where the deleted type is defined. | |||
3821 | if (getSourceManager().isInSystemHeader(PointeeRD->getLocation())) | |||
3822 | return; | |||
3823 | ||||
3824 | QualType ClassType = dtor->getThisType()->getPointeeType(); | |||
3825 | if (PointeeRD->isAbstract()) { | |||
3826 | // If the class is abstract, we warn by default, because we're | |||
3827 | // sure the code has undefined behavior. | |||
3828 | Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1) | |||
3829 | << ClassType; | |||
3830 | } else if (WarnOnNonAbstractTypes) { | |||
3831 | // Otherwise, if this is not an array delete, it's a bit suspect, | |||
3832 | // but not necessarily wrong. | |||
3833 | Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1) | |||
3834 | << ClassType; | |||
3835 | } | |||
3836 | if (!IsDelete) { | |||
3837 | std::string TypeStr; | |||
3838 | ClassType.getAsStringInternal(TypeStr, getPrintingPolicy()); | |||
3839 | Diag(DtorLoc, diag::note_delete_non_virtual) | |||
3840 | << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::"); | |||
3841 | } | |||
3842 | } | |||
3843 | ||||
3844 | Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar, | |||
3845 | SourceLocation StmtLoc, | |||
3846 | ConditionKind CK) { | |||
3847 | ExprResult E = | |||
3848 | CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK); | |||
3849 | if (E.isInvalid()) | |||
3850 | return ConditionError(); | |||
3851 | return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc), | |||
3852 | CK == ConditionKind::ConstexprIf); | |||
3853 | } | |||
3854 | ||||
3855 | /// Check the use of the given variable as a C++ condition in an if, | |||
3856 | /// while, do-while, or switch statement. | |||
3857 | ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar, | |||
3858 | SourceLocation StmtLoc, | |||
3859 | ConditionKind CK) { | |||
3860 | if (ConditionVar->isInvalidDecl()) | |||
3861 | return ExprError(); | |||
3862 | ||||
3863 | QualType T = ConditionVar->getType(); | |||
3864 | ||||
3865 | // C++ [stmt.select]p2: | |||
3866 | // The declarator shall not specify a function or an array. | |||
3867 | if (T->isFunctionType()) | |||
3868 | return ExprError(Diag(ConditionVar->getLocation(), | |||
3869 | diag::err_invalid_use_of_function_type) | |||
3870 | << ConditionVar->getSourceRange()); | |||
3871 | else if (T->isArrayType()) | |||
3872 | return ExprError(Diag(ConditionVar->getLocation(), | |||
3873 | diag::err_invalid_use_of_array_type) | |||
3874 | << ConditionVar->getSourceRange()); | |||
3875 | ||||
3876 | ExprResult Condition = BuildDeclRefExpr( | |||
3877 | ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue, | |||
3878 | ConditionVar->getLocation()); | |||
3879 | ||||
3880 | switch (CK) { | |||
3881 | case ConditionKind::Boolean: | |||
3882 | return CheckBooleanCondition(StmtLoc, Condition.get()); | |||
3883 | ||||
3884 | case ConditionKind::ConstexprIf: | |||
3885 | return CheckBooleanCondition(StmtLoc, Condition.get(), true); | |||
3886 | ||||
3887 | case ConditionKind::Switch: | |||
3888 | return CheckSwitchCondition(StmtLoc, Condition.get()); | |||
3889 | } | |||
3890 | ||||
3891 | llvm_unreachable("unexpected condition kind")::llvm::llvm_unreachable_internal("unexpected condition kind" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 3891); | |||
3892 | } | |||
3893 | ||||
3894 | /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid. | |||
3895 | ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) { | |||
3896 | // C++ 6.4p4: | |||
3897 | // The value of a condition that is an initialized declaration in a statement | |||
3898 | // other than a switch statement is the value of the declared variable | |||
3899 | // implicitly converted to type bool. If that conversion is ill-formed, the | |||
3900 | // program is ill-formed. | |||
3901 | // The value of a condition that is an expression is the value of the | |||
3902 | // expression, implicitly converted to bool. | |||
3903 | // | |||
3904 | // FIXME: Return this value to the caller so they don't need to recompute it. | |||
3905 | llvm::APSInt Value(/*BitWidth*/1); | |||
3906 | return (IsConstexpr && !CondExpr->isValueDependent()) | |||
3907 | ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value, | |||
3908 | CCEK_ConstexprIf) | |||
3909 | : PerformContextuallyConvertToBool(CondExpr); | |||
3910 | } | |||
3911 | ||||
3912 | /// Helper function to determine whether this is the (deprecated) C++ | |||
3913 | /// conversion from a string literal to a pointer to non-const char or | |||
3914 | /// non-const wchar_t (for narrow and wide string literals, | |||
3915 | /// respectively). | |||
3916 | bool | |||
3917 | Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { | |||
3918 | // Look inside the implicit cast, if it exists. | |||
3919 | if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) | |||
3920 | From = Cast->getSubExpr(); | |||
3921 | ||||
3922 | // A string literal (2.13.4) that is not a wide string literal can | |||
3923 | // be converted to an rvalue of type "pointer to char"; a wide | |||
3924 | // string literal can be converted to an rvalue of type "pointer | |||
3925 | // to wchar_t" (C++ 4.2p2). | |||
3926 | if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens())) | |||
3927 | if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) | |||
3928 | if (const BuiltinType *ToPointeeType | |||
3929 | = ToPtrType->getPointeeType()->getAs<BuiltinType>()) { | |||
3930 | // This conversion is considered only when there is an | |||
3931 | // explicit appropriate pointer target type (C++ 4.2p2). | |||
3932 | if (!ToPtrType->getPointeeType().hasQualifiers()) { | |||
3933 | switch (StrLit->getKind()) { | |||
3934 | case StringLiteral::UTF8: | |||
3935 | case StringLiteral::UTF16: | |||
3936 | case StringLiteral::UTF32: | |||
3937 | // We don't allow UTF literals to be implicitly converted | |||
3938 | break; | |||
3939 | case StringLiteral::Ascii: | |||
3940 | return (ToPointeeType->getKind() == BuiltinType::Char_U || | |||
3941 | ToPointeeType->getKind() == BuiltinType::Char_S); | |||
3942 | case StringLiteral::Wide: | |||
3943 | return Context.typesAreCompatible(Context.getWideCharType(), | |||
3944 | QualType(ToPointeeType, 0)); | |||
3945 | } | |||
3946 | } | |||
3947 | } | |||
3948 | ||||
3949 | return false; | |||
3950 | } | |||
3951 | ||||
3952 | static ExprResult BuildCXXCastArgument(Sema &S, | |||
3953 | SourceLocation CastLoc, | |||
3954 | QualType Ty, | |||
3955 | CastKind Kind, | |||
3956 | CXXMethodDecl *Method, | |||
3957 | DeclAccessPair FoundDecl, | |||
3958 | bool HadMultipleCandidates, | |||
3959 | Expr *From) { | |||
3960 | switch (Kind) { | |||
3961 | default: llvm_unreachable("Unhandled cast kind!")::llvm::llvm_unreachable_internal("Unhandled cast kind!", "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 3961); | |||
3962 | case CK_ConstructorConversion: { | |||
3963 | CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method); | |||
3964 | SmallVector<Expr*, 8> ConstructorArgs; | |||
3965 | ||||
3966 | if (S.RequireNonAbstractType(CastLoc, Ty, | |||
3967 | diag::err_allocation_of_abstract_type)) | |||
3968 | return ExprError(); | |||
3969 | ||||
3970 | if (S.CompleteConstructorCall(Constructor, Ty, From, CastLoc, | |||
3971 | ConstructorArgs)) | |||
3972 | return ExprError(); | |||
3973 | ||||
3974 | S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl, | |||
3975 | InitializedEntity::InitializeTemporary(Ty)); | |||
3976 | if (S.DiagnoseUseOfDecl(Method, CastLoc)) | |||
3977 | return ExprError(); | |||
3978 | ||||
3979 | ExprResult Result = S.BuildCXXConstructExpr( | |||
3980 | CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method), | |||
3981 | ConstructorArgs, HadMultipleCandidates, | |||
3982 | /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, | |||
3983 | CXXConstructExpr::CK_Complete, SourceRange()); | |||
3984 | if (Result.isInvalid()) | |||
3985 | return ExprError(); | |||
3986 | ||||
3987 | return S.MaybeBindToTemporary(Result.getAs<Expr>()); | |||
3988 | } | |||
3989 | ||||
3990 | case CK_UserDefinedConversion: { | |||
3991 | assert(!From->getType()->isPointerType() && "Arg can't have pointer type!")(static_cast <bool> (!From->getType()->isPointerType () && "Arg can't have pointer type!") ? void (0) : __assert_fail ("!From->getType()->isPointerType() && \"Arg can't have pointer type!\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 3991, __extension__ __PRETTY_FUNCTION__)); | |||
3992 | ||||
3993 | S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl); | |||
3994 | if (S.DiagnoseUseOfDecl(Method, CastLoc)) | |||
3995 | return ExprError(); | |||
3996 | ||||
3997 | // Create an implicit call expr that calls it. | |||
3998 | CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method); | |||
3999 | ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv, | |||
4000 | HadMultipleCandidates); | |||
4001 | if (Result.isInvalid()) | |||
4002 | return ExprError(); | |||
4003 | // Record usage of conversion in an implicit cast. | |||
4004 | Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(), | |||
4005 | CK_UserDefinedConversion, Result.get(), | |||
4006 | nullptr, Result.get()->getValueKind(), | |||
4007 | S.CurFPFeatureOverrides()); | |||
4008 | ||||
4009 | return S.MaybeBindToTemporary(Result.get()); | |||
4010 | } | |||
4011 | } | |||
4012 | } | |||
4013 | ||||
4014 | /// PerformImplicitConversion - Perform an implicit conversion of the | |||
4015 | /// expression From to the type ToType using the pre-computed implicit | |||
4016 | /// conversion sequence ICS. Returns the converted | |||
4017 | /// expression. Action is the kind of conversion we're performing, | |||
4018 | /// used in the error message. | |||
4019 | ExprResult | |||
4020 | Sema::PerformImplicitConversion(Expr *From, QualType ToType, | |||
4021 | const ImplicitConversionSequence &ICS, | |||
4022 | AssignmentAction Action, | |||
4023 | CheckedConversionKind CCK) { | |||
4024 | // C++ [over.match.oper]p7: [...] operands of class type are converted [...] | |||
4025 | if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType()) | |||
4026 | return From; | |||
4027 | ||||
4028 | switch (ICS.getKind()) { | |||
4029 | case ImplicitConversionSequence::StandardConversion: { | |||
4030 | ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard, | |||
4031 | Action, CCK); | |||
4032 | if (Res.isInvalid()) | |||
4033 | return ExprError(); | |||
4034 | From = Res.get(); | |||
4035 | break; | |||
4036 | } | |||
4037 | ||||
4038 | case ImplicitConversionSequence::UserDefinedConversion: { | |||
4039 | ||||
4040 | FunctionDecl *FD = ICS.UserDefined.ConversionFunction; | |||
4041 | CastKind CastKind; | |||
4042 | QualType BeforeToType; | |||
4043 | assert(FD && "no conversion function for user-defined conversion seq")(static_cast <bool> (FD && "no conversion function for user-defined conversion seq" ) ? void (0) : __assert_fail ("FD && \"no conversion function for user-defined conversion seq\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 4043, __extension__ __PRETTY_FUNCTION__)); | |||
4044 | if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) { | |||
4045 | CastKind = CK_UserDefinedConversion; | |||
4046 | ||||
4047 | // If the user-defined conversion is specified by a conversion function, | |||
4048 | // the initial standard conversion sequence converts the source type to | |||
4049 | // the implicit object parameter of the conversion function. | |||
4050 | BeforeToType = Context.getTagDeclType(Conv->getParent()); | |||
4051 | } else { | |||
4052 | const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD); | |||
4053 | CastKind = CK_ConstructorConversion; | |||
4054 | // Do no conversion if dealing with ... for the first conversion. | |||
4055 | if (!ICS.UserDefined.EllipsisConversion) { | |||
4056 | // If the user-defined conversion is specified by a constructor, the | |||
4057 | // initial standard conversion sequence converts the source type to | |||
4058 | // the type required by the argument of the constructor | |||
4059 | BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType(); | |||
4060 | } | |||
4061 | } | |||
4062 | // Watch out for ellipsis conversion. | |||
4063 | if (!ICS.UserDefined.EllipsisConversion) { | |||
4064 | ExprResult Res = | |||
4065 | PerformImplicitConversion(From, BeforeToType, | |||
4066 | ICS.UserDefined.Before, AA_Converting, | |||
4067 | CCK); | |||
4068 | if (Res.isInvalid()) | |||
4069 | return ExprError(); | |||
4070 | From = Res.get(); | |||
4071 | } | |||
4072 | ||||
4073 | ExprResult CastArg = BuildCXXCastArgument( | |||
4074 | *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind, | |||
4075 | cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction, | |||
4076 | ICS.UserDefined.HadMultipleCandidates, From); | |||
4077 | ||||
4078 | if (CastArg.isInvalid()) | |||
4079 | return ExprError(); | |||
4080 | ||||
4081 | From = CastArg.get(); | |||
4082 | ||||
4083 | // C++ [over.match.oper]p7: | |||
4084 | // [...] the second standard conversion sequence of a user-defined | |||
4085 | // conversion sequence is not applied. | |||
4086 | if (CCK == CCK_ForBuiltinOverloadedOp) | |||
4087 | return From; | |||
4088 | ||||
4089 | return PerformImplicitConversion(From, ToType, ICS.UserDefined.After, | |||
4090 | AA_Converting, CCK); | |||
4091 | } | |||
4092 | ||||
4093 | case ImplicitConversionSequence::AmbiguousConversion: | |||
4094 | ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(), | |||
4095 | PDiag(diag::err_typecheck_ambiguous_condition) | |||
4096 | << From->getSourceRange()); | |||
4097 | return ExprError(); | |||
4098 | ||||
4099 | case ImplicitConversionSequence::EllipsisConversion: | |||
4100 | llvm_unreachable("Cannot perform an ellipsis conversion")::llvm::llvm_unreachable_internal("Cannot perform an ellipsis conversion" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 4100); | |||
4101 | ||||
4102 | case ImplicitConversionSequence::BadConversion: | |||
4103 | Sema::AssignConvertType ConvTy = | |||
4104 | CheckAssignmentConstraints(From->getExprLoc(), ToType, From->getType()); | |||
4105 | bool Diagnosed = DiagnoseAssignmentResult( | |||
4106 | ConvTy == Compatible ? Incompatible : ConvTy, From->getExprLoc(), | |||
4107 | ToType, From->getType(), From, Action); | |||
4108 | assert(Diagnosed && "failed to diagnose bad conversion")(static_cast <bool> (Diagnosed && "failed to diagnose bad conversion" ) ? void (0) : __assert_fail ("Diagnosed && \"failed to diagnose bad conversion\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 4108, __extension__ __PRETTY_FUNCTION__)); (void)Diagnosed; | |||
4109 | return ExprError(); | |||
4110 | } | |||
4111 | ||||
4112 | // Everything went well. | |||
4113 | return From; | |||
4114 | } | |||
4115 | ||||
4116 | /// PerformImplicitConversion - Perform an implicit conversion of the | |||
4117 | /// expression From to the type ToType by following the standard | |||
4118 | /// conversion sequence SCS. Returns the converted | |||
4119 | /// expression. Flavor is the context in which we're performing this | |||
4120 | /// conversion, for use in error messages. | |||
4121 | ExprResult | |||
4122 | Sema::PerformImplicitConversion(Expr *From, QualType ToType, | |||
4123 | const StandardConversionSequence& SCS, | |||
4124 | AssignmentAction Action, | |||
4125 | CheckedConversionKind CCK) { | |||
4126 | bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast); | |||
4127 | ||||
4128 | // Overall FIXME: we are recomputing too many types here and doing far too | |||
4129 | // much extra work. What this means is that we need to keep track of more | |||
4130 | // information that is computed when we try the implicit conversion initially, | |||
4131 | // so that we don't need to recompute anything here. | |||
4132 | QualType FromType = From->getType(); | |||
4133 | ||||
4134 | if (SCS.CopyConstructor) { | |||
4135 | // FIXME: When can ToType be a reference type? | |||
4136 | assert(!ToType->isReferenceType())(static_cast <bool> (!ToType->isReferenceType()) ? void (0) : __assert_fail ("!ToType->isReferenceType()", "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 4136, __extension__ __PRETTY_FUNCTION__)); | |||
4137 | if (SCS.Second == ICK_Derived_To_Base) { | |||
4138 | SmallVector<Expr*, 8> ConstructorArgs; | |||
4139 | if (CompleteConstructorCall( | |||
4140 | cast<CXXConstructorDecl>(SCS.CopyConstructor), ToType, From, | |||
4141 | /*FIXME:ConstructLoc*/ SourceLocation(), ConstructorArgs)) | |||
4142 | return ExprError(); | |||
4143 | return BuildCXXConstructExpr( | |||
4144 | /*FIXME:ConstructLoc*/ SourceLocation(), ToType, | |||
4145 | SCS.FoundCopyConstructor, SCS.CopyConstructor, | |||
4146 | ConstructorArgs, /*HadMultipleCandidates*/ false, | |||
4147 | /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, | |||
4148 | CXXConstructExpr::CK_Complete, SourceRange()); | |||
4149 | } | |||
4150 | return BuildCXXConstructExpr( | |||
4151 | /*FIXME:ConstructLoc*/ SourceLocation(), ToType, | |||
4152 | SCS.FoundCopyConstructor, SCS.CopyConstructor, | |||
4153 | From, /*HadMultipleCandidates*/ false, | |||
4154 | /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, | |||
4155 | CXXConstructExpr::CK_Complete, SourceRange()); | |||
4156 | } | |||
4157 | ||||
4158 | // Resolve overloaded function references. | |||
4159 | if (Context.hasSameType(FromType, Context.OverloadTy)) { | |||
4160 | DeclAccessPair Found; | |||
4161 | FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, | |||
4162 | true, Found); | |||
4163 | if (!Fn) | |||
4164 | return ExprError(); | |||
4165 | ||||
4166 | if (DiagnoseUseOfDecl(Fn, From->getBeginLoc())) | |||
4167 | return ExprError(); | |||
4168 | ||||
4169 | From = FixOverloadedFunctionReference(From, Found, Fn); | |||
4170 | FromType = From->getType(); | |||
4171 | } | |||
4172 | ||||
4173 | // If we're converting to an atomic type, first convert to the corresponding | |||
4174 | // non-atomic type. | |||
4175 | QualType ToAtomicType; | |||
4176 | if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) { | |||
4177 | ToAtomicType = ToType; | |||
4178 | ToType = ToAtomic->getValueType(); | |||
4179 | } | |||
4180 | ||||
4181 | QualType InitialFromType = FromType; | |||
4182 | // Perform the first implicit conversion. | |||
4183 | switch (SCS.First) { | |||
4184 | case ICK_Identity: | |||
4185 | if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) { | |||
4186 | FromType = FromAtomic->getValueType().getUnqualifiedType(); | |||
4187 | From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic, | |||
4188 | From, /*BasePath=*/nullptr, VK_RValue, | |||
4189 | FPOptionsOverride()); | |||
4190 | } | |||
4191 | break; | |||
4192 | ||||
4193 | case ICK_Lvalue_To_Rvalue: { | |||
4194 | assert(From->getObjectKind() != OK_ObjCProperty)(static_cast <bool> (From->getObjectKind() != OK_ObjCProperty ) ? void (0) : __assert_fail ("From->getObjectKind() != OK_ObjCProperty" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 4194, __extension__ __PRETTY_FUNCTION__)); | |||
4195 | ExprResult FromRes = DefaultLvalueConversion(From); | |||
4196 | assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!")(static_cast <bool> (!FromRes.isInvalid() && "Can't perform deduced conversion?!" ) ? void (0) : __assert_fail ("!FromRes.isInvalid() && \"Can't perform deduced conversion?!\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 4196, __extension__ __PRETTY_FUNCTION__)); | |||
4197 | From = FromRes.get(); | |||
4198 | FromType = From->getType(); | |||
4199 | break; | |||
4200 | } | |||
4201 | ||||
4202 | case ICK_Array_To_Pointer: | |||
4203 | FromType = Context.getArrayDecayedType(FromType); | |||
4204 | From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, | |||
4205 | VK_RValue, /*BasePath=*/nullptr, CCK).get(); | |||
4206 | break; | |||
4207 | ||||
4208 | case ICK_Function_To_Pointer: | |||
4209 | FromType = Context.getPointerType(FromType); | |||
4210 | From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay, | |||
4211 | VK_RValue, /*BasePath=*/nullptr, CCK).get(); | |||
4212 | break; | |||
4213 | ||||
4214 | default: | |||
4215 | llvm_unreachable("Improper first standard conversion")::llvm::llvm_unreachable_internal("Improper first standard conversion" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 4215); | |||
4216 | } | |||
4217 | ||||
4218 | // Perform the second implicit conversion | |||
4219 | switch (SCS.Second) { | |||
4220 | case ICK_Identity: | |||
4221 | // C++ [except.spec]p5: | |||
4222 | // [For] assignment to and initialization of pointers to functions, | |||
4223 | // pointers to member functions, and references to functions: the | |||
4224 | // target entity shall allow at least the exceptions allowed by the | |||
4225 | // source value in the assignment or initialization. | |||
4226 | switch (Action) { | |||
4227 | case AA_Assigning: | |||
4228 | case AA_Initializing: | |||
4229 | // Note, function argument passing and returning are initialization. | |||
4230 | case AA_Passing: | |||
4231 | case AA_Returning: | |||
4232 | case AA_Sending: | |||
4233 | case AA_Passing_CFAudited: | |||
4234 | if (CheckExceptionSpecCompatibility(From, ToType)) | |||
4235 | return ExprError(); | |||
4236 | break; | |||
4237 | ||||
4238 | case AA_Casting: | |||
4239 | case AA_Converting: | |||
4240 | // Casts and implicit conversions are not initialization, so are not | |||
4241 | // checked for exception specification mismatches. | |||
4242 | break; | |||
4243 | } | |||
4244 | // Nothing else to do. | |||
4245 | break; | |||
4246 | ||||
4247 | case ICK_Integral_Promotion: | |||
4248 | case ICK_Integral_Conversion: | |||
4249 | if (ToType->isBooleanType()) { | |||
4250 | assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&(static_cast <bool> (FromType->castAs<EnumType> ()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && "only enums with fixed underlying type can promote to bool" ) ? void (0) : __assert_fail ("FromType->castAs<EnumType>()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && \"only enums with fixed underlying type can promote to bool\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 4252, __extension__ __PRETTY_FUNCTION__)) | |||
4251 | SCS.Second == ICK_Integral_Promotion &&(static_cast <bool> (FromType->castAs<EnumType> ()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && "only enums with fixed underlying type can promote to bool" ) ? void (0) : __assert_fail ("FromType->castAs<EnumType>()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && \"only enums with fixed underlying type can promote to bool\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 4252, __extension__ __PRETTY_FUNCTION__)) | |||
4252 | "only enums with fixed underlying type can promote to bool")(static_cast <bool> (FromType->castAs<EnumType> ()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && "only enums with fixed underlying type can promote to bool" ) ? void (0) : __assert_fail ("FromType->castAs<EnumType>()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && \"only enums with fixed underlying type can promote to bool\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 4252, __extension__ __PRETTY_FUNCTION__)); | |||
4253 | From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean, | |||
4254 | VK_RValue, /*BasePath=*/nullptr, CCK).get(); | |||
4255 | } else { | |||
4256 | From = ImpCastExprToType(From, ToType, CK_IntegralCast, | |||
4257 | VK_RValue, /*BasePath=*/nullptr, CCK).get(); | |||
4258 | } | |||
4259 | break; | |||
4260 | ||||
4261 | case ICK_Floating_Promotion: | |||
4262 | case ICK_Floating_Conversion: | |||
4263 | From = ImpCastExprToType(From, ToType, CK_FloatingCast, | |||
4264 | VK_RValue, /*BasePath=*/nullptr, CCK).get(); | |||
4265 | break; | |||
4266 | ||||
4267 | case ICK_Complex_Promotion: | |||
4268 | case ICK_Complex_Conversion: { | |||
4269 | QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType(); | |||
4270 | QualType ToEl = ToType->castAs<ComplexType>()->getElementType(); | |||
4271 | CastKind CK; | |||
4272 | if (FromEl->isRealFloatingType()) { | |||
4273 | if (ToEl->isRealFloatingType()) | |||
4274 | CK = CK_FloatingComplexCast; | |||
4275 | else | |||
4276 | CK = CK_FloatingComplexToIntegralComplex; | |||
4277 | } else if (ToEl->isRealFloatingType()) { | |||
4278 | CK = CK_IntegralComplexToFloatingComplex; | |||
4279 | } else { | |||
4280 | CK = CK_IntegralComplexCast; | |||
4281 | } | |||
4282 | From = ImpCastExprToType(From, ToType, CK, | |||
4283 | VK_RValue, /*BasePath=*/nullptr, CCK).get(); | |||
4284 | break; | |||
4285 | } | |||
4286 | ||||
4287 | case ICK_Floating_Integral: | |||
4288 | if (ToType->isRealFloatingType()) | |||
4289 | From = ImpCastExprToType(From, ToType, CK_IntegralToFloating, | |||
4290 | VK_RValue, /*BasePath=*/nullptr, CCK).get(); | |||
4291 | else | |||
4292 | From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral, | |||
4293 | VK_RValue, /*BasePath=*/nullptr, CCK).get(); | |||
4294 | break; | |||
4295 | ||||
4296 | case ICK_Compatible_Conversion: | |||
4297 | From = ImpCastExprToType(From, ToType, CK_NoOp, From->getValueKind(), | |||
4298 | /*BasePath=*/nullptr, CCK).get(); | |||
4299 | break; | |||
4300 | ||||
4301 | case ICK_Writeback_Conversion: | |||
4302 | case ICK_Pointer_Conversion: { | |||
4303 | if (SCS.IncompatibleObjC && Action != AA_Casting) { | |||
4304 | // Diagnose incompatible Objective-C conversions | |||
4305 | if (Action == AA_Initializing || Action == AA_Assigning) | |||
4306 | Diag(From->getBeginLoc(), | |||
4307 | diag::ext_typecheck_convert_incompatible_pointer) | |||
4308 | << ToType << From->getType() << Action << From->getSourceRange() | |||
4309 | << 0; | |||
4310 | else | |||
4311 | Diag(From->getBeginLoc(), | |||
4312 | diag::ext_typecheck_convert_incompatible_pointer) | |||
4313 | << From->getType() << ToType << Action << From->getSourceRange() | |||
4314 | << 0; | |||
4315 | ||||
4316 | if (From->getType()->isObjCObjectPointerType() && | |||
4317 | ToType->isObjCObjectPointerType()) | |||
4318 | EmitRelatedResultTypeNote(From); | |||
4319 | } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && | |||
4320 | !CheckObjCARCUnavailableWeakConversion(ToType, | |||
4321 | From->getType())) { | |||
4322 | if (Action == AA_Initializing) | |||
4323 | Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign); | |||
4324 | else | |||
4325 | Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable) | |||
4326 | << (Action == AA_Casting) << From->getType() << ToType | |||
4327 | << From->getSourceRange(); | |||
4328 | } | |||
4329 | ||||
4330 | // Defer address space conversion to the third conversion. | |||
4331 | QualType FromPteeType = From->getType()->getPointeeType(); | |||
4332 | QualType ToPteeType = ToType->getPointeeType(); | |||
4333 | QualType NewToType = ToType; | |||
4334 | if (!FromPteeType.isNull() && !ToPteeType.isNull() && | |||
4335 | FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) { | |||
4336 | NewToType = Context.removeAddrSpaceQualType(ToPteeType); | |||
4337 | NewToType = Context.getAddrSpaceQualType(NewToType, | |||
4338 | FromPteeType.getAddressSpace()); | |||
4339 | if (ToType->isObjCObjectPointerType()) | |||
4340 | NewToType = Context.getObjCObjectPointerType(NewToType); | |||
4341 | else if (ToType->isBlockPointerType()) | |||
4342 | NewToType = Context.getBlockPointerType(NewToType); | |||
4343 | else | |||
4344 | NewToType = Context.getPointerType(NewToType); | |||
4345 | } | |||
4346 | ||||
4347 | CastKind Kind; | |||
4348 | CXXCastPath BasePath; | |||
4349 | if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle)) | |||
4350 | return ExprError(); | |||
4351 | ||||
4352 | // Make sure we extend blocks if necessary. | |||
4353 | // FIXME: doing this here is really ugly. | |||
4354 | if (Kind == CK_BlockPointerToObjCPointerCast) { | |||
4355 | ExprResult E = From; | |||
4356 | (void) PrepareCastToObjCObjectPointer(E); | |||
4357 | From = E.get(); | |||
4358 | } | |||
4359 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) | |||
4360 | CheckObjCConversion(SourceRange(), NewToType, From, CCK); | |||
4361 | From = ImpCastExprToType(From, NewToType, Kind, VK_RValue, &BasePath, CCK) | |||
4362 | .get(); | |||
4363 | break; | |||
4364 | } | |||
4365 | ||||
4366 | case ICK_Pointer_Member: { | |||
4367 | CastKind Kind; | |||
4368 | CXXCastPath BasePath; | |||
4369 | if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle)) | |||
4370 | return ExprError(); | |||
4371 | if (CheckExceptionSpecCompatibility(From, ToType)) | |||
4372 | return ExprError(); | |||
4373 | ||||
4374 | // We may not have been able to figure out what this member pointer resolved | |||
4375 | // to up until this exact point. Attempt to lock-in it's inheritance model. | |||
4376 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { | |||
4377 | (void)isCompleteType(From->getExprLoc(), From->getType()); | |||
4378 | (void)isCompleteType(From->getExprLoc(), ToType); | |||
4379 | } | |||
4380 | ||||
4381 | From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK) | |||
4382 | .get(); | |||
4383 | break; | |||
4384 | } | |||
4385 | ||||
4386 | case ICK_Boolean_Conversion: | |||
4387 | // Perform half-to-boolean conversion via float. | |||
4388 | if (From->getType()->isHalfType()) { | |||
4389 | From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get(); | |||
4390 | FromType = Context.FloatTy; | |||
4391 | } | |||
4392 | ||||
4393 | From = ImpCastExprToType(From, Context.BoolTy, | |||
4394 | ScalarTypeToBooleanCastKind(FromType), | |||
4395 | VK_RValue, /*BasePath=*/nullptr, CCK).get(); | |||
4396 | break; | |||
4397 | ||||
4398 | case ICK_Derived_To_Base: { | |||
4399 | CXXCastPath BasePath; | |||
4400 | if (CheckDerivedToBaseConversion( | |||
4401 | From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(), | |||
4402 | From->getSourceRange(), &BasePath, CStyle)) | |||
4403 | return ExprError(); | |||
4404 | ||||
4405 | From = ImpCastExprToType(From, ToType.getNonReferenceType(), | |||
4406 | CK_DerivedToBase, From->getValueKind(), | |||
4407 | &BasePath, CCK).get(); | |||
4408 | break; | |||
4409 | } | |||
4410 | ||||
4411 | case ICK_Vector_Conversion: | |||
4412 | From = ImpCastExprToType(From, ToType, CK_BitCast, | |||
4413 | VK_RValue, /*BasePath=*/nullptr, CCK).get(); | |||
4414 | break; | |||
4415 | ||||
4416 | case ICK_SVE_Vector_Conversion: | |||
4417 | From = ImpCastExprToType(From, ToType, CK_BitCast, VK_RValue, | |||
4418 | /*BasePath=*/nullptr, CCK) | |||
4419 | .get(); | |||
4420 | break; | |||
4421 | ||||
4422 | case ICK_Vector_Splat: { | |||
4423 | // Vector splat from any arithmetic type to a vector. | |||
4424 | Expr *Elem = prepareVectorSplat(ToType, From).get(); | |||
4425 | From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue, | |||
4426 | /*BasePath=*/nullptr, CCK).get(); | |||
4427 | break; | |||
4428 | } | |||
4429 | ||||
4430 | case ICK_Complex_Real: | |||
4431 | // Case 1. x -> _Complex y | |||
4432 | if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) { | |||
4433 | QualType ElType = ToComplex->getElementType(); | |||
4434 | bool isFloatingComplex = ElType->isRealFloatingType(); | |||
4435 | ||||
4436 | // x -> y | |||
4437 | if (Context.hasSameUnqualifiedType(ElType, From->getType())) { | |||
4438 | // do nothing | |||
4439 | } else if (From->getType()->isRealFloatingType()) { | |||
4440 | From = ImpCastExprToType(From, ElType, | |||
4441 | isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get(); | |||
4442 | } else { | |||
4443 | assert(From->getType()->isIntegerType())(static_cast <bool> (From->getType()->isIntegerType ()) ? void (0) : __assert_fail ("From->getType()->isIntegerType()" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 4443, __extension__ __PRETTY_FUNCTION__)); | |||
4444 | From = ImpCastExprToType(From, ElType, | |||
4445 | isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get(); | |||
4446 | } | |||
4447 | // y -> _Complex y | |||
4448 | From = ImpCastExprToType(From, ToType, | |||
4449 | isFloatingComplex ? CK_FloatingRealToComplex | |||
4450 | : CK_IntegralRealToComplex).get(); | |||
4451 | ||||
4452 | // Case 2. _Complex x -> y | |||
4453 | } else { | |||
4454 | auto *FromComplex = From->getType()->castAs<ComplexType>(); | |||
4455 | QualType ElType = FromComplex->getElementType(); | |||
4456 | bool isFloatingComplex = ElType->isRealFloatingType(); | |||
4457 | ||||
4458 | // _Complex x -> x | |||
4459 | From = ImpCastExprToType(From, ElType, | |||
4460 | isFloatingComplex ? CK_FloatingComplexToReal | |||
4461 | : CK_IntegralComplexToReal, | |||
4462 | VK_RValue, /*BasePath=*/nullptr, CCK).get(); | |||
4463 | ||||
4464 | // x -> y | |||
4465 | if (Context.hasSameUnqualifiedType(ElType, ToType)) { | |||
4466 | // do nothing | |||
4467 | } else if (ToType->isRealFloatingType()) { | |||
4468 | From = ImpCastExprToType(From, ToType, | |||
4469 | isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating, | |||
4470 | VK_RValue, /*BasePath=*/nullptr, CCK).get(); | |||
4471 | } else { | |||
4472 | assert(ToType->isIntegerType())(static_cast <bool> (ToType->isIntegerType()) ? void (0) : __assert_fail ("ToType->isIntegerType()", "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 4472, __extension__ __PRETTY_FUNCTION__)); | |||
4473 | From = ImpCastExprToType(From, ToType, | |||
4474 | isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast, | |||
4475 | VK_RValue, /*BasePath=*/nullptr, CCK).get(); | |||
4476 | } | |||
4477 | } | |||
4478 | break; | |||
4479 | ||||
4480 | case ICK_Block_Pointer_Conversion: { | |||
4481 | LangAS AddrSpaceL = | |||
4482 | ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace(); | |||
4483 | LangAS AddrSpaceR = | |||
4484 | FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace(); | |||
4485 | assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) &&(static_cast <bool> (Qualifiers::isAddressSpaceSupersetOf (AddrSpaceL, AddrSpaceR) && "Invalid cast") ? void (0 ) : __assert_fail ("Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) && \"Invalid cast\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 4486, __extension__ __PRETTY_FUNCTION__)) | |||
4486 | "Invalid cast")(static_cast <bool> (Qualifiers::isAddressSpaceSupersetOf (AddrSpaceL, AddrSpaceR) && "Invalid cast") ? void (0 ) : __assert_fail ("Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) && \"Invalid cast\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 4486, __extension__ __PRETTY_FUNCTION__)); | |||
4487 | CastKind Kind = | |||
4488 | AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; | |||
4489 | From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind, | |||
4490 | VK_RValue, /*BasePath=*/nullptr, CCK).get(); | |||
4491 | break; | |||
4492 | } | |||
4493 | ||||
4494 | case ICK_TransparentUnionConversion: { | |||
4495 | ExprResult FromRes = From; | |||
4496 | Sema::AssignConvertType ConvTy = | |||
4497 | CheckTransparentUnionArgumentConstraints(ToType, FromRes); | |||
4498 | if (FromRes.isInvalid()) | |||
4499 | return ExprError(); | |||
4500 | From = FromRes.get(); | |||
4501 | assert ((ConvTy == Sema::Compatible) &&(static_cast <bool> ((ConvTy == Sema::Compatible) && "Improper transparent union conversion") ? void (0) : __assert_fail ("(ConvTy == Sema::Compatible) && \"Improper transparent union conversion\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 4502, __extension__ __PRETTY_FUNCTION__)) | |||
4502 | "Improper transparent union conversion")(static_cast <bool> ((ConvTy == Sema::Compatible) && "Improper transparent union conversion") ? void (0) : __assert_fail ("(ConvTy == Sema::Compatible) && \"Improper transparent union conversion\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 4502, __extension__ __PRETTY_FUNCTION__)); | |||
4503 | (void)ConvTy; | |||
4504 | break; | |||
4505 | } | |||
4506 | ||||
4507 | case ICK_Zero_Event_Conversion: | |||
4508 | case ICK_Zero_Queue_Conversion: | |||
4509 | From = ImpCastExprToType(From, ToType, | |||
4510 | CK_ZeroToOCLOpaqueType, | |||
4511 | From->getValueKind()).get(); | |||
4512 | break; | |||
4513 | ||||
4514 | case ICK_Lvalue_To_Rvalue: | |||
4515 | case ICK_Array_To_Pointer: | |||
4516 | case ICK_Function_To_Pointer: | |||
4517 | case ICK_Function_Conversion: | |||
4518 | case ICK_Qualification: | |||
4519 | case ICK_Num_Conversion_Kinds: | |||
4520 | case ICK_C_Only_Conversion: | |||
4521 | case ICK_Incompatible_Pointer_Conversion: | |||
4522 | llvm_unreachable("Improper second standard conversion")::llvm::llvm_unreachable_internal("Improper second standard conversion" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 4522); | |||
4523 | } | |||
4524 | ||||
4525 | switch (SCS.Third) { | |||
4526 | case ICK_Identity: | |||
4527 | // Nothing to do. | |||
4528 | break; | |||
4529 | ||||
4530 | case ICK_Function_Conversion: | |||
4531 | // If both sides are functions (or pointers/references to them), there could | |||
4532 | // be incompatible exception declarations. | |||
4533 | if (CheckExceptionSpecCompatibility(From, ToType)) | |||
4534 | return ExprError(); | |||
4535 | ||||
4536 | From = ImpCastExprToType(From, ToType, CK_NoOp, | |||
4537 | VK_RValue, /*BasePath=*/nullptr, CCK).get(); | |||
4538 | break; | |||
4539 | ||||
4540 | case ICK_Qualification: { | |||
4541 | ExprValueKind VK = From->getValueKind(); | |||
4542 | CastKind CK = CK_NoOp; | |||
4543 | ||||
4544 | if (ToType->isReferenceType() && | |||
4545 | ToType->getPointeeType().getAddressSpace() != | |||
4546 | From->getType().getAddressSpace()) | |||
4547 | CK = CK_AddressSpaceConversion; | |||
4548 | ||||
4549 | if (ToType->isPointerType() && | |||
4550 | ToType->getPointeeType().getAddressSpace() != | |||
4551 | From->getType()->getPointeeType().getAddressSpace()) | |||
4552 | CK = CK_AddressSpaceConversion; | |||
4553 | ||||
4554 | From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK, | |||
4555 | /*BasePath=*/nullptr, CCK) | |||
4556 | .get(); | |||
4557 | ||||
4558 | if (SCS.DeprecatedStringLiteralToCharPtr && | |||
4559 | !getLangOpts().WritableStrings) { | |||
4560 | Diag(From->getBeginLoc(), | |||
4561 | getLangOpts().CPlusPlus11 | |||
4562 | ? diag::ext_deprecated_string_literal_conversion | |||
4563 | : diag::warn_deprecated_string_literal_conversion) | |||
4564 | << ToType.getNonReferenceType(); | |||
4565 | } | |||
4566 | ||||
4567 | break; | |||
4568 | } | |||
4569 | ||||
4570 | default: | |||
4571 | llvm_unreachable("Improper third standard conversion")::llvm::llvm_unreachable_internal("Improper third standard conversion" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 4571); | |||
4572 | } | |||
4573 | ||||
4574 | // If this conversion sequence involved a scalar -> atomic conversion, perform | |||
4575 | // that conversion now. | |||
4576 | if (!ToAtomicType.isNull()) { | |||
4577 | assert(Context.hasSameType((static_cast <bool> (Context.hasSameType( ToAtomicType-> castAs<AtomicType>()->getValueType(), From->getType ())) ? void (0) : __assert_fail ("Context.hasSameType( ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType())" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 4578, __extension__ __PRETTY_FUNCTION__)) | |||
4578 | ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()))(static_cast <bool> (Context.hasSameType( ToAtomicType-> castAs<AtomicType>()->getValueType(), From->getType ())) ? void (0) : __assert_fail ("Context.hasSameType( ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType())" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 4578, __extension__ __PRETTY_FUNCTION__)); | |||
4579 | From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic, | |||
4580 | VK_RValue, nullptr, CCK).get(); | |||
4581 | } | |||
4582 | ||||
4583 | // Materialize a temporary if we're implicitly converting to a reference | |||
4584 | // type. This is not required by the C++ rules but is necessary to maintain | |||
4585 | // AST invariants. | |||
4586 | if (ToType->isReferenceType() && From->isRValue()) { | |||
4587 | ExprResult Res = TemporaryMaterializationConversion(From); | |||
4588 | if (Res.isInvalid()) | |||
4589 | return ExprError(); | |||
4590 | From = Res.get(); | |||
4591 | } | |||
4592 | ||||
4593 | // If this conversion sequence succeeded and involved implicitly converting a | |||
4594 | // _Nullable type to a _Nonnull one, complain. | |||
4595 | if (!isCast(CCK)) | |||
4596 | diagnoseNullableToNonnullConversion(ToType, InitialFromType, | |||
4597 | From->getBeginLoc()); | |||
4598 | ||||
4599 | return From; | |||
4600 | } | |||
4601 | ||||
4602 | /// Check the completeness of a type in a unary type trait. | |||
4603 | /// | |||
4604 | /// If the particular type trait requires a complete type, tries to complete | |||
4605 | /// it. If completing the type fails, a diagnostic is emitted and false | |||
4606 | /// returned. If completing the type succeeds or no completion was required, | |||
4607 | /// returns true. | |||
4608 | static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT, | |||
4609 | SourceLocation Loc, | |||
4610 | QualType ArgTy) { | |||
4611 | // C++0x [meta.unary.prop]p3: | |||
4612 | // For all of the class templates X declared in this Clause, instantiating | |||
4613 | // that template with a template argument that is a class template | |||
4614 | // specialization may result in the implicit instantiation of the template | |||
4615 | // argument if and only if the semantics of X require that the argument | |||
4616 | // must be a complete type. | |||
4617 | // We apply this rule to all the type trait expressions used to implement | |||
4618 | // these class templates. We also try to follow any GCC documented behavior | |||
4619 | // in these expressions to ensure portability of standard libraries. | |||
4620 | switch (UTT) { | |||
4621 | default: llvm_unreachable("not a UTT")::llvm::llvm_unreachable_internal("not a UTT", "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 4621); | |||
4622 | // is_complete_type somewhat obviously cannot require a complete type. | |||
4623 | case UTT_IsCompleteType: | |||
4624 | // Fall-through | |||
4625 | ||||
4626 | // These traits are modeled on the type predicates in C++0x | |||
4627 | // [meta.unary.cat] and [meta.unary.comp]. They are not specified as | |||
4628 | // requiring a complete type, as whether or not they return true cannot be | |||
4629 | // impacted by the completeness of the type. | |||
4630 | case UTT_IsVoid: | |||
4631 | case UTT_IsIntegral: | |||
4632 | case UTT_IsFloatingPoint: | |||
4633 | case UTT_IsArray: | |||
4634 | case UTT_IsPointer: | |||
4635 | case UTT_IsLvalueReference: | |||
4636 | case UTT_IsRvalueReference: | |||
4637 | case UTT_IsMemberFunctionPointer: | |||
4638 | case UTT_IsMemberObjectPointer: | |||
4639 | case UTT_IsEnum: | |||
4640 | case UTT_IsUnion: | |||
4641 | case UTT_IsClass: | |||
4642 | case UTT_IsFunction: | |||
4643 | case UTT_IsReference: | |||
4644 | case UTT_IsArithmetic: | |||
4645 | case UTT_IsFundamental: | |||
4646 | case UTT_IsObject: | |||
4647 | case UTT_IsScalar: | |||
4648 | case UTT_IsCompound: | |||
4649 | case UTT_IsMemberPointer: | |||
4650 | // Fall-through | |||
4651 | ||||
4652 | // These traits are modeled on type predicates in C++0x [meta.unary.prop] | |||
4653 | // which requires some of its traits to have the complete type. However, | |||
4654 | // the completeness of the type cannot impact these traits' semantics, and | |||
4655 | // so they don't require it. This matches the comments on these traits in | |||
4656 | // Table 49. | |||
4657 | case UTT_IsConst: | |||
4658 | case UTT_IsVolatile: | |||
4659 | case UTT_IsSigned: | |||
4660 | case UTT_IsUnsigned: | |||
4661 | ||||
4662 | // This type trait always returns false, checking the type is moot. | |||
4663 | case UTT_IsInterfaceClass: | |||
4664 | return true; | |||
4665 | ||||
4666 | // C++14 [meta.unary.prop]: | |||
4667 | // If T is a non-union class type, T shall be a complete type. | |||
4668 | case UTT_IsEmpty: | |||
4669 | case UTT_IsPolymorphic: | |||
4670 | case UTT_IsAbstract: | |||
4671 | if (const auto *RD = ArgTy->getAsCXXRecordDecl()) | |||
4672 | if (!RD->isUnion()) | |||
4673 | return !S.RequireCompleteType( | |||
4674 | Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); | |||
4675 | return true; | |||
4676 | ||||
4677 | // C++14 [meta.unary.prop]: | |||
4678 | // If T is a class type, T shall be a complete type. | |||
4679 | case UTT_IsFinal: | |||
4680 | case UTT_IsSealed: | |||
4681 | if (ArgTy->getAsCXXRecordDecl()) | |||
4682 | return !S.RequireCompleteType( | |||
4683 | Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); | |||
4684 | return true; | |||
4685 | ||||
4686 | // C++1z [meta.unary.prop]: | |||
4687 | // remove_all_extents_t<T> shall be a complete type or cv void. | |||
4688 | case UTT_IsAggregate: | |||
4689 | case UTT_IsTrivial: | |||
4690 | case UTT_IsTriviallyCopyable: | |||
4691 | case UTT_IsStandardLayout: | |||
4692 | case UTT_IsPOD: | |||
4693 | case UTT_IsLiteral: | |||
4694 | // Per the GCC type traits documentation, T shall be a complete type, cv void, | |||
4695 | // or an array of unknown bound. But GCC actually imposes the same constraints | |||
4696 | // as above. | |||
4697 | case UTT_HasNothrowAssign: | |||
4698 | case UTT_HasNothrowMoveAssign: | |||
4699 | case UTT_HasNothrowConstructor: | |||
4700 | case UTT_HasNothrowCopy: | |||
4701 | case UTT_HasTrivialAssign: | |||
4702 | case UTT_HasTrivialMoveAssign: | |||
4703 | case UTT_HasTrivialDefaultConstructor: | |||
4704 | case UTT_HasTrivialMoveConstructor: | |||
4705 | case UTT_HasTrivialCopy: | |||
4706 | case UTT_HasTrivialDestructor: | |||
4707 | case UTT_HasVirtualDestructor: | |||
4708 | ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0); | |||
4709 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
4710 | ||||
4711 | // C++1z [meta.unary.prop]: | |||
4712 | // T shall be a complete type, cv void, or an array of unknown bound. | |||
4713 | case UTT_IsDestructible: | |||
4714 | case UTT_IsNothrowDestructible: | |||
4715 | case UTT_IsTriviallyDestructible: | |||
4716 | case UTT_HasUniqueObjectRepresentations: | |||
4717 | if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType()) | |||
4718 | return true; | |||
4719 | ||||
4720 | return !S.RequireCompleteType( | |||
4721 | Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); | |||
4722 | } | |||
4723 | } | |||
4724 | ||||
4725 | static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op, | |||
4726 | Sema &Self, SourceLocation KeyLoc, ASTContext &C, | |||
4727 | bool (CXXRecordDecl::*HasTrivial)() const, | |||
4728 | bool (CXXRecordDecl::*HasNonTrivial)() const, | |||
4729 | bool (CXXMethodDecl::*IsDesiredOp)() const) | |||
4730 | { | |||
4731 | CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); | |||
4732 | if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)()) | |||
4733 | return true; | |||
4734 | ||||
4735 | DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op); | |||
4736 | DeclarationNameInfo NameInfo(Name, KeyLoc); | |||
4737 | LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName); | |||
4738 | if (Self.LookupQualifiedName(Res, RD)) { | |||
4739 | bool FoundOperator = false; | |||
4740 | Res.suppressDiagnostics(); | |||
4741 | for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end(); | |||
4742 | Op != OpEnd; ++Op) { | |||
4743 | if (isa<FunctionTemplateDecl>(*Op)) | |||
4744 | continue; | |||
4745 | ||||
4746 | CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op); | |||
4747 | if((Operator->*IsDesiredOp)()) { | |||
4748 | FoundOperator = true; | |||
4749 | auto *CPT = Operator->getType()->castAs<FunctionProtoType>(); | |||
4750 | CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); | |||
4751 | if (!CPT || !CPT->isNothrow()) | |||
4752 | return false; | |||
4753 | } | |||
4754 | } | |||
4755 | return FoundOperator; | |||
4756 | } | |||
4757 | return false; | |||
4758 | } | |||
4759 | ||||
4760 | static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT, | |||
4761 | SourceLocation KeyLoc, QualType T) { | |||
4762 | assert(!T->isDependentType() && "Cannot evaluate traits of dependent type")(static_cast <bool> (!T->isDependentType() && "Cannot evaluate traits of dependent type") ? void (0) : __assert_fail ("!T->isDependentType() && \"Cannot evaluate traits of dependent type\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 4762, __extension__ __PRETTY_FUNCTION__)); | |||
4763 | ||||
4764 | ASTContext &C = Self.Context; | |||
4765 | switch(UTT) { | |||
4766 | default: llvm_unreachable("not a UTT")::llvm::llvm_unreachable_internal("not a UTT", "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 4766); | |||
4767 | // Type trait expressions corresponding to the primary type category | |||
4768 | // predicates in C++0x [meta.unary.cat]. | |||
4769 | case UTT_IsVoid: | |||
4770 | return T->isVoidType(); | |||
4771 | case UTT_IsIntegral: | |||
4772 | return T->isIntegralType(C); | |||
4773 | case UTT_IsFloatingPoint: | |||
4774 | return T->isFloatingType(); | |||
4775 | case UTT_IsArray: | |||
4776 | return T->isArrayType(); | |||
4777 | case UTT_IsPointer: | |||
4778 | return T->isAnyPointerType(); | |||
4779 | case UTT_IsLvalueReference: | |||
4780 | return T->isLValueReferenceType(); | |||
4781 | case UTT_IsRvalueReference: | |||
4782 | return T->isRValueReferenceType(); | |||
4783 | case UTT_IsMemberFunctionPointer: | |||
4784 | return T->isMemberFunctionPointerType(); | |||
4785 | case UTT_IsMemberObjectPointer: | |||
4786 | return T->isMemberDataPointerType(); | |||
4787 | case UTT_IsEnum: | |||
4788 | return T->isEnumeralType(); | |||
4789 | case UTT_IsUnion: | |||
4790 | return T->isUnionType(); | |||
4791 | case UTT_IsClass: | |||
4792 | return T->isClassType() || T->isStructureType() || T->isInterfaceType(); | |||
4793 | case UTT_IsFunction: | |||
4794 | return T->isFunctionType(); | |||
4795 | ||||
4796 | // Type trait expressions which correspond to the convenient composition | |||
4797 | // predicates in C++0x [meta.unary.comp]. | |||
4798 | case UTT_IsReference: | |||
4799 | return T->isReferenceType(); | |||
4800 | case UTT_IsArithmetic: | |||
4801 | return T->isArithmeticType() && !T->isEnumeralType(); | |||
4802 | case UTT_IsFundamental: | |||
4803 | return T->isFundamentalType(); | |||
4804 | case UTT_IsObject: | |||
4805 | return T->isObjectType(); | |||
4806 | case UTT_IsScalar: | |||
4807 | // Note: semantic analysis depends on Objective-C lifetime types to be | |||
4808 | // considered scalar types. However, such types do not actually behave | |||
4809 | // like scalar types at run time (since they may require retain/release | |||
4810 | // operations), so we report them as non-scalar. | |||
4811 | if (T->isObjCLifetimeType()) { | |||
4812 | switch (T.getObjCLifetime()) { | |||
4813 | case Qualifiers::OCL_None: | |||
4814 | case Qualifiers::OCL_ExplicitNone: | |||
4815 | return true; | |||
4816 | ||||
4817 | case Qualifiers::OCL_Strong: | |||
4818 | case Qualifiers::OCL_Weak: | |||
4819 | case Qualifiers::OCL_Autoreleasing: | |||
4820 | return false; | |||
4821 | } | |||
4822 | } | |||
4823 | ||||
4824 | return T->isScalarType(); | |||
4825 | case UTT_IsCompound: | |||
4826 | return T->isCompoundType(); | |||
4827 | case UTT_IsMemberPointer: | |||
4828 | return T->isMemberPointerType(); | |||
4829 | ||||
4830 | // Type trait expressions which correspond to the type property predicates | |||
4831 | // in C++0x [meta.unary.prop]. | |||
4832 | case UTT_IsConst: | |||
4833 | return T.isConstQualified(); | |||
4834 | case UTT_IsVolatile: | |||
4835 | return T.isVolatileQualified(); | |||
4836 | case UTT_IsTrivial: | |||
4837 | return T.isTrivialType(C); | |||
4838 | case UTT_IsTriviallyCopyable: | |||
4839 | return T.isTriviallyCopyableType(C); | |||
4840 | case UTT_IsStandardLayout: | |||
4841 | return T->isStandardLayoutType(); | |||
4842 | case UTT_IsPOD: | |||
4843 | return T.isPODType(C); | |||
4844 | case UTT_IsLiteral: | |||
4845 | return T->isLiteralType(C); | |||
4846 | case UTT_IsEmpty: | |||
4847 | if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) | |||
4848 | return !RD->isUnion() && RD->isEmpty(); | |||
4849 | return false; | |||
4850 | case UTT_IsPolymorphic: | |||
4851 | if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) | |||
4852 | return !RD->isUnion() && RD->isPolymorphic(); | |||
4853 | return false; | |||
4854 | case UTT_IsAbstract: | |||
4855 | if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) | |||
4856 | return !RD->isUnion() && RD->isAbstract(); | |||
4857 | return false; | |||
4858 | case UTT_IsAggregate: | |||
4859 | // Report vector extensions and complex types as aggregates because they | |||
4860 | // support aggregate initialization. GCC mirrors this behavior for vectors | |||
4861 | // but not _Complex. | |||
4862 | return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() || | |||
4863 | T->isAnyComplexType(); | |||
4864 | // __is_interface_class only returns true when CL is invoked in /CLR mode and | |||
4865 | // even then only when it is used with the 'interface struct ...' syntax | |||
4866 | // Clang doesn't support /CLR which makes this type trait moot. | |||
4867 | case UTT_IsInterfaceClass: | |||
4868 | return false; | |||
4869 | case UTT_IsFinal: | |||
4870 | case UTT_IsSealed: | |||
4871 | if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) | |||
4872 | return RD->hasAttr<FinalAttr>(); | |||
4873 | return false; | |||
4874 | case UTT_IsSigned: | |||
4875 | // Enum types should always return false. | |||
4876 | // Floating points should always return true. | |||
4877 | return T->isFloatingType() || | |||
4878 | (T->isSignedIntegerType() && !T->isEnumeralType()); | |||
4879 | case UTT_IsUnsigned: | |||
4880 | // Enum types should always return false. | |||
4881 | return T->isUnsignedIntegerType() && !T->isEnumeralType(); | |||
4882 | ||||
4883 | // Type trait expressions which query classes regarding their construction, | |||
4884 | // destruction, and copying. Rather than being based directly on the | |||
4885 | // related type predicates in the standard, they are specified by both | |||
4886 | // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those | |||
4887 | // specifications. | |||
4888 | // | |||
4889 | // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html | |||
4890 | // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index | |||
4891 | // | |||
4892 | // Note that these builtins do not behave as documented in g++: if a class | |||
4893 | // has both a trivial and a non-trivial special member of a particular kind, | |||
4894 | // they return false! For now, we emulate this behavior. | |||
4895 | // FIXME: This appears to be a g++ bug: more complex cases reveal that it | |||
4896 | // does not correctly compute triviality in the presence of multiple special | |||
4897 | // members of the same kind. Revisit this once the g++ bug is fixed. | |||
4898 | case UTT_HasTrivialDefaultConstructor: | |||
4899 | // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: | |||
4900 | // If __is_pod (type) is true then the trait is true, else if type is | |||
4901 | // a cv class or union type (or array thereof) with a trivial default | |||
4902 | // constructor ([class.ctor]) then the trait is true, else it is false. | |||
4903 | if (T.isPODType(C)) | |||
4904 | return true; | |||
4905 | if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) | |||
4906 | return RD->hasTrivialDefaultConstructor() && | |||
4907 | !RD->hasNonTrivialDefaultConstructor(); | |||
4908 | return false; | |||
4909 | case UTT_HasTrivialMoveConstructor: | |||
4910 | // This trait is implemented by MSVC 2012 and needed to parse the | |||
4911 | // standard library headers. Specifically this is used as the logic | |||
4912 | // behind std::is_trivially_move_constructible (20.9.4.3). | |||
4913 | if (T.isPODType(C)) | |||
4914 | return true; | |||
4915 | if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) | |||
4916 | return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor(); | |||
4917 | return false; | |||
4918 | case UTT_HasTrivialCopy: | |||
4919 | // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: | |||
4920 | // If __is_pod (type) is true or type is a reference type then | |||
4921 | // the trait is true, else if type is a cv class or union type | |||
4922 | // with a trivial copy constructor ([class.copy]) then the trait | |||
4923 | // is true, else it is false. | |||
4924 | if (T.isPODType(C) || T->isReferenceType()) | |||
4925 | return true; | |||
4926 | if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) | |||
4927 | return RD->hasTrivialCopyConstructor() && | |||
4928 | !RD->hasNonTrivialCopyConstructor(); | |||
4929 | return false; | |||
4930 | case UTT_HasTrivialMoveAssign: | |||
4931 | // This trait is implemented by MSVC 2012 and needed to parse the | |||
4932 | // standard library headers. Specifically it is used as the logic | |||
4933 | // behind std::is_trivially_move_assignable (20.9.4.3) | |||
4934 | if (T.isPODType(C)) | |||
4935 | return true; | |||
4936 | if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) | |||
4937 | return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment(); | |||
4938 | return false; | |||
4939 | case UTT_HasTrivialAssign: | |||
4940 | // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: | |||
4941 | // If type is const qualified or is a reference type then the | |||
4942 | // trait is false. Otherwise if __is_pod (type) is true then the | |||
4943 | // trait is true, else if type is a cv class or union type with | |||
4944 | // a trivial copy assignment ([class.copy]) then the trait is | |||
4945 | // true, else it is false. | |||
4946 | // Note: the const and reference restrictions are interesting, | |||
4947 | // given that const and reference members don't prevent a class | |||
4948 | // from having a trivial copy assignment operator (but do cause | |||
4949 | // errors if the copy assignment operator is actually used, q.v. | |||
4950 | // [class.copy]p12). | |||
4951 | ||||
4952 | if (T.isConstQualified()) | |||
4953 | return false; | |||
4954 | if (T.isPODType(C)) | |||
4955 | return true; | |||
4956 | if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) | |||
4957 | return RD->hasTrivialCopyAssignment() && | |||
4958 | !RD->hasNonTrivialCopyAssignment(); | |||
4959 | return false; | |||
4960 | case UTT_IsDestructible: | |||
4961 | case UTT_IsTriviallyDestructible: | |||
4962 | case UTT_IsNothrowDestructible: | |||
4963 | // C++14 [meta.unary.prop]: | |||
4964 | // For reference types, is_destructible<T>::value is true. | |||
4965 | if (T->isReferenceType()) | |||
4966 | return true; | |||
4967 | ||||
4968 | // Objective-C++ ARC: autorelease types don't require destruction. | |||
4969 | if (T->isObjCLifetimeType() && | |||
4970 | T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) | |||
4971 | return true; | |||
4972 | ||||
4973 | // C++14 [meta.unary.prop]: | |||
4974 | // For incomplete types and function types, is_destructible<T>::value is | |||
4975 | // false. | |||
4976 | if (T->isIncompleteType() || T->isFunctionType()) | |||
4977 | return false; | |||
4978 | ||||
4979 | // A type that requires destruction (via a non-trivial destructor or ARC | |||
4980 | // lifetime semantics) is not trivially-destructible. | |||
4981 | if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType()) | |||
4982 | return false; | |||
4983 | ||||
4984 | // C++14 [meta.unary.prop]: | |||
4985 | // For object types and given U equal to remove_all_extents_t<T>, if the | |||
4986 | // expression std::declval<U&>().~U() is well-formed when treated as an | |||
4987 | // unevaluated operand (Clause 5), then is_destructible<T>::value is true | |||
4988 | if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) { | |||
4989 | CXXDestructorDecl *Destructor = Self.LookupDestructor(RD); | |||
4990 | if (!Destructor) | |||
4991 | return false; | |||
4992 | // C++14 [dcl.fct.def.delete]p2: | |||
4993 | // A program that refers to a deleted function implicitly or | |||
4994 | // explicitly, other than to declare it, is ill-formed. | |||
4995 | if (Destructor->isDeleted()) | |||
4996 | return false; | |||
4997 | if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public) | |||
4998 | return false; | |||
4999 | if (UTT == UTT_IsNothrowDestructible) { | |||
5000 | auto *CPT = Destructor->getType()->castAs<FunctionProtoType>(); | |||
5001 | CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); | |||
5002 | if (!CPT || !CPT->isNothrow()) | |||
5003 | return false; | |||
5004 | } | |||
5005 | } | |||
5006 | return true; | |||
5007 | ||||
5008 | case UTT_HasTrivialDestructor: | |||
5009 | // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html | |||
5010 | // If __is_pod (type) is true or type is a reference type | |||
5011 | // then the trait is true, else if type is a cv class or union | |||
5012 | // type (or array thereof) with a trivial destructor | |||
5013 | // ([class.dtor]) then the trait is true, else it is | |||
5014 | // false. | |||
5015 | if (T.isPODType(C) || T->isReferenceType()) | |||
5016 | return true; | |||
5017 | ||||
5018 | // Objective-C++ ARC: autorelease types don't require destruction. | |||
5019 | if (T->isObjCLifetimeType() && | |||
5020 | T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) | |||
5021 | return true; | |||
5022 | ||||
5023 | if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) | |||
5024 | return RD->hasTrivialDestructor(); | |||
5025 | return false; | |||
5026 | // TODO: Propagate nothrowness for implicitly declared special members. | |||
5027 | case UTT_HasNothrowAssign: | |||
5028 | // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: | |||
5029 | // If type is const qualified or is a reference type then the | |||
5030 | // trait is false. Otherwise if __has_trivial_assign (type) | |||
5031 | // is true then the trait is true, else if type is a cv class | |||
5032 | // or union type with copy assignment operators that are known | |||
5033 | // not to throw an exception then the trait is true, else it is | |||
5034 | // false. | |||
5035 | if (C.getBaseElementType(T).isConstQualified()) | |||
5036 | return false; | |||
5037 | if (T->isReferenceType()) | |||
5038 | return false; | |||
5039 | if (T.isPODType(C) || T->isObjCLifetimeType()) | |||
5040 | return true; | |||
5041 | ||||
5042 | if (const RecordType *RT = T->getAs<RecordType>()) | |||
5043 | return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C, | |||
5044 | &CXXRecordDecl::hasTrivialCopyAssignment, | |||
5045 | &CXXRecordDecl::hasNonTrivialCopyAssignment, | |||
5046 | &CXXMethodDecl::isCopyAssignmentOperator); | |||
5047 | return false; | |||
5048 | case UTT_HasNothrowMoveAssign: | |||
5049 | // This trait is implemented by MSVC 2012 and needed to parse the | |||
5050 | // standard library headers. Specifically this is used as the logic | |||
5051 | // behind std::is_nothrow_move_assignable (20.9.4.3). | |||
5052 | if (T.isPODType(C)) | |||
5053 | return true; | |||
5054 | ||||
5055 | if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) | |||
5056 | return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C, | |||
5057 | &CXXRecordDecl::hasTrivialMoveAssignment, | |||
5058 | &CXXRecordDecl::hasNonTrivialMoveAssignment, | |||
5059 | &CXXMethodDecl::isMoveAssignmentOperator); | |||
5060 | return false; | |||
5061 | case UTT_HasNothrowCopy: | |||
5062 | // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: | |||
5063 | // If __has_trivial_copy (type) is true then the trait is true, else | |||
5064 | // if type is a cv class or union type with copy constructors that are | |||
5065 | // known not to throw an exception then the trait is true, else it is | |||
5066 | // false. | |||
5067 | if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType()) | |||
5068 | return true; | |||
5069 | if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { | |||
5070 | if (RD->hasTrivialCopyConstructor() && | |||
5071 | !RD->hasNonTrivialCopyConstructor()) | |||
5072 | return true; | |||
5073 | ||||
5074 | bool FoundConstructor = false; | |||
5075 | unsigned FoundTQs; | |||
5076 | for (const auto *ND : Self.LookupConstructors(RD)) { | |||
5077 | // A template constructor is never a copy constructor. | |||
5078 | // FIXME: However, it may actually be selected at the actual overload | |||
5079 | // resolution point. | |||
5080 | if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl())) | |||
5081 | continue; | |||
5082 | // UsingDecl itself is not a constructor | |||
5083 | if (isa<UsingDecl>(ND)) | |||
5084 | continue; | |||
5085 | auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl()); | |||
5086 | if (Constructor->isCopyConstructor(FoundTQs)) { | |||
5087 | FoundConstructor = true; | |||
5088 | auto *CPT = Constructor->getType()->castAs<FunctionProtoType>(); | |||
5089 | CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); | |||
5090 | if (!CPT) | |||
5091 | return false; | |||
5092 | // TODO: check whether evaluating default arguments can throw. | |||
5093 | // For now, we'll be conservative and assume that they can throw. | |||
5094 | if (!CPT->isNothrow() || CPT->getNumParams() > 1) | |||
5095 | return false; | |||
5096 | } | |||
5097 | } | |||
5098 | ||||
5099 | return FoundConstructor; | |||
5100 | } | |||
5101 | return false; | |||
5102 | case UTT_HasNothrowConstructor: | |||
5103 | // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html | |||
5104 | // If __has_trivial_constructor (type) is true then the trait is | |||
5105 | // true, else if type is a cv class or union type (or array | |||
5106 | // thereof) with a default constructor that is known not to | |||
5107 | // throw an exception then the trait is true, else it is false. | |||
5108 | if (T.isPODType(C) || T->isObjCLifetimeType()) | |||
5109 | return true; | |||
5110 | if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) { | |||
5111 | if (RD->hasTrivialDefaultConstructor() && | |||
5112 | !RD->hasNonTrivialDefaultConstructor()) | |||
5113 | return true; | |||
5114 | ||||
5115 | bool FoundConstructor = false; | |||
5116 | for (const auto *ND : Self.LookupConstructors(RD)) { | |||
5117 | // FIXME: In C++0x, a constructor template can be a default constructor. | |||
5118 | if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl())) | |||
5119 | continue; | |||
5120 | // UsingDecl itself is not a constructor | |||
5121 | if (isa<UsingDecl>(ND)) | |||
5122 | continue; | |||
5123 | auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl()); | |||
5124 | if (Constructor->isDefaultConstructor()) { | |||
5125 | FoundConstructor = true; | |||
5126 | auto *CPT = Constructor->getType()->castAs<FunctionProtoType>(); | |||
5127 | CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); | |||
5128 | if (!CPT) | |||
5129 | return false; | |||
5130 | // FIXME: check whether evaluating default arguments can throw. | |||
5131 | // For now, we'll be conservative and assume that they can throw. | |||
5132 | if (!CPT->isNothrow() || CPT->getNumParams() > 0) | |||
5133 | return false; | |||
5134 | } | |||
5135 | } | |||
5136 | return FoundConstructor; | |||
5137 | } | |||
5138 | return false; | |||
5139 | case UTT_HasVirtualDestructor: | |||
5140 | // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: | |||
5141 | // If type is a class type with a virtual destructor ([class.dtor]) | |||
5142 | // then the trait is true, else it is false. | |||
5143 | if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) | |||
5144 | if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD)) | |||
5145 | return Destructor->isVirtual(); | |||
5146 | return false; | |||
5147 | ||||
5148 | // These type trait expressions are modeled on the specifications for the | |||
5149 | // Embarcadero C++0x type trait functions: | |||
5150 | // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index | |||
5151 | case UTT_IsCompleteType: | |||
5152 | // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_): | |||
5153 | // Returns True if and only if T is a complete type at the point of the | |||
5154 | // function call. | |||
5155 | return !T->isIncompleteType(); | |||
5156 | case UTT_HasUniqueObjectRepresentations: | |||
5157 | return C.hasUniqueObjectRepresentations(T); | |||
5158 | } | |||
5159 | } | |||
5160 | ||||
5161 | static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT, | |||
5162 | QualType RhsT, SourceLocation KeyLoc); | |||
5163 | ||||
5164 | static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc, | |||
5165 | ArrayRef<TypeSourceInfo *> Args, | |||
5166 | SourceLocation RParenLoc) { | |||
5167 | if (Kind <= UTT_Last) | |||
5168 | return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType()); | |||
5169 | ||||
5170 | // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible | |||
5171 | // traits to avoid duplication. | |||
5172 | if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary) | |||
5173 | return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(), | |||
5174 | Args[1]->getType(), RParenLoc); | |||
5175 | ||||
5176 | switch (Kind) { | |||
5177 | case clang::BTT_ReferenceBindsToTemporary: | |||
5178 | case clang::TT_IsConstructible: | |||
5179 | case clang::TT_IsNothrowConstructible: | |||
5180 | case clang::TT_IsTriviallyConstructible: { | |||
5181 | // C++11 [meta.unary.prop]: | |||
5182 | // is_trivially_constructible is defined as: | |||
5183 | // | |||
5184 | // is_constructible<T, Args...>::value is true and the variable | |||
5185 | // definition for is_constructible, as defined below, is known to call | |||
5186 | // no operation that is not trivial. | |||
5187 | // | |||
5188 | // The predicate condition for a template specialization | |||
5189 | // is_constructible<T, Args...> shall be satisfied if and only if the | |||
5190 | // following variable definition would be well-formed for some invented | |||
5191 | // variable t: | |||
5192 | // | |||
5193 | // T t(create<Args>()...); | |||
5194 | assert(!Args.empty())(static_cast <bool> (!Args.empty()) ? void (0) : __assert_fail ("!Args.empty()", "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 5194, __extension__ __PRETTY_FUNCTION__)); | |||
5195 | ||||
5196 | // Precondition: T and all types in the parameter pack Args shall be | |||
5197 | // complete types, (possibly cv-qualified) void, or arrays of | |||
5198 | // unknown bound. | |||
5199 | for (const auto *TSI : Args) { | |||
5200 | QualType ArgTy = TSI->getType(); | |||
5201 | if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType()) | |||
5202 | continue; | |||
5203 | ||||
5204 | if (S.RequireCompleteType(KWLoc, ArgTy, | |||
5205 | diag::err_incomplete_type_used_in_type_trait_expr)) | |||
5206 | return false; | |||
5207 | } | |||
5208 | ||||
5209 | // Make sure the first argument is not incomplete nor a function type. | |||
5210 | QualType T = Args[0]->getType(); | |||
5211 | if (T->isIncompleteType() || T->isFunctionType()) | |||
5212 | return false; | |||
5213 | ||||
5214 | // Make sure the first argument is not an abstract type. | |||
5215 | CXXRecordDecl *RD = T->getAsCXXRecordDecl(); | |||
5216 | if (RD && RD->isAbstract()) | |||
5217 | return false; | |||
5218 | ||||
5219 | llvm::BumpPtrAllocator OpaqueExprAllocator; | |||
5220 | SmallVector<Expr *, 2> ArgExprs; | |||
5221 | ArgExprs.reserve(Args.size() - 1); | |||
5222 | for (unsigned I = 1, N = Args.size(); I != N; ++I) { | |||
5223 | QualType ArgTy = Args[I]->getType(); | |||
5224 | if (ArgTy->isObjectType() || ArgTy->isFunctionType()) | |||
5225 | ArgTy = S.Context.getRValueReferenceType(ArgTy); | |||
5226 | ArgExprs.push_back( | |||
5227 | new (OpaqueExprAllocator.Allocate<OpaqueValueExpr>()) | |||
5228 | OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(), | |||
5229 | ArgTy.getNonLValueExprType(S.Context), | |||
5230 | Expr::getValueKindForType(ArgTy))); | |||
5231 | } | |||
5232 | ||||
5233 | // Perform the initialization in an unevaluated context within a SFINAE | |||
5234 | // trap at translation unit scope. | |||
5235 | EnterExpressionEvaluationContext Unevaluated( | |||
5236 | S, Sema::ExpressionEvaluationContext::Unevaluated); | |||
5237 | Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true); | |||
5238 | Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl()); | |||
5239 | InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0])); | |||
5240 | InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc, | |||
5241 | RParenLoc)); | |||
5242 | InitializationSequence Init(S, To, InitKind, ArgExprs); | |||
5243 | if (Init.Failed()) | |||
5244 | return false; | |||
5245 | ||||
5246 | ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs); | |||
5247 | if (Result.isInvalid() || SFINAE.hasErrorOccurred()) | |||
5248 | return false; | |||
5249 | ||||
5250 | if (Kind == clang::TT_IsConstructible) | |||
5251 | return true; | |||
5252 | ||||
5253 | if (Kind == clang::BTT_ReferenceBindsToTemporary) { | |||
5254 | if (!T->isReferenceType()) | |||
5255 | return false; | |||
5256 | ||||
5257 | return !Init.isDirectReferenceBinding(); | |||
5258 | } | |||
5259 | ||||
5260 | if (Kind == clang::TT_IsNothrowConstructible) | |||
5261 | return S.canThrow(Result.get()) == CT_Cannot; | |||
5262 | ||||
5263 | if (Kind == clang::TT_IsTriviallyConstructible) { | |||
5264 | // Under Objective-C ARC and Weak, if the destination has non-trivial | |||
5265 | // Objective-C lifetime, this is a non-trivial construction. | |||
5266 | if (T.getNonReferenceType().hasNonTrivialObjCLifetime()) | |||
5267 | return false; | |||
5268 | ||||
5269 | // The initialization succeeded; now make sure there are no non-trivial | |||
5270 | // calls. | |||
5271 | return !Result.get()->hasNonTrivialCall(S.Context); | |||
5272 | } | |||
5273 | ||||
5274 | llvm_unreachable("unhandled type trait")::llvm::llvm_unreachable_internal("unhandled type trait", "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 5274); | |||
5275 | return false; | |||
5276 | } | |||
5277 | default: llvm_unreachable("not a TT")::llvm::llvm_unreachable_internal("not a TT", "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 5277); | |||
5278 | } | |||
5279 | ||||
5280 | return false; | |||
5281 | } | |||
5282 | ||||
5283 | ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, | |||
5284 | ArrayRef<TypeSourceInfo *> Args, | |||
5285 | SourceLocation RParenLoc) { | |||
5286 | QualType ResultType = Context.getLogicalOperationType(); | |||
5287 | ||||
5288 | if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness( | |||
5289 | *this, Kind, KWLoc, Args[0]->getType())) | |||
5290 | return ExprError(); | |||
5291 | ||||
5292 | bool Dependent = false; | |||
5293 | for (unsigned I = 0, N = Args.size(); I != N; ++I) { | |||
5294 | if (Args[I]->getType()->isDependentType()) { | |||
5295 | Dependent = true; | |||
5296 | break; | |||
5297 | } | |||
5298 | } | |||
5299 | ||||
5300 | bool Result = false; | |||
5301 | if (!Dependent) | |||
5302 | Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc); | |||
5303 | ||||
5304 | return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args, | |||
5305 | RParenLoc, Result); | |||
5306 | } | |||
5307 | ||||
5308 | ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, | |||
5309 | ArrayRef<ParsedType> Args, | |||
5310 | SourceLocation RParenLoc) { | |||
5311 | SmallVector<TypeSourceInfo *, 4> ConvertedArgs; | |||
5312 | ConvertedArgs.reserve(Args.size()); | |||
5313 | ||||
5314 | for (unsigned I = 0, N = Args.size(); I != N; ++I) { | |||
5315 | TypeSourceInfo *TInfo; | |||
5316 | QualType T = GetTypeFromParser(Args[I], &TInfo); | |||
5317 | if (!TInfo) | |||
5318 | TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc); | |||
5319 | ||||
5320 | ConvertedArgs.push_back(TInfo); | |||
5321 | } | |||
5322 | ||||
5323 | return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc); | |||
5324 | } | |||
5325 | ||||
5326 | static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT, | |||
5327 | QualType RhsT, SourceLocation KeyLoc) { | |||
5328 | assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&(static_cast <bool> (!LhsT->isDependentType() && !RhsT->isDependentType() && "Cannot evaluate traits of dependent types" ) ? void (0) : __assert_fail ("!LhsT->isDependentType() && !RhsT->isDependentType() && \"Cannot evaluate traits of dependent types\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 5329, __extension__ __PRETTY_FUNCTION__)) | |||
5329 | "Cannot evaluate traits of dependent types")(static_cast <bool> (!LhsT->isDependentType() && !RhsT->isDependentType() && "Cannot evaluate traits of dependent types" ) ? void (0) : __assert_fail ("!LhsT->isDependentType() && !RhsT->isDependentType() && \"Cannot evaluate traits of dependent types\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 5329, __extension__ __PRETTY_FUNCTION__)); | |||
5330 | ||||
5331 | switch(BTT) { | |||
5332 | case BTT_IsBaseOf: { | |||
5333 | // C++0x [meta.rel]p2 | |||
5334 | // Base is a base class of Derived without regard to cv-qualifiers or | |||
5335 | // Base and Derived are not unions and name the same class type without | |||
5336 | // regard to cv-qualifiers. | |||
5337 | ||||
5338 | const RecordType *lhsRecord = LhsT->getAs<RecordType>(); | |||
5339 | const RecordType *rhsRecord = RhsT->getAs<RecordType>(); | |||
5340 | if (!rhsRecord || !lhsRecord) { | |||
5341 | const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>(); | |||
5342 | const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>(); | |||
5343 | if (!LHSObjTy || !RHSObjTy) | |||
5344 | return false; | |||
5345 | ||||
5346 | ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface(); | |||
5347 | ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface(); | |||
5348 | if (!BaseInterface || !DerivedInterface) | |||
5349 | return false; | |||
5350 | ||||
5351 | if (Self.RequireCompleteType( | |||
5352 | KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr)) | |||
5353 | return false; | |||
5354 | ||||
5355 | return BaseInterface->isSuperClassOf(DerivedInterface); | |||
5356 | } | |||
5357 | ||||
5358 | assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)(static_cast <bool> (Self.Context.hasSameUnqualifiedType (LhsT, RhsT) == (lhsRecord == rhsRecord)) ? void (0) : __assert_fail ("Self.Context.hasSameUnqualifiedType(LhsT, RhsT) == (lhsRecord == rhsRecord)" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 5359, __extension__ __PRETTY_FUNCTION__)) | |||
5359 | == (lhsRecord == rhsRecord))(static_cast <bool> (Self.Context.hasSameUnqualifiedType (LhsT, RhsT) == (lhsRecord == rhsRecord)) ? void (0) : __assert_fail ("Self.Context.hasSameUnqualifiedType(LhsT, RhsT) == (lhsRecord == rhsRecord)" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 5359, __extension__ __PRETTY_FUNCTION__)); | |||
5360 | ||||
5361 | // Unions are never base classes, and never have base classes. | |||
5362 | // It doesn't matter if they are complete or not. See PR#41843 | |||
5363 | if (lhsRecord && lhsRecord->getDecl()->isUnion()) | |||
5364 | return false; | |||
5365 | if (rhsRecord && rhsRecord->getDecl()->isUnion()) | |||
5366 | return false; | |||
5367 | ||||
5368 | if (lhsRecord == rhsRecord) | |||
5369 | return true; | |||
5370 | ||||
5371 | // C++0x [meta.rel]p2: | |||
5372 | // If Base and Derived are class types and are different types | |||
5373 | // (ignoring possible cv-qualifiers) then Derived shall be a | |||
5374 | // complete type. | |||
5375 | if (Self.RequireCompleteType(KeyLoc, RhsT, | |||
5376 | diag::err_incomplete_type_used_in_type_trait_expr)) | |||
5377 | return false; | |||
5378 | ||||
5379 | return cast<CXXRecordDecl>(rhsRecord->getDecl()) | |||
5380 | ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl())); | |||
5381 | } | |||
5382 | case BTT_IsSame: | |||
5383 | return Self.Context.hasSameType(LhsT, RhsT); | |||
5384 | case BTT_TypeCompatible: { | |||
5385 | // GCC ignores cv-qualifiers on arrays for this builtin. | |||
5386 | Qualifiers LhsQuals, RhsQuals; | |||
5387 | QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals); | |||
5388 | QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals); | |||
5389 | return Self.Context.typesAreCompatible(Lhs, Rhs); | |||
5390 | } | |||
5391 | case BTT_IsConvertible: | |||
5392 | case BTT_IsConvertibleTo: { | |||
5393 | // C++0x [meta.rel]p4: | |||
5394 | // Given the following function prototype: | |||
5395 | // | |||
5396 | // template <class T> | |||
5397 | // typename add_rvalue_reference<T>::type create(); | |||
5398 | // | |||
5399 | // the predicate condition for a template specialization | |||
5400 | // is_convertible<From, To> shall be satisfied if and only if | |||
5401 | // the return expression in the following code would be | |||
5402 | // well-formed, including any implicit conversions to the return | |||
5403 | // type of the function: | |||
5404 | // | |||
5405 | // To test() { | |||
5406 | // return create<From>(); | |||
5407 | // } | |||
5408 | // | |||
5409 | // Access checking is performed as if in a context unrelated to To and | |||
5410 | // From. Only the validity of the immediate context of the expression | |||
5411 | // of the return-statement (including conversions to the return type) | |||
5412 | // is considered. | |||
5413 | // | |||
5414 | // We model the initialization as a copy-initialization of a temporary | |||
5415 | // of the appropriate type, which for this expression is identical to the | |||
5416 | // return statement (since NRVO doesn't apply). | |||
5417 | ||||
5418 | // Functions aren't allowed to return function or array types. | |||
5419 | if (RhsT->isFunctionType() || RhsT->isArrayType()) | |||
5420 | return false; | |||
5421 | ||||
5422 | // A return statement in a void function must have void type. | |||
5423 | if (RhsT->isVoidType()) | |||
5424 | return LhsT->isVoidType(); | |||
5425 | ||||
5426 | // A function definition requires a complete, non-abstract return type. | |||
5427 | if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT)) | |||
5428 | return false; | |||
5429 | ||||
5430 | // Compute the result of add_rvalue_reference. | |||
5431 | if (LhsT->isObjectType() || LhsT->isFunctionType()) | |||
5432 | LhsT = Self.Context.getRValueReferenceType(LhsT); | |||
5433 | ||||
5434 | // Build a fake source and destination for initialization. | |||
5435 | InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT)); | |||
5436 | OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context), | |||
5437 | Expr::getValueKindForType(LhsT)); | |||
5438 | Expr *FromPtr = &From; | |||
5439 | InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc, | |||
5440 | SourceLocation())); | |||
5441 | ||||
5442 | // Perform the initialization in an unevaluated context within a SFINAE | |||
5443 | // trap at translation unit scope. | |||
5444 | EnterExpressionEvaluationContext Unevaluated( | |||
5445 | Self, Sema::ExpressionEvaluationContext::Unevaluated); | |||
5446 | Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true); | |||
5447 | Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl()); | |||
5448 | InitializationSequence Init(Self, To, Kind, FromPtr); | |||
5449 | if (Init.Failed()) | |||
5450 | return false; | |||
5451 | ||||
5452 | ExprResult Result = Init.Perform(Self, To, Kind, FromPtr); | |||
5453 | return !Result.isInvalid() && !SFINAE.hasErrorOccurred(); | |||
5454 | } | |||
5455 | ||||
5456 | case BTT_IsAssignable: | |||
5457 | case BTT_IsNothrowAssignable: | |||
5458 | case BTT_IsTriviallyAssignable: { | |||
5459 | // C++11 [meta.unary.prop]p3: | |||
5460 | // is_trivially_assignable is defined as: | |||
5461 | // is_assignable<T, U>::value is true and the assignment, as defined by | |||
5462 | // is_assignable, is known to call no operation that is not trivial | |||
5463 | // | |||
5464 | // is_assignable is defined as: | |||
5465 | // The expression declval<T>() = declval<U>() is well-formed when | |||
5466 | // treated as an unevaluated operand (Clause 5). | |||
5467 | // | |||
5468 | // For both, T and U shall be complete types, (possibly cv-qualified) | |||
5469 | // void, or arrays of unknown bound. | |||
5470 | if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() && | |||
5471 | Self.RequireCompleteType(KeyLoc, LhsT, | |||
5472 | diag::err_incomplete_type_used_in_type_trait_expr)) | |||
5473 | return false; | |||
5474 | if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() && | |||
5475 | Self.RequireCompleteType(KeyLoc, RhsT, | |||
5476 | diag::err_incomplete_type_used_in_type_trait_expr)) | |||
5477 | return false; | |||
5478 | ||||
5479 | // cv void is never assignable. | |||
5480 | if (LhsT->isVoidType() || RhsT->isVoidType()) | |||
5481 | return false; | |||
5482 | ||||
5483 | // Build expressions that emulate the effect of declval<T>() and | |||
5484 | // declval<U>(). | |||
5485 | if (LhsT->isObjectType() || LhsT->isFunctionType()) | |||
5486 | LhsT = Self.Context.getRValueReferenceType(LhsT); | |||
5487 | if (RhsT->isObjectType() || RhsT->isFunctionType()) | |||
5488 | RhsT = Self.Context.getRValueReferenceType(RhsT); | |||
5489 | OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context), | |||
5490 | Expr::getValueKindForType(LhsT)); | |||
5491 | OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context), | |||
5492 | Expr::getValueKindForType(RhsT)); | |||
5493 | ||||
5494 | // Attempt the assignment in an unevaluated context within a SFINAE | |||
5495 | // trap at translation unit scope. | |||
5496 | EnterExpressionEvaluationContext Unevaluated( | |||
5497 | Self, Sema::ExpressionEvaluationContext::Unevaluated); | |||
5498 | Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true); | |||
5499 | Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl()); | |||
5500 | ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs, | |||
5501 | &Rhs); | |||
5502 | if (Result.isInvalid()) | |||
5503 | return false; | |||
5504 | ||||
5505 | // Treat the assignment as unused for the purpose of -Wdeprecated-volatile. | |||
5506 | Self.CheckUnusedVolatileAssignment(Result.get()); | |||
5507 | ||||
5508 | if (SFINAE.hasErrorOccurred()) | |||
5509 | return false; | |||
5510 | ||||
5511 | if (BTT == BTT_IsAssignable) | |||
5512 | return true; | |||
5513 | ||||
5514 | if (BTT == BTT_IsNothrowAssignable) | |||
5515 | return Self.canThrow(Result.get()) == CT_Cannot; | |||
5516 | ||||
5517 | if (BTT == BTT_IsTriviallyAssignable) { | |||
5518 | // Under Objective-C ARC and Weak, if the destination has non-trivial | |||
5519 | // Objective-C lifetime, this is a non-trivial assignment. | |||
5520 | if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime()) | |||
5521 | return false; | |||
5522 | ||||
5523 | return !Result.get()->hasNonTrivialCall(Self.Context); | |||
5524 | } | |||
5525 | ||||
5526 | llvm_unreachable("unhandled type trait")::llvm::llvm_unreachable_internal("unhandled type trait", "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 5526); | |||
5527 | return false; | |||
5528 | } | |||
5529 | default: llvm_unreachable("not a BTT")::llvm::llvm_unreachable_internal("not a BTT", "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 5529); | |||
5530 | } | |||
5531 | llvm_unreachable("Unknown type trait or not implemented")::llvm::llvm_unreachable_internal("Unknown type trait or not implemented" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 5531); | |||
5532 | } | |||
5533 | ||||
5534 | ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT, | |||
5535 | SourceLocation KWLoc, | |||
5536 | ParsedType Ty, | |||
5537 | Expr* DimExpr, | |||
5538 | SourceLocation RParen) { | |||
5539 | TypeSourceInfo *TSInfo; | |||
5540 | QualType T = GetTypeFromParser(Ty, &TSInfo); | |||
5541 | if (!TSInfo) | |||
5542 | TSInfo = Context.getTrivialTypeSourceInfo(T); | |||
5543 | ||||
5544 | return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen); | |||
5545 | } | |||
5546 | ||||
5547 | static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT, | |||
5548 | QualType T, Expr *DimExpr, | |||
5549 | SourceLocation KeyLoc) { | |||
5550 | assert(!T->isDependentType() && "Cannot evaluate traits of dependent type")(static_cast <bool> (!T->isDependentType() && "Cannot evaluate traits of dependent type") ? void (0) : __assert_fail ("!T->isDependentType() && \"Cannot evaluate traits of dependent type\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 5550, __extension__ __PRETTY_FUNCTION__)); | |||
5551 | ||||
5552 | switch(ATT) { | |||
5553 | case ATT_ArrayRank: | |||
5554 | if (T->isArrayType()) { | |||
5555 | unsigned Dim = 0; | |||
5556 | while (const ArrayType *AT = Self.Context.getAsArrayType(T)) { | |||
5557 | ++Dim; | |||
5558 | T = AT->getElementType(); | |||
5559 | } | |||
5560 | return Dim; | |||
5561 | } | |||
5562 | return 0; | |||
5563 | ||||
5564 | case ATT_ArrayExtent: { | |||
5565 | llvm::APSInt Value; | |||
5566 | uint64_t Dim; | |||
5567 | if (Self.VerifyIntegerConstantExpression( | |||
5568 | DimExpr, &Value, diag::err_dimension_expr_not_constant_integer) | |||
5569 | .isInvalid()) | |||
5570 | return 0; | |||
5571 | if (Value.isSigned() && Value.isNegative()) { | |||
5572 | Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) | |||
5573 | << DimExpr->getSourceRange(); | |||
5574 | return 0; | |||
5575 | } | |||
5576 | Dim = Value.getLimitedValue(); | |||
5577 | ||||
5578 | if (T->isArrayType()) { | |||
5579 | unsigned D = 0; | |||
5580 | bool Matched = false; | |||
5581 | while (const ArrayType *AT = Self.Context.getAsArrayType(T)) { | |||
5582 | if (Dim == D) { | |||
5583 | Matched = true; | |||
5584 | break; | |||
5585 | } | |||
5586 | ++D; | |||
5587 | T = AT->getElementType(); | |||
5588 | } | |||
5589 | ||||
5590 | if (Matched && T->isArrayType()) { | |||
5591 | if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T)) | |||
5592 | return CAT->getSize().getLimitedValue(); | |||
5593 | } | |||
5594 | } | |||
5595 | return 0; | |||
5596 | } | |||
5597 | } | |||
5598 | llvm_unreachable("Unknown type trait or not implemented")::llvm::llvm_unreachable_internal("Unknown type trait or not implemented" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 5598); | |||
5599 | } | |||
5600 | ||||
5601 | ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT, | |||
5602 | SourceLocation KWLoc, | |||
5603 | TypeSourceInfo *TSInfo, | |||
5604 | Expr* DimExpr, | |||
5605 | SourceLocation RParen) { | |||
5606 | QualType T = TSInfo->getType(); | |||
5607 | ||||
5608 | // FIXME: This should likely be tracked as an APInt to remove any host | |||
5609 | // assumptions about the width of size_t on the target. | |||
5610 | uint64_t Value = 0; | |||
5611 | if (!T->isDependentType()) | |||
5612 | Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc); | |||
5613 | ||||
5614 | // While the specification for these traits from the Embarcadero C++ | |||
5615 | // compiler's documentation says the return type is 'unsigned int', Clang | |||
5616 | // returns 'size_t'. On Windows, the primary platform for the Embarcadero | |||
5617 | // compiler, there is no difference. On several other platforms this is an | |||
5618 | // important distinction. | |||
5619 | return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr, | |||
5620 | RParen, Context.getSizeType()); | |||
5621 | } | |||
5622 | ||||
5623 | ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET, | |||
5624 | SourceLocation KWLoc, | |||
5625 | Expr *Queried, | |||
5626 | SourceLocation RParen) { | |||
5627 | // If error parsing the expression, ignore. | |||
5628 | if (!Queried) | |||
5629 | return ExprError(); | |||
5630 | ||||
5631 | ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen); | |||
5632 | ||||
5633 | return Result; | |||
5634 | } | |||
5635 | ||||
5636 | static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) { | |||
5637 | switch (ET) { | |||
5638 | case ET_IsLValueExpr: return E->isLValue(); | |||
5639 | case ET_IsRValueExpr: return E->isRValue(); | |||
5640 | } | |||
5641 | llvm_unreachable("Expression trait not covered by switch")::llvm::llvm_unreachable_internal("Expression trait not covered by switch" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 5641); | |||
5642 | } | |||
5643 | ||||
5644 | ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET, | |||
5645 | SourceLocation KWLoc, | |||
5646 | Expr *Queried, | |||
5647 | SourceLocation RParen) { | |||
5648 | if (Queried->isTypeDependent()) { | |||
5649 | // Delay type-checking for type-dependent expressions. | |||
5650 | } else if (Queried->getType()->isPlaceholderType()) { | |||
5651 | ExprResult PE = CheckPlaceholderExpr(Queried); | |||
5652 | if (PE.isInvalid()) return ExprError(); | |||
5653 | return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen); | |||
5654 | } | |||
5655 | ||||
5656 | bool Value = EvaluateExpressionTrait(ET, Queried); | |||
5657 | ||||
5658 | return new (Context) | |||
5659 | ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy); | |||
5660 | } | |||
5661 | ||||
5662 | QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, | |||
5663 | ExprValueKind &VK, | |||
5664 | SourceLocation Loc, | |||
5665 | bool isIndirect) { | |||
5666 | assert(!LHS.get()->getType()->isPlaceholderType() &&(static_cast <bool> (!LHS.get()->getType()->isPlaceholderType () && !RHS.get()->getType()->isPlaceholderType( ) && "placeholders should have been weeded out by now" ) ? void (0) : __assert_fail ("!LHS.get()->getType()->isPlaceholderType() && !RHS.get()->getType()->isPlaceholderType() && \"placeholders should have been weeded out by now\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 5668, __extension__ __PRETTY_FUNCTION__)) | |||
5667 | !RHS.get()->getType()->isPlaceholderType() &&(static_cast <bool> (!LHS.get()->getType()->isPlaceholderType () && !RHS.get()->getType()->isPlaceholderType( ) && "placeholders should have been weeded out by now" ) ? void (0) : __assert_fail ("!LHS.get()->getType()->isPlaceholderType() && !RHS.get()->getType()->isPlaceholderType() && \"placeholders should have been weeded out by now\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 5668, __extension__ __PRETTY_FUNCTION__)) | |||
5668 | "placeholders should have been weeded out by now")(static_cast <bool> (!LHS.get()->getType()->isPlaceholderType () && !RHS.get()->getType()->isPlaceholderType( ) && "placeholders should have been weeded out by now" ) ? void (0) : __assert_fail ("!LHS.get()->getType()->isPlaceholderType() && !RHS.get()->getType()->isPlaceholderType() && \"placeholders should have been weeded out by now\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 5668, __extension__ __PRETTY_FUNCTION__)); | |||
5669 | ||||
5670 | // The LHS undergoes lvalue conversions if this is ->*, and undergoes the | |||
5671 | // temporary materialization conversion otherwise. | |||
5672 | if (isIndirect) | |||
5673 | LHS = DefaultLvalueConversion(LHS.get()); | |||
5674 | else if (LHS.get()->isRValue()) | |||
5675 | LHS = TemporaryMaterializationConversion(LHS.get()); | |||
5676 | if (LHS.isInvalid()) | |||
5677 | return QualType(); | |||
5678 | ||||
5679 | // The RHS always undergoes lvalue conversions. | |||
5680 | RHS = DefaultLvalueConversion(RHS.get()); | |||
5681 | if (RHS.isInvalid()) return QualType(); | |||
5682 | ||||
5683 | const char *OpSpelling = isIndirect ? "->*" : ".*"; | |||
5684 | // C++ 5.5p2 | |||
5685 | // The binary operator .* [p3: ->*] binds its second operand, which shall | |||
5686 | // be of type "pointer to member of T" (where T is a completely-defined | |||
5687 | // class type) [...] | |||
5688 | QualType RHSType = RHS.get()->getType(); | |||
5689 | const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>(); | |||
5690 | if (!MemPtr) { | |||
5691 | Diag(Loc, diag::err_bad_memptr_rhs) | |||
5692 | << OpSpelling << RHSType << RHS.get()->getSourceRange(); | |||
5693 | return QualType(); | |||
5694 | } | |||
5695 | ||||
5696 | QualType Class(MemPtr->getClass(), 0); | |||
5697 | ||||
5698 | // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the | |||
5699 | // member pointer points must be completely-defined. However, there is no | |||
5700 | // reason for this semantic distinction, and the rule is not enforced by | |||
5701 | // other compilers. Therefore, we do not check this property, as it is | |||
5702 | // likely to be considered a defect. | |||
5703 | ||||
5704 | // C++ 5.5p2 | |||
5705 | // [...] to its first operand, which shall be of class T or of a class of | |||
5706 | // which T is an unambiguous and accessible base class. [p3: a pointer to | |||
5707 | // such a class] | |||
5708 | QualType LHSType = LHS.get()->getType(); | |||
5709 | if (isIndirect) { | |||
5710 | if (const PointerType *Ptr = LHSType->getAs<PointerType>()) | |||
5711 | LHSType = Ptr->getPointeeType(); | |||
5712 | else { | |||
5713 | Diag(Loc, diag::err_bad_memptr_lhs) | |||
5714 | << OpSpelling << 1 << LHSType | |||
5715 | << FixItHint::CreateReplacement(SourceRange(Loc), ".*"); | |||
5716 | return QualType(); | |||
5717 | } | |||
5718 | } | |||
5719 | ||||
5720 | if (!Context.hasSameUnqualifiedType(Class, LHSType)) { | |||
5721 | // If we want to check the hierarchy, we need a complete type. | |||
5722 | if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs, | |||
5723 | OpSpelling, (int)isIndirect)) { | |||
5724 | return QualType(); | |||
5725 | } | |||
5726 | ||||
5727 | if (!IsDerivedFrom(Loc, LHSType, Class)) { | |||
5728 | Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling | |||
5729 | << (int)isIndirect << LHS.get()->getType(); | |||
5730 | return QualType(); | |||
5731 | } | |||
5732 | ||||
5733 | CXXCastPath BasePath; | |||
5734 | if (CheckDerivedToBaseConversion( | |||
5735 | LHSType, Class, Loc, | |||
5736 | SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()), | |||
5737 | &BasePath)) | |||
5738 | return QualType(); | |||
5739 | ||||
5740 | // Cast LHS to type of use. | |||
5741 | QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers()); | |||
5742 | if (isIndirect) | |||
5743 | UseType = Context.getPointerType(UseType); | |||
5744 | ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind(); | |||
5745 | LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK, | |||
5746 | &BasePath); | |||
5747 | } | |||
5748 | ||||
5749 | if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) { | |||
5750 | // Diagnose use of pointer-to-member type which when used as | |||
5751 | // the functional cast in a pointer-to-member expression. | |||
5752 | Diag(Loc, diag::err_pointer_to_member_type) << isIndirect; | |||
5753 | return QualType(); | |||
5754 | } | |||
5755 | ||||
5756 | // C++ 5.5p2 | |||
5757 | // The result is an object or a function of the type specified by the | |||
5758 | // second operand. | |||
5759 | // The cv qualifiers are the union of those in the pointer and the left side, | |||
5760 | // in accordance with 5.5p5 and 5.2.5. | |||
5761 | QualType Result = MemPtr->getPointeeType(); | |||
5762 | Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers()); | |||
5763 | ||||
5764 | // C++0x [expr.mptr.oper]p6: | |||
5765 | // In a .* expression whose object expression is an rvalue, the program is | |||
5766 | // ill-formed if the second operand is a pointer to member function with | |||
5767 | // ref-qualifier &. In a ->* expression or in a .* expression whose object | |||
5768 | // expression is an lvalue, the program is ill-formed if the second operand | |||
5769 | // is a pointer to member function with ref-qualifier &&. | |||
5770 | if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) { | |||
5771 | switch (Proto->getRefQualifier()) { | |||
5772 | case RQ_None: | |||
5773 | // Do nothing | |||
5774 | break; | |||
5775 | ||||
5776 | case RQ_LValue: | |||
5777 | if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) { | |||
5778 | // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq | |||
5779 | // is (exactly) 'const'. | |||
5780 | if (Proto->isConst() && !Proto->isVolatile()) | |||
5781 | Diag(Loc, getLangOpts().CPlusPlus20 | |||
5782 | ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue | |||
5783 | : diag::ext_pointer_to_const_ref_member_on_rvalue); | |||
5784 | else | |||
5785 | Diag(Loc, diag::err_pointer_to_member_oper_value_classify) | |||
5786 | << RHSType << 1 << LHS.get()->getSourceRange(); | |||
5787 | } | |||
5788 | break; | |||
5789 | ||||
5790 | case RQ_RValue: | |||
5791 | if (isIndirect || !LHS.get()->Classify(Context).isRValue()) | |||
5792 | Diag(Loc, diag::err_pointer_to_member_oper_value_classify) | |||
5793 | << RHSType << 0 << LHS.get()->getSourceRange(); | |||
5794 | break; | |||
5795 | } | |||
5796 | } | |||
5797 | ||||
5798 | // C++ [expr.mptr.oper]p6: | |||
5799 | // The result of a .* expression whose second operand is a pointer | |||
5800 | // to a data member is of the same value category as its | |||
5801 | // first operand. The result of a .* expression whose second | |||
5802 | // operand is a pointer to a member function is a prvalue. The | |||
5803 | // result of an ->* expression is an lvalue if its second operand | |||
5804 | // is a pointer to data member and a prvalue otherwise. | |||
5805 | if (Result->isFunctionType()) { | |||
5806 | VK = VK_RValue; | |||
5807 | return Context.BoundMemberTy; | |||
5808 | } else if (isIndirect) { | |||
5809 | VK = VK_LValue; | |||
5810 | } else { | |||
5811 | VK = LHS.get()->getValueKind(); | |||
5812 | } | |||
5813 | ||||
5814 | return Result; | |||
5815 | } | |||
5816 | ||||
5817 | /// Try to convert a type to another according to C++11 5.16p3. | |||
5818 | /// | |||
5819 | /// This is part of the parameter validation for the ? operator. If either | |||
5820 | /// value operand is a class type, the two operands are attempted to be | |||
5821 | /// converted to each other. This function does the conversion in one direction. | |||
5822 | /// It returns true if the program is ill-formed and has already been diagnosed | |||
5823 | /// as such. | |||
5824 | static bool TryClassUnification(Sema &Self, Expr *From, Expr *To, | |||
5825 | SourceLocation QuestionLoc, | |||
5826 | bool &HaveConversion, | |||
5827 | QualType &ToType) { | |||
5828 | HaveConversion = false; | |||
5829 | ToType = To->getType(); | |||
5830 | ||||
5831 | InitializationKind Kind = | |||
5832 | InitializationKind::CreateCopy(To->getBeginLoc(), SourceLocation()); | |||
5833 | // C++11 5.16p3 | |||
5834 | // The process for determining whether an operand expression E1 of type T1 | |||
5835 | // can be converted to match an operand expression E2 of type T2 is defined | |||
5836 | // as follows: | |||
5837 | // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be | |||
5838 | // implicitly converted to type "lvalue reference to T2", subject to the | |||
5839 | // constraint that in the conversion the reference must bind directly to | |||
5840 | // an lvalue. | |||
5841 | // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be | |||
5842 | // implicitly converted to the type "rvalue reference to R2", subject to | |||
5843 | // the constraint that the reference must bind directly. | |||
5844 | if (To->isLValue() || To->isXValue()) { | |||
5845 | QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType) | |||
5846 | : Self.Context.getRValueReferenceType(ToType); | |||
5847 | ||||
5848 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); | |||
5849 | ||||
5850 | InitializationSequence InitSeq(Self, Entity, Kind, From); | |||
5851 | if (InitSeq.isDirectReferenceBinding()) { | |||
5852 | ToType = T; | |||
5853 | HaveConversion = true; | |||
5854 | return false; | |||
5855 | } | |||
5856 | ||||
5857 | if (InitSeq.isAmbiguous()) | |||
5858 | return InitSeq.Diagnose(Self, Entity, Kind, From); | |||
5859 | } | |||
5860 | ||||
5861 | // -- If E2 is an rvalue, or if the conversion above cannot be done: | |||
5862 | // -- if E1 and E2 have class type, and the underlying class types are | |||
5863 | // the same or one is a base class of the other: | |||
5864 | QualType FTy = From->getType(); | |||
5865 | QualType TTy = To->getType(); | |||
5866 | const RecordType *FRec = FTy->getAs<RecordType>(); | |||
5867 | const RecordType *TRec = TTy->getAs<RecordType>(); | |||
5868 | bool FDerivedFromT = FRec && TRec && FRec != TRec && | |||
5869 | Self.IsDerivedFrom(QuestionLoc, FTy, TTy); | |||
5870 | if (FRec && TRec && (FRec == TRec || FDerivedFromT || | |||
5871 | Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) { | |||
5872 | // E1 can be converted to match E2 if the class of T2 is the | |||
5873 | // same type as, or a base class of, the class of T1, and | |||
5874 | // [cv2 > cv1]. | |||
5875 | if (FRec == TRec || FDerivedFromT) { | |||
5876 | if (TTy.isAtLeastAsQualifiedAs(FTy)) { | |||
5877 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); | |||
5878 | InitializationSequence InitSeq(Self, Entity, Kind, From); | |||
5879 | if (InitSeq) { | |||
5880 | HaveConversion = true; | |||
5881 | return false; | |||
5882 | } | |||
5883 | ||||
5884 | if (InitSeq.isAmbiguous()) | |||
5885 | return InitSeq.Diagnose(Self, Entity, Kind, From); | |||
5886 | } | |||
5887 | } | |||
5888 | ||||
5889 | return false; | |||
5890 | } | |||
5891 | ||||
5892 | // -- Otherwise: E1 can be converted to match E2 if E1 can be | |||
5893 | // implicitly converted to the type that expression E2 would have | |||
5894 | // if E2 were converted to an rvalue (or the type it has, if E2 is | |||
5895 | // an rvalue). | |||
5896 | // | |||
5897 | // This actually refers very narrowly to the lvalue-to-rvalue conversion, not | |||
5898 | // to the array-to-pointer or function-to-pointer conversions. | |||
5899 | TTy = TTy.getNonLValueExprType(Self.Context); | |||
5900 | ||||
5901 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); | |||
5902 | InitializationSequence InitSeq(Self, Entity, Kind, From); | |||
5903 | HaveConversion = !InitSeq.Failed(); | |||
5904 | ToType = TTy; | |||
5905 | if (InitSeq.isAmbiguous()) | |||
5906 | return InitSeq.Diagnose(Self, Entity, Kind, From); | |||
5907 | ||||
5908 | return false; | |||
5909 | } | |||
5910 | ||||
5911 | /// Try to find a common type for two according to C++0x 5.16p5. | |||
5912 | /// | |||
5913 | /// This is part of the parameter validation for the ? operator. If either | |||
5914 | /// value operand is a class type, overload resolution is used to find a | |||
5915 | /// conversion to a common type. | |||
5916 | static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS, | |||
5917 | SourceLocation QuestionLoc) { | |||
5918 | Expr *Args[2] = { LHS.get(), RHS.get() }; | |||
5919 | OverloadCandidateSet CandidateSet(QuestionLoc, | |||
5920 | OverloadCandidateSet::CSK_Operator); | |||
5921 | Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, | |||
5922 | CandidateSet); | |||
5923 | ||||
5924 | OverloadCandidateSet::iterator Best; | |||
5925 | switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) { | |||
5926 | case OR_Success: { | |||
5927 | // We found a match. Perform the conversions on the arguments and move on. | |||
5928 | ExprResult LHSRes = Self.PerformImplicitConversion( | |||
5929 | LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0], | |||
5930 | Sema::AA_Converting); | |||
5931 | if (LHSRes.isInvalid()) | |||
5932 | break; | |||
5933 | LHS = LHSRes; | |||
5934 | ||||
5935 | ExprResult RHSRes = Self.PerformImplicitConversion( | |||
5936 | RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1], | |||
5937 | Sema::AA_Converting); | |||
5938 | if (RHSRes.isInvalid()) | |||
5939 | break; | |||
5940 | RHS = RHSRes; | |||
5941 | if (Best->Function) | |||
5942 | Self.MarkFunctionReferenced(QuestionLoc, Best->Function); | |||
5943 | return false; | |||
5944 | } | |||
5945 | ||||
5946 | case OR_No_Viable_Function: | |||
5947 | ||||
5948 | // Emit a better diagnostic if one of the expressions is a null pointer | |||
5949 | // constant and the other is a pointer type. In this case, the user most | |||
5950 | // likely forgot to take the address of the other expression. | |||
5951 | if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) | |||
5952 | return true; | |||
5953 | ||||
5954 | Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) | |||
5955 | << LHS.get()->getType() << RHS.get()->getType() | |||
5956 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
5957 | return true; | |||
5958 | ||||
5959 | case OR_Ambiguous: | |||
5960 | Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl) | |||
5961 | << LHS.get()->getType() << RHS.get()->getType() | |||
5962 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
5963 | // FIXME: Print the possible common types by printing the return types of | |||
5964 | // the viable candidates. | |||
5965 | break; | |||
5966 | ||||
5967 | case OR_Deleted: | |||
5968 | llvm_unreachable("Conditional operator has only built-in overloads")::llvm::llvm_unreachable_internal("Conditional operator has only built-in overloads" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 5968); | |||
5969 | } | |||
5970 | return true; | |||
5971 | } | |||
5972 | ||||
5973 | /// Perform an "extended" implicit conversion as returned by | |||
5974 | /// TryClassUnification. | |||
5975 | static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) { | |||
5976 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); | |||
5977 | InitializationKind Kind = | |||
5978 | InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation()); | |||
5979 | Expr *Arg = E.get(); | |||
5980 | InitializationSequence InitSeq(Self, Entity, Kind, Arg); | |||
5981 | ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg); | |||
5982 | if (Result.isInvalid()) | |||
5983 | return true; | |||
5984 | ||||
5985 | E = Result; | |||
5986 | return false; | |||
5987 | } | |||
5988 | ||||
5989 | // Check the condition operand of ?: to see if it is valid for the GCC | |||
5990 | // extension. | |||
5991 | static bool isValidVectorForConditionalCondition(ASTContext &Ctx, | |||
5992 | QualType CondTy) { | |||
5993 | if (!CondTy->isVectorType() && !CondTy->isExtVectorType()) | |||
5994 | return false; | |||
5995 | const QualType EltTy = | |||
5996 | cast<VectorType>(CondTy.getCanonicalType())->getElementType(); | |||
5997 | assert(!EltTy->isBooleanType() && !EltTy->isEnumeralType() &&(static_cast <bool> (!EltTy->isBooleanType() && !EltTy->isEnumeralType() && "Vectors cant be boolean or enum types" ) ? void (0) : __assert_fail ("!EltTy->isBooleanType() && !EltTy->isEnumeralType() && \"Vectors cant be boolean or enum types\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 5998, __extension__ __PRETTY_FUNCTION__)) | |||
5998 | "Vectors cant be boolean or enum types")(static_cast <bool> (!EltTy->isBooleanType() && !EltTy->isEnumeralType() && "Vectors cant be boolean or enum types" ) ? void (0) : __assert_fail ("!EltTy->isBooleanType() && !EltTy->isEnumeralType() && \"Vectors cant be boolean or enum types\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 5998, __extension__ __PRETTY_FUNCTION__)); | |||
5999 | return EltTy->isIntegralType(Ctx); | |||
6000 | } | |||
6001 | ||||
6002 | QualType Sema::CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, | |||
6003 | ExprResult &RHS, | |||
6004 | SourceLocation QuestionLoc) { | |||
6005 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | |||
6006 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | |||
6007 | ||||
6008 | QualType CondType = Cond.get()->getType(); | |||
6009 | const auto *CondVT = CondType->castAs<VectorType>(); | |||
6010 | QualType CondElementTy = CondVT->getElementType(); | |||
6011 | unsigned CondElementCount = CondVT->getNumElements(); | |||
6012 | QualType LHSType = LHS.get()->getType(); | |||
6013 | const auto *LHSVT = LHSType->getAs<VectorType>(); | |||
6014 | QualType RHSType = RHS.get()->getType(); | |||
6015 | const auto *RHSVT = RHSType->getAs<VectorType>(); | |||
6016 | ||||
6017 | QualType ResultType; | |||
6018 | ||||
6019 | ||||
6020 | if (LHSVT && RHSVT) { | |||
6021 | if (isa<ExtVectorType>(CondVT) != isa<ExtVectorType>(LHSVT)) { | |||
6022 | Diag(QuestionLoc, diag::err_conditional_vector_cond_result_mismatch) | |||
6023 | << /*isExtVector*/ isa<ExtVectorType>(CondVT); | |||
6024 | return {}; | |||
6025 | } | |||
6026 | ||||
6027 | // If both are vector types, they must be the same type. | |||
6028 | if (!Context.hasSameType(LHSType, RHSType)) { | |||
6029 | Diag(QuestionLoc, diag::err_conditional_vector_mismatched) | |||
6030 | << LHSType << RHSType; | |||
6031 | return {}; | |||
6032 | } | |||
6033 | ResultType = LHSType; | |||
6034 | } else if (LHSVT || RHSVT) { | |||
6035 | ResultType = CheckVectorOperands( | |||
6036 | LHS, RHS, QuestionLoc, /*isCompAssign*/ false, /*AllowBothBool*/ true, | |||
6037 | /*AllowBoolConversions*/ false); | |||
6038 | if (ResultType.isNull()) | |||
6039 | return {}; | |||
6040 | } else { | |||
6041 | // Both are scalar. | |||
6042 | QualType ResultElementTy; | |||
6043 | LHSType = LHSType.getCanonicalType().getUnqualifiedType(); | |||
6044 | RHSType = RHSType.getCanonicalType().getUnqualifiedType(); | |||
6045 | ||||
6046 | if (Context.hasSameType(LHSType, RHSType)) | |||
6047 | ResultElementTy = LHSType; | |||
6048 | else | |||
6049 | ResultElementTy = | |||
6050 | UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); | |||
6051 | ||||
6052 | if (ResultElementTy->isEnumeralType()) { | |||
6053 | Diag(QuestionLoc, diag::err_conditional_vector_operand_type) | |||
6054 | << ResultElementTy; | |||
6055 | return {}; | |||
6056 | } | |||
6057 | if (CondType->isExtVectorType()) | |||
6058 | ResultType = | |||
6059 | Context.getExtVectorType(ResultElementTy, CondVT->getNumElements()); | |||
6060 | else | |||
6061 | ResultType = Context.getVectorType( | |||
6062 | ResultElementTy, CondVT->getNumElements(), VectorType::GenericVector); | |||
6063 | ||||
6064 | LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat); | |||
6065 | RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat); | |||
6066 | } | |||
6067 | ||||
6068 | assert(!ResultType.isNull() && ResultType->isVectorType() &&(static_cast <bool> (!ResultType.isNull() && ResultType ->isVectorType() && (!CondType->isExtVectorType () || ResultType->isExtVectorType()) && "Result should have been a vector type" ) ? void (0) : __assert_fail ("!ResultType.isNull() && ResultType->isVectorType() && (!CondType->isExtVectorType() || ResultType->isExtVectorType()) && \"Result should have been a vector type\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 6070, __extension__ __PRETTY_FUNCTION__)) | |||
6069 | (!CondType->isExtVectorType() || ResultType->isExtVectorType()) &&(static_cast <bool> (!ResultType.isNull() && ResultType ->isVectorType() && (!CondType->isExtVectorType () || ResultType->isExtVectorType()) && "Result should have been a vector type" ) ? void (0) : __assert_fail ("!ResultType.isNull() && ResultType->isVectorType() && (!CondType->isExtVectorType() || ResultType->isExtVectorType()) && \"Result should have been a vector type\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 6070, __extension__ __PRETTY_FUNCTION__)) | |||
6070 | "Result should have been a vector type")(static_cast <bool> (!ResultType.isNull() && ResultType ->isVectorType() && (!CondType->isExtVectorType () || ResultType->isExtVectorType()) && "Result should have been a vector type" ) ? void (0) : __assert_fail ("!ResultType.isNull() && ResultType->isVectorType() && (!CondType->isExtVectorType() || ResultType->isExtVectorType()) && \"Result should have been a vector type\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 6070, __extension__ __PRETTY_FUNCTION__)); | |||
6071 | auto *ResultVectorTy = ResultType->castAs<VectorType>(); | |||
6072 | QualType ResultElementTy = ResultVectorTy->getElementType(); | |||
6073 | unsigned ResultElementCount = ResultVectorTy->getNumElements(); | |||
6074 | ||||
6075 | if (ResultElementCount != CondElementCount) { | |||
6076 | Diag(QuestionLoc, diag::err_conditional_vector_size) << CondType | |||
6077 | << ResultType; | |||
6078 | return {}; | |||
6079 | } | |||
6080 | ||||
6081 | if (Context.getTypeSize(ResultElementTy) != | |||
6082 | Context.getTypeSize(CondElementTy)) { | |||
6083 | Diag(QuestionLoc, diag::err_conditional_vector_element_size) << CondType | |||
6084 | << ResultType; | |||
6085 | return {}; | |||
6086 | } | |||
6087 | ||||
6088 | return ResultType; | |||
6089 | } | |||
6090 | ||||
6091 | /// Check the operands of ?: under C++ semantics. | |||
6092 | /// | |||
6093 | /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y | |||
6094 | /// extension. In this case, LHS == Cond. (But they're not aliases.) | |||
6095 | /// | |||
6096 | /// This function also implements GCC's vector extension and the | |||
6097 | /// OpenCL/ext_vector_type extension for conditionals. The vector extensions | |||
6098 | /// permit the use of a?b:c where the type of a is that of a integer vector with | |||
6099 | /// the same number of elements and size as the vectors of b and c. If one of | |||
6100 | /// either b or c is a scalar it is implicitly converted to match the type of | |||
6101 | /// the vector. Otherwise the expression is ill-formed. If both b and c are | |||
6102 | /// scalars, then b and c are checked and converted to the type of a if | |||
6103 | /// possible. | |||
6104 | /// | |||
6105 | /// The expressions are evaluated differently for GCC's and OpenCL's extensions. | |||
6106 | /// For the GCC extension, the ?: operator is evaluated as | |||
6107 | /// (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]). | |||
6108 | /// For the OpenCL extensions, the ?: operator is evaluated as | |||
6109 | /// (most-significant-bit-set(a[0]) ? b[0] : c[0], .. , | |||
6110 | /// most-significant-bit-set(a[n]) ? b[n] : c[n]). | |||
6111 | QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, | |||
6112 | ExprResult &RHS, ExprValueKind &VK, | |||
6113 | ExprObjectKind &OK, | |||
6114 | SourceLocation QuestionLoc) { | |||
6115 | // FIXME: Handle C99's complex types, block pointers and Obj-C++ interface | |||
6116 | // pointers. | |||
6117 | ||||
6118 | // Assume r-value. | |||
6119 | VK = VK_RValue; | |||
6120 | OK = OK_Ordinary; | |||
6121 | bool IsVectorConditional = | |||
6122 | isValidVectorForConditionalCondition(Context, Cond.get()->getType()); | |||
6123 | ||||
6124 | // C++11 [expr.cond]p1 | |||
6125 | // The first expression is contextually converted to bool. | |||
6126 | if (!Cond.get()->isTypeDependent()) { | |||
6127 | ExprResult CondRes = IsVectorConditional | |||
6128 | ? DefaultFunctionArrayLvalueConversion(Cond.get()) | |||
6129 | : CheckCXXBooleanCondition(Cond.get()); | |||
6130 | if (CondRes.isInvalid()) | |||
6131 | return QualType(); | |||
6132 | Cond = CondRes; | |||
6133 | } else { | |||
6134 | // To implement C++, the first expression typically doesn't alter the result | |||
6135 | // type of the conditional, however the GCC compatible vector extension | |||
6136 | // changes the result type to be that of the conditional. Since we cannot | |||
6137 | // know if this is a vector extension here, delay the conversion of the | |||
6138 | // LHS/RHS below until later. | |||
6139 | return Context.DependentTy; | |||
6140 | } | |||
6141 | ||||
6142 | ||||
6143 | // Either of the arguments dependent? | |||
6144 | if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent()) | |||
6145 | return Context.DependentTy; | |||
6146 | ||||
6147 | // C++11 [expr.cond]p2 | |||
6148 | // If either the second or the third operand has type (cv) void, ... | |||
6149 | QualType LTy = LHS.get()->getType(); | |||
6150 | QualType RTy = RHS.get()->getType(); | |||
6151 | bool LVoid = LTy->isVoidType(); | |||
6152 | bool RVoid = RTy->isVoidType(); | |||
6153 | if (LVoid || RVoid) { | |||
6154 | // ... one of the following shall hold: | |||
6155 | // -- The second or the third operand (but not both) is a (possibly | |||
6156 | // parenthesized) throw-expression; the result is of the type | |||
6157 | // and value category of the other. | |||
6158 | bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts()); | |||
6159 | bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts()); | |||
6160 | ||||
6161 | // Void expressions aren't legal in the vector-conditional expressions. | |||
6162 | if (IsVectorConditional) { | |||
6163 | SourceRange DiagLoc = | |||
6164 | LVoid ? LHS.get()->getSourceRange() : RHS.get()->getSourceRange(); | |||
6165 | bool IsThrow = LVoid ? LThrow : RThrow; | |||
6166 | Diag(DiagLoc.getBegin(), diag::err_conditional_vector_has_void) | |||
6167 | << DiagLoc << IsThrow; | |||
6168 | return QualType(); | |||
6169 | } | |||
6170 | ||||
6171 | if (LThrow != RThrow) { | |||
6172 | Expr *NonThrow = LThrow ? RHS.get() : LHS.get(); | |||
6173 | VK = NonThrow->getValueKind(); | |||
6174 | // DR (no number yet): the result is a bit-field if the | |||
6175 | // non-throw-expression operand is a bit-field. | |||
6176 | OK = NonThrow->getObjectKind(); | |||
6177 | return NonThrow->getType(); | |||
6178 | } | |||
6179 | ||||
6180 | // -- Both the second and third operands have type void; the result is of | |||
6181 | // type void and is a prvalue. | |||
6182 | if (LVoid && RVoid) | |||
6183 | return Context.VoidTy; | |||
6184 | ||||
6185 | // Neither holds, error. | |||
6186 | Diag(QuestionLoc, diag::err_conditional_void_nonvoid) | |||
6187 | << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1) | |||
6188 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
6189 | return QualType(); | |||
6190 | } | |||
6191 | ||||
6192 | // Neither is void. | |||
6193 | if (IsVectorConditional) | |||
6194 | return CheckVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc); | |||
6195 | ||||
6196 | // C++11 [expr.cond]p3 | |||
6197 | // Otherwise, if the second and third operand have different types, and | |||
6198 | // either has (cv) class type [...] an attempt is made to convert each of | |||
6199 | // those operands to the type of the other. | |||
6200 | if (!Context.hasSameType(LTy, RTy) && | |||
6201 | (LTy->isRecordType() || RTy->isRecordType())) { | |||
6202 | // These return true if a single direction is already ambiguous. | |||
6203 | QualType L2RType, R2LType; | |||
6204 | bool HaveL2R, HaveR2L; | |||
6205 | if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType)) | |||
6206 | return QualType(); | |||
6207 | if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType)) | |||
6208 | return QualType(); | |||
6209 | ||||
6210 | // If both can be converted, [...] the program is ill-formed. | |||
6211 | if (HaveL2R && HaveR2L) { | |||
6212 | Diag(QuestionLoc, diag::err_conditional_ambiguous) | |||
6213 | << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
6214 | return QualType(); | |||
6215 | } | |||
6216 | ||||
6217 | // If exactly one conversion is possible, that conversion is applied to | |||
6218 | // the chosen operand and the converted operands are used in place of the | |||
6219 | // original operands for the remainder of this section. | |||
6220 | if (HaveL2R) { | |||
6221 | if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid()) | |||
6222 | return QualType(); | |||
6223 | LTy = LHS.get()->getType(); | |||
6224 | } else if (HaveR2L) { | |||
6225 | if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid()) | |||
6226 | return QualType(); | |||
6227 | RTy = RHS.get()->getType(); | |||
6228 | } | |||
6229 | } | |||
6230 | ||||
6231 | // C++11 [expr.cond]p3 | |||
6232 | // if both are glvalues of the same value category and the same type except | |||
6233 | // for cv-qualification, an attempt is made to convert each of those | |||
6234 | // operands to the type of the other. | |||
6235 | // FIXME: | |||
6236 | // Resolving a defect in P0012R1: we extend this to cover all cases where | |||
6237 | // one of the operands is reference-compatible with the other, in order | |||
6238 | // to support conditionals between functions differing in noexcept. This | |||
6239 | // will similarly cover difference in array bounds after P0388R4. | |||
6240 | // FIXME: If LTy and RTy have a composite pointer type, should we convert to | |||
6241 | // that instead? | |||
6242 | ExprValueKind LVK = LHS.get()->getValueKind(); | |||
6243 | ExprValueKind RVK = RHS.get()->getValueKind(); | |||
6244 | if (!Context.hasSameType(LTy, RTy) && | |||
6245 | LVK == RVK && LVK != VK_RValue) { | |||
6246 | // DerivedToBase was already handled by the class-specific case above. | |||
6247 | // FIXME: Should we allow ObjC conversions here? | |||
6248 | const ReferenceConversions AllowedConversions = | |||
6249 | ReferenceConversions::Qualification | | |||
6250 | ReferenceConversions::NestedQualification | | |||
6251 | ReferenceConversions::Function; | |||
6252 | ||||
6253 | ReferenceConversions RefConv; | |||
6254 | if (CompareReferenceRelationship(QuestionLoc, LTy, RTy, &RefConv) == | |||
6255 | Ref_Compatible && | |||
6256 | !(RefConv & ~AllowedConversions) && | |||
6257 | // [...] subject to the constraint that the reference must bind | |||
6258 | // directly [...] | |||
6259 | !RHS.get()->refersToBitField() && !RHS.get()->refersToVectorElement()) { | |||
6260 | RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK); | |||
6261 | RTy = RHS.get()->getType(); | |||
6262 | } else if (CompareReferenceRelationship(QuestionLoc, RTy, LTy, &RefConv) == | |||
6263 | Ref_Compatible && | |||
6264 | !(RefConv & ~AllowedConversions) && | |||
6265 | !LHS.get()->refersToBitField() && | |||
6266 | !LHS.get()->refersToVectorElement()) { | |||
6267 | LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK); | |||
6268 | LTy = LHS.get()->getType(); | |||
6269 | } | |||
6270 | } | |||
6271 | ||||
6272 | // C++11 [expr.cond]p4 | |||
6273 | // If the second and third operands are glvalues of the same value | |||
6274 | // category and have the same type, the result is of that type and | |||
6275 | // value category and it is a bit-field if the second or the third | |||
6276 | // operand is a bit-field, or if both are bit-fields. | |||
6277 | // We only extend this to bitfields, not to the crazy other kinds of | |||
6278 | // l-values. | |||
6279 | bool Same = Context.hasSameType(LTy, RTy); | |||
6280 | if (Same && LVK == RVK && LVK != VK_RValue && | |||
6281 | LHS.get()->isOrdinaryOrBitFieldObject() && | |||
6282 | RHS.get()->isOrdinaryOrBitFieldObject()) { | |||
6283 | VK = LHS.get()->getValueKind(); | |||
6284 | if (LHS.get()->getObjectKind() == OK_BitField || | |||
6285 | RHS.get()->getObjectKind() == OK_BitField) | |||
6286 | OK = OK_BitField; | |||
6287 | ||||
6288 | // If we have function pointer types, unify them anyway to unify their | |||
6289 | // exception specifications, if any. | |||
6290 | if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) { | |||
6291 | Qualifiers Qs = LTy.getQualifiers(); | |||
6292 | LTy = FindCompositePointerType(QuestionLoc, LHS, RHS, | |||
6293 | /*ConvertArgs*/false); | |||
6294 | LTy = Context.getQualifiedType(LTy, Qs); | |||
6295 | ||||
6296 | assert(!LTy.isNull() && "failed to find composite pointer type for "(static_cast <bool> (!LTy.isNull() && "failed to find composite pointer type for " "canonically equivalent function ptr types") ? void (0) : __assert_fail ("!LTy.isNull() && \"failed to find composite pointer type for \" \"canonically equivalent function ptr types\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 6297, __extension__ __PRETTY_FUNCTION__)) | |||
6297 | "canonically equivalent function ptr types")(static_cast <bool> (!LTy.isNull() && "failed to find composite pointer type for " "canonically equivalent function ptr types") ? void (0) : __assert_fail ("!LTy.isNull() && \"failed to find composite pointer type for \" \"canonically equivalent function ptr types\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 6297, __extension__ __PRETTY_FUNCTION__)); | |||
6298 | assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type")(static_cast <bool> (Context.hasSameType(LTy, RTy) && "bad composite pointer type") ? void (0) : __assert_fail ("Context.hasSameType(LTy, RTy) && \"bad composite pointer type\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 6298, __extension__ __PRETTY_FUNCTION__)); | |||
6299 | } | |||
6300 | ||||
6301 | return LTy; | |||
6302 | } | |||
6303 | ||||
6304 | // C++11 [expr.cond]p5 | |||
6305 | // Otherwise, the result is a prvalue. If the second and third operands | |||
6306 | // do not have the same type, and either has (cv) class type, ... | |||
6307 | if (!Same && (LTy->isRecordType() || RTy->isRecordType())) { | |||
6308 | // ... overload resolution is used to determine the conversions (if any) | |||
6309 | // to be applied to the operands. If the overload resolution fails, the | |||
6310 | // program is ill-formed. | |||
6311 | if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc)) | |||
6312 | return QualType(); | |||
6313 | } | |||
6314 | ||||
6315 | // C++11 [expr.cond]p6 | |||
6316 | // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard | |||
6317 | // conversions are performed on the second and third operands. | |||
6318 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | |||
6319 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | |||
6320 | if (LHS.isInvalid() || RHS.isInvalid()) | |||
6321 | return QualType(); | |||
6322 | LTy = LHS.get()->getType(); | |||
6323 | RTy = RHS.get()->getType(); | |||
6324 | ||||
6325 | // After those conversions, one of the following shall hold: | |||
6326 | // -- The second and third operands have the same type; the result | |||
6327 | // is of that type. If the operands have class type, the result | |||
6328 | // is a prvalue temporary of the result type, which is | |||
6329 | // copy-initialized from either the second operand or the third | |||
6330 | // operand depending on the value of the first operand. | |||
6331 | if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) { | |||
6332 | if (LTy->isRecordType()) { | |||
6333 | // The operands have class type. Make a temporary copy. | |||
6334 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy); | |||
6335 | ||||
6336 | ExprResult LHSCopy = PerformCopyInitialization(Entity, | |||
6337 | SourceLocation(), | |||
6338 | LHS); | |||
6339 | if (LHSCopy.isInvalid()) | |||
6340 | return QualType(); | |||
6341 | ||||
6342 | ExprResult RHSCopy = PerformCopyInitialization(Entity, | |||
6343 | SourceLocation(), | |||
6344 | RHS); | |||
6345 | if (RHSCopy.isInvalid()) | |||
6346 | return QualType(); | |||
6347 | ||||
6348 | LHS = LHSCopy; | |||
6349 | RHS = RHSCopy; | |||
6350 | } | |||
6351 | ||||
6352 | // If we have function pointer types, unify them anyway to unify their | |||
6353 | // exception specifications, if any. | |||
6354 | if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) { | |||
6355 | LTy = FindCompositePointerType(QuestionLoc, LHS, RHS); | |||
6356 | assert(!LTy.isNull() && "failed to find composite pointer type for "(static_cast <bool> (!LTy.isNull() && "failed to find composite pointer type for " "canonically equivalent function ptr types") ? void (0) : __assert_fail ("!LTy.isNull() && \"failed to find composite pointer type for \" \"canonically equivalent function ptr types\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 6357, __extension__ __PRETTY_FUNCTION__)) | |||
6357 | "canonically equivalent function ptr types")(static_cast <bool> (!LTy.isNull() && "failed to find composite pointer type for " "canonically equivalent function ptr types") ? void (0) : __assert_fail ("!LTy.isNull() && \"failed to find composite pointer type for \" \"canonically equivalent function ptr types\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 6357, __extension__ __PRETTY_FUNCTION__)); | |||
6358 | } | |||
6359 | ||||
6360 | return LTy; | |||
6361 | } | |||
6362 | ||||
6363 | // Extension: conditional operator involving vector types. | |||
6364 | if (LTy->isVectorType() || RTy->isVectorType()) | |||
6365 | return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, | |||
6366 | /*AllowBothBool*/true, | |||
6367 | /*AllowBoolConversions*/false); | |||
6368 | ||||
6369 | // -- The second and third operands have arithmetic or enumeration type; | |||
6370 | // the usual arithmetic conversions are performed to bring them to a | |||
6371 | // common type, and the result is of that type. | |||
6372 | if (LTy->isArithmeticType() && RTy->isArithmeticType()) { | |||
6373 | QualType ResTy = | |||
6374 | UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); | |||
6375 | if (LHS.isInvalid() || RHS.isInvalid()) | |||
6376 | return QualType(); | |||
6377 | if (ResTy.isNull()) { | |||
6378 | Diag(QuestionLoc, | |||
6379 | diag::err_typecheck_cond_incompatible_operands) << LTy << RTy | |||
6380 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
6381 | return QualType(); | |||
6382 | } | |||
6383 | ||||
6384 | LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); | |||
6385 | RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); | |||
6386 | ||||
6387 | return ResTy; | |||
6388 | } | |||
6389 | ||||
6390 | // -- The second and third operands have pointer type, or one has pointer | |||
6391 | // type and the other is a null pointer constant, or both are null | |||
6392 | // pointer constants, at least one of which is non-integral; pointer | |||
6393 | // conversions and qualification conversions are performed to bring them | |||
6394 | // to their composite pointer type. The result is of the composite | |||
6395 | // pointer type. | |||
6396 | // -- The second and third operands have pointer to member type, or one has | |||
6397 | // pointer to member type and the other is a null pointer constant; | |||
6398 | // pointer to member conversions and qualification conversions are | |||
6399 | // performed to bring them to a common type, whose cv-qualification | |||
6400 | // shall match the cv-qualification of either the second or the third | |||
6401 | // operand. The result is of the common type. | |||
6402 | QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS); | |||
6403 | if (!Composite.isNull()) | |||
6404 | return Composite; | |||
6405 | ||||
6406 | // Similarly, attempt to find composite type of two objective-c pointers. | |||
6407 | Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc); | |||
6408 | if (LHS.isInvalid() || RHS.isInvalid()) | |||
6409 | return QualType(); | |||
6410 | if (!Composite.isNull()) | |||
6411 | return Composite; | |||
6412 | ||||
6413 | // Check if we are using a null with a non-pointer type. | |||
6414 | if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) | |||
6415 | return QualType(); | |||
6416 | ||||
6417 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) | |||
6418 | << LHS.get()->getType() << RHS.get()->getType() | |||
6419 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
6420 | return QualType(); | |||
6421 | } | |||
6422 | ||||
6423 | static FunctionProtoType::ExceptionSpecInfo | |||
6424 | mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1, | |||
6425 | FunctionProtoType::ExceptionSpecInfo ESI2, | |||
6426 | SmallVectorImpl<QualType> &ExceptionTypeStorage) { | |||
6427 | ExceptionSpecificationType EST1 = ESI1.Type; | |||
6428 | ExceptionSpecificationType EST2 = ESI2.Type; | |||
6429 | ||||
6430 | // If either of them can throw anything, that is the result. | |||
6431 | if (EST1 == EST_None) return ESI1; | |||
6432 | if (EST2 == EST_None) return ESI2; | |||
6433 | if (EST1 == EST_MSAny) return ESI1; | |||
6434 | if (EST2 == EST_MSAny) return ESI2; | |||
6435 | if (EST1 == EST_NoexceptFalse) return ESI1; | |||
6436 | if (EST2 == EST_NoexceptFalse) return ESI2; | |||
6437 | ||||
6438 | // If either of them is non-throwing, the result is the other. | |||
6439 | if (EST1 == EST_NoThrow) return ESI2; | |||
6440 | if (EST2 == EST_NoThrow) return ESI1; | |||
6441 | if (EST1 == EST_DynamicNone) return ESI2; | |||
6442 | if (EST2 == EST_DynamicNone) return ESI1; | |||
6443 | if (EST1 == EST_BasicNoexcept) return ESI2; | |||
6444 | if (EST2 == EST_BasicNoexcept) return ESI1; | |||
6445 | if (EST1 == EST_NoexceptTrue) return ESI2; | |||
6446 | if (EST2 == EST_NoexceptTrue) return ESI1; | |||
6447 | ||||
6448 | // If we're left with value-dependent computed noexcept expressions, we're | |||
6449 | // stuck. Before C++17, we can just drop the exception specification entirely, | |||
6450 | // since it's not actually part of the canonical type. And this should never | |||
6451 | // happen in C++17, because it would mean we were computing the composite | |||
6452 | // pointer type of dependent types, which should never happen. | |||
6453 | if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) { | |||
6454 | assert(!S.getLangOpts().CPlusPlus17 &&(static_cast <bool> (!S.getLangOpts().CPlusPlus17 && "computing composite pointer type of dependent types") ? void (0) : __assert_fail ("!S.getLangOpts().CPlusPlus17 && \"computing composite pointer type of dependent types\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 6455, __extension__ __PRETTY_FUNCTION__)) | |||
6455 | "computing composite pointer type of dependent types")(static_cast <bool> (!S.getLangOpts().CPlusPlus17 && "computing composite pointer type of dependent types") ? void (0) : __assert_fail ("!S.getLangOpts().CPlusPlus17 && \"computing composite pointer type of dependent types\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 6455, __extension__ __PRETTY_FUNCTION__)); | |||
6456 | return FunctionProtoType::ExceptionSpecInfo(); | |||
6457 | } | |||
6458 | ||||
6459 | // Switch over the possibilities so that people adding new values know to | |||
6460 | // update this function. | |||
6461 | switch (EST1) { | |||
6462 | case EST_None: | |||
6463 | case EST_DynamicNone: | |||
6464 | case EST_MSAny: | |||
6465 | case EST_BasicNoexcept: | |||
6466 | case EST_DependentNoexcept: | |||
6467 | case EST_NoexceptFalse: | |||
6468 | case EST_NoexceptTrue: | |||
6469 | case EST_NoThrow: | |||
6470 | llvm_unreachable("handled above")::llvm::llvm_unreachable_internal("handled above", "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 6470); | |||
6471 | ||||
6472 | case EST_Dynamic: { | |||
6473 | // This is the fun case: both exception specifications are dynamic. Form | |||
6474 | // the union of the two lists. | |||
6475 | assert(EST2 == EST_Dynamic && "other cases should already be handled")(static_cast <bool> (EST2 == EST_Dynamic && "other cases should already be handled" ) ? void (0) : __assert_fail ("EST2 == EST_Dynamic && \"other cases should already be handled\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 6475, __extension__ __PRETTY_FUNCTION__)); | |||
6476 | llvm::SmallPtrSet<QualType, 8> Found; | |||
6477 | for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions}) | |||
6478 | for (QualType E : Exceptions) | |||
6479 | if (Found.insert(S.Context.getCanonicalType(E)).second) | |||
6480 | ExceptionTypeStorage.push_back(E); | |||
6481 | ||||
6482 | FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic); | |||
6483 | Result.Exceptions = ExceptionTypeStorage; | |||
6484 | return Result; | |||
6485 | } | |||
6486 | ||||
6487 | case EST_Unevaluated: | |||
6488 | case EST_Uninstantiated: | |||
6489 | case EST_Unparsed: | |||
6490 | llvm_unreachable("shouldn't see unresolved exception specifications here")::llvm::llvm_unreachable_internal("shouldn't see unresolved exception specifications here" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 6490); | |||
6491 | } | |||
6492 | ||||
6493 | llvm_unreachable("invalid ExceptionSpecificationType")::llvm::llvm_unreachable_internal("invalid ExceptionSpecificationType" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 6493); | |||
6494 | } | |||
6495 | ||||
6496 | /// Find a merged pointer type and convert the two expressions to it. | |||
6497 | /// | |||
6498 | /// This finds the composite pointer type for \p E1 and \p E2 according to | |||
6499 | /// C++2a [expr.type]p3. It converts both expressions to this type and returns | |||
6500 | /// it. It does not emit diagnostics (FIXME: that's not true if \p ConvertArgs | |||
6501 | /// is \c true). | |||
6502 | /// | |||
6503 | /// \param Loc The location of the operator requiring these two expressions to | |||
6504 | /// be converted to the composite pointer type. | |||
6505 | /// | |||
6506 | /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type. | |||
6507 | QualType Sema::FindCompositePointerType(SourceLocation Loc, | |||
6508 | Expr *&E1, Expr *&E2, | |||
6509 | bool ConvertArgs) { | |||
6510 | assert(getLangOpts().CPlusPlus && "This function assumes C++")(static_cast <bool> (getLangOpts().CPlusPlus && "This function assumes C++") ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"This function assumes C++\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 6510, __extension__ __PRETTY_FUNCTION__)); | |||
6511 | ||||
6512 | // C++1z [expr]p14: | |||
6513 | // The composite pointer type of two operands p1 and p2 having types T1 | |||
6514 | // and T2 | |||
6515 | QualType T1 = E1->getType(), T2 = E2->getType(); | |||
6516 | ||||
6517 | // where at least one is a pointer or pointer to member type or | |||
6518 | // std::nullptr_t is: | |||
6519 | bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() || | |||
6520 | T1->isNullPtrType(); | |||
6521 | bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() || | |||
6522 | T2->isNullPtrType(); | |||
6523 | if (!T1IsPointerLike && !T2IsPointerLike) | |||
6524 | return QualType(); | |||
6525 | ||||
6526 | // - if both p1 and p2 are null pointer constants, std::nullptr_t; | |||
6527 | // This can't actually happen, following the standard, but we also use this | |||
6528 | // to implement the end of [expr.conv], which hits this case. | |||
6529 | // | |||
6530 | // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively; | |||
6531 | if (T1IsPointerLike && | |||
6532 | E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { | |||
6533 | if (ConvertArgs) | |||
6534 | E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType() | |||
6535 | ? CK_NullToMemberPointer | |||
6536 | : CK_NullToPointer).get(); | |||
6537 | return T1; | |||
6538 | } | |||
6539 | if (T2IsPointerLike && | |||
6540 | E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { | |||
6541 | if (ConvertArgs) | |||
6542 | E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType() | |||
6543 | ? CK_NullToMemberPointer | |||
6544 | : CK_NullToPointer).get(); | |||
6545 | return T2; | |||
6546 | } | |||
6547 | ||||
6548 | // Now both have to be pointers or member pointers. | |||
6549 | if (!T1IsPointerLike || !T2IsPointerLike) | |||
6550 | return QualType(); | |||
6551 | assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&(static_cast <bool> (!T1->isNullPtrType() && !T2->isNullPtrType() && "nullptr_t should be a null pointer constant" ) ? void (0) : __assert_fail ("!T1->isNullPtrType() && !T2->isNullPtrType() && \"nullptr_t should be a null pointer constant\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 6552, __extension__ __PRETTY_FUNCTION__)) | |||
6552 | "nullptr_t should be a null pointer constant")(static_cast <bool> (!T1->isNullPtrType() && !T2->isNullPtrType() && "nullptr_t should be a null pointer constant" ) ? void (0) : __assert_fail ("!T1->isNullPtrType() && !T2->isNullPtrType() && \"nullptr_t should be a null pointer constant\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 6552, __extension__ __PRETTY_FUNCTION__)); | |||
6553 | ||||
6554 | struct Step { | |||
6555 | enum Kind { Pointer, ObjCPointer, MemberPointer, Array } K; | |||
6556 | // Qualifiers to apply under the step kind. | |||
6557 | Qualifiers Quals; | |||
6558 | /// The class for a pointer-to-member; a constant array type with a bound | |||
6559 | /// (if any) for an array. | |||
6560 | const Type *ClassOrBound; | |||
6561 | ||||
6562 | Step(Kind K, const Type *ClassOrBound = nullptr) | |||
6563 | : K(K), Quals(), ClassOrBound(ClassOrBound) {} | |||
6564 | QualType rebuild(ASTContext &Ctx, QualType T) const { | |||
6565 | T = Ctx.getQualifiedType(T, Quals); | |||
6566 | switch (K) { | |||
6567 | case Pointer: | |||
6568 | return Ctx.getPointerType(T); | |||
6569 | case MemberPointer: | |||
6570 | return Ctx.getMemberPointerType(T, ClassOrBound); | |||
6571 | case ObjCPointer: | |||
6572 | return Ctx.getObjCObjectPointerType(T); | |||
6573 | case Array: | |||
6574 | if (auto *CAT = cast_or_null<ConstantArrayType>(ClassOrBound)) | |||
6575 | return Ctx.getConstantArrayType(T, CAT->getSize(), nullptr, | |||
6576 | ArrayType::Normal, 0); | |||
6577 | else | |||
6578 | return Ctx.getIncompleteArrayType(T, ArrayType::Normal, 0); | |||
6579 | } | |||
6580 | llvm_unreachable("unknown step kind")::llvm::llvm_unreachable_internal("unknown step kind", "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 6580); | |||
6581 | } | |||
6582 | }; | |||
6583 | ||||
6584 | SmallVector<Step, 8> Steps; | |||
6585 | ||||
6586 | // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1 | |||
6587 | // is reference-related to C2 or C2 is reference-related to C1 (8.6.3), | |||
6588 | // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1, | |||
6589 | // respectively; | |||
6590 | // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer | |||
6591 | // to member of C2 of type cv2 U2" for some non-function type U, where | |||
6592 | // C1 is reference-related to C2 or C2 is reference-related to C1, the | |||
6593 | // cv-combined type of T2 and T1 or the cv-combined type of T1 and T2, | |||
6594 | // respectively; | |||
6595 | // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and | |||
6596 | // T2; | |||
6597 | // | |||
6598 | // Dismantle T1 and T2 to simultaneously determine whether they are similar | |||
6599 | // and to prepare to form the cv-combined type if so. | |||
6600 | QualType Composite1 = T1; | |||
6601 | QualType Composite2 = T2; | |||
6602 | unsigned NeedConstBefore = 0; | |||
6603 | while (true) { | |||
6604 | assert(!Composite1.isNull() && !Composite2.isNull())(static_cast <bool> (!Composite1.isNull() && !Composite2 .isNull()) ? void (0) : __assert_fail ("!Composite1.isNull() && !Composite2.isNull()" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 6604, __extension__ __PRETTY_FUNCTION__)); | |||
6605 | ||||
6606 | Qualifiers Q1, Q2; | |||
6607 | Composite1 = Context.getUnqualifiedArrayType(Composite1, Q1); | |||
6608 | Composite2 = Context.getUnqualifiedArrayType(Composite2, Q2); | |||
6609 | ||||
6610 | // Top-level qualifiers are ignored. Merge at all lower levels. | |||
6611 | if (!Steps.empty()) { | |||
6612 | // Find the qualifier union: (approximately) the unique minimal set of | |||
6613 | // qualifiers that is compatible with both types. | |||
6614 | Qualifiers Quals = Qualifiers::fromCVRUMask(Q1.getCVRUQualifiers() | | |||
6615 | Q2.getCVRUQualifiers()); | |||
6616 | ||||
6617 | // Under one level of pointer or pointer-to-member, we can change to an | |||
6618 | // unambiguous compatible address space. | |||
6619 | if (Q1.getAddressSpace() == Q2.getAddressSpace()) { | |||
6620 | Quals.setAddressSpace(Q1.getAddressSpace()); | |||
6621 | } else if (Steps.size() == 1) { | |||
6622 | bool MaybeQ1 = Q1.isAddressSpaceSupersetOf(Q2); | |||
6623 | bool MaybeQ2 = Q2.isAddressSpaceSupersetOf(Q1); | |||
6624 | if (MaybeQ1 == MaybeQ2) | |||
6625 | return QualType(); // No unique best address space. | |||
6626 | Quals.setAddressSpace(MaybeQ1 ? Q1.getAddressSpace() | |||
6627 | : Q2.getAddressSpace()); | |||
6628 | } else { | |||
6629 | return QualType(); | |||
6630 | } | |||
6631 | ||||
6632 | // FIXME: In C, we merge __strong and none to __strong at the top level. | |||
6633 | if (Q1.getObjCGCAttr() == Q2.getObjCGCAttr()) | |||
6634 | Quals.setObjCGCAttr(Q1.getObjCGCAttr()); | |||
6635 | else if (T1->isVoidPointerType() || T2->isVoidPointerType()) | |||
6636 | assert(Steps.size() == 1)(static_cast <bool> (Steps.size() == 1) ? void (0) : __assert_fail ("Steps.size() == 1", "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 6636, __extension__ __PRETTY_FUNCTION__)); | |||
6637 | else | |||
6638 | return QualType(); | |||
6639 | ||||
6640 | // Mismatched lifetime qualifiers never compatibly include each other. | |||
6641 | if (Q1.getObjCLifetime() == Q2.getObjCLifetime()) | |||
6642 | Quals.setObjCLifetime(Q1.getObjCLifetime()); | |||
6643 | else if (T1->isVoidPointerType() || T2->isVoidPointerType()) | |||
6644 | assert(Steps.size() == 1)(static_cast <bool> (Steps.size() == 1) ? void (0) : __assert_fail ("Steps.size() == 1", "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 6644, __extension__ __PRETTY_FUNCTION__)); | |||
6645 | else | |||
6646 | return QualType(); | |||
6647 | ||||
6648 | Steps.back().Quals = Quals; | |||
6649 | if (Q1 != Quals || Q2 != Quals) | |||
6650 | NeedConstBefore = Steps.size() - 1; | |||
6651 | } | |||
6652 | ||||
6653 | // FIXME: Can we unify the following with UnwrapSimilarTypes? | |||
6654 | const PointerType *Ptr1, *Ptr2; | |||
6655 | if ((Ptr1 = Composite1->getAs<PointerType>()) && | |||
6656 | (Ptr2 = Composite2->getAs<PointerType>())) { | |||
6657 | Composite1 = Ptr1->getPointeeType(); | |||
6658 | Composite2 = Ptr2->getPointeeType(); | |||
6659 | Steps.emplace_back(Step::Pointer); | |||
6660 | continue; | |||
6661 | } | |||
6662 | ||||
6663 | const ObjCObjectPointerType *ObjPtr1, *ObjPtr2; | |||
6664 | if ((ObjPtr1 = Composite1->getAs<ObjCObjectPointerType>()) && | |||
6665 | (ObjPtr2 = Composite2->getAs<ObjCObjectPointerType>())) { | |||
6666 | Composite1 = ObjPtr1->getPointeeType(); | |||
6667 | Composite2 = ObjPtr2->getPointeeType(); | |||
6668 | Steps.emplace_back(Step::ObjCPointer); | |||
6669 | continue; | |||
6670 | } | |||
6671 | ||||
6672 | const MemberPointerType *MemPtr1, *MemPtr2; | |||
6673 | if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) && | |||
6674 | (MemPtr2 = Composite2->getAs<MemberPointerType>())) { | |||
6675 | Composite1 = MemPtr1->getPointeeType(); | |||
6676 | Composite2 = MemPtr2->getPointeeType(); | |||
6677 | ||||
6678 | // At the top level, we can perform a base-to-derived pointer-to-member | |||
6679 | // conversion: | |||
6680 | // | |||
6681 | // - [...] where C1 is reference-related to C2 or C2 is | |||
6682 | // reference-related to C1 | |||
6683 | // | |||
6684 | // (Note that the only kinds of reference-relatedness in scope here are | |||
6685 | // "same type or derived from".) At any other level, the class must | |||
6686 | // exactly match. | |||
6687 | const Type *Class = nullptr; | |||
6688 | QualType Cls1(MemPtr1->getClass(), 0); | |||
6689 | QualType Cls2(MemPtr2->getClass(), 0); | |||
6690 | if (Context.hasSameType(Cls1, Cls2)) | |||
6691 | Class = MemPtr1->getClass(); | |||
6692 | else if (Steps.empty()) | |||
6693 | Class = IsDerivedFrom(Loc, Cls1, Cls2) ? MemPtr1->getClass() : | |||
6694 | IsDerivedFrom(Loc, Cls2, Cls1) ? MemPtr2->getClass() : nullptr; | |||
6695 | if (!Class) | |||
6696 | return QualType(); | |||
6697 | ||||
6698 | Steps.emplace_back(Step::MemberPointer, Class); | |||
6699 | continue; | |||
6700 | } | |||
6701 | ||||
6702 | // Special case: at the top level, we can decompose an Objective-C pointer | |||
6703 | // and a 'cv void *'. Unify the qualifiers. | |||
6704 | if (Steps.empty() && ((Composite1->isVoidPointerType() && | |||
6705 | Composite2->isObjCObjectPointerType()) || | |||
6706 | (Composite1->isObjCObjectPointerType() && | |||
6707 | Composite2->isVoidPointerType()))) { | |||
6708 | Composite1 = Composite1->getPointeeType(); | |||
6709 | Composite2 = Composite2->getPointeeType(); | |||
6710 | Steps.emplace_back(Step::Pointer); | |||
6711 | continue; | |||
6712 | } | |||
6713 | ||||
6714 | // FIXME: arrays | |||
6715 | ||||
6716 | // FIXME: block pointer types? | |||
6717 | ||||
6718 | // Cannot unwrap any more types. | |||
6719 | break; | |||
6720 | } | |||
6721 | ||||
6722 | // - if T1 or T2 is "pointer to noexcept function" and the other type is | |||
6723 | // "pointer to function", where the function types are otherwise the same, | |||
6724 | // "pointer to function"; | |||
6725 | // - if T1 or T2 is "pointer to member of C1 of type function", the other | |||
6726 | // type is "pointer to member of C2 of type noexcept function", and C1 | |||
6727 | // is reference-related to C2 or C2 is reference-related to C1, where | |||
6728 | // the function types are otherwise the same, "pointer to member of C2 of | |||
6729 | // type function" or "pointer to member of C1 of type function", | |||
6730 | // respectively; | |||
6731 | // | |||
6732 | // We also support 'noreturn' here, so as a Clang extension we generalize the | |||
6733 | // above to: | |||
6734 | // | |||
6735 | // - [Clang] If T1 and T2 are both of type "pointer to function" or | |||
6736 | // "pointer to member function" and the pointee types can be unified | |||
6737 | // by a function pointer conversion, that conversion is applied | |||
6738 | // before checking the following rules. | |||
6739 | // | |||
6740 | // We've already unwrapped down to the function types, and we want to merge | |||
6741 | // rather than just convert, so do this ourselves rather than calling | |||
6742 | // IsFunctionConversion. | |||
6743 | // | |||
6744 | // FIXME: In order to match the standard wording as closely as possible, we | |||
6745 | // currently only do this under a single level of pointers. Ideally, we would | |||
6746 | // allow this in general, and set NeedConstBefore to the relevant depth on | |||
6747 | // the side(s) where we changed anything. If we permit that, we should also | |||
6748 | // consider this conversion when determining type similarity and model it as | |||
6749 | // a qualification conversion. | |||
6750 | if (Steps.size() == 1) { | |||
6751 | if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) { | |||
6752 | if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) { | |||
6753 | FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo(); | |||
6754 | FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo(); | |||
6755 | ||||
6756 | // The result is noreturn if both operands are. | |||
6757 | bool Noreturn = | |||
6758 | EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn(); | |||
6759 | EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn); | |||
6760 | EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn); | |||
6761 | ||||
6762 | // The result is nothrow if both operands are. | |||
6763 | SmallVector<QualType, 8> ExceptionTypeStorage; | |||
6764 | EPI1.ExceptionSpec = EPI2.ExceptionSpec = | |||
6765 | mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec, | |||
6766 | ExceptionTypeStorage); | |||
6767 | ||||
6768 | Composite1 = Context.getFunctionType(FPT1->getReturnType(), | |||
6769 | FPT1->getParamTypes(), EPI1); | |||
6770 | Composite2 = Context.getFunctionType(FPT2->getReturnType(), | |||
6771 | FPT2->getParamTypes(), EPI2); | |||
6772 | } | |||
6773 | } | |||
6774 | } | |||
6775 | ||||
6776 | // There are some more conversions we can perform under exactly one pointer. | |||
6777 | if (Steps.size() == 1 && Steps.front().K == Step::Pointer && | |||
6778 | !Context.hasSameType(Composite1, Composite2)) { | |||
6779 | // - if T1 or T2 is "pointer to cv1 void" and the other type is | |||
6780 | // "pointer to cv2 T", where T is an object type or void, | |||
6781 | // "pointer to cv12 void", where cv12 is the union of cv1 and cv2; | |||
6782 | if (Composite1->isVoidType() && Composite2->isObjectType()) | |||
6783 | Composite2 = Composite1; | |||
6784 | else if (Composite2->isVoidType() && Composite1->isObjectType()) | |||
6785 | Composite1 = Composite2; | |||
6786 | // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1 | |||
6787 | // is reference-related to C2 or C2 is reference-related to C1 (8.6.3), | |||
6788 | // the cv-combined type of T1 and T2 or the cv-combined type of T2 and | |||
6789 | // T1, respectively; | |||
6790 | // | |||
6791 | // The "similar type" handling covers all of this except for the "T1 is a | |||
6792 | // base class of T2" case in the definition of reference-related. | |||
6793 | else if (IsDerivedFrom(Loc, Composite1, Composite2)) | |||
6794 | Composite1 = Composite2; | |||
6795 | else if (IsDerivedFrom(Loc, Composite2, Composite1)) | |||
6796 | Composite2 = Composite1; | |||
6797 | } | |||
6798 | ||||
6799 | // At this point, either the inner types are the same or we have failed to | |||
6800 | // find a composite pointer type. | |||
6801 | if (!Context.hasSameType(Composite1, Composite2)) | |||
6802 | return QualType(); | |||
6803 | ||||
6804 | // Per C++ [conv.qual]p3, add 'const' to every level before the last | |||
6805 | // differing qualifier. | |||
6806 | for (unsigned I = 0; I != NeedConstBefore; ++I) | |||
6807 | Steps[I].Quals.addConst(); | |||
6808 | ||||
6809 | // Rebuild the composite type. | |||
6810 | QualType Composite = Composite1; | |||
6811 | for (auto &S : llvm::reverse(Steps)) | |||
6812 | Composite = S.rebuild(Context, Composite); | |||
6813 | ||||
6814 | if (ConvertArgs) { | |||
6815 | // Convert the expressions to the composite pointer type. | |||
6816 | InitializedEntity Entity = | |||
6817 | InitializedEntity::InitializeTemporary(Composite); | |||
6818 | InitializationKind Kind = | |||
6819 | InitializationKind::CreateCopy(Loc, SourceLocation()); | |||
6820 | ||||
6821 | InitializationSequence E1ToC(*this, Entity, Kind, E1); | |||
6822 | if (!E1ToC) | |||
6823 | return QualType(); | |||
6824 | ||||
6825 | InitializationSequence E2ToC(*this, Entity, Kind, E2); | |||
6826 | if (!E2ToC) | |||
6827 | return QualType(); | |||
6828 | ||||
6829 | // FIXME: Let the caller know if these fail to avoid duplicate diagnostics. | |||
6830 | ExprResult E1Result = E1ToC.Perform(*this, Entity, Kind, E1); | |||
6831 | if (E1Result.isInvalid()) | |||
6832 | return QualType(); | |||
6833 | E1 = E1Result.get(); | |||
6834 | ||||
6835 | ExprResult E2Result = E2ToC.Perform(*this, Entity, Kind, E2); | |||
6836 | if (E2Result.isInvalid()) | |||
6837 | return QualType(); | |||
6838 | E2 = E2Result.get(); | |||
6839 | } | |||
6840 | ||||
6841 | return Composite; | |||
6842 | } | |||
6843 | ||||
6844 | ExprResult Sema::MaybeBindToTemporary(Expr *E) { | |||
6845 | if (!E) | |||
6846 | return ExprError(); | |||
6847 | ||||
6848 | assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?")(static_cast <bool> (!isa<CXXBindTemporaryExpr>(E ) && "Double-bound temporary?") ? void (0) : __assert_fail ("!isa<CXXBindTemporaryExpr>(E) && \"Double-bound temporary?\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 6848, __extension__ __PRETTY_FUNCTION__)); | |||
6849 | ||||
6850 | // If the result is a glvalue, we shouldn't bind it. | |||
6851 | if (!E->isRValue()) | |||
6852 | return E; | |||
6853 | ||||
6854 | // In ARC, calls that return a retainable type can return retained, | |||
6855 | // in which case we have to insert a consuming cast. | |||
6856 | if (getLangOpts().ObjCAutoRefCount && | |||
6857 | E->getType()->isObjCRetainableType()) { | |||
6858 | ||||
6859 | bool ReturnsRetained; | |||
6860 | ||||
6861 | // For actual calls, we compute this by examining the type of the | |||
6862 | // called value. | |||
6863 | if (CallExpr *Call = dyn_cast<CallExpr>(E)) { | |||
6864 | Expr *Callee = Call->getCallee()->IgnoreParens(); | |||
6865 | QualType T = Callee->getType(); | |||
6866 | ||||
6867 | if (T == Context.BoundMemberTy) { | |||
6868 | // Handle pointer-to-members. | |||
6869 | if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee)) | |||
6870 | T = BinOp->getRHS()->getType(); | |||
6871 | else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee)) | |||
6872 | T = Mem->getMemberDecl()->getType(); | |||
6873 | } | |||
6874 | ||||
6875 | if (const PointerType *Ptr = T->getAs<PointerType>()) | |||
6876 | T = Ptr->getPointeeType(); | |||
6877 | else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>()) | |||
6878 | T = Ptr->getPointeeType(); | |||
6879 | else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>()) | |||
6880 | T = MemPtr->getPointeeType(); | |||
6881 | ||||
6882 | auto *FTy = T->castAs<FunctionType>(); | |||
6883 | ReturnsRetained = FTy->getExtInfo().getProducesResult(); | |||
6884 | ||||
6885 | // ActOnStmtExpr arranges things so that StmtExprs of retainable | |||
6886 | // type always produce a +1 object. | |||
6887 | } else if (isa<StmtExpr>(E)) { | |||
6888 | ReturnsRetained = true; | |||
6889 | ||||
6890 | // We hit this case with the lambda conversion-to-block optimization; | |||
6891 | // we don't want any extra casts here. | |||
6892 | } else if (isa<CastExpr>(E) && | |||
6893 | isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) { | |||
6894 | return E; | |||
6895 | ||||
6896 | // For message sends and property references, we try to find an | |||
6897 | // actual method. FIXME: we should infer retention by selector in | |||
6898 | // cases where we don't have an actual method. | |||
6899 | } else { | |||
6900 | ObjCMethodDecl *D = nullptr; | |||
6901 | if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) { | |||
6902 | D = Send->getMethodDecl(); | |||
6903 | } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) { | |||
6904 | D = BoxedExpr->getBoxingMethod(); | |||
6905 | } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) { | |||
6906 | // Don't do reclaims if we're using the zero-element array | |||
6907 | // constant. | |||
6908 | if (ArrayLit->getNumElements() == 0 && | |||
6909 | Context.getLangOpts().ObjCRuntime.hasEmptyCollections()) | |||
6910 | return E; | |||
6911 | ||||
6912 | D = ArrayLit->getArrayWithObjectsMethod(); | |||
6913 | } else if (ObjCDictionaryLiteral *DictLit | |||
6914 | = dyn_cast<ObjCDictionaryLiteral>(E)) { | |||
6915 | // Don't do reclaims if we're using the zero-element dictionary | |||
6916 | // constant. | |||
6917 | if (DictLit->getNumElements() == 0 && | |||
6918 | Context.getLangOpts().ObjCRuntime.hasEmptyCollections()) | |||
6919 | return E; | |||
6920 | ||||
6921 | D = DictLit->getDictWithObjectsMethod(); | |||
6922 | } | |||
6923 | ||||
6924 | ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>()); | |||
6925 | ||||
6926 | // Don't do reclaims on performSelector calls; despite their | |||
6927 | // return type, the invoked method doesn't necessarily actually | |||
6928 | // return an object. | |||
6929 | if (!ReturnsRetained && | |||
6930 | D && D->getMethodFamily() == OMF_performSelector) | |||
6931 | return E; | |||
6932 | } | |||
6933 | ||||
6934 | // Don't reclaim an object of Class type. | |||
6935 | if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType()) | |||
6936 | return E; | |||
6937 | ||||
6938 | Cleanup.setExprNeedsCleanups(true); | |||
6939 | ||||
6940 | CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject | |||
6941 | : CK_ARCReclaimReturnedObject); | |||
6942 | return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr, | |||
6943 | VK_RValue, FPOptionsOverride()); | |||
6944 | } | |||
6945 | ||||
6946 | if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) | |||
6947 | Cleanup.setExprNeedsCleanups(true); | |||
6948 | ||||
6949 | if (!getLangOpts().CPlusPlus) | |||
6950 | return E; | |||
6951 | ||||
6952 | // Search for the base element type (cf. ASTContext::getBaseElementType) with | |||
6953 | // a fast path for the common case that the type is directly a RecordType. | |||
6954 | const Type *T = Context.getCanonicalType(E->getType().getTypePtr()); | |||
6955 | const RecordType *RT = nullptr; | |||
6956 | while (!RT) { | |||
6957 | switch (T->getTypeClass()) { | |||
6958 | case Type::Record: | |||
6959 | RT = cast<RecordType>(T); | |||
6960 | break; | |||
6961 | case Type::ConstantArray: | |||
6962 | case Type::IncompleteArray: | |||
6963 | case Type::VariableArray: | |||
6964 | case Type::DependentSizedArray: | |||
6965 | T = cast<ArrayType>(T)->getElementType().getTypePtr(); | |||
6966 | break; | |||
6967 | default: | |||
6968 | return E; | |||
6969 | } | |||
6970 | } | |||
6971 | ||||
6972 | // That should be enough to guarantee that this type is complete, if we're | |||
6973 | // not processing a decltype expression. | |||
6974 | CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); | |||
6975 | if (RD->isInvalidDecl() || RD->isDependentContext()) | |||
6976 | return E; | |||
6977 | ||||
6978 | bool IsDecltype = ExprEvalContexts.back().ExprContext == | |||
6979 | ExpressionEvaluationContextRecord::EK_Decltype; | |||
6980 | CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD); | |||
6981 | ||||
6982 | if (Destructor) { | |||
6983 | MarkFunctionReferenced(E->getExprLoc(), Destructor); | |||
6984 | CheckDestructorAccess(E->getExprLoc(), Destructor, | |||
6985 | PDiag(diag::err_access_dtor_temp) | |||
6986 | << E->getType()); | |||
6987 | if (DiagnoseUseOfDecl(Destructor, E->getExprLoc())) | |||
6988 | return ExprError(); | |||
6989 | ||||
6990 | // If destructor is trivial, we can avoid the extra copy. | |||
6991 | if (Destructor->isTrivial()) | |||
6992 | return E; | |||
6993 | ||||
6994 | // We need a cleanup, but we don't need to remember the temporary. | |||
6995 | Cleanup.setExprNeedsCleanups(true); | |||
6996 | } | |||
6997 | ||||
6998 | CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor); | |||
6999 | CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E); | |||
7000 | ||||
7001 | if (IsDecltype) | |||
7002 | ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind); | |||
7003 | ||||
7004 | return Bind; | |||
7005 | } | |||
7006 | ||||
7007 | ExprResult | |||
7008 | Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) { | |||
7009 | if (SubExpr.isInvalid()) | |||
7010 | return ExprError(); | |||
7011 | ||||
7012 | return MaybeCreateExprWithCleanups(SubExpr.get()); | |||
7013 | } | |||
7014 | ||||
7015 | Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) { | |||
7016 | assert(SubExpr && "subexpression can't be null!")(static_cast <bool> (SubExpr && "subexpression can't be null!" ) ? void (0) : __assert_fail ("SubExpr && \"subexpression can't be null!\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 7016, __extension__ __PRETTY_FUNCTION__)); | |||
7017 | ||||
7018 | CleanupVarDeclMarking(); | |||
7019 | ||||
7020 | unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects; | |||
7021 | assert(ExprCleanupObjects.size() >= FirstCleanup)(static_cast <bool> (ExprCleanupObjects.size() >= FirstCleanup ) ? void (0) : __assert_fail ("ExprCleanupObjects.size() >= FirstCleanup" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 7021, __extension__ __PRETTY_FUNCTION__)); | |||
7022 | assert(Cleanup.exprNeedsCleanups() ||(static_cast <bool> (Cleanup.exprNeedsCleanups() || ExprCleanupObjects .size() == FirstCleanup) ? void (0) : __assert_fail ("Cleanup.exprNeedsCleanups() || ExprCleanupObjects.size() == FirstCleanup" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 7023, __extension__ __PRETTY_FUNCTION__)) | |||
7023 | ExprCleanupObjects.size() == FirstCleanup)(static_cast <bool> (Cleanup.exprNeedsCleanups() || ExprCleanupObjects .size() == FirstCleanup) ? void (0) : __assert_fail ("Cleanup.exprNeedsCleanups() || ExprCleanupObjects.size() == FirstCleanup" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 7023, __extension__ __PRETTY_FUNCTION__)); | |||
7024 | if (!Cleanup.exprNeedsCleanups()) | |||
7025 | return SubExpr; | |||
7026 | ||||
7027 | auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup, | |||
7028 | ExprCleanupObjects.size() - FirstCleanup); | |||
7029 | ||||
7030 | auto *E = ExprWithCleanups::Create( | |||
7031 | Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups); | |||
7032 | DiscardCleanupsInEvaluationContext(); | |||
7033 | ||||
7034 | return E; | |||
7035 | } | |||
7036 | ||||
7037 | Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) { | |||
7038 | assert(SubStmt && "sub-statement can't be null!")(static_cast <bool> (SubStmt && "sub-statement can't be null!" ) ? void (0) : __assert_fail ("SubStmt && \"sub-statement can't be null!\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 7038, __extension__ __PRETTY_FUNCTION__)); | |||
7039 | ||||
7040 | CleanupVarDeclMarking(); | |||
7041 | ||||
7042 | if (!Cleanup.exprNeedsCleanups()) | |||
7043 | return SubStmt; | |||
7044 | ||||
7045 | // FIXME: In order to attach the temporaries, wrap the statement into | |||
7046 | // a StmtExpr; currently this is only used for asm statements. | |||
7047 | // This is hacky, either create a new CXXStmtWithTemporaries statement or | |||
7048 | // a new AsmStmtWithTemporaries. | |||
7049 | CompoundStmt *CompStmt = CompoundStmt::Create( | |||
7050 | Context, SubStmt, SourceLocation(), SourceLocation()); | |||
7051 | Expr *E = new (Context) | |||
7052 | StmtExpr(CompStmt, Context.VoidTy, SourceLocation(), SourceLocation(), | |||
7053 | /*FIXME TemplateDepth=*/0); | |||
7054 | return MaybeCreateExprWithCleanups(E); | |||
7055 | } | |||
7056 | ||||
7057 | /// Process the expression contained within a decltype. For such expressions, | |||
7058 | /// certain semantic checks on temporaries are delayed until this point, and | |||
7059 | /// are omitted for the 'topmost' call in the decltype expression. If the | |||
7060 | /// topmost call bound a temporary, strip that temporary off the expression. | |||
7061 | ExprResult Sema::ActOnDecltypeExpression(Expr *E) { | |||
7062 | assert(ExprEvalContexts.back().ExprContext ==(static_cast <bool> (ExprEvalContexts.back().ExprContext == ExpressionEvaluationContextRecord::EK_Decltype && "not in a decltype expression") ? void (0) : __assert_fail ( "ExprEvalContexts.back().ExprContext == ExpressionEvaluationContextRecord::EK_Decltype && \"not in a decltype expression\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 7064, __extension__ __PRETTY_FUNCTION__)) | |||
7063 | ExpressionEvaluationContextRecord::EK_Decltype &&(static_cast <bool> (ExprEvalContexts.back().ExprContext == ExpressionEvaluationContextRecord::EK_Decltype && "not in a decltype expression") ? void (0) : __assert_fail ( "ExprEvalContexts.back().ExprContext == ExpressionEvaluationContextRecord::EK_Decltype && \"not in a decltype expression\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 7064, __extension__ __PRETTY_FUNCTION__)) | |||
7064 | "not in a decltype expression")(static_cast <bool> (ExprEvalContexts.back().ExprContext == ExpressionEvaluationContextRecord::EK_Decltype && "not in a decltype expression") ? void (0) : __assert_fail ( "ExprEvalContexts.back().ExprContext == ExpressionEvaluationContextRecord::EK_Decltype && \"not in a decltype expression\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 7064, __extension__ __PRETTY_FUNCTION__)); | |||
7065 | ||||
7066 | ExprResult Result = CheckPlaceholderExpr(E); | |||
7067 | if (Result.isInvalid()) | |||
7068 | return ExprError(); | |||
7069 | E = Result.get(); | |||
7070 | ||||
7071 | // C++11 [expr.call]p11: | |||
7072 | // If a function call is a prvalue of object type, | |||
7073 | // -- if the function call is either | |||
7074 | // -- the operand of a decltype-specifier, or | |||
7075 | // -- the right operand of a comma operator that is the operand of a | |||
7076 | // decltype-specifier, | |||
7077 | // a temporary object is not introduced for the prvalue. | |||
7078 | ||||
7079 | // Recursively rebuild ParenExprs and comma expressions to strip out the | |||
7080 | // outermost CXXBindTemporaryExpr, if any. | |||
7081 | if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { | |||
7082 | ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr()); | |||
7083 | if (SubExpr.isInvalid()) | |||
7084 | return ExprError(); | |||
7085 | if (SubExpr.get() == PE->getSubExpr()) | |||
7086 | return E; | |||
7087 | return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get()); | |||
7088 | } | |||
7089 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { | |||
7090 | if (BO->getOpcode() == BO_Comma) { | |||
7091 | ExprResult RHS = ActOnDecltypeExpression(BO->getRHS()); | |||
7092 | if (RHS.isInvalid()) | |||
7093 | return ExprError(); | |||
7094 | if (RHS.get() == BO->getRHS()) | |||
7095 | return E; | |||
7096 | return BinaryOperator::Create(Context, BO->getLHS(), RHS.get(), BO_Comma, | |||
7097 | BO->getType(), BO->getValueKind(), | |||
7098 | BO->getObjectKind(), BO->getOperatorLoc(), | |||
7099 | BO->getFPFeatures(getLangOpts())); | |||
7100 | } | |||
7101 | } | |||
7102 | ||||
7103 | CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E); | |||
7104 | CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr()) | |||
7105 | : nullptr; | |||
7106 | if (TopCall) | |||
7107 | E = TopCall; | |||
7108 | else | |||
7109 | TopBind = nullptr; | |||
7110 | ||||
7111 | // Disable the special decltype handling now. | |||
7112 | ExprEvalContexts.back().ExprContext = | |||
7113 | ExpressionEvaluationContextRecord::EK_Other; | |||
7114 | ||||
7115 | Result = CheckUnevaluatedOperand(E); | |||
7116 | if (Result.isInvalid()) | |||
7117 | return ExprError(); | |||
7118 | E = Result.get(); | |||
7119 | ||||
7120 | // In MS mode, don't perform any extra checking of call return types within a | |||
7121 | // decltype expression. | |||
7122 | if (getLangOpts().MSVCCompat) | |||
7123 | return E; | |||
7124 | ||||
7125 | // Perform the semantic checks we delayed until this point. | |||
7126 | for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size(); | |||
7127 | I != N; ++I) { | |||
7128 | CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I]; | |||
7129 | if (Call == TopCall) | |||
7130 | continue; | |||
7131 | ||||
7132 | if (CheckCallReturnType(Call->getCallReturnType(Context), | |||
7133 | Call->getBeginLoc(), Call, Call->getDirectCallee())) | |||
7134 | return ExprError(); | |||
7135 | } | |||
7136 | ||||
7137 | // Now all relevant types are complete, check the destructors are accessible | |||
7138 | // and non-deleted, and annotate them on the temporaries. | |||
7139 | for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size(); | |||
7140 | I != N; ++I) { | |||
7141 | CXXBindTemporaryExpr *Bind = | |||
7142 | ExprEvalContexts.back().DelayedDecltypeBinds[I]; | |||
7143 | if (Bind == TopBind) | |||
7144 | continue; | |||
7145 | ||||
7146 | CXXTemporary *Temp = Bind->getTemporary(); | |||
7147 | ||||
7148 | CXXRecordDecl *RD = | |||
7149 | Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); | |||
7150 | CXXDestructorDecl *Destructor = LookupDestructor(RD); | |||
7151 | Temp->setDestructor(Destructor); | |||
7152 | ||||
7153 | MarkFunctionReferenced(Bind->getExprLoc(), Destructor); | |||
7154 | CheckDestructorAccess(Bind->getExprLoc(), Destructor, | |||
7155 | PDiag(diag::err_access_dtor_temp) | |||
7156 | << Bind->getType()); | |||
7157 | if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc())) | |||
7158 | return ExprError(); | |||
7159 | ||||
7160 | // We need a cleanup, but we don't need to remember the temporary. | |||
7161 | Cleanup.setExprNeedsCleanups(true); | |||
7162 | } | |||
7163 | ||||
7164 | // Possibly strip off the top CXXBindTemporaryExpr. | |||
7165 | return E; | |||
7166 | } | |||
7167 | ||||
7168 | /// Note a set of 'operator->' functions that were used for a member access. | |||
7169 | static void noteOperatorArrows(Sema &S, | |||
7170 | ArrayRef<FunctionDecl *> OperatorArrows) { | |||
7171 | unsigned SkipStart = OperatorArrows.size(), SkipCount = 0; | |||
7172 | // FIXME: Make this configurable? | |||
7173 | unsigned Limit = 9; | |||
7174 | if (OperatorArrows.size() > Limit) { | |||
7175 | // Produce Limit-1 normal notes and one 'skipping' note. | |||
7176 | SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2; | |||
7177 | SkipCount = OperatorArrows.size() - (Limit - 1); | |||
7178 | } | |||
7179 | ||||
7180 | for (unsigned I = 0; I < OperatorArrows.size(); /**/) { | |||
7181 | if (I == SkipStart) { | |||
7182 | S.Diag(OperatorArrows[I]->getLocation(), | |||
7183 | diag::note_operator_arrows_suppressed) | |||
7184 | << SkipCount; | |||
7185 | I += SkipCount; | |||
7186 | } else { | |||
7187 | S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here) | |||
7188 | << OperatorArrows[I]->getCallResultType(); | |||
7189 | ++I; | |||
7190 | } | |||
7191 | } | |||
7192 | } | |||
7193 | ||||
7194 | ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, | |||
7195 | SourceLocation OpLoc, | |||
7196 | tok::TokenKind OpKind, | |||
7197 | ParsedType &ObjectType, | |||
7198 | bool &MayBePseudoDestructor) { | |||
7199 | // Since this might be a postfix expression, get rid of ParenListExprs. | |||
7200 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); | |||
7201 | if (Result.isInvalid()) return ExprError(); | |||
7202 | Base = Result.get(); | |||
7203 | ||||
7204 | Result = CheckPlaceholderExpr(Base); | |||
7205 | if (Result.isInvalid()) return ExprError(); | |||
7206 | Base = Result.get(); | |||
7207 | ||||
7208 | QualType BaseType = Base->getType(); | |||
7209 | MayBePseudoDestructor = false; | |||
7210 | if (BaseType->isDependentType()) { | |||
7211 | // If we have a pointer to a dependent type and are using the -> operator, | |||
7212 | // the object type is the type that the pointer points to. We might still | |||
7213 | // have enough information about that type to do something useful. | |||
7214 | if (OpKind == tok::arrow) | |||
7215 | if (const PointerType *Ptr = BaseType->getAs<PointerType>()) | |||
7216 | BaseType = Ptr->getPointeeType(); | |||
7217 | ||||
7218 | ObjectType = ParsedType::make(BaseType); | |||
7219 | MayBePseudoDestructor = true; | |||
7220 | return Base; | |||
7221 | } | |||
7222 | ||||
7223 | // C++ [over.match.oper]p8: | |||
7224 | // [...] When operator->returns, the operator-> is applied to the value | |||
7225 | // returned, with the original second operand. | |||
7226 | if (OpKind == tok::arrow) { | |||
7227 | QualType StartingType = BaseType; | |||
7228 | bool NoArrowOperatorFound = false; | |||
7229 | bool FirstIteration = true; | |||
7230 | FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext); | |||
7231 | // The set of types we've considered so far. | |||
7232 | llvm::SmallPtrSet<CanQualType,8> CTypes; | |||
7233 | SmallVector<FunctionDecl*, 8> OperatorArrows; | |||
7234 | CTypes.insert(Context.getCanonicalType(BaseType)); | |||
7235 | ||||
7236 | while (BaseType->isRecordType()) { | |||
7237 | if (OperatorArrows.size() >= getLangOpts().ArrowDepth) { | |||
7238 | Diag(OpLoc, diag::err_operator_arrow_depth_exceeded) | |||
7239 | << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange(); | |||
7240 | noteOperatorArrows(*this, OperatorArrows); | |||
7241 | Diag(OpLoc, diag::note_operator_arrow_depth) | |||
7242 | << getLangOpts().ArrowDepth; | |||
7243 | return ExprError(); | |||
7244 | } | |||
7245 | ||||
7246 | Result = BuildOverloadedArrowExpr( | |||
7247 | S, Base, OpLoc, | |||
7248 | // When in a template specialization and on the first loop iteration, | |||
7249 | // potentially give the default diagnostic (with the fixit in a | |||
7250 | // separate note) instead of having the error reported back to here | |||
7251 | // and giving a diagnostic with a fixit attached to the error itself. | |||
7252 | (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization()) | |||
7253 | ? nullptr | |||
7254 | : &NoArrowOperatorFound); | |||
7255 | if (Result.isInvalid()) { | |||
7256 | if (NoArrowOperatorFound) { | |||
7257 | if (FirstIteration) { | |||
7258 | Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) | |||
7259 | << BaseType << 1 << Base->getSourceRange() | |||
7260 | << FixItHint::CreateReplacement(OpLoc, "."); | |||
7261 | OpKind = tok::period; | |||
7262 | break; | |||
7263 | } | |||
7264 | Diag(OpLoc, diag::err_typecheck_member_reference_arrow) | |||
7265 | << BaseType << Base->getSourceRange(); | |||
7266 | CallExpr *CE = dyn_cast<CallExpr>(Base); | |||
7267 | if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) { | |||
7268 | Diag(CD->getBeginLoc(), | |||
7269 | diag::note_member_reference_arrow_from_operator_arrow); | |||
7270 | } | |||
7271 | } | |||
7272 | return ExprError(); | |||
7273 | } | |||
7274 | Base = Result.get(); | |||
7275 | if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base)) | |||
7276 | OperatorArrows.push_back(OpCall->getDirectCallee()); | |||
7277 | BaseType = Base->getType(); | |||
7278 | CanQualType CBaseType = Context.getCanonicalType(BaseType); | |||
7279 | if (!CTypes.insert(CBaseType).second) { | |||
7280 | Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType; | |||
7281 | noteOperatorArrows(*this, OperatorArrows); | |||
7282 | return ExprError(); | |||
7283 | } | |||
7284 | FirstIteration = false; | |||
7285 | } | |||
7286 | ||||
7287 | if (OpKind == tok::arrow) { | |||
7288 | if (BaseType->isPointerType()) | |||
7289 | BaseType = BaseType->getPointeeType(); | |||
7290 | else if (auto *AT = Context.getAsArrayType(BaseType)) | |||
7291 | BaseType = AT->getElementType(); | |||
7292 | } | |||
7293 | } | |||
7294 | ||||
7295 | // Objective-C properties allow "." access on Objective-C pointer types, | |||
7296 | // so adjust the base type to the object type itself. | |||
7297 | if (BaseType->isObjCObjectPointerType()) | |||
7298 | BaseType = BaseType->getPointeeType(); | |||
7299 | ||||
7300 | // C++ [basic.lookup.classref]p2: | |||
7301 | // [...] If the type of the object expression is of pointer to scalar | |||
7302 | // type, the unqualified-id is looked up in the context of the complete | |||
7303 | // postfix-expression. | |||
7304 | // | |||
7305 | // This also indicates that we could be parsing a pseudo-destructor-name. | |||
7306 | // Note that Objective-C class and object types can be pseudo-destructor | |||
7307 | // expressions or normal member (ivar or property) access expressions, and | |||
7308 | // it's legal for the type to be incomplete if this is a pseudo-destructor | |||
7309 | // call. We'll do more incomplete-type checks later in the lookup process, | |||
7310 | // so just skip this check for ObjC types. | |||
7311 | if (!BaseType->isRecordType()) { | |||
7312 | ObjectType = ParsedType::make(BaseType); | |||
7313 | MayBePseudoDestructor = true; | |||
7314 | return Base; | |||
7315 | } | |||
7316 | ||||
7317 | // The object type must be complete (or dependent), or | |||
7318 | // C++11 [expr.prim.general]p3: | |||
7319 | // Unlike the object expression in other contexts, *this is not required to | |||
7320 | // be of complete type for purposes of class member access (5.2.5) outside | |||
7321 | // the member function body. | |||
7322 | if (!BaseType->isDependentType() && | |||
7323 | !isThisOutsideMemberFunctionBody(BaseType) && | |||
7324 | RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access)) | |||
7325 | return ExprError(); | |||
7326 | ||||
7327 | // C++ [basic.lookup.classref]p2: | |||
7328 | // If the id-expression in a class member access (5.2.5) is an | |||
7329 | // unqualified-id, and the type of the object expression is of a class | |||
7330 | // type C (or of pointer to a class type C), the unqualified-id is looked | |||
7331 | // up in the scope of class C. [...] | |||
7332 | ObjectType = ParsedType::make(BaseType); | |||
7333 | return Base; | |||
7334 | } | |||
7335 | ||||
7336 | static bool CheckArrow(Sema &S, QualType &ObjectType, Expr *&Base, | |||
7337 | tok::TokenKind &OpKind, SourceLocation OpLoc) { | |||
7338 | if (Base->hasPlaceholderType()) { | |||
7339 | ExprResult result = S.CheckPlaceholderExpr(Base); | |||
7340 | if (result.isInvalid()) return true; | |||
7341 | Base = result.get(); | |||
7342 | } | |||
7343 | ObjectType = Base->getType(); | |||
7344 | ||||
7345 | // C++ [expr.pseudo]p2: | |||
7346 | // The left-hand side of the dot operator shall be of scalar type. The | |||
7347 | // left-hand side of the arrow operator shall be of pointer to scalar type. | |||
7348 | // This scalar type is the object type. | |||
7349 | // Note that this is rather different from the normal handling for the | |||
7350 | // arrow operator. | |||
7351 | if (OpKind == tok::arrow) { | |||
7352 | // The operator requires a prvalue, so perform lvalue conversions. | |||
7353 | // Only do this if we might plausibly end with a pointer, as otherwise | |||
7354 | // this was likely to be intended to be a '.'. | |||
7355 | if (ObjectType->isPointerType() || ObjectType->isArrayType() || | |||
7356 | ObjectType->isFunctionType()) { | |||
7357 | ExprResult BaseResult = S.DefaultFunctionArrayLvalueConversion(Base); | |||
7358 | if (BaseResult.isInvalid()) | |||
7359 | return true; | |||
7360 | Base = BaseResult.get(); | |||
7361 | ObjectType = Base->getType(); | |||
7362 | } | |||
7363 | ||||
7364 | if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) { | |||
7365 | ObjectType = Ptr->getPointeeType(); | |||
7366 | } else if (!Base->isTypeDependent()) { | |||
7367 | // The user wrote "p->" when they probably meant "p."; fix it. | |||
7368 | S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) | |||
7369 | << ObjectType << true | |||
7370 | << FixItHint::CreateReplacement(OpLoc, "."); | |||
7371 | if (S.isSFINAEContext()) | |||
7372 | return true; | |||
7373 | ||||
7374 | OpKind = tok::period; | |||
7375 | } | |||
7376 | } | |||
7377 | ||||
7378 | return false; | |||
7379 | } | |||
7380 | ||||
7381 | /// Check if it's ok to try and recover dot pseudo destructor calls on | |||
7382 | /// pointer objects. | |||
7383 | static bool | |||
7384 | canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef, | |||
7385 | QualType DestructedType) { | |||
7386 | // If this is a record type, check if its destructor is callable. | |||
7387 | if (auto *RD = DestructedType->getAsCXXRecordDecl()) { | |||
7388 | if (RD->hasDefinition()) | |||
7389 | if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD)) | |||
7390 | return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false); | |||
7391 | return false; | |||
7392 | } | |||
7393 | ||||
7394 | // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor. | |||
7395 | return DestructedType->isDependentType() || DestructedType->isScalarType() || | |||
7396 | DestructedType->isVectorType(); | |||
7397 | } | |||
7398 | ||||
7399 | ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base, | |||
7400 | SourceLocation OpLoc, | |||
7401 | tok::TokenKind OpKind, | |||
7402 | const CXXScopeSpec &SS, | |||
7403 | TypeSourceInfo *ScopeTypeInfo, | |||
7404 | SourceLocation CCLoc, | |||
7405 | SourceLocation TildeLoc, | |||
7406 | PseudoDestructorTypeStorage Destructed) { | |||
7407 | TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo(); | |||
7408 | ||||
7409 | QualType ObjectType; | |||
7410 | if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) | |||
7411 | return ExprError(); | |||
7412 | ||||
7413 | if (!ObjectType->isDependentType() && !ObjectType->isScalarType() && | |||
7414 | !ObjectType->isVectorType()) { | |||
7415 | if (getLangOpts().MSVCCompat && ObjectType->isVoidType()) | |||
7416 | Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange(); | |||
7417 | else { | |||
7418 | Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar) | |||
7419 | << ObjectType << Base->getSourceRange(); | |||
7420 | return ExprError(); | |||
7421 | } | |||
7422 | } | |||
7423 | ||||
7424 | // C++ [expr.pseudo]p2: | |||
7425 | // [...] The cv-unqualified versions of the object type and of the type | |||
7426 | // designated by the pseudo-destructor-name shall be the same type. | |||
7427 | if (DestructedTypeInfo) { | |||
7428 | QualType DestructedType = DestructedTypeInfo->getType(); | |||
7429 | SourceLocation DestructedTypeStart | |||
7430 | = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(); | |||
7431 | if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) { | |||
7432 | if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) { | |||
7433 | // Detect dot pseudo destructor calls on pointer objects, e.g.: | |||
7434 | // Foo *foo; | |||
7435 | // foo.~Foo(); | |||
7436 | if (OpKind == tok::period && ObjectType->isPointerType() && | |||
7437 | Context.hasSameUnqualifiedType(DestructedType, | |||
7438 | ObjectType->getPointeeType())) { | |||
7439 | auto Diagnostic = | |||
7440 | Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) | |||
7441 | << ObjectType << /*IsArrow=*/0 << Base->getSourceRange(); | |||
7442 | ||||
7443 | // Issue a fixit only when the destructor is valid. | |||
7444 | if (canRecoverDotPseudoDestructorCallsOnPointerObjects( | |||
7445 | *this, DestructedType)) | |||
7446 | Diagnostic << FixItHint::CreateReplacement(OpLoc, "->"); | |||
7447 | ||||
7448 | // Recover by setting the object type to the destructed type and the | |||
7449 | // operator to '->'. | |||
7450 | ObjectType = DestructedType; | |||
7451 | OpKind = tok::arrow; | |||
7452 | } else { | |||
7453 | Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch) | |||
7454 | << ObjectType << DestructedType << Base->getSourceRange() | |||
7455 | << DestructedTypeInfo->getTypeLoc().getLocalSourceRange(); | |||
7456 | ||||
7457 | // Recover by setting the destructed type to the object type. | |||
7458 | DestructedType = ObjectType; | |||
7459 | DestructedTypeInfo = | |||
7460 | Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart); | |||
7461 | Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); | |||
7462 | } | |||
7463 | } else if (DestructedType.getObjCLifetime() != | |||
7464 | ObjectType.getObjCLifetime()) { | |||
7465 | ||||
7466 | if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) { | |||
7467 | // Okay: just pretend that the user provided the correctly-qualified | |||
7468 | // type. | |||
7469 | } else { | |||
7470 | Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals) | |||
7471 | << ObjectType << DestructedType << Base->getSourceRange() | |||
7472 | << DestructedTypeInfo->getTypeLoc().getLocalSourceRange(); | |||
7473 | } | |||
7474 | ||||
7475 | // Recover by setting the destructed type to the object type. | |||
7476 | DestructedType = ObjectType; | |||
7477 | DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType, | |||
7478 | DestructedTypeStart); | |||
7479 | Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); | |||
7480 | } | |||
7481 | } | |||
7482 | } | |||
7483 | ||||
7484 | // C++ [expr.pseudo]p2: | |||
7485 | // [...] Furthermore, the two type-names in a pseudo-destructor-name of the | |||
7486 | // form | |||
7487 | // | |||
7488 | // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name | |||
7489 | // | |||
7490 | // shall designate the same scalar type. | |||
7491 | if (ScopeTypeInfo) { | |||
7492 | QualType ScopeType = ScopeTypeInfo->getType(); | |||
7493 | if (!ScopeType->isDependentType() && !ObjectType->isDependentType() && | |||
7494 | !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) { | |||
7495 | ||||
7496 | Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(), | |||
7497 | diag::err_pseudo_dtor_type_mismatch) | |||
7498 | << ObjectType << ScopeType << Base->getSourceRange() | |||
7499 | << ScopeTypeInfo->getTypeLoc().getLocalSourceRange(); | |||
7500 | ||||
7501 | ScopeType = QualType(); | |||
7502 | ScopeTypeInfo = nullptr; | |||
7503 | } | |||
7504 | } | |||
7505 | ||||
7506 | Expr *Result | |||
7507 | = new (Context) CXXPseudoDestructorExpr(Context, Base, | |||
7508 | OpKind == tok::arrow, OpLoc, | |||
7509 | SS.getWithLocInContext(Context), | |||
7510 | ScopeTypeInfo, | |||
7511 | CCLoc, | |||
7512 | TildeLoc, | |||
7513 | Destructed); | |||
7514 | ||||
7515 | return Result; | |||
7516 | } | |||
7517 | ||||
7518 | ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, | |||
7519 | SourceLocation OpLoc, | |||
7520 | tok::TokenKind OpKind, | |||
7521 | CXXScopeSpec &SS, | |||
7522 | UnqualifiedId &FirstTypeName, | |||
7523 | SourceLocation CCLoc, | |||
7524 | SourceLocation TildeLoc, | |||
7525 | UnqualifiedId &SecondTypeName) { | |||
7526 | assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||(static_cast <bool> ((FirstTypeName.getKind() == UnqualifiedIdKind ::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedIdKind ::IK_Identifier) && "Invalid first type name in pseudo-destructor" ) ? void (0) : __assert_fail ("(FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid first type name in pseudo-destructor\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 7528, __extension__ __PRETTY_FUNCTION__)) | |||
7527 | FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&(static_cast <bool> ((FirstTypeName.getKind() == UnqualifiedIdKind ::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedIdKind ::IK_Identifier) && "Invalid first type name in pseudo-destructor" ) ? void (0) : __assert_fail ("(FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid first type name in pseudo-destructor\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 7528, __extension__ __PRETTY_FUNCTION__)) | |||
7528 | "Invalid first type name in pseudo-destructor")(static_cast <bool> ((FirstTypeName.getKind() == UnqualifiedIdKind ::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedIdKind ::IK_Identifier) && "Invalid first type name in pseudo-destructor" ) ? void (0) : __assert_fail ("(FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid first type name in pseudo-destructor\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 7528, __extension__ __PRETTY_FUNCTION__)); | |||
7529 | assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||(static_cast <bool> ((SecondTypeName.getKind() == UnqualifiedIdKind ::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedIdKind ::IK_Identifier) && "Invalid second type name in pseudo-destructor" ) ? void (0) : __assert_fail ("(SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid second type name in pseudo-destructor\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 7531, __extension__ __PRETTY_FUNCTION__)) | |||
7530 | SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&(static_cast <bool> ((SecondTypeName.getKind() == UnqualifiedIdKind ::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedIdKind ::IK_Identifier) && "Invalid second type name in pseudo-destructor" ) ? void (0) : __assert_fail ("(SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid second type name in pseudo-destructor\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 7531, __extension__ __PRETTY_FUNCTION__)) | |||
7531 | "Invalid second type name in pseudo-destructor")(static_cast <bool> ((SecondTypeName.getKind() == UnqualifiedIdKind ::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedIdKind ::IK_Identifier) && "Invalid second type name in pseudo-destructor" ) ? void (0) : __assert_fail ("(SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid second type name in pseudo-destructor\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 7531, __extension__ __PRETTY_FUNCTION__)); | |||
7532 | ||||
7533 | QualType ObjectType; | |||
7534 | if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) | |||
7535 | return ExprError(); | |||
7536 | ||||
7537 | // Compute the object type that we should use for name lookup purposes. Only | |||
7538 | // record types and dependent types matter. | |||
7539 | ParsedType ObjectTypePtrForLookup; | |||
7540 | if (!SS.isSet()) { | |||
7541 | if (ObjectType->isRecordType()) | |||
7542 | ObjectTypePtrForLookup = ParsedType::make(ObjectType); | |||
7543 | else if (ObjectType->isDependentType()) | |||
7544 | ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy); | |||
7545 | } | |||
7546 | ||||
7547 | // Convert the name of the type being destructed (following the ~) into a | |||
7548 | // type (with source-location information). | |||
7549 | QualType DestructedType; | |||
7550 | TypeSourceInfo *DestructedTypeInfo = nullptr; | |||
7551 | PseudoDestructorTypeStorage Destructed; | |||
7552 | if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) { | |||
7553 | ParsedType T = getTypeName(*SecondTypeName.Identifier, | |||
7554 | SecondTypeName.StartLocation, | |||
7555 | S, &SS, true, false, ObjectTypePtrForLookup, | |||
7556 | /*IsCtorOrDtorName*/true); | |||
7557 | if (!T && | |||
7558 | ((SS.isSet() && !computeDeclContext(SS, false)) || | |||
7559 | (!SS.isSet() && ObjectType->isDependentType()))) { | |||
7560 | // The name of the type being destroyed is a dependent name, and we | |||
7561 | // couldn't find anything useful in scope. Just store the identifier and | |||
7562 | // it's location, and we'll perform (qualified) name lookup again at | |||
7563 | // template instantiation time. | |||
7564 | Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier, | |||
7565 | SecondTypeName.StartLocation); | |||
7566 | } else if (!T) { | |||
7567 | Diag(SecondTypeName.StartLocation, | |||
7568 | diag::err_pseudo_dtor_destructor_non_type) | |||
7569 | << SecondTypeName.Identifier << ObjectType; | |||
7570 | if (isSFINAEContext()) | |||
7571 | return ExprError(); | |||
7572 | ||||
7573 | // Recover by assuming we had the right type all along. | |||
7574 | DestructedType = ObjectType; | |||
7575 | } else | |||
7576 | DestructedType = GetTypeFromParser(T, &DestructedTypeInfo); | |||
7577 | } else { | |||
7578 | // Resolve the template-id to a type. | |||
7579 | TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId; | |||
7580 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), | |||
7581 | TemplateId->NumArgs); | |||
7582 | TypeResult T = ActOnTemplateIdType(S, | |||
7583 | SS, | |||
7584 | TemplateId->TemplateKWLoc, | |||
7585 | TemplateId->Template, | |||
7586 | TemplateId->Name, | |||
7587 | TemplateId->TemplateNameLoc, | |||
7588 | TemplateId->LAngleLoc, | |||
7589 | TemplateArgsPtr, | |||
7590 | TemplateId->RAngleLoc, | |||
7591 | /*IsCtorOrDtorName*/true); | |||
7592 | if (T.isInvalid() || !T.get()) { | |||
7593 | // Recover by assuming we had the right type all along. | |||
7594 | DestructedType = ObjectType; | |||
7595 | } else | |||
7596 | DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo); | |||
7597 | } | |||
7598 | ||||
7599 | // If we've performed some kind of recovery, (re-)build the type source | |||
7600 | // information. | |||
7601 | if (!DestructedType.isNull()) { | |||
7602 | if (!DestructedTypeInfo) | |||
7603 | DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType, | |||
7604 | SecondTypeName.StartLocation); | |||
7605 | Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); | |||
7606 | } | |||
7607 | ||||
7608 | // Convert the name of the scope type (the type prior to '::') into a type. | |||
7609 | TypeSourceInfo *ScopeTypeInfo = nullptr; | |||
7610 | QualType ScopeType; | |||
7611 | if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || | |||
7612 | FirstTypeName.Identifier) { | |||
7613 | if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) { | |||
7614 | ParsedType T = getTypeName(*FirstTypeName.Identifier, | |||
7615 | FirstTypeName.StartLocation, | |||
7616 | S, &SS, true, false, ObjectTypePtrForLookup, | |||
7617 | /*IsCtorOrDtorName*/true); | |||
7618 | if (!T) { | |||
7619 | Diag(FirstTypeName.StartLocation, | |||
7620 | diag::err_pseudo_dtor_destructor_non_type) | |||
7621 | << FirstTypeName.Identifier << ObjectType; | |||
7622 | ||||
7623 | if (isSFINAEContext()) | |||
7624 | return ExprError(); | |||
7625 | ||||
7626 | // Just drop this type. It's unnecessary anyway. | |||
7627 | ScopeType = QualType(); | |||
7628 | } else | |||
7629 | ScopeType = GetTypeFromParser(T, &ScopeTypeInfo); | |||
7630 | } else { | |||
7631 | // Resolve the template-id to a type. | |||
7632 | TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId; | |||
7633 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), | |||
7634 | TemplateId->NumArgs); | |||
7635 | TypeResult T = ActOnTemplateIdType(S, | |||
7636 | SS, | |||
7637 | TemplateId->TemplateKWLoc, | |||
7638 | TemplateId->Template, | |||
7639 | TemplateId->Name, | |||
7640 | TemplateId->TemplateNameLoc, | |||
7641 | TemplateId->LAngleLoc, | |||
7642 | TemplateArgsPtr, | |||
7643 | TemplateId->RAngleLoc, | |||
7644 | /*IsCtorOrDtorName*/true); | |||
7645 | if (T.isInvalid() || !T.get()) { | |||
7646 | // Recover by dropping this type. | |||
7647 | ScopeType = QualType(); | |||
7648 | } else | |||
7649 | ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo); | |||
7650 | } | |||
7651 | } | |||
7652 | ||||
7653 | if (!ScopeType.isNull() && !ScopeTypeInfo) | |||
7654 | ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType, | |||
7655 | FirstTypeName.StartLocation); | |||
7656 | ||||
7657 | ||||
7658 | return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS, | |||
7659 | ScopeTypeInfo, CCLoc, TildeLoc, | |||
7660 | Destructed); | |||
7661 | } | |||
7662 | ||||
7663 | ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, | |||
7664 | SourceLocation OpLoc, | |||
7665 | tok::TokenKind OpKind, | |||
7666 | SourceLocation TildeLoc, | |||
7667 | const DeclSpec& DS) { | |||
7668 | QualType ObjectType; | |||
7669 | if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) | |||
7670 | return ExprError(); | |||
7671 | ||||
7672 | if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) { | |||
7673 | Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); | |||
7674 | return true; | |||
7675 | } | |||
7676 | ||||
7677 | QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(), | |||
7678 | false); | |||
7679 | ||||
7680 | TypeLocBuilder TLB; | |||
7681 | DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T); | |||
7682 | DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc()); | |||
7683 | TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T); | |||
7684 | PseudoDestructorTypeStorage Destructed(DestructedTypeInfo); | |||
7685 | ||||
7686 | return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(), | |||
7687 | nullptr, SourceLocation(), TildeLoc, | |||
7688 | Destructed); | |||
7689 | } | |||
7690 | ||||
7691 | ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl, | |||
7692 | CXXConversionDecl *Method, | |||
7693 | bool HadMultipleCandidates) { | |||
7694 | // Convert the expression to match the conversion function's implicit object | |||
7695 | // parameter. | |||
7696 | ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr, | |||
7697 | FoundDecl, Method); | |||
7698 | if (Exp.isInvalid()) | |||
7699 | return true; | |||
7700 | ||||
7701 | if (Method->getParent()->isLambda() && | |||
7702 | Method->getConversionType()->isBlockPointerType()) { | |||
7703 | // This is a lambda conversion to block pointer; check if the argument | |||
7704 | // was a LambdaExpr. | |||
7705 | Expr *SubE = E; | |||
7706 | CastExpr *CE = dyn_cast<CastExpr>(SubE); | |||
7707 | if (CE && CE->getCastKind() == CK_NoOp) | |||
7708 | SubE = CE->getSubExpr(); | |||
7709 | SubE = SubE->IgnoreParens(); | |||
7710 | if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE)) | |||
7711 | SubE = BE->getSubExpr(); | |||
7712 | if (isa<LambdaExpr>(SubE)) { | |||
7713 | // For the conversion to block pointer on a lambda expression, we | |||
7714 | // construct a special BlockLiteral instead; this doesn't really make | |||
7715 | // a difference in ARC, but outside of ARC the resulting block literal | |||
7716 | // follows the normal lifetime rules for block literals instead of being | |||
7717 | // autoreleased. | |||
7718 | PushExpressionEvaluationContext( | |||
7719 | ExpressionEvaluationContext::PotentiallyEvaluated); | |||
7720 | ExprResult BlockExp = BuildBlockForLambdaConversion( | |||
7721 | Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get()); | |||
7722 | PopExpressionEvaluationContext(); | |||
7723 | ||||
7724 | // FIXME: This note should be produced by a CodeSynthesisContext. | |||
7725 | if (BlockExp.isInvalid()) | |||
7726 | Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv); | |||
7727 | return BlockExp; | |||
7728 | } | |||
7729 | } | |||
7730 | ||||
7731 | MemberExpr *ME = | |||
7732 | BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(), | |||
7733 | NestedNameSpecifierLoc(), SourceLocation(), Method, | |||
7734 | DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), | |||
7735 | HadMultipleCandidates, DeclarationNameInfo(), | |||
7736 | Context.BoundMemberTy, VK_RValue, OK_Ordinary); | |||
7737 | ||||
7738 | QualType ResultType = Method->getReturnType(); | |||
7739 | ExprValueKind VK = Expr::getValueKindForType(ResultType); | |||
7740 | ResultType = ResultType.getNonLValueExprType(Context); | |||
7741 | ||||
7742 | CXXMemberCallExpr *CE = CXXMemberCallExpr::Create( | |||
7743 | Context, ME, /*Args=*/{}, ResultType, VK, Exp.get()->getEndLoc(), | |||
7744 | CurFPFeatureOverrides()); | |||
7745 | ||||
7746 | if (CheckFunctionCall(Method, CE, | |||
7747 | Method->getType()->castAs<FunctionProtoType>())) | |||
7748 | return ExprError(); | |||
7749 | ||||
7750 | return CE; | |||
7751 | } | |||
7752 | ||||
7753 | ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, | |||
7754 | SourceLocation RParen) { | |||
7755 | // If the operand is an unresolved lookup expression, the expression is ill- | |||
7756 | // formed per [over.over]p1, because overloaded function names cannot be used | |||
7757 | // without arguments except in explicit contexts. | |||
7758 | ExprResult R = CheckPlaceholderExpr(Operand); | |||
7759 | if (R.isInvalid()) | |||
7760 | return R; | |||
7761 | ||||
7762 | R = CheckUnevaluatedOperand(R.get()); | |||
7763 | if (R.isInvalid()) | |||
7764 | return ExprError(); | |||
7765 | ||||
7766 | Operand = R.get(); | |||
7767 | ||||
7768 | if (!inTemplateInstantiation() && !Operand->isInstantiationDependent() && | |||
7769 | Operand->HasSideEffects(Context, false)) { | |||
7770 | // The expression operand for noexcept is in an unevaluated expression | |||
7771 | // context, so side effects could result in unintended consequences. | |||
7772 | Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context); | |||
7773 | } | |||
7774 | ||||
7775 | CanThrowResult CanThrow = canThrow(Operand); | |||
7776 | return new (Context) | |||
7777 | CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen); | |||
7778 | } | |||
7779 | ||||
7780 | ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation, | |||
7781 | Expr *Operand, SourceLocation RParen) { | |||
7782 | return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen); | |||
7783 | } | |||
7784 | ||||
7785 | /// Perform the conversions required for an expression used in a | |||
7786 | /// context that ignores the result. | |||
7787 | ExprResult Sema::IgnoredValueConversions(Expr *E) { | |||
7788 | if (E->hasPlaceholderType()) { | |||
7789 | ExprResult result = CheckPlaceholderExpr(E); | |||
7790 | if (result.isInvalid()) return E; | |||
7791 | E = result.get(); | |||
7792 | } | |||
7793 | ||||
7794 | // C99 6.3.2.1: | |||
7795 | // [Except in specific positions,] an lvalue that does not have | |||
7796 | // array type is converted to the value stored in the | |||
7797 | // designated object (and is no longer an lvalue). | |||
7798 | if (E->isRValue()) { | |||
7799 | // In C, function designators (i.e. expressions of function type) | |||
7800 | // are r-values, but we still want to do function-to-pointer decay | |||
7801 | // on them. This is both technically correct and convenient for | |||
7802 | // some clients. | |||
7803 | if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType()) | |||
7804 | return DefaultFunctionArrayConversion(E); | |||
7805 | ||||
7806 | return E; | |||
7807 | } | |||
7808 | ||||
7809 | if (getLangOpts().CPlusPlus) { | |||
7810 | // The C++11 standard defines the notion of a discarded-value expression; | |||
7811 | // normally, we don't need to do anything to handle it, but if it is a | |||
7812 | // volatile lvalue with a special form, we perform an lvalue-to-rvalue | |||
7813 | // conversion. | |||
7814 | if (getLangOpts().CPlusPlus11 && E->isReadIfDiscardedInCPlusPlus11()) { | |||
7815 | ExprResult Res = DefaultLvalueConversion(E); | |||
7816 | if (Res.isInvalid()) | |||
7817 | return E; | |||
7818 | E = Res.get(); | |||
7819 | } else { | |||
7820 | // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if | |||
7821 | // it occurs as a discarded-value expression. | |||
7822 | CheckUnusedVolatileAssignment(E); | |||
7823 | } | |||
7824 | ||||
7825 | // C++1z: | |||
7826 | // If the expression is a prvalue after this optional conversion, the | |||
7827 | // temporary materialization conversion is applied. | |||
7828 | // | |||
7829 | // We skip this step: IR generation is able to synthesize the storage for | |||
7830 | // itself in the aggregate case, and adding the extra node to the AST is | |||
7831 | // just clutter. | |||
7832 | // FIXME: We don't emit lifetime markers for the temporaries due to this. | |||
7833 | // FIXME: Do any other AST consumers care about this? | |||
7834 | return E; | |||
7835 | } | |||
7836 | ||||
7837 | // GCC seems to also exclude expressions of incomplete enum type. | |||
7838 | if (const EnumType *T = E->getType()->getAs<EnumType>()) { | |||
7839 | if (!T->getDecl()->isComplete()) { | |||
7840 | // FIXME: stupid workaround for a codegen bug! | |||
7841 | E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get(); | |||
7842 | return E; | |||
7843 | } | |||
7844 | } | |||
7845 | ||||
7846 | ExprResult Res = DefaultFunctionArrayLvalueConversion(E); | |||
7847 | if (Res.isInvalid()) | |||
7848 | return E; | |||
7849 | E = Res.get(); | |||
7850 | ||||
7851 | if (!E->getType()->isVoidType()) | |||
7852 | RequireCompleteType(E->getExprLoc(), E->getType(), | |||
7853 | diag::err_incomplete_type); | |||
7854 | return E; | |||
7855 | } | |||
7856 | ||||
7857 | ExprResult Sema::CheckUnevaluatedOperand(Expr *E) { | |||
7858 | // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if | |||
7859 | // it occurs as an unevaluated operand. | |||
7860 | CheckUnusedVolatileAssignment(E); | |||
7861 | ||||
7862 | return E; | |||
7863 | } | |||
7864 | ||||
7865 | // If we can unambiguously determine whether Var can never be used | |||
7866 | // in a constant expression, return true. | |||
7867 | // - if the variable and its initializer are non-dependent, then | |||
7868 | // we can unambiguously check if the variable is a constant expression. | |||
7869 | // - if the initializer is not value dependent - we can determine whether | |||
7870 | // it can be used to initialize a constant expression. If Init can not | |||
7871 | // be used to initialize a constant expression we conclude that Var can | |||
7872 | // never be a constant expression. | |||
7873 | // - FXIME: if the initializer is dependent, we can still do some analysis and | |||
7874 | // identify certain cases unambiguously as non-const by using a Visitor: | |||
7875 | // - such as those that involve odr-use of a ParmVarDecl, involve a new | |||
7876 | // delete, lambda-expr, dynamic-cast, reinterpret-cast etc... | |||
7877 | static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var, | |||
7878 | ASTContext &Context) { | |||
7879 | if (isa<ParmVarDecl>(Var)) return true; | |||
7880 | const VarDecl *DefVD = nullptr; | |||
7881 | ||||
7882 | // If there is no initializer - this can not be a constant expression. | |||
7883 | if (!Var->getAnyInitializer(DefVD)) return true; | |||
7884 | assert(DefVD)(static_cast <bool> (DefVD) ? void (0) : __assert_fail ( "DefVD", "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 7884, __extension__ __PRETTY_FUNCTION__)); | |||
7885 | if (DefVD->isWeak()) return false; | |||
7886 | EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); | |||
7887 | ||||
7888 | Expr *Init = cast<Expr>(Eval->Value); | |||
7889 | ||||
7890 | if (Var->getType()->isDependentType() || Init->isValueDependent()) { | |||
7891 | // FIXME: Teach the constant evaluator to deal with the non-dependent parts | |||
7892 | // of value-dependent expressions, and use it here to determine whether the | |||
7893 | // initializer is a potential constant expression. | |||
7894 | return false; | |||
7895 | } | |||
7896 | ||||
7897 | return !Var->isUsableInConstantExpressions(Context); | |||
7898 | } | |||
7899 | ||||
7900 | /// Check if the current lambda has any potential captures | |||
7901 | /// that must be captured by any of its enclosing lambdas that are ready to | |||
7902 | /// capture. If there is a lambda that can capture a nested | |||
7903 | /// potential-capture, go ahead and do so. Also, check to see if any | |||
7904 | /// variables are uncaptureable or do not involve an odr-use so do not | |||
7905 | /// need to be captured. | |||
7906 | ||||
7907 | static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures( | |||
7908 | Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) { | |||
7909 | ||||
7910 | assert(!S.isUnevaluatedContext())(static_cast <bool> (!S.isUnevaluatedContext()) ? void ( 0) : __assert_fail ("!S.isUnevaluatedContext()", "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 7910, __extension__ __PRETTY_FUNCTION__)); | |||
7911 | assert(S.CurContext->isDependentContext())(static_cast <bool> (S.CurContext->isDependentContext ()) ? void (0) : __assert_fail ("S.CurContext->isDependentContext()" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 7911, __extension__ __PRETTY_FUNCTION__)); | |||
7912 | #ifndef NDEBUG | |||
7913 | DeclContext *DC = S.CurContext; | |||
7914 | while (DC && isa<CapturedDecl>(DC)) | |||
7915 | DC = DC->getParent(); | |||
7916 | assert((static_cast <bool> (CurrentLSI->CallOperator == DC && "The current call operator must be synchronized with Sema's CurContext" ) ? void (0) : __assert_fail ("CurrentLSI->CallOperator == DC && \"The current call operator must be synchronized with Sema's CurContext\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 7918, __extension__ __PRETTY_FUNCTION__)) | |||
7917 | CurrentLSI->CallOperator == DC &&(static_cast <bool> (CurrentLSI->CallOperator == DC && "The current call operator must be synchronized with Sema's CurContext" ) ? void (0) : __assert_fail ("CurrentLSI->CallOperator == DC && \"The current call operator must be synchronized with Sema's CurContext\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 7918, __extension__ __PRETTY_FUNCTION__)) | |||
7918 | "The current call operator must be synchronized with Sema's CurContext")(static_cast <bool> (CurrentLSI->CallOperator == DC && "The current call operator must be synchronized with Sema's CurContext" ) ? void (0) : __assert_fail ("CurrentLSI->CallOperator == DC && \"The current call operator must be synchronized with Sema's CurContext\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 7918, __extension__ __PRETTY_FUNCTION__)); | |||
7919 | #endif // NDEBUG | |||
7920 | ||||
7921 | const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent(); | |||
7922 | ||||
7923 | // All the potentially captureable variables in the current nested | |||
7924 | // lambda (within a generic outer lambda), must be captured by an | |||
7925 | // outer lambda that is enclosed within a non-dependent context. | |||
7926 | CurrentLSI->visitPotentialCaptures([&] (VarDecl *Var, Expr *VarExpr) { | |||
7927 | // If the variable is clearly identified as non-odr-used and the full | |||
7928 | // expression is not instantiation dependent, only then do we not | |||
7929 | // need to check enclosing lambda's for speculative captures. | |||
7930 | // For e.g.: | |||
7931 | // Even though 'x' is not odr-used, it should be captured. | |||
7932 | // int test() { | |||
7933 | // const int x = 10; | |||
7934 | // auto L = [=](auto a) { | |||
7935 | // (void) +x + a; | |||
7936 | // }; | |||
7937 | // } | |||
7938 | if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) && | |||
7939 | !IsFullExprInstantiationDependent) | |||
7940 | return; | |||
7941 | ||||
7942 | // If we have a capture-capable lambda for the variable, go ahead and | |||
7943 | // capture the variable in that lambda (and all its enclosing lambdas). | |||
7944 | if (const Optional<unsigned> Index = | |||
7945 | getStackIndexOfNearestEnclosingCaptureCapableLambda( | |||
7946 | S.FunctionScopes, Var, S)) | |||
7947 | S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(), | |||
7948 | Index.getValue()); | |||
7949 | const bool IsVarNeverAConstantExpression = | |||
7950 | VariableCanNeverBeAConstantExpression(Var, S.Context); | |||
7951 | if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) { | |||
7952 | // This full expression is not instantiation dependent or the variable | |||
7953 | // can not be used in a constant expression - which means | |||
7954 | // this variable must be odr-used here, so diagnose a | |||
7955 | // capture violation early, if the variable is un-captureable. | |||
7956 | // This is purely for diagnosing errors early. Otherwise, this | |||
7957 | // error would get diagnosed when the lambda becomes capture ready. | |||
7958 | QualType CaptureType, DeclRefType; | |||
7959 | SourceLocation ExprLoc = VarExpr->getExprLoc(); | |||
7960 | if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit, | |||
7961 | /*EllipsisLoc*/ SourceLocation(), | |||
7962 | /*BuildAndDiagnose*/false, CaptureType, | |||
7963 | DeclRefType, nullptr)) { | |||
7964 | // We will never be able to capture this variable, and we need | |||
7965 | // to be able to in any and all instantiations, so diagnose it. | |||
7966 | S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit, | |||
7967 | /*EllipsisLoc*/ SourceLocation(), | |||
7968 | /*BuildAndDiagnose*/true, CaptureType, | |||
7969 | DeclRefType, nullptr); | |||
7970 | } | |||
7971 | } | |||
7972 | }); | |||
7973 | ||||
7974 | // Check if 'this' needs to be captured. | |||
7975 | if (CurrentLSI->hasPotentialThisCapture()) { | |||
7976 | // If we have a capture-capable lambda for 'this', go ahead and capture | |||
7977 | // 'this' in that lambda (and all its enclosing lambdas). | |||
7978 | if (const Optional<unsigned> Index = | |||
7979 | getStackIndexOfNearestEnclosingCaptureCapableLambda( | |||
7980 | S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) { | |||
7981 | const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue(); | |||
7982 | S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation, | |||
7983 | /*Explicit*/ false, /*BuildAndDiagnose*/ true, | |||
7984 | &FunctionScopeIndexOfCapturableLambda); | |||
7985 | } | |||
7986 | } | |||
7987 | ||||
7988 | // Reset all the potential captures at the end of each full-expression. | |||
7989 | CurrentLSI->clearPotentialCaptures(); | |||
7990 | } | |||
7991 | ||||
7992 | static ExprResult attemptRecovery(Sema &SemaRef, | |||
7993 | const TypoCorrectionConsumer &Consumer, | |||
7994 | const TypoCorrection &TC) { | |||
7995 | LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(), | |||
7996 | Consumer.getLookupResult().getLookupKind()); | |||
7997 | const CXXScopeSpec *SS = Consumer.getSS(); | |||
7998 | CXXScopeSpec NewSS; | |||
7999 | ||||
8000 | // Use an approprate CXXScopeSpec for building the expr. | |||
8001 | if (auto *NNS = TC.getCorrectionSpecifier()) | |||
8002 | NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange()); | |||
8003 | else if (SS && !TC.WillReplaceSpecifier()) | |||
8004 | NewSS = *SS; | |||
8005 | ||||
8006 | if (auto *ND = TC.getFoundDecl()) { | |||
8007 | R.setLookupName(ND->getDeclName()); | |||
8008 | R.addDecl(ND); | |||
8009 | if (ND->isCXXClassMember()) { | |||
8010 | // Figure out the correct naming class to add to the LookupResult. | |||
8011 | CXXRecordDecl *Record = nullptr; | |||
8012 | if (auto *NNS = TC.getCorrectionSpecifier()) | |||
8013 | Record = NNS->getAsType()->getAsCXXRecordDecl(); | |||
8014 | if (!Record) | |||
8015 | Record = | |||
8016 | dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext()); | |||
8017 | if (Record) | |||
8018 | R.setNamingClass(Record); | |||
8019 | ||||
8020 | // Detect and handle the case where the decl might be an implicit | |||
8021 | // member. | |||
8022 | bool MightBeImplicitMember; | |||
8023 | if (!Consumer.isAddressOfOperand()) | |||
8024 | MightBeImplicitMember = true; | |||
8025 | else if (!NewSS.isEmpty()) | |||
8026 | MightBeImplicitMember = false; | |||
8027 | else if (R.isOverloadedResult()) | |||
8028 | MightBeImplicitMember = false; | |||
8029 | else if (R.isUnresolvableResult()) | |||
8030 | MightBeImplicitMember = true; | |||
8031 | else | |||
8032 | MightBeImplicitMember = isa<FieldDecl>(ND) || | |||
8033 | isa<IndirectFieldDecl>(ND) || | |||
8034 | isa<MSPropertyDecl>(ND); | |||
8035 | ||||
8036 | if (MightBeImplicitMember) | |||
8037 | return SemaRef.BuildPossibleImplicitMemberExpr( | |||
8038 | NewSS, /*TemplateKWLoc*/ SourceLocation(), R, | |||
8039 | /*TemplateArgs*/ nullptr, /*S*/ nullptr); | |||
8040 | } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) { | |||
8041 | return SemaRef.LookupInObjCMethod(R, Consumer.getScope(), | |||
8042 | Ivar->getIdentifier()); | |||
8043 | } | |||
8044 | } | |||
8045 | ||||
8046 | return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false, | |||
8047 | /*AcceptInvalidDecl*/ true); | |||
8048 | } | |||
8049 | ||||
8050 | namespace { | |||
8051 | class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> { | |||
8052 | llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs; | |||
8053 | ||||
8054 | public: | |||
8055 | explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs) | |||
8056 | : TypoExprs(TypoExprs) {} | |||
8057 | bool VisitTypoExpr(TypoExpr *TE) { | |||
8058 | TypoExprs.insert(TE); | |||
8059 | return true; | |||
8060 | } | |||
8061 | }; | |||
8062 | ||||
8063 | class TransformTypos : public TreeTransform<TransformTypos> { | |||
8064 | typedef TreeTransform<TransformTypos> BaseTransform; | |||
8065 | ||||
8066 | VarDecl *InitDecl; // A decl to avoid as a correction because it is in the | |||
8067 | // process of being initialized. | |||
8068 | llvm::function_ref<ExprResult(Expr *)> ExprFilter; | |||
8069 | llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs; | |||
8070 | llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache; | |||
8071 | llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution; | |||
8072 | ||||
8073 | /// Emit diagnostics for all of the TypoExprs encountered. | |||
8074 | /// | |||
8075 | /// If the TypoExprs were successfully corrected, then the diagnostics should | |||
8076 | /// suggest the corrections. Otherwise the diagnostics will not suggest | |||
8077 | /// anything (having been passed an empty TypoCorrection). | |||
8078 | /// | |||
8079 | /// If we've failed to correct due to ambiguous corrections, we need to | |||
8080 | /// be sure to pass empty corrections and replacements. Otherwise it's | |||
8081 | /// possible that the Consumer has a TypoCorrection that failed to ambiguity | |||
8082 | /// and we don't want to report those diagnostics. | |||
8083 | void EmitAllDiagnostics(bool IsAmbiguous) { | |||
8084 | for (TypoExpr *TE : TypoExprs) { | |||
8085 | auto &State = SemaRef.getTypoExprState(TE); | |||
8086 | if (State.DiagHandler) { | |||
8087 | TypoCorrection TC = IsAmbiguous | |||
8088 | ? TypoCorrection() : State.Consumer->getCurrentCorrection(); | |||
8089 | ExprResult Replacement = IsAmbiguous ? ExprError() : TransformCache[TE]; | |||
8090 | ||||
8091 | // Extract the NamedDecl from the transformed TypoExpr and add it to the | |||
8092 | // TypoCorrection, replacing the existing decls. This ensures the right | |||
8093 | // NamedDecl is used in diagnostics e.g. in the case where overload | |||
8094 | // resolution was used to select one from several possible decls that | |||
8095 | // had been stored in the TypoCorrection. | |||
8096 | if (auto *ND = getDeclFromExpr( | |||
8097 | Replacement.isInvalid() ? nullptr : Replacement.get())) | |||
8098 | TC.setCorrectionDecl(ND); | |||
8099 | ||||
8100 | State.DiagHandler(TC); | |||
8101 | } | |||
8102 | SemaRef.clearDelayedTypo(TE); | |||
8103 | } | |||
8104 | } | |||
8105 | ||||
8106 | /// Try to advance the typo correction state of the first unfinished TypoExpr. | |||
8107 | /// We allow advancement of the correction stream by removing it from the | |||
8108 | /// TransformCache which allows `TransformTypoExpr` to advance during the | |||
8109 | /// next transformation attempt. | |||
8110 | /// | |||
8111 | /// Any substitution attempts for the previous TypoExprs (which must have been | |||
8112 | /// finished) will need to be retried since it's possible that they will now | |||
8113 | /// be invalid given the latest advancement. | |||
8114 | /// | |||
8115 | /// We need to be sure that we're making progress - it's possible that the | |||
8116 | /// tree is so malformed that the transform never makes it to the | |||
8117 | /// `TransformTypoExpr`. | |||
8118 | /// | |||
8119 | /// Returns true if there are any untried correction combinations. | |||
8120 | bool CheckAndAdvanceTypoExprCorrectionStreams() { | |||
8121 | for (auto TE : TypoExprs) { | |||
8122 | auto &State = SemaRef.getTypoExprState(TE); | |||
8123 | TransformCache.erase(TE); | |||
8124 | if (!State.Consumer->hasMadeAnyCorrectionProgress()) | |||
8125 | return false; | |||
8126 | if (!State.Consumer->finished()) | |||
8127 | return true; | |||
8128 | State.Consumer->resetCorrectionStream(); | |||
8129 | } | |||
8130 | return false; | |||
8131 | } | |||
8132 | ||||
8133 | NamedDecl *getDeclFromExpr(Expr *E) { | |||
8134 | if (auto *OE = dyn_cast_or_null<OverloadExpr>(E)) | |||
8135 | E = OverloadResolution[OE]; | |||
8136 | ||||
8137 | if (!E) | |||
8138 | return nullptr; | |||
8139 | if (auto *DRE = dyn_cast<DeclRefExpr>(E)) | |||
8140 | return DRE->getFoundDecl(); | |||
8141 | if (auto *ME = dyn_cast<MemberExpr>(E)) | |||
8142 | return ME->getFoundDecl(); | |||
8143 | // FIXME: Add any other expr types that could be be seen by the delayed typo | |||
8144 | // correction TreeTransform for which the corresponding TypoCorrection could | |||
8145 | // contain multiple decls. | |||
8146 | return nullptr; | |||
8147 | } | |||
8148 | ||||
8149 | ExprResult TryTransform(Expr *E) { | |||
8150 | Sema::SFINAETrap Trap(SemaRef); | |||
8151 | ExprResult Res = TransformExpr(E); | |||
8152 | if (Trap.hasErrorOccurred() || Res.isInvalid()) | |||
8153 | return ExprError(); | |||
8154 | ||||
8155 | return ExprFilter(Res.get()); | |||
8156 | } | |||
8157 | ||||
8158 | // Since correcting typos may intoduce new TypoExprs, this function | |||
8159 | // checks for new TypoExprs and recurses if it finds any. Note that it will | |||
8160 | // only succeed if it is able to correct all typos in the given expression. | |||
8161 | ExprResult CheckForRecursiveTypos(ExprResult Res, bool &IsAmbiguous) { | |||
8162 | if (Res.isInvalid()) { | |||
8163 | return Res; | |||
8164 | } | |||
8165 | // Check to see if any new TypoExprs were created. If so, we need to recurse | |||
8166 | // to check their validity. | |||
8167 | Expr *FixedExpr = Res.get(); | |||
8168 | ||||
8169 | auto SavedTypoExprs = std::move(TypoExprs); | |||
8170 | auto SavedAmbiguousTypoExprs = std::move(AmbiguousTypoExprs); | |||
8171 | TypoExprs.clear(); | |||
8172 | AmbiguousTypoExprs.clear(); | |||
8173 | ||||
8174 | FindTypoExprs(TypoExprs).TraverseStmt(FixedExpr); | |||
8175 | if (!TypoExprs.empty()) { | |||
8176 | // Recurse to handle newly created TypoExprs. If we're not able to | |||
8177 | // handle them, discard these TypoExprs. | |||
8178 | ExprResult RecurResult = | |||
8179 | RecursiveTransformLoop(FixedExpr, IsAmbiguous); | |||
8180 | if (RecurResult.isInvalid()) { | |||
8181 | Res = ExprError(); | |||
8182 | // Recursive corrections didn't work, wipe them away and don't add | |||
8183 | // them to the TypoExprs set. Remove them from Sema's TypoExpr list | |||
8184 | // since we don't want to clear them twice. Note: it's possible the | |||
8185 | // TypoExprs were created recursively and thus won't be in our | |||
8186 | // Sema's TypoExprs - they were created in our `RecursiveTransformLoop`. | |||
8187 | auto &SemaTypoExprs = SemaRef.TypoExprs; | |||
8188 | for (auto TE : TypoExprs) { | |||
8189 | TransformCache.erase(TE); | |||
8190 | SemaRef.clearDelayedTypo(TE); | |||
8191 | ||||
8192 | auto SI = find(SemaTypoExprs, TE); | |||
8193 | if (SI != SemaTypoExprs.end()) { | |||
8194 | SemaTypoExprs.erase(SI); | |||
8195 | } | |||
8196 | } | |||
8197 | } else { | |||
8198 | // TypoExpr is valid: add newly created TypoExprs since we were | |||
8199 | // able to correct them. | |||
8200 | Res = RecurResult; | |||
8201 | SavedTypoExprs.set_union(TypoExprs); | |||
8202 | } | |||
8203 | } | |||
8204 | ||||
8205 | TypoExprs = std::move(SavedTypoExprs); | |||
8206 | AmbiguousTypoExprs = std::move(SavedAmbiguousTypoExprs); | |||
8207 | ||||
8208 | return Res; | |||
8209 | } | |||
8210 | ||||
8211 | // Try to transform the given expression, looping through the correction | |||
8212 | // candidates with `CheckAndAdvanceTypoExprCorrectionStreams`. | |||
8213 | // | |||
8214 | // If valid ambiguous typo corrections are seen, `IsAmbiguous` is set to | |||
8215 | // true and this method immediately will return an `ExprError`. | |||
8216 | ExprResult RecursiveTransformLoop(Expr *E, bool &IsAmbiguous) { | |||
8217 | ExprResult Res; | |||
8218 | auto SavedTypoExprs = std::move(SemaRef.TypoExprs); | |||
8219 | SemaRef.TypoExprs.clear(); | |||
8220 | ||||
8221 | while (true) { | |||
8222 | Res = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous); | |||
8223 | ||||
8224 | // Recursion encountered an ambiguous correction. This means that our | |||
8225 | // correction itself is ambiguous, so stop now. | |||
8226 | if (IsAmbiguous) | |||
8227 | break; | |||
8228 | ||||
8229 | // If the transform is still valid after checking for any new typos, | |||
8230 | // it's good to go. | |||
8231 | if (!Res.isInvalid()) | |||
8232 | break; | |||
8233 | ||||
8234 | // The transform was invalid, see if we have any TypoExprs with untried | |||
8235 | // correction candidates. | |||
8236 | if (!CheckAndAdvanceTypoExprCorrectionStreams()) | |||
8237 | break; | |||
8238 | } | |||
8239 | ||||
8240 | // If we found a valid result, double check to make sure it's not ambiguous. | |||
8241 | if (!IsAmbiguous && !Res.isInvalid() && !AmbiguousTypoExprs.empty()) { | |||
8242 | auto SavedTransformCache = | |||
8243 | llvm::SmallDenseMap<TypoExpr *, ExprResult, 2>(TransformCache); | |||
8244 | ||||
8245 | // Ensure none of the TypoExprs have multiple typo correction candidates | |||
8246 | // with the same edit length that pass all the checks and filters. | |||
8247 | while (!AmbiguousTypoExprs.empty()) { | |||
8248 | auto TE = AmbiguousTypoExprs.back(); | |||
8249 | ||||
8250 | // TryTransform itself can create new Typos, adding them to the TypoExpr map | |||
8251 | // and invalidating our TypoExprState, so always fetch it instead of storing. | |||
8252 | SemaRef.getTypoExprState(TE).Consumer->saveCurrentPosition(); | |||
8253 | ||||
8254 | TypoCorrection TC = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection(); | |||
8255 | TypoCorrection Next; | |||
8256 | do { | |||
8257 | // Fetch the next correction by erasing the typo from the cache and calling | |||
8258 | // `TryTransform` which will iterate through corrections in | |||
8259 | // `TransformTypoExpr`. | |||
8260 | TransformCache.erase(TE); | |||
8261 | ExprResult AmbigRes = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous); | |||
8262 | ||||
8263 | if (!AmbigRes.isInvalid() || IsAmbiguous) { | |||
8264 | SemaRef.getTypoExprState(TE).Consumer->resetCorrectionStream(); | |||
8265 | SavedTransformCache.erase(TE); | |||
8266 | Res = ExprError(); | |||
8267 | IsAmbiguous = true; | |||
8268 | break; | |||
8269 | } | |||
8270 | } while ((Next = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection()) && | |||
8271 | Next.getEditDistance(false) == TC.getEditDistance(false)); | |||
8272 | ||||
8273 | if (IsAmbiguous) | |||
8274 | break; | |||
8275 | ||||
8276 | AmbiguousTypoExprs.remove(TE); | |||
8277 | SemaRef.getTypoExprState(TE).Consumer->restoreSavedPosition(); | |||
8278 | } | |||
8279 | TransformCache = std::move(SavedTransformCache); | |||
8280 | } | |||
8281 | ||||
8282 | // Wipe away any newly created TypoExprs that we don't know about. Since we | |||
8283 | // clear any invalid TypoExprs in `CheckForRecursiveTypos`, this is only | |||
8284 | // possible if a `TypoExpr` is created during a transformation but then | |||
8285 | // fails before we can discover it. | |||
8286 | auto &SemaTypoExprs = SemaRef.TypoExprs; | |||
8287 | for (auto Iterator = SemaTypoExprs.begin(); Iterator != SemaTypoExprs.end();) { | |||
8288 | auto TE = *Iterator; | |||
8289 | auto FI = find(TypoExprs, TE); | |||
8290 | if (FI != TypoExprs.end()) { | |||
8291 | Iterator++; | |||
8292 | continue; | |||
8293 | } | |||
8294 | SemaRef.clearDelayedTypo(TE); | |||
8295 | Iterator = SemaTypoExprs.erase(Iterator); | |||
8296 | } | |||
8297 | SemaRef.TypoExprs = std::move(SavedTypoExprs); | |||
8298 | ||||
8299 | return Res; | |||
8300 | } | |||
8301 | ||||
8302 | public: | |||
8303 | TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter) | |||
8304 | : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {} | |||
8305 | ||||
8306 | ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc, | |||
8307 | MultiExprArg Args, | |||
8308 | SourceLocation RParenLoc, | |||
8309 | Expr *ExecConfig = nullptr) { | |||
8310 | auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args, | |||
8311 | RParenLoc, ExecConfig); | |||
8312 | if (auto *OE = dyn_cast<OverloadExpr>(Callee)) { | |||
8313 | if (Result.isUsable()) { | |||
8314 | Expr *ResultCall = Result.get(); | |||
8315 | if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall)) | |||
8316 | ResultCall = BE->getSubExpr(); | |||
8317 | if (auto *CE = dyn_cast<CallExpr>(ResultCall)) | |||
8318 | OverloadResolution[OE] = CE->getCallee(); | |||
8319 | } | |||
8320 | } | |||
8321 | return Result; | |||
8322 | } | |||
8323 | ||||
8324 | ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); } | |||
8325 | ||||
8326 | ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); } | |||
8327 | ||||
8328 | ExprResult Transform(Expr *E) { | |||
8329 | bool IsAmbiguous = false; | |||
8330 | ExprResult Res = RecursiveTransformLoop(E, IsAmbiguous); | |||
8331 | ||||
8332 | if (!Res.isUsable()) | |||
8333 | FindTypoExprs(TypoExprs).TraverseStmt(E); | |||
8334 | ||||
8335 | EmitAllDiagnostics(IsAmbiguous); | |||
8336 | ||||
8337 | return Res; | |||
8338 | } | |||
8339 | ||||
8340 | ExprResult TransformTypoExpr(TypoExpr *E) { | |||
8341 | // If the TypoExpr hasn't been seen before, record it. Otherwise, return the | |||
8342 | // cached transformation result if there is one and the TypoExpr isn't the | |||
8343 | // first one that was encountered. | |||
8344 | auto &CacheEntry = TransformCache[E]; | |||
8345 | if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) { | |||
8346 | return CacheEntry; | |||
8347 | } | |||
8348 | ||||
8349 | auto &State = SemaRef.getTypoExprState(E); | |||
8350 | assert(State.Consumer && "Cannot transform a cleared TypoExpr")(static_cast <bool> (State.Consumer && "Cannot transform a cleared TypoExpr" ) ? void (0) : __assert_fail ("State.Consumer && \"Cannot transform a cleared TypoExpr\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 8350, __extension__ __PRETTY_FUNCTION__)); | |||
8351 | ||||
8352 | // For the first TypoExpr and an uncached TypoExpr, find the next likely | |||
8353 | // typo correction and return it. | |||
8354 | while (TypoCorrection TC = State.Consumer->getNextCorrection()) { | |||
8355 | if (InitDecl && TC.getFoundDecl() == InitDecl) | |||
8356 | continue; | |||
8357 | // FIXME: If we would typo-correct to an invalid declaration, it's | |||
8358 | // probably best to just suppress all errors from this typo correction. | |||
8359 | ExprResult NE = State.RecoveryHandler ? | |||
8360 | State.RecoveryHandler(SemaRef, E, TC) : | |||
8361 | attemptRecovery(SemaRef, *State.Consumer, TC); | |||
8362 | if (!NE.isInvalid()) { | |||
8363 | // Check whether there may be a second viable correction with the same | |||
8364 | // edit distance; if so, remember this TypoExpr may have an ambiguous | |||
8365 | // correction so it can be more thoroughly vetted later. | |||
8366 | TypoCorrection Next; | |||
8367 | if ((Next = State.Consumer->peekNextCorrection()) && | |||
8368 | Next.getEditDistance(false) == TC.getEditDistance(false)) { | |||
8369 | AmbiguousTypoExprs.insert(E); | |||
8370 | } else { | |||
8371 | AmbiguousTypoExprs.remove(E); | |||
8372 | } | |||
8373 | assert(!NE.isUnset() &&(static_cast <bool> (!NE.isUnset() && "Typo was transformed into a valid-but-null ExprResult" ) ? void (0) : __assert_fail ("!NE.isUnset() && \"Typo was transformed into a valid-but-null ExprResult\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 8374, __extension__ __PRETTY_FUNCTION__)) | |||
8374 | "Typo was transformed into a valid-but-null ExprResult")(static_cast <bool> (!NE.isUnset() && "Typo was transformed into a valid-but-null ExprResult" ) ? void (0) : __assert_fail ("!NE.isUnset() && \"Typo was transformed into a valid-but-null ExprResult\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 8374, __extension__ __PRETTY_FUNCTION__)); | |||
8375 | return CacheEntry = NE; | |||
8376 | } | |||
8377 | } | |||
8378 | return CacheEntry = ExprError(); | |||
8379 | } | |||
8380 | }; | |||
8381 | } | |||
8382 | ||||
8383 | ExprResult | |||
8384 | Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl, | |||
8385 | bool RecoverUncorrectedTypos, | |||
8386 | llvm::function_ref<ExprResult(Expr *)> Filter) { | |||
8387 | // If the current evaluation context indicates there are uncorrected typos | |||
8388 | // and the current expression isn't guaranteed to not have typos, try to | |||
8389 | // resolve any TypoExpr nodes that might be in the expression. | |||
8390 | if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos && | |||
8391 | (E->isTypeDependent() || E->isValueDependent() || | |||
8392 | E->isInstantiationDependent())) { | |||
8393 | auto TyposResolved = DelayedTypos.size(); | |||
8394 | auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E); | |||
8395 | TyposResolved -= DelayedTypos.size(); | |||
8396 | if (Result.isInvalid() || Result.get() != E) { | |||
8397 | ExprEvalContexts.back().NumTypos -= TyposResolved; | |||
8398 | if (Result.isInvalid() && RecoverUncorrectedTypos) { | |||
8399 | struct TyposReplace : TreeTransform<TyposReplace> { | |||
8400 | TyposReplace(Sema &SemaRef) : TreeTransform(SemaRef) {} | |||
8401 | ExprResult TransformTypoExpr(clang::TypoExpr *E) { | |||
8402 | return this->SemaRef.CreateRecoveryExpr(E->getBeginLoc(), | |||
8403 | E->getEndLoc(), {}); | |||
8404 | } | |||
8405 | } TT(*this); | |||
8406 | return TT.TransformExpr(E); | |||
8407 | } | |||
8408 | return Result; | |||
8409 | } | |||
8410 | assert(TyposResolved == 0 && "Corrected typo but got same Expr back?")(static_cast <bool> (TyposResolved == 0 && "Corrected typo but got same Expr back?" ) ? void (0) : __assert_fail ("TyposResolved == 0 && \"Corrected typo but got same Expr back?\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 8410, __extension__ __PRETTY_FUNCTION__)); | |||
8411 | } | |||
8412 | return E; | |||
8413 | } | |||
8414 | ||||
8415 | ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC, | |||
8416 | bool DiscardedValue, | |||
8417 | bool IsConstexpr) { | |||
8418 | ExprResult FullExpr = FE; | |||
8419 | ||||
8420 | if (!FullExpr.get()) | |||
8421 | return ExprError(); | |||
8422 | ||||
8423 | if (DiagnoseUnexpandedParameterPack(FullExpr.get())) | |||
8424 | return ExprError(); | |||
8425 | ||||
8426 | if (DiscardedValue) { | |||
8427 | // Top-level expressions default to 'id' when we're in a debugger. | |||
8428 | if (getLangOpts().DebuggerCastResultToId && | |||
8429 | FullExpr.get()->getType() == Context.UnknownAnyTy) { | |||
8430 | FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType()); | |||
8431 | if (FullExpr.isInvalid()) | |||
8432 | return ExprError(); | |||
8433 | } | |||
8434 | ||||
8435 | FullExpr = CheckPlaceholderExpr(FullExpr.get()); | |||
8436 | if (FullExpr.isInvalid()) | |||
8437 | return ExprError(); | |||
8438 | ||||
8439 | FullExpr = IgnoredValueConversions(FullExpr.get()); | |||
8440 | if (FullExpr.isInvalid()) | |||
8441 | return ExprError(); | |||
8442 | ||||
8443 | DiagnoseUnusedExprResult(FullExpr.get()); | |||
8444 | } | |||
8445 | ||||
8446 | FullExpr = CorrectDelayedTyposInExpr(FullExpr.get(), /*InitDecl=*/nullptr, | |||
8447 | /*RecoverUncorrectedTypos=*/true); | |||
8448 | if (FullExpr.isInvalid()) | |||
8449 | return ExprError(); | |||
8450 | ||||
8451 | CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr); | |||
8452 | ||||
8453 | // At the end of this full expression (which could be a deeply nested | |||
8454 | // lambda), if there is a potential capture within the nested lambda, | |||
8455 | // have the outer capture-able lambda try and capture it. | |||
8456 | // Consider the following code: | |||
8457 | // void f(int, int); | |||
8458 | // void f(const int&, double); | |||
8459 | // void foo() { | |||
8460 | // const int x = 10, y = 20; | |||
8461 | // auto L = [=](auto a) { | |||
8462 | // auto M = [=](auto b) { | |||
8463 | // f(x, b); <-- requires x to be captured by L and M | |||
8464 | // f(y, a); <-- requires y to be captured by L, but not all Ms | |||
8465 | // }; | |||
8466 | // }; | |||
8467 | // } | |||
8468 | ||||
8469 | // FIXME: Also consider what happens for something like this that involves | |||
8470 | // the gnu-extension statement-expressions or even lambda-init-captures: | |||
8471 | // void f() { | |||
8472 | // const int n = 0; | |||
8473 | // auto L = [&](auto a) { | |||
8474 | // +n + ({ 0; a; }); | |||
8475 | // }; | |||
8476 | // } | |||
8477 | // | |||
8478 | // Here, we see +n, and then the full-expression 0; ends, so we don't | |||
8479 | // capture n (and instead remove it from our list of potential captures), | |||
8480 | // and then the full-expression +n + ({ 0; }); ends, but it's too late | |||
8481 | // for us to see that we need to capture n after all. | |||
8482 | ||||
8483 | LambdaScopeInfo *const CurrentLSI = | |||
8484 | getCurLambda(/*IgnoreCapturedRegions=*/true); | |||
8485 | // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer | |||
8486 | // even if CurContext is not a lambda call operator. Refer to that Bug Report | |||
8487 | // for an example of the code that might cause this asynchrony. | |||
8488 | // By ensuring we are in the context of a lambda's call operator | |||
8489 | // we can fix the bug (we only need to check whether we need to capture | |||
8490 | // if we are within a lambda's body); but per the comments in that | |||
8491 | // PR, a proper fix would entail : | |||
8492 | // "Alternative suggestion: | |||
8493 | // - Add to Sema an integer holding the smallest (outermost) scope | |||
8494 | // index that we are *lexically* within, and save/restore/set to | |||
8495 | // FunctionScopes.size() in InstantiatingTemplate's | |||
8496 | // constructor/destructor. | |||
8497 | // - Teach the handful of places that iterate over FunctionScopes to | |||
8498 | // stop at the outermost enclosing lexical scope." | |||
8499 | DeclContext *DC = CurContext; | |||
8500 | while (DC && isa<CapturedDecl>(DC)) | |||
8501 | DC = DC->getParent(); | |||
8502 | const bool IsInLambdaDeclContext = isLambdaCallOperator(DC); | |||
8503 | if (IsInLambdaDeclContext && CurrentLSI && | |||
8504 | CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid()) | |||
8505 | CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI, | |||
8506 | *this); | |||
8507 | return MaybeCreateExprWithCleanups(FullExpr); | |||
8508 | } | |||
8509 | ||||
8510 | StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) { | |||
8511 | if (!FullStmt) return StmtError(); | |||
8512 | ||||
8513 | return MaybeCreateStmtWithCleanups(FullStmt); | |||
8514 | } | |||
8515 | ||||
8516 | Sema::IfExistsResult | |||
8517 | Sema::CheckMicrosoftIfExistsSymbol(Scope *S, | |||
8518 | CXXScopeSpec &SS, | |||
8519 | const DeclarationNameInfo &TargetNameInfo) { | |||
8520 | DeclarationName TargetName = TargetNameInfo.getName(); | |||
8521 | if (!TargetName) | |||
8522 | return IER_DoesNotExist; | |||
8523 | ||||
8524 | // If the name itself is dependent, then the result is dependent. | |||
8525 | if (TargetName.isDependentName()) | |||
8526 | return IER_Dependent; | |||
8527 | ||||
8528 | // Do the redeclaration lookup in the current scope. | |||
8529 | LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName, | |||
8530 | Sema::NotForRedeclaration); | |||
8531 | LookupParsedName(R, S, &SS); | |||
8532 | R.suppressDiagnostics(); | |||
8533 | ||||
8534 | switch (R.getResultKind()) { | |||
8535 | case LookupResult::Found: | |||
8536 | case LookupResult::FoundOverloaded: | |||
8537 | case LookupResult::FoundUnresolvedValue: | |||
8538 | case LookupResult::Ambiguous: | |||
8539 | return IER_Exists; | |||
8540 | ||||
8541 | case LookupResult::NotFound: | |||
8542 | return IER_DoesNotExist; | |||
8543 | ||||
8544 | case LookupResult::NotFoundInCurrentInstantiation: | |||
8545 | return IER_Dependent; | |||
8546 | } | |||
8547 | ||||
8548 | llvm_unreachable("Invalid LookupResult Kind!")::llvm::llvm_unreachable_internal("Invalid LookupResult Kind!" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 8548); | |||
8549 | } | |||
8550 | ||||
8551 | Sema::IfExistsResult | |||
8552 | Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, | |||
8553 | bool IsIfExists, CXXScopeSpec &SS, | |||
8554 | UnqualifiedId &Name) { | |||
8555 | DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); | |||
8556 | ||||
8557 | // Check for an unexpanded parameter pack. | |||
8558 | auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists; | |||
8559 | if (DiagnoseUnexpandedParameterPack(SS, UPPC) || | |||
8560 | DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC)) | |||
8561 | return IER_Error; | |||
8562 | ||||
8563 | return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo); | |||
8564 | } | |||
8565 | ||||
8566 | concepts::Requirement *Sema::ActOnSimpleRequirement(Expr *E) { | |||
8567 | return BuildExprRequirement(E, /*IsSimple=*/true, | |||
8568 | /*NoexceptLoc=*/SourceLocation(), | |||
8569 | /*ReturnTypeRequirement=*/{}); | |||
8570 | } | |||
8571 | ||||
8572 | concepts::Requirement * | |||
8573 | Sema::ActOnTypeRequirement(SourceLocation TypenameKWLoc, CXXScopeSpec &SS, | |||
8574 | SourceLocation NameLoc, IdentifierInfo *TypeName, | |||
8575 | TemplateIdAnnotation *TemplateId) { | |||
8576 | assert(((!TypeName && TemplateId) || (TypeName && !TemplateId)) &&(static_cast <bool> (((!TypeName && TemplateId) || (TypeName && !TemplateId)) && "Exactly one of TypeName and TemplateId must be specified." ) ? void (0) : __assert_fail ("((!TypeName && TemplateId) || (TypeName && !TemplateId)) && \"Exactly one of TypeName and TemplateId must be specified.\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 8577, __extension__ __PRETTY_FUNCTION__)) | |||
8577 | "Exactly one of TypeName and TemplateId must be specified.")(static_cast <bool> (((!TypeName && TemplateId) || (TypeName && !TemplateId)) && "Exactly one of TypeName and TemplateId must be specified." ) ? void (0) : __assert_fail ("((!TypeName && TemplateId) || (TypeName && !TemplateId)) && \"Exactly one of TypeName and TemplateId must be specified.\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 8577, __extension__ __PRETTY_FUNCTION__)); | |||
8578 | TypeSourceInfo *TSI = nullptr; | |||
8579 | if (TypeName) { | |||
8580 | QualType T = CheckTypenameType(ETK_Typename, TypenameKWLoc, | |||
8581 | SS.getWithLocInContext(Context), *TypeName, | |||
8582 | NameLoc, &TSI, /*DeducedTypeContext=*/false); | |||
8583 | if (T.isNull()) | |||
8584 | return nullptr; | |||
8585 | } else { | |||
8586 | ASTTemplateArgsPtr ArgsPtr(TemplateId->getTemplateArgs(), | |||
8587 | TemplateId->NumArgs); | |||
8588 | TypeResult T = ActOnTypenameType(CurScope, TypenameKWLoc, SS, | |||
8589 | TemplateId->TemplateKWLoc, | |||
8590 | TemplateId->Template, TemplateId->Name, | |||
8591 | TemplateId->TemplateNameLoc, | |||
8592 | TemplateId->LAngleLoc, ArgsPtr, | |||
8593 | TemplateId->RAngleLoc); | |||
8594 | if (T.isInvalid()) | |||
8595 | return nullptr; | |||
8596 | if (GetTypeFromParser(T.get(), &TSI).isNull()) | |||
8597 | return nullptr; | |||
8598 | } | |||
8599 | return BuildTypeRequirement(TSI); | |||
8600 | } | |||
8601 | ||||
8602 | concepts::Requirement * | |||
8603 | Sema::ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc) { | |||
8604 | return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, | |||
8605 | /*ReturnTypeRequirement=*/{}); | |||
8606 | } | |||
8607 | ||||
8608 | concepts::Requirement * | |||
8609 | Sema::ActOnCompoundRequirement( | |||
8610 | Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS, | |||
8611 | TemplateIdAnnotation *TypeConstraint, unsigned Depth) { | |||
8612 | // C++2a [expr.prim.req.compound] p1.3.3 | |||
8613 | // [..] the expression is deduced against an invented function template | |||
8614 | // F [...] F is a void function template with a single type template | |||
8615 | // parameter T declared with the constrained-parameter. Form a new | |||
8616 | // cv-qualifier-seq cv by taking the union of const and volatile specifiers | |||
8617 | // around the constrained-parameter. F has a single parameter whose | |||
8618 | // type-specifier is cv T followed by the abstract-declarator. [...] | |||
8619 | // | |||
8620 | // The cv part is done in the calling function - we get the concept with | |||
8621 | // arguments and the abstract declarator with the correct CV qualification and | |||
8622 | // have to synthesize T and the single parameter of F. | |||
8623 | auto &II = Context.Idents.get("expr-type"); | |||
8624 | auto *TParam = TemplateTypeParmDecl::Create(Context, CurContext, | |||
8625 | SourceLocation(), | |||
8626 | SourceLocation(), Depth, | |||
8627 | /*Index=*/0, &II, | |||
8628 | /*Typename=*/true, | |||
8629 | /*ParameterPack=*/false, | |||
8630 | /*HasTypeConstraint=*/true); | |||
8631 | ||||
8632 | if (BuildTypeConstraint(SS, TypeConstraint, TParam, | |||
8633 | /*EllpsisLoc=*/SourceLocation(), | |||
8634 | /*AllowUnexpandedPack=*/true)) | |||
8635 | // Just produce a requirement with no type requirements. | |||
8636 | return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, {}); | |||
8637 | ||||
8638 | auto *TPL = TemplateParameterList::Create(Context, SourceLocation(), | |||
8639 | SourceLocation(), | |||
8640 | ArrayRef<NamedDecl *>(TParam), | |||
8641 | SourceLocation(), | |||
8642 | /*RequiresClause=*/nullptr); | |||
8643 | return BuildExprRequirement( | |||
8644 | E, /*IsSimple=*/false, NoexceptLoc, | |||
8645 | concepts::ExprRequirement::ReturnTypeRequirement(TPL)); | |||
8646 | } | |||
8647 | ||||
8648 | concepts::ExprRequirement * | |||
8649 | Sema::BuildExprRequirement( | |||
8650 | Expr *E, bool IsSimple, SourceLocation NoexceptLoc, | |||
8651 | concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) { | |||
8652 | auto Status = concepts::ExprRequirement::SS_Satisfied; | |||
8653 | ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr; | |||
8654 | if (E->isInstantiationDependent() || ReturnTypeRequirement.isDependent()) | |||
8655 | Status = concepts::ExprRequirement::SS_Dependent; | |||
8656 | else if (NoexceptLoc.isValid() && canThrow(E) == CanThrowResult::CT_Can) | |||
8657 | Status = concepts::ExprRequirement::SS_NoexceptNotMet; | |||
8658 | else if (ReturnTypeRequirement.isSubstitutionFailure()) | |||
8659 | Status = concepts::ExprRequirement::SS_TypeRequirementSubstitutionFailure; | |||
8660 | else if (ReturnTypeRequirement.isTypeConstraint()) { | |||
8661 | // C++2a [expr.prim.req]p1.3.3 | |||
8662 | // The immediately-declared constraint ([temp]) of decltype((E)) shall | |||
8663 | // be satisfied. | |||
8664 | TemplateParameterList *TPL = | |||
8665 | ReturnTypeRequirement.getTypeConstraintTemplateParameterList(); | |||
8666 | QualType MatchedType = | |||
8667 | getDecltypeForParenthesizedExpr(E).getCanonicalType(); | |||
8668 | llvm::SmallVector<TemplateArgument, 1> Args; | |||
8669 | Args.push_back(TemplateArgument(MatchedType)); | |||
8670 | TemplateArgumentList TAL(TemplateArgumentList::OnStack, Args); | |||
8671 | MultiLevelTemplateArgumentList MLTAL(TAL); | |||
8672 | for (unsigned I = 0; I < TPL->getDepth(); ++I) | |||
8673 | MLTAL.addOuterRetainedLevel(); | |||
8674 | Expr *IDC = | |||
8675 | cast<TemplateTypeParmDecl>(TPL->getParam(0))->getTypeConstraint() | |||
8676 | ->getImmediatelyDeclaredConstraint(); | |||
8677 | ExprResult Constraint = SubstExpr(IDC, MLTAL); | |||
8678 | assert(!Constraint.isInvalid() &&(static_cast <bool> (!Constraint.isInvalid() && "Substitution cannot fail as it is simply putting a type template " "argument into a concept specialization expression's parameter." ) ? void (0) : __assert_fail ("!Constraint.isInvalid() && \"Substitution cannot fail as it is simply putting a type template \" \"argument into a concept specialization expression's parameter.\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 8680, __extension__ __PRETTY_FUNCTION__)) | |||
8679 | "Substitution cannot fail as it is simply putting a type template "(static_cast <bool> (!Constraint.isInvalid() && "Substitution cannot fail as it is simply putting a type template " "argument into a concept specialization expression's parameter." ) ? void (0) : __assert_fail ("!Constraint.isInvalid() && \"Substitution cannot fail as it is simply putting a type template \" \"argument into a concept specialization expression's parameter.\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 8680, __extension__ __PRETTY_FUNCTION__)) | |||
8680 | "argument into a concept specialization expression's parameter.")(static_cast <bool> (!Constraint.isInvalid() && "Substitution cannot fail as it is simply putting a type template " "argument into a concept specialization expression's parameter." ) ? void (0) : __assert_fail ("!Constraint.isInvalid() && \"Substitution cannot fail as it is simply putting a type template \" \"argument into a concept specialization expression's parameter.\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 8680, __extension__ __PRETTY_FUNCTION__)); | |||
8681 | ||||
8682 | SubstitutedConstraintExpr = | |||
8683 | cast<ConceptSpecializationExpr>(Constraint.get()); | |||
8684 | if (!SubstitutedConstraintExpr->isSatisfied()) | |||
8685 | Status = concepts::ExprRequirement::SS_ConstraintsNotSatisfied; | |||
8686 | } | |||
8687 | return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc, | |||
8688 | ReturnTypeRequirement, Status, | |||
8689 | SubstitutedConstraintExpr); | |||
8690 | } | |||
8691 | ||||
8692 | concepts::ExprRequirement * | |||
8693 | Sema::BuildExprRequirement( | |||
8694 | concepts::Requirement::SubstitutionDiagnostic *ExprSubstitutionDiagnostic, | |||
8695 | bool IsSimple, SourceLocation NoexceptLoc, | |||
8696 | concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) { | |||
8697 | return new (Context) concepts::ExprRequirement(ExprSubstitutionDiagnostic, | |||
8698 | IsSimple, NoexceptLoc, | |||
8699 | ReturnTypeRequirement); | |||
8700 | } | |||
8701 | ||||
8702 | concepts::TypeRequirement * | |||
8703 | Sema::BuildTypeRequirement(TypeSourceInfo *Type) { | |||
8704 | return new (Context) concepts::TypeRequirement(Type); | |||
8705 | } | |||
8706 | ||||
8707 | concepts::TypeRequirement * | |||
8708 | Sema::BuildTypeRequirement( | |||
8709 | concepts::Requirement::SubstitutionDiagnostic *SubstDiag) { | |||
8710 | return new (Context) concepts::TypeRequirement(SubstDiag); | |||
8711 | } | |||
8712 | ||||
8713 | concepts::Requirement *Sema::ActOnNestedRequirement(Expr *Constraint) { | |||
8714 | return BuildNestedRequirement(Constraint); | |||
8715 | } | |||
8716 | ||||
8717 | concepts::NestedRequirement * | |||
8718 | Sema::BuildNestedRequirement(Expr *Constraint) { | |||
8719 | ConstraintSatisfaction Satisfaction; | |||
8720 | if (!Constraint->isInstantiationDependent() && | |||
8721 | CheckConstraintSatisfaction(nullptr, {Constraint}, /*TemplateArgs=*/{}, | |||
8722 | Constraint->getSourceRange(), Satisfaction)) | |||
8723 | return nullptr; | |||
8724 | return new (Context) concepts::NestedRequirement(Context, Constraint, | |||
8725 | Satisfaction); | |||
8726 | } | |||
8727 | ||||
8728 | concepts::NestedRequirement * | |||
8729 | Sema::BuildNestedRequirement( | |||
8730 | concepts::Requirement::SubstitutionDiagnostic *SubstDiag) { | |||
8731 | return new (Context) concepts::NestedRequirement(SubstDiag); | |||
8732 | } | |||
8733 | ||||
8734 | RequiresExprBodyDecl * | |||
8735 | Sema::ActOnStartRequiresExpr(SourceLocation RequiresKWLoc, | |||
8736 | ArrayRef<ParmVarDecl *> LocalParameters, | |||
8737 | Scope *BodyScope) { | |||
8738 | assert(BodyScope)(static_cast <bool> (BodyScope) ? void (0) : __assert_fail ("BodyScope", "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 8738, __extension__ __PRETTY_FUNCTION__)); | |||
8739 | ||||
8740 | RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(Context, CurContext, | |||
8741 | RequiresKWLoc); | |||
8742 | ||||
8743 | PushDeclContext(BodyScope, Body); | |||
8744 | ||||
8745 | for (ParmVarDecl *Param : LocalParameters) { | |||
8746 | if (Param->hasDefaultArg()) | |||
8747 | // C++2a [expr.prim.req] p4 | |||
8748 | // [...] A local parameter of a requires-expression shall not have a | |||
8749 | // default argument. [...] | |||
8750 | Diag(Param->getDefaultArgRange().getBegin(), | |||
8751 | diag::err_requires_expr_local_parameter_default_argument); | |||
8752 | // Ignore default argument and move on | |||
8753 | ||||
8754 | Param->setDeclContext(Body); | |||
8755 | // If this has an identifier, add it to the scope stack. | |||
8756 | if (Param->getIdentifier()) { | |||
8757 | CheckShadow(BodyScope, Param); | |||
8758 | PushOnScopeChains(Param, BodyScope); | |||
8759 | } | |||
8760 | } | |||
8761 | return Body; | |||
8762 | } | |||
8763 | ||||
8764 | void Sema::ActOnFinishRequiresExpr() { | |||
8765 | assert(CurContext && "DeclContext imbalance!")(static_cast <bool> (CurContext && "DeclContext imbalance!" ) ? void (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 8765, __extension__ __PRETTY_FUNCTION__)); | |||
8766 | CurContext = CurContext->getLexicalParent(); | |||
8767 | assert(CurContext && "Popped translation unit!")(static_cast <bool> (CurContext && "Popped translation unit!" ) ? void (0) : __assert_fail ("CurContext && \"Popped translation unit!\"" , "/build/llvm-toolchain-snapshot-13~++20210601111131+18225d45769b/clang/lib/Sema/SemaExprCXX.cpp" , 8767, __extension__ __PRETTY_FUNCTION__)); | |||
8768 | } | |||
8769 | ||||
8770 | ExprResult | |||
8771 | Sema::ActOnRequiresExpr(SourceLocation RequiresKWLoc, | |||
8772 | RequiresExprBodyDecl *Body, | |||
8773 | ArrayRef<ParmVarDecl *> LocalParameters, | |||
8774 | ArrayRef<concepts::Requirement *> Requirements, | |||
8775 | SourceLocation ClosingBraceLoc) { | |||
8776 | auto *RE = RequiresExpr::Create(Context, RequiresKWLoc, Body, LocalParameters, | |||
8777 | Requirements, ClosingBraceLoc); | |||
8778 | if (DiagnoseUnexpandedParameterPackInRequiresExpr(RE)) | |||
8779 | return ExprError(); | |||
8780 | return RE; | |||
8781 | } |