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 "TreeTransform.h" |
15 | #include "TypeLocBuilder.h" |
16 | #include "clang/AST/ASTContext.h" |
17 | #include "clang/AST/ASTLambda.h" |
18 | #include "clang/AST/CXXInheritance.h" |
19 | #include "clang/AST/CharUnits.h" |
20 | #include "clang/AST/DeclObjC.h" |
21 | #include "clang/AST/ExprCXX.h" |
22 | #include "clang/AST/ExprConcepts.h" |
23 | #include "clang/AST/ExprObjC.h" |
24 | #include "clang/AST/RecursiveASTVisitor.h" |
25 | #include "clang/AST/Type.h" |
26 | #include "clang/AST/TypeLoc.h" |
27 | #include "clang/Basic/AlignedAllocation.h" |
28 | #include "clang/Basic/DiagnosticSema.h" |
29 | #include "clang/Basic/PartialDiagnostic.h" |
30 | #include "clang/Basic/TargetInfo.h" |
31 | #include "clang/Basic/TokenKinds.h" |
32 | #include "clang/Basic/TypeTraits.h" |
33 | #include "clang/Lex/Preprocessor.h" |
34 | #include "clang/Sema/DeclSpec.h" |
35 | #include "clang/Sema/EnterExpressionEvaluationContext.h" |
36 | #include "clang/Sema/Initialization.h" |
37 | #include "clang/Sema/Lookup.h" |
38 | #include "clang/Sema/ParsedTemplate.h" |
39 | #include "clang/Sema/Scope.h" |
40 | #include "clang/Sema/ScopeInfo.h" |
41 | #include "clang/Sema/SemaCUDA.h" |
42 | #include "clang/Sema/SemaInternal.h" |
43 | #include "clang/Sema/SemaLambda.h" |
44 | #include "clang/Sema/Template.h" |
45 | #include "clang/Sema/TemplateDeduction.h" |
46 | #include "llvm/ADT/APInt.h" |
47 | #include "llvm/ADT/STLExtras.h" |
48 | #include "llvm/ADT/STLForwardCompat.h" |
49 | #include "llvm/ADT/StringExtras.h" |
50 | #include "llvm/Support/ErrorHandling.h" |
51 | #include "llvm/Support/TypeSize.h" |
52 | #include <optional> |
53 | using namespace clang; |
54 | using namespace sema; |
55 | |
56 | /// Handle the result of the special case name lookup for inheriting |
57 | /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as |
58 | /// constructor names in member using declarations, even if 'X' is not the |
59 | /// name of the corresponding type. |
60 | ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS, |
61 | SourceLocation NameLoc, |
62 | const IdentifierInfo &Name) { |
63 | NestedNameSpecifier *NNS = SS.getScopeRep(); |
64 | |
65 | // Convert the nested-name-specifier into a type. |
66 | QualType Type; |
67 | switch (NNS->getKind()) { |
68 | case NestedNameSpecifier::TypeSpec: |
69 | case NestedNameSpecifier::TypeSpecWithTemplate: |
70 | Type = QualType(NNS->getAsType(), 0); |
71 | break; |
72 | |
73 | case NestedNameSpecifier::Identifier: |
74 | // Strip off the last layer of the nested-name-specifier and build a |
75 | // typename type for it. |
76 | assert(NNS->getAsIdentifier() == &Name && "not a constructor name" ); |
77 | Type = Context.getDependentNameType( |
78 | Keyword: ElaboratedTypeKeyword::None, NNS: NNS->getPrefix(), Name: NNS->getAsIdentifier()); |
79 | break; |
80 | |
81 | case NestedNameSpecifier::Global: |
82 | case NestedNameSpecifier::Super: |
83 | case NestedNameSpecifier::Namespace: |
84 | case NestedNameSpecifier::NamespaceAlias: |
85 | llvm_unreachable("Nested name specifier is not a type for inheriting ctor" ); |
86 | } |
87 | |
88 | // This reference to the type is located entirely at the location of the |
89 | // final identifier in the qualified-id. |
90 | return CreateParsedType(T: Type, |
91 | TInfo: Context.getTrivialTypeSourceInfo(T: Type, Loc: NameLoc)); |
92 | } |
93 | |
94 | ParsedType Sema::getConstructorName(const IdentifierInfo &II, |
95 | SourceLocation NameLoc, Scope *S, |
96 | CXXScopeSpec &SS, bool EnteringContext) { |
97 | CXXRecordDecl *CurClass = getCurrentClass(S, SS: &SS); |
98 | assert(CurClass && &II == CurClass->getIdentifier() && |
99 | "not a constructor name" ); |
100 | |
101 | // When naming a constructor as a member of a dependent context (eg, in a |
102 | // friend declaration or an inherited constructor declaration), form an |
103 | // unresolved "typename" type. |
104 | if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) { |
105 | QualType T = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None, |
106 | NNS: SS.getScopeRep(), Name: &II); |
107 | return ParsedType::make(P: T); |
108 | } |
109 | |
110 | if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass)) |
111 | return ParsedType(); |
112 | |
113 | // Find the injected-class-name declaration. Note that we make no attempt to |
114 | // diagnose cases where the injected-class-name is shadowed: the only |
115 | // declaration that can validly shadow the injected-class-name is a |
116 | // non-static data member, and if the class contains both a non-static data |
117 | // member and a constructor then it is ill-formed (we check that in |
118 | // CheckCompletedCXXClass). |
119 | CXXRecordDecl *InjectedClassName = nullptr; |
120 | for (NamedDecl *ND : CurClass->lookup(&II)) { |
121 | auto *RD = dyn_cast<CXXRecordDecl>(ND); |
122 | if (RD && RD->isInjectedClassName()) { |
123 | InjectedClassName = RD; |
124 | break; |
125 | } |
126 | } |
127 | if (!InjectedClassName) { |
128 | if (!CurClass->isInvalidDecl()) { |
129 | // FIXME: RequireCompleteDeclContext doesn't check dependent contexts |
130 | // properly. Work around it here for now. |
131 | Diag(SS.getLastQualifierNameLoc(), |
132 | diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange(); |
133 | } |
134 | return ParsedType(); |
135 | } |
136 | |
137 | QualType T = Context.getTypeDeclType(InjectedClassName); |
138 | DiagnoseUseOfDecl(InjectedClassName, NameLoc); |
139 | MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false); |
140 | |
141 | return ParsedType::make(P: T); |
142 | } |
143 | |
144 | ParsedType Sema::getDestructorName(const IdentifierInfo &II, |
145 | SourceLocation NameLoc, Scope *S, |
146 | CXXScopeSpec &SS, ParsedType ObjectTypePtr, |
147 | bool EnteringContext) { |
148 | // Determine where to perform name lookup. |
149 | |
150 | // FIXME: This area of the standard is very messy, and the current |
151 | // wording is rather unclear about which scopes we search for the |
152 | // destructor name; see core issues 399 and 555. Issue 399 in |
153 | // particular shows where the current description of destructor name |
154 | // lookup is completely out of line with existing practice, e.g., |
155 | // this appears to be ill-formed: |
156 | // |
157 | // namespace N { |
158 | // template <typename T> struct S { |
159 | // ~S(); |
160 | // }; |
161 | // } |
162 | // |
163 | // void f(N::S<int>* s) { |
164 | // s->N::S<int>::~S(); |
165 | // } |
166 | // |
167 | // See also PR6358 and PR6359. |
168 | // |
169 | // For now, we accept all the cases in which the name given could plausibly |
170 | // be interpreted as a correct destructor name, issuing off-by-default |
171 | // extension diagnostics on the cases that don't strictly conform to the |
172 | // C++20 rules. This basically means we always consider looking in the |
173 | // nested-name-specifier prefix, the complete nested-name-specifier, and |
174 | // the scope, and accept if we find the expected type in any of the three |
175 | // places. |
176 | |
177 | if (SS.isInvalid()) |
178 | return nullptr; |
179 | |
180 | // Whether we've failed with a diagnostic already. |
181 | bool Failed = false; |
182 | |
183 | llvm::SmallVector<NamedDecl*, 8> FoundDecls; |
184 | llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 8> FoundDeclSet; |
185 | |
186 | // If we have an object type, it's because we are in a |
187 | // pseudo-destructor-expression or a member access expression, and |
188 | // we know what type we're looking for. |
189 | QualType SearchType = |
190 | ObjectTypePtr ? GetTypeFromParser(Ty: ObjectTypePtr) : QualType(); |
191 | |
192 | auto CheckLookupResult = [&](LookupResult &Found) -> ParsedType { |
193 | auto IsAcceptableResult = [&](NamedDecl *D) -> bool { |
194 | auto *Type = dyn_cast<TypeDecl>(Val: D->getUnderlyingDecl()); |
195 | if (!Type) |
196 | return false; |
197 | |
198 | if (SearchType.isNull() || SearchType->isDependentType()) |
199 | return true; |
200 | |
201 | QualType T = Context.getTypeDeclType(Decl: Type); |
202 | return Context.hasSameUnqualifiedType(T1: T, T2: SearchType); |
203 | }; |
204 | |
205 | unsigned NumAcceptableResults = 0; |
206 | for (NamedDecl *D : Found) { |
207 | if (IsAcceptableResult(D)) |
208 | ++NumAcceptableResults; |
209 | |
210 | // Don't list a class twice in the lookup failure diagnostic if it's |
211 | // found by both its injected-class-name and by the name in the enclosing |
212 | // scope. |
213 | if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) |
214 | if (RD->isInjectedClassName()) |
215 | D = cast<NamedDecl>(RD->getParent()); |
216 | |
217 | if (FoundDeclSet.insert(D).second) |
218 | FoundDecls.push_back(Elt: D); |
219 | } |
220 | |
221 | // As an extension, attempt to "fix" an ambiguity by erasing all non-type |
222 | // results, and all non-matching results if we have a search type. It's not |
223 | // clear what the right behavior is if destructor lookup hits an ambiguity, |
224 | // but other compilers do generally accept at least some kinds of |
225 | // ambiguity. |
226 | if (Found.isAmbiguous() && NumAcceptableResults == 1) { |
227 | Diag(NameLoc, diag::ext_dtor_name_ambiguous); |
228 | LookupResult::Filter F = Found.makeFilter(); |
229 | while (F.hasNext()) { |
230 | NamedDecl *D = F.next(); |
231 | if (auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl())) |
232 | Diag(D->getLocation(), diag::note_destructor_type_here) |
233 | << Context.getTypeDeclType(TD); |
234 | else |
235 | Diag(D->getLocation(), diag::note_destructor_nontype_here); |
236 | |
237 | if (!IsAcceptableResult(D)) |
238 | F.erase(); |
239 | } |
240 | F.done(); |
241 | } |
242 | |
243 | if (Found.isAmbiguous()) |
244 | Failed = true; |
245 | |
246 | if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) { |
247 | if (IsAcceptableResult(Type)) { |
248 | QualType T = Context.getTypeDeclType(Decl: Type); |
249 | MarkAnyDeclReferenced(Loc: Type->getLocation(), D: Type, /*OdrUse=*/MightBeOdrUse: false); |
250 | return CreateParsedType( |
251 | T: Context.getElaboratedType(Keyword: ElaboratedTypeKeyword::None, NNS: nullptr, NamedType: T), |
252 | TInfo: Context.getTrivialTypeSourceInfo(T, Loc: NameLoc)); |
253 | } |
254 | } |
255 | |
256 | return nullptr; |
257 | }; |
258 | |
259 | bool IsDependent = false; |
260 | |
261 | auto LookupInObjectType = [&]() -> ParsedType { |
262 | if (Failed || SearchType.isNull()) |
263 | return nullptr; |
264 | |
265 | IsDependent |= SearchType->isDependentType(); |
266 | |
267 | LookupResult Found(*this, &II, NameLoc, LookupDestructorName); |
268 | DeclContext *LookupCtx = computeDeclContext(T: SearchType); |
269 | if (!LookupCtx) |
270 | return nullptr; |
271 | LookupQualifiedName(R&: Found, LookupCtx); |
272 | return CheckLookupResult(Found); |
273 | }; |
274 | |
275 | auto LookupInNestedNameSpec = [&](CXXScopeSpec &LookupSS) -> ParsedType { |
276 | if (Failed) |
277 | return nullptr; |
278 | |
279 | IsDependent |= isDependentScopeSpecifier(SS: LookupSS); |
280 | DeclContext *LookupCtx = computeDeclContext(SS: LookupSS, EnteringContext); |
281 | if (!LookupCtx) |
282 | return nullptr; |
283 | |
284 | LookupResult Found(*this, &II, NameLoc, LookupDestructorName); |
285 | if (RequireCompleteDeclContext(SS&: LookupSS, DC: LookupCtx)) { |
286 | Failed = true; |
287 | return nullptr; |
288 | } |
289 | LookupQualifiedName(R&: Found, LookupCtx); |
290 | return CheckLookupResult(Found); |
291 | }; |
292 | |
293 | auto LookupInScope = [&]() -> ParsedType { |
294 | if (Failed || !S) |
295 | return nullptr; |
296 | |
297 | LookupResult Found(*this, &II, NameLoc, LookupDestructorName); |
298 | LookupName(R&: Found, S); |
299 | return CheckLookupResult(Found); |
300 | }; |
301 | |
302 | // C++2a [basic.lookup.qual]p6: |
303 | // In a qualified-id of the form |
304 | // |
305 | // nested-name-specifier[opt] type-name :: ~ type-name |
306 | // |
307 | // the second type-name is looked up in the same scope as the first. |
308 | // |
309 | // We interpret this as meaning that if you do a dual-scope lookup for the |
310 | // first name, you also do a dual-scope lookup for the second name, per |
311 | // C++ [basic.lookup.classref]p4: |
312 | // |
313 | // If the id-expression in a class member access is a qualified-id of the |
314 | // form |
315 | // |
316 | // class-name-or-namespace-name :: ... |
317 | // |
318 | // the class-name-or-namespace-name following the . or -> is first looked |
319 | // up in the class of the object expression and the name, if found, is used. |
320 | // Otherwise, it is looked up in the context of the entire |
321 | // postfix-expression. |
322 | // |
323 | // This looks in the same scopes as for an unqualified destructor name: |
324 | // |
325 | // C++ [basic.lookup.classref]p3: |
326 | // If the unqualified-id is ~ type-name, the type-name is looked up |
327 | // in the context of the entire postfix-expression. If the type T |
328 | // of the object expression is of a class type C, the type-name is |
329 | // also looked up in the scope of class C. At least one of the |
330 | // lookups shall find a name that refers to cv T. |
331 | // |
332 | // FIXME: The intent is unclear here. Should type-name::~type-name look in |
333 | // the scope anyway if it finds a non-matching name declared in the class? |
334 | // If both lookups succeed and find a dependent result, which result should |
335 | // we retain? (Same question for p->~type-name().) |
336 | |
337 | if (NestedNameSpecifier *Prefix = |
338 | SS.isSet() ? SS.getScopeRep()->getPrefix() : nullptr) { |
339 | // This is |
340 | // |
341 | // nested-name-specifier type-name :: ~ type-name |
342 | // |
343 | // Look for the second type-name in the nested-name-specifier. |
344 | CXXScopeSpec PrefixSS; |
345 | PrefixSS.Adopt(Other: NestedNameSpecifierLoc(Prefix, SS.location_data())); |
346 | if (ParsedType T = LookupInNestedNameSpec(PrefixSS)) |
347 | return T; |
348 | } else { |
349 | // This is one of |
350 | // |
351 | // type-name :: ~ type-name |
352 | // ~ type-name |
353 | // |
354 | // Look in the scope and (if any) the object type. |
355 | if (ParsedType T = LookupInScope()) |
356 | return T; |
357 | if (ParsedType T = LookupInObjectType()) |
358 | return T; |
359 | } |
360 | |
361 | if (Failed) |
362 | return nullptr; |
363 | |
364 | if (IsDependent) { |
365 | // We didn't find our type, but that's OK: it's dependent anyway. |
366 | |
367 | // FIXME: What if we have no nested-name-specifier? |
368 | QualType T = |
369 | CheckTypenameType(Keyword: ElaboratedTypeKeyword::None, KeywordLoc: SourceLocation(), |
370 | QualifierLoc: SS.getWithLocInContext(Context), II, IILoc: NameLoc); |
371 | return ParsedType::make(P: T); |
372 | } |
373 | |
374 | // The remaining cases are all non-standard extensions imitating the behavior |
375 | // of various other compilers. |
376 | unsigned NumNonExtensionDecls = FoundDecls.size(); |
377 | |
378 | if (SS.isSet()) { |
379 | // For compatibility with older broken C++ rules and existing code, |
380 | // |
381 | // nested-name-specifier :: ~ type-name |
382 | // |
383 | // also looks for type-name within the nested-name-specifier. |
384 | if (ParsedType T = LookupInNestedNameSpec(SS)) { |
385 | Diag(SS.getEndLoc(), diag::ext_dtor_named_in_wrong_scope) |
386 | << SS.getRange() |
387 | << FixItHint::CreateInsertion(SS.getEndLoc(), |
388 | ("::" + II.getName()).str()); |
389 | return T; |
390 | } |
391 | |
392 | // For compatibility with other compilers and older versions of Clang, |
393 | // |
394 | // nested-name-specifier type-name :: ~ type-name |
395 | // |
396 | // also looks for type-name in the scope. Unfortunately, we can't |
397 | // reasonably apply this fallback for dependent nested-name-specifiers. |
398 | if (SS.isValid() && SS.getScopeRep()->getPrefix()) { |
399 | if (ParsedType T = LookupInScope()) { |
400 | Diag(SS.getEndLoc(), diag::ext_qualified_dtor_named_in_lexical_scope) |
401 | << FixItHint::CreateRemoval(SS.getRange()); |
402 | Diag(FoundDecls.back()->getLocation(), diag::note_destructor_type_here) |
403 | << GetTypeFromParser(T); |
404 | return T; |
405 | } |
406 | } |
407 | } |
408 | |
409 | // We didn't find anything matching; tell the user what we did find (if |
410 | // anything). |
411 | |
412 | // Don't tell the user about declarations we shouldn't have found. |
413 | FoundDecls.resize(N: NumNonExtensionDecls); |
414 | |
415 | // List types before non-types. |
416 | std::stable_sort(first: FoundDecls.begin(), last: FoundDecls.end(), |
417 | comp: [](NamedDecl *A, NamedDecl *B) { |
418 | return isa<TypeDecl>(Val: A->getUnderlyingDecl()) > |
419 | isa<TypeDecl>(Val: B->getUnderlyingDecl()); |
420 | }); |
421 | |
422 | // Suggest a fixit to properly name the destroyed type. |
423 | auto MakeFixItHint = [&]{ |
424 | const CXXRecordDecl *Destroyed = nullptr; |
425 | // FIXME: If we have a scope specifier, suggest its last component? |
426 | if (!SearchType.isNull()) |
427 | Destroyed = SearchType->getAsCXXRecordDecl(); |
428 | else if (S) |
429 | Destroyed = dyn_cast_or_null<CXXRecordDecl>(Val: S->getEntity()); |
430 | if (Destroyed) |
431 | return FixItHint::CreateReplacement(SourceRange(NameLoc), |
432 | Destroyed->getNameAsString()); |
433 | return FixItHint(); |
434 | }; |
435 | |
436 | if (FoundDecls.empty()) { |
437 | // FIXME: Attempt typo-correction? |
438 | Diag(NameLoc, diag::err_undeclared_destructor_name) |
439 | << &II << MakeFixItHint(); |
440 | } else if (!SearchType.isNull() && FoundDecls.size() == 1) { |
441 | if (auto *TD = dyn_cast<TypeDecl>(Val: FoundDecls[0]->getUnderlyingDecl())) { |
442 | assert(!SearchType.isNull() && |
443 | "should only reject a type result if we have a search type" ); |
444 | QualType T = Context.getTypeDeclType(Decl: TD); |
445 | Diag(NameLoc, diag::err_destructor_expr_type_mismatch) |
446 | << T << SearchType << MakeFixItHint(); |
447 | } else { |
448 | Diag(NameLoc, diag::err_destructor_expr_nontype) |
449 | << &II << MakeFixItHint(); |
450 | } |
451 | } else { |
452 | Diag(NameLoc, SearchType.isNull() ? diag::err_destructor_name_nontype |
453 | : diag::err_destructor_expr_mismatch) |
454 | << &II << SearchType << MakeFixItHint(); |
455 | } |
456 | |
457 | for (NamedDecl *FoundD : FoundDecls) { |
458 | if (auto *TD = dyn_cast<TypeDecl>(FoundD->getUnderlyingDecl())) |
459 | Diag(FoundD->getLocation(), diag::note_destructor_type_here) |
460 | << Context.getTypeDeclType(TD); |
461 | else |
462 | Diag(FoundD->getLocation(), diag::note_destructor_nontype_here) |
463 | << FoundD; |
464 | } |
465 | |
466 | return nullptr; |
467 | } |
468 | |
469 | ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS, |
470 | ParsedType ObjectType) { |
471 | if (DS.getTypeSpecType() == DeclSpec::TST_error) |
472 | return nullptr; |
473 | |
474 | if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) { |
475 | Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); |
476 | return nullptr; |
477 | } |
478 | |
479 | assert(DS.getTypeSpecType() == DeclSpec::TST_decltype && |
480 | "unexpected type in getDestructorType" ); |
481 | QualType T = BuildDecltypeType(E: DS.getRepAsExpr()); |
482 | |
483 | // If we know the type of the object, check that the correct destructor |
484 | // type was named now; we can give better diagnostics this way. |
485 | QualType SearchType = GetTypeFromParser(Ty: ObjectType); |
486 | if (!SearchType.isNull() && !SearchType->isDependentType() && |
487 | !Context.hasSameUnqualifiedType(T1: T, T2: SearchType)) { |
488 | Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch) |
489 | << T << SearchType; |
490 | return nullptr; |
491 | } |
492 | |
493 | return ParsedType::make(P: T); |
494 | } |
495 | |
496 | bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS, |
497 | const UnqualifiedId &Name, bool IsUDSuffix) { |
498 | assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId); |
499 | if (!IsUDSuffix) { |
500 | // [over.literal] p8 |
501 | // |
502 | // double operator""_Bq(long double); // OK: not a reserved identifier |
503 | // double operator"" _Bq(long double); // ill-formed, no diagnostic required |
504 | const IdentifierInfo *II = Name.Identifier; |
505 | ReservedIdentifierStatus Status = II->isReserved(LangOpts: PP.getLangOpts()); |
506 | SourceLocation Loc = Name.getEndLoc(); |
507 | if (!PP.getSourceManager().isInSystemHeader(Loc)) { |
508 | if (auto Hint = FixItHint::CreateReplacement( |
509 | RemoveRange: Name.getSourceRange(), |
510 | Code: (StringRef("operator\"\"" ) + II->getName()).str()); |
511 | isReservedInAllContexts(Status)) { |
512 | Diag(Loc, diag::warn_reserved_extern_symbol) |
513 | << II << static_cast<int>(Status) << Hint; |
514 | } else { |
515 | Diag(Loc, diag::warn_deprecated_literal_operator_id) << II << Hint; |
516 | } |
517 | } |
518 | } |
519 | |
520 | if (!SS.isValid()) |
521 | return false; |
522 | |
523 | switch (SS.getScopeRep()->getKind()) { |
524 | case NestedNameSpecifier::Identifier: |
525 | case NestedNameSpecifier::TypeSpec: |
526 | case NestedNameSpecifier::TypeSpecWithTemplate: |
527 | // Per C++11 [over.literal]p2, literal operators can only be declared at |
528 | // namespace scope. Therefore, this unqualified-id cannot name anything. |
529 | // Reject it early, because we have no AST representation for this in the |
530 | // case where the scope is dependent. |
531 | Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace) |
532 | << SS.getScopeRep(); |
533 | return true; |
534 | |
535 | case NestedNameSpecifier::Global: |
536 | case NestedNameSpecifier::Super: |
537 | case NestedNameSpecifier::Namespace: |
538 | case NestedNameSpecifier::NamespaceAlias: |
539 | return false; |
540 | } |
541 | |
542 | llvm_unreachable("unknown nested name specifier kind" ); |
543 | } |
544 | |
545 | /// Build a C++ typeid expression with a type operand. |
546 | ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, |
547 | SourceLocation TypeidLoc, |
548 | TypeSourceInfo *Operand, |
549 | SourceLocation RParenLoc) { |
550 | // C++ [expr.typeid]p4: |
551 | // The top-level cv-qualifiers of the lvalue expression or the type-id |
552 | // that is the operand of typeid are always ignored. |
553 | // If the type of the type-id is a class type or a reference to a class |
554 | // type, the class shall be completely-defined. |
555 | Qualifiers Quals; |
556 | QualType T |
557 | = Context.getUnqualifiedArrayType(T: Operand->getType().getNonReferenceType(), |
558 | Quals); |
559 | if (T->getAs<RecordType>() && |
560 | RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) |
561 | return ExprError(); |
562 | |
563 | if (T->isVariablyModifiedType()) |
564 | return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T); |
565 | |
566 | if (CheckQualifiedFunctionForTypeId(T, Loc: TypeidLoc)) |
567 | return ExprError(); |
568 | |
569 | return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand, |
570 | SourceRange(TypeidLoc, RParenLoc)); |
571 | } |
572 | |
573 | /// Build a C++ typeid expression with an expression operand. |
574 | ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, |
575 | SourceLocation TypeidLoc, |
576 | Expr *E, |
577 | SourceLocation RParenLoc) { |
578 | bool WasEvaluated = false; |
579 | if (E && !E->isTypeDependent()) { |
580 | if (E->hasPlaceholderType()) { |
581 | ExprResult result = CheckPlaceholderExpr(E); |
582 | if (result.isInvalid()) return ExprError(); |
583 | E = result.get(); |
584 | } |
585 | |
586 | QualType T = E->getType(); |
587 | if (const RecordType *RecordT = T->getAs<RecordType>()) { |
588 | CXXRecordDecl *RecordD = cast<CXXRecordDecl>(Val: RecordT->getDecl()); |
589 | // C++ [expr.typeid]p3: |
590 | // [...] If the type of the expression is a class type, the class |
591 | // shall be completely-defined. |
592 | if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) |
593 | return ExprError(); |
594 | |
595 | // C++ [expr.typeid]p3: |
596 | // When typeid is applied to an expression other than an glvalue of a |
597 | // polymorphic class type [...] [the] expression is an unevaluated |
598 | // operand. [...] |
599 | if (RecordD->isPolymorphic() && E->isGLValue()) { |
600 | if (isUnevaluatedContext()) { |
601 | // The operand was processed in unevaluated context, switch the |
602 | // context and recheck the subexpression. |
603 | ExprResult Result = TransformToPotentiallyEvaluated(E); |
604 | if (Result.isInvalid()) |
605 | return ExprError(); |
606 | E = Result.get(); |
607 | } |
608 | |
609 | // We require a vtable to query the type at run time. |
610 | MarkVTableUsed(Loc: TypeidLoc, Class: RecordD); |
611 | WasEvaluated = true; |
612 | } |
613 | } |
614 | |
615 | ExprResult Result = CheckUnevaluatedOperand(E); |
616 | if (Result.isInvalid()) |
617 | return ExprError(); |
618 | E = Result.get(); |
619 | |
620 | // C++ [expr.typeid]p4: |
621 | // [...] If the type of the type-id is a reference to a possibly |
622 | // cv-qualified type, the result of the typeid expression refers to a |
623 | // std::type_info object representing the cv-unqualified referenced |
624 | // type. |
625 | Qualifiers Quals; |
626 | QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals); |
627 | if (!Context.hasSameType(T1: T, T2: UnqualT)) { |
628 | T = UnqualT; |
629 | E = ImpCastExprToType(E, Type: UnqualT, CK: CK_NoOp, VK: E->getValueKind()).get(); |
630 | } |
631 | } |
632 | |
633 | if (E->getType()->isVariablyModifiedType()) |
634 | return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) |
635 | << E->getType()); |
636 | else if (!inTemplateInstantiation() && |
637 | E->HasSideEffects(Ctx: Context, IncludePossibleEffects: WasEvaluated)) { |
638 | // The expression operand for typeid is in an unevaluated expression |
639 | // context, so side effects could result in unintended consequences. |
640 | Diag(E->getExprLoc(), WasEvaluated |
641 | ? diag::warn_side_effects_typeid |
642 | : diag::warn_side_effects_unevaluated_context); |
643 | } |
644 | |
645 | return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E, |
646 | SourceRange(TypeidLoc, RParenLoc)); |
647 | } |
648 | |
649 | /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression); |
650 | ExprResult |
651 | Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, |
652 | bool isType, void *TyOrExpr, SourceLocation RParenLoc) { |
653 | // typeid is not supported in OpenCL. |
654 | if (getLangOpts().OpenCLCPlusPlus) { |
655 | return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported) |
656 | << "typeid" ); |
657 | } |
658 | |
659 | // Find the std::type_info type. |
660 | if (!getStdNamespace()) |
661 | return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); |
662 | |
663 | if (!CXXTypeInfoDecl) { |
664 | IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get(Name: "type_info" ); |
665 | LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName); |
666 | LookupQualifiedName(R, getStdNamespace()); |
667 | CXXTypeInfoDecl = R.getAsSingle<RecordDecl>(); |
668 | // Microsoft's typeinfo doesn't have type_info in std but in the global |
669 | // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153. |
670 | if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) { |
671 | LookupQualifiedName(R, Context.getTranslationUnitDecl()); |
672 | CXXTypeInfoDecl = R.getAsSingle<RecordDecl>(); |
673 | } |
674 | if (!CXXTypeInfoDecl) |
675 | return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); |
676 | } |
677 | |
678 | if (!getLangOpts().RTTI) { |
679 | return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti)); |
680 | } |
681 | |
682 | QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl); |
683 | |
684 | if (isType) { |
685 | // The operand is a type; handle it as such. |
686 | TypeSourceInfo *TInfo = nullptr; |
687 | QualType T = GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: TyOrExpr), |
688 | TInfo: &TInfo); |
689 | if (T.isNull()) |
690 | return ExprError(); |
691 | |
692 | if (!TInfo) |
693 | TInfo = Context.getTrivialTypeSourceInfo(T, Loc: OpLoc); |
694 | |
695 | return BuildCXXTypeId(TypeInfoType, TypeidLoc: OpLoc, Operand: TInfo, RParenLoc); |
696 | } |
697 | |
698 | // The operand is an expression. |
699 | ExprResult Result = |
700 | BuildCXXTypeId(TypeInfoType, TypeidLoc: OpLoc, E: (Expr *)TyOrExpr, RParenLoc); |
701 | |
702 | if (!getLangOpts().RTTIData && !Result.isInvalid()) |
703 | if (auto *CTE = dyn_cast<CXXTypeidExpr>(Result.get())) |
704 | if (CTE->isPotentiallyEvaluated() && !CTE->isMostDerived(Context)) |
705 | Diag(OpLoc, diag::warn_no_typeid_with_rtti_disabled) |
706 | << (getDiagnostics().getDiagnosticOptions().getFormat() == |
707 | DiagnosticOptions::MSVC); |
708 | return Result; |
709 | } |
710 | |
711 | /// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to |
712 | /// a single GUID. |
713 | static void |
714 | getUuidAttrOfType(Sema &SemaRef, QualType QT, |
715 | llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) { |
716 | // Optionally remove one level of pointer, reference or array indirection. |
717 | const Type *Ty = QT.getTypePtr(); |
718 | if (QT->isPointerType() || QT->isReferenceType()) |
719 | Ty = QT->getPointeeType().getTypePtr(); |
720 | else if (QT->isArrayType()) |
721 | Ty = Ty->getBaseElementTypeUnsafe(); |
722 | |
723 | const auto *TD = Ty->getAsTagDecl(); |
724 | if (!TD) |
725 | return; |
726 | |
727 | if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) { |
728 | UuidAttrs.insert(Uuid); |
729 | return; |
730 | } |
731 | |
732 | // __uuidof can grab UUIDs from template arguments. |
733 | if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: TD)) { |
734 | const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); |
735 | for (const TemplateArgument &TA : TAL.asArray()) { |
736 | const UuidAttr *UuidForTA = nullptr; |
737 | if (TA.getKind() == TemplateArgument::Type) |
738 | getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs); |
739 | else if (TA.getKind() == TemplateArgument::Declaration) |
740 | getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs); |
741 | |
742 | if (UuidForTA) |
743 | UuidAttrs.insert(UuidForTA); |
744 | } |
745 | } |
746 | } |
747 | |
748 | /// Build a Microsoft __uuidof expression with a type operand. |
749 | ExprResult Sema::BuildCXXUuidof(QualType Type, |
750 | SourceLocation TypeidLoc, |
751 | TypeSourceInfo *Operand, |
752 | SourceLocation RParenLoc) { |
753 | MSGuidDecl *Guid = nullptr; |
754 | if (!Operand->getType()->isDependentType()) { |
755 | llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs; |
756 | getUuidAttrOfType(*this, Operand->getType(), UuidAttrs); |
757 | if (UuidAttrs.empty()) |
758 | return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid)); |
759 | if (UuidAttrs.size() > 1) |
760 | return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids)); |
761 | Guid = UuidAttrs.back()->getGuidDecl(); |
762 | } |
763 | |
764 | return new (Context) |
765 | CXXUuidofExpr(Type, Operand, Guid, SourceRange(TypeidLoc, RParenLoc)); |
766 | } |
767 | |
768 | /// Build a Microsoft __uuidof expression with an expression operand. |
769 | ExprResult Sema::BuildCXXUuidof(QualType Type, SourceLocation TypeidLoc, |
770 | Expr *E, SourceLocation RParenLoc) { |
771 | MSGuidDecl *Guid = nullptr; |
772 | if (!E->getType()->isDependentType()) { |
773 | if (E->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull)) { |
774 | // A null pointer results in {00000000-0000-0000-0000-000000000000}. |
775 | Guid = Context.getMSGuidDecl(Parts: MSGuidDecl::Parts{}); |
776 | } else { |
777 | llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs; |
778 | getUuidAttrOfType(*this, E->getType(), UuidAttrs); |
779 | if (UuidAttrs.empty()) |
780 | return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid)); |
781 | if (UuidAttrs.size() > 1) |
782 | return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids)); |
783 | Guid = UuidAttrs.back()->getGuidDecl(); |
784 | } |
785 | } |
786 | |
787 | return new (Context) |
788 | CXXUuidofExpr(Type, E, Guid, SourceRange(TypeidLoc, RParenLoc)); |
789 | } |
790 | |
791 | /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression); |
792 | ExprResult |
793 | Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, |
794 | bool isType, void *TyOrExpr, SourceLocation RParenLoc) { |
795 | QualType GuidType = Context.getMSGuidType(); |
796 | GuidType.addConst(); |
797 | |
798 | if (isType) { |
799 | // The operand is a type; handle it as such. |
800 | TypeSourceInfo *TInfo = nullptr; |
801 | QualType T = GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: TyOrExpr), |
802 | TInfo: &TInfo); |
803 | if (T.isNull()) |
804 | return ExprError(); |
805 | |
806 | if (!TInfo) |
807 | TInfo = Context.getTrivialTypeSourceInfo(T, Loc: OpLoc); |
808 | |
809 | return BuildCXXUuidof(Type: GuidType, TypeidLoc: OpLoc, Operand: TInfo, RParenLoc); |
810 | } |
811 | |
812 | // The operand is an expression. |
813 | return BuildCXXUuidof(Type: GuidType, TypeidLoc: OpLoc, E: (Expr*)TyOrExpr, RParenLoc); |
814 | } |
815 | |
816 | /// ActOnCXXBoolLiteral - Parse {true,false} literals. |
817 | ExprResult |
818 | Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { |
819 | assert((Kind == tok::kw_true || Kind == tok::kw_false) && |
820 | "Unknown C++ Boolean value!" ); |
821 | return new (Context) |
822 | CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc); |
823 | } |
824 | |
825 | /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. |
826 | ExprResult |
827 | Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) { |
828 | return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc); |
829 | } |
830 | |
831 | /// ActOnCXXThrow - Parse throw expressions. |
832 | ExprResult |
833 | Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) { |
834 | bool IsThrownVarInScope = false; |
835 | if (Ex) { |
836 | // C++0x [class.copymove]p31: |
837 | // When certain criteria are met, an implementation is allowed to omit the |
838 | // copy/move construction of a class object [...] |
839 | // |
840 | // - in a throw-expression, when the operand is the name of a |
841 | // non-volatile automatic object (other than a function or catch- |
842 | // clause parameter) whose scope does not extend beyond the end of the |
843 | // innermost enclosing try-block (if there is one), the copy/move |
844 | // operation from the operand to the exception object (15.1) can be |
845 | // omitted by constructing the automatic object directly into the |
846 | // exception object |
847 | if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: Ex->IgnoreParens())) |
848 | if (const auto *Var = dyn_cast<VarDecl>(Val: DRE->getDecl()); |
849 | Var && Var->hasLocalStorage() && |
850 | !Var->getType().isVolatileQualified()) { |
851 | for (; S; S = S->getParent()) { |
852 | if (S->isDeclScope(Var)) { |
853 | IsThrownVarInScope = true; |
854 | break; |
855 | } |
856 | |
857 | // FIXME: Many of the scope checks here seem incorrect. |
858 | if (S->getFlags() & |
859 | (Scope::FnScope | Scope::ClassScope | Scope::BlockScope | |
860 | Scope::ObjCMethodScope | Scope::TryScope)) |
861 | break; |
862 | } |
863 | } |
864 | } |
865 | |
866 | return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope); |
867 | } |
868 | |
869 | ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, |
870 | bool IsThrownVarInScope) { |
871 | const llvm::Triple &T = Context.getTargetInfo().getTriple(); |
872 | const bool IsOpenMPGPUTarget = |
873 | getLangOpts().OpenMPIsTargetDevice && (T.isNVPTX() || T.isAMDGCN()); |
874 | // Don't report an error if 'throw' is used in system headers or in an OpenMP |
875 | // target region compiled for a GPU architecture. |
876 | if (!IsOpenMPGPUTarget && !getLangOpts().CXXExceptions && |
877 | !getSourceManager().isInSystemHeader(Loc: OpLoc) && !getLangOpts().CUDA) { |
878 | // Delay error emission for the OpenMP device code. |
879 | targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw" ; |
880 | } |
881 | |
882 | // In OpenMP target regions, we replace 'throw' with a trap on GPU targets. |
883 | if (IsOpenMPGPUTarget) |
884 | targetDiag(OpLoc, diag::warn_throw_not_valid_on_target) << T.str(); |
885 | |
886 | // Exceptions aren't allowed in CUDA device code. |
887 | if (getLangOpts().CUDA) |
888 | CUDA().DiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions) |
889 | << "throw" << llvm::to_underlying(CUDA().CurrentTarget()); |
890 | |
891 | if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope()) |
892 | Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw" ; |
893 | |
894 | // Exceptions that escape a compute construct are ill-formed. |
895 | if (getLangOpts().OpenACC && getCurScope() && |
896 | getCurScope()->isInOpenACCComputeConstructScope(Scope::TryScope)) |
897 | Diag(OpLoc, diag::err_acc_branch_in_out_compute_construct) |
898 | << /*throw*/ 2 << /*out of*/ 0; |
899 | |
900 | if (Ex && !Ex->isTypeDependent()) { |
901 | // Initialize the exception result. This implicitly weeds out |
902 | // abstract types or types with inaccessible copy constructors. |
903 | |
904 | // C++0x [class.copymove]p31: |
905 | // When certain criteria are met, an implementation is allowed to omit the |
906 | // copy/move construction of a class object [...] |
907 | // |
908 | // - in a throw-expression, when the operand is the name of a |
909 | // non-volatile automatic object (other than a function or |
910 | // catch-clause |
911 | // parameter) whose scope does not extend beyond the end of the |
912 | // innermost enclosing try-block (if there is one), the copy/move |
913 | // operation from the operand to the exception object (15.1) can be |
914 | // omitted by constructing the automatic object directly into the |
915 | // exception object |
916 | NamedReturnInfo NRInfo = |
917 | IsThrownVarInScope ? getNamedReturnInfo(E&: Ex) : NamedReturnInfo(); |
918 | |
919 | QualType ExceptionObjectTy = Context.getExceptionObjectType(T: Ex->getType()); |
920 | if (CheckCXXThrowOperand(ThrowLoc: OpLoc, ThrowTy: ExceptionObjectTy, E: Ex)) |
921 | return ExprError(); |
922 | |
923 | InitializedEntity Entity = |
924 | InitializedEntity::InitializeException(ThrowLoc: OpLoc, Type: ExceptionObjectTy); |
925 | ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRInfo, Value: Ex); |
926 | if (Res.isInvalid()) |
927 | return ExprError(); |
928 | Ex = Res.get(); |
929 | } |
930 | |
931 | // PPC MMA non-pointer types are not allowed as throw expr types. |
932 | if (Ex && Context.getTargetInfo().getTriple().isPPC64()) |
933 | CheckPPCMMAType(Type: Ex->getType(), TypeLoc: Ex->getBeginLoc()); |
934 | |
935 | return new (Context) |
936 | CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope); |
937 | } |
938 | |
939 | static void |
940 | collectPublicBases(CXXRecordDecl *RD, |
941 | llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen, |
942 | llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases, |
943 | llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen, |
944 | bool ParentIsPublic) { |
945 | for (const CXXBaseSpecifier &BS : RD->bases()) { |
946 | CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); |
947 | bool NewSubobject; |
948 | // Virtual bases constitute the same subobject. Non-virtual bases are |
949 | // always distinct subobjects. |
950 | if (BS.isVirtual()) |
951 | NewSubobject = VBases.insert(Ptr: BaseDecl).second; |
952 | else |
953 | NewSubobject = true; |
954 | |
955 | if (NewSubobject) |
956 | ++SubobjectsSeen[BaseDecl]; |
957 | |
958 | // Only add subobjects which have public access throughout the entire chain. |
959 | bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public; |
960 | if (PublicPath) |
961 | PublicSubobjectsSeen.insert(X: BaseDecl); |
962 | |
963 | // Recurse on to each base subobject. |
964 | collectPublicBases(RD: BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen, |
965 | ParentIsPublic: PublicPath); |
966 | } |
967 | } |
968 | |
969 | static void getUnambiguousPublicSubobjects( |
970 | CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) { |
971 | llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen; |
972 | llvm::SmallSet<CXXRecordDecl *, 2> VBases; |
973 | llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen; |
974 | SubobjectsSeen[RD] = 1; |
975 | PublicSubobjectsSeen.insert(X: RD); |
976 | collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen, |
977 | /*ParentIsPublic=*/true); |
978 | |
979 | for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) { |
980 | // Skip ambiguous objects. |
981 | if (SubobjectsSeen[PublicSubobject] > 1) |
982 | continue; |
983 | |
984 | Objects.push_back(Elt: PublicSubobject); |
985 | } |
986 | } |
987 | |
988 | /// CheckCXXThrowOperand - Validate the operand of a throw. |
989 | bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, |
990 | QualType ExceptionObjectTy, Expr *E) { |
991 | // If the type of the exception would be an incomplete type or a pointer |
992 | // to an incomplete type other than (cv) void the program is ill-formed. |
993 | QualType Ty = ExceptionObjectTy; |
994 | bool isPointer = false; |
995 | if (const PointerType* Ptr = Ty->getAs<PointerType>()) { |
996 | Ty = Ptr->getPointeeType(); |
997 | isPointer = true; |
998 | } |
999 | |
1000 | // Cannot throw WebAssembly reference type. |
1001 | if (Ty.isWebAssemblyReferenceType()) { |
1002 | Diag(ThrowLoc, diag::err_wasm_reftype_tc) << 0 << E->getSourceRange(); |
1003 | return true; |
1004 | } |
1005 | |
1006 | // Cannot throw WebAssembly table. |
1007 | if (isPointer && Ty.isWebAssemblyReferenceType()) { |
1008 | Diag(ThrowLoc, diag::err_wasm_table_art) << 2 << E->getSourceRange(); |
1009 | return true; |
1010 | } |
1011 | |
1012 | if (!isPointer || !Ty->isVoidType()) { |
1013 | if (RequireCompleteType(ThrowLoc, Ty, |
1014 | isPointer ? diag::err_throw_incomplete_ptr |
1015 | : diag::err_throw_incomplete, |
1016 | E->getSourceRange())) |
1017 | return true; |
1018 | |
1019 | if (!isPointer && Ty->isSizelessType()) { |
1020 | Diag(ThrowLoc, diag::err_throw_sizeless) << Ty << E->getSourceRange(); |
1021 | return true; |
1022 | } |
1023 | |
1024 | if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy, |
1025 | diag::err_throw_abstract_type, E)) |
1026 | return true; |
1027 | } |
1028 | |
1029 | // If the exception has class type, we need additional handling. |
1030 | CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); |
1031 | if (!RD) |
1032 | return false; |
1033 | |
1034 | // If we are throwing a polymorphic class type or pointer thereof, |
1035 | // exception handling will make use of the vtable. |
1036 | MarkVTableUsed(Loc: ThrowLoc, Class: RD); |
1037 | |
1038 | // If a pointer is thrown, the referenced object will not be destroyed. |
1039 | if (isPointer) |
1040 | return false; |
1041 | |
1042 | // If the class has a destructor, we must be able to call it. |
1043 | if (!RD->hasIrrelevantDestructor()) { |
1044 | if (CXXDestructorDecl *Destructor = LookupDestructor(Class: RD)) { |
1045 | MarkFunctionReferenced(E->getExprLoc(), Destructor); |
1046 | CheckDestructorAccess(E->getExprLoc(), Destructor, |
1047 | PDiag(diag::err_access_dtor_exception) << Ty); |
1048 | if (DiagnoseUseOfDecl(Destructor, E->getExprLoc())) |
1049 | return true; |
1050 | } |
1051 | } |
1052 | |
1053 | // The MSVC ABI creates a list of all types which can catch the exception |
1054 | // object. This list also references the appropriate copy constructor to call |
1055 | // if the object is caught by value and has a non-trivial copy constructor. |
1056 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { |
1057 | // We are only interested in the public, unambiguous bases contained within |
1058 | // the exception object. Bases which are ambiguous or otherwise |
1059 | // inaccessible are not catchable types. |
1060 | llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects; |
1061 | getUnambiguousPublicSubobjects(RD, Objects&: UnambiguousPublicSubobjects); |
1062 | |
1063 | for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) { |
1064 | // Attempt to lookup the copy constructor. Various pieces of machinery |
1065 | // will spring into action, like template instantiation, which means this |
1066 | // cannot be a simple walk of the class's decls. Instead, we must perform |
1067 | // lookup and overload resolution. |
1068 | CXXConstructorDecl *CD = LookupCopyingConstructor(Class: Subobject, Quals: 0); |
1069 | if (!CD || CD->isDeleted()) |
1070 | continue; |
1071 | |
1072 | // Mark the constructor referenced as it is used by this throw expression. |
1073 | MarkFunctionReferenced(E->getExprLoc(), CD); |
1074 | |
1075 | // Skip this copy constructor if it is trivial, we don't need to record it |
1076 | // in the catchable type data. |
1077 | if (CD->isTrivial()) |
1078 | continue; |
1079 | |
1080 | // The copy constructor is non-trivial, create a mapping from this class |
1081 | // type to this constructor. |
1082 | // N.B. The selection of copy constructor is not sensitive to this |
1083 | // particular throw-site. Lookup will be performed at the catch-site to |
1084 | // ensure that the copy constructor is, in fact, accessible (via |
1085 | // friendship or any other means). |
1086 | Context.addCopyConstructorForExceptionObject(RD: Subobject, CD); |
1087 | |
1088 | // We don't keep the instantiated default argument expressions around so |
1089 | // we must rebuild them here. |
1090 | for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) { |
1091 | if (CheckCXXDefaultArgExpr(CallLoc: ThrowLoc, FD: CD, Param: CD->getParamDecl(I))) |
1092 | return true; |
1093 | } |
1094 | } |
1095 | } |
1096 | |
1097 | // Under the Itanium C++ ABI, memory for the exception object is allocated by |
1098 | // the runtime with no ability for the compiler to request additional |
1099 | // alignment. Warn if the exception type requires alignment beyond the minimum |
1100 | // guaranteed by the target C++ runtime. |
1101 | if (Context.getTargetInfo().getCXXABI().isItaniumFamily()) { |
1102 | CharUnits TypeAlign = Context.getTypeAlignInChars(T: Ty); |
1103 | CharUnits ExnObjAlign = Context.getExnObjectAlignment(); |
1104 | if (ExnObjAlign < TypeAlign) { |
1105 | Diag(ThrowLoc, diag::warn_throw_underaligned_obj); |
1106 | Diag(ThrowLoc, diag::note_throw_underaligned_obj) |
1107 | << Ty << (unsigned)TypeAlign.getQuantity() |
1108 | << (unsigned)ExnObjAlign.getQuantity(); |
1109 | } |
1110 | } |
1111 | if (!isPointer && getLangOpts().AssumeNothrowExceptionDtor) { |
1112 | if (CXXDestructorDecl *Dtor = RD->getDestructor()) { |
1113 | auto Ty = Dtor->getType(); |
1114 | if (auto *FT = Ty.getTypePtr()->getAs<FunctionProtoType>()) { |
1115 | if (!isUnresolvedExceptionSpec(FT->getExceptionSpecType()) && |
1116 | !FT->isNothrow()) |
1117 | Diag(ThrowLoc, diag::err_throw_object_throwing_dtor) << RD; |
1118 | } |
1119 | } |
1120 | } |
1121 | |
1122 | return false; |
1123 | } |
1124 | |
1125 | static QualType adjustCVQualifiersForCXXThisWithinLambda( |
1126 | ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy, |
1127 | DeclContext *CurSemaContext, ASTContext &ASTCtx) { |
1128 | |
1129 | QualType ClassType = ThisTy->getPointeeType(); |
1130 | LambdaScopeInfo *CurLSI = nullptr; |
1131 | DeclContext *CurDC = CurSemaContext; |
1132 | |
1133 | // Iterate through the stack of lambdas starting from the innermost lambda to |
1134 | // the outermost lambda, checking if '*this' is ever captured by copy - since |
1135 | // that could change the cv-qualifiers of the '*this' object. |
1136 | // The object referred to by '*this' starts out with the cv-qualifiers of its |
1137 | // member function. We then start with the innermost lambda and iterate |
1138 | // outward checking to see if any lambda performs a by-copy capture of '*this' |
1139 | // - and if so, any nested lambda must respect the 'constness' of that |
1140 | // capturing lamdbda's call operator. |
1141 | // |
1142 | |
1143 | // Since the FunctionScopeInfo stack is representative of the lexical |
1144 | // nesting of the lambda expressions during initial parsing (and is the best |
1145 | // place for querying information about captures about lambdas that are |
1146 | // partially processed) and perhaps during instantiation of function templates |
1147 | // that contain lambda expressions that need to be transformed BUT not |
1148 | // necessarily during instantiation of a nested generic lambda's function call |
1149 | // operator (which might even be instantiated at the end of the TU) - at which |
1150 | // time the DeclContext tree is mature enough to query capture information |
1151 | // reliably - we use a two pronged approach to walk through all the lexically |
1152 | // enclosing lambda expressions: |
1153 | // |
1154 | // 1) Climb down the FunctionScopeInfo stack as long as each item represents |
1155 | // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically |
1156 | // enclosed by the call-operator of the LSI below it on the stack (while |
1157 | // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on |
1158 | // the stack represents the innermost lambda. |
1159 | // |
1160 | // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext |
1161 | // represents a lambda's call operator. If it does, we must be instantiating |
1162 | // a generic lambda's call operator (represented by the Current LSI, and |
1163 | // should be the only scenario where an inconsistency between the LSI and the |
1164 | // DeclContext should occur), so climb out the DeclContexts if they |
1165 | // represent lambdas, while querying the corresponding closure types |
1166 | // regarding capture information. |
1167 | |
1168 | // 1) Climb down the function scope info stack. |
1169 | for (int I = FunctionScopes.size(); |
1170 | I-- && isa<LambdaScopeInfo>(Val: FunctionScopes[I]) && |
1171 | (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() == |
1172 | cast<LambdaScopeInfo>(Val: FunctionScopes[I])->CallOperator); |
1173 | CurDC = getLambdaAwareParentOfDeclContext(DC: CurDC)) { |
1174 | CurLSI = cast<LambdaScopeInfo>(Val: FunctionScopes[I]); |
1175 | |
1176 | if (!CurLSI->isCXXThisCaptured()) |
1177 | continue; |
1178 | |
1179 | auto C = CurLSI->getCXXThisCapture(); |
1180 | |
1181 | if (C.isCopyCapture()) { |
1182 | if (CurLSI->lambdaCaptureShouldBeConst()) |
1183 | ClassType.addConst(); |
1184 | return ASTCtx.getPointerType(T: ClassType); |
1185 | } |
1186 | } |
1187 | |
1188 | // 2) We've run out of ScopeInfos but check 1. if CurDC is a lambda (which |
1189 | // can happen during instantiation of its nested generic lambda call |
1190 | // operator); 2. if we're in a lambda scope (lambda body). |
1191 | if (CurLSI && isLambdaCallOperator(DC: CurDC)) { |
1192 | assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && |
1193 | "While computing 'this' capture-type for a generic lambda, when we " |
1194 | "run out of enclosing LSI's, yet the enclosing DC is a " |
1195 | "lambda-call-operator we must be (i.e. Current LSI) in a generic " |
1196 | "lambda call oeprator" ); |
1197 | assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator)); |
1198 | |
1199 | auto IsThisCaptured = |
1200 | [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) { |
1201 | IsConst = false; |
1202 | IsByCopy = false; |
1203 | for (auto &&C : Closure->captures()) { |
1204 | if (C.capturesThis()) { |
1205 | if (C.getCaptureKind() == LCK_StarThis) |
1206 | IsByCopy = true; |
1207 | if (Closure->getLambdaCallOperator()->isConst()) |
1208 | IsConst = true; |
1209 | return true; |
1210 | } |
1211 | } |
1212 | return false; |
1213 | }; |
1214 | |
1215 | bool IsByCopyCapture = false; |
1216 | bool IsConstCapture = false; |
1217 | CXXRecordDecl *Closure = cast<CXXRecordDecl>(Val: CurDC->getParent()); |
1218 | while (Closure && |
1219 | IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) { |
1220 | if (IsByCopyCapture) { |
1221 | if (IsConstCapture) |
1222 | ClassType.addConst(); |
1223 | return ASTCtx.getPointerType(T: ClassType); |
1224 | } |
1225 | Closure = isLambdaCallOperator(Closure->getParent()) |
1226 | ? cast<CXXRecordDecl>(Closure->getParent()->getParent()) |
1227 | : nullptr; |
1228 | } |
1229 | } |
1230 | return ThisTy; |
1231 | } |
1232 | |
1233 | QualType Sema::getCurrentThisType() { |
1234 | DeclContext *DC = getFunctionLevelDeclContext(); |
1235 | QualType ThisTy = CXXThisTypeOverride; |
1236 | |
1237 | if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(Val: DC)) { |
1238 | if (method && method->isImplicitObjectMemberFunction()) |
1239 | ThisTy = method->getThisType().getNonReferenceType(); |
1240 | } |
1241 | |
1242 | if (ThisTy.isNull() && isLambdaCallWithImplicitObjectParameter(DC: CurContext) && |
1243 | inTemplateInstantiation() && isa<CXXRecordDecl>(Val: DC)) { |
1244 | |
1245 | // This is a lambda call operator that is being instantiated as a default |
1246 | // initializer. DC must point to the enclosing class type, so we can recover |
1247 | // the 'this' type from it. |
1248 | QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(Val: DC)); |
1249 | // There are no cv-qualifiers for 'this' within default initializers, |
1250 | // per [expr.prim.general]p4. |
1251 | ThisTy = Context.getPointerType(T: ClassTy); |
1252 | } |
1253 | |
1254 | // If we are within a lambda's call operator, the cv-qualifiers of 'this' |
1255 | // might need to be adjusted if the lambda or any of its enclosing lambda's |
1256 | // captures '*this' by copy. |
1257 | if (!ThisTy.isNull() && isLambdaCallOperator(DC: CurContext)) |
1258 | return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy, |
1259 | CurSemaContext: CurContext, ASTCtx&: Context); |
1260 | return ThisTy; |
1261 | } |
1262 | |
1263 | Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S, |
1264 | Decl *ContextDecl, |
1265 | Qualifiers CXXThisTypeQuals, |
1266 | bool Enabled) |
1267 | : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false) |
1268 | { |
1269 | if (!Enabled || !ContextDecl) |
1270 | return; |
1271 | |
1272 | CXXRecordDecl *Record = nullptr; |
1273 | if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(Val: ContextDecl)) |
1274 | Record = Template->getTemplatedDecl(); |
1275 | else |
1276 | Record = cast<CXXRecordDecl>(Val: ContextDecl); |
1277 | |
1278 | QualType T = S.Context.getRecordType(Record); |
1279 | T = S.getASTContext().getQualifiedType(T, Qs: CXXThisTypeQuals); |
1280 | |
1281 | S.CXXThisTypeOverride = |
1282 | S.Context.getLangOpts().HLSL ? T : S.Context.getPointerType(T); |
1283 | |
1284 | this->Enabled = true; |
1285 | } |
1286 | |
1287 | |
1288 | Sema::CXXThisScopeRAII::~CXXThisScopeRAII() { |
1289 | if (Enabled) { |
1290 | S.CXXThisTypeOverride = OldCXXThisTypeOverride; |
1291 | } |
1292 | } |
1293 | |
1294 | static void buildLambdaThisCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI) { |
1295 | SourceLocation DiagLoc = LSI->IntroducerRange.getEnd(); |
1296 | assert(!LSI->isCXXThisCaptured()); |
1297 | // [=, this] {}; // until C++20: Error: this when = is the default |
1298 | if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval && |
1299 | !Sema.getLangOpts().CPlusPlus20) |
1300 | return; |
1301 | Sema.Diag(DiagLoc, diag::note_lambda_this_capture_fixit) |
1302 | << FixItHint::CreateInsertion( |
1303 | DiagLoc, LSI->NumExplicitCaptures > 0 ? ", this" : "this" ); |
1304 | } |
1305 | |
1306 | bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit, |
1307 | bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt, |
1308 | const bool ByCopy) { |
1309 | // We don't need to capture this in an unevaluated context. |
1310 | if (isUnevaluatedContext() && !Explicit) |
1311 | return true; |
1312 | |
1313 | assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value" ); |
1314 | |
1315 | const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt |
1316 | ? *FunctionScopeIndexToStopAt |
1317 | : FunctionScopes.size() - 1; |
1318 | |
1319 | // Check that we can capture the *enclosing object* (referred to by '*this') |
1320 | // by the capturing-entity/closure (lambda/block/etc) at |
1321 | // MaxFunctionScopesIndex-deep on the FunctionScopes stack. |
1322 | |
1323 | // Note: The *enclosing object* can only be captured by-value by a |
1324 | // closure that is a lambda, using the explicit notation: |
1325 | // [*this] { ... }. |
1326 | // Every other capture of the *enclosing object* results in its by-reference |
1327 | // capture. |
1328 | |
1329 | // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes |
1330 | // stack), we can capture the *enclosing object* only if: |
1331 | // - 'L' has an explicit byref or byval capture of the *enclosing object* |
1332 | // - or, 'L' has an implicit capture. |
1333 | // AND |
1334 | // -- there is no enclosing closure |
1335 | // -- or, there is some enclosing closure 'E' that has already captured the |
1336 | // *enclosing object*, and every intervening closure (if any) between 'E' |
1337 | // and 'L' can implicitly capture the *enclosing object*. |
1338 | // -- or, every enclosing closure can implicitly capture the |
1339 | // *enclosing object* |
1340 | |
1341 | |
1342 | unsigned NumCapturingClosures = 0; |
1343 | for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) { |
1344 | if (CapturingScopeInfo *CSI = |
1345 | dyn_cast<CapturingScopeInfo>(Val: FunctionScopes[idx])) { |
1346 | if (CSI->CXXThisCaptureIndex != 0) { |
1347 | // 'this' is already being captured; there isn't anything more to do. |
1348 | CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(IsODRUse: BuildAndDiagnose); |
1349 | break; |
1350 | } |
1351 | LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(Val: CSI); |
1352 | if (LSI && isGenericLambdaCallOperatorSpecialization(MD: LSI->CallOperator)) { |
1353 | // This context can't implicitly capture 'this'; fail out. |
1354 | if (BuildAndDiagnose) { |
1355 | LSI->CallOperator->setInvalidDecl(); |
1356 | Diag(Loc, diag::err_this_capture) |
1357 | << (Explicit && idx == MaxFunctionScopesIndex); |
1358 | if (!Explicit) |
1359 | buildLambdaThisCaptureFixit(Sema&: *this, LSI); |
1360 | } |
1361 | return true; |
1362 | } |
1363 | if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref || |
1364 | CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval || |
1365 | CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block || |
1366 | CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion || |
1367 | (Explicit && idx == MaxFunctionScopesIndex)) { |
1368 | // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first |
1369 | // iteration through can be an explicit capture, all enclosing closures, |
1370 | // if any, must perform implicit captures. |
1371 | |
1372 | // This closure can capture 'this'; continue looking upwards. |
1373 | NumCapturingClosures++; |
1374 | continue; |
1375 | } |
1376 | // This context can't implicitly capture 'this'; fail out. |
1377 | if (BuildAndDiagnose) { |
1378 | LSI->CallOperator->setInvalidDecl(); |
1379 | Diag(Loc, diag::err_this_capture) |
1380 | << (Explicit && idx == MaxFunctionScopesIndex); |
1381 | } |
1382 | if (!Explicit) |
1383 | buildLambdaThisCaptureFixit(Sema&: *this, LSI); |
1384 | return true; |
1385 | } |
1386 | break; |
1387 | } |
1388 | if (!BuildAndDiagnose) return false; |
1389 | |
1390 | // If we got here, then the closure at MaxFunctionScopesIndex on the |
1391 | // FunctionScopes stack, can capture the *enclosing object*, so capture it |
1392 | // (including implicit by-reference captures in any enclosing closures). |
1393 | |
1394 | // In the loop below, respect the ByCopy flag only for the closure requesting |
1395 | // the capture (i.e. first iteration through the loop below). Ignore it for |
1396 | // all enclosing closure's up to NumCapturingClosures (since they must be |
1397 | // implicitly capturing the *enclosing object* by reference (see loop |
1398 | // above)). |
1399 | assert((!ByCopy || |
1400 | isa<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && |
1401 | "Only a lambda can capture the enclosing object (referred to by " |
1402 | "*this) by copy" ); |
1403 | QualType ThisTy = getCurrentThisType(); |
1404 | for (int idx = MaxFunctionScopesIndex; NumCapturingClosures; |
1405 | --idx, --NumCapturingClosures) { |
1406 | CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(Val: FunctionScopes[idx]); |
1407 | |
1408 | // The type of the corresponding data member (not a 'this' pointer if 'by |
1409 | // copy'). |
1410 | QualType CaptureType = ByCopy ? ThisTy->getPointeeType() : ThisTy; |
1411 | |
1412 | bool isNested = NumCapturingClosures > 1; |
1413 | CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy); |
1414 | } |
1415 | return false; |
1416 | } |
1417 | |
1418 | ExprResult Sema::ActOnCXXThis(SourceLocation Loc) { |
1419 | // C++20 [expr.prim.this]p1: |
1420 | // The keyword this names a pointer to the object for which an |
1421 | // implicit object member function is invoked or a non-static |
1422 | // data member's initializer is evaluated. |
1423 | QualType ThisTy = getCurrentThisType(); |
1424 | |
1425 | if (CheckCXXThisType(Loc, Type: ThisTy)) |
1426 | return ExprError(); |
1427 | |
1428 | return BuildCXXThisExpr(Loc, Type: ThisTy, /*IsImplicit=*/false); |
1429 | } |
1430 | |
1431 | bool Sema::CheckCXXThisType(SourceLocation Loc, QualType Type) { |
1432 | if (!Type.isNull()) |
1433 | return false; |
1434 | |
1435 | // C++20 [expr.prim.this]p3: |
1436 | // If a declaration declares a member function or member function template |
1437 | // of a class X, the expression this is a prvalue of type |
1438 | // "pointer to cv-qualifier-seq X" wherever X is the current class between |
1439 | // the optional cv-qualifier-seq and the end of the function-definition, |
1440 | // member-declarator, or declarator. It shall not appear within the |
1441 | // declaration of either a static member function or an explicit object |
1442 | // member function of the current class (although its type and value |
1443 | // category are defined within such member functions as they are within |
1444 | // an implicit object member function). |
1445 | DeclContext *DC = getFunctionLevelDeclContext(); |
1446 | if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: DC); |
1447 | Method && Method->isExplicitObjectMemberFunction()) { |
1448 | Diag(Loc, diag::err_invalid_this_use) << 1; |
1449 | } else if (isLambdaCallWithExplicitObjectParameter(DC: CurContext)) { |
1450 | Diag(Loc, diag::err_invalid_this_use) << 1; |
1451 | } else { |
1452 | Diag(Loc, diag::err_invalid_this_use) << 0; |
1453 | } |
1454 | return true; |
1455 | } |
1456 | |
1457 | Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type, |
1458 | bool IsImplicit) { |
1459 | auto *This = CXXThisExpr::Create(Ctx: Context, L: Loc, Ty: Type, IsImplicit); |
1460 | MarkThisReferenced(This); |
1461 | return This; |
1462 | } |
1463 | |
1464 | void Sema::MarkThisReferenced(CXXThisExpr *This) { |
1465 | CheckCXXThisCapture(Loc: This->getExprLoc()); |
1466 | if (This->isTypeDependent()) |
1467 | return; |
1468 | |
1469 | // Check if 'this' is captured by value in a lambda with a dependent explicit |
1470 | // object parameter, and mark it as type-dependent as well if so. |
1471 | auto IsDependent = [&]() { |
1472 | for (auto *Scope : llvm::reverse(C&: FunctionScopes)) { |
1473 | auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Val: Scope); |
1474 | if (!LSI) |
1475 | continue; |
1476 | |
1477 | if (LSI->Lambda && !LSI->Lambda->Encloses(CurContext) && |
1478 | LSI->AfterParameterList) |
1479 | return false; |
1480 | |
1481 | // If this lambda captures 'this' by value, then 'this' is dependent iff |
1482 | // this lambda has a dependent explicit object parameter. If we can't |
1483 | // determine whether it does (e.g. because the CXXMethodDecl's type is |
1484 | // null), assume it doesn't. |
1485 | if (LSI->isCXXThisCaptured()) { |
1486 | if (!LSI->getCXXThisCapture().isCopyCapture()) |
1487 | continue; |
1488 | |
1489 | const auto *MD = LSI->CallOperator; |
1490 | if (MD->getType().isNull()) |
1491 | return false; |
1492 | |
1493 | const auto *Ty = MD->getType()->getAs<FunctionProtoType>(); |
1494 | return Ty && MD->isExplicitObjectMemberFunction() && |
1495 | Ty->getParamType(0)->isDependentType(); |
1496 | } |
1497 | } |
1498 | return false; |
1499 | }(); |
1500 | |
1501 | This->setCapturedByCopyInLambdaWithExplicitObjectParameter(IsDependent); |
1502 | } |
1503 | |
1504 | bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) { |
1505 | // If we're outside the body of a member function, then we'll have a specified |
1506 | // type for 'this'. |
1507 | if (CXXThisTypeOverride.isNull()) |
1508 | return false; |
1509 | |
1510 | // Determine whether we're looking into a class that's currently being |
1511 | // defined. |
1512 | CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl(); |
1513 | return Class && Class->isBeingDefined(); |
1514 | } |
1515 | |
1516 | /// Parse construction of a specified type. |
1517 | /// Can be interpreted either as function-style casting ("int(x)") |
1518 | /// or class type construction ("ClassType(x,y,z)") |
1519 | /// or creation of a value-initialized type ("int()"). |
1520 | ExprResult |
1521 | Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep, |
1522 | SourceLocation LParenOrBraceLoc, |
1523 | MultiExprArg exprs, |
1524 | SourceLocation RParenOrBraceLoc, |
1525 | bool ListInitialization) { |
1526 | if (!TypeRep) |
1527 | return ExprError(); |
1528 | |
1529 | TypeSourceInfo *TInfo; |
1530 | QualType Ty = GetTypeFromParser(Ty: TypeRep, TInfo: &TInfo); |
1531 | if (!TInfo) |
1532 | TInfo = Context.getTrivialTypeSourceInfo(T: Ty, Loc: SourceLocation()); |
1533 | |
1534 | auto Result = BuildCXXTypeConstructExpr(Type: TInfo, LParenLoc: LParenOrBraceLoc, Exprs: exprs, |
1535 | RParenLoc: RParenOrBraceLoc, ListInitialization); |
1536 | // Avoid creating a non-type-dependent expression that contains typos. |
1537 | // Non-type-dependent expressions are liable to be discarded without |
1538 | // checking for embedded typos. |
1539 | if (!Result.isInvalid() && Result.get()->isInstantiationDependent() && |
1540 | !Result.get()->isTypeDependent()) |
1541 | Result = CorrectDelayedTyposInExpr(E: Result.get()); |
1542 | else if (Result.isInvalid()) |
1543 | Result = CreateRecoveryExpr(Begin: TInfo->getTypeLoc().getBeginLoc(), |
1544 | End: RParenOrBraceLoc, SubExprs: exprs, T: Ty); |
1545 | return Result; |
1546 | } |
1547 | |
1548 | ExprResult |
1549 | Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo, |
1550 | SourceLocation LParenOrBraceLoc, |
1551 | MultiExprArg Exprs, |
1552 | SourceLocation RParenOrBraceLoc, |
1553 | bool ListInitialization) { |
1554 | QualType Ty = TInfo->getType(); |
1555 | SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc(); |
1556 | |
1557 | assert((!ListInitialization || Exprs.size() == 1) && |
1558 | "List initialization must have exactly one expression." ); |
1559 | SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc); |
1560 | |
1561 | InitializedEntity Entity = |
1562 | InitializedEntity::InitializeTemporary(Context, TypeInfo: TInfo); |
1563 | InitializationKind Kind = |
1564 | Exprs.size() |
1565 | ? ListInitialization |
1566 | ? InitializationKind::CreateDirectList( |
1567 | InitLoc: TyBeginLoc, LBraceLoc: LParenOrBraceLoc, RBraceLoc: RParenOrBraceLoc) |
1568 | : InitializationKind::CreateDirect(InitLoc: TyBeginLoc, LParenLoc: LParenOrBraceLoc, |
1569 | RParenLoc: RParenOrBraceLoc) |
1570 | : InitializationKind::CreateValue(InitLoc: TyBeginLoc, LParenLoc: LParenOrBraceLoc, |
1571 | RParenLoc: RParenOrBraceLoc); |
1572 | |
1573 | // C++17 [expr.type.conv]p1: |
1574 | // If the type is a placeholder for a deduced class type, [...perform class |
1575 | // template argument deduction...] |
1576 | // C++23: |
1577 | // Otherwise, if the type contains a placeholder type, it is replaced by the |
1578 | // type determined by placeholder type deduction. |
1579 | DeducedType *Deduced = Ty->getContainedDeducedType(); |
1580 | if (Deduced && !Deduced->isDeduced() && |
1581 | isa<DeducedTemplateSpecializationType>(Val: Deduced)) { |
1582 | Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity, |
1583 | Kind, Init: Exprs); |
1584 | if (Ty.isNull()) |
1585 | return ExprError(); |
1586 | Entity = InitializedEntity::InitializeTemporary(TypeInfo: TInfo, Type: Ty); |
1587 | } else if (Deduced && !Deduced->isDeduced()) { |
1588 | MultiExprArg Inits = Exprs; |
1589 | if (ListInitialization) { |
1590 | auto *ILE = cast<InitListExpr>(Val: Exprs[0]); |
1591 | Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits()); |
1592 | } |
1593 | |
1594 | if (Inits.empty()) |
1595 | return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_init_no_expression) |
1596 | << Ty << FullRange); |
1597 | if (Inits.size() > 1) { |
1598 | Expr *FirstBad = Inits[1]; |
1599 | return ExprError(Diag(FirstBad->getBeginLoc(), |
1600 | diag::err_auto_expr_init_multiple_expressions) |
1601 | << Ty << FullRange); |
1602 | } |
1603 | if (getLangOpts().CPlusPlus23) { |
1604 | if (Ty->getAs<AutoType>()) |
1605 | Diag(TyBeginLoc, diag::warn_cxx20_compat_auto_expr) << FullRange; |
1606 | } |
1607 | Expr *Deduce = Inits[0]; |
1608 | if (isa<InitListExpr>(Deduce)) |
1609 | return ExprError( |
1610 | Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces) |
1611 | << ListInitialization << Ty << FullRange); |
1612 | QualType DeducedType; |
1613 | TemplateDeductionInfo Info(Deduce->getExprLoc()); |
1614 | TemplateDeductionResult Result = |
1615 | DeduceAutoType(AutoTypeLoc: TInfo->getTypeLoc(), Initializer: Deduce, Result&: DeducedType, Info); |
1616 | if (Result != TemplateDeductionResult::Success && |
1617 | Result != TemplateDeductionResult::AlreadyDiagnosed) |
1618 | return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_deduction_failure) |
1619 | << Ty << Deduce->getType() << FullRange |
1620 | << Deduce->getSourceRange()); |
1621 | if (DeducedType.isNull()) { |
1622 | assert(Result == TemplateDeductionResult::AlreadyDiagnosed); |
1623 | return ExprError(); |
1624 | } |
1625 | |
1626 | Ty = DeducedType; |
1627 | Entity = InitializedEntity::InitializeTemporary(TypeInfo: TInfo, Type: Ty); |
1628 | } |
1629 | |
1630 | if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) |
1631 | return CXXUnresolvedConstructExpr::Create( |
1632 | Context, T: Ty.getNonReferenceType(), TSI: TInfo, LParenLoc: LParenOrBraceLoc, Args: Exprs, |
1633 | RParenLoc: RParenOrBraceLoc, IsListInit: ListInitialization); |
1634 | |
1635 | // C++ [expr.type.conv]p1: |
1636 | // If the expression list is a parenthesized single expression, the type |
1637 | // conversion expression is equivalent (in definedness, and if defined in |
1638 | // meaning) to the corresponding cast expression. |
1639 | if (Exprs.size() == 1 && !ListInitialization && |
1640 | !isa<InitListExpr>(Val: Exprs[0])) { |
1641 | Expr *Arg = Exprs[0]; |
1642 | return BuildCXXFunctionalCastExpr(TInfo, Type: Ty, LParenLoc: LParenOrBraceLoc, CastExpr: Arg, |
1643 | RParenLoc: RParenOrBraceLoc); |
1644 | } |
1645 | |
1646 | // For an expression of the form T(), T shall not be an array type. |
1647 | QualType ElemTy = Ty; |
1648 | if (Ty->isArrayType()) { |
1649 | if (!ListInitialization) |
1650 | return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type) |
1651 | << FullRange); |
1652 | ElemTy = Context.getBaseElementType(QT: Ty); |
1653 | } |
1654 | |
1655 | // Only construct objects with object types. |
1656 | // The standard doesn't explicitly forbid function types here, but that's an |
1657 | // obvious oversight, as there's no way to dynamically construct a function |
1658 | // in general. |
1659 | if (Ty->isFunctionType()) |
1660 | return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type) |
1661 | << Ty << FullRange); |
1662 | |
1663 | // C++17 [expr.type.conv]p2: |
1664 | // If the type is cv void and the initializer is (), the expression is a |
1665 | // prvalue of the specified type that performs no initialization. |
1666 | if (!Ty->isVoidType() && |
1667 | RequireCompleteType(TyBeginLoc, ElemTy, |
1668 | diag::err_invalid_incomplete_type_use, FullRange)) |
1669 | return ExprError(); |
1670 | |
1671 | // Otherwise, the expression is a prvalue of the specified type whose |
1672 | // result object is direct-initialized (11.6) with the initializer. |
1673 | InitializationSequence InitSeq(*this, Entity, Kind, Exprs); |
1674 | ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: Exprs); |
1675 | |
1676 | if (Result.isInvalid()) |
1677 | return Result; |
1678 | |
1679 | Expr *Inner = Result.get(); |
1680 | if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Val: Inner)) |
1681 | Inner = BTE->getSubExpr(); |
1682 | if (auto *CE = dyn_cast<ConstantExpr>(Val: Inner); |
1683 | CE && CE->isImmediateInvocation()) |
1684 | Inner = CE->getSubExpr(); |
1685 | if (!isa<CXXTemporaryObjectExpr>(Val: Inner) && |
1686 | !isa<CXXScalarValueInitExpr>(Val: Inner)) { |
1687 | // If we created a CXXTemporaryObjectExpr, that node also represents the |
1688 | // functional cast. Otherwise, create an explicit cast to represent |
1689 | // the syntactic form of a functional-style cast that was used here. |
1690 | // |
1691 | // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr |
1692 | // would give a more consistent AST representation than using a |
1693 | // CXXTemporaryObjectExpr. It's also weird that the functional cast |
1694 | // is sometimes handled by initialization and sometimes not. |
1695 | QualType ResultType = Result.get()->getType(); |
1696 | SourceRange Locs = ListInitialization |
1697 | ? SourceRange() |
1698 | : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc); |
1699 | Result = CXXFunctionalCastExpr::Create( |
1700 | Context, T: ResultType, VK: Expr::getValueKindForType(T: Ty), Written: TInfo, Kind: CK_NoOp, |
1701 | Op: Result.get(), /*Path=*/nullptr, FPO: CurFPFeatureOverrides(), |
1702 | LPLoc: Locs.getBegin(), RPLoc: Locs.getEnd()); |
1703 | } |
1704 | |
1705 | return Result; |
1706 | } |
1707 | |
1708 | bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) { |
1709 | // [CUDA] Ignore this function, if we can't call it. |
1710 | const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true); |
1711 | if (getLangOpts().CUDA) { |
1712 | auto CallPreference = CUDA().IdentifyPreference(Caller, Method); |
1713 | // If it's not callable at all, it's not the right function. |
1714 | if (CallPreference < SemaCUDA::CFP_WrongSide) |
1715 | return false; |
1716 | if (CallPreference == SemaCUDA::CFP_WrongSide) { |
1717 | // Maybe. We have to check if there are better alternatives. |
1718 | DeclContext::lookup_result R = |
1719 | Method->getDeclContext()->lookup(Method->getDeclName()); |
1720 | for (const auto *D : R) { |
1721 | if (const auto *FD = dyn_cast<FunctionDecl>(D)) { |
1722 | if (CUDA().IdentifyPreference(Caller, FD) > SemaCUDA::CFP_WrongSide) |
1723 | return false; |
1724 | } |
1725 | } |
1726 | // We've found no better variants. |
1727 | } |
1728 | } |
1729 | |
1730 | SmallVector<const FunctionDecl*, 4> PreventedBy; |
1731 | bool Result = Method->isUsualDeallocationFunction(PreventedBy); |
1732 | |
1733 | if (Result || !getLangOpts().CUDA || PreventedBy.empty()) |
1734 | return Result; |
1735 | |
1736 | // In case of CUDA, return true if none of the 1-argument deallocator |
1737 | // functions are actually callable. |
1738 | return llvm::none_of(Range&: PreventedBy, P: [&](const FunctionDecl *FD) { |
1739 | assert(FD->getNumParams() == 1 && |
1740 | "Only single-operand functions should be in PreventedBy" ); |
1741 | return CUDA().IdentifyPreference(Caller, Callee: FD) >= SemaCUDA::CFP_HostDevice; |
1742 | }); |
1743 | } |
1744 | |
1745 | /// Determine whether the given function is a non-placement |
1746 | /// deallocation function. |
1747 | static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) { |
1748 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: FD)) |
1749 | return S.isUsualDeallocationFunction(Method); |
1750 | |
1751 | if (FD->getOverloadedOperator() != OO_Delete && |
1752 | FD->getOverloadedOperator() != OO_Array_Delete) |
1753 | return false; |
1754 | |
1755 | unsigned UsualParams = 1; |
1756 | |
1757 | if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() && |
1758 | S.Context.hasSameUnqualifiedType( |
1759 | T1: FD->getParamDecl(i: UsualParams)->getType(), |
1760 | T2: S.Context.getSizeType())) |
1761 | ++UsualParams; |
1762 | |
1763 | if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() && |
1764 | S.Context.hasSameUnqualifiedType( |
1765 | T1: FD->getParamDecl(i: UsualParams)->getType(), |
1766 | T2: S.Context.getTypeDeclType(S.getStdAlignValT()))) |
1767 | ++UsualParams; |
1768 | |
1769 | return UsualParams == FD->getNumParams(); |
1770 | } |
1771 | |
1772 | namespace { |
1773 | struct UsualDeallocFnInfo { |
1774 | UsualDeallocFnInfo() : Found(), FD(nullptr) {} |
1775 | UsualDeallocFnInfo(Sema &S, DeclAccessPair Found) |
1776 | : Found(Found), FD(dyn_cast<FunctionDecl>(Val: Found->getUnderlyingDecl())), |
1777 | Destroying(false), HasSizeT(false), HasAlignValT(false), |
1778 | CUDAPref(SemaCUDA::CFP_Native) { |
1779 | // A function template declaration is never a usual deallocation function. |
1780 | if (!FD) |
1781 | return; |
1782 | unsigned NumBaseParams = 1; |
1783 | if (FD->isDestroyingOperatorDelete()) { |
1784 | Destroying = true; |
1785 | ++NumBaseParams; |
1786 | } |
1787 | |
1788 | if (NumBaseParams < FD->getNumParams() && |
1789 | S.Context.hasSameUnqualifiedType( |
1790 | T1: FD->getParamDecl(i: NumBaseParams)->getType(), |
1791 | T2: S.Context.getSizeType())) { |
1792 | ++NumBaseParams; |
1793 | HasSizeT = true; |
1794 | } |
1795 | |
1796 | if (NumBaseParams < FD->getNumParams() && |
1797 | FD->getParamDecl(i: NumBaseParams)->getType()->isAlignValT()) { |
1798 | ++NumBaseParams; |
1799 | HasAlignValT = true; |
1800 | } |
1801 | |
1802 | // In CUDA, determine how much we'd like / dislike to call this. |
1803 | if (S.getLangOpts().CUDA) |
1804 | CUDAPref = S.CUDA().IdentifyPreference( |
1805 | Caller: S.getCurFunctionDecl(/*AllowLambda=*/true), Callee: FD); |
1806 | } |
1807 | |
1808 | explicit operator bool() const { return FD; } |
1809 | |
1810 | bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize, |
1811 | bool WantAlign) const { |
1812 | // C++ P0722: |
1813 | // A destroying operator delete is preferred over a non-destroying |
1814 | // operator delete. |
1815 | if (Destroying != Other.Destroying) |
1816 | return Destroying; |
1817 | |
1818 | // C++17 [expr.delete]p10: |
1819 | // If the type has new-extended alignment, a function with a parameter |
1820 | // of type std::align_val_t is preferred; otherwise a function without |
1821 | // such a parameter is preferred |
1822 | if (HasAlignValT != Other.HasAlignValT) |
1823 | return HasAlignValT == WantAlign; |
1824 | |
1825 | if (HasSizeT != Other.HasSizeT) |
1826 | return HasSizeT == WantSize; |
1827 | |
1828 | // Use CUDA call preference as a tiebreaker. |
1829 | return CUDAPref > Other.CUDAPref; |
1830 | } |
1831 | |
1832 | DeclAccessPair Found; |
1833 | FunctionDecl *FD; |
1834 | bool Destroying, HasSizeT, HasAlignValT; |
1835 | SemaCUDA::CUDAFunctionPreference CUDAPref; |
1836 | }; |
1837 | } |
1838 | |
1839 | /// Determine whether a type has new-extended alignment. This may be called when |
1840 | /// the type is incomplete (for a delete-expression with an incomplete pointee |
1841 | /// type), in which case it will conservatively return false if the alignment is |
1842 | /// not known. |
1843 | static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) { |
1844 | return S.getLangOpts().AlignedAllocation && |
1845 | S.getASTContext().getTypeAlignIfKnown(T: AllocType) > |
1846 | S.getASTContext().getTargetInfo().getNewAlign(); |
1847 | } |
1848 | |
1849 | /// Select the correct "usual" deallocation function to use from a selection of |
1850 | /// deallocation functions (either global or class-scope). |
1851 | static UsualDeallocFnInfo resolveDeallocationOverload( |
1852 | Sema &S, LookupResult &R, bool WantSize, bool WantAlign, |
1853 | llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) { |
1854 | UsualDeallocFnInfo Best; |
1855 | |
1856 | for (auto I = R.begin(), E = R.end(); I != E; ++I) { |
1857 | UsualDeallocFnInfo Info(S, I.getPair()); |
1858 | if (!Info || !isNonPlacementDeallocationFunction(S, FD: Info.FD) || |
1859 | Info.CUDAPref == SemaCUDA::CFP_Never) |
1860 | continue; |
1861 | |
1862 | if (!Best) { |
1863 | Best = Info; |
1864 | if (BestFns) |
1865 | BestFns->push_back(Elt: Info); |
1866 | continue; |
1867 | } |
1868 | |
1869 | if (Best.isBetterThan(Other: Info, WantSize, WantAlign)) |
1870 | continue; |
1871 | |
1872 | // If more than one preferred function is found, all non-preferred |
1873 | // functions are eliminated from further consideration. |
1874 | if (BestFns && Info.isBetterThan(Other: Best, WantSize, WantAlign)) |
1875 | BestFns->clear(); |
1876 | |
1877 | Best = Info; |
1878 | if (BestFns) |
1879 | BestFns->push_back(Elt: Info); |
1880 | } |
1881 | |
1882 | return Best; |
1883 | } |
1884 | |
1885 | /// Determine whether a given type is a class for which 'delete[]' would call |
1886 | /// a member 'operator delete[]' with a 'size_t' parameter. This implies that |
1887 | /// we need to store the array size (even if the type is |
1888 | /// trivially-destructible). |
1889 | static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc, |
1890 | QualType allocType) { |
1891 | const RecordType *record = |
1892 | allocType->getBaseElementTypeUnsafe()->getAs<RecordType>(); |
1893 | if (!record) return false; |
1894 | |
1895 | // Try to find an operator delete[] in class scope. |
1896 | |
1897 | DeclarationName deleteName = |
1898 | S.Context.DeclarationNames.getCXXOperatorName(Op: OO_Array_Delete); |
1899 | LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName); |
1900 | S.LookupQualifiedName(ops, record->getDecl()); |
1901 | |
1902 | // We're just doing this for information. |
1903 | ops.suppressDiagnostics(); |
1904 | |
1905 | // Very likely: there's no operator delete[]. |
1906 | if (ops.empty()) return false; |
1907 | |
1908 | // If it's ambiguous, it should be illegal to call operator delete[] |
1909 | // on this thing, so it doesn't matter if we allocate extra space or not. |
1910 | if (ops.isAmbiguous()) return false; |
1911 | |
1912 | // C++17 [expr.delete]p10: |
1913 | // If the deallocation functions have class scope, the one without a |
1914 | // parameter of type std::size_t is selected. |
1915 | auto Best = resolveDeallocationOverload( |
1916 | S, R&: ops, /*WantSize*/false, |
1917 | /*WantAlign*/hasNewExtendedAlignment(S, AllocType: allocType)); |
1918 | return Best && Best.HasSizeT; |
1919 | } |
1920 | |
1921 | /// Parsed a C++ 'new' expression (C++ 5.3.4). |
1922 | /// |
1923 | /// E.g.: |
1924 | /// @code new (memory) int[size][4] @endcode |
1925 | /// or |
1926 | /// @code ::new Foo(23, "hello") @endcode |
1927 | /// |
1928 | /// \param StartLoc The first location of the expression. |
1929 | /// \param UseGlobal True if 'new' was prefixed with '::'. |
1930 | /// \param PlacementLParen Opening paren of the placement arguments. |
1931 | /// \param PlacementArgs Placement new arguments. |
1932 | /// \param PlacementRParen Closing paren of the placement arguments. |
1933 | /// \param TypeIdParens If the type is in parens, the source range. |
1934 | /// \param D The type to be allocated, as well as array dimensions. |
1935 | /// \param Initializer The initializing expression or initializer-list, or null |
1936 | /// if there is none. |
1937 | ExprResult |
1938 | Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, |
1939 | SourceLocation PlacementLParen, MultiExprArg PlacementArgs, |
1940 | SourceLocation PlacementRParen, SourceRange TypeIdParens, |
1941 | Declarator &D, Expr *Initializer) { |
1942 | std::optional<Expr *> ArraySize; |
1943 | // If the specified type is an array, unwrap it and save the expression. |
1944 | if (D.getNumTypeObjects() > 0 && |
1945 | D.getTypeObject(i: 0).Kind == DeclaratorChunk::Array) { |
1946 | DeclaratorChunk &Chunk = D.getTypeObject(i: 0); |
1947 | if (D.getDeclSpec().hasAutoTypeSpec()) |
1948 | return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto) |
1949 | << D.getSourceRange()); |
1950 | if (Chunk.Arr.hasStatic) |
1951 | return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new) |
1952 | << D.getSourceRange()); |
1953 | if (!Chunk.Arr.NumElts && !Initializer) |
1954 | return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size) |
1955 | << D.getSourceRange()); |
1956 | |
1957 | ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts); |
1958 | D.DropFirstTypeObject(); |
1959 | } |
1960 | |
1961 | // Every dimension shall be of constant size. |
1962 | if (ArraySize) { |
1963 | for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) { |
1964 | if (D.getTypeObject(i: I).Kind != DeclaratorChunk::Array) |
1965 | break; |
1966 | |
1967 | DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(i: I).Arr; |
1968 | if (Expr *NumElts = (Expr *)Array.NumElts) { |
1969 | if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) { |
1970 | // FIXME: GCC permits constant folding here. We should either do so consistently |
1971 | // or not do so at all, rather than changing behavior in C++14 onwards. |
1972 | if (getLangOpts().CPlusPlus14) { |
1973 | // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator |
1974 | // shall be a converted constant expression (5.19) of type std::size_t |
1975 | // and shall evaluate to a strictly positive value. |
1976 | llvm::APSInt Value(Context.getIntWidth(T: Context.getSizeType())); |
1977 | Array.NumElts |
1978 | = CheckConvertedConstantExpression(From: NumElts, T: Context.getSizeType(), Value, |
1979 | CCE: CCEK_ArrayBound) |
1980 | .get(); |
1981 | } else { |
1982 | Array.NumElts = |
1983 | VerifyIntegerConstantExpression( |
1984 | NumElts, nullptr, diag::err_new_array_nonconst, AllowFold) |
1985 | .get(); |
1986 | } |
1987 | if (!Array.NumElts) |
1988 | return ExprError(); |
1989 | } |
1990 | } |
1991 | } |
1992 | } |
1993 | |
1994 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D); |
1995 | QualType AllocType = TInfo->getType(); |
1996 | if (D.isInvalidType()) |
1997 | return ExprError(); |
1998 | |
1999 | SourceRange DirectInitRange; |
2000 | if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Val: Initializer)) |
2001 | DirectInitRange = List->getSourceRange(); |
2002 | |
2003 | return BuildCXXNew(Range: SourceRange(StartLoc, D.getEndLoc()), UseGlobal, |
2004 | PlacementLParen, PlacementArgs, PlacementRParen, |
2005 | TypeIdParens, AllocType, AllocTypeInfo: TInfo, ArraySize, DirectInitRange, |
2006 | Initializer); |
2007 | } |
2008 | |
2009 | static bool isLegalArrayNewInitializer(CXXNewInitializationStyle Style, |
2010 | Expr *Init, bool IsCPlusPlus20) { |
2011 | if (!Init) |
2012 | return true; |
2013 | if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Val: Init)) |
2014 | return IsCPlusPlus20 || PLE->getNumExprs() == 0; |
2015 | if (isa<ImplicitValueInitExpr>(Val: Init)) |
2016 | return true; |
2017 | else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Val: Init)) |
2018 | return !CCE->isListInitialization() && |
2019 | CCE->getConstructor()->isDefaultConstructor(); |
2020 | else if (Style == CXXNewInitializationStyle::Braces) { |
2021 | assert(isa<InitListExpr>(Init) && |
2022 | "Shouldn't create list CXXConstructExprs for arrays." ); |
2023 | return true; |
2024 | } |
2025 | return false; |
2026 | } |
2027 | |
2028 | bool |
2029 | Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const { |
2030 | if (!getLangOpts().AlignedAllocationUnavailable) |
2031 | return false; |
2032 | if (FD.isDefined()) |
2033 | return false; |
2034 | std::optional<unsigned> AlignmentParam; |
2035 | if (FD.isReplaceableGlobalAllocationFunction(AlignmentParam: &AlignmentParam) && |
2036 | AlignmentParam) |
2037 | return true; |
2038 | return false; |
2039 | } |
2040 | |
2041 | // Emit a diagnostic if an aligned allocation/deallocation function that is not |
2042 | // implemented in the standard library is selected. |
2043 | void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, |
2044 | SourceLocation Loc) { |
2045 | if (isUnavailableAlignedAllocationFunction(FD)) { |
2046 | const llvm::Triple &T = getASTContext().getTargetInfo().getTriple(); |
2047 | StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling( |
2048 | getASTContext().getTargetInfo().getPlatformName()); |
2049 | VersionTuple OSVersion = alignedAllocMinVersion(OS: T.getOS()); |
2050 | |
2051 | OverloadedOperatorKind Kind = FD.getDeclName().getCXXOverloadedOperator(); |
2052 | bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete; |
2053 | Diag(Loc, diag::err_aligned_allocation_unavailable) |
2054 | << IsDelete << FD.getType().getAsString() << OSName |
2055 | << OSVersion.getAsString() << OSVersion.empty(); |
2056 | Diag(Loc, diag::note_silence_aligned_allocation_unavailable); |
2057 | } |
2058 | } |
2059 | |
2060 | ExprResult Sema::BuildCXXNew(SourceRange Range, bool UseGlobal, |
2061 | SourceLocation PlacementLParen, |
2062 | MultiExprArg PlacementArgs, |
2063 | SourceLocation PlacementRParen, |
2064 | SourceRange TypeIdParens, QualType AllocType, |
2065 | TypeSourceInfo *AllocTypeInfo, |
2066 | std::optional<Expr *> ArraySize, |
2067 | SourceRange DirectInitRange, Expr *Initializer) { |
2068 | SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange(); |
2069 | SourceLocation StartLoc = Range.getBegin(); |
2070 | |
2071 | CXXNewInitializationStyle InitStyle; |
2072 | if (DirectInitRange.isValid()) { |
2073 | assert(Initializer && "Have parens but no initializer." ); |
2074 | InitStyle = CXXNewInitializationStyle::Parens; |
2075 | } else if (Initializer && isa<InitListExpr>(Val: Initializer)) |
2076 | InitStyle = CXXNewInitializationStyle::Braces; |
2077 | else { |
2078 | assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) || |
2079 | isa<CXXConstructExpr>(Initializer)) && |
2080 | "Initializer expression that cannot have been implicitly created." ); |
2081 | InitStyle = CXXNewInitializationStyle::None; |
2082 | } |
2083 | |
2084 | MultiExprArg Exprs(&Initializer, Initializer ? 1 : 0); |
2085 | if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Val: Initializer)) { |
2086 | assert(InitStyle == CXXNewInitializationStyle::Parens && |
2087 | "paren init for non-call init" ); |
2088 | Exprs = MultiExprArg(List->getExprs(), List->getNumExprs()); |
2089 | } |
2090 | |
2091 | // C++11 [expr.new]p15: |
2092 | // A new-expression that creates an object of type T initializes that |
2093 | // object as follows: |
2094 | InitializationKind Kind = [&] { |
2095 | switch (InitStyle) { |
2096 | // - If the new-initializer is omitted, the object is default- |
2097 | // initialized (8.5); if no initialization is performed, |
2098 | // the object has indeterminate value |
2099 | case CXXNewInitializationStyle::None: |
2100 | return InitializationKind::CreateDefault(InitLoc: TypeRange.getBegin()); |
2101 | // - Otherwise, the new-initializer is interpreted according to the |
2102 | // initialization rules of 8.5 for direct-initialization. |
2103 | case CXXNewInitializationStyle::Parens: |
2104 | return InitializationKind::CreateDirect(InitLoc: TypeRange.getBegin(), |
2105 | LParenLoc: DirectInitRange.getBegin(), |
2106 | RParenLoc: DirectInitRange.getEnd()); |
2107 | case CXXNewInitializationStyle::Braces: |
2108 | return InitializationKind::CreateDirectList(TypeRange.getBegin(), |
2109 | Initializer->getBeginLoc(), |
2110 | Initializer->getEndLoc()); |
2111 | } |
2112 | llvm_unreachable("Unknown initialization kind" ); |
2113 | }(); |
2114 | |
2115 | // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for. |
2116 | auto *Deduced = AllocType->getContainedDeducedType(); |
2117 | if (Deduced && !Deduced->isDeduced() && |
2118 | isa<DeducedTemplateSpecializationType>(Deduced)) { |
2119 | if (ArraySize) |
2120 | return ExprError( |
2121 | Diag(*ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(), |
2122 | diag::err_deduced_class_template_compound_type) |
2123 | << /*array*/ 2 |
2124 | << (*ArraySize ? (*ArraySize)->getSourceRange() : TypeRange)); |
2125 | |
2126 | InitializedEntity Entity |
2127 | = InitializedEntity::InitializeNew(NewLoc: StartLoc, Type: AllocType); |
2128 | AllocType = DeduceTemplateSpecializationFromInitializer( |
2129 | TInfo: AllocTypeInfo, Entity, Kind, Init: Exprs); |
2130 | if (AllocType.isNull()) |
2131 | return ExprError(); |
2132 | } else if (Deduced && !Deduced->isDeduced()) { |
2133 | MultiExprArg Inits = Exprs; |
2134 | bool Braced = (InitStyle == CXXNewInitializationStyle::Braces); |
2135 | if (Braced) { |
2136 | auto *ILE = cast<InitListExpr>(Val: Exprs[0]); |
2137 | Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits()); |
2138 | } |
2139 | |
2140 | if (InitStyle == CXXNewInitializationStyle::None || Inits.empty()) |
2141 | return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg) |
2142 | << AllocType << TypeRange); |
2143 | if (Inits.size() > 1) { |
2144 | Expr *FirstBad = Inits[1]; |
2145 | return ExprError(Diag(FirstBad->getBeginLoc(), |
2146 | diag::err_auto_new_ctor_multiple_expressions) |
2147 | << AllocType << TypeRange); |
2148 | } |
2149 | if (Braced && !getLangOpts().CPlusPlus17) |
2150 | Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init) |
2151 | << AllocType << TypeRange; |
2152 | Expr *Deduce = Inits[0]; |
2153 | if (isa<InitListExpr>(Deduce)) |
2154 | return ExprError( |
2155 | Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces) |
2156 | << Braced << AllocType << TypeRange); |
2157 | QualType DeducedType; |
2158 | TemplateDeductionInfo Info(Deduce->getExprLoc()); |
2159 | TemplateDeductionResult Result = |
2160 | DeduceAutoType(AutoTypeLoc: AllocTypeInfo->getTypeLoc(), Initializer: Deduce, Result&: DeducedType, Info); |
2161 | if (Result != TemplateDeductionResult::Success && |
2162 | Result != TemplateDeductionResult::AlreadyDiagnosed) |
2163 | return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure) |
2164 | << AllocType << Deduce->getType() << TypeRange |
2165 | << Deduce->getSourceRange()); |
2166 | if (DeducedType.isNull()) { |
2167 | assert(Result == TemplateDeductionResult::AlreadyDiagnosed); |
2168 | return ExprError(); |
2169 | } |
2170 | AllocType = DeducedType; |
2171 | } |
2172 | |
2173 | // Per C++0x [expr.new]p5, the type being constructed may be a |
2174 | // typedef of an array type. |
2175 | if (!ArraySize) { |
2176 | if (const ConstantArrayType *Array |
2177 | = Context.getAsConstantArrayType(T: AllocType)) { |
2178 | ArraySize = IntegerLiteral::Create(C: Context, V: Array->getSize(), |
2179 | type: Context.getSizeType(), |
2180 | l: TypeRange.getEnd()); |
2181 | AllocType = Array->getElementType(); |
2182 | } |
2183 | } |
2184 | |
2185 | if (CheckAllocatedType(AllocType, Loc: TypeRange.getBegin(), R: TypeRange)) |
2186 | return ExprError(); |
2187 | |
2188 | if (ArraySize && !checkArrayElementAlignment(EltTy: AllocType, Loc: TypeRange.getBegin())) |
2189 | return ExprError(); |
2190 | |
2191 | // In ARC, infer 'retaining' for the allocated |
2192 | if (getLangOpts().ObjCAutoRefCount && |
2193 | AllocType.getObjCLifetime() == Qualifiers::OCL_None && |
2194 | AllocType->isObjCLifetimeType()) { |
2195 | AllocType = Context.getLifetimeQualifiedType(type: AllocType, |
2196 | lifetime: AllocType->getObjCARCImplicitLifetime()); |
2197 | } |
2198 | |
2199 | QualType ResultType = Context.getPointerType(T: AllocType); |
2200 | |
2201 | if (ArraySize && *ArraySize && |
2202 | (*ArraySize)->getType()->isNonOverloadPlaceholderType()) { |
2203 | ExprResult result = CheckPlaceholderExpr(E: *ArraySize); |
2204 | if (result.isInvalid()) return ExprError(); |
2205 | ArraySize = result.get(); |
2206 | } |
2207 | // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have |
2208 | // integral or enumeration type with a non-negative value." |
2209 | // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped |
2210 | // enumeration type, or a class type for which a single non-explicit |
2211 | // conversion function to integral or unscoped enumeration type exists. |
2212 | // C++1y [expr.new]p6: The expression [...] is implicitly converted to |
2213 | // std::size_t. |
2214 | std::optional<uint64_t> KnownArraySize; |
2215 | if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) { |
2216 | ExprResult ConvertedSize; |
2217 | if (getLangOpts().CPlusPlus14) { |
2218 | assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?" ); |
2219 | |
2220 | ConvertedSize = PerformImplicitConversion(From: *ArraySize, ToType: Context.getSizeType(), |
2221 | Action: AA_Converting); |
2222 | |
2223 | if (!ConvertedSize.isInvalid() && |
2224 | (*ArraySize)->getType()->getAs<RecordType>()) |
2225 | // Diagnose the compatibility of this conversion. |
2226 | Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion) |
2227 | << (*ArraySize)->getType() << 0 << "'size_t'" ; |
2228 | } else { |
2229 | class SizeConvertDiagnoser : public ICEConvertDiagnoser { |
2230 | protected: |
2231 | Expr *ArraySize; |
2232 | |
2233 | public: |
2234 | SizeConvertDiagnoser(Expr *ArraySize) |
2235 | : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false), |
2236 | ArraySize(ArraySize) {} |
2237 | |
2238 | SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, |
2239 | QualType T) override { |
2240 | return S.Diag(Loc, diag::err_array_size_not_integral) |
2241 | << S.getLangOpts().CPlusPlus11 << T; |
2242 | } |
2243 | |
2244 | SemaDiagnosticBuilder diagnoseIncomplete( |
2245 | Sema &S, SourceLocation Loc, QualType T) override { |
2246 | return S.Diag(Loc, diag::err_array_size_incomplete_type) |
2247 | << T << ArraySize->getSourceRange(); |
2248 | } |
2249 | |
2250 | SemaDiagnosticBuilder diagnoseExplicitConv( |
2251 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { |
2252 | return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy; |
2253 | } |
2254 | |
2255 | SemaDiagnosticBuilder noteExplicitConv( |
2256 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { |
2257 | return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) |
2258 | << ConvTy->isEnumeralType() << ConvTy; |
2259 | } |
2260 | |
2261 | SemaDiagnosticBuilder diagnoseAmbiguous( |
2262 | Sema &S, SourceLocation Loc, QualType T) override { |
2263 | return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T; |
2264 | } |
2265 | |
2266 | SemaDiagnosticBuilder noteAmbiguous( |
2267 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { |
2268 | return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) |
2269 | << ConvTy->isEnumeralType() << ConvTy; |
2270 | } |
2271 | |
2272 | SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, |
2273 | QualType T, |
2274 | QualType ConvTy) override { |
2275 | return S.Diag(Loc, |
2276 | S.getLangOpts().CPlusPlus11 |
2277 | ? diag::warn_cxx98_compat_array_size_conversion |
2278 | : diag::ext_array_size_conversion) |
2279 | << T << ConvTy->isEnumeralType() << ConvTy; |
2280 | } |
2281 | } SizeDiagnoser(*ArraySize); |
2282 | |
2283 | ConvertedSize = PerformContextualImplicitConversion(Loc: StartLoc, FromE: *ArraySize, |
2284 | Converter&: SizeDiagnoser); |
2285 | } |
2286 | if (ConvertedSize.isInvalid()) |
2287 | return ExprError(); |
2288 | |
2289 | ArraySize = ConvertedSize.get(); |
2290 | QualType SizeType = (*ArraySize)->getType(); |
2291 | |
2292 | if (!SizeType->isIntegralOrUnscopedEnumerationType()) |
2293 | return ExprError(); |
2294 | |
2295 | // C++98 [expr.new]p7: |
2296 | // The expression in a direct-new-declarator shall have integral type |
2297 | // with a non-negative value. |
2298 | // |
2299 | // Let's see if this is a constant < 0. If so, we reject it out of hand, |
2300 | // per CWG1464. Otherwise, if it's not a constant, we must have an |
2301 | // unparenthesized array type. |
2302 | |
2303 | // We've already performed any required implicit conversion to integer or |
2304 | // unscoped enumeration type. |
2305 | // FIXME: Per CWG1464, we are required to check the value prior to |
2306 | // converting to size_t. This will never find a negative array size in |
2307 | // C++14 onwards, because Value is always unsigned here! |
2308 | if (std::optional<llvm::APSInt> Value = |
2309 | (*ArraySize)->getIntegerConstantExpr(Ctx: Context)) { |
2310 | if (Value->isSigned() && Value->isNegative()) { |
2311 | return ExprError(Diag((*ArraySize)->getBeginLoc(), |
2312 | diag::err_typecheck_negative_array_size) |
2313 | << (*ArraySize)->getSourceRange()); |
2314 | } |
2315 | |
2316 | if (!AllocType->isDependentType()) { |
2317 | unsigned ActiveSizeBits = |
2318 | ConstantArrayType::getNumAddressingBits(Context, ElementType: AllocType, NumElements: *Value); |
2319 | if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) |
2320 | return ExprError( |
2321 | Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large) |
2322 | << toString(*Value, 10) << (*ArraySize)->getSourceRange()); |
2323 | } |
2324 | |
2325 | KnownArraySize = Value->getZExtValue(); |
2326 | } else if (TypeIdParens.isValid()) { |
2327 | // Can't have dynamic array size when the type-id is in parentheses. |
2328 | Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst) |
2329 | << (*ArraySize)->getSourceRange() |
2330 | << FixItHint::CreateRemoval(TypeIdParens.getBegin()) |
2331 | << FixItHint::CreateRemoval(TypeIdParens.getEnd()); |
2332 | |
2333 | TypeIdParens = SourceRange(); |
2334 | } |
2335 | |
2336 | // Note that we do *not* convert the argument in any way. It can |
2337 | // be signed, larger than size_t, whatever. |
2338 | } |
2339 | |
2340 | FunctionDecl *OperatorNew = nullptr; |
2341 | FunctionDecl *OperatorDelete = nullptr; |
2342 | unsigned Alignment = |
2343 | AllocType->isDependentType() ? 0 : Context.getTypeAlign(T: AllocType); |
2344 | unsigned NewAlignment = Context.getTargetInfo().getNewAlign(); |
2345 | bool PassAlignment = getLangOpts().AlignedAllocation && |
2346 | Alignment > NewAlignment; |
2347 | |
2348 | if (CheckArgsForPlaceholders(args: PlacementArgs)) |
2349 | return ExprError(); |
2350 | |
2351 | AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both; |
2352 | if (!AllocType->isDependentType() && |
2353 | !Expr::hasAnyTypeDependentArguments(Exprs: PlacementArgs) && |
2354 | FindAllocationFunctions( |
2355 | StartLoc, Range: SourceRange(PlacementLParen, PlacementRParen), NewScope: Scope, DeleteScope: Scope, |
2356 | AllocType, IsArray: ArraySize.has_value(), PassAlignment, PlaceArgs: PlacementArgs, |
2357 | OperatorNew, OperatorDelete)) |
2358 | return ExprError(); |
2359 | |
2360 | // If this is an array allocation, compute whether the usual array |
2361 | // deallocation function for the type has a size_t parameter. |
2362 | bool UsualArrayDeleteWantsSize = false; |
2363 | if (ArraySize && !AllocType->isDependentType()) |
2364 | UsualArrayDeleteWantsSize = |
2365 | doesUsualArrayDeleteWantSize(S&: *this, loc: StartLoc, allocType: AllocType); |
2366 | |
2367 | SmallVector<Expr *, 8> AllPlaceArgs; |
2368 | if (OperatorNew) { |
2369 | auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>(); |
2370 | VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction |
2371 | : VariadicDoesNotApply; |
2372 | |
2373 | // We've already converted the placement args, just fill in any default |
2374 | // arguments. Skip the first parameter because we don't have a corresponding |
2375 | // argument. Skip the second parameter too if we're passing in the |
2376 | // alignment; we've already filled it in. |
2377 | unsigned NumImplicitArgs = PassAlignment ? 2 : 1; |
2378 | if (GatherArgumentsForCall(CallLoc: PlacementLParen, FDecl: OperatorNew, Proto: Proto, |
2379 | FirstParam: NumImplicitArgs, Args: PlacementArgs, AllArgs&: AllPlaceArgs, |
2380 | CallType)) |
2381 | return ExprError(); |
2382 | |
2383 | if (!AllPlaceArgs.empty()) |
2384 | PlacementArgs = AllPlaceArgs; |
2385 | |
2386 | // We would like to perform some checking on the given `operator new` call, |
2387 | // but the PlacementArgs does not contain the implicit arguments, |
2388 | // namely allocation size and maybe allocation alignment, |
2389 | // so we need to conjure them. |
2390 | |
2391 | QualType SizeTy = Context.getSizeType(); |
2392 | unsigned SizeTyWidth = Context.getTypeSize(T: SizeTy); |
2393 | |
2394 | llvm::APInt SingleEltSize( |
2395 | SizeTyWidth, Context.getTypeSizeInChars(T: AllocType).getQuantity()); |
2396 | |
2397 | // How many bytes do we want to allocate here? |
2398 | std::optional<llvm::APInt> AllocationSize; |
2399 | if (!ArraySize && !AllocType->isDependentType()) { |
2400 | // For non-array operator new, we only want to allocate one element. |
2401 | AllocationSize = SingleEltSize; |
2402 | } else if (KnownArraySize && !AllocType->isDependentType()) { |
2403 | // For array operator new, only deal with static array size case. |
2404 | bool Overflow; |
2405 | AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize) |
2406 | .umul_ov(RHS: SingleEltSize, Overflow); |
2407 | (void)Overflow; |
2408 | assert( |
2409 | !Overflow && |
2410 | "Expected that all the overflows would have been handled already." ); |
2411 | } |
2412 | |
2413 | IntegerLiteral AllocationSizeLiteral( |
2414 | Context, AllocationSize.value_or(u: llvm::APInt::getZero(numBits: SizeTyWidth)), |
2415 | SizeTy, SourceLocation()); |
2416 | // Otherwise, if we failed to constant-fold the allocation size, we'll |
2417 | // just give up and pass-in something opaque, that isn't a null pointer. |
2418 | OpaqueValueExpr OpaqueAllocationSize(SourceLocation(), SizeTy, VK_PRValue, |
2419 | OK_Ordinary, /*SourceExpr=*/nullptr); |
2420 | |
2421 | // Let's synthesize the alignment argument in case we will need it. |
2422 | // Since we *really* want to allocate these on stack, this is slightly ugly |
2423 | // because there might not be a `std::align_val_t` type. |
2424 | EnumDecl *StdAlignValT = getStdAlignValT(); |
2425 | QualType AlignValT = |
2426 | StdAlignValT ? Context.getTypeDeclType(StdAlignValT) : SizeTy; |
2427 | IntegerLiteral AlignmentLiteral( |
2428 | Context, |
2429 | llvm::APInt(Context.getTypeSize(T: SizeTy), |
2430 | Alignment / Context.getCharWidth()), |
2431 | SizeTy, SourceLocation()); |
2432 | ImplicitCastExpr DesiredAlignment(ImplicitCastExpr::OnStack, AlignValT, |
2433 | CK_IntegralCast, &AlignmentLiteral, |
2434 | VK_PRValue, FPOptionsOverride()); |
2435 | |
2436 | // Adjust placement args by prepending conjured size and alignment exprs. |
2437 | llvm::SmallVector<Expr *, 8> CallArgs; |
2438 | CallArgs.reserve(N: NumImplicitArgs + PlacementArgs.size()); |
2439 | CallArgs.emplace_back(AllocationSize |
2440 | ? static_cast<Expr *>(&AllocationSizeLiteral) |
2441 | : &OpaqueAllocationSize); |
2442 | if (PassAlignment) |
2443 | CallArgs.emplace_back(Args: &DesiredAlignment); |
2444 | CallArgs.insert(I: CallArgs.end(), From: PlacementArgs.begin(), To: PlacementArgs.end()); |
2445 | |
2446 | DiagnoseSentinelCalls(OperatorNew, PlacementLParen, CallArgs); |
2447 | |
2448 | checkCall(FDecl: OperatorNew, Proto: Proto, /*ThisArg=*/nullptr, Args: CallArgs, |
2449 | /*IsMemberFunction=*/false, Loc: StartLoc, Range, CallType); |
2450 | |
2451 | // Warn if the type is over-aligned and is being allocated by (unaligned) |
2452 | // global operator new. |
2453 | if (PlacementArgs.empty() && !PassAlignment && |
2454 | (OperatorNew->isImplicit() || |
2455 | (OperatorNew->getBeginLoc().isValid() && |
2456 | getSourceManager().isInSystemHeader(Loc: OperatorNew->getBeginLoc())))) { |
2457 | if (Alignment > NewAlignment) |
2458 | Diag(StartLoc, diag::warn_overaligned_type) |
2459 | << AllocType |
2460 | << unsigned(Alignment / Context.getCharWidth()) |
2461 | << unsigned(NewAlignment / Context.getCharWidth()); |
2462 | } |
2463 | } |
2464 | |
2465 | // Array 'new' can't have any initializers except empty parentheses. |
2466 | // Initializer lists are also allowed, in C++11. Rely on the parser for the |
2467 | // dialect distinction. |
2468 | if (ArraySize && !isLegalArrayNewInitializer(Style: InitStyle, Init: Initializer, |
2469 | IsCPlusPlus20: getLangOpts().CPlusPlus20)) { |
2470 | SourceRange InitRange(Exprs.front()->getBeginLoc(), |
2471 | Exprs.back()->getEndLoc()); |
2472 | Diag(StartLoc, diag::err_new_array_init_args) << InitRange; |
2473 | return ExprError(); |
2474 | } |
2475 | |
2476 | // If we can perform the initialization, and we've not already done so, |
2477 | // do it now. |
2478 | if (!AllocType->isDependentType() && |
2479 | !Expr::hasAnyTypeDependentArguments(Exprs)) { |
2480 | // The type we initialize is the complete type, including the array bound. |
2481 | QualType InitType; |
2482 | if (KnownArraySize) |
2483 | InitType = Context.getConstantArrayType( |
2484 | EltTy: AllocType, |
2485 | ArySize: llvm::APInt(Context.getTypeSize(T: Context.getSizeType()), |
2486 | *KnownArraySize), |
2487 | SizeExpr: *ArraySize, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0); |
2488 | else if (ArraySize) |
2489 | InitType = Context.getIncompleteArrayType(EltTy: AllocType, |
2490 | ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0); |
2491 | else |
2492 | InitType = AllocType; |
2493 | |
2494 | InitializedEntity Entity |
2495 | = InitializedEntity::InitializeNew(NewLoc: StartLoc, Type: InitType); |
2496 | InitializationSequence InitSeq(*this, Entity, Kind, Exprs); |
2497 | ExprResult FullInit = InitSeq.Perform(S&: *this, Entity, Kind, Args: Exprs); |
2498 | if (FullInit.isInvalid()) |
2499 | return ExprError(); |
2500 | |
2501 | // FullInit is our initializer; strip off CXXBindTemporaryExprs, because |
2502 | // we don't want the initialized object to be destructed. |
2503 | // FIXME: We should not create these in the first place. |
2504 | if (CXXBindTemporaryExpr *Binder = |
2505 | dyn_cast_or_null<CXXBindTemporaryExpr>(Val: FullInit.get())) |
2506 | FullInit = Binder->getSubExpr(); |
2507 | |
2508 | Initializer = FullInit.get(); |
2509 | |
2510 | // FIXME: If we have a KnownArraySize, check that the array bound of the |
2511 | // initializer is no greater than that constant value. |
2512 | |
2513 | if (ArraySize && !*ArraySize) { |
2514 | auto *CAT = Context.getAsConstantArrayType(T: Initializer->getType()); |
2515 | if (CAT) { |
2516 | // FIXME: Track that the array size was inferred rather than explicitly |
2517 | // specified. |
2518 | ArraySize = IntegerLiteral::Create( |
2519 | C: Context, V: CAT->getSize(), type: Context.getSizeType(), l: TypeRange.getEnd()); |
2520 | } else { |
2521 | Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init) |
2522 | << Initializer->getSourceRange(); |
2523 | } |
2524 | } |
2525 | } |
2526 | |
2527 | // Mark the new and delete operators as referenced. |
2528 | if (OperatorNew) { |
2529 | if (DiagnoseUseOfDecl(OperatorNew, StartLoc)) |
2530 | return ExprError(); |
2531 | MarkFunctionReferenced(Loc: StartLoc, Func: OperatorNew); |
2532 | } |
2533 | if (OperatorDelete) { |
2534 | if (DiagnoseUseOfDecl(OperatorDelete, StartLoc)) |
2535 | return ExprError(); |
2536 | MarkFunctionReferenced(Loc: StartLoc, Func: OperatorDelete); |
2537 | } |
2538 | |
2539 | return CXXNewExpr::Create(Ctx: Context, IsGlobalNew: UseGlobal, OperatorNew, OperatorDelete, |
2540 | ShouldPassAlignment: PassAlignment, UsualArrayDeleteWantsSize, |
2541 | PlacementArgs, TypeIdParens, ArraySize, InitializationStyle: InitStyle, |
2542 | Initializer, Ty: ResultType, AllocatedTypeInfo: AllocTypeInfo, Range, |
2543 | DirectInitRange); |
2544 | } |
2545 | |
2546 | /// Checks that a type is suitable as the allocated type |
2547 | /// in a new-expression. |
2548 | bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc, |
2549 | SourceRange R) { |
2550 | // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an |
2551 | // abstract class type or array thereof. |
2552 | if (AllocType->isFunctionType()) |
2553 | return Diag(Loc, diag::err_bad_new_type) |
2554 | << AllocType << 0 << R; |
2555 | else if (AllocType->isReferenceType()) |
2556 | return Diag(Loc, diag::err_bad_new_type) |
2557 | << AllocType << 1 << R; |
2558 | else if (!AllocType->isDependentType() && |
2559 | RequireCompleteSizedType( |
2560 | Loc, AllocType, diag::err_new_incomplete_or_sizeless_type, R)) |
2561 | return true; |
2562 | else if (RequireNonAbstractType(Loc, AllocType, |
2563 | diag::err_allocation_of_abstract_type)) |
2564 | return true; |
2565 | else if (AllocType->isVariablyModifiedType()) |
2566 | return Diag(Loc, diag::err_variably_modified_new_type) |
2567 | << AllocType; |
2568 | else if (AllocType.getAddressSpace() != LangAS::Default && |
2569 | !getLangOpts().OpenCLCPlusPlus) |
2570 | return Diag(Loc, diag::err_address_space_qualified_new) |
2571 | << AllocType.getUnqualifiedType() |
2572 | << AllocType.getQualifiers().getAddressSpaceAttributePrintValue(); |
2573 | else if (getLangOpts().ObjCAutoRefCount) { |
2574 | if (const ArrayType *AT = Context.getAsArrayType(T: AllocType)) { |
2575 | QualType BaseAllocType = Context.getBaseElementType(VAT: AT); |
2576 | if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None && |
2577 | BaseAllocType->isObjCLifetimeType()) |
2578 | return Diag(Loc, diag::err_arc_new_array_without_ownership) |
2579 | << BaseAllocType; |
2580 | } |
2581 | } |
2582 | |
2583 | return false; |
2584 | } |
2585 | |
2586 | static bool resolveAllocationOverload( |
2587 | Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args, |
2588 | bool &PassAlignment, FunctionDecl *&Operator, |
2589 | OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) { |
2590 | OverloadCandidateSet Candidates(R.getNameLoc(), |
2591 | OverloadCandidateSet::CSK_Normal); |
2592 | for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end(); |
2593 | Alloc != AllocEnd; ++Alloc) { |
2594 | // Even member operator new/delete are implicitly treated as |
2595 | // static, so don't use AddMemberCandidate. |
2596 | NamedDecl *D = (*Alloc)->getUnderlyingDecl(); |
2597 | |
2598 | if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(Val: D)) { |
2599 | S.AddTemplateOverloadCandidate(FunctionTemplate: FnTemplate, FoundDecl: Alloc.getPair(), |
2600 | /*ExplicitTemplateArgs=*/nullptr, Args, |
2601 | CandidateSet&: Candidates, |
2602 | /*SuppressUserConversions=*/false); |
2603 | continue; |
2604 | } |
2605 | |
2606 | FunctionDecl *Fn = cast<FunctionDecl>(Val: D); |
2607 | S.AddOverloadCandidate(Function: Fn, FoundDecl: Alloc.getPair(), Args, CandidateSet&: Candidates, |
2608 | /*SuppressUserConversions=*/false); |
2609 | } |
2610 | |
2611 | // Do the resolution. |
2612 | OverloadCandidateSet::iterator Best; |
2613 | switch (Candidates.BestViableFunction(S, Loc: R.getNameLoc(), Best)) { |
2614 | case OR_Success: { |
2615 | // Got one! |
2616 | FunctionDecl *FnDecl = Best->Function; |
2617 | if (S.CheckAllocationAccess(OperatorLoc: R.getNameLoc(), PlacementRange: Range, NamingClass: R.getNamingClass(), |
2618 | FoundDecl: Best->FoundDecl) == Sema::AR_inaccessible) |
2619 | return true; |
2620 | |
2621 | Operator = FnDecl; |
2622 | return false; |
2623 | } |
2624 | |
2625 | case OR_No_Viable_Function: |
2626 | // C++17 [expr.new]p13: |
2627 | // If no matching function is found and the allocated object type has |
2628 | // new-extended alignment, the alignment argument is removed from the |
2629 | // argument list, and overload resolution is performed again. |
2630 | if (PassAlignment) { |
2631 | PassAlignment = false; |
2632 | AlignArg = Args[1]; |
2633 | Args.erase(CI: Args.begin() + 1); |
2634 | return resolveAllocationOverload(S, R, Range, Args, PassAlignment, |
2635 | Operator, AlignedCandidates: &Candidates, AlignArg, |
2636 | Diagnose); |
2637 | } |
2638 | |
2639 | // MSVC will fall back on trying to find a matching global operator new |
2640 | // if operator new[] cannot be found. Also, MSVC will leak by not |
2641 | // generating a call to operator delete or operator delete[], but we |
2642 | // will not replicate that bug. |
2643 | // FIXME: Find out how this interacts with the std::align_val_t fallback |
2644 | // once MSVC implements it. |
2645 | if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New && |
2646 | S.Context.getLangOpts().MSVCCompat) { |
2647 | R.clear(); |
2648 | R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(Op: OO_New)); |
2649 | S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl()); |
2650 | // FIXME: This will give bad diagnostics pointing at the wrong functions. |
2651 | return resolveAllocationOverload(S, R, Range, Args, PassAlignment, |
2652 | Operator, /*Candidates=*/AlignedCandidates: nullptr, |
2653 | /*AlignArg=*/nullptr, Diagnose); |
2654 | } |
2655 | |
2656 | if (Diagnose) { |
2657 | // If this is an allocation of the form 'new (p) X' for some object |
2658 | // pointer p (or an expression that will decay to such a pointer), |
2659 | // diagnose the missing inclusion of <new>. |
2660 | if (!R.isClassLookup() && Args.size() == 2 && |
2661 | (Args[1]->getType()->isObjectPointerType() || |
2662 | Args[1]->getType()->isArrayType())) { |
2663 | S.Diag(R.getNameLoc(), diag::err_need_header_before_placement_new) |
2664 | << R.getLookupName() << Range; |
2665 | // Listing the candidates is unlikely to be useful; skip it. |
2666 | return true; |
2667 | } |
2668 | |
2669 | // Finish checking all candidates before we note any. This checking can |
2670 | // produce additional diagnostics so can't be interleaved with our |
2671 | // emission of notes. |
2672 | // |
2673 | // For an aligned allocation, separately check the aligned and unaligned |
2674 | // candidates with their respective argument lists. |
2675 | SmallVector<OverloadCandidate*, 32> Cands; |
2676 | SmallVector<OverloadCandidate*, 32> AlignedCands; |
2677 | llvm::SmallVector<Expr*, 4> AlignedArgs; |
2678 | if (AlignedCandidates) { |
2679 | auto IsAligned = [](OverloadCandidate &C) { |
2680 | return C.Function->getNumParams() > 1 && |
2681 | C.Function->getParamDecl(1)->getType()->isAlignValT(); |
2682 | }; |
2683 | auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); }; |
2684 | |
2685 | AlignedArgs.reserve(N: Args.size() + 1); |
2686 | AlignedArgs.push_back(Elt: Args[0]); |
2687 | AlignedArgs.push_back(Elt: AlignArg); |
2688 | AlignedArgs.append(in_start: Args.begin() + 1, in_end: Args.end()); |
2689 | AlignedCands = AlignedCandidates->CompleteCandidates( |
2690 | S, OCD_AllCandidates, AlignedArgs, R.getNameLoc(), IsAligned); |
2691 | |
2692 | Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args, |
2693 | R.getNameLoc(), IsUnaligned); |
2694 | } else { |
2695 | Cands = Candidates.CompleteCandidates(S, OCD: OCD_AllCandidates, Args, |
2696 | OpLoc: R.getNameLoc()); |
2697 | } |
2698 | |
2699 | S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call) |
2700 | << R.getLookupName() << Range; |
2701 | if (AlignedCandidates) |
2702 | AlignedCandidates->NoteCandidates(S, Args: AlignedArgs, Cands: AlignedCands, Opc: "" , |
2703 | OpLoc: R.getNameLoc()); |
2704 | Candidates.NoteCandidates(S, Args, Cands, Opc: "" , OpLoc: R.getNameLoc()); |
2705 | } |
2706 | return true; |
2707 | |
2708 | case OR_Ambiguous: |
2709 | if (Diagnose) { |
2710 | Candidates.NoteCandidates( |
2711 | PartialDiagnosticAt(R.getNameLoc(), |
2712 | S.PDiag(diag::err_ovl_ambiguous_call) |
2713 | << R.getLookupName() << Range), |
2714 | S, OCD_AmbiguousCandidates, Args); |
2715 | } |
2716 | return true; |
2717 | |
2718 | case OR_Deleted: { |
2719 | if (Diagnose) |
2720 | S.DiagnoseUseOfDeletedFunction(Loc: R.getNameLoc(), Range, Name: R.getLookupName(), |
2721 | CandidateSet&: Candidates, Fn: Best->Function, Args); |
2722 | return true; |
2723 | } |
2724 | } |
2725 | llvm_unreachable("Unreachable, bad result from BestViableFunction" ); |
2726 | } |
2727 | |
2728 | bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, |
2729 | AllocationFunctionScope NewScope, |
2730 | AllocationFunctionScope DeleteScope, |
2731 | QualType AllocType, bool IsArray, |
2732 | bool &PassAlignment, MultiExprArg PlaceArgs, |
2733 | FunctionDecl *&OperatorNew, |
2734 | FunctionDecl *&OperatorDelete, |
2735 | bool Diagnose) { |
2736 | // --- Choosing an allocation function --- |
2737 | // C++ 5.3.4p8 - 14 & 18 |
2738 | // 1) If looking in AFS_Global scope for allocation functions, only look in |
2739 | // the global scope. Else, if AFS_Class, only look in the scope of the |
2740 | // allocated class. If AFS_Both, look in both. |
2741 | // 2) If an array size is given, look for operator new[], else look for |
2742 | // operator new. |
2743 | // 3) The first argument is always size_t. Append the arguments from the |
2744 | // placement form. |
2745 | |
2746 | SmallVector<Expr*, 8> AllocArgs; |
2747 | AllocArgs.reserve(N: (PassAlignment ? 2 : 1) + PlaceArgs.size()); |
2748 | |
2749 | // We don't care about the actual value of these arguments. |
2750 | // FIXME: Should the Sema create the expression and embed it in the syntax |
2751 | // tree? Or should the consumer just recalculate the value? |
2752 | // FIXME: Using a dummy value will interact poorly with attribute enable_if. |
2753 | QualType SizeTy = Context.getSizeType(); |
2754 | unsigned SizeTyWidth = Context.getTypeSize(T: SizeTy); |
2755 | IntegerLiteral Size(Context, llvm::APInt::getZero(numBits: SizeTyWidth), SizeTy, |
2756 | SourceLocation()); |
2757 | AllocArgs.push_back(&Size); |
2758 | |
2759 | QualType AlignValT = Context.VoidTy; |
2760 | if (PassAlignment) { |
2761 | DeclareGlobalNewDelete(); |
2762 | AlignValT = Context.getTypeDeclType(getStdAlignValT()); |
2763 | } |
2764 | CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation()); |
2765 | if (PassAlignment) |
2766 | AllocArgs.push_back(&Align); |
2767 | |
2768 | AllocArgs.insert(I: AllocArgs.end(), From: PlaceArgs.begin(), To: PlaceArgs.end()); |
2769 | |
2770 | // C++ [expr.new]p8: |
2771 | // If the allocated type is a non-array type, the allocation |
2772 | // function's name is operator new and the deallocation function's |
2773 | // name is operator delete. If the allocated type is an array |
2774 | // type, the allocation function's name is operator new[] and the |
2775 | // deallocation function's name is operator delete[]. |
2776 | DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName( |
2777 | Op: IsArray ? OO_Array_New : OO_New); |
2778 | |
2779 | QualType AllocElemType = Context.getBaseElementType(QT: AllocType); |
2780 | |
2781 | // Find the allocation function. |
2782 | { |
2783 | LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName); |
2784 | |
2785 | // C++1z [expr.new]p9: |
2786 | // If the new-expression begins with a unary :: operator, the allocation |
2787 | // function's name is looked up in the global scope. Otherwise, if the |
2788 | // allocated type is a class type T or array thereof, the allocation |
2789 | // function's name is looked up in the scope of T. |
2790 | if (AllocElemType->isRecordType() && NewScope != AFS_Global) |
2791 | LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl()); |
2792 | |
2793 | // We can see ambiguity here if the allocation function is found in |
2794 | // multiple base classes. |
2795 | if (R.isAmbiguous()) |
2796 | return true; |
2797 | |
2798 | // If this lookup fails to find the name, or if the allocated type is not |
2799 | // a class type, the allocation function's name is looked up in the |
2800 | // global scope. |
2801 | if (R.empty()) { |
2802 | if (NewScope == AFS_Class) |
2803 | return true; |
2804 | |
2805 | LookupQualifiedName(R, Context.getTranslationUnitDecl()); |
2806 | } |
2807 | |
2808 | if (getLangOpts().OpenCLCPlusPlus && R.empty()) { |
2809 | if (PlaceArgs.empty()) { |
2810 | Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new" ; |
2811 | } else { |
2812 | Diag(StartLoc, diag::err_openclcxx_placement_new); |
2813 | } |
2814 | return true; |
2815 | } |
2816 | |
2817 | assert(!R.empty() && "implicitly declared allocation functions not found" ); |
2818 | assert(!R.isAmbiguous() && "global allocation functions are ambiguous" ); |
2819 | |
2820 | // We do our own custom access checks below. |
2821 | R.suppressDiagnostics(); |
2822 | |
2823 | if (resolveAllocationOverload(S&: *this, R, Range, Args&: AllocArgs, PassAlignment, |
2824 | Operator&: OperatorNew, /*Candidates=*/AlignedCandidates: nullptr, |
2825 | /*AlignArg=*/nullptr, Diagnose)) |
2826 | return true; |
2827 | } |
2828 | |
2829 | // We don't need an operator delete if we're running under -fno-exceptions. |
2830 | if (!getLangOpts().Exceptions) { |
2831 | OperatorDelete = nullptr; |
2832 | return false; |
2833 | } |
2834 | |
2835 | // Note, the name of OperatorNew might have been changed from array to |
2836 | // non-array by resolveAllocationOverload. |
2837 | DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( |
2838 | Op: OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New |
2839 | ? OO_Array_Delete |
2840 | : OO_Delete); |
2841 | |
2842 | // C++ [expr.new]p19: |
2843 | // |
2844 | // If the new-expression begins with a unary :: operator, the |
2845 | // deallocation function's name is looked up in the global |
2846 | // scope. Otherwise, if the allocated type is a class type T or an |
2847 | // array thereof, the deallocation function's name is looked up in |
2848 | // the scope of T. If this lookup fails to find the name, or if |
2849 | // the allocated type is not a class type or array thereof, the |
2850 | // deallocation function's name is looked up in the global scope. |
2851 | LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName); |
2852 | if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) { |
2853 | auto *RD = |
2854 | cast<CXXRecordDecl>(Val: AllocElemType->castAs<RecordType>()->getDecl()); |
2855 | LookupQualifiedName(FoundDelete, RD); |
2856 | } |
2857 | if (FoundDelete.isAmbiguous()) |
2858 | return true; // FIXME: clean up expressions? |
2859 | |
2860 | // Filter out any destroying operator deletes. We can't possibly call such a |
2861 | // function in this context, because we're handling the case where the object |
2862 | // was not successfully constructed. |
2863 | // FIXME: This is not covered by the language rules yet. |
2864 | { |
2865 | LookupResult::Filter Filter = FoundDelete.makeFilter(); |
2866 | while (Filter.hasNext()) { |
2867 | auto *FD = dyn_cast<FunctionDecl>(Val: Filter.next()->getUnderlyingDecl()); |
2868 | if (FD && FD->isDestroyingOperatorDelete()) |
2869 | Filter.erase(); |
2870 | } |
2871 | Filter.done(); |
2872 | } |
2873 | |
2874 | bool FoundGlobalDelete = FoundDelete.empty(); |
2875 | if (FoundDelete.empty()) { |
2876 | FoundDelete.clear(Kind: LookupOrdinaryName); |
2877 | |
2878 | if (DeleteScope == AFS_Class) |
2879 | return true; |
2880 | |
2881 | DeclareGlobalNewDelete(); |
2882 | LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); |
2883 | } |
2884 | |
2885 | FoundDelete.suppressDiagnostics(); |
2886 | |
2887 | SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches; |
2888 | |
2889 | // Whether we're looking for a placement operator delete is dictated |
2890 | // by whether we selected a placement operator new, not by whether |
2891 | // we had explicit placement arguments. This matters for things like |
2892 | // struct A { void *operator new(size_t, int = 0); ... }; |
2893 | // A *a = new A() |
2894 | // |
2895 | // We don't have any definition for what a "placement allocation function" |
2896 | // is, but we assume it's any allocation function whose |
2897 | // parameter-declaration-clause is anything other than (size_t). |
2898 | // |
2899 | // FIXME: Should (size_t, std::align_val_t) also be considered non-placement? |
2900 | // This affects whether an exception from the constructor of an overaligned |
2901 | // type uses the sized or non-sized form of aligned operator delete. |
2902 | bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 || |
2903 | OperatorNew->isVariadic(); |
2904 | |
2905 | if (isPlacementNew) { |
2906 | // C++ [expr.new]p20: |
2907 | // A declaration of a placement deallocation function matches the |
2908 | // declaration of a placement allocation function if it has the |
2909 | // same number of parameters and, after parameter transformations |
2910 | // (8.3.5), all parameter types except the first are |
2911 | // identical. [...] |
2912 | // |
2913 | // To perform this comparison, we compute the function type that |
2914 | // the deallocation function should have, and use that type both |
2915 | // for template argument deduction and for comparison purposes. |
2916 | QualType ExpectedFunctionType; |
2917 | { |
2918 | auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>(); |
2919 | |
2920 | SmallVector<QualType, 4> ArgTypes; |
2921 | ArgTypes.push_back(Elt: Context.VoidPtrTy); |
2922 | for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I) |
2923 | ArgTypes.push_back(Elt: Proto->getParamType(I)); |
2924 | |
2925 | FunctionProtoType::ExtProtoInfo EPI; |
2926 | // FIXME: This is not part of the standard's rule. |
2927 | EPI.Variadic = Proto->isVariadic(); |
2928 | |
2929 | ExpectedFunctionType |
2930 | = Context.getFunctionType(ResultTy: Context.VoidTy, Args: ArgTypes, EPI); |
2931 | } |
2932 | |
2933 | for (LookupResult::iterator D = FoundDelete.begin(), |
2934 | DEnd = FoundDelete.end(); |
2935 | D != DEnd; ++D) { |
2936 | FunctionDecl *Fn = nullptr; |
2937 | if (FunctionTemplateDecl *FnTmpl = |
2938 | dyn_cast<FunctionTemplateDecl>(Val: (*D)->getUnderlyingDecl())) { |
2939 | // Perform template argument deduction to try to match the |
2940 | // expected function type. |
2941 | TemplateDeductionInfo Info(StartLoc); |
2942 | if (DeduceTemplateArguments(FunctionTemplate: FnTmpl, ExplicitTemplateArgs: nullptr, ArgFunctionType: ExpectedFunctionType, Specialization&: Fn, |
2943 | Info) != TemplateDeductionResult::Success) |
2944 | continue; |
2945 | } else |
2946 | Fn = cast<FunctionDecl>(Val: (*D)->getUnderlyingDecl()); |
2947 | |
2948 | if (Context.hasSameType(adjustCCAndNoReturn(ArgFunctionType: Fn->getType(), |
2949 | FunctionType: ExpectedFunctionType, |
2950 | /*AdjustExcpetionSpec*/AdjustExceptionSpec: true), |
2951 | ExpectedFunctionType)) |
2952 | Matches.push_back(Elt: std::make_pair(x: D.getPair(), y&: Fn)); |
2953 | } |
2954 | |
2955 | if (getLangOpts().CUDA) |
2956 | CUDA().EraseUnwantedMatches(Caller: getCurFunctionDecl(/*AllowLambda=*/true), |
2957 | Matches); |
2958 | } else { |
2959 | // C++1y [expr.new]p22: |
2960 | // For a non-placement allocation function, the normal deallocation |
2961 | // function lookup is used |
2962 | // |
2963 | // Per [expr.delete]p10, this lookup prefers a member operator delete |
2964 | // without a size_t argument, but prefers a non-member operator delete |
2965 | // with a size_t where possible (which it always is in this case). |
2966 | llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns; |
2967 | UsualDeallocFnInfo Selected = resolveDeallocationOverload( |
2968 | S&: *this, R&: FoundDelete, /*WantSize*/ FoundGlobalDelete, |
2969 | /*WantAlign*/ hasNewExtendedAlignment(S&: *this, AllocType: AllocElemType), |
2970 | BestFns: &BestDeallocFns); |
2971 | if (Selected) |
2972 | Matches.push_back(Elt: std::make_pair(x&: Selected.Found, y&: Selected.FD)); |
2973 | else { |
2974 | // If we failed to select an operator, all remaining functions are viable |
2975 | // but ambiguous. |
2976 | for (auto Fn : BestDeallocFns) |
2977 | Matches.push_back(Elt: std::make_pair(x&: Fn.Found, y&: Fn.FD)); |
2978 | } |
2979 | } |
2980 | |
2981 | // C++ [expr.new]p20: |
2982 | // [...] If the lookup finds a single matching deallocation |
2983 | // function, that function will be called; otherwise, no |
2984 | // deallocation function will be called. |
2985 | if (Matches.size() == 1) { |
2986 | OperatorDelete = Matches[0].second; |
2987 | |
2988 | // C++1z [expr.new]p23: |
2989 | // If the lookup finds a usual deallocation function (3.7.4.2) |
2990 | // with a parameter of type std::size_t and that function, considered |
2991 | // as a placement deallocation function, would have been |
2992 | // selected as a match for the allocation function, the program |
2993 | // is ill-formed. |
2994 | if (getLangOpts().CPlusPlus11 && isPlacementNew && |
2995 | isNonPlacementDeallocationFunction(S&: *this, FD: OperatorDelete)) { |
2996 | UsualDeallocFnInfo Info(*this, |
2997 | DeclAccessPair::make(OperatorDelete, AS_public)); |
2998 | // Core issue, per mail to core reflector, 2016-10-09: |
2999 | // If this is a member operator delete, and there is a corresponding |
3000 | // non-sized member operator delete, this isn't /really/ a sized |
3001 | // deallocation function, it just happens to have a size_t parameter. |
3002 | bool IsSizedDelete = Info.HasSizeT; |
3003 | if (IsSizedDelete && !FoundGlobalDelete) { |
3004 | auto NonSizedDelete = |
3005 | resolveDeallocationOverload(S&: *this, R&: FoundDelete, /*WantSize*/false, |
3006 | /*WantAlign*/Info.HasAlignValT); |
3007 | if (NonSizedDelete && !NonSizedDelete.HasSizeT && |
3008 | NonSizedDelete.HasAlignValT == Info.HasAlignValT) |
3009 | IsSizedDelete = false; |
3010 | } |
3011 | |
3012 | if (IsSizedDelete) { |
3013 | SourceRange R = PlaceArgs.empty() |
3014 | ? SourceRange() |
3015 | : SourceRange(PlaceArgs.front()->getBeginLoc(), |
3016 | PlaceArgs.back()->getEndLoc()); |
3017 | Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R; |
3018 | if (!OperatorDelete->isImplicit()) |
3019 | Diag(OperatorDelete->getLocation(), diag::note_previous_decl) |
3020 | << DeleteName; |
3021 | } |
3022 | } |
3023 | |
3024 | CheckAllocationAccess(OperatorLoc: StartLoc, PlacementRange: Range, NamingClass: FoundDelete.getNamingClass(), |
3025 | FoundDecl: Matches[0].first); |
3026 | } else if (!Matches.empty()) { |
3027 | // We found multiple suitable operators. Per [expr.new]p20, that means we |
3028 | // call no 'operator delete' function, but we should at least warn the user. |
3029 | // FIXME: Suppress this warning if the construction cannot throw. |
3030 | Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found) |
3031 | << DeleteName << AllocElemType; |
3032 | |
3033 | for (auto &Match : Matches) |
3034 | Diag(Match.second->getLocation(), |
3035 | diag::note_member_declared_here) << DeleteName; |
3036 | } |
3037 | |
3038 | return false; |
3039 | } |
3040 | |
3041 | /// DeclareGlobalNewDelete - Declare the global forms of operator new and |
3042 | /// delete. These are: |
3043 | /// @code |
3044 | /// // C++03: |
3045 | /// void* operator new(std::size_t) throw(std::bad_alloc); |
3046 | /// void* operator new[](std::size_t) throw(std::bad_alloc); |
3047 | /// void operator delete(void *) throw(); |
3048 | /// void operator delete[](void *) throw(); |
3049 | /// // C++11: |
3050 | /// void* operator new(std::size_t); |
3051 | /// void* operator new[](std::size_t); |
3052 | /// void operator delete(void *) noexcept; |
3053 | /// void operator delete[](void *) noexcept; |
3054 | /// // C++1y: |
3055 | /// void* operator new(std::size_t); |
3056 | /// void* operator new[](std::size_t); |
3057 | /// void operator delete(void *) noexcept; |
3058 | /// void operator delete[](void *) noexcept; |
3059 | /// void operator delete(void *, std::size_t) noexcept; |
3060 | /// void operator delete[](void *, std::size_t) noexcept; |
3061 | /// @endcode |
3062 | /// Note that the placement and nothrow forms of new are *not* implicitly |
3063 | /// declared. Their use requires including \<new\>. |
3064 | void Sema::DeclareGlobalNewDelete() { |
3065 | if (GlobalNewDeleteDeclared) |
3066 | return; |
3067 | |
3068 | // The implicitly declared new and delete operators |
3069 | // are not supported in OpenCL. |
3070 | if (getLangOpts().OpenCLCPlusPlus) |
3071 | return; |
3072 | |
3073 | // C++ [basic.stc.dynamic.general]p2: |
3074 | // The library provides default definitions for the global allocation |
3075 | // and deallocation functions. Some global allocation and deallocation |
3076 | // functions are replaceable ([new.delete]); these are attached to the |
3077 | // global module ([module.unit]). |
3078 | if (getLangOpts().CPlusPlusModules && getCurrentModule()) |
3079 | PushGlobalModuleFragment(BeginLoc: SourceLocation()); |
3080 | |
3081 | // C++ [basic.std.dynamic]p2: |
3082 | // [...] The following allocation and deallocation functions (18.4) are |
3083 | // implicitly declared in global scope in each translation unit of a |
3084 | // program |
3085 | // |
3086 | // C++03: |
3087 | // void* operator new(std::size_t) throw(std::bad_alloc); |
3088 | // void* operator new[](std::size_t) throw(std::bad_alloc); |
3089 | // void operator delete(void*) throw(); |
3090 | // void operator delete[](void*) throw(); |
3091 | // C++11: |
3092 | // void* operator new(std::size_t); |
3093 | // void* operator new[](std::size_t); |
3094 | // void operator delete(void*) noexcept; |
3095 | // void operator delete[](void*) noexcept; |
3096 | // C++1y: |
3097 | // void* operator new(std::size_t); |
3098 | // void* operator new[](std::size_t); |
3099 | // void operator delete(void*) noexcept; |
3100 | // void operator delete[](void*) noexcept; |
3101 | // void operator delete(void*, std::size_t) noexcept; |
3102 | // void operator delete[](void*, std::size_t) noexcept; |
3103 | // |
3104 | // These implicit declarations introduce only the function names operator |
3105 | // new, operator new[], operator delete, operator delete[]. |
3106 | // |
3107 | // Here, we need to refer to std::bad_alloc, so we will implicitly declare |
3108 | // "std" or "bad_alloc" as necessary to form the exception specification. |
3109 | // However, we do not make these implicit declarations visible to name |
3110 | // lookup. |
3111 | if (!StdBadAlloc && !getLangOpts().CPlusPlus11) { |
3112 | // The "std::bad_alloc" class has not yet been declared, so build it |
3113 | // implicitly. |
3114 | StdBadAlloc = CXXRecordDecl::Create( |
3115 | Context, TagTypeKind::Class, getOrCreateStdNamespace(), |
3116 | SourceLocation(), SourceLocation(), |
3117 | &PP.getIdentifierTable().get(Name: "bad_alloc" ), nullptr); |
3118 | getStdBadAlloc()->setImplicit(true); |
3119 | |
3120 | // The implicitly declared "std::bad_alloc" should live in global module |
3121 | // fragment. |
3122 | if (TheGlobalModuleFragment) { |
3123 | getStdBadAlloc()->setModuleOwnershipKind( |
3124 | Decl::ModuleOwnershipKind::ReachableWhenImported); |
3125 | getStdBadAlloc()->setLocalOwningModule(TheGlobalModuleFragment); |
3126 | } |
3127 | } |
3128 | if (!StdAlignValT && getLangOpts().AlignedAllocation) { |
3129 | // The "std::align_val_t" enum class has not yet been declared, so build it |
3130 | // implicitly. |
3131 | auto *AlignValT = EnumDecl::Create( |
3132 | Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(), |
3133 | &PP.getIdentifierTable().get(Name: "align_val_t" ), nullptr, true, true, true); |
3134 | |
3135 | // The implicitly declared "std::align_val_t" should live in global module |
3136 | // fragment. |
3137 | if (TheGlobalModuleFragment) { |
3138 | AlignValT->setModuleOwnershipKind( |
3139 | Decl::ModuleOwnershipKind::ReachableWhenImported); |
3140 | AlignValT->setLocalOwningModule(TheGlobalModuleFragment); |
3141 | } |
3142 | |
3143 | AlignValT->setIntegerType(Context.getSizeType()); |
3144 | AlignValT->setPromotionType(Context.getSizeType()); |
3145 | AlignValT->setImplicit(true); |
3146 | |
3147 | StdAlignValT = AlignValT; |
3148 | } |
3149 | |
3150 | GlobalNewDeleteDeclared = true; |
3151 | |
3152 | QualType VoidPtr = Context.getPointerType(Context.VoidTy); |
3153 | QualType SizeT = Context.getSizeType(); |
3154 | |
3155 | auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind, |
3156 | QualType Return, QualType Param) { |
3157 | llvm::SmallVector<QualType, 3> Params; |
3158 | Params.push_back(Elt: Param); |
3159 | |
3160 | // Create up to four variants of the function (sized/aligned). |
3161 | bool HasSizedVariant = getLangOpts().SizedDeallocation && |
3162 | (Kind == OO_Delete || Kind == OO_Array_Delete); |
3163 | bool HasAlignedVariant = getLangOpts().AlignedAllocation; |
3164 | |
3165 | int NumSizeVariants = (HasSizedVariant ? 2 : 1); |
3166 | int NumAlignVariants = (HasAlignedVariant ? 2 : 1); |
3167 | for (int Sized = 0; Sized < NumSizeVariants; ++Sized) { |
3168 | if (Sized) |
3169 | Params.push_back(Elt: SizeT); |
3170 | |
3171 | for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) { |
3172 | if (Aligned) |
3173 | Params.push_back(Elt: Context.getTypeDeclType(getStdAlignValT())); |
3174 | |
3175 | DeclareGlobalAllocationFunction( |
3176 | Name: Context.DeclarationNames.getCXXOperatorName(Op: Kind), Return, Params); |
3177 | |
3178 | if (Aligned) |
3179 | Params.pop_back(); |
3180 | } |
3181 | } |
3182 | }; |
3183 | |
3184 | DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT); |
3185 | DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT); |
3186 | DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr); |
3187 | DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr); |
3188 | |
3189 | if (getLangOpts().CPlusPlusModules && getCurrentModule()) |
3190 | PopGlobalModuleFragment(); |
3191 | } |
3192 | |
3193 | /// DeclareGlobalAllocationFunction - Declares a single implicit global |
3194 | /// allocation function if it doesn't already exist. |
3195 | void Sema::DeclareGlobalAllocationFunction(DeclarationName Name, |
3196 | QualType Return, |
3197 | ArrayRef<QualType> Params) { |
3198 | DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); |
3199 | |
3200 | // Check if this function is already declared. |
3201 | DeclContext::lookup_result R = GlobalCtx->lookup(Name); |
3202 | for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end(); |
3203 | Alloc != AllocEnd; ++Alloc) { |
3204 | // Only look at non-template functions, as it is the predefined, |
3205 | // non-templated allocation function we are trying to declare here. |
3206 | if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Val: *Alloc)) { |
3207 | if (Func->getNumParams() == Params.size()) { |
3208 | llvm::SmallVector<QualType, 3> FuncParams; |
3209 | for (auto *P : Func->parameters()) |
3210 | FuncParams.push_back( |
3211 | Context.getCanonicalType(P->getType().getUnqualifiedType())); |
3212 | if (llvm::ArrayRef(FuncParams) == Params) { |
3213 | // Make the function visible to name lookup, even if we found it in |
3214 | // an unimported module. It either is an implicitly-declared global |
3215 | // allocation function, or is suppressing that function. |
3216 | Func->setVisibleDespiteOwningModule(); |
3217 | return; |
3218 | } |
3219 | } |
3220 | } |
3221 | } |
3222 | |
3223 | FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention( |
3224 | /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true)); |
3225 | |
3226 | QualType BadAllocType; |
3227 | bool HasBadAllocExceptionSpec |
3228 | = (Name.getCXXOverloadedOperator() == OO_New || |
3229 | Name.getCXXOverloadedOperator() == OO_Array_New); |
3230 | if (HasBadAllocExceptionSpec) { |
3231 | if (!getLangOpts().CPlusPlus11) { |
3232 | BadAllocType = Context.getTypeDeclType(getStdBadAlloc()); |
3233 | assert(StdBadAlloc && "Must have std::bad_alloc declared" ); |
3234 | EPI.ExceptionSpec.Type = EST_Dynamic; |
3235 | EPI.ExceptionSpec.Exceptions = llvm::ArrayRef(BadAllocType); |
3236 | } |
3237 | if (getLangOpts().NewInfallible) { |
3238 | EPI.ExceptionSpec.Type = EST_DynamicNone; |
3239 | } |
3240 | } else { |
3241 | EPI.ExceptionSpec = |
3242 | getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone; |
3243 | } |
3244 | |
3245 | auto CreateAllocationFunctionDecl = [&](Attr *) { |
3246 | QualType FnType = Context.getFunctionType(ResultTy: Return, Args: Params, EPI); |
3247 | FunctionDecl *Alloc = FunctionDecl::Create( |
3248 | C&: Context, DC: GlobalCtx, StartLoc: SourceLocation(), NLoc: SourceLocation(), N: Name, T: FnType, |
3249 | /*TInfo=*/nullptr, SC: SC_None, UsesFPIntrin: getCurFPFeatures().isFPConstrained(), isInlineSpecified: false, |
3250 | hasWrittenPrototype: true); |
3251 | Alloc->setImplicit(); |
3252 | // Global allocation functions should always be visible. |
3253 | Alloc->setVisibleDespiteOwningModule(); |
3254 | |
3255 | if (HasBadAllocExceptionSpec && getLangOpts().NewInfallible && |
3256 | !getLangOpts().CheckNew) |
3257 | Alloc->addAttr( |
3258 | ReturnsNonNullAttr::CreateImplicit(Context, Alloc->getLocation())); |
3259 | |
3260 | // C++ [basic.stc.dynamic.general]p2: |
3261 | // The library provides default definitions for the global allocation |
3262 | // and deallocation functions. Some global allocation and deallocation |
3263 | // functions are replaceable ([new.delete]); these are attached to the |
3264 | // global module ([module.unit]). |
3265 | // |
3266 | // In the language wording, these functions are attched to the global |
3267 | // module all the time. But in the implementation, the global module |
3268 | // is only meaningful when we're in a module unit. So here we attach |
3269 | // these allocation functions to global module conditionally. |
3270 | if (TheGlobalModuleFragment) { |
3271 | Alloc->setModuleOwnershipKind( |
3272 | Decl::ModuleOwnershipKind::ReachableWhenImported); |
3273 | Alloc->setLocalOwningModule(TheGlobalModuleFragment); |
3274 | } |
3275 | |
3276 | if (LangOpts.hasGlobalAllocationFunctionVisibility()) |
3277 | Alloc->addAttr(VisibilityAttr::CreateImplicit( |
3278 | Context, LangOpts.hasHiddenGlobalAllocationFunctionVisibility() |
3279 | ? VisibilityAttr::Hidden |
3280 | : LangOpts.hasProtectedGlobalAllocationFunctionVisibility() |
3281 | ? VisibilityAttr::Protected |
3282 | : VisibilityAttr::Default)); |
3283 | |
3284 | llvm::SmallVector<ParmVarDecl *, 3> ParamDecls; |
3285 | for (QualType T : Params) { |
3286 | ParamDecls.push_back(Elt: ParmVarDecl::Create( |
3287 | Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T, |
3288 | /*TInfo=*/nullptr, SC_None, nullptr)); |
3289 | ParamDecls.back()->setImplicit(); |
3290 | } |
3291 | Alloc->setParams(ParamDecls); |
3292 | if (ExtraAttr) |
3293 | Alloc->addAttr(ExtraAttr); |
3294 | AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD: Alloc); |
3295 | Context.getTranslationUnitDecl()->addDecl(Alloc); |
3296 | IdResolver.tryAddTopLevelDecl(Alloc, Name); |
3297 | }; |
3298 | |
3299 | if (!LangOpts.CUDA) |
3300 | CreateAllocationFunctionDecl(nullptr); |
3301 | else { |
3302 | // Host and device get their own declaration so each can be |
3303 | // defined or re-declared independently. |
3304 | CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context)); |
3305 | CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context)); |
3306 | } |
3307 | } |
3308 | |
3309 | FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc, |
3310 | bool CanProvideSize, |
3311 | bool Overaligned, |
3312 | DeclarationName Name) { |
3313 | DeclareGlobalNewDelete(); |
3314 | |
3315 | LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName); |
3316 | LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); |
3317 | |
3318 | // FIXME: It's possible for this to result in ambiguity, through a |
3319 | // user-declared variadic operator delete or the enable_if attribute. We |
3320 | // should probably not consider those cases to be usual deallocation |
3321 | // functions. But for now we just make an arbitrary choice in that case. |
3322 | auto Result = resolveDeallocationOverload(S&: *this, R&: FoundDelete, WantSize: CanProvideSize, |
3323 | WantAlign: Overaligned); |
3324 | assert(Result.FD && "operator delete missing from global scope?" ); |
3325 | return Result.FD; |
3326 | } |
3327 | |
3328 | FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc, |
3329 | CXXRecordDecl *RD) { |
3330 | DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op: OO_Delete); |
3331 | |
3332 | FunctionDecl *OperatorDelete = nullptr; |
3333 | if (FindDeallocationFunction(StartLoc: Loc, RD, Name, Operator&: OperatorDelete)) |
3334 | return nullptr; |
3335 | if (OperatorDelete) |
3336 | return OperatorDelete; |
3337 | |
3338 | // If there's no class-specific operator delete, look up the global |
3339 | // non-array delete. |
3340 | return FindUsualDeallocationFunction( |
3341 | StartLoc: Loc, CanProvideSize: true, Overaligned: hasNewExtendedAlignment(S&: *this, AllocType: Context.getRecordType(RD)), |
3342 | Name); |
3343 | } |
3344 | |
3345 | bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, |
3346 | DeclarationName Name, |
3347 | FunctionDecl *&Operator, bool Diagnose, |
3348 | bool WantSize, bool WantAligned) { |
3349 | LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName); |
3350 | // Try to find operator delete/operator delete[] in class scope. |
3351 | LookupQualifiedName(Found, RD); |
3352 | |
3353 | if (Found.isAmbiguous()) |
3354 | return true; |
3355 | |
3356 | Found.suppressDiagnostics(); |
3357 | |
3358 | bool Overaligned = |
3359 | WantAligned || hasNewExtendedAlignment(S&: *this, AllocType: Context.getRecordType(RD)); |
3360 | |
3361 | // C++17 [expr.delete]p10: |
3362 | // If the deallocation functions have class scope, the one without a |
3363 | // parameter of type std::size_t is selected. |
3364 | llvm::SmallVector<UsualDeallocFnInfo, 4> Matches; |
3365 | resolveDeallocationOverload(S&: *this, R&: Found, /*WantSize*/ WantSize, |
3366 | /*WantAlign*/ Overaligned, BestFns: &Matches); |
3367 | |
3368 | // If we could find an overload, use it. |
3369 | if (Matches.size() == 1) { |
3370 | Operator = cast<CXXMethodDecl>(Val: Matches[0].FD); |
3371 | |
3372 | // FIXME: DiagnoseUseOfDecl? |
3373 | if (Operator->isDeleted()) { |
3374 | if (Diagnose) { |
3375 | StringLiteral *Msg = Operator->getDeletedMessage(); |
3376 | Diag(StartLoc, diag::err_deleted_function_use) |
3377 | << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef()); |
3378 | NoteDeletedFunction(FD: Operator); |
3379 | } |
3380 | return true; |
3381 | } |
3382 | |
3383 | if (CheckAllocationAccess(OperatorLoc: StartLoc, PlacementRange: SourceRange(), NamingClass: Found.getNamingClass(), |
3384 | FoundDecl: Matches[0].Found, Diagnose) == AR_inaccessible) |
3385 | return true; |
3386 | |
3387 | return false; |
3388 | } |
3389 | |
3390 | // We found multiple suitable operators; complain about the ambiguity. |
3391 | // FIXME: The standard doesn't say to do this; it appears that the intent |
3392 | // is that this should never happen. |
3393 | if (!Matches.empty()) { |
3394 | if (Diagnose) { |
3395 | Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found) |
3396 | << Name << RD; |
3397 | for (auto &Match : Matches) |
3398 | Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name; |
3399 | } |
3400 | return true; |
3401 | } |
3402 | |
3403 | // We did find operator delete/operator delete[] declarations, but |
3404 | // none of them were suitable. |
3405 | if (!Found.empty()) { |
3406 | if (Diagnose) { |
3407 | Diag(StartLoc, diag::err_no_suitable_delete_member_function_found) |
3408 | << Name << RD; |
3409 | |
3410 | for (NamedDecl *D : Found) |
3411 | Diag(D->getUnderlyingDecl()->getLocation(), |
3412 | diag::note_member_declared_here) << Name; |
3413 | } |
3414 | return true; |
3415 | } |
3416 | |
3417 | Operator = nullptr; |
3418 | return false; |
3419 | } |
3420 | |
3421 | namespace { |
3422 | /// Checks whether delete-expression, and new-expression used for |
3423 | /// initializing deletee have the same array form. |
3424 | class MismatchingNewDeleteDetector { |
3425 | public: |
3426 | enum MismatchResult { |
3427 | /// Indicates that there is no mismatch or a mismatch cannot be proven. |
3428 | NoMismatch, |
3429 | /// Indicates that variable is initialized with mismatching form of \a new. |
3430 | VarInitMismatches, |
3431 | /// Indicates that member is initialized with mismatching form of \a new. |
3432 | MemberInitMismatches, |
3433 | /// Indicates that 1 or more constructors' definitions could not been |
3434 | /// analyzed, and they will be checked again at the end of translation unit. |
3435 | AnalyzeLater |
3436 | }; |
3437 | |
3438 | /// \param EndOfTU True, if this is the final analysis at the end of |
3439 | /// translation unit. False, if this is the initial analysis at the point |
3440 | /// delete-expression was encountered. |
3441 | explicit MismatchingNewDeleteDetector(bool EndOfTU) |
3442 | : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU), |
3443 | HasUndefinedConstructors(false) {} |
3444 | |
3445 | /// Checks whether pointee of a delete-expression is initialized with |
3446 | /// matching form of new-expression. |
3447 | /// |
3448 | /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the |
3449 | /// point where delete-expression is encountered, then a warning will be |
3450 | /// issued immediately. If return value is \c AnalyzeLater at the point where |
3451 | /// delete-expression is seen, then member will be analyzed at the end of |
3452 | /// translation unit. \c AnalyzeLater is returned iff at least one constructor |
3453 | /// couldn't be analyzed. If at least one constructor initializes the member |
3454 | /// with matching type of new, the return value is \c NoMismatch. |
3455 | MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE); |
3456 | /// Analyzes a class member. |
3457 | /// \param Field Class member to analyze. |
3458 | /// \param DeleteWasArrayForm Array form-ness of the delete-expression used |
3459 | /// for deleting the \p Field. |
3460 | MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm); |
3461 | FieldDecl *Field; |
3462 | /// List of mismatching new-expressions used for initialization of the pointee |
3463 | llvm::SmallVector<const CXXNewExpr *, 4> NewExprs; |
3464 | /// Indicates whether delete-expression was in array form. |
3465 | bool IsArrayForm; |
3466 | |
3467 | private: |
3468 | const bool EndOfTU; |
3469 | /// Indicates that there is at least one constructor without body. |
3470 | bool HasUndefinedConstructors; |
3471 | /// Returns \c CXXNewExpr from given initialization expression. |
3472 | /// \param E Expression used for initializing pointee in delete-expression. |
3473 | /// E can be a single-element \c InitListExpr consisting of new-expression. |
3474 | const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E); |
3475 | /// Returns whether member is initialized with mismatching form of |
3476 | /// \c new either by the member initializer or in-class initialization. |
3477 | /// |
3478 | /// If bodies of all constructors are not visible at the end of translation |
3479 | /// unit or at least one constructor initializes member with the matching |
3480 | /// form of \c new, mismatch cannot be proven, and this function will return |
3481 | /// \c NoMismatch. |
3482 | MismatchResult analyzeMemberExpr(const MemberExpr *ME); |
3483 | /// Returns whether variable is initialized with mismatching form of |
3484 | /// \c new. |
3485 | /// |
3486 | /// If variable is initialized with matching form of \c new or variable is not |
3487 | /// initialized with a \c new expression, this function will return true. |
3488 | /// If variable is initialized with mismatching form of \c new, returns false. |
3489 | /// \param D Variable to analyze. |
3490 | bool hasMatchingVarInit(const DeclRefExpr *D); |
3491 | /// Checks whether the constructor initializes pointee with mismatching |
3492 | /// form of \c new. |
3493 | /// |
3494 | /// Returns true, if member is initialized with matching form of \c new in |
3495 | /// member initializer list. Returns false, if member is initialized with the |
3496 | /// matching form of \c new in this constructor's initializer or given |
3497 | /// constructor isn't defined at the point where delete-expression is seen, or |
3498 | /// member isn't initialized by the constructor. |
3499 | bool hasMatchingNewInCtor(const CXXConstructorDecl *CD); |
3500 | /// Checks whether member is initialized with matching form of |
3501 | /// \c new in member initializer list. |
3502 | bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI); |
3503 | /// Checks whether member is initialized with mismatching form of \c new by |
3504 | /// in-class initializer. |
3505 | MismatchResult analyzeInClassInitializer(); |
3506 | }; |
3507 | } |
3508 | |
3509 | MismatchingNewDeleteDetector::MismatchResult |
3510 | MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) { |
3511 | NewExprs.clear(); |
3512 | assert(DE && "Expected delete-expression" ); |
3513 | IsArrayForm = DE->isArrayForm(); |
3514 | const Expr *E = DE->getArgument()->IgnoreParenImpCasts(); |
3515 | if (const MemberExpr *ME = dyn_cast<const MemberExpr>(Val: E)) { |
3516 | return analyzeMemberExpr(ME); |
3517 | } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(Val: E)) { |
3518 | if (!hasMatchingVarInit(D)) |
3519 | return VarInitMismatches; |
3520 | } |
3521 | return NoMismatch; |
3522 | } |
3523 | |
3524 | const CXXNewExpr * |
3525 | MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) { |
3526 | assert(E != nullptr && "Expected a valid initializer expression" ); |
3527 | E = E->IgnoreParenImpCasts(); |
3528 | if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(Val: E)) { |
3529 | if (ILE->getNumInits() == 1) |
3530 | E = dyn_cast<const CXXNewExpr>(Val: ILE->getInit(Init: 0)->IgnoreParenImpCasts()); |
3531 | } |
3532 | |
3533 | return dyn_cast_or_null<const CXXNewExpr>(Val: E); |
3534 | } |
3535 | |
3536 | bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit( |
3537 | const CXXCtorInitializer *CI) { |
3538 | const CXXNewExpr *NE = nullptr; |
3539 | if (Field == CI->getMember() && |
3540 | (NE = getNewExprFromInitListOrExpr(E: CI->getInit()))) { |
3541 | if (NE->isArray() == IsArrayForm) |
3542 | return true; |
3543 | else |
3544 | NewExprs.push_back(Elt: NE); |
3545 | } |
3546 | return false; |
3547 | } |
3548 | |
3549 | bool MismatchingNewDeleteDetector::hasMatchingNewInCtor( |
3550 | const CXXConstructorDecl *CD) { |
3551 | if (CD->isImplicit()) |
3552 | return false; |
3553 | const FunctionDecl *Definition = CD; |
3554 | if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) { |
3555 | HasUndefinedConstructors = true; |
3556 | return EndOfTU; |
3557 | } |
3558 | for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) { |
3559 | if (hasMatchingNewInCtorInit(CI)) |
3560 | return true; |
3561 | } |
3562 | return false; |
3563 | } |
3564 | |
3565 | MismatchingNewDeleteDetector::MismatchResult |
3566 | MismatchingNewDeleteDetector::analyzeInClassInitializer() { |
3567 | assert(Field != nullptr && "This should be called only for members" ); |
3568 | const Expr *InitExpr = Field->getInClassInitializer(); |
3569 | if (!InitExpr) |
3570 | return EndOfTU ? NoMismatch : AnalyzeLater; |
3571 | if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(E: InitExpr)) { |
3572 | if (NE->isArray() != IsArrayForm) { |
3573 | NewExprs.push_back(Elt: NE); |
3574 | return MemberInitMismatches; |
3575 | } |
3576 | } |
3577 | return NoMismatch; |
3578 | } |
3579 | |
3580 | MismatchingNewDeleteDetector::MismatchResult |
3581 | MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field, |
3582 | bool DeleteWasArrayForm) { |
3583 | assert(Field != nullptr && "Analysis requires a valid class member." ); |
3584 | this->Field = Field; |
3585 | IsArrayForm = DeleteWasArrayForm; |
3586 | const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Val: Field->getParent()); |
3587 | for (const auto *CD : RD->ctors()) { |
3588 | if (hasMatchingNewInCtor(CD)) |
3589 | return NoMismatch; |
3590 | } |
3591 | if (HasUndefinedConstructors) |
3592 | return EndOfTU ? NoMismatch : AnalyzeLater; |
3593 | if (!NewExprs.empty()) |
3594 | return MemberInitMismatches; |
3595 | return Field->hasInClassInitializer() ? analyzeInClassInitializer() |
3596 | : NoMismatch; |
3597 | } |
3598 | |
3599 | MismatchingNewDeleteDetector::MismatchResult |
3600 | MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) { |
3601 | assert(ME != nullptr && "Expected a member expression" ); |
3602 | if (FieldDecl *F = dyn_cast<FieldDecl>(Val: ME->getMemberDecl())) |
3603 | return analyzeField(Field: F, DeleteWasArrayForm: IsArrayForm); |
3604 | return NoMismatch; |
3605 | } |
3606 | |
3607 | bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) { |
3608 | const CXXNewExpr *NE = nullptr; |
3609 | if (const VarDecl *VD = dyn_cast<const VarDecl>(Val: D->getDecl())) { |
3610 | if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(E: VD->getInit())) && |
3611 | NE->isArray() != IsArrayForm) { |
3612 | NewExprs.push_back(Elt: NE); |
3613 | } |
3614 | } |
3615 | return NewExprs.empty(); |
3616 | } |
3617 | |
3618 | static void |
3619 | DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc, |
3620 | const MismatchingNewDeleteDetector &Detector) { |
3621 | SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(Loc: DeleteLoc); |
3622 | FixItHint H; |
3623 | if (!Detector.IsArrayForm) |
3624 | H = FixItHint::CreateInsertion(InsertionLoc: EndOfDelete, Code: "[]" ); |
3625 | else { |
3626 | SourceLocation RSquare = Lexer::findLocationAfterToken( |
3627 | loc: DeleteLoc, TKind: tok::l_square, SM: SemaRef.getSourceManager(), |
3628 | LangOpts: SemaRef.getLangOpts(), SkipTrailingWhitespaceAndNewLine: true); |
3629 | if (RSquare.isValid()) |
3630 | H = FixItHint::CreateRemoval(RemoveRange: SourceRange(EndOfDelete, RSquare)); |
3631 | } |
3632 | SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new) |
3633 | << Detector.IsArrayForm << H; |
3634 | |
3635 | for (const auto *NE : Detector.NewExprs) |
3636 | SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here) |
3637 | << Detector.IsArrayForm; |
3638 | } |
3639 | |
3640 | void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) { |
3641 | if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) |
3642 | return; |
3643 | MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false); |
3644 | switch (Detector.analyzeDeleteExpr(DE)) { |
3645 | case MismatchingNewDeleteDetector::VarInitMismatches: |
3646 | case MismatchingNewDeleteDetector::MemberInitMismatches: { |
3647 | DiagnoseMismatchedNewDelete(SemaRef&: *this, DeleteLoc: DE->getBeginLoc(), Detector); |
3648 | break; |
3649 | } |
3650 | case MismatchingNewDeleteDetector::AnalyzeLater: { |
3651 | DeleteExprs[Detector.Field].push_back( |
3652 | Elt: std::make_pair(x: DE->getBeginLoc(), y: DE->isArrayForm())); |
3653 | break; |
3654 | } |
3655 | case MismatchingNewDeleteDetector::NoMismatch: |
3656 | break; |
3657 | } |
3658 | } |
3659 | |
3660 | void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, |
3661 | bool DeleteWasArrayForm) { |
3662 | MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true); |
3663 | switch (Detector.analyzeField(Field, DeleteWasArrayForm)) { |
3664 | case MismatchingNewDeleteDetector::VarInitMismatches: |
3665 | llvm_unreachable("This analysis should have been done for class members." ); |
3666 | case MismatchingNewDeleteDetector::AnalyzeLater: |
3667 | llvm_unreachable("Analysis cannot be postponed any point beyond end of " |
3668 | "translation unit." ); |
3669 | case MismatchingNewDeleteDetector::MemberInitMismatches: |
3670 | DiagnoseMismatchedNewDelete(SemaRef&: *this, DeleteLoc, Detector); |
3671 | break; |
3672 | case MismatchingNewDeleteDetector::NoMismatch: |
3673 | break; |
3674 | } |
3675 | } |
3676 | |
3677 | /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in: |
3678 | /// @code ::delete ptr; @endcode |
3679 | /// or |
3680 | /// @code delete [] ptr; @endcode |
3681 | ExprResult |
3682 | Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, |
3683 | bool ArrayForm, Expr *ExE) { |
3684 | // C++ [expr.delete]p1: |
3685 | // The operand shall have a pointer type, or a class type having a single |
3686 | // non-explicit conversion function to a pointer type. The result has type |
3687 | // void. |
3688 | // |
3689 | // DR599 amends "pointer type" to "pointer to object type" in both cases. |
3690 | |
3691 | ExprResult Ex = ExE; |
3692 | FunctionDecl *OperatorDelete = nullptr; |
3693 | bool ArrayFormAsWritten = ArrayForm; |
3694 | bool UsualArrayDeleteWantsSize = false; |
3695 | |
3696 | if (!Ex.get()->isTypeDependent()) { |
3697 | // Perform lvalue-to-rvalue cast, if needed. |
3698 | Ex = DefaultLvalueConversion(E: Ex.get()); |
3699 | if (Ex.isInvalid()) |
3700 | return ExprError(); |
3701 | |
3702 | QualType Type = Ex.get()->getType(); |
3703 | |
3704 | class DeleteConverter : public ContextualImplicitConverter { |
3705 | public: |
3706 | DeleteConverter() : ContextualImplicitConverter(false, true) {} |
3707 | |
3708 | bool match(QualType ConvType) override { |
3709 | // FIXME: If we have an operator T* and an operator void*, we must pick |
3710 | // the operator T*. |
3711 | if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) |
3712 | if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType()) |
3713 | return true; |
3714 | return false; |
3715 | } |
3716 | |
3717 | SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, |
3718 | QualType T) override { |
3719 | return S.Diag(Loc, diag::err_delete_operand) << T; |
3720 | } |
3721 | |
3722 | SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, |
3723 | QualType T) override { |
3724 | return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T; |
3725 | } |
3726 | |
3727 | SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, |
3728 | QualType T, |
3729 | QualType ConvTy) override { |
3730 | return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy; |
3731 | } |
3732 | |
3733 | SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, |
3734 | QualType ConvTy) override { |
3735 | return S.Diag(Conv->getLocation(), diag::note_delete_conversion) |
3736 | << ConvTy; |
3737 | } |
3738 | |
3739 | SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, |
3740 | QualType T) override { |
3741 | return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T; |
3742 | } |
3743 | |
3744 | SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, |
3745 | QualType ConvTy) override { |
3746 | return S.Diag(Conv->getLocation(), diag::note_delete_conversion) |
3747 | << ConvTy; |
3748 | } |
3749 | |
3750 | SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, |
3751 | QualType T, |
3752 | QualType ConvTy) override { |
3753 | llvm_unreachable("conversion functions are permitted" ); |
3754 | } |
3755 | } Converter; |
3756 | |
3757 | Ex = PerformContextualImplicitConversion(Loc: StartLoc, FromE: Ex.get(), Converter); |
3758 | if (Ex.isInvalid()) |
3759 | return ExprError(); |
3760 | Type = Ex.get()->getType(); |
3761 | if (!Converter.match(ConvType: Type)) |
3762 | // FIXME: PerformContextualImplicitConversion should return ExprError |
3763 | // itself in this case. |
3764 | return ExprError(); |
3765 | |
3766 | QualType Pointee = Type->castAs<PointerType>()->getPointeeType(); |
3767 | QualType PointeeElem = Context.getBaseElementType(QT: Pointee); |
3768 | |
3769 | if (Pointee.getAddressSpace() != LangAS::Default && |
3770 | !getLangOpts().OpenCLCPlusPlus) |
3771 | return Diag(Ex.get()->getBeginLoc(), |
3772 | diag::err_address_space_qualified_delete) |
3773 | << Pointee.getUnqualifiedType() |
3774 | << Pointee.getQualifiers().getAddressSpaceAttributePrintValue(); |
3775 | |
3776 | CXXRecordDecl *PointeeRD = nullptr; |
3777 | if (Pointee->isVoidType() && !isSFINAEContext()) { |
3778 | // The C++ standard bans deleting a pointer to a non-object type, which |
3779 | // effectively bans deletion of "void*". However, most compilers support |
3780 | // this, so we treat it as a warning unless we're in a SFINAE context. |
3781 | Diag(StartLoc, diag::ext_delete_void_ptr_operand) |
3782 | << Type << Ex.get()->getSourceRange(); |
3783 | } else if (Pointee->isFunctionType() || Pointee->isVoidType() || |
3784 | Pointee->isSizelessType()) { |
3785 | return ExprError(Diag(StartLoc, diag::err_delete_operand) |
3786 | << Type << Ex.get()->getSourceRange()); |
3787 | } else if (!Pointee->isDependentType()) { |
3788 | // FIXME: This can result in errors if the definition was imported from a |
3789 | // module but is hidden. |
3790 | if (!RequireCompleteType(StartLoc, Pointee, |
3791 | diag::warn_delete_incomplete, Ex.get())) { |
3792 | if (const RecordType *RT = PointeeElem->getAs<RecordType>()) |
3793 | PointeeRD = cast<CXXRecordDecl>(Val: RT->getDecl()); |
3794 | } |
3795 | } |
3796 | |
3797 | if (Pointee->isArrayType() && !ArrayForm) { |
3798 | Diag(StartLoc, diag::warn_delete_array_type) |
3799 | << Type << Ex.get()->getSourceRange() |
3800 | << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]" ); |
3801 | ArrayForm = true; |
3802 | } |
3803 | |
3804 | DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( |
3805 | Op: ArrayForm ? OO_Array_Delete : OO_Delete); |
3806 | |
3807 | if (PointeeRD) { |
3808 | if (!UseGlobal && |
3809 | FindDeallocationFunction(StartLoc, RD: PointeeRD, Name: DeleteName, |
3810 | Operator&: OperatorDelete)) |
3811 | return ExprError(); |
3812 | |
3813 | // If we're allocating an array of records, check whether the |
3814 | // usual operator delete[] has a size_t parameter. |
3815 | if (ArrayForm) { |
3816 | // If the user specifically asked to use the global allocator, |
3817 | // we'll need to do the lookup into the class. |
3818 | if (UseGlobal) |
3819 | UsualArrayDeleteWantsSize = |
3820 | doesUsualArrayDeleteWantSize(S&: *this, loc: StartLoc, allocType: PointeeElem); |
3821 | |
3822 | // Otherwise, the usual operator delete[] should be the |
3823 | // function we just found. |
3824 | else if (OperatorDelete && isa<CXXMethodDecl>(Val: OperatorDelete)) |
3825 | UsualArrayDeleteWantsSize = |
3826 | UsualDeallocFnInfo(*this, |
3827 | DeclAccessPair::make(OperatorDelete, AS_public)) |
3828 | .HasSizeT; |
3829 | } |
3830 | |
3831 | if (!PointeeRD->hasIrrelevantDestructor()) |
3832 | if (CXXDestructorDecl *Dtor = LookupDestructor(Class: PointeeRD)) { |
3833 | MarkFunctionReferenced(StartLoc, |
3834 | const_cast<CXXDestructorDecl*>(Dtor)); |
3835 | if (DiagnoseUseOfDecl(Dtor, StartLoc)) |
3836 | return ExprError(); |
3837 | } |
3838 | |
3839 | CheckVirtualDtorCall(dtor: PointeeRD->getDestructor(), Loc: StartLoc, |
3840 | /*IsDelete=*/true, /*CallCanBeVirtual=*/true, |
3841 | /*WarnOnNonAbstractTypes=*/!ArrayForm, |
3842 | DtorLoc: SourceLocation()); |
3843 | } |
3844 | |
3845 | if (!OperatorDelete) { |
3846 | if (getLangOpts().OpenCLCPlusPlus) { |
3847 | Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete" ; |
3848 | return ExprError(); |
3849 | } |
3850 | |
3851 | bool IsComplete = isCompleteType(Loc: StartLoc, T: Pointee); |
3852 | bool CanProvideSize = |
3853 | IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize || |
3854 | Pointee.isDestructedType()); |
3855 | bool Overaligned = hasNewExtendedAlignment(S&: *this, AllocType: Pointee); |
3856 | |
3857 | // Look for a global declaration. |
3858 | OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize, |
3859 | Overaligned, Name: DeleteName); |
3860 | } |
3861 | |
3862 | MarkFunctionReferenced(Loc: StartLoc, Func: OperatorDelete); |
3863 | |
3864 | // Check access and ambiguity of destructor if we're going to call it. |
3865 | // Note that this is required even for a virtual delete. |
3866 | bool IsVirtualDelete = false; |
3867 | if (PointeeRD) { |
3868 | if (CXXDestructorDecl *Dtor = LookupDestructor(Class: PointeeRD)) { |
3869 | CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor, |
3870 | PDiag(diag::err_access_dtor) << PointeeElem); |
3871 | IsVirtualDelete = Dtor->isVirtual(); |
3872 | } |
3873 | } |
3874 | |
3875 | DiagnoseUseOfDecl(OperatorDelete, StartLoc); |
3876 | |
3877 | // Convert the operand to the type of the first parameter of operator |
3878 | // delete. This is only necessary if we selected a destroying operator |
3879 | // delete that we are going to call (non-virtually); converting to void* |
3880 | // is trivial and left to AST consumers to handle. |
3881 | QualType ParamType = OperatorDelete->getParamDecl(i: 0)->getType(); |
3882 | if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) { |
3883 | Qualifiers Qs = Pointee.getQualifiers(); |
3884 | if (Qs.hasCVRQualifiers()) { |
3885 | // Qualifiers are irrelevant to this conversion; we're only looking |
3886 | // for access and ambiguity. |
3887 | Qs.removeCVRQualifiers(); |
3888 | QualType Unqual = Context.getPointerType( |
3889 | T: Context.getQualifiedType(T: Pointee.getUnqualifiedType(), Qs)); |
3890 | Ex = ImpCastExprToType(E: Ex.get(), Type: Unqual, CK: CK_NoOp); |
3891 | } |
3892 | Ex = PerformImplicitConversion(From: Ex.get(), ToType: ParamType, Action: AA_Passing); |
3893 | if (Ex.isInvalid()) |
3894 | return ExprError(); |
3895 | } |
3896 | } |
3897 | |
3898 | CXXDeleteExpr *Result = new (Context) CXXDeleteExpr( |
3899 | Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten, |
3900 | UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc); |
3901 | AnalyzeDeleteExprMismatch(DE: Result); |
3902 | return Result; |
3903 | } |
3904 | |
3905 | static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall, |
3906 | bool IsDelete, |
3907 | FunctionDecl *&Operator) { |
3908 | |
3909 | DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName( |
3910 | Op: IsDelete ? OO_Delete : OO_New); |
3911 | |
3912 | LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName); |
3913 | S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl()); |
3914 | assert(!R.empty() && "implicitly declared allocation functions not found" ); |
3915 | assert(!R.isAmbiguous() && "global allocation functions are ambiguous" ); |
3916 | |
3917 | // We do our own custom access checks below. |
3918 | R.suppressDiagnostics(); |
3919 | |
3920 | SmallVector<Expr *, 8> Args(TheCall->arguments()); |
3921 | OverloadCandidateSet Candidates(R.getNameLoc(), |
3922 | OverloadCandidateSet::CSK_Normal); |
3923 | for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end(); |
3924 | FnOvl != FnOvlEnd; ++FnOvl) { |
3925 | // Even member operator new/delete are implicitly treated as |
3926 | // static, so don't use AddMemberCandidate. |
3927 | NamedDecl *D = (*FnOvl)->getUnderlyingDecl(); |
3928 | |
3929 | if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(Val: D)) { |
3930 | S.AddTemplateOverloadCandidate(FunctionTemplate: FnTemplate, FoundDecl: FnOvl.getPair(), |
3931 | /*ExplicitTemplateArgs=*/nullptr, Args, |
3932 | CandidateSet&: Candidates, |
3933 | /*SuppressUserConversions=*/false); |
3934 | continue; |
3935 | } |
3936 | |
3937 | FunctionDecl *Fn = cast<FunctionDecl>(Val: D); |
3938 | S.AddOverloadCandidate(Function: Fn, FoundDecl: FnOvl.getPair(), Args, CandidateSet&: Candidates, |
3939 | /*SuppressUserConversions=*/false); |
3940 | } |
3941 | |
3942 | SourceRange Range = TheCall->getSourceRange(); |
3943 | |
3944 | // Do the resolution. |
3945 | OverloadCandidateSet::iterator Best; |
3946 | switch (Candidates.BestViableFunction(S, Loc: R.getNameLoc(), Best)) { |
3947 | case OR_Success: { |
3948 | // Got one! |
3949 | FunctionDecl *FnDecl = Best->Function; |
3950 | assert(R.getNamingClass() == nullptr && |
3951 | "class members should not be considered" ); |
3952 | |
3953 | if (!FnDecl->isReplaceableGlobalAllocationFunction()) { |
3954 | S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual) |
3955 | << (IsDelete ? 1 : 0) << Range; |
3956 | S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here) |
3957 | << R.getLookupName() << FnDecl->getSourceRange(); |
3958 | return true; |
3959 | } |
3960 | |
3961 | Operator = FnDecl; |
3962 | return false; |
3963 | } |
3964 | |
3965 | case OR_No_Viable_Function: |
3966 | Candidates.NoteCandidates( |
3967 | PartialDiagnosticAt(R.getNameLoc(), |
3968 | S.PDiag(diag::err_ovl_no_viable_function_in_call) |
3969 | << R.getLookupName() << Range), |
3970 | S, OCD_AllCandidates, Args); |
3971 | return true; |
3972 | |
3973 | case OR_Ambiguous: |
3974 | Candidates.NoteCandidates( |
3975 | PartialDiagnosticAt(R.getNameLoc(), |
3976 | S.PDiag(diag::err_ovl_ambiguous_call) |
3977 | << R.getLookupName() << Range), |
3978 | S, OCD_AmbiguousCandidates, Args); |
3979 | return true; |
3980 | |
3981 | case OR_Deleted: |
3982 | S.DiagnoseUseOfDeletedFunction(Loc: R.getNameLoc(), Range, Name: R.getLookupName(), |
3983 | CandidateSet&: Candidates, Fn: Best->Function, Args); |
3984 | return true; |
3985 | } |
3986 | llvm_unreachable("Unreachable, bad result from BestViableFunction" ); |
3987 | } |
3988 | |
3989 | ExprResult Sema::BuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, |
3990 | bool IsDelete) { |
3991 | CallExpr *TheCall = cast<CallExpr>(Val: TheCallResult.get()); |
3992 | if (!getLangOpts().CPlusPlus) { |
3993 | Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language) |
3994 | << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new" ) |
3995 | << "C++" ; |
3996 | return ExprError(); |
3997 | } |
3998 | // CodeGen assumes it can find the global new and delete to call, |
3999 | // so ensure that they are declared. |
4000 | DeclareGlobalNewDelete(); |
4001 | |
4002 | FunctionDecl *OperatorNewOrDelete = nullptr; |
4003 | if (resolveBuiltinNewDeleteOverload(S&: *this, TheCall, IsDelete, |
4004 | Operator&: OperatorNewOrDelete)) |
4005 | return ExprError(); |
4006 | assert(OperatorNewOrDelete && "should be found" ); |
4007 | |
4008 | DiagnoseUseOfDecl(D: OperatorNewOrDelete, Locs: TheCall->getExprLoc()); |
4009 | MarkFunctionReferenced(Loc: TheCall->getExprLoc(), Func: OperatorNewOrDelete); |
4010 | |
4011 | TheCall->setType(OperatorNewOrDelete->getReturnType()); |
4012 | for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) { |
4013 | QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType(); |
4014 | InitializedEntity Entity = |
4015 | InitializedEntity::InitializeParameter(Context, Type: ParamTy, Consumed: false); |
4016 | ExprResult Arg = PerformCopyInitialization( |
4017 | Entity, EqualLoc: TheCall->getArg(Arg: i)->getBeginLoc(), Init: TheCall->getArg(Arg: i)); |
4018 | if (Arg.isInvalid()) |
4019 | return ExprError(); |
4020 | TheCall->setArg(Arg: i, ArgExpr: Arg.get()); |
4021 | } |
4022 | auto Callee = dyn_cast<ImplicitCastExpr>(Val: TheCall->getCallee()); |
4023 | assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr && |
4024 | "Callee expected to be implicit cast to a builtin function pointer" ); |
4025 | Callee->setType(OperatorNewOrDelete->getType()); |
4026 | |
4027 | return TheCallResult; |
4028 | } |
4029 | |
4030 | void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, |
4031 | bool IsDelete, bool CallCanBeVirtual, |
4032 | bool WarnOnNonAbstractTypes, |
4033 | SourceLocation DtorLoc) { |
4034 | if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext()) |
4035 | return; |
4036 | |
4037 | // C++ [expr.delete]p3: |
4038 | // In the first alternative (delete object), if the static type of the |
4039 | // object to be deleted is different from its dynamic type, the static |
4040 | // type shall be a base class of the dynamic type of the object to be |
4041 | // deleted and the static type shall have a virtual destructor or the |
4042 | // behavior is undefined. |
4043 | // |
4044 | const CXXRecordDecl *PointeeRD = dtor->getParent(); |
4045 | // Note: a final class cannot be derived from, no issue there |
4046 | if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>()) |
4047 | return; |
4048 | |
4049 | // If the superclass is in a system header, there's nothing that can be done. |
4050 | // The `delete` (where we emit the warning) can be in a system header, |
4051 | // what matters for this warning is where the deleted type is defined. |
4052 | if (getSourceManager().isInSystemHeader(Loc: PointeeRD->getLocation())) |
4053 | return; |
4054 | |
4055 | QualType ClassType = dtor->getFunctionObjectParameterType(); |
4056 | if (PointeeRD->isAbstract()) { |
4057 | // If the class is abstract, we warn by default, because we're |
4058 | // sure the code has undefined behavior. |
4059 | Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1) |
4060 | << ClassType; |
4061 | } else if (WarnOnNonAbstractTypes) { |
4062 | // Otherwise, if this is not an array delete, it's a bit suspect, |
4063 | // but not necessarily wrong. |
4064 | Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1) |
4065 | << ClassType; |
4066 | } |
4067 | if (!IsDelete) { |
4068 | std::string TypeStr; |
4069 | ClassType.getAsStringInternal(Str&: TypeStr, Policy: getPrintingPolicy()); |
4070 | Diag(DtorLoc, diag::note_delete_non_virtual) |
4071 | << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::" ); |
4072 | } |
4073 | } |
4074 | |
4075 | Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar, |
4076 | SourceLocation StmtLoc, |
4077 | ConditionKind CK) { |
4078 | ExprResult E = |
4079 | CheckConditionVariable(ConditionVar: cast<VarDecl>(Val: ConditionVar), StmtLoc, CK); |
4080 | if (E.isInvalid()) |
4081 | return ConditionError(); |
4082 | return ConditionResult(*this, ConditionVar, MakeFullExpr(Arg: E.get(), CC: StmtLoc), |
4083 | CK == ConditionKind::ConstexprIf); |
4084 | } |
4085 | |
4086 | /// Check the use of the given variable as a C++ condition in an if, |
4087 | /// while, do-while, or switch statement. |
4088 | ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar, |
4089 | SourceLocation StmtLoc, |
4090 | ConditionKind CK) { |
4091 | if (ConditionVar->isInvalidDecl()) |
4092 | return ExprError(); |
4093 | |
4094 | QualType T = ConditionVar->getType(); |
4095 | |
4096 | // C++ [stmt.select]p2: |
4097 | // The declarator shall not specify a function or an array. |
4098 | if (T->isFunctionType()) |
4099 | return ExprError(Diag(ConditionVar->getLocation(), |
4100 | diag::err_invalid_use_of_function_type) |
4101 | << ConditionVar->getSourceRange()); |
4102 | else if (T->isArrayType()) |
4103 | return ExprError(Diag(ConditionVar->getLocation(), |
4104 | diag::err_invalid_use_of_array_type) |
4105 | << ConditionVar->getSourceRange()); |
4106 | |
4107 | ExprResult Condition = BuildDeclRefExpr( |
4108 | ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue, |
4109 | ConditionVar->getLocation()); |
4110 | |
4111 | switch (CK) { |
4112 | case ConditionKind::Boolean: |
4113 | return CheckBooleanCondition(Loc: StmtLoc, E: Condition.get()); |
4114 | |
4115 | case ConditionKind::ConstexprIf: |
4116 | return CheckBooleanCondition(Loc: StmtLoc, E: Condition.get(), IsConstexpr: true); |
4117 | |
4118 | case ConditionKind::Switch: |
4119 | return CheckSwitchCondition(SwitchLoc: StmtLoc, Cond: Condition.get()); |
4120 | } |
4121 | |
4122 | llvm_unreachable("unexpected condition kind" ); |
4123 | } |
4124 | |
4125 | /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid. |
4126 | ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) { |
4127 | // C++11 6.4p4: |
4128 | // The value of a condition that is an initialized declaration in a statement |
4129 | // other than a switch statement is the value of the declared variable |
4130 | // implicitly converted to type bool. If that conversion is ill-formed, the |
4131 | // program is ill-formed. |
4132 | // The value of a condition that is an expression is the value of the |
4133 | // expression, implicitly converted to bool. |
4134 | // |
4135 | // C++23 8.5.2p2 |
4136 | // If the if statement is of the form if constexpr, the value of the condition |
4137 | // is contextually converted to bool and the converted expression shall be |
4138 | // a constant expression. |
4139 | // |
4140 | |
4141 | ExprResult E = PerformContextuallyConvertToBool(From: CondExpr); |
4142 | if (!IsConstexpr || E.isInvalid() || E.get()->isValueDependent()) |
4143 | return E; |
4144 | |
4145 | // FIXME: Return this value to the caller so they don't need to recompute it. |
4146 | llvm::APSInt Cond; |
4147 | E = VerifyIntegerConstantExpression( |
4148 | E.get(), &Cond, |
4149 | diag::err_constexpr_if_condition_expression_is_not_constant); |
4150 | return E; |
4151 | } |
4152 | |
4153 | /// Helper function to determine whether this is the (deprecated) C++ |
4154 | /// conversion from a string literal to a pointer to non-const char or |
4155 | /// non-const wchar_t (for narrow and wide string literals, |
4156 | /// respectively). |
4157 | bool |
4158 | Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { |
4159 | // Look inside the implicit cast, if it exists. |
4160 | if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Val: From)) |
4161 | From = Cast->getSubExpr(); |
4162 | |
4163 | // A string literal (2.13.4) that is not a wide string literal can |
4164 | // be converted to an rvalue of type "pointer to char"; a wide |
4165 | // string literal can be converted to an rvalue of type "pointer |
4166 | // to wchar_t" (C++ 4.2p2). |
4167 | if (StringLiteral *StrLit = dyn_cast<StringLiteral>(Val: From->IgnoreParens())) |
4168 | if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) |
4169 | if (const BuiltinType *ToPointeeType |
4170 | = ToPtrType->getPointeeType()->getAs<BuiltinType>()) { |
4171 | // This conversion is considered only when there is an |
4172 | // explicit appropriate pointer target type (C++ 4.2p2). |
4173 | if (!ToPtrType->getPointeeType().hasQualifiers()) { |
4174 | switch (StrLit->getKind()) { |
4175 | case StringLiteralKind::UTF8: |
4176 | case StringLiteralKind::UTF16: |
4177 | case StringLiteralKind::UTF32: |
4178 | // We don't allow UTF literals to be implicitly converted |
4179 | break; |
4180 | case StringLiteralKind::Ordinary: |
4181 | return (ToPointeeType->getKind() == BuiltinType::Char_U || |
4182 | ToPointeeType->getKind() == BuiltinType::Char_S); |
4183 | case StringLiteralKind::Wide: |
4184 | return Context.typesAreCompatible(T1: Context.getWideCharType(), |
4185 | T2: QualType(ToPointeeType, 0)); |
4186 | case StringLiteralKind::Unevaluated: |
4187 | assert(false && "Unevaluated string literal in expression" ); |
4188 | break; |
4189 | } |
4190 | } |
4191 | } |
4192 | |
4193 | return false; |
4194 | } |
4195 | |
4196 | static ExprResult BuildCXXCastArgument(Sema &S, |
4197 | SourceLocation CastLoc, |
4198 | QualType Ty, |
4199 | CastKind Kind, |
4200 | CXXMethodDecl *Method, |
4201 | DeclAccessPair FoundDecl, |
4202 | bool HadMultipleCandidates, |
4203 | Expr *From) { |
4204 | switch (Kind) { |
4205 | default: llvm_unreachable("Unhandled cast kind!" ); |
4206 | case CK_ConstructorConversion: { |
4207 | CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Val: Method); |
4208 | SmallVector<Expr*, 8> ConstructorArgs; |
4209 | |
4210 | if (S.RequireNonAbstractType(CastLoc, Ty, |
4211 | diag::err_allocation_of_abstract_type)) |
4212 | return ExprError(); |
4213 | |
4214 | if (S.CompleteConstructorCall(Constructor, DeclInitType: Ty, ArgsPtr: From, Loc: CastLoc, |
4215 | ConvertedArgs&: ConstructorArgs)) |
4216 | return ExprError(); |
4217 | |
4218 | S.CheckConstructorAccess(Loc: CastLoc, D: Constructor, FoundDecl, |
4219 | Entity: InitializedEntity::InitializeTemporary(Type: Ty)); |
4220 | if (S.DiagnoseUseOfDecl(Method, CastLoc)) |
4221 | return ExprError(); |
4222 | |
4223 | ExprResult Result = S.BuildCXXConstructExpr( |
4224 | ConstructLoc: CastLoc, DeclInitType: Ty, FoundDecl, Constructor: cast<CXXConstructorDecl>(Val: Method), |
4225 | Exprs: ConstructorArgs, HadMultipleCandidates, |
4226 | /*ListInit*/ IsListInitialization: false, /*StdInitListInit*/ IsStdInitListInitialization: false, /*ZeroInit*/ RequiresZeroInit: false, |
4227 | ConstructKind: CXXConstructionKind::Complete, ParenRange: SourceRange()); |
4228 | if (Result.isInvalid()) |
4229 | return ExprError(); |
4230 | |
4231 | return S.MaybeBindToTemporary(E: Result.getAs<Expr>()); |
4232 | } |
4233 | |
4234 | case CK_UserDefinedConversion: { |
4235 | assert(!From->getType()->isPointerType() && "Arg can't have pointer type!" ); |
4236 | |
4237 | S.CheckMemberOperatorAccess(Loc: CastLoc, ObjectExpr: From, /*arg*/ ArgExpr: nullptr, FoundDecl); |
4238 | if (S.DiagnoseUseOfDecl(Method, CastLoc)) |
4239 | return ExprError(); |
4240 | |
4241 | // Create an implicit call expr that calls it. |
4242 | CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: Method); |
4243 | ExprResult Result = S.BuildCXXMemberCallExpr(Exp: From, FoundDecl, Method: Conv, |
4244 | HadMultipleCandidates); |
4245 | if (Result.isInvalid()) |
4246 | return ExprError(); |
4247 | // Record usage of conversion in an implicit cast. |
4248 | Result = ImplicitCastExpr::Create(Context: S.Context, T: Result.get()->getType(), |
4249 | Kind: CK_UserDefinedConversion, Operand: Result.get(), |
4250 | BasePath: nullptr, Cat: Result.get()->getValueKind(), |
4251 | FPO: S.CurFPFeatureOverrides()); |
4252 | |
4253 | return S.MaybeBindToTemporary(E: Result.get()); |
4254 | } |
4255 | } |
4256 | } |
4257 | |
4258 | /// PerformImplicitConversion - Perform an implicit conversion of the |
4259 | /// expression From to the type ToType using the pre-computed implicit |
4260 | /// conversion sequence ICS. Returns the converted |
4261 | /// expression. Action is the kind of conversion we're performing, |
4262 | /// used in the error message. |
4263 | ExprResult |
4264 | Sema::PerformImplicitConversion(Expr *From, QualType ToType, |
4265 | const ImplicitConversionSequence &ICS, |
4266 | AssignmentAction Action, |
4267 | CheckedConversionKind CCK) { |
4268 | // C++ [over.match.oper]p7: [...] operands of class type are converted [...] |
4269 | if (CCK == CheckedConversionKind::ForBuiltinOverloadedOp && |
4270 | !From->getType()->isRecordType()) |
4271 | return From; |
4272 | |
4273 | switch (ICS.getKind()) { |
4274 | case ImplicitConversionSequence::StandardConversion: { |
4275 | ExprResult Res = PerformImplicitConversion(From, ToType, SCS: ICS.Standard, |
4276 | Action, CCK); |
4277 | if (Res.isInvalid()) |
4278 | return ExprError(); |
4279 | From = Res.get(); |
4280 | break; |
4281 | } |
4282 | |
4283 | case ImplicitConversionSequence::UserDefinedConversion: { |
4284 | |
4285 | FunctionDecl *FD = ICS.UserDefined.ConversionFunction; |
4286 | CastKind CastKind; |
4287 | QualType BeforeToType; |
4288 | assert(FD && "no conversion function for user-defined conversion seq" ); |
4289 | if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Val: FD)) { |
4290 | CastKind = CK_UserDefinedConversion; |
4291 | |
4292 | // If the user-defined conversion is specified by a conversion function, |
4293 | // the initial standard conversion sequence converts the source type to |
4294 | // the implicit object parameter of the conversion function. |
4295 | BeforeToType = Context.getTagDeclType(Decl: Conv->getParent()); |
4296 | } else { |
4297 | const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(Val: FD); |
4298 | CastKind = CK_ConstructorConversion; |
4299 | // Do no conversion if dealing with ... for the first conversion. |
4300 | if (!ICS.UserDefined.EllipsisConversion) { |
4301 | // If the user-defined conversion is specified by a constructor, the |
4302 | // initial standard conversion sequence converts the source type to |
4303 | // the type required by the argument of the constructor |
4304 | BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType(); |
4305 | } |
4306 | } |
4307 | // Watch out for ellipsis conversion. |
4308 | if (!ICS.UserDefined.EllipsisConversion) { |
4309 | ExprResult Res = |
4310 | PerformImplicitConversion(From, ToType: BeforeToType, |
4311 | SCS: ICS.UserDefined.Before, Action: AA_Converting, |
4312 | CCK); |
4313 | if (Res.isInvalid()) |
4314 | return ExprError(); |
4315 | From = Res.get(); |
4316 | } |
4317 | |
4318 | ExprResult CastArg = BuildCXXCastArgument( |
4319 | *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind, |
4320 | cast<CXXMethodDecl>(Val: FD), ICS.UserDefined.FoundConversionFunction, |
4321 | ICS.UserDefined.HadMultipleCandidates, From); |
4322 | |
4323 | if (CastArg.isInvalid()) |
4324 | return ExprError(); |
4325 | |
4326 | From = CastArg.get(); |
4327 | |
4328 | // C++ [over.match.oper]p7: |
4329 | // [...] the second standard conversion sequence of a user-defined |
4330 | // conversion sequence is not applied. |
4331 | if (CCK == CheckedConversionKind::ForBuiltinOverloadedOp) |
4332 | return From; |
4333 | |
4334 | return PerformImplicitConversion(From, ToType, SCS: ICS.UserDefined.After, |
4335 | Action: AA_Converting, CCK); |
4336 | } |
4337 | |
4338 | case ImplicitConversionSequence::AmbiguousConversion: |
4339 | ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(), |
4340 | PDiag(diag::err_typecheck_ambiguous_condition) |
4341 | << From->getSourceRange()); |
4342 | return ExprError(); |
4343 | |
4344 | case ImplicitConversionSequence::EllipsisConversion: |
4345 | case ImplicitConversionSequence::StaticObjectArgumentConversion: |
4346 | llvm_unreachable("bad conversion" ); |
4347 | |
4348 | case ImplicitConversionSequence::BadConversion: |
4349 | Sema::AssignConvertType ConvTy = |
4350 | CheckAssignmentConstraints(Loc: From->getExprLoc(), LHSType: ToType, RHSType: From->getType()); |
4351 | bool Diagnosed = DiagnoseAssignmentResult( |
4352 | ConvTy: ConvTy == Compatible ? Incompatible : ConvTy, Loc: From->getExprLoc(), |
4353 | DstType: ToType, SrcType: From->getType(), SrcExpr: From, Action); |
4354 | assert(Diagnosed && "failed to diagnose bad conversion" ); (void)Diagnosed; |
4355 | return ExprError(); |
4356 | } |
4357 | |
4358 | // Everything went well. |
4359 | return From; |
4360 | } |
4361 | |
4362 | /// PerformImplicitConversion - Perform an implicit conversion of the |
4363 | /// expression From to the type ToType by following the standard |
4364 | /// conversion sequence SCS. Returns the converted |
4365 | /// expression. Flavor is the context in which we're performing this |
4366 | /// conversion, for use in error messages. |
4367 | ExprResult |
4368 | Sema::PerformImplicitConversion(Expr *From, QualType ToType, |
4369 | const StandardConversionSequence& SCS, |
4370 | AssignmentAction Action, |
4371 | CheckedConversionKind CCK) { |
4372 | bool CStyle = (CCK == CheckedConversionKind::CStyleCast || |
4373 | CCK == CheckedConversionKind::FunctionalCast); |
4374 | |
4375 | // Overall FIXME: we are recomputing too many types here and doing far too |
4376 | // much extra work. What this means is that we need to keep track of more |
4377 | // information that is computed when we try the implicit conversion initially, |
4378 | // so that we don't need to recompute anything here. |
4379 | QualType FromType = From->getType(); |
4380 | |
4381 | if (SCS.CopyConstructor) { |
4382 | // FIXME: When can ToType be a reference type? |
4383 | assert(!ToType->isReferenceType()); |
4384 | if (SCS.Second == ICK_Derived_To_Base) { |
4385 | SmallVector<Expr*, 8> ConstructorArgs; |
4386 | if (CompleteConstructorCall( |
4387 | Constructor: cast<CXXConstructorDecl>(Val: SCS.CopyConstructor), DeclInitType: ToType, ArgsPtr: From, |
4388 | /*FIXME:ConstructLoc*/ Loc: SourceLocation(), ConvertedArgs&: ConstructorArgs)) |
4389 | return ExprError(); |
4390 | return BuildCXXConstructExpr( |
4391 | /*FIXME:ConstructLoc*/ ConstructLoc: SourceLocation(), DeclInitType: ToType, |
4392 | FoundDecl: SCS.FoundCopyConstructor, Constructor: SCS.CopyConstructor, Exprs: ConstructorArgs, |
4393 | /*HadMultipleCandidates*/ false, |
4394 | /*ListInit*/ IsListInitialization: false, /*StdInitListInit*/ IsStdInitListInitialization: false, /*ZeroInit*/ RequiresZeroInit: false, |
4395 | ConstructKind: CXXConstructionKind::Complete, ParenRange: SourceRange()); |
4396 | } |
4397 | return BuildCXXConstructExpr( |
4398 | /*FIXME:ConstructLoc*/ ConstructLoc: SourceLocation(), DeclInitType: ToType, |
4399 | FoundDecl: SCS.FoundCopyConstructor, Constructor: SCS.CopyConstructor, Exprs: From, |
4400 | /*HadMultipleCandidates*/ false, |
4401 | /*ListInit*/ IsListInitialization: false, /*StdInitListInit*/ IsStdInitListInitialization: false, /*ZeroInit*/ RequiresZeroInit: false, |
4402 | ConstructKind: CXXConstructionKind::Complete, ParenRange: SourceRange()); |
4403 | } |
4404 | |
4405 | // Resolve overloaded function references. |
4406 | if (Context.hasSameType(FromType, Context.OverloadTy)) { |
4407 | DeclAccessPair Found; |
4408 | FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(AddressOfExpr: From, TargetType: ToType, |
4409 | Complain: true, Found); |
4410 | if (!Fn) |
4411 | return ExprError(); |
4412 | |
4413 | if (DiagnoseUseOfDecl(D: Fn, Locs: From->getBeginLoc())) |
4414 | return ExprError(); |
4415 | |
4416 | ExprResult Res = FixOverloadedFunctionReference(E: From, FoundDecl: Found, Fn); |
4417 | if (Res.isInvalid()) |
4418 | return ExprError(); |
4419 | |
4420 | // We might get back another placeholder expression if we resolved to a |
4421 | // builtin. |
4422 | Res = CheckPlaceholderExpr(E: Res.get()); |
4423 | if (Res.isInvalid()) |
4424 | return ExprError(); |
4425 | |
4426 | From = Res.get(); |
4427 | FromType = From->getType(); |
4428 | } |
4429 | |
4430 | // If we're converting to an atomic type, first convert to the corresponding |
4431 | // non-atomic type. |
4432 | QualType ToAtomicType; |
4433 | if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) { |
4434 | ToAtomicType = ToType; |
4435 | ToType = ToAtomic->getValueType(); |
4436 | } |
4437 | |
4438 | QualType InitialFromType = FromType; |
4439 | // Perform the first implicit conversion. |
4440 | switch (SCS.First) { |
4441 | case ICK_Identity: |
4442 | if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) { |
4443 | FromType = FromAtomic->getValueType().getUnqualifiedType(); |
4444 | From = ImplicitCastExpr::Create(Context, T: FromType, Kind: CK_AtomicToNonAtomic, |
4445 | Operand: From, /*BasePath=*/nullptr, Cat: VK_PRValue, |
4446 | FPO: FPOptionsOverride()); |
4447 | } |
4448 | break; |
4449 | |
4450 | case ICK_Lvalue_To_Rvalue: { |
4451 | assert(From->getObjectKind() != OK_ObjCProperty); |
4452 | ExprResult FromRes = DefaultLvalueConversion(E: From); |
4453 | if (FromRes.isInvalid()) |
4454 | return ExprError(); |
4455 | |
4456 | From = FromRes.get(); |
4457 | FromType = From->getType(); |
4458 | break; |
4459 | } |
4460 | |
4461 | case ICK_Array_To_Pointer: |
4462 | FromType = Context.getArrayDecayedType(T: FromType); |
4463 | From = ImpCastExprToType(E: From, Type: FromType, CK: CK_ArrayToPointerDecay, VK: VK_PRValue, |
4464 | /*BasePath=*/nullptr, CCK) |
4465 | .get(); |
4466 | break; |
4467 | |
4468 | case ICK_HLSL_Array_RValue: |
4469 | FromType = Context.getArrayParameterType(Ty: FromType); |
4470 | From = ImpCastExprToType(E: From, Type: FromType, CK: CK_HLSLArrayRValue, VK: VK_PRValue, |
4471 | /*BasePath=*/nullptr, CCK) |
4472 | .get(); |
4473 | break; |
4474 | |
4475 | case ICK_Function_To_Pointer: |
4476 | FromType = Context.getPointerType(T: FromType); |
4477 | From = ImpCastExprToType(E: From, Type: FromType, CK: CK_FunctionToPointerDecay, |
4478 | VK: VK_PRValue, /*BasePath=*/nullptr, CCK) |
4479 | .get(); |
4480 | break; |
4481 | |
4482 | default: |
4483 | llvm_unreachable("Improper first standard conversion" ); |
4484 | } |
4485 | |
4486 | // Perform the second implicit conversion |
4487 | switch (SCS.Second) { |
4488 | case ICK_Identity: |
4489 | // C++ [except.spec]p5: |
4490 | // [For] assignment to and initialization of pointers to functions, |
4491 | // pointers to member functions, and references to functions: the |
4492 | // target entity shall allow at least the exceptions allowed by the |
4493 | // source value in the assignment or initialization. |
4494 | switch (Action) { |
4495 | case AA_Assigning: |
4496 | case AA_Initializing: |
4497 | // Note, function argument passing and returning are initialization. |
4498 | case AA_Passing: |
4499 | case AA_Returning: |
4500 | case AA_Sending: |
4501 | case AA_Passing_CFAudited: |
4502 | if (CheckExceptionSpecCompatibility(From, ToType)) |
4503 | return ExprError(); |
4504 | break; |
4505 | |
4506 | case AA_Casting: |
4507 | case AA_Converting: |
4508 | // Casts and implicit conversions are not initialization, so are not |
4509 | // checked for exception specification mismatches. |
4510 | break; |
4511 | } |
4512 | // Nothing else to do. |
4513 | break; |
4514 | |
4515 | case ICK_Integral_Promotion: |
4516 | case ICK_Integral_Conversion: |
4517 | if (ToType->isBooleanType()) { |
4518 | assert(FromType->castAs<EnumType>()->getDecl()->isFixed() && |
4519 | SCS.Second == ICK_Integral_Promotion && |
4520 | "only enums with fixed underlying type can promote to bool" ); |
4521 | From = ImpCastExprToType(E: From, Type: ToType, CK: CK_IntegralToBoolean, VK: VK_PRValue, |
4522 | /*BasePath=*/nullptr, CCK) |
4523 | .get(); |
4524 | } else { |
4525 | From = ImpCastExprToType(E: From, Type: ToType, CK: CK_IntegralCast, VK: VK_PRValue, |
4526 | /*BasePath=*/nullptr, CCK) |
4527 | .get(); |
4528 | } |
4529 | break; |
4530 | |
4531 | case ICK_Floating_Promotion: |
4532 | case ICK_Floating_Conversion: |
4533 | From = ImpCastExprToType(E: From, Type: ToType, CK: CK_FloatingCast, VK: VK_PRValue, |
4534 | /*BasePath=*/nullptr, CCK) |
4535 | .get(); |
4536 | break; |
4537 | |
4538 | case ICK_Complex_Promotion: |
4539 | case ICK_Complex_Conversion: { |
4540 | QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType(); |
4541 | QualType ToEl = ToType->castAs<ComplexType>()->getElementType(); |
4542 | CastKind CK; |
4543 | if (FromEl->isRealFloatingType()) { |
4544 | if (ToEl->isRealFloatingType()) |
4545 | CK = CK_FloatingComplexCast; |
4546 | else |
4547 | CK = CK_FloatingComplexToIntegralComplex; |
4548 | } else if (ToEl->isRealFloatingType()) { |
4549 | CK = CK_IntegralComplexToFloatingComplex; |
4550 | } else { |
4551 | CK = CK_IntegralComplexCast; |
4552 | } |
4553 | From = ImpCastExprToType(E: From, Type: ToType, CK, VK: VK_PRValue, /*BasePath=*/nullptr, |
4554 | CCK) |
4555 | .get(); |
4556 | break; |
4557 | } |
4558 | |
4559 | case ICK_Floating_Integral: |
4560 | if (ToType->isRealFloatingType()) |
4561 | From = ImpCastExprToType(E: From, Type: ToType, CK: CK_IntegralToFloating, VK: VK_PRValue, |
4562 | /*BasePath=*/nullptr, CCK) |
4563 | .get(); |
4564 | else |
4565 | From = ImpCastExprToType(E: From, Type: ToType, CK: CK_FloatingToIntegral, VK: VK_PRValue, |
4566 | /*BasePath=*/nullptr, CCK) |
4567 | .get(); |
4568 | break; |
4569 | |
4570 | case ICK_Fixed_Point_Conversion: |
4571 | assert((FromType->isFixedPointType() || ToType->isFixedPointType()) && |
4572 | "Attempting implicit fixed point conversion without a fixed " |
4573 | "point operand" ); |
4574 | if (FromType->isFloatingType()) |
4575 | From = ImpCastExprToType(E: From, Type: ToType, CK: CK_FloatingToFixedPoint, |
4576 | VK: VK_PRValue, |
4577 | /*BasePath=*/nullptr, CCK).get(); |
4578 | else if (ToType->isFloatingType()) |
4579 | From = ImpCastExprToType(E: From, Type: ToType, CK: CK_FixedPointToFloating, |
4580 | VK: VK_PRValue, |
4581 | /*BasePath=*/nullptr, CCK).get(); |
4582 | else if (FromType->isIntegralType(Ctx: Context)) |
4583 | From = ImpCastExprToType(E: From, Type: ToType, CK: CK_IntegralToFixedPoint, |
4584 | VK: VK_PRValue, |
4585 | /*BasePath=*/nullptr, CCK).get(); |
4586 | else if (ToType->isIntegralType(Ctx: Context)) |
4587 | From = ImpCastExprToType(E: From, Type: ToType, CK: CK_FixedPointToIntegral, |
4588 | VK: VK_PRValue, |
4589 | /*BasePath=*/nullptr, CCK).get(); |
4590 | else if (ToType->isBooleanType()) |
4591 | From = ImpCastExprToType(E: From, Type: ToType, CK: CK_FixedPointToBoolean, |
4592 | VK: VK_PRValue, |
4593 | /*BasePath=*/nullptr, CCK).get(); |
4594 | else |
4595 | From = ImpCastExprToType(E: From, Type: ToType, CK: CK_FixedPointCast, |
4596 | VK: VK_PRValue, |
4597 | /*BasePath=*/nullptr, CCK).get(); |
4598 | break; |
4599 | |
4600 | case ICK_Compatible_Conversion: |
4601 | From = ImpCastExprToType(E: From, Type: ToType, CK: CK_NoOp, VK: From->getValueKind(), |
4602 | /*BasePath=*/nullptr, CCK).get(); |
4603 | break; |
4604 | |
4605 | case ICK_Writeback_Conversion: |
4606 | case ICK_Pointer_Conversion: { |
4607 | if (SCS.IncompatibleObjC && Action != AA_Casting) { |
4608 | // Diagnose incompatible Objective-C conversions |
4609 | if (Action == AA_Initializing || Action == AA_Assigning) |
4610 | Diag(From->getBeginLoc(), |
4611 | diag::ext_typecheck_convert_incompatible_pointer) |
4612 | << ToType << From->getType() << Action << From->getSourceRange() |
4613 | << 0; |
4614 | else |
4615 | Diag(From->getBeginLoc(), |
4616 | diag::ext_typecheck_convert_incompatible_pointer) |
4617 | << From->getType() << ToType << Action << From->getSourceRange() |
4618 | << 0; |
4619 | |
4620 | if (From->getType()->isObjCObjectPointerType() && |
4621 | ToType->isObjCObjectPointerType()) |
4622 | EmitRelatedResultTypeNote(E: From); |
4623 | } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && |
4624 | !CheckObjCARCUnavailableWeakConversion(castType: ToType, |
4625 | ExprType: From->getType())) { |
4626 | if (Action == AA_Initializing) |
4627 | Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign); |
4628 | else |
4629 | Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable) |
4630 | << (Action == AA_Casting) << From->getType() << ToType |
4631 | << From->getSourceRange(); |
4632 | } |
4633 | |
4634 | // Defer address space conversion to the third conversion. |
4635 | QualType FromPteeType = From->getType()->getPointeeType(); |
4636 | QualType ToPteeType = ToType->getPointeeType(); |
4637 | QualType NewToType = ToType; |
4638 | if (!FromPteeType.isNull() && !ToPteeType.isNull() && |
4639 | FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) { |
4640 | NewToType = Context.removeAddrSpaceQualType(T: ToPteeType); |
4641 | NewToType = Context.getAddrSpaceQualType(T: NewToType, |
4642 | AddressSpace: FromPteeType.getAddressSpace()); |
4643 | if (ToType->isObjCObjectPointerType()) |
4644 | NewToType = Context.getObjCObjectPointerType(OIT: NewToType); |
4645 | else if (ToType->isBlockPointerType()) |
4646 | NewToType = Context.getBlockPointerType(T: NewToType); |
4647 | else |
4648 | NewToType = Context.getPointerType(T: NewToType); |
4649 | } |
4650 | |
4651 | CastKind Kind; |
4652 | CXXCastPath BasePath; |
4653 | if (CheckPointerConversion(From, ToType: NewToType, Kind, BasePath, IgnoreBaseAccess: CStyle)) |
4654 | return ExprError(); |
4655 | |
4656 | // Make sure we extend blocks if necessary. |
4657 | // FIXME: doing this here is really ugly. |
4658 | if (Kind == CK_BlockPointerToObjCPointerCast) { |
4659 | ExprResult E = From; |
4660 | (void) PrepareCastToObjCObjectPointer(E); |
4661 | From = E.get(); |
4662 | } |
4663 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) |
4664 | CheckObjCConversion(castRange: SourceRange(), castType: NewToType, op&: From, CCK); |
4665 | From = ImpCastExprToType(E: From, Type: NewToType, CK: Kind, VK: VK_PRValue, BasePath: &BasePath, CCK) |
4666 | .get(); |
4667 | break; |
4668 | } |
4669 | |
4670 | case ICK_Pointer_Member: { |
4671 | CastKind Kind; |
4672 | CXXCastPath BasePath; |
4673 | if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess: CStyle)) |
4674 | return ExprError(); |
4675 | if (CheckExceptionSpecCompatibility(From, ToType)) |
4676 | return ExprError(); |
4677 | |
4678 | // We may not have been able to figure out what this member pointer resolved |
4679 | // to up until this exact point. Attempt to lock-in it's inheritance model. |
4680 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { |
4681 | (void)isCompleteType(Loc: From->getExprLoc(), T: From->getType()); |
4682 | (void)isCompleteType(Loc: From->getExprLoc(), T: ToType); |
4683 | } |
4684 | |
4685 | From = |
4686 | ImpCastExprToType(E: From, Type: ToType, CK: Kind, VK: VK_PRValue, BasePath: &BasePath, CCK).get(); |
4687 | break; |
4688 | } |
4689 | |
4690 | case ICK_Boolean_Conversion: |
4691 | // Perform half-to-boolean conversion via float. |
4692 | if (From->getType()->isHalfType()) { |
4693 | From = ImpCastExprToType(E: From, Type: Context.FloatTy, CK: CK_FloatingCast).get(); |
4694 | FromType = Context.FloatTy; |
4695 | } |
4696 | |
4697 | From = ImpCastExprToType(E: From, Type: Context.BoolTy, |
4698 | CK: ScalarTypeToBooleanCastKind(ScalarTy: FromType), VK: VK_PRValue, |
4699 | /*BasePath=*/nullptr, CCK) |
4700 | .get(); |
4701 | break; |
4702 | |
4703 | case ICK_Derived_To_Base: { |
4704 | CXXCastPath BasePath; |
4705 | if (CheckDerivedToBaseConversion( |
4706 | From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(), |
4707 | From->getSourceRange(), &BasePath, CStyle)) |
4708 | return ExprError(); |
4709 | |
4710 | From = ImpCastExprToType(E: From, Type: ToType.getNonReferenceType(), |
4711 | CK: CK_DerivedToBase, VK: From->getValueKind(), |
4712 | BasePath: &BasePath, CCK).get(); |
4713 | break; |
4714 | } |
4715 | |
4716 | case ICK_Vector_Conversion: |
4717 | From = ImpCastExprToType(E: From, Type: ToType, CK: CK_BitCast, VK: VK_PRValue, |
4718 | /*BasePath=*/nullptr, CCK) |
4719 | .get(); |
4720 | break; |
4721 | |
4722 | case ICK_SVE_Vector_Conversion: |
4723 | case ICK_RVV_Vector_Conversion: |
4724 | From = ImpCastExprToType(E: From, Type: ToType, CK: CK_BitCast, VK: VK_PRValue, |
4725 | /*BasePath=*/nullptr, CCK) |
4726 | .get(); |
4727 | break; |
4728 | |
4729 | case ICK_Vector_Splat: { |
4730 | // Vector splat from any arithmetic type to a vector. |
4731 | Expr *Elem = prepareVectorSplat(VectorTy: ToType, SplattedExpr: From).get(); |
4732 | From = ImpCastExprToType(E: Elem, Type: ToType, CK: CK_VectorSplat, VK: VK_PRValue, |
4733 | /*BasePath=*/nullptr, CCK) |
4734 | .get(); |
4735 | break; |
4736 | } |
4737 | |
4738 | case ICK_Complex_Real: |
4739 | // Case 1. x -> _Complex y |
4740 | if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) { |
4741 | QualType ElType = ToComplex->getElementType(); |
4742 | bool isFloatingComplex = ElType->isRealFloatingType(); |
4743 | |
4744 | // x -> y |
4745 | if (Context.hasSameUnqualifiedType(T1: ElType, T2: From->getType())) { |
4746 | // do nothing |
4747 | } else if (From->getType()->isRealFloatingType()) { |
4748 | From = ImpCastExprToType(E: From, Type: ElType, |
4749 | CK: isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get(); |
4750 | } else { |
4751 | assert(From->getType()->isIntegerType()); |
4752 | From = ImpCastExprToType(E: From, Type: ElType, |
4753 | CK: isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get(); |
4754 | } |
4755 | // y -> _Complex y |
4756 | From = ImpCastExprToType(E: From, Type: ToType, |
4757 | CK: isFloatingComplex ? CK_FloatingRealToComplex |
4758 | : CK_IntegralRealToComplex).get(); |
4759 | |
4760 | // Case 2. _Complex x -> y |
4761 | } else { |
4762 | auto *FromComplex = From->getType()->castAs<ComplexType>(); |
4763 | QualType ElType = FromComplex->getElementType(); |
4764 | bool isFloatingComplex = ElType->isRealFloatingType(); |
4765 | |
4766 | // _Complex x -> x |
4767 | From = ImpCastExprToType(E: From, Type: ElType, |
4768 | CK: isFloatingComplex ? CK_FloatingComplexToReal |
4769 | : CK_IntegralComplexToReal, |
4770 | VK: VK_PRValue, /*BasePath=*/nullptr, CCK) |
4771 | .get(); |
4772 | |
4773 | // x -> y |
4774 | if (Context.hasSameUnqualifiedType(T1: ElType, T2: ToType)) { |
4775 | // do nothing |
4776 | } else if (ToType->isRealFloatingType()) { |
4777 | From = ImpCastExprToType(E: From, Type: ToType, |
4778 | CK: isFloatingComplex ? CK_FloatingCast |
4779 | : CK_IntegralToFloating, |
4780 | VK: VK_PRValue, /*BasePath=*/nullptr, CCK) |
4781 | .get(); |
4782 | } else { |
4783 | assert(ToType->isIntegerType()); |
4784 | From = ImpCastExprToType(E: From, Type: ToType, |
4785 | CK: isFloatingComplex ? CK_FloatingToIntegral |
4786 | : CK_IntegralCast, |
4787 | VK: VK_PRValue, /*BasePath=*/nullptr, CCK) |
4788 | .get(); |
4789 | } |
4790 | } |
4791 | break; |
4792 | |
4793 | case ICK_Block_Pointer_Conversion: { |
4794 | LangAS AddrSpaceL = |
4795 | ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace(); |
4796 | LangAS AddrSpaceR = |
4797 | FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace(); |
4798 | assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) && |
4799 | "Invalid cast" ); |
4800 | CastKind Kind = |
4801 | AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; |
4802 | From = ImpCastExprToType(E: From, Type: ToType.getUnqualifiedType(), CK: Kind, |
4803 | VK: VK_PRValue, /*BasePath=*/nullptr, CCK) |
4804 | .get(); |
4805 | break; |
4806 | } |
4807 | |
4808 | case ICK_TransparentUnionConversion: { |
4809 | ExprResult FromRes = From; |
4810 | Sema::AssignConvertType ConvTy = |
4811 | CheckTransparentUnionArgumentConstraints(ArgType: ToType, RHS&: FromRes); |
4812 | if (FromRes.isInvalid()) |
4813 | return ExprError(); |
4814 | From = FromRes.get(); |
4815 | assert ((ConvTy == Sema::Compatible) && |
4816 | "Improper transparent union conversion" ); |
4817 | (void)ConvTy; |
4818 | break; |
4819 | } |
4820 | |
4821 | case ICK_Zero_Event_Conversion: |
4822 | case ICK_Zero_Queue_Conversion: |
4823 | From = ImpCastExprToType(E: From, Type: ToType, |
4824 | CK: CK_ZeroToOCLOpaqueType, |
4825 | VK: From->getValueKind()).get(); |
4826 | break; |
4827 | case ICK_HLSL_Vector_Truncation: { |
4828 | // Note: HLSL built-in vectors are ExtVectors. Since this truncates a vector |
4829 | // to a smaller vector, this can only operate on arguments where the source |
4830 | // and destination types are ExtVectors. |
4831 | assert(From->getType()->isExtVectorType() && ToType->isExtVectorType() && |
4832 | "HLSL vector truncation should only apply to ExtVectors" ); |
4833 | auto *FromVec = From->getType()->castAs<VectorType>(); |
4834 | auto *ToVec = ToType->castAs<VectorType>(); |
4835 | QualType ElType = FromVec->getElementType(); |
4836 | QualType TruncTy = |
4837 | Context.getExtVectorType(VectorType: ElType, NumElts: ToVec->getNumElements()); |
4838 | From = ImpCastExprToType(E: From, Type: TruncTy, CK: CK_HLSLVectorTruncation, |
4839 | VK: From->getValueKind()) |
4840 | .get(); |
4841 | break; |
4842 | } |
4843 | |
4844 | case ICK_Lvalue_To_Rvalue: |
4845 | case ICK_Array_To_Pointer: |
4846 | case ICK_Function_To_Pointer: |
4847 | case ICK_Function_Conversion: |
4848 | case ICK_Qualification: |
4849 | case ICK_Num_Conversion_Kinds: |
4850 | case ICK_C_Only_Conversion: |
4851 | case ICK_Incompatible_Pointer_Conversion: |
4852 | case ICK_HLSL_Array_RValue: |
4853 | llvm_unreachable("Improper second standard conversion" ); |
4854 | } |
4855 | |
4856 | if (SCS.Element != ICK_Identity) { |
4857 | // If SCS.Element is not ICK_Identity the To and From types must be HLSL |
4858 | // vectors or matrices. |
4859 | |
4860 | // TODO: Support HLSL matrices. |
4861 | assert((!From->getType()->isMatrixType() && !ToType->isMatrixType()) && |
4862 | "Element conversion for matrix types is not implemented yet." ); |
4863 | assert(From->getType()->isVectorType() && ToType->isVectorType() && |
4864 | "Element conversion is only supported for vector types." ); |
4865 | assert(From->getType()->getAs<VectorType>()->getNumElements() == |
4866 | ToType->getAs<VectorType>()->getNumElements() && |
4867 | "Element conversion is only supported for vectors with the same " |
4868 | "element counts." ); |
4869 | QualType FromElTy = From->getType()->getAs<VectorType>()->getElementType(); |
4870 | unsigned NumElts = ToType->getAs<VectorType>()->getNumElements(); |
4871 | switch (SCS.Element) { |
4872 | case ICK_Boolean_Conversion: |
4873 | // Perform half-to-boolean conversion via float. |
4874 | if (FromElTy->isHalfType()) { |
4875 | QualType FPExtType = Context.getExtVectorType(VectorType: FromElTy, NumElts); |
4876 | From = ImpCastExprToType(E: From, Type: FPExtType, CK: CK_FloatingCast).get(); |
4877 | FromType = FPExtType; |
4878 | } |
4879 | |
4880 | From = |
4881 | ImpCastExprToType(E: From, Type: ToType, CK: ScalarTypeToBooleanCastKind(ScalarTy: FromElTy), |
4882 | VK: VK_PRValue, |
4883 | /*BasePath=*/nullptr, CCK) |
4884 | .get(); |
4885 | break; |
4886 | case ICK_Integral_Promotion: |
4887 | case ICK_Integral_Conversion: |
4888 | if (ToType->isBooleanType()) { |
4889 | assert(FromType->castAs<EnumType>()->getDecl()->isFixed() && |
4890 | SCS.Second == ICK_Integral_Promotion && |
4891 | "only enums with fixed underlying type can promote to bool" ); |
4892 | From = ImpCastExprToType(E: From, Type: ToType, CK: CK_IntegralToBoolean, VK: VK_PRValue, |
4893 | /*BasePath=*/nullptr, CCK) |
4894 | .get(); |
4895 | } else { |
4896 | From = ImpCastExprToType(E: From, Type: ToType, CK: CK_IntegralCast, VK: VK_PRValue, |
4897 | /*BasePath=*/nullptr, CCK) |
4898 | .get(); |
4899 | } |
4900 | break; |
4901 | |
4902 | case ICK_Floating_Promotion: |
4903 | case ICK_Floating_Conversion: |
4904 | From = ImpCastExprToType(E: From, Type: ToType, CK: CK_FloatingCast, VK: VK_PRValue, |
4905 | /*BasePath=*/nullptr, CCK) |
4906 | .get(); |
4907 | break; |
4908 | case ICK_Floating_Integral: |
4909 | if (ToType->hasFloatingRepresentation()) |
4910 | From = |
4911 | ImpCastExprToType(E: From, Type: ToType, CK: CK_IntegralToFloating, VK: VK_PRValue, |
4912 | /*BasePath=*/nullptr, CCK) |
4913 | .get(); |
4914 | else |
4915 | From = |
4916 | ImpCastExprToType(E: From, Type: ToType, CK: CK_FloatingToIntegral, VK: VK_PRValue, |
4917 | /*BasePath=*/nullptr, CCK) |
4918 | .get(); |
4919 | break; |
4920 | case ICK_Identity: |
4921 | default: |
4922 | llvm_unreachable("Improper element standard conversion" ); |
4923 | } |
4924 | } |
4925 | |
4926 | switch (SCS.Third) { |
4927 | case ICK_Identity: |
4928 | // Nothing to do. |
4929 | break; |
4930 | |
4931 | case ICK_Function_Conversion: |
4932 | // If both sides are functions (or pointers/references to them), there could |
4933 | // be incompatible exception declarations. |
4934 | if (CheckExceptionSpecCompatibility(From, ToType)) |
4935 | return ExprError(); |
4936 | |
4937 | From = ImpCastExprToType(E: From, Type: ToType, CK: CK_NoOp, VK: VK_PRValue, |
4938 | /*BasePath=*/nullptr, CCK) |
4939 | .get(); |
4940 | break; |
4941 | |
4942 | case ICK_Qualification: { |
4943 | ExprValueKind VK = From->getValueKind(); |
4944 | CastKind CK = CK_NoOp; |
4945 | |
4946 | if (ToType->isReferenceType() && |
4947 | ToType->getPointeeType().getAddressSpace() != |
4948 | From->getType().getAddressSpace()) |
4949 | CK = CK_AddressSpaceConversion; |
4950 | |
4951 | if (ToType->isPointerType() && |
4952 | ToType->getPointeeType().getAddressSpace() != |
4953 | From->getType()->getPointeeType().getAddressSpace()) |
4954 | CK = CK_AddressSpaceConversion; |
4955 | |
4956 | if (!isCast(CCK) && |
4957 | !ToType->getPointeeType().getQualifiers().hasUnaligned() && |
4958 | From->getType()->getPointeeType().getQualifiers().hasUnaligned()) { |
4959 | Diag(From->getBeginLoc(), diag::warn_imp_cast_drops_unaligned) |
4960 | << InitialFromType << ToType; |
4961 | } |
4962 | |
4963 | From = ImpCastExprToType(E: From, Type: ToType.getNonLValueExprType(Context), CK, VK, |
4964 | /*BasePath=*/nullptr, CCK) |
4965 | .get(); |
4966 | |
4967 | if (SCS.DeprecatedStringLiteralToCharPtr && |
4968 | !getLangOpts().WritableStrings) { |
4969 | Diag(From->getBeginLoc(), |
4970 | getLangOpts().CPlusPlus11 |
4971 | ? diag::ext_deprecated_string_literal_conversion |
4972 | : diag::warn_deprecated_string_literal_conversion) |
4973 | << ToType.getNonReferenceType(); |
4974 | } |
4975 | |
4976 | break; |
4977 | } |
4978 | |
4979 | default: |
4980 | llvm_unreachable("Improper third standard conversion" ); |
4981 | } |
4982 | |
4983 | // If this conversion sequence involved a scalar -> atomic conversion, perform |
4984 | // that conversion now. |
4985 | if (!ToAtomicType.isNull()) { |
4986 | assert(Context.hasSameType( |
4987 | ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType())); |
4988 | From = ImpCastExprToType(E: From, Type: ToAtomicType, CK: CK_NonAtomicToAtomic, |
4989 | VK: VK_PRValue, BasePath: nullptr, CCK) |
4990 | .get(); |
4991 | } |
4992 | |
4993 | // Materialize a temporary if we're implicitly converting to a reference |
4994 | // type. This is not required by the C++ rules but is necessary to maintain |
4995 | // AST invariants. |
4996 | if (ToType->isReferenceType() && From->isPRValue()) { |
4997 | ExprResult Res = TemporaryMaterializationConversion(E: From); |
4998 | if (Res.isInvalid()) |
4999 | return ExprError(); |
5000 | From = Res.get(); |
5001 | } |
5002 | |
5003 | // If this conversion sequence succeeded and involved implicitly converting a |
5004 | // _Nullable type to a _Nonnull one, complain. |
5005 | if (!isCast(CCK)) |
5006 | diagnoseNullableToNonnullConversion(DstType: ToType, SrcType: InitialFromType, |
5007 | Loc: From->getBeginLoc()); |
5008 | |
5009 | return From; |
5010 | } |
5011 | |
5012 | /// Checks that type T is not a VLA. |
5013 | /// |
5014 | /// @returns @c true if @p T is VLA and a diagnostic was emitted, |
5015 | /// @c false otherwise. |
5016 | static bool DiagnoseVLAInCXXTypeTrait(Sema &S, const TypeSourceInfo *T, |
5017 | clang::tok::TokenKind TypeTraitID) { |
5018 | if (!T->getType()->isVariableArrayType()) |
5019 | return false; |
5020 | |
5021 | S.Diag(T->getTypeLoc().getBeginLoc(), diag::err_vla_unsupported) |
5022 | << 1 << TypeTraitID; |
5023 | return true; |
5024 | } |
5025 | |
5026 | /// Check the completeness of a type in a unary type trait. |
5027 | /// |
5028 | /// If the particular type trait requires a complete type, tries to complete |
5029 | /// it. If completing the type fails, a diagnostic is emitted and false |
5030 | /// returned. If completing the type succeeds or no completion was required, |
5031 | /// returns true. |
5032 | static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT, |
5033 | SourceLocation Loc, |
5034 | QualType ArgTy) { |
5035 | // C++0x [meta.unary.prop]p3: |
5036 | // For all of the class templates X declared in this Clause, instantiating |
5037 | // that template with a template argument that is a class template |
5038 | // specialization may result in the implicit instantiation of the template |
5039 | // argument if and only if the semantics of X require that the argument |
5040 | // must be a complete type. |
5041 | // We apply this rule to all the type trait expressions used to implement |
5042 | // these class templates. We also try to follow any GCC documented behavior |
5043 | // in these expressions to ensure portability of standard libraries. |
5044 | switch (UTT) { |
5045 | default: llvm_unreachable("not a UTT" ); |
5046 | // is_complete_type somewhat obviously cannot require a complete type. |
5047 | case UTT_IsCompleteType: |
5048 | // Fall-through |
5049 | |
5050 | // These traits are modeled on the type predicates in C++0x |
5051 | // [meta.unary.cat] and [meta.unary.comp]. They are not specified as |
5052 | // requiring a complete type, as whether or not they return true cannot be |
5053 | // impacted by the completeness of the type. |
5054 | case UTT_IsVoid: |
5055 | case UTT_IsIntegral: |
5056 | case UTT_IsFloatingPoint: |
5057 | case UTT_IsArray: |
5058 | case UTT_IsBoundedArray: |
5059 | case UTT_IsPointer: |
5060 | case UTT_IsNullPointer: |
5061 | case UTT_IsReferenceable: |
5062 | case UTT_IsLvalueReference: |
5063 | case UTT_IsRvalueReference: |
5064 | case UTT_IsMemberFunctionPointer: |
5065 | case UTT_IsMemberObjectPointer: |
5066 | case UTT_IsEnum: |
5067 | case UTT_IsScopedEnum: |
5068 | case UTT_IsUnion: |
5069 | case UTT_IsClass: |
5070 | case UTT_IsFunction: |
5071 | case UTT_IsReference: |
5072 | case UTT_IsArithmetic: |
5073 | case UTT_IsFundamental: |
5074 | case UTT_IsObject: |
5075 | case UTT_IsScalar: |
5076 | case UTT_IsCompound: |
5077 | case UTT_IsMemberPointer: |
5078 | // Fall-through |
5079 | |
5080 | // These traits are modeled on type predicates in C++0x [meta.unary.prop] |
5081 | // which requires some of its traits to have the complete type. However, |
5082 | // the completeness of the type cannot impact these traits' semantics, and |
5083 | // so they don't require it. This matches the comments on these traits in |
5084 | // Table 49. |
5085 | case UTT_IsConst: |
5086 | case UTT_IsVolatile: |
5087 | case UTT_IsSigned: |
5088 | case UTT_IsUnboundedArray: |
5089 | case UTT_IsUnsigned: |
5090 | |
5091 | // This type trait always returns false, checking the type is moot. |
5092 | case UTT_IsInterfaceClass: |
5093 | return true; |
5094 | |
5095 | // C++14 [meta.unary.prop]: |
5096 | // If T is a non-union class type, T shall be a complete type. |
5097 | case UTT_IsEmpty: |
5098 | case UTT_IsPolymorphic: |
5099 | case UTT_IsAbstract: |
5100 | if (const auto *RD = ArgTy->getAsCXXRecordDecl()) |
5101 | if (!RD->isUnion()) |
5102 | return !S.RequireCompleteType( |
5103 | Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); |
5104 | return true; |
5105 | |
5106 | // C++14 [meta.unary.prop]: |
5107 | // If T is a class type, T shall be a complete type. |
5108 | case UTT_IsFinal: |
5109 | case UTT_IsSealed: |
5110 | if (ArgTy->getAsCXXRecordDecl()) |
5111 | return !S.RequireCompleteType( |
5112 | Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); |
5113 | return true; |
5114 | |
5115 | // LWG3823: T shall be an array type, a complete type, or cv void. |
5116 | case UTT_IsAggregate: |
5117 | if (ArgTy->isArrayType() || ArgTy->isVoidType()) |
5118 | return true; |
5119 | |
5120 | return !S.RequireCompleteType( |
5121 | Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); |
5122 | |
5123 | // C++1z [meta.unary.prop]: |
5124 | // remove_all_extents_t<T> shall be a complete type or cv void. |
5125 | case UTT_IsTrivial: |
5126 | case UTT_IsTriviallyCopyable: |
5127 | case UTT_IsStandardLayout: |
5128 | case UTT_IsPOD: |
5129 | case UTT_IsLiteral: |
5130 | // By analogy, is_trivially_relocatable and is_trivially_equality_comparable |
5131 | // impose the same constraints. |
5132 | case UTT_IsTriviallyRelocatable: |
5133 | case UTT_IsTriviallyEqualityComparable: |
5134 | case UTT_CanPassInRegs: |
5135 | // Per the GCC type traits documentation, T shall be a complete type, cv void, |
5136 | // or an array of unknown bound. But GCC actually imposes the same constraints |
5137 | // as above. |
5138 | case UTT_HasNothrowAssign: |
5139 | case UTT_HasNothrowMoveAssign: |
5140 | case UTT_HasNothrowConstructor: |
5141 | case UTT_HasNothrowCopy: |
5142 | case UTT_HasTrivialAssign: |
5143 | case UTT_HasTrivialMoveAssign: |
5144 | case UTT_HasTrivialDefaultConstructor: |
5145 | case UTT_HasTrivialMoveConstructor: |
5146 | case UTT_HasTrivialCopy: |
5147 | case UTT_HasTrivialDestructor: |
5148 | case UTT_HasVirtualDestructor: |
5149 | ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0); |
5150 | [[fallthrough]]; |
5151 | |
5152 | // C++1z [meta.unary.prop]: |
5153 | // T shall be a complete type, cv void, or an array of unknown bound. |
5154 | case UTT_IsDestructible: |
5155 | case UTT_IsNothrowDestructible: |
5156 | case UTT_IsTriviallyDestructible: |
5157 | case UTT_HasUniqueObjectRepresentations: |
5158 | if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType()) |
5159 | return true; |
5160 | |
5161 | return !S.RequireCompleteType( |
5162 | Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); |
5163 | } |
5164 | } |
5165 | |
5166 | static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op, |
5167 | Sema &Self, SourceLocation KeyLoc, ASTContext &C, |
5168 | bool (CXXRecordDecl::*HasTrivial)() const, |
5169 | bool (CXXRecordDecl::*HasNonTrivial)() const, |
5170 | bool (CXXMethodDecl::*IsDesiredOp)() const) |
5171 | { |
5172 | CXXRecordDecl *RD = cast<CXXRecordDecl>(Val: RT->getDecl()); |
5173 | if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)()) |
5174 | return true; |
5175 | |
5176 | DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op); |
5177 | DeclarationNameInfo NameInfo(Name, KeyLoc); |
5178 | LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName); |
5179 | if (Self.LookupQualifiedName(Res, RD)) { |
5180 | bool FoundOperator = false; |
5181 | Res.suppressDiagnostics(); |
5182 | for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end(); |
5183 | Op != OpEnd; ++Op) { |
5184 | if (isa<FunctionTemplateDecl>(Val: *Op)) |
5185 | continue; |
5186 | |
5187 | CXXMethodDecl *Operator = cast<CXXMethodDecl>(Val: *Op); |
5188 | if((Operator->*IsDesiredOp)()) { |
5189 | FoundOperator = true; |
5190 | auto *CPT = Operator->getType()->castAs<FunctionProtoType>(); |
5191 | CPT = Self.ResolveExceptionSpec(Loc: KeyLoc, FPT: CPT); |
5192 | if (!CPT || !CPT->isNothrow()) |
5193 | return false; |
5194 | } |
5195 | } |
5196 | return FoundOperator; |
5197 | } |
5198 | return false; |
5199 | } |
5200 | |
5201 | static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT, |
5202 | SourceLocation KeyLoc, |
5203 | TypeSourceInfo *TInfo) { |
5204 | QualType T = TInfo->getType(); |
5205 | assert(!T->isDependentType() && "Cannot evaluate traits of dependent type" ); |
5206 | |
5207 | ASTContext &C = Self.Context; |
5208 | switch(UTT) { |
5209 | default: llvm_unreachable("not a UTT" ); |
5210 | // Type trait expressions corresponding to the primary type category |
5211 | // predicates in C++0x [meta.unary.cat]. |
5212 | case UTT_IsVoid: |
5213 | return T->isVoidType(); |
5214 | case UTT_IsIntegral: |
5215 | return T->isIntegralType(Ctx: C); |
5216 | case UTT_IsFloatingPoint: |
5217 | return T->isFloatingType(); |
5218 | case UTT_IsArray: |
5219 | return T->isArrayType(); |
5220 | case UTT_IsBoundedArray: |
5221 | if (DiagnoseVLAInCXXTypeTrait(S&: Self, T: TInfo, TypeTraitID: tok::kw___is_bounded_array)) |
5222 | return false; |
5223 | return T->isArrayType() && !T->isIncompleteArrayType(); |
5224 | case UTT_IsUnboundedArray: |
5225 | if (DiagnoseVLAInCXXTypeTrait(S&: Self, T: TInfo, TypeTraitID: tok::kw___is_unbounded_array)) |
5226 | return false; |
5227 | return T->isIncompleteArrayType(); |
5228 | case UTT_IsPointer: |
5229 | return T->isAnyPointerType(); |
5230 | case UTT_IsNullPointer: |
5231 | return T->isNullPtrType(); |
5232 | case UTT_IsLvalueReference: |
5233 | return T->isLValueReferenceType(); |
5234 | case UTT_IsRvalueReference: |
5235 | return T->isRValueReferenceType(); |
5236 | case UTT_IsMemberFunctionPointer: |
5237 | return T->isMemberFunctionPointerType(); |
5238 | case UTT_IsMemberObjectPointer: |
5239 | return T->isMemberDataPointerType(); |
5240 | case UTT_IsEnum: |
5241 | return T->isEnumeralType(); |
5242 | case UTT_IsScopedEnum: |
5243 | return T->isScopedEnumeralType(); |
5244 | case UTT_IsUnion: |
5245 | return T->isUnionType(); |
5246 | case UTT_IsClass: |
5247 | return T->isClassType() || T->isStructureType() || T->isInterfaceType(); |
5248 | case UTT_IsFunction: |
5249 | return T->isFunctionType(); |
5250 | |
5251 | // Type trait expressions which correspond to the convenient composition |
5252 | // predicates in C++0x [meta.unary.comp]. |
5253 | case UTT_IsReference: |
5254 | return T->isReferenceType(); |
5255 | case UTT_IsArithmetic: |
5256 | return T->isArithmeticType() && !T->isEnumeralType(); |
5257 | case UTT_IsFundamental: |
5258 | return T->isFundamentalType(); |
5259 | case UTT_IsObject: |
5260 | return T->isObjectType(); |
5261 | case UTT_IsScalar: |
5262 | // Note: semantic analysis depends on Objective-C lifetime types to be |
5263 | // considered scalar types. However, such types do not actually behave |
5264 | // like scalar types at run time (since they may require retain/release |
5265 | // operations), so we report them as non-scalar. |
5266 | if (T->isObjCLifetimeType()) { |
5267 | switch (T.getObjCLifetime()) { |
5268 | case Qualifiers::OCL_None: |
5269 | case Qualifiers::OCL_ExplicitNone: |
5270 | return true; |
5271 | |
5272 | case Qualifiers::OCL_Strong: |
5273 | case Qualifiers::OCL_Weak: |
5274 | case Qualifiers::OCL_Autoreleasing: |
5275 | return false; |
5276 | } |
5277 | } |
5278 | |
5279 | return T->isScalarType(); |
5280 | case UTT_IsCompound: |
5281 | return T->isCompoundType(); |
5282 | case UTT_IsMemberPointer: |
5283 | return T->isMemberPointerType(); |
5284 | |
5285 | // Type trait expressions which correspond to the type property predicates |
5286 | // in C++0x [meta.unary.prop]. |
5287 | case UTT_IsConst: |
5288 | return T.isConstQualified(); |
5289 | case UTT_IsVolatile: |
5290 | return T.isVolatileQualified(); |
5291 | case UTT_IsTrivial: |
5292 | return T.isTrivialType(Context: C); |
5293 | case UTT_IsTriviallyCopyable: |
5294 | return T.isTriviallyCopyableType(Context: C); |
5295 | case UTT_IsStandardLayout: |
5296 | return T->isStandardLayoutType(); |
5297 | case UTT_IsPOD: |
5298 | return T.isPODType(Context: C); |
5299 | case UTT_IsLiteral: |
5300 | return T->isLiteralType(Ctx: C); |
5301 | case UTT_IsEmpty: |
5302 | if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) |
5303 | return !RD->isUnion() && RD->isEmpty(); |
5304 | return false; |
5305 | case UTT_IsPolymorphic: |
5306 | if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) |
5307 | return !RD->isUnion() && RD->isPolymorphic(); |
5308 | return false; |
5309 | case UTT_IsAbstract: |
5310 | if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) |
5311 | return !RD->isUnion() && RD->isAbstract(); |
5312 | return false; |
5313 | case UTT_IsAggregate: |
5314 | // Report vector extensions and complex types as aggregates because they |
5315 | // support aggregate initialization. GCC mirrors this behavior for vectors |
5316 | // but not _Complex. |
5317 | return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() || |
5318 | T->isAnyComplexType(); |
5319 | // __is_interface_class only returns true when CL is invoked in /CLR mode and |
5320 | // even then only when it is used with the 'interface struct ...' syntax |
5321 | // Clang doesn't support /CLR which makes this type trait moot. |
5322 | case UTT_IsInterfaceClass: |
5323 | return false; |
5324 | case UTT_IsFinal: |
5325 | case UTT_IsSealed: |
5326 | if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) |
5327 | return RD->hasAttr<FinalAttr>(); |
5328 | return false; |
5329 | case UTT_IsSigned: |
5330 | // Enum types should always return false. |
5331 | // Floating points should always return true. |
5332 | return T->isFloatingType() || |
5333 | (T->isSignedIntegerType() && !T->isEnumeralType()); |
5334 | case UTT_IsUnsigned: |
5335 | // Enum types should always return false. |
5336 | return T->isUnsignedIntegerType() && !T->isEnumeralType(); |
5337 | |
5338 | // Type trait expressions which query classes regarding their construction, |
5339 | // destruction, and copying. Rather than being based directly on the |
5340 | // related type predicates in the standard, they are specified by both |
5341 | // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those |
5342 | // specifications. |
5343 | // |
5344 | // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html |
5345 | // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index |
5346 | // |
5347 | // Note that these builtins do not behave as documented in g++: if a class |
5348 | // has both a trivial and a non-trivial special member of a particular kind, |
5349 | // they return false! For now, we emulate this behavior. |
5350 | // FIXME: This appears to be a g++ bug: more complex cases reveal that it |
5351 | // does not correctly compute triviality in the presence of multiple special |
5352 | // members of the same kind. Revisit this once the g++ bug is fixed. |
5353 | case UTT_HasTrivialDefaultConstructor: |
5354 | // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: |
5355 | // If __is_pod (type) is true then the trait is true, else if type is |
5356 | // a cv class or union type (or array thereof) with a trivial default |
5357 | // constructor ([class.ctor]) then the trait is true, else it is false. |
5358 | if (T.isPODType(Context: C)) |
5359 | return true; |
5360 | if (CXXRecordDecl *RD = C.getBaseElementType(QT: T)->getAsCXXRecordDecl()) |
5361 | return RD->hasTrivialDefaultConstructor() && |
5362 | !RD->hasNonTrivialDefaultConstructor(); |
5363 | return false; |
5364 | case UTT_HasTrivialMoveConstructor: |
5365 | // This trait is implemented by MSVC 2012 and needed to parse the |
5366 | // standard library headers. Specifically this is used as the logic |
5367 | // behind std::is_trivially_move_constructible (20.9.4.3). |
5368 | if (T.isPODType(Context: C)) |
5369 | return true; |
5370 | if (CXXRecordDecl *RD = C.getBaseElementType(QT: T)->getAsCXXRecordDecl()) |
5371 | return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor(); |
5372 | return false; |
5373 | case UTT_HasTrivialCopy: |
5374 | // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: |
5375 | // If __is_pod (type) is true or type is a reference type then |
5376 | // the trait is true, else if type is a cv class or union type |
5377 | // with a trivial copy constructor ([class.copy]) then the trait |
5378 | // is true, else it is false. |
5379 | if (T.isPODType(Context: C) || T->isReferenceType()) |
5380 | return true; |
5381 | if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) |
5382 | return RD->hasTrivialCopyConstructor() && |
5383 | !RD->hasNonTrivialCopyConstructor(); |
5384 | return false; |
5385 | case UTT_HasTrivialMoveAssign: |
5386 | // This trait is implemented by MSVC 2012 and needed to parse the |
5387 | // standard library headers. Specifically it is used as the logic |
5388 | // behind std::is_trivially_move_assignable (20.9.4.3) |
5389 | if (T.isPODType(Context: C)) |
5390 | return true; |
5391 | if (CXXRecordDecl *RD = C.getBaseElementType(QT: T)->getAsCXXRecordDecl()) |
5392 | return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment(); |
5393 | return false; |
5394 | case UTT_HasTrivialAssign: |
5395 | // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: |
5396 | // If type is const qualified or is a reference type then the |
5397 | // trait is false. Otherwise if __is_pod (type) is true then the |
5398 | // trait is true, else if type is a cv class or union type with |
5399 | // a trivial copy assignment ([class.copy]) then the trait is |
5400 | // true, else it is false. |
5401 | // Note: the const and reference restrictions are interesting, |
5402 | // given that const and reference members don't prevent a class |
5403 | // from having a trivial copy assignment operator (but do cause |
5404 | // errors if the copy assignment operator is actually used, q.v. |
5405 | // [class.copy]p12). |
5406 | |
5407 | if (T.isConstQualified()) |
5408 | return false; |
5409 | if (T.isPODType(Context: C)) |
5410 | return true; |
5411 | if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) |
5412 | return RD->hasTrivialCopyAssignment() && |
5413 | !RD->hasNonTrivialCopyAssignment(); |
5414 | return false; |
5415 | case UTT_IsDestructible: |
5416 | case UTT_IsTriviallyDestructible: |
5417 | case UTT_IsNothrowDestructible: |
5418 | // C++14 [meta.unary.prop]: |
5419 | // For reference types, is_destructible<T>::value is true. |
5420 | if (T->isReferenceType()) |
5421 | return true; |
5422 | |
5423 | // Objective-C++ ARC: autorelease types don't require destruction. |
5424 | if (T->isObjCLifetimeType() && |
5425 | T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) |
5426 | return true; |
5427 | |
5428 | // C++14 [meta.unary.prop]: |
5429 | // For incomplete types and function types, is_destructible<T>::value is |
5430 | // false. |
5431 | if (T->isIncompleteType() || T->isFunctionType()) |
5432 | return false; |
5433 | |
5434 | // A type that requires destruction (via a non-trivial destructor or ARC |
5435 | // lifetime semantics) is not trivially-destructible. |
5436 | if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType()) |
5437 | return false; |
5438 | |
5439 | // C++14 [meta.unary.prop]: |
5440 | // For object types and given U equal to remove_all_extents_t<T>, if the |
5441 | // expression std::declval<U&>().~U() is well-formed when treated as an |
5442 | // unevaluated operand (Clause 5), then is_destructible<T>::value is true |
5443 | if (auto *RD = C.getBaseElementType(QT: T)->getAsCXXRecordDecl()) { |
5444 | CXXDestructorDecl *Destructor = Self.LookupDestructor(Class: RD); |
5445 | if (!Destructor) |
5446 | return false; |
5447 | // C++14 [dcl.fct.def.delete]p2: |
5448 | // A program that refers to a deleted function implicitly or |
5449 | // explicitly, other than to declare it, is ill-formed. |
5450 | if (Destructor->isDeleted()) |
5451 | return false; |
5452 | if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public) |
5453 | return false; |
5454 | if (UTT == UTT_IsNothrowDestructible) { |
5455 | auto *CPT = Destructor->getType()->castAs<FunctionProtoType>(); |
5456 | CPT = Self.ResolveExceptionSpec(Loc: KeyLoc, FPT: CPT); |
5457 | if (!CPT || !CPT->isNothrow()) |
5458 | return false; |
5459 | } |
5460 | } |
5461 | return true; |
5462 | |
5463 | case UTT_HasTrivialDestructor: |
5464 | // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html |
5465 | // If __is_pod (type) is true or type is a reference type |
5466 | // then the trait is true, else if type is a cv class or union |
5467 | // type (or array thereof) with a trivial destructor |
5468 | // ([class.dtor]) then the trait is true, else it is |
5469 | // false. |
5470 | if (T.isPODType(Context: C) || T->isReferenceType()) |
5471 | return true; |
5472 | |
5473 | // Objective-C++ ARC: autorelease types don't require destruction. |
5474 | if (T->isObjCLifetimeType() && |
5475 | T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) |
5476 | return true; |
5477 | |
5478 | if (CXXRecordDecl *RD = C.getBaseElementType(QT: T)->getAsCXXRecordDecl()) |
5479 | return RD->hasTrivialDestructor(); |
5480 | return false; |
5481 | // TODO: Propagate nothrowness for implicitly declared special members. |
5482 | case UTT_HasNothrowAssign: |
5483 | // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: |
5484 | // If type is const qualified or is a reference type then the |
5485 | // trait is false. Otherwise if __has_trivial_assign (type) |
5486 | // is true then the trait is true, else if type is a cv class |
5487 | // or union type with copy assignment operators that are known |
5488 | // not to throw an exception then the trait is true, else it is |
5489 | // false. |
5490 | if (C.getBaseElementType(QT: T).isConstQualified()) |
5491 | return false; |
5492 | if (T->isReferenceType()) |
5493 | return false; |
5494 | if (T.isPODType(Context: C) || T->isObjCLifetimeType()) |
5495 | return true; |
5496 | |
5497 | if (const RecordType *RT = T->getAs<RecordType>()) |
5498 | return HasNoThrowOperator(RT, Op: OO_Equal, Self, KeyLoc, C, |
5499 | HasTrivial: &CXXRecordDecl::hasTrivialCopyAssignment, |
5500 | HasNonTrivial: &CXXRecordDecl::hasNonTrivialCopyAssignment, |
5501 | IsDesiredOp: &CXXMethodDecl::isCopyAssignmentOperator); |
5502 | return false; |
5503 | case UTT_HasNothrowMoveAssign: |
5504 | // This trait is implemented by MSVC 2012 and needed to parse the |
5505 | // standard library headers. Specifically this is used as the logic |
5506 | // behind std::is_nothrow_move_assignable (20.9.4.3). |
5507 | if (T.isPODType(Context: C)) |
5508 | return true; |
5509 | |
5510 | if (const RecordType *RT = C.getBaseElementType(QT: T)->getAs<RecordType>()) |
5511 | return HasNoThrowOperator(RT, Op: OO_Equal, Self, KeyLoc, C, |
5512 | HasTrivial: &CXXRecordDecl::hasTrivialMoveAssignment, |
5513 | HasNonTrivial: &CXXRecordDecl::hasNonTrivialMoveAssignment, |
5514 | IsDesiredOp: &CXXMethodDecl::isMoveAssignmentOperator); |
5515 | return false; |
5516 | case UTT_HasNothrowCopy: |
5517 | // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: |
5518 | // If __has_trivial_copy (type) is true then the trait is true, else |
5519 | // if type is a cv class or union type with copy constructors that are |
5520 | // known not to throw an exception then the trait is true, else it is |
5521 | // false. |
5522 | if (T.isPODType(Context: C) || T->isReferenceType() || T->isObjCLifetimeType()) |
5523 | return true; |
5524 | if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { |
5525 | if (RD->hasTrivialCopyConstructor() && |
5526 | !RD->hasNonTrivialCopyConstructor()) |
5527 | return true; |
5528 | |
5529 | bool FoundConstructor = false; |
5530 | unsigned FoundTQs; |
5531 | for (const auto *ND : Self.LookupConstructors(Class: RD)) { |
5532 | // A template constructor is never a copy constructor. |
5533 | // FIXME: However, it may actually be selected at the actual overload |
5534 | // resolution point. |
5535 | if (isa<FunctionTemplateDecl>(Val: ND->getUnderlyingDecl())) |
5536 | continue; |
5537 | // UsingDecl itself is not a constructor |
5538 | if (isa<UsingDecl>(Val: ND)) |
5539 | continue; |
5540 | auto *Constructor = cast<CXXConstructorDecl>(Val: ND->getUnderlyingDecl()); |
5541 | if (Constructor->isCopyConstructor(TypeQuals&: FoundTQs)) { |
5542 | FoundConstructor = true; |
5543 | auto *CPT = Constructor->getType()->castAs<FunctionProtoType>(); |
5544 | CPT = Self.ResolveExceptionSpec(Loc: KeyLoc, FPT: CPT); |
5545 | if (!CPT) |
5546 | return false; |
5547 | // TODO: check whether evaluating default arguments can throw. |
5548 | // For now, we'll be conservative and assume that they can throw. |
5549 | if (!CPT->isNothrow() || CPT->getNumParams() > 1) |
5550 | return false; |
5551 | } |
5552 | } |
5553 | |
5554 | return FoundConstructor; |
5555 | } |
5556 | return false; |
5557 | case UTT_HasNothrowConstructor: |
5558 | // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html |
5559 | // If __has_trivial_constructor (type) is true then the trait is |
5560 | // true, else if type is a cv class or union type (or array |
5561 | // thereof) with a default constructor that is known not to |
5562 | // throw an exception then the trait is true, else it is false. |
5563 | if (T.isPODType(Context: C) || T->isObjCLifetimeType()) |
5564 | return true; |
5565 | if (CXXRecordDecl *RD = C.getBaseElementType(QT: T)->getAsCXXRecordDecl()) { |
5566 | if (RD->hasTrivialDefaultConstructor() && |
5567 | !RD->hasNonTrivialDefaultConstructor()) |
5568 | return true; |
5569 | |
5570 | bool FoundConstructor = false; |
5571 | for (const auto *ND : Self.LookupConstructors(Class: RD)) { |
5572 | // FIXME: In C++0x, a constructor template can be a default constructor. |
5573 | if (isa<FunctionTemplateDecl>(Val: ND->getUnderlyingDecl())) |
5574 | continue; |
5575 | // UsingDecl itself is not a constructor |
5576 | if (isa<UsingDecl>(Val: ND)) |
5577 | continue; |
5578 | auto *Constructor = cast<CXXConstructorDecl>(Val: ND->getUnderlyingDecl()); |
5579 | if (Constructor->isDefaultConstructor()) { |
5580 | FoundConstructor = true; |
5581 | auto *CPT = Constructor->getType()->castAs<FunctionProtoType>(); |
5582 | CPT = Self.ResolveExceptionSpec(Loc: KeyLoc, FPT: CPT); |
5583 | if (!CPT) |
5584 | return false; |
5585 | // FIXME: check whether evaluating default arguments can throw. |
5586 | // For now, we'll be conservative and assume that they can throw. |
5587 | if (!CPT->isNothrow() || CPT->getNumParams() > 0) |
5588 | return false; |
5589 | } |
5590 | } |
5591 | return FoundConstructor; |
5592 | } |
5593 | return false; |
5594 | case UTT_HasVirtualDestructor: |
5595 | // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: |
5596 | // If type is a class type with a virtual destructor ([class.dtor]) |
5597 | // then the trait is true, else it is false. |
5598 | if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) |
5599 | if (CXXDestructorDecl *Destructor = Self.LookupDestructor(Class: RD)) |
5600 | return Destructor->isVirtual(); |
5601 | return false; |
5602 | |
5603 | // These type trait expressions are modeled on the specifications for the |
5604 | // Embarcadero C++0x type trait functions: |
5605 | // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index |
5606 | case UTT_IsCompleteType: |
5607 | // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_): |
5608 | // Returns True if and only if T is a complete type at the point of the |
5609 | // function call. |
5610 | return !T->isIncompleteType(); |
5611 | case UTT_HasUniqueObjectRepresentations: |
5612 | return C.hasUniqueObjectRepresentations(Ty: T); |
5613 | case UTT_IsTriviallyRelocatable: |
5614 | return T.isTriviallyRelocatableType(Context: C); |
5615 | case UTT_IsReferenceable: |
5616 | return T.isReferenceable(); |
5617 | case UTT_CanPassInRegs: |
5618 | if (CXXRecordDecl *RD = T->getAsCXXRecordDecl(); RD && !T.hasQualifiers()) |
5619 | return RD->canPassInRegisters(); |
5620 | Self.Diag(KeyLoc, diag::err_builtin_pass_in_regs_non_class) << T; |
5621 | return false; |
5622 | case UTT_IsTriviallyEqualityComparable: |
5623 | return T.isTriviallyEqualityComparableType(Context: C); |
5624 | } |
5625 | } |
5626 | |
5627 | static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, const TypeSourceInfo *Lhs, |
5628 | const TypeSourceInfo *Rhs, SourceLocation KeyLoc); |
5629 | |
5630 | static bool EvaluateBooleanTypeTrait(Sema &S, TypeTrait Kind, |
5631 | SourceLocation KWLoc, |
5632 | ArrayRef<TypeSourceInfo *> Args, |
5633 | SourceLocation RParenLoc, |
5634 | bool IsDependent) { |
5635 | if (IsDependent) |
5636 | return false; |
5637 | |
5638 | if (Kind <= UTT_Last) |
5639 | return EvaluateUnaryTypeTrait(Self&: S, UTT: Kind, KeyLoc: KWLoc, TInfo: Args[0]); |
5640 | |
5641 | // Evaluate ReferenceBindsToTemporary and ReferenceConstructsFromTemporary |
5642 | // alongside the IsConstructible traits to avoid duplication. |
5643 | if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary && Kind != BTT_ReferenceConstructsFromTemporary) |
5644 | return EvaluateBinaryTypeTrait(Self&: S, BTT: Kind, Lhs: Args[0], |
5645 | Rhs: Args[1], KeyLoc: RParenLoc); |
5646 | |
5647 | switch (Kind) { |
5648 | case clang::BTT_ReferenceBindsToTemporary: |
5649 | case clang::BTT_ReferenceConstructsFromTemporary: |
5650 | case clang::TT_IsConstructible: |
5651 | case clang::TT_IsNothrowConstructible: |
5652 | case clang::TT_IsTriviallyConstructible: { |
5653 | // C++11 [meta.unary.prop]: |
5654 | // is_trivially_constructible is defined as: |
5655 | // |
5656 | // is_constructible<T, Args...>::value is true and the variable |
5657 | // definition for is_constructible, as defined below, is known to call |
5658 | // no operation that is not trivial. |
5659 | // |
5660 | // The predicate condition for a template specialization |
5661 | // is_constructible<T, Args...> shall be satisfied if and only if the |
5662 | // following variable definition would be well-formed for some invented |
5663 | // variable t: |
5664 | // |
5665 | // T t(create<Args>()...); |
5666 | assert(!Args.empty()); |
5667 | |
5668 | // Precondition: T and all types in the parameter pack Args shall be |
5669 | // complete types, (possibly cv-qualified) void, or arrays of |
5670 | // unknown bound. |
5671 | for (const auto *TSI : Args) { |
5672 | QualType ArgTy = TSI->getType(); |
5673 | if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType()) |
5674 | continue; |
5675 | |
5676 | if (S.RequireCompleteType(KWLoc, ArgTy, |
5677 | diag::err_incomplete_type_used_in_type_trait_expr)) |
5678 | return false; |
5679 | } |
5680 | |
5681 | // Make sure the first argument is not incomplete nor a function type. |
5682 | QualType T = Args[0]->getType(); |
5683 | if (T->isIncompleteType() || T->isFunctionType()) |
5684 | return false; |
5685 | |
5686 | // Make sure the first argument is not an abstract type. |
5687 | CXXRecordDecl *RD = T->getAsCXXRecordDecl(); |
5688 | if (RD && RD->isAbstract()) |
5689 | return false; |
5690 | |
5691 | llvm::BumpPtrAllocator OpaqueExprAllocator; |
5692 | SmallVector<Expr *, 2> ArgExprs; |
5693 | ArgExprs.reserve(N: Args.size() - 1); |
5694 | for (unsigned I = 1, N = Args.size(); I != N; ++I) { |
5695 | QualType ArgTy = Args[I]->getType(); |
5696 | if (ArgTy->isObjectType() || ArgTy->isFunctionType()) |
5697 | ArgTy = S.Context.getRValueReferenceType(T: ArgTy); |
5698 | ArgExprs.push_back( |
5699 | new (OpaqueExprAllocator.Allocate<OpaqueValueExpr>()) |
5700 | OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(), |
5701 | ArgTy.getNonLValueExprType(Context: S.Context), |
5702 | Expr::getValueKindForType(T: ArgTy))); |
5703 | } |
5704 | |
5705 | // Perform the initialization in an unevaluated context within a SFINAE |
5706 | // trap at translation unit scope. |
5707 | EnterExpressionEvaluationContext Unevaluated( |
5708 | S, Sema::ExpressionEvaluationContext::Unevaluated); |
5709 | Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true); |
5710 | Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl()); |
5711 | InitializedEntity To( |
5712 | InitializedEntity::InitializeTemporary(Context&: S.Context, TypeInfo: Args[0])); |
5713 | InitializationKind InitKind(InitializationKind::CreateDirect(InitLoc: KWLoc, LParenLoc: KWLoc, |
5714 | RParenLoc)); |
5715 | InitializationSequence Init(S, To, InitKind, ArgExprs); |
5716 | if (Init.Failed()) |
5717 | return false; |
5718 | |
5719 | ExprResult Result = Init.Perform(S, Entity: To, Kind: InitKind, Args: ArgExprs); |
5720 | if (Result.isInvalid() || SFINAE.hasErrorOccurred()) |
5721 | return false; |
5722 | |
5723 | if (Kind == clang::TT_IsConstructible) |
5724 | return true; |
5725 | |
5726 | if (Kind == clang::BTT_ReferenceBindsToTemporary || Kind == clang::BTT_ReferenceConstructsFromTemporary) { |
5727 | if (!T->isReferenceType()) |
5728 | return false; |
5729 | |
5730 | if (!Init.isDirectReferenceBinding()) |
5731 | return true; |
5732 | |
5733 | if (Kind == clang::BTT_ReferenceBindsToTemporary) |
5734 | return false; |
5735 | |
5736 | QualType U = Args[1]->getType(); |
5737 | if (U->isReferenceType()) |
5738 | return false; |
5739 | |
5740 | TypeSourceInfo *TPtr = S.Context.CreateTypeSourceInfo(T: S.Context.getPointerType(T: S.BuiltinRemoveReference(BaseType: T, UKind: UnaryTransformType::RemoveCVRef, Loc: {}))); |
5741 | TypeSourceInfo *UPtr = S.Context.CreateTypeSourceInfo(T: S.Context.getPointerType(T: S.BuiltinRemoveReference(BaseType: U, UKind: UnaryTransformType::RemoveCVRef, Loc: {}))); |
5742 | return EvaluateBinaryTypeTrait(Self&: S, BTT: TypeTrait::BTT_IsConvertibleTo, Lhs: UPtr, Rhs: TPtr, KeyLoc: RParenLoc); |
5743 | } |
5744 | |
5745 | if (Kind == clang::TT_IsNothrowConstructible) |
5746 | return S.canThrow(Result.get()) == CT_Cannot; |
5747 | |
5748 | if (Kind == clang::TT_IsTriviallyConstructible) { |
5749 | // Under Objective-C ARC and Weak, if the destination has non-trivial |
5750 | // Objective-C lifetime, this is a non-trivial construction. |
5751 | if (T.getNonReferenceType().hasNonTrivialObjCLifetime()) |
5752 | return false; |
5753 | |
5754 | // The initialization succeeded; now make sure there are no non-trivial |
5755 | // calls. |
5756 | return !Result.get()->hasNonTrivialCall(Ctx: S.Context); |
5757 | } |
5758 | |
5759 | llvm_unreachable("unhandled type trait" ); |
5760 | return false; |
5761 | } |
5762 | default: llvm_unreachable("not a TT" ); |
5763 | } |
5764 | |
5765 | return false; |
5766 | } |
5767 | |
5768 | namespace { |
5769 | void DiagnoseBuiltinDeprecation(Sema& S, TypeTrait Kind, |
5770 | SourceLocation KWLoc) { |
5771 | TypeTrait Replacement; |
5772 | switch (Kind) { |
5773 | case UTT_HasNothrowAssign: |
5774 | case UTT_HasNothrowMoveAssign: |
5775 | Replacement = BTT_IsNothrowAssignable; |
5776 | break; |
5777 | case UTT_HasNothrowCopy: |
5778 | case UTT_HasNothrowConstructor: |
5779 | Replacement = TT_IsNothrowConstructible; |
5780 | break; |
5781 | case UTT_HasTrivialAssign: |
5782 | case UTT_HasTrivialMoveAssign: |
5783 | Replacement = BTT_IsTriviallyAssignable; |
5784 | break; |
5785 | case UTT_HasTrivialCopy: |
5786 | Replacement = UTT_IsTriviallyCopyable; |
5787 | break; |
5788 | case UTT_HasTrivialDefaultConstructor: |
5789 | case UTT_HasTrivialMoveConstructor: |
5790 | Replacement = TT_IsTriviallyConstructible; |
5791 | break; |
5792 | case UTT_HasTrivialDestructor: |
5793 | Replacement = UTT_IsTriviallyDestructible; |
5794 | break; |
5795 | default: |
5796 | return; |
5797 | } |
5798 | S.Diag(KWLoc, diag::warn_deprecated_builtin) |
5799 | << getTraitSpelling(Kind) << getTraitSpelling(Replacement); |
5800 | } |
5801 | } |
5802 | |
5803 | bool Sema::CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N) { |
5804 | if (Arity && N != Arity) { |
5805 | Diag(Loc, diag::err_type_trait_arity) |
5806 | << Arity << 0 << (Arity > 1) << (int)N << SourceRange(Loc); |
5807 | return false; |
5808 | } |
5809 | |
5810 | if (!Arity && N == 0) { |
5811 | Diag(Loc, diag::err_type_trait_arity) |
5812 | << 1 << 1 << 1 << (int)N << SourceRange(Loc); |
5813 | return false; |
5814 | } |
5815 | return true; |
5816 | } |
5817 | |
5818 | enum class TypeTraitReturnType { |
5819 | Bool, |
5820 | }; |
5821 | |
5822 | static TypeTraitReturnType GetReturnType(TypeTrait Kind) { |
5823 | return TypeTraitReturnType::Bool; |
5824 | } |
5825 | |
5826 | ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, |
5827 | ArrayRef<TypeSourceInfo *> Args, |
5828 | SourceLocation RParenLoc) { |
5829 | if (!CheckTypeTraitArity(Arity: getTypeTraitArity(T: Kind), Loc: KWLoc, N: Args.size())) |
5830 | return ExprError(); |
5831 | |
5832 | if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness( |
5833 | S&: *this, UTT: Kind, Loc: KWLoc, ArgTy: Args[0]->getType())) |
5834 | return ExprError(); |
5835 | |
5836 | DiagnoseBuiltinDeprecation(S&: *this, Kind, KWLoc); |
5837 | |
5838 | bool Dependent = false; |
5839 | for (unsigned I = 0, N = Args.size(); I != N; ++I) { |
5840 | if (Args[I]->getType()->isDependentType()) { |
5841 | Dependent = true; |
5842 | break; |
5843 | } |
5844 | } |
5845 | |
5846 | switch (GetReturnType(Kind)) { |
5847 | case TypeTraitReturnType::Bool: { |
5848 | bool Result = EvaluateBooleanTypeTrait(S&: *this, Kind, KWLoc, Args, RParenLoc, |
5849 | IsDependent: Dependent); |
5850 | return TypeTraitExpr::Create(C: Context, T: Context.getLogicalOperationType(), |
5851 | Loc: KWLoc, Kind, Args, RParenLoc, Value: Result); |
5852 | } |
5853 | } |
5854 | llvm_unreachable("unhandled type trait return type" ); |
5855 | } |
5856 | |
5857 | ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, |
5858 | ArrayRef<ParsedType> Args, |
5859 | SourceLocation RParenLoc) { |
5860 | SmallVector<TypeSourceInfo *, 4> ConvertedArgs; |
5861 | ConvertedArgs.reserve(N: Args.size()); |
5862 | |
5863 | for (unsigned I = 0, N = Args.size(); I != N; ++I) { |
5864 | TypeSourceInfo *TInfo; |
5865 | QualType T = GetTypeFromParser(Ty: Args[I], TInfo: &TInfo); |
5866 | if (!TInfo) |
5867 | TInfo = Context.getTrivialTypeSourceInfo(T, Loc: KWLoc); |
5868 | |
5869 | ConvertedArgs.push_back(Elt: TInfo); |
5870 | } |
5871 | |
5872 | return BuildTypeTrait(Kind, KWLoc, Args: ConvertedArgs, RParenLoc); |
5873 | } |
5874 | |
5875 | static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, const TypeSourceInfo *Lhs, |
5876 | const TypeSourceInfo *Rhs, SourceLocation KeyLoc) { |
5877 | QualType LhsT = Lhs->getType(); |
5878 | QualType RhsT = Rhs->getType(); |
5879 | |
5880 | assert(!LhsT->isDependentType() && !RhsT->isDependentType() && |
5881 | "Cannot evaluate traits of dependent types" ); |
5882 | |
5883 | switch(BTT) { |
5884 | case BTT_IsBaseOf: { |
5885 | // C++0x [meta.rel]p2 |
5886 | // Base is a base class of Derived without regard to cv-qualifiers or |
5887 | // Base and Derived are not unions and name the same class type without |
5888 | // regard to cv-qualifiers. |
5889 | |
5890 | const RecordType *lhsRecord = LhsT->getAs<RecordType>(); |
5891 | const RecordType *rhsRecord = RhsT->getAs<RecordType>(); |
5892 | if (!rhsRecord || !lhsRecord) { |
5893 | const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>(); |
5894 | const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>(); |
5895 | if (!LHSObjTy || !RHSObjTy) |
5896 | return false; |
5897 | |
5898 | ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface(); |
5899 | ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface(); |
5900 | if (!BaseInterface || !DerivedInterface) |
5901 | return false; |
5902 | |
5903 | if (Self.RequireCompleteType( |
5904 | Rhs->getTypeLoc().getBeginLoc(), RhsT, |
5905 | diag::err_incomplete_type_used_in_type_trait_expr)) |
5906 | return false; |
5907 | |
5908 | return BaseInterface->isSuperClassOf(I: DerivedInterface); |
5909 | } |
5910 | |
5911 | assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT) |
5912 | == (lhsRecord == rhsRecord)); |
5913 | |
5914 | // Unions are never base classes, and never have base classes. |
5915 | // It doesn't matter if they are complete or not. See PR#41843 |
5916 | if (lhsRecord && lhsRecord->getDecl()->isUnion()) |
5917 | return false; |
5918 | if (rhsRecord && rhsRecord->getDecl()->isUnion()) |
5919 | return false; |
5920 | |
5921 | if (lhsRecord == rhsRecord) |
5922 | return true; |
5923 | |
5924 | // C++0x [meta.rel]p2: |
5925 | // If Base and Derived are class types and are different types |
5926 | // (ignoring possible cv-qualifiers) then Derived shall be a |
5927 | // complete type. |
5928 | if (Self.RequireCompleteType( |
5929 | Rhs->getTypeLoc().getBeginLoc(), RhsT, |
5930 | diag::err_incomplete_type_used_in_type_trait_expr)) |
5931 | return false; |
5932 | |
5933 | return cast<CXXRecordDecl>(Val: rhsRecord->getDecl()) |
5934 | ->isDerivedFrom(Base: cast<CXXRecordDecl>(Val: lhsRecord->getDecl())); |
5935 | } |
5936 | case BTT_IsSame: |
5937 | return Self.Context.hasSameType(T1: LhsT, T2: RhsT); |
5938 | case BTT_TypeCompatible: { |
5939 | // GCC ignores cv-qualifiers on arrays for this builtin. |
5940 | Qualifiers LhsQuals, RhsQuals; |
5941 | QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(T: LhsT, Quals&: LhsQuals); |
5942 | QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(T: RhsT, Quals&: RhsQuals); |
5943 | return Self.Context.typesAreCompatible(T1: Lhs, T2: Rhs); |
5944 | } |
5945 | case BTT_IsConvertible: |
5946 | case BTT_IsConvertibleTo: |
5947 | case BTT_IsNothrowConvertible: { |
5948 | // C++0x [meta.rel]p4: |
5949 | // Given the following function prototype: |
5950 | // |
5951 | // template <class T> |
5952 | // typename add_rvalue_reference<T>::type create(); |
5953 | // |
5954 | // the predicate condition for a template specialization |
5955 | // is_convertible<From, To> shall be satisfied if and only if |
5956 | // the return expression in the following code would be |
5957 | // well-formed, including any implicit conversions to the return |
5958 | // type of the function: |
5959 | // |
5960 | // To test() { |
5961 | // return create<From>(); |
5962 | // } |
5963 | // |
5964 | // Access checking is performed as if in a context unrelated to To and |
5965 | // From. Only the validity of the immediate context of the expression |
5966 | // of the return-statement (including conversions to the return type) |
5967 | // is considered. |
5968 | // |
5969 | // We model the initialization as a copy-initialization of a temporary |
5970 | // of the appropriate type, which for this expression is identical to the |
5971 | // return statement (since NRVO doesn't apply). |
5972 | |
5973 | // Functions aren't allowed to return function or array types. |
5974 | if (RhsT->isFunctionType() || RhsT->isArrayType()) |
5975 | return false; |
5976 | |
5977 | // A return statement in a void function must have void type. |
5978 | if (RhsT->isVoidType()) |
5979 | return LhsT->isVoidType(); |
5980 | |
5981 | // A function definition requires a complete, non-abstract return type. |
5982 | if (!Self.isCompleteType(Loc: Rhs->getTypeLoc().getBeginLoc(), T: RhsT) || |
5983 | Self.isAbstractType(Loc: Rhs->getTypeLoc().getBeginLoc(), T: RhsT)) |
5984 | return false; |
5985 | |
5986 | // Compute the result of add_rvalue_reference. |
5987 | if (LhsT->isObjectType() || LhsT->isFunctionType()) |
5988 | LhsT = Self.Context.getRValueReferenceType(T: LhsT); |
5989 | |
5990 | // Build a fake source and destination for initialization. |
5991 | InitializedEntity To(InitializedEntity::InitializeTemporary(Type: RhsT)); |
5992 | OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Context: Self.Context), |
5993 | Expr::getValueKindForType(T: LhsT)); |
5994 | Expr *FromPtr = &From; |
5995 | InitializationKind Kind(InitializationKind::CreateCopy(InitLoc: KeyLoc, |
5996 | EqualLoc: SourceLocation())); |
5997 | |
5998 | // Perform the initialization in an unevaluated context within a SFINAE |
5999 | // trap at translation unit scope. |
6000 | EnterExpressionEvaluationContext Unevaluated( |
6001 | Self, Sema::ExpressionEvaluationContext::Unevaluated); |
6002 | Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true); |
6003 | Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl()); |
6004 | InitializationSequence Init(Self, To, Kind, FromPtr); |
6005 | if (Init.Failed()) |
6006 | return false; |
6007 | |
6008 | ExprResult Result = Init.Perform(S&: Self, Entity: To, Kind, Args: FromPtr); |
6009 | if (Result.isInvalid() || SFINAE.hasErrorOccurred()) |
6010 | return false; |
6011 | |
6012 | if (BTT != BTT_IsNothrowConvertible) |
6013 | return true; |
6014 | |
6015 | return Self.canThrow(Result.get()) == CT_Cannot; |
6016 | } |
6017 | |
6018 | case BTT_IsAssignable: |
6019 | case BTT_IsNothrowAssignable: |
6020 | case BTT_IsTriviallyAssignable: { |
6021 | // C++11 [meta.unary.prop]p3: |
6022 | // is_trivially_assignable is defined as: |
6023 | // is_assignable<T, U>::value is true and the assignment, as defined by |
6024 | // is_assignable, is known to call no operation that is not trivial |
6025 | // |
6026 | // is_assignable is defined as: |
6027 | // The expression declval<T>() = declval<U>() is well-formed when |
6028 | // treated as an unevaluated operand (Clause 5). |
6029 | // |
6030 | // For both, T and U shall be complete types, (possibly cv-qualified) |
6031 | // void, or arrays of unknown bound. |
6032 | if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() && |
6033 | Self.RequireCompleteType( |
6034 | Lhs->getTypeLoc().getBeginLoc(), LhsT, |
6035 | diag::err_incomplete_type_used_in_type_trait_expr)) |
6036 | return false; |
6037 | if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() && |
6038 | Self.RequireCompleteType( |
6039 | Rhs->getTypeLoc().getBeginLoc(), RhsT, |
6040 | diag::err_incomplete_type_used_in_type_trait_expr)) |
6041 | return false; |
6042 | |
6043 | // cv void is never assignable. |
6044 | if (LhsT->isVoidType() || RhsT->isVoidType()) |
6045 | return false; |
6046 | |
6047 | // Build expressions that emulate the effect of declval<T>() and |
6048 | // declval<U>(). |
6049 | if (LhsT->isObjectType() || LhsT->isFunctionType()) |
6050 | LhsT = Self.Context.getRValueReferenceType(T: LhsT); |
6051 | if (RhsT->isObjectType() || RhsT->isFunctionType()) |
6052 | RhsT = Self.Context.getRValueReferenceType(T: RhsT); |
6053 | OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Context: Self.Context), |
6054 | Expr::getValueKindForType(T: LhsT)); |
6055 | OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Context: Self.Context), |
6056 | Expr::getValueKindForType(T: RhsT)); |
6057 | |
6058 | // Attempt the assignment in an unevaluated context within a SFINAE |
6059 | // trap at translation unit scope. |
6060 | EnterExpressionEvaluationContext Unevaluated( |
6061 | Self, Sema::ExpressionEvaluationContext::Unevaluated); |
6062 | Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true); |
6063 | Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl()); |
6064 | ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs, |
6065 | &Rhs); |
6066 | if (Result.isInvalid()) |
6067 | return false; |
6068 | |
6069 | // Treat the assignment as unused for the purpose of -Wdeprecated-volatile. |
6070 | Self.CheckUnusedVolatileAssignment(E: Result.get()); |
6071 | |
6072 | if (SFINAE.hasErrorOccurred()) |
6073 | return false; |
6074 | |
6075 | if (BTT == BTT_IsAssignable) |
6076 | return true; |
6077 | |
6078 | if (BTT == BTT_IsNothrowAssignable) |
6079 | return Self.canThrow(Result.get()) == CT_Cannot; |
6080 | |
6081 | if (BTT == BTT_IsTriviallyAssignable) { |
6082 | // Under Objective-C ARC and Weak, if the destination has non-trivial |
6083 | // Objective-C lifetime, this is a non-trivial assignment. |
6084 | if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime()) |
6085 | return false; |
6086 | |
6087 | return !Result.get()->hasNonTrivialCall(Ctx: Self.Context); |
6088 | } |
6089 | |
6090 | llvm_unreachable("unhandled type trait" ); |
6091 | return false; |
6092 | } |
6093 | case BTT_IsLayoutCompatible: { |
6094 | if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType()) |
6095 | Self.RequireCompleteType(Lhs->getTypeLoc().getBeginLoc(), LhsT, |
6096 | diag::err_incomplete_type); |
6097 | if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType()) |
6098 | Self.RequireCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT, |
6099 | diag::err_incomplete_type); |
6100 | |
6101 | DiagnoseVLAInCXXTypeTrait(S&: Self, T: Lhs, TypeTraitID: tok::kw___is_layout_compatible); |
6102 | DiagnoseVLAInCXXTypeTrait(S&: Self, T: Rhs, TypeTraitID: tok::kw___is_layout_compatible); |
6103 | |
6104 | return Self.IsLayoutCompatible(T1: LhsT, T2: RhsT); |
6105 | } |
6106 | case BTT_IsPointerInterconvertibleBaseOf: { |
6107 | if (LhsT->isStructureOrClassType() && RhsT->isStructureOrClassType() && |
6108 | !Self.getASTContext().hasSameUnqualifiedType(T1: LhsT, T2: RhsT)) { |
6109 | Self.RequireCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT, |
6110 | diag::err_incomplete_type); |
6111 | } |
6112 | |
6113 | DiagnoseVLAInCXXTypeTrait(S&: Self, T: Lhs, |
6114 | TypeTraitID: tok::kw___is_pointer_interconvertible_base_of); |
6115 | DiagnoseVLAInCXXTypeTrait(S&: Self, T: Rhs, |
6116 | TypeTraitID: tok::kw___is_pointer_interconvertible_base_of); |
6117 | |
6118 | return Self.IsPointerInterconvertibleBaseOf(Base: Lhs, Derived: Rhs); |
6119 | } |
6120 | default: llvm_unreachable("not a BTT" ); |
6121 | } |
6122 | llvm_unreachable("Unknown type trait or not implemented" ); |
6123 | } |
6124 | |
6125 | ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT, |
6126 | SourceLocation KWLoc, |
6127 | ParsedType Ty, |
6128 | Expr* DimExpr, |
6129 | SourceLocation RParen) { |
6130 | TypeSourceInfo *TSInfo; |
6131 | QualType T = GetTypeFromParser(Ty, TInfo: &TSInfo); |
6132 | if (!TSInfo) |
6133 | TSInfo = Context.getTrivialTypeSourceInfo(T); |
6134 | |
6135 | return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen); |
6136 | } |
6137 | |
6138 | static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT, |
6139 | QualType T, Expr *DimExpr, |
6140 | SourceLocation KeyLoc) { |
6141 | assert(!T->isDependentType() && "Cannot evaluate traits of dependent type" ); |
6142 | |
6143 | switch(ATT) { |
6144 | case ATT_ArrayRank: |
6145 | if (T->isArrayType()) { |
6146 | unsigned Dim = 0; |
6147 | while (const ArrayType *AT = Self.Context.getAsArrayType(T)) { |
6148 | ++Dim; |
6149 | T = AT->getElementType(); |
6150 | } |
6151 | return Dim; |
6152 | } |
6153 | return 0; |
6154 | |
6155 | case ATT_ArrayExtent: { |
6156 | llvm::APSInt Value; |
6157 | uint64_t Dim; |
6158 | if (Self.VerifyIntegerConstantExpression( |
6159 | DimExpr, &Value, diag::err_dimension_expr_not_constant_integer) |
6160 | .isInvalid()) |
6161 | return 0; |
6162 | if (Value.isSigned() && Value.isNegative()) { |
6163 | Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) |
6164 | << DimExpr->getSourceRange(); |
6165 | return 0; |
6166 | } |
6167 | Dim = Value.getLimitedValue(); |
6168 | |
6169 | if (T->isArrayType()) { |
6170 | unsigned D = 0; |
6171 | bool Matched = false; |
6172 | while (const ArrayType *AT = Self.Context.getAsArrayType(T)) { |
6173 | if (Dim == D) { |
6174 | Matched = true; |
6175 | break; |
6176 | } |
6177 | ++D; |
6178 | T = AT->getElementType(); |
6179 | } |
6180 | |
6181 | if (Matched && T->isArrayType()) { |
6182 | if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T)) |
6183 | return CAT->getLimitedSize(); |
6184 | } |
6185 | } |
6186 | return 0; |
6187 | } |
6188 | } |
6189 | llvm_unreachable("Unknown type trait or not implemented" ); |
6190 | } |
6191 | |
6192 | ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT, |
6193 | SourceLocation KWLoc, |
6194 | TypeSourceInfo *TSInfo, |
6195 | Expr* DimExpr, |
6196 | SourceLocation RParen) { |
6197 | QualType T = TSInfo->getType(); |
6198 | |
6199 | // FIXME: This should likely be tracked as an APInt to remove any host |
6200 | // assumptions about the width of size_t on the target. |
6201 | uint64_t Value = 0; |
6202 | if (!T->isDependentType()) |
6203 | Value = EvaluateArrayTypeTrait(Self&: *this, ATT, T, DimExpr, KeyLoc: KWLoc); |
6204 | |
6205 | // While the specification for these traits from the Embarcadero C++ |
6206 | // compiler's documentation says the return type is 'unsigned int', Clang |
6207 | // returns 'size_t'. On Windows, the primary platform for the Embarcadero |
6208 | // compiler, there is no difference. On several other platforms this is an |
6209 | // important distinction. |
6210 | return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr, |
6211 | RParen, Context.getSizeType()); |
6212 | } |
6213 | |
6214 | ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET, |
6215 | SourceLocation KWLoc, |
6216 | Expr *Queried, |
6217 | SourceLocation RParen) { |
6218 | // If error parsing the expression, ignore. |
6219 | if (!Queried) |
6220 | return ExprError(); |
6221 | |
6222 | ExprResult Result = BuildExpressionTrait(OET: ET, KWLoc, Queried, RParen); |
6223 | |
6224 | return Result; |
6225 | } |
6226 | |
6227 | static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) { |
6228 | switch (ET) { |
6229 | case ET_IsLValueExpr: return E->isLValue(); |
6230 | case ET_IsRValueExpr: |
6231 | return E->isPRValue(); |
6232 | } |
6233 | llvm_unreachable("Expression trait not covered by switch" ); |
6234 | } |
6235 | |
6236 | ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET, |
6237 | SourceLocation KWLoc, |
6238 | Expr *Queried, |
6239 | SourceLocation RParen) { |
6240 | if (Queried->isTypeDependent()) { |
6241 | // Delay type-checking for type-dependent expressions. |
6242 | } else if (Queried->hasPlaceholderType()) { |
6243 | ExprResult PE = CheckPlaceholderExpr(E: Queried); |
6244 | if (PE.isInvalid()) return ExprError(); |
6245 | return BuildExpressionTrait(ET, KWLoc, Queried: PE.get(), RParen); |
6246 | } |
6247 | |
6248 | bool Value = EvaluateExpressionTrait(ET, E: Queried); |
6249 | |
6250 | return new (Context) |
6251 | ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy); |
6252 | } |
6253 | |
6254 | QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, |
6255 | ExprValueKind &VK, |
6256 | SourceLocation Loc, |
6257 | bool isIndirect) { |
6258 | assert(!LHS.get()->hasPlaceholderType() && !RHS.get()->hasPlaceholderType() && |
6259 | "placeholders should have been weeded out by now" ); |
6260 | |
6261 | // The LHS undergoes lvalue conversions if this is ->*, and undergoes the |
6262 | // temporary materialization conversion otherwise. |
6263 | if (isIndirect) |
6264 | LHS = DefaultLvalueConversion(E: LHS.get()); |
6265 | else if (LHS.get()->isPRValue()) |
6266 | LHS = TemporaryMaterializationConversion(E: LHS.get()); |
6267 | if (LHS.isInvalid()) |
6268 | return QualType(); |
6269 | |
6270 | // The RHS always undergoes lvalue conversions. |
6271 | RHS = DefaultLvalueConversion(E: RHS.get()); |
6272 | if (RHS.isInvalid()) return QualType(); |
6273 | |
6274 | const char *OpSpelling = isIndirect ? "->*" : ".*" ; |
6275 | // C++ 5.5p2 |
6276 | // The binary operator .* [p3: ->*] binds its second operand, which shall |
6277 | // be of type "pointer to member of T" (where T is a completely-defined |
6278 | // class type) [...] |
6279 | QualType RHSType = RHS.get()->getType(); |
6280 | const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>(); |
6281 | if (!MemPtr) { |
6282 | Diag(Loc, diag::err_bad_memptr_rhs) |
6283 | << OpSpelling << RHSType << RHS.get()->getSourceRange(); |
6284 | return QualType(); |
6285 | } |
6286 | |
6287 | QualType Class(MemPtr->getClass(), 0); |
6288 | |
6289 | // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the |
6290 | // member pointer points must be completely-defined. However, there is no |
6291 | // reason for this semantic distinction, and the rule is not enforced by |
6292 | // other compilers. Therefore, we do not check this property, as it is |
6293 | // likely to be considered a defect. |
6294 | |
6295 | // C++ 5.5p2 |
6296 | // [...] to its first operand, which shall be of class T or of a class of |
6297 | // which T is an unambiguous and accessible base class. [p3: a pointer to |
6298 | // such a class] |
6299 | QualType LHSType = LHS.get()->getType(); |
6300 | if (isIndirect) { |
6301 | if (const PointerType *Ptr = LHSType->getAs<PointerType>()) |
6302 | LHSType = Ptr->getPointeeType(); |
6303 | else { |
6304 | Diag(Loc, diag::err_bad_memptr_lhs) |
6305 | << OpSpelling << 1 << LHSType |
6306 | << FixItHint::CreateReplacement(SourceRange(Loc), ".*" ); |
6307 | return QualType(); |
6308 | } |
6309 | } |
6310 | |
6311 | if (!Context.hasSameUnqualifiedType(T1: Class, T2: LHSType)) { |
6312 | // If we want to check the hierarchy, we need a complete type. |
6313 | if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs, |
6314 | OpSpelling, (int)isIndirect)) { |
6315 | return QualType(); |
6316 | } |
6317 | |
6318 | if (!IsDerivedFrom(Loc, Derived: LHSType, Base: Class)) { |
6319 | Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling |
6320 | << (int)isIndirect << LHS.get()->getType(); |
6321 | return QualType(); |
6322 | } |
6323 | |
6324 | CXXCastPath BasePath; |
6325 | if (CheckDerivedToBaseConversion( |
6326 | Derived: LHSType, Base: Class, Loc, |
6327 | Range: SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()), |
6328 | BasePath: &BasePath)) |
6329 | return QualType(); |
6330 | |
6331 | // Cast LHS to type of use. |
6332 | QualType UseType = Context.getQualifiedType(T: Class, Qs: LHSType.getQualifiers()); |
6333 | if (isIndirect) |
6334 | UseType = Context.getPointerType(T: UseType); |
6335 | ExprValueKind VK = isIndirect ? VK_PRValue : LHS.get()->getValueKind(); |
6336 | LHS = ImpCastExprToType(E: LHS.get(), Type: UseType, CK: CK_DerivedToBase, VK, |
6337 | BasePath: &BasePath); |
6338 | } |
6339 | |
6340 | if (isa<CXXScalarValueInitExpr>(Val: RHS.get()->IgnoreParens())) { |
6341 | // Diagnose use of pointer-to-member type which when used as |
6342 | // the functional cast in a pointer-to-member expression. |
6343 | Diag(Loc, diag::err_pointer_to_member_type) << isIndirect; |
6344 | return QualType(); |
6345 | } |
6346 | |
6347 | // C++ 5.5p2 |
6348 | // The result is an object or a function of the type specified by the |
6349 | // second operand. |
6350 | // The cv qualifiers are the union of those in the pointer and the left side, |
6351 | // in accordance with 5.5p5 and 5.2.5. |
6352 | QualType Result = MemPtr->getPointeeType(); |
6353 | Result = Context.getCVRQualifiedType(T: Result, CVR: LHSType.getCVRQualifiers()); |
6354 | |
6355 | // C++0x [expr.mptr.oper]p6: |
6356 | // In a .* expression whose object expression is an rvalue, the program is |
6357 | // ill-formed if the second operand is a pointer to member function with |
6358 | // ref-qualifier &. In a ->* expression or in a .* expression whose object |
6359 | // expression is an lvalue, the program is ill-formed if the second operand |
6360 | // is a pointer to member function with ref-qualifier &&. |
6361 | if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) { |
6362 | switch (Proto->getRefQualifier()) { |
6363 | case RQ_None: |
6364 | // Do nothing |
6365 | break; |
6366 | |
6367 | case RQ_LValue: |
6368 | if (!isIndirect && !LHS.get()->Classify(Ctx&: Context).isLValue()) { |
6369 | // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq |
6370 | // is (exactly) 'const'. |
6371 | if (Proto->isConst() && !Proto->isVolatile()) |
6372 | Diag(Loc, getLangOpts().CPlusPlus20 |
6373 | ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue |
6374 | : diag::ext_pointer_to_const_ref_member_on_rvalue); |
6375 | else |
6376 | Diag(Loc, diag::err_pointer_to_member_oper_value_classify) |
6377 | << RHSType << 1 << LHS.get()->getSourceRange(); |
6378 | } |
6379 | break; |
6380 | |
6381 | case RQ_RValue: |
6382 | if (isIndirect || !LHS.get()->Classify(Context).isRValue()) |
6383 | Diag(Loc, diag::err_pointer_to_member_oper_value_classify) |
6384 | << RHSType << 0 << LHS.get()->getSourceRange(); |
6385 | break; |
6386 | } |
6387 | } |
6388 | |
6389 | // C++ [expr.mptr.oper]p6: |
6390 | // The result of a .* expression whose second operand is a pointer |
6391 | // to a data member is of the same value category as its |
6392 | // first operand. The result of a .* expression whose second |
6393 | // operand is a pointer to a member function is a prvalue. The |
6394 | // result of an ->* expression is an lvalue if its second operand |
6395 | // is a pointer to data member and a prvalue otherwise. |
6396 | if (Result->isFunctionType()) { |
6397 | VK = VK_PRValue; |
6398 | return Context.BoundMemberTy; |
6399 | } else if (isIndirect) { |
6400 | VK = VK_LValue; |
6401 | } else { |
6402 | VK = LHS.get()->getValueKind(); |
6403 | } |
6404 | |
6405 | return Result; |
6406 | } |
6407 | |
6408 | /// Try to convert a type to another according to C++11 5.16p3. |
6409 | /// |
6410 | /// This is part of the parameter validation for the ? operator. If either |
6411 | /// value operand is a class type, the two operands are attempted to be |
6412 | /// converted to each other. This function does the conversion in one direction. |
6413 | /// It returns true if the program is ill-formed and has already been diagnosed |
6414 | /// as such. |
6415 | static bool TryClassUnification(Sema &Self, Expr *From, Expr *To, |
6416 | SourceLocation QuestionLoc, |
6417 | bool &HaveConversion, |
6418 | QualType &ToType) { |
6419 | HaveConversion = false; |
6420 | ToType = To->getType(); |
6421 | |
6422 | InitializationKind Kind = |
6423 | InitializationKind::CreateCopy(InitLoc: To->getBeginLoc(), EqualLoc: SourceLocation()); |
6424 | // C++11 5.16p3 |
6425 | // The process for determining whether an operand expression E1 of type T1 |
6426 | // can be converted to match an operand expression E2 of type T2 is defined |
6427 | // as follows: |
6428 | // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be |
6429 | // implicitly converted to type "lvalue reference to T2", subject to the |
6430 | // constraint that in the conversion the reference must bind directly to |
6431 | // an lvalue. |
6432 | // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be |
6433 | // implicitly converted to the type "rvalue reference to R2", subject to |
6434 | // the constraint that the reference must bind directly. |
6435 | if (To->isGLValue()) { |
6436 | QualType T = Self.Context.getReferenceQualifiedType(e: To); |
6437 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(Type: T); |
6438 | |
6439 | InitializationSequence InitSeq(Self, Entity, Kind, From); |
6440 | if (InitSeq.isDirectReferenceBinding()) { |
6441 | ToType = T; |
6442 | HaveConversion = true; |
6443 | return false; |
6444 | } |
6445 | |
6446 | if (InitSeq.isAmbiguous()) |
6447 | return InitSeq.Diagnose(S&: Self, Entity, Kind, Args: From); |
6448 | } |
6449 | |
6450 | // -- If E2 is an rvalue, or if the conversion above cannot be done: |
6451 | // -- if E1 and E2 have class type, and the underlying class types are |
6452 | // the same or one is a base class of the other: |
6453 | QualType FTy = From->getType(); |
6454 | QualType TTy = To->getType(); |
6455 | const RecordType *FRec = FTy->getAs<RecordType>(); |
6456 | const RecordType *TRec = TTy->getAs<RecordType>(); |
6457 | bool FDerivedFromT = FRec && TRec && FRec != TRec && |
6458 | Self.IsDerivedFrom(Loc: QuestionLoc, Derived: FTy, Base: TTy); |
6459 | if (FRec && TRec && (FRec == TRec || FDerivedFromT || |
6460 | Self.IsDerivedFrom(Loc: QuestionLoc, Derived: TTy, Base: FTy))) { |
6461 | // E1 can be converted to match E2 if the class of T2 is the |
6462 | // same type as, or a base class of, the class of T1, and |
6463 | // [cv2 > cv1]. |
6464 | if (FRec == TRec || FDerivedFromT) { |
6465 | if (TTy.isAtLeastAsQualifiedAs(other: FTy)) { |
6466 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(Type: TTy); |
6467 | InitializationSequence InitSeq(Self, Entity, Kind, From); |
6468 | if (InitSeq) { |
6469 | HaveConversion = true; |
6470 | return false; |
6471 | } |
6472 | |
6473 | if (InitSeq.isAmbiguous()) |
6474 | return InitSeq.Diagnose(S&: Self, Entity, Kind, Args: From); |
6475 | } |
6476 | } |
6477 | |
6478 | return false; |
6479 | } |
6480 | |
6481 | // -- Otherwise: E1 can be converted to match E2 if E1 can be |
6482 | // implicitly converted to the type that expression E2 would have |
6483 | // if E2 were converted to an rvalue (or the type it has, if E2 is |
6484 | // an rvalue). |
6485 | // |
6486 | // This actually refers very narrowly to the lvalue-to-rvalue conversion, not |
6487 | // to the array-to-pointer or function-to-pointer conversions. |
6488 | TTy = TTy.getNonLValueExprType(Context: Self.Context); |
6489 | |
6490 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(Type: TTy); |
6491 | InitializationSequence InitSeq(Self, Entity, Kind, From); |
6492 | HaveConversion = !InitSeq.Failed(); |
6493 | ToType = TTy; |
6494 | if (InitSeq.isAmbiguous()) |
6495 | return InitSeq.Diagnose(S&: Self, Entity, Kind, Args: From); |
6496 | |
6497 | return false; |
6498 | } |
6499 | |
6500 | /// Try to find a common type for two according to C++0x 5.16p5. |
6501 | /// |
6502 | /// This is part of the parameter validation for the ? operator. If either |
6503 | /// value operand is a class type, overload resolution is used to find a |
6504 | /// conversion to a common type. |
6505 | static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS, |
6506 | SourceLocation QuestionLoc) { |
6507 | Expr *Args[2] = { LHS.get(), RHS.get() }; |
6508 | OverloadCandidateSet CandidateSet(QuestionLoc, |
6509 | OverloadCandidateSet::CSK_Operator); |
6510 | Self.AddBuiltinOperatorCandidates(Op: OO_Conditional, OpLoc: QuestionLoc, Args, |
6511 | CandidateSet); |
6512 | |
6513 | OverloadCandidateSet::iterator Best; |
6514 | switch (CandidateSet.BestViableFunction(S&: Self, Loc: QuestionLoc, Best)) { |
6515 | case OR_Success: { |
6516 | // We found a match. Perform the conversions on the arguments and move on. |
6517 | ExprResult LHSRes = Self.PerformImplicitConversion( |
6518 | LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0], |
6519 | Sema::AA_Converting); |
6520 | if (LHSRes.isInvalid()) |
6521 | break; |
6522 | LHS = LHSRes; |
6523 | |
6524 | ExprResult RHSRes = Self.PerformImplicitConversion( |
6525 | RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1], |
6526 | Sema::AA_Converting); |
6527 | if (RHSRes.isInvalid()) |
6528 | break; |
6529 | RHS = RHSRes; |
6530 | if (Best->Function) |
6531 | Self.MarkFunctionReferenced(Loc: QuestionLoc, Func: Best->Function); |
6532 | return false; |
6533 | } |
6534 | |
6535 | case OR_No_Viable_Function: |
6536 | |
6537 | // Emit a better diagnostic if one of the expressions is a null pointer |
6538 | // constant and the other is a pointer type. In this case, the user most |
6539 | // likely forgot to take the address of the other expression. |
6540 | if (Self.DiagnoseConditionalForNull(LHSExpr: LHS.get(), RHSExpr: RHS.get(), QuestionLoc)) |
6541 | return true; |
6542 | |
6543 | Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) |
6544 | << LHS.get()->getType() << RHS.get()->getType() |
6545 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
6546 | return true; |
6547 | |
6548 | case OR_Ambiguous: |
6549 | Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl) |
6550 | << LHS.get()->getType() << RHS.get()->getType() |
6551 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
6552 | // FIXME: Print the possible common types by printing the return types of |
6553 | // the viable candidates. |
6554 | break; |
6555 | |
6556 | case OR_Deleted: |
6557 | llvm_unreachable("Conditional operator has only built-in overloads" ); |
6558 | } |
6559 | return true; |
6560 | } |
6561 | |
6562 | /// Perform an "extended" implicit conversion as returned by |
6563 | /// TryClassUnification. |
6564 | static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) { |
6565 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(Type: T); |
6566 | InitializationKind Kind = |
6567 | InitializationKind::CreateCopy(InitLoc: E.get()->getBeginLoc(), EqualLoc: SourceLocation()); |
6568 | Expr *Arg = E.get(); |
6569 | InitializationSequence InitSeq(Self, Entity, Kind, Arg); |
6570 | ExprResult Result = InitSeq.Perform(S&: Self, Entity, Kind, Args: Arg); |
6571 | if (Result.isInvalid()) |
6572 | return true; |
6573 | |
6574 | E = Result; |
6575 | return false; |
6576 | } |
6577 | |
6578 | // Check the condition operand of ?: to see if it is valid for the GCC |
6579 | // extension. |
6580 | static bool isValidVectorForConditionalCondition(ASTContext &Ctx, |
6581 | QualType CondTy) { |
6582 | if (!CondTy->isVectorType() && !CondTy->isExtVectorType()) |
6583 | return false; |
6584 | const QualType EltTy = |
6585 | cast<VectorType>(Val: CondTy.getCanonicalType())->getElementType(); |
6586 | assert(!EltTy->isEnumeralType() && "Vectors cant be enum types" ); |
6587 | return EltTy->isIntegralType(Ctx); |
6588 | } |
6589 | |
6590 | static bool isValidSizelessVectorForConditionalCondition(ASTContext &Ctx, |
6591 | QualType CondTy) { |
6592 | if (!CondTy->isSveVLSBuiltinType()) |
6593 | return false; |
6594 | const QualType EltTy = |
6595 | cast<BuiltinType>(Val: CondTy.getCanonicalType())->getSveEltType(Ctx); |
6596 | assert(!EltTy->isEnumeralType() && "Vectors cant be enum types" ); |
6597 | return EltTy->isIntegralType(Ctx); |
6598 | } |
6599 | |
6600 | QualType Sema::CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, |
6601 | ExprResult &RHS, |
6602 | SourceLocation QuestionLoc) { |
6603 | LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get()); |
6604 | RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get()); |
6605 | |
6606 | QualType CondType = Cond.get()->getType(); |
6607 | const auto *CondVT = CondType->castAs<VectorType>(); |
6608 | QualType CondElementTy = CondVT->getElementType(); |
6609 | unsigned CondElementCount = CondVT->getNumElements(); |
6610 | QualType LHSType = LHS.get()->getType(); |
6611 | const auto *LHSVT = LHSType->getAs<VectorType>(); |
6612 | QualType RHSType = RHS.get()->getType(); |
6613 | const auto *RHSVT = RHSType->getAs<VectorType>(); |
6614 | |
6615 | QualType ResultType; |
6616 | |
6617 | |
6618 | if (LHSVT && RHSVT) { |
6619 | if (isa<ExtVectorType>(Val: CondVT) != isa<ExtVectorType>(Val: LHSVT)) { |
6620 | Diag(QuestionLoc, diag::err_conditional_vector_cond_result_mismatch) |
6621 | << /*isExtVector*/ isa<ExtVectorType>(CondVT); |
6622 | return {}; |
6623 | } |
6624 | |
6625 | // If both are vector types, they must be the same type. |
6626 | if (!Context.hasSameType(T1: LHSType, T2: RHSType)) { |
6627 | Diag(QuestionLoc, diag::err_conditional_vector_mismatched) |
6628 | << LHSType << RHSType; |
6629 | return {}; |
6630 | } |
6631 | ResultType = Context.getCommonSugaredType(X: LHSType, Y: RHSType); |
6632 | } else if (LHSVT || RHSVT) { |
6633 | ResultType = CheckVectorOperands( |
6634 | LHS, RHS, Loc: QuestionLoc, /*isCompAssign*/ IsCompAssign: false, /*AllowBothBool*/ true, |
6635 | /*AllowBoolConversions*/ AllowBoolConversion: false, |
6636 | /*AllowBoolOperation*/ true, |
6637 | /*ReportInvalid*/ true); |
6638 | if (ResultType.isNull()) |
6639 | return {}; |
6640 | } else { |
6641 | // Both are scalar. |
6642 | LHSType = LHSType.getUnqualifiedType(); |
6643 | RHSType = RHSType.getUnqualifiedType(); |
6644 | QualType ResultElementTy = |
6645 | Context.hasSameType(T1: LHSType, T2: RHSType) |
6646 | ? Context.getCommonSugaredType(X: LHSType, Y: RHSType) |
6647 | : UsualArithmeticConversions(LHS, RHS, Loc: QuestionLoc, |
6648 | ACK: ACK_Conditional); |
6649 | |
6650 | if (ResultElementTy->isEnumeralType()) { |
6651 | Diag(QuestionLoc, diag::err_conditional_vector_operand_type) |
6652 | << ResultElementTy; |
6653 | return {}; |
6654 | } |
6655 | if (CondType->isExtVectorType()) |
6656 | ResultType = |
6657 | Context.getExtVectorType(VectorType: ResultElementTy, NumElts: CondVT->getNumElements()); |
6658 | else |
6659 | ResultType = Context.getVectorType( |
6660 | VectorType: ResultElementTy, NumElts: CondVT->getNumElements(), VecKind: VectorKind::Generic); |
6661 | |
6662 | LHS = ImpCastExprToType(E: LHS.get(), Type: ResultType, CK: CK_VectorSplat); |
6663 | RHS = ImpCastExprToType(E: RHS.get(), Type: ResultType, CK: CK_VectorSplat); |
6664 | } |
6665 | |
6666 | assert(!ResultType.isNull() && ResultType->isVectorType() && |
6667 | (!CondType->isExtVectorType() || ResultType->isExtVectorType()) && |
6668 | "Result should have been a vector type" ); |
6669 | auto *ResultVectorTy = ResultType->castAs<VectorType>(); |
6670 | QualType ResultElementTy = ResultVectorTy->getElementType(); |
6671 | unsigned ResultElementCount = ResultVectorTy->getNumElements(); |
6672 | |
6673 | if (ResultElementCount != CondElementCount) { |
6674 | Diag(QuestionLoc, diag::err_conditional_vector_size) << CondType |
6675 | << ResultType; |
6676 | return {}; |
6677 | } |
6678 | |
6679 | if (Context.getTypeSize(T: ResultElementTy) != |
6680 | Context.getTypeSize(T: CondElementTy)) { |
6681 | Diag(QuestionLoc, diag::err_conditional_vector_element_size) << CondType |
6682 | << ResultType; |
6683 | return {}; |
6684 | } |
6685 | |
6686 | return ResultType; |
6687 | } |
6688 | |
6689 | QualType Sema::CheckSizelessVectorConditionalTypes(ExprResult &Cond, |
6690 | ExprResult &LHS, |
6691 | ExprResult &RHS, |
6692 | SourceLocation QuestionLoc) { |
6693 | LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get()); |
6694 | RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get()); |
6695 | |
6696 | QualType CondType = Cond.get()->getType(); |
6697 | const auto *CondBT = CondType->castAs<BuiltinType>(); |
6698 | QualType CondElementTy = CondBT->getSveEltType(Context); |
6699 | llvm::ElementCount CondElementCount = |
6700 | Context.getBuiltinVectorTypeInfo(VecTy: CondBT).EC; |
6701 | |
6702 | QualType LHSType = LHS.get()->getType(); |
6703 | const auto *LHSBT = |
6704 | LHSType->isSveVLSBuiltinType() ? LHSType->getAs<BuiltinType>() : nullptr; |
6705 | QualType RHSType = RHS.get()->getType(); |
6706 | const auto *RHSBT = |
6707 | RHSType->isSveVLSBuiltinType() ? RHSType->getAs<BuiltinType>() : nullptr; |
6708 | |
6709 | QualType ResultType; |
6710 | |
6711 | if (LHSBT && RHSBT) { |
6712 | // If both are sizeless vector types, they must be the same type. |
6713 | if (!Context.hasSameType(T1: LHSType, T2: RHSType)) { |
6714 | Diag(QuestionLoc, diag::err_conditional_vector_mismatched) |
6715 | << LHSType << RHSType; |
6716 | return QualType(); |
6717 | } |
6718 | ResultType = LHSType; |
6719 | } else if (LHSBT || RHSBT) { |
6720 | ResultType = CheckSizelessVectorOperands( |
6721 | LHS, RHS, Loc: QuestionLoc, /*IsCompAssign*/ false, OperationKind: ACK_Conditional); |
6722 | if (ResultType.isNull()) |
6723 | return QualType(); |
6724 | } else { |
6725 | // Both are scalar so splat |
6726 | QualType ResultElementTy; |
6727 | LHSType = LHSType.getCanonicalType().getUnqualifiedType(); |
6728 | RHSType = RHSType.getCanonicalType().getUnqualifiedType(); |
6729 | |
6730 | if (Context.hasSameType(T1: LHSType, T2: RHSType)) |
6731 | ResultElementTy = LHSType; |
6732 | else |
6733 | ResultElementTy = |
6734 | UsualArithmeticConversions(LHS, RHS, Loc: QuestionLoc, ACK: ACK_Conditional); |
6735 | |
6736 | if (ResultElementTy->isEnumeralType()) { |
6737 | Diag(QuestionLoc, diag::err_conditional_vector_operand_type) |
6738 | << ResultElementTy; |
6739 | return QualType(); |
6740 | } |
6741 | |
6742 | ResultType = Context.getScalableVectorType( |
6743 | EltTy: ResultElementTy, NumElts: CondElementCount.getKnownMinValue()); |
6744 | |
6745 | LHS = ImpCastExprToType(E: LHS.get(), Type: ResultType, CK: CK_VectorSplat); |
6746 | RHS = ImpCastExprToType(E: RHS.get(), Type: ResultType, CK: CK_VectorSplat); |
6747 | } |
6748 | |
6749 | assert(!ResultType.isNull() && ResultType->isSveVLSBuiltinType() && |
6750 | "Result should have been a vector type" ); |
6751 | auto *ResultBuiltinTy = ResultType->castAs<BuiltinType>(); |
6752 | QualType ResultElementTy = ResultBuiltinTy->getSveEltType(Context); |
6753 | llvm::ElementCount ResultElementCount = |
6754 | Context.getBuiltinVectorTypeInfo(VecTy: ResultBuiltinTy).EC; |
6755 | |
6756 | if (ResultElementCount != CondElementCount) { |
6757 | Diag(QuestionLoc, diag::err_conditional_vector_size) |
6758 | << CondType << ResultType; |
6759 | return QualType(); |
6760 | } |
6761 | |
6762 | if (Context.getTypeSize(T: ResultElementTy) != |
6763 | Context.getTypeSize(T: CondElementTy)) { |
6764 | Diag(QuestionLoc, diag::err_conditional_vector_element_size) |
6765 | << CondType << ResultType; |
6766 | return QualType(); |
6767 | } |
6768 | |
6769 | return ResultType; |
6770 | } |
6771 | |
6772 | /// Check the operands of ?: under C++ semantics. |
6773 | /// |
6774 | /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y |
6775 | /// extension. In this case, LHS == Cond. (But they're not aliases.) |
6776 | /// |
6777 | /// This function also implements GCC's vector extension and the |
6778 | /// OpenCL/ext_vector_type extension for conditionals. The vector extensions |
6779 | /// permit the use of a?b:c where the type of a is that of a integer vector with |
6780 | /// the same number of elements and size as the vectors of b and c. If one of |
6781 | /// either b or c is a scalar it is implicitly converted to match the type of |
6782 | /// the vector. Otherwise the expression is ill-formed. If both b and c are |
6783 | /// scalars, then b and c are checked and converted to the type of a if |
6784 | /// possible. |
6785 | /// |
6786 | /// The expressions are evaluated differently for GCC's and OpenCL's extensions. |
6787 | /// For the GCC extension, the ?: operator is evaluated as |
6788 | /// (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]). |
6789 | /// For the OpenCL extensions, the ?: operator is evaluated as |
6790 | /// (most-significant-bit-set(a[0]) ? b[0] : c[0], .. , |
6791 | /// most-significant-bit-set(a[n]) ? b[n] : c[n]). |
6792 | QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, |
6793 | ExprResult &RHS, ExprValueKind &VK, |
6794 | ExprObjectKind &OK, |
6795 | SourceLocation QuestionLoc) { |
6796 | // FIXME: Handle C99's complex types, block pointers and Obj-C++ interface |
6797 | // pointers. |
6798 | |
6799 | // Assume r-value. |
6800 | VK = VK_PRValue; |
6801 | OK = OK_Ordinary; |
6802 | bool IsVectorConditional = |
6803 | isValidVectorForConditionalCondition(Ctx&: Context, CondTy: Cond.get()->getType()); |
6804 | |
6805 | bool IsSizelessVectorConditional = |
6806 | isValidSizelessVectorForConditionalCondition(Ctx&: Context, |
6807 | CondTy: Cond.get()->getType()); |
6808 | |
6809 | // C++11 [expr.cond]p1 |
6810 | // The first expression is contextually converted to bool. |
6811 | if (!Cond.get()->isTypeDependent()) { |
6812 | ExprResult CondRes = IsVectorConditional || IsSizelessVectorConditional |
6813 | ? DefaultFunctionArrayLvalueConversion(E: Cond.get()) |
6814 | : CheckCXXBooleanCondition(CondExpr: Cond.get()); |
6815 | if (CondRes.isInvalid()) |
6816 | return QualType(); |
6817 | Cond = CondRes; |
6818 | } else { |
6819 | // To implement C++, the first expression typically doesn't alter the result |
6820 | // type of the conditional, however the GCC compatible vector extension |
6821 | // changes the result type to be that of the conditional. Since we cannot |
6822 | // know if this is a vector extension here, delay the conversion of the |
6823 | // LHS/RHS below until later. |
6824 | return Context.DependentTy; |
6825 | } |
6826 | |
6827 | |
6828 | // Either of the arguments dependent? |
6829 | if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent()) |
6830 | return Context.DependentTy; |
6831 | |
6832 | // C++11 [expr.cond]p2 |
6833 | // If either the second or the third operand has type (cv) void, ... |
6834 | QualType LTy = LHS.get()->getType(); |
6835 | QualType RTy = RHS.get()->getType(); |
6836 | bool LVoid = LTy->isVoidType(); |
6837 | bool RVoid = RTy->isVoidType(); |
6838 | if (LVoid || RVoid) { |
6839 | // ... one of the following shall hold: |
6840 | // -- The second or the third operand (but not both) is a (possibly |
6841 | // parenthesized) throw-expression; the result is of the type |
6842 | // and value category of the other. |
6843 | bool LThrow = isa<CXXThrowExpr>(Val: LHS.get()->IgnoreParenImpCasts()); |
6844 | bool RThrow = isa<CXXThrowExpr>(Val: RHS.get()->IgnoreParenImpCasts()); |
6845 | |
6846 | // Void expressions aren't legal in the vector-conditional expressions. |
6847 | if (IsVectorConditional) { |
6848 | SourceRange DiagLoc = |
6849 | LVoid ? LHS.get()->getSourceRange() : RHS.get()->getSourceRange(); |
6850 | bool IsThrow = LVoid ? LThrow : RThrow; |
6851 | Diag(DiagLoc.getBegin(), diag::err_conditional_vector_has_void) |
6852 | << DiagLoc << IsThrow; |
6853 | return QualType(); |
6854 | } |
6855 | |
6856 | if (LThrow != RThrow) { |
6857 | Expr *NonThrow = LThrow ? RHS.get() : LHS.get(); |
6858 | VK = NonThrow->getValueKind(); |
6859 | // DR (no number yet): the result is a bit-field if the |
6860 | // non-throw-expression operand is a bit-field. |
6861 | OK = NonThrow->getObjectKind(); |
6862 | return NonThrow->getType(); |
6863 | } |
6864 | |
6865 | // -- Both the second and third operands have type void; the result is of |
6866 | // type void and is a prvalue. |
6867 | if (LVoid && RVoid) |
6868 | return Context.getCommonSugaredType(X: LTy, Y: RTy); |
6869 | |
6870 | // Neither holds, error. |
6871 | Diag(QuestionLoc, diag::err_conditional_void_nonvoid) |
6872 | << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1) |
6873 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
6874 | return QualType(); |
6875 | } |
6876 | |
6877 | // Neither is void. |
6878 | if (IsVectorConditional) |
6879 | return CheckVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc); |
6880 | |
6881 | if (IsSizelessVectorConditional) |
6882 | return CheckSizelessVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc); |
6883 | |
6884 | // WebAssembly tables are not allowed as conditional LHS or RHS. |
6885 | if (LTy->isWebAssemblyTableType() || RTy->isWebAssemblyTableType()) { |
6886 | Diag(QuestionLoc, diag::err_wasm_table_conditional_expression) |
6887 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
6888 | return QualType(); |
6889 | } |
6890 | |
6891 | // C++11 [expr.cond]p3 |
6892 | // Otherwise, if the second and third operand have different types, and |
6893 | // either has (cv) class type [...] an attempt is made to convert each of |
6894 | // those operands to the type of the other. |
6895 | if (!Context.hasSameType(T1: LTy, T2: RTy) && |
6896 | (LTy->isRecordType() || RTy->isRecordType())) { |
6897 | // These return true if a single direction is already ambiguous. |
6898 | QualType L2RType, R2LType; |
6899 | bool HaveL2R, HaveR2L; |
6900 | if (TryClassUnification(Self&: *this, From: LHS.get(), To: RHS.get(), QuestionLoc, HaveConversion&: HaveL2R, ToType&: L2RType)) |
6901 | return QualType(); |
6902 | if (TryClassUnification(Self&: *this, From: RHS.get(), To: LHS.get(), QuestionLoc, HaveConversion&: HaveR2L, ToType&: R2LType)) |
6903 | return QualType(); |
6904 | |
6905 | // If both can be converted, [...] the program is ill-formed. |
6906 | if (HaveL2R && HaveR2L) { |
6907 | Diag(QuestionLoc, diag::err_conditional_ambiguous) |
6908 | << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
6909 | return QualType(); |
6910 | } |
6911 | |
6912 | // If exactly one conversion is possible, that conversion is applied to |
6913 | // the chosen operand and the converted operands are used in place of the |
6914 | // original operands for the remainder of this section. |
6915 | if (HaveL2R) { |
6916 | if (ConvertForConditional(Self&: *this, E&: LHS, T: L2RType) || LHS.isInvalid()) |
6917 | return QualType(); |
6918 | LTy = LHS.get()->getType(); |
6919 | } else if (HaveR2L) { |
6920 | if (ConvertForConditional(Self&: *this, E&: RHS, T: R2LType) || RHS.isInvalid()) |
6921 | return QualType(); |
6922 | RTy = RHS.get()->getType(); |
6923 | } |
6924 | } |
6925 | |
6926 | // C++11 [expr.cond]p3 |
6927 | // if both are glvalues of the same value category and the same type except |
6928 | // for cv-qualification, an attempt is made to convert each of those |
6929 | // operands to the type of the other. |
6930 | // FIXME: |
6931 | // Resolving a defect in P0012R1: we extend this to cover all cases where |
6932 | // one of the operands is reference-compatible with the other, in order |
6933 | // to support conditionals between functions differing in noexcept. This |
6934 | // will similarly cover difference in array bounds after P0388R4. |
6935 | // FIXME: If LTy and RTy have a composite pointer type, should we convert to |
6936 | // that instead? |
6937 | ExprValueKind LVK = LHS.get()->getValueKind(); |
6938 | ExprValueKind RVK = RHS.get()->getValueKind(); |
6939 | if (!Context.hasSameType(T1: LTy, T2: RTy) && LVK == RVK && LVK != VK_PRValue) { |
6940 | // DerivedToBase was already handled by the class-specific case above. |
6941 | // FIXME: Should we allow ObjC conversions here? |
6942 | const ReferenceConversions AllowedConversions = |
6943 | ReferenceConversions::Qualification | |
6944 | ReferenceConversions::NestedQualification | |
6945 | ReferenceConversions::Function; |
6946 | |
6947 | ReferenceConversions RefConv; |
6948 | if (CompareReferenceRelationship(Loc: QuestionLoc, T1: LTy, T2: RTy, Conv: &RefConv) == |
6949 | Ref_Compatible && |
6950 | !(RefConv & ~AllowedConversions) && |
6951 | // [...] subject to the constraint that the reference must bind |
6952 | // directly [...] |
6953 | !RHS.get()->refersToBitField() && !RHS.get()->refersToVectorElement()) { |
6954 | RHS = ImpCastExprToType(E: RHS.get(), Type: LTy, CK: CK_NoOp, VK: RVK); |
6955 | RTy = RHS.get()->getType(); |
6956 | } else if (CompareReferenceRelationship(Loc: QuestionLoc, T1: RTy, T2: LTy, Conv: &RefConv) == |
6957 | Ref_Compatible && |
6958 | !(RefConv & ~AllowedConversions) && |
6959 | !LHS.get()->refersToBitField() && |
6960 | !LHS.get()->refersToVectorElement()) { |
6961 | LHS = ImpCastExprToType(E: LHS.get(), Type: RTy, CK: CK_NoOp, VK: LVK); |
6962 | LTy = LHS.get()->getType(); |
6963 | } |
6964 | } |
6965 | |
6966 | // C++11 [expr.cond]p4 |
6967 | // If the second and third operands are glvalues of the same value |
6968 | // category and have the same type, the result is of that type and |
6969 | // value category and it is a bit-field if the second or the third |
6970 | // operand is a bit-field, or if both are bit-fields. |
6971 | // We only extend this to bitfields, not to the crazy other kinds of |
6972 | // l-values. |
6973 | bool Same = Context.hasSameType(T1: LTy, T2: RTy); |
6974 | if (Same && LVK == RVK && LVK != VK_PRValue && |
6975 | LHS.get()->isOrdinaryOrBitFieldObject() && |
6976 | RHS.get()->isOrdinaryOrBitFieldObject()) { |
6977 | VK = LHS.get()->getValueKind(); |
6978 | if (LHS.get()->getObjectKind() == OK_BitField || |
6979 | RHS.get()->getObjectKind() == OK_BitField) |
6980 | OK = OK_BitField; |
6981 | return Context.getCommonSugaredType(X: LTy, Y: RTy); |
6982 | } |
6983 | |
6984 | // C++11 [expr.cond]p5 |
6985 | // Otherwise, the result is a prvalue. If the second and third operands |
6986 | // do not have the same type, and either has (cv) class type, ... |
6987 | if (!Same && (LTy->isRecordType() || RTy->isRecordType())) { |
6988 | // ... overload resolution is used to determine the conversions (if any) |
6989 | // to be applied to the operands. If the overload resolution fails, the |
6990 | // program is ill-formed. |
6991 | if (FindConditionalOverload(Self&: *this, LHS, RHS, QuestionLoc)) |
6992 | return QualType(); |
6993 | } |
6994 | |
6995 | // C++11 [expr.cond]p6 |
6996 | // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard |
6997 | // conversions are performed on the second and third operands. |
6998 | LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get()); |
6999 | RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get()); |
7000 | if (LHS.isInvalid() || RHS.isInvalid()) |
7001 | return QualType(); |
7002 | LTy = LHS.get()->getType(); |
7003 | RTy = RHS.get()->getType(); |
7004 | |
7005 | // After those conversions, one of the following shall hold: |
7006 | // -- The second and third operands have the same type; the result |
7007 | // is of that type. If the operands have class type, the result |
7008 | // is a prvalue temporary of the result type, which is |
7009 | // copy-initialized from either the second operand or the third |
7010 | // operand depending on the value of the first operand. |
7011 | if (Context.hasSameType(T1: LTy, T2: RTy)) { |
7012 | if (LTy->isRecordType()) { |
7013 | // The operands have class type. Make a temporary copy. |
7014 | ExprResult LHSCopy = PerformCopyInitialization( |
7015 | Entity: InitializedEntity::InitializeTemporary(Type: LTy), EqualLoc: SourceLocation(), Init: LHS); |
7016 | if (LHSCopy.isInvalid()) |
7017 | return QualType(); |
7018 | |
7019 | ExprResult RHSCopy = PerformCopyInitialization( |
7020 | Entity: InitializedEntity::InitializeTemporary(Type: RTy), EqualLoc: SourceLocation(), Init: RHS); |
7021 | if (RHSCopy.isInvalid()) |
7022 | return QualType(); |
7023 | |
7024 | LHS = LHSCopy; |
7025 | RHS = RHSCopy; |
7026 | } |
7027 | return Context.getCommonSugaredType(X: LTy, Y: RTy); |
7028 | } |
7029 | |
7030 | // Extension: conditional operator involving vector types. |
7031 | if (LTy->isVectorType() || RTy->isVectorType()) |
7032 | return CheckVectorOperands(LHS, RHS, Loc: QuestionLoc, /*isCompAssign*/ IsCompAssign: false, |
7033 | /*AllowBothBool*/ true, |
7034 | /*AllowBoolConversions*/ AllowBoolConversion: false, |
7035 | /*AllowBoolOperation*/ false, |
7036 | /*ReportInvalid*/ true); |
7037 | |
7038 | // -- The second and third operands have arithmetic or enumeration type; |
7039 | // the usual arithmetic conversions are performed to bring them to a |
7040 | // common type, and the result is of that type. |
7041 | if (LTy->isArithmeticType() && RTy->isArithmeticType()) { |
7042 | QualType ResTy = |
7043 | UsualArithmeticConversions(LHS, RHS, Loc: QuestionLoc, ACK: ACK_Conditional); |
7044 | if (LHS.isInvalid() || RHS.isInvalid()) |
7045 | return QualType(); |
7046 | if (ResTy.isNull()) { |
7047 | Diag(QuestionLoc, |
7048 | diag::err_typecheck_cond_incompatible_operands) << LTy << RTy |
7049 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
7050 | return QualType(); |
7051 | } |
7052 | |
7053 | LHS = ImpCastExprToType(E: LHS.get(), Type: ResTy, CK: PrepareScalarCast(src&: LHS, destType: ResTy)); |
7054 | RHS = ImpCastExprToType(E: RHS.get(), Type: ResTy, CK: PrepareScalarCast(src&: RHS, destType: ResTy)); |
7055 | |
7056 | return ResTy; |
7057 | } |
7058 | |
7059 | // -- The second and third operands have pointer type, or one has pointer |
7060 | // type and the other is a null pointer constant, or both are null |
7061 | // pointer constants, at least one of which is non-integral; pointer |
7062 | // conversions and qualification conversions are performed to bring them |
7063 | // to their composite pointer type. The result is of the composite |
7064 | // pointer type. |
7065 | // -- The second and third operands have pointer to member type, or one has |
7066 | // pointer to member type and the other is a null pointer constant; |
7067 | // pointer to member conversions and qualification conversions are |
7068 | // performed to bring them to a common type, whose cv-qualification |
7069 | // shall match the cv-qualification of either the second or the third |
7070 | // operand. The result is of the common type. |
7071 | QualType Composite = FindCompositePointerType(Loc: QuestionLoc, E1&: LHS, E2&: RHS); |
7072 | if (!Composite.isNull()) |
7073 | return Composite; |
7074 | |
7075 | // Similarly, attempt to find composite type of two objective-c pointers. |
7076 | Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc); |
7077 | if (LHS.isInvalid() || RHS.isInvalid()) |
7078 | return QualType(); |
7079 | if (!Composite.isNull()) |
7080 | return Composite; |
7081 | |
7082 | // Check if we are using a null with a non-pointer type. |
7083 | if (DiagnoseConditionalForNull(LHSExpr: LHS.get(), RHSExpr: RHS.get(), QuestionLoc)) |
7084 | return QualType(); |
7085 | |
7086 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) |
7087 | << LHS.get()->getType() << RHS.get()->getType() |
7088 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
7089 | return QualType(); |
7090 | } |
7091 | |
7092 | /// Find a merged pointer type and convert the two expressions to it. |
7093 | /// |
7094 | /// This finds the composite pointer type for \p E1 and \p E2 according to |
7095 | /// C++2a [expr.type]p3. It converts both expressions to this type and returns |
7096 | /// it. It does not emit diagnostics (FIXME: that's not true if \p ConvertArgs |
7097 | /// is \c true). |
7098 | /// |
7099 | /// \param Loc The location of the operator requiring these two expressions to |
7100 | /// be converted to the composite pointer type. |
7101 | /// |
7102 | /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type. |
7103 | QualType Sema::FindCompositePointerType(SourceLocation Loc, |
7104 | Expr *&E1, Expr *&E2, |
7105 | bool ConvertArgs) { |
7106 | assert(getLangOpts().CPlusPlus && "This function assumes C++" ); |
7107 | |
7108 | // C++1z [expr]p14: |
7109 | // The composite pointer type of two operands p1 and p2 having types T1 |
7110 | // and T2 |
7111 | QualType T1 = E1->getType(), T2 = E2->getType(); |
7112 | |
7113 | // where at least one is a pointer or pointer to member type or |
7114 | // std::nullptr_t is: |
7115 | bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() || |
7116 | T1->isNullPtrType(); |
7117 | bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() || |
7118 | T2->isNullPtrType(); |
7119 | if (!T1IsPointerLike && !T2IsPointerLike) |
7120 | return QualType(); |
7121 | |
7122 | // - if both p1 and p2 are null pointer constants, std::nullptr_t; |
7123 | // This can't actually happen, following the standard, but we also use this |
7124 | // to implement the end of [expr.conv], which hits this case. |
7125 | // |
7126 | // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively; |
7127 | if (T1IsPointerLike && |
7128 | E2->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull)) { |
7129 | if (ConvertArgs) |
7130 | E2 = ImpCastExprToType(E: E2, Type: T1, CK: T1->isMemberPointerType() |
7131 | ? CK_NullToMemberPointer |
7132 | : CK_NullToPointer).get(); |
7133 | return T1; |
7134 | } |
7135 | if (T2IsPointerLike && |
7136 | E1->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull)) { |
7137 | if (ConvertArgs) |
7138 | E1 = ImpCastExprToType(E: E1, Type: T2, CK: T2->isMemberPointerType() |
7139 | ? CK_NullToMemberPointer |
7140 | : CK_NullToPointer).get(); |
7141 | return T2; |
7142 | } |
7143 | |
7144 | // Now both have to be pointers or member pointers. |
7145 | if (!T1IsPointerLike || !T2IsPointerLike) |
7146 | return QualType(); |
7147 | assert(!T1->isNullPtrType() && !T2->isNullPtrType() && |
7148 | "nullptr_t should be a null pointer constant" ); |
7149 | |
7150 | struct Step { |
7151 | enum Kind { Pointer, ObjCPointer, MemberPointer, Array } K; |
7152 | // Qualifiers to apply under the step kind. |
7153 | Qualifiers Quals; |
7154 | /// The class for a pointer-to-member; a constant array type with a bound |
7155 | /// (if any) for an array. |
7156 | const Type *ClassOrBound; |
7157 | |
7158 | Step(Kind K, const Type *ClassOrBound = nullptr) |
7159 | : K(K), ClassOrBound(ClassOrBound) {} |
7160 | QualType rebuild(ASTContext &Ctx, QualType T) const { |
7161 | T = Ctx.getQualifiedType(T, Qs: Quals); |
7162 | switch (K) { |
7163 | case Pointer: |
7164 | return Ctx.getPointerType(T); |
7165 | case MemberPointer: |
7166 | return Ctx.getMemberPointerType(T, Cls: ClassOrBound); |
7167 | case ObjCPointer: |
7168 | return Ctx.getObjCObjectPointerType(OIT: T); |
7169 | case Array: |
7170 | if (auto *CAT = cast_or_null<ConstantArrayType>(Val: ClassOrBound)) |
7171 | return Ctx.getConstantArrayType(EltTy: T, ArySize: CAT->getSize(), SizeExpr: nullptr, |
7172 | ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0); |
7173 | else |
7174 | return Ctx.getIncompleteArrayType(EltTy: T, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0); |
7175 | } |
7176 | llvm_unreachable("unknown step kind" ); |
7177 | } |
7178 | }; |
7179 | |
7180 | SmallVector<Step, 8> Steps; |
7181 | |
7182 | // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1 |
7183 | // is reference-related to C2 or C2 is reference-related to C1 (8.6.3), |
7184 | // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1, |
7185 | // respectively; |
7186 | // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer |
7187 | // to member of C2 of type cv2 U2" for some non-function type U, where |
7188 | // C1 is reference-related to C2 or C2 is reference-related to C1, the |
7189 | // cv-combined type of T2 and T1 or the cv-combined type of T1 and T2, |
7190 | // respectively; |
7191 | // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and |
7192 | // T2; |
7193 | // |
7194 | // Dismantle T1 and T2 to simultaneously determine whether they are similar |
7195 | // and to prepare to form the cv-combined type if so. |
7196 | QualType Composite1 = T1; |
7197 | QualType Composite2 = T2; |
7198 | unsigned NeedConstBefore = 0; |
7199 | while (true) { |
7200 | assert(!Composite1.isNull() && !Composite2.isNull()); |
7201 | |
7202 | Qualifiers Q1, Q2; |
7203 | Composite1 = Context.getUnqualifiedArrayType(T: Composite1, Quals&: Q1); |
7204 | Composite2 = Context.getUnqualifiedArrayType(T: Composite2, Quals&: Q2); |
7205 | |
7206 | // Top-level qualifiers are ignored. Merge at all lower levels. |
7207 | if (!Steps.empty()) { |
7208 | // Find the qualifier union: (approximately) the unique minimal set of |
7209 | // qualifiers that is compatible with both types. |
7210 | Qualifiers Quals = Qualifiers::fromCVRUMask(CVRU: Q1.getCVRUQualifiers() | |
7211 | Q2.getCVRUQualifiers()); |
7212 | |
7213 | // Under one level of pointer or pointer-to-member, we can change to an |
7214 | // unambiguous compatible address space. |
7215 | if (Q1.getAddressSpace() == Q2.getAddressSpace()) { |
7216 | Quals.setAddressSpace(Q1.getAddressSpace()); |
7217 | } else if (Steps.size() == 1) { |
7218 | bool MaybeQ1 = Q1.isAddressSpaceSupersetOf(other: Q2); |
7219 | bool MaybeQ2 = Q2.isAddressSpaceSupersetOf(other: Q1); |
7220 | if (MaybeQ1 == MaybeQ2) { |
7221 | // Exception for ptr size address spaces. Should be able to choose |
7222 | // either address space during comparison. |
7223 | if (isPtrSizeAddressSpace(AS: Q1.getAddressSpace()) || |
7224 | isPtrSizeAddressSpace(AS: Q2.getAddressSpace())) |
7225 | MaybeQ1 = true; |
7226 | else |
7227 | return QualType(); // No unique best address space. |
7228 | } |
7229 | Quals.setAddressSpace(MaybeQ1 ? Q1.getAddressSpace() |
7230 | : Q2.getAddressSpace()); |
7231 | } else { |
7232 | return QualType(); |
7233 | } |
7234 | |
7235 | // FIXME: In C, we merge __strong and none to __strong at the top level. |
7236 | if (Q1.getObjCGCAttr() == Q2.getObjCGCAttr()) |
7237 | Quals.setObjCGCAttr(Q1.getObjCGCAttr()); |
7238 | else if (T1->isVoidPointerType() || T2->isVoidPointerType()) |
7239 | assert(Steps.size() == 1); |
7240 | else |
7241 | return QualType(); |
7242 | |
7243 | // Mismatched lifetime qualifiers never compatibly include each other. |
7244 | if (Q1.getObjCLifetime() == Q2.getObjCLifetime()) |
7245 | Quals.setObjCLifetime(Q1.getObjCLifetime()); |
7246 | else if (T1->isVoidPointerType() || T2->isVoidPointerType()) |
7247 | assert(Steps.size() == 1); |
7248 | else |
7249 | return QualType(); |
7250 | |
7251 | Steps.back().Quals = Quals; |
7252 | if (Q1 != Quals || Q2 != Quals) |
7253 | NeedConstBefore = Steps.size() - 1; |
7254 | } |
7255 | |
7256 | // FIXME: Can we unify the following with UnwrapSimilarTypes? |
7257 | |
7258 | const ArrayType *Arr1, *Arr2; |
7259 | if ((Arr1 = Context.getAsArrayType(T: Composite1)) && |
7260 | (Arr2 = Context.getAsArrayType(T: Composite2))) { |
7261 | auto *CAT1 = dyn_cast<ConstantArrayType>(Val: Arr1); |
7262 | auto *CAT2 = dyn_cast<ConstantArrayType>(Val: Arr2); |
7263 | if (CAT1 && CAT2 && CAT1->getSize() == CAT2->getSize()) { |
7264 | Composite1 = Arr1->getElementType(); |
7265 | Composite2 = Arr2->getElementType(); |
7266 | Steps.emplace_back(Args: Step::Array, Args&: CAT1); |
7267 | continue; |
7268 | } |
7269 | bool IAT1 = isa<IncompleteArrayType>(Val: Arr1); |
7270 | bool IAT2 = isa<IncompleteArrayType>(Val: Arr2); |
7271 | if ((IAT1 && IAT2) || |
7272 | (getLangOpts().CPlusPlus20 && (IAT1 != IAT2) && |
7273 | ((bool)CAT1 != (bool)CAT2) && |
7274 | (Steps.empty() || Steps.back().K != Step::Array))) { |
7275 | // In C++20 onwards, we can unify an array of N T with an array of |
7276 | // a different or unknown bound. But we can't form an array whose |
7277 | // element type is an array of unknown bound by doing so. |
7278 | Composite1 = Arr1->getElementType(); |
7279 | Composite2 = Arr2->getElementType(); |
7280 | Steps.emplace_back(Args: Step::Array); |
7281 | if (CAT1 || CAT2) |
7282 | NeedConstBefore = Steps.size(); |
7283 | continue; |
7284 | } |
7285 | } |
7286 | |
7287 | const PointerType *Ptr1, *Ptr2; |
7288 | if ((Ptr1 = Composite1->getAs<PointerType>()) && |
7289 | (Ptr2 = Composite2->getAs<PointerType>())) { |
7290 | Composite1 = Ptr1->getPointeeType(); |
7291 | Composite2 = Ptr2->getPointeeType(); |
7292 | Steps.emplace_back(Args: Step::Pointer); |
7293 | continue; |
7294 | } |
7295 | |
7296 | const ObjCObjectPointerType *ObjPtr1, *ObjPtr2; |
7297 | if ((ObjPtr1 = Composite1->getAs<ObjCObjectPointerType>()) && |
7298 | (ObjPtr2 = Composite2->getAs<ObjCObjectPointerType>())) { |
7299 | Composite1 = ObjPtr1->getPointeeType(); |
7300 | Composite2 = ObjPtr2->getPointeeType(); |
7301 | Steps.emplace_back(Args: Step::ObjCPointer); |
7302 | continue; |
7303 | } |
7304 | |
7305 | const MemberPointerType *MemPtr1, *MemPtr2; |
7306 | if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) && |
7307 | (MemPtr2 = Composite2->getAs<MemberPointerType>())) { |
7308 | Composite1 = MemPtr1->getPointeeType(); |
7309 | Composite2 = MemPtr2->getPointeeType(); |
7310 | |
7311 | // At the top level, we can perform a base-to-derived pointer-to-member |
7312 | // conversion: |
7313 | // |
7314 | // - [...] where C1 is reference-related to C2 or C2 is |
7315 | // reference-related to C1 |
7316 | // |
7317 | // (Note that the only kinds of reference-relatedness in scope here are |
7318 | // "same type or derived from".) At any other level, the class must |
7319 | // exactly match. |
7320 | const Type *Class = nullptr; |
7321 | QualType Cls1(MemPtr1->getClass(), 0); |
7322 | QualType Cls2(MemPtr2->getClass(), 0); |
7323 | if (Context.hasSameType(T1: Cls1, T2: Cls2)) |
7324 | Class = MemPtr1->getClass(); |
7325 | else if (Steps.empty()) |
7326 | Class = IsDerivedFrom(Loc, Derived: Cls1, Base: Cls2) ? MemPtr1->getClass() : |
7327 | IsDerivedFrom(Loc, Derived: Cls2, Base: Cls1) ? MemPtr2->getClass() : nullptr; |
7328 | if (!Class) |
7329 | return QualType(); |
7330 | |
7331 | Steps.emplace_back(Args: Step::MemberPointer, Args&: Class); |
7332 | continue; |
7333 | } |
7334 | |
7335 | // Special case: at the top level, we can decompose an Objective-C pointer |
7336 | // and a 'cv void *'. Unify the qualifiers. |
7337 | if (Steps.empty() && ((Composite1->isVoidPointerType() && |
7338 | Composite2->isObjCObjectPointerType()) || |
7339 | (Composite1->isObjCObjectPointerType() && |
7340 | Composite2->isVoidPointerType()))) { |
7341 | Composite1 = Composite1->getPointeeType(); |
7342 | Composite2 = Composite2->getPointeeType(); |
7343 | Steps.emplace_back(Args: Step::Pointer); |
7344 | continue; |
7345 | } |
7346 | |
7347 | // FIXME: block pointer types? |
7348 | |
7349 | // Cannot unwrap any more types. |
7350 | break; |
7351 | } |
7352 | |
7353 | // - if T1 or T2 is "pointer to noexcept function" and the other type is |
7354 | // "pointer to function", where the function types are otherwise the same, |
7355 | // "pointer to function"; |
7356 | // - if T1 or T2 is "pointer to member of C1 of type function", the other |
7357 | // type is "pointer to member of C2 of type noexcept function", and C1 |
7358 | // is reference-related to C2 or C2 is reference-related to C1, where |
7359 | // the function types are otherwise the same, "pointer to member of C2 of |
7360 | // type function" or "pointer to member of C1 of type function", |
7361 | // respectively; |
7362 | // |
7363 | // We also support 'noreturn' here, so as a Clang extension we generalize the |
7364 | // above to: |
7365 | // |
7366 | // - [Clang] If T1 and T2 are both of type "pointer to function" or |
7367 | // "pointer to member function" and the pointee types can be unified |
7368 | // by a function pointer conversion, that conversion is applied |
7369 | // before checking the following rules. |
7370 | // |
7371 | // We've already unwrapped down to the function types, and we want to merge |
7372 | // rather than just convert, so do this ourselves rather than calling |
7373 | // IsFunctionConversion. |
7374 | // |
7375 | // FIXME: In order to match the standard wording as closely as possible, we |
7376 | // currently only do this under a single level of pointers. Ideally, we would |
7377 | // allow this in general, and set NeedConstBefore to the relevant depth on |
7378 | // the side(s) where we changed anything. If we permit that, we should also |
7379 | // consider this conversion when determining type similarity and model it as |
7380 | // a qualification conversion. |
7381 | if (Steps.size() == 1) { |
7382 | if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) { |
7383 | if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) { |
7384 | FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo(); |
7385 | FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo(); |
7386 | |
7387 | // The result is noreturn if both operands are. |
7388 | bool Noreturn = |
7389 | EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn(); |
7390 | EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(noReturn: Noreturn); |
7391 | EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(noReturn: Noreturn); |
7392 | |
7393 | // The result is nothrow if both operands are. |
7394 | SmallVector<QualType, 8> ExceptionTypeStorage; |
7395 | EPI1.ExceptionSpec = EPI2.ExceptionSpec = Context.mergeExceptionSpecs( |
7396 | ESI1: EPI1.ExceptionSpec, ESI2: EPI2.ExceptionSpec, ExceptionTypeStorage, |
7397 | AcceptDependent: getLangOpts().CPlusPlus17); |
7398 | |
7399 | Composite1 = Context.getFunctionType(ResultTy: FPT1->getReturnType(), |
7400 | Args: FPT1->getParamTypes(), EPI: EPI1); |
7401 | Composite2 = Context.getFunctionType(ResultTy: FPT2->getReturnType(), |
7402 | Args: FPT2->getParamTypes(), EPI: EPI2); |
7403 | } |
7404 | } |
7405 | } |
7406 | |
7407 | // There are some more conversions we can perform under exactly one pointer. |
7408 | if (Steps.size() == 1 && Steps.front().K == Step::Pointer && |
7409 | !Context.hasSameType(T1: Composite1, T2: Composite2)) { |
7410 | // - if T1 or T2 is "pointer to cv1 void" and the other type is |
7411 | // "pointer to cv2 T", where T is an object type or void, |
7412 | // "pointer to cv12 void", where cv12 is the union of cv1 and cv2; |
7413 | if (Composite1->isVoidType() && Composite2->isObjectType()) |
7414 | Composite2 = Composite1; |
7415 | else if (Composite2->isVoidType() && Composite1->isObjectType()) |
7416 | Composite1 = Composite2; |
7417 | // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1 |
7418 | // is reference-related to C2 or C2 is reference-related to C1 (8.6.3), |
7419 | // the cv-combined type of T1 and T2 or the cv-combined type of T2 and |
7420 | // T1, respectively; |
7421 | // |
7422 | // The "similar type" handling covers all of this except for the "T1 is a |
7423 | // base class of T2" case in the definition of reference-related. |
7424 | else if (IsDerivedFrom(Loc, Derived: Composite1, Base: Composite2)) |
7425 | Composite1 = Composite2; |
7426 | else if (IsDerivedFrom(Loc, Derived: Composite2, Base: Composite1)) |
7427 | Composite2 = Composite1; |
7428 | } |
7429 | |
7430 | // At this point, either the inner types are the same or we have failed to |
7431 | // find a composite pointer type. |
7432 | if (!Context.hasSameType(T1: Composite1, T2: Composite2)) |
7433 | return QualType(); |
7434 | |
7435 | // Per C++ [conv.qual]p3, add 'const' to every level before the last |
7436 | // differing qualifier. |
7437 | for (unsigned I = 0; I != NeedConstBefore; ++I) |
7438 | Steps[I].Quals.addConst(); |
7439 | |
7440 | // Rebuild the composite type. |
7441 | QualType Composite = Context.getCommonSugaredType(X: Composite1, Y: Composite2); |
7442 | for (auto &S : llvm::reverse(C&: Steps)) |
7443 | Composite = S.rebuild(Ctx&: Context, T: Composite); |
7444 | |
7445 | if (ConvertArgs) { |
7446 | // Convert the expressions to the composite pointer type. |
7447 | InitializedEntity Entity = |
7448 | InitializedEntity::InitializeTemporary(Type: Composite); |
7449 | InitializationKind Kind = |
7450 | InitializationKind::CreateCopy(InitLoc: Loc, EqualLoc: SourceLocation()); |
7451 | |
7452 | InitializationSequence E1ToC(*this, Entity, Kind, E1); |
7453 | if (!E1ToC) |
7454 | return QualType(); |
7455 | |
7456 | InitializationSequence E2ToC(*this, Entity, Kind, E2); |
7457 | if (!E2ToC) |
7458 | return QualType(); |
7459 | |
7460 | // FIXME: Let the caller know if these fail to avoid duplicate diagnostics. |
7461 | ExprResult E1Result = E1ToC.Perform(S&: *this, Entity, Kind, Args: E1); |
7462 | if (E1Result.isInvalid()) |
7463 | return QualType(); |
7464 | E1 = E1Result.get(); |
7465 | |
7466 | ExprResult E2Result = E2ToC.Perform(S&: *this, Entity, Kind, Args: E2); |
7467 | if (E2Result.isInvalid()) |
7468 | return QualType(); |
7469 | E2 = E2Result.get(); |
7470 | } |
7471 | |
7472 | return Composite; |
7473 | } |
7474 | |
7475 | ExprResult Sema::MaybeBindToTemporary(Expr *E) { |
7476 | if (!E) |
7477 | return ExprError(); |
7478 | |
7479 | assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?" ); |
7480 | |
7481 | // If the result is a glvalue, we shouldn't bind it. |
7482 | if (E->isGLValue()) |
7483 | return E; |
7484 | |
7485 | // In ARC, calls that return a retainable type can return retained, |
7486 | // in which case we have to insert a consuming cast. |
7487 | if (getLangOpts().ObjCAutoRefCount && |
7488 | E->getType()->isObjCRetainableType()) { |
7489 | |
7490 | bool ReturnsRetained; |
7491 | |
7492 | // For actual calls, we compute this by examining the type of the |
7493 | // called value. |
7494 | if (CallExpr *Call = dyn_cast<CallExpr>(Val: E)) { |
7495 | Expr *Callee = Call->getCallee()->IgnoreParens(); |
7496 | QualType T = Callee->getType(); |
7497 | |
7498 | if (T == Context.BoundMemberTy) { |
7499 | // Handle pointer-to-members. |
7500 | if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Val: Callee)) |
7501 | T = BinOp->getRHS()->getType(); |
7502 | else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Val: Callee)) |
7503 | T = Mem->getMemberDecl()->getType(); |
7504 | } |
7505 | |
7506 | if (const PointerType *Ptr = T->getAs<PointerType>()) |
7507 | T = Ptr->getPointeeType(); |
7508 | else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>()) |
7509 | T = Ptr->getPointeeType(); |
7510 | else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>()) |
7511 | T = MemPtr->getPointeeType(); |
7512 | |
7513 | auto *FTy = T->castAs<FunctionType>(); |
7514 | ReturnsRetained = FTy->getExtInfo().getProducesResult(); |
7515 | |
7516 | // ActOnStmtExpr arranges things so that StmtExprs of retainable |
7517 | // type always produce a +1 object. |
7518 | } else if (isa<StmtExpr>(Val: E)) { |
7519 | ReturnsRetained = true; |
7520 | |
7521 | // We hit this case with the lambda conversion-to-block optimization; |
7522 | // we don't want any extra casts here. |
7523 | } else if (isa<CastExpr>(Val: E) && |
7524 | isa<BlockExpr>(Val: cast<CastExpr>(Val: E)->getSubExpr())) { |
7525 | return E; |
7526 | |
7527 | // For message sends and property references, we try to find an |
7528 | // actual method. FIXME: we should infer retention by selector in |
7529 | // cases where we don't have an actual method. |
7530 | } else { |
7531 | ObjCMethodDecl *D = nullptr; |
7532 | if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(Val: E)) { |
7533 | D = Send->getMethodDecl(); |
7534 | } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(Val: E)) { |
7535 | D = BoxedExpr->getBoxingMethod(); |
7536 | } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(Val: E)) { |
7537 | // Don't do reclaims if we're using the zero-element array |
7538 | // constant. |
7539 | if (ArrayLit->getNumElements() == 0 && |
7540 | Context.getLangOpts().ObjCRuntime.hasEmptyCollections()) |
7541 | return E; |
7542 | |
7543 | D = ArrayLit->getArrayWithObjectsMethod(); |
7544 | } else if (ObjCDictionaryLiteral *DictLit |
7545 | = dyn_cast<ObjCDictionaryLiteral>(Val: E)) { |
7546 | // Don't do reclaims if we're using the zero-element dictionary |
7547 | // constant. |
7548 | if (DictLit->getNumElements() == 0 && |
7549 | Context.getLangOpts().ObjCRuntime.hasEmptyCollections()) |
7550 | return E; |
7551 | |
7552 | D = DictLit->getDictWithObjectsMethod(); |
7553 | } |
7554 | |
7555 | ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>()); |
7556 | |
7557 | // Don't do reclaims on performSelector calls; despite their |
7558 | // return type, the invoked method doesn't necessarily actually |
7559 | // return an object. |
7560 | if (!ReturnsRetained && |
7561 | D && D->getMethodFamily() == OMF_performSelector) |
7562 | return E; |
7563 | } |
7564 | |
7565 | // Don't reclaim an object of Class type. |
7566 | if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType()) |
7567 | return E; |
7568 | |
7569 | Cleanup.setExprNeedsCleanups(true); |
7570 | |
7571 | CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject |
7572 | : CK_ARCReclaimReturnedObject); |
7573 | return ImplicitCastExpr::Create(Context, T: E->getType(), Kind: ck, Operand: E, BasePath: nullptr, |
7574 | Cat: VK_PRValue, FPO: FPOptionsOverride()); |
7575 | } |
7576 | |
7577 | if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) |
7578 | Cleanup.setExprNeedsCleanups(true); |
7579 | |
7580 | if (!getLangOpts().CPlusPlus) |
7581 | return E; |
7582 | |
7583 | // Search for the base element type (cf. ASTContext::getBaseElementType) with |
7584 | // a fast path for the common case that the type is directly a RecordType. |
7585 | const Type *T = Context.getCanonicalType(T: E->getType().getTypePtr()); |
7586 | const RecordType *RT = nullptr; |
7587 | while (!RT) { |
7588 | switch (T->getTypeClass()) { |
7589 | case Type::Record: |
7590 | RT = cast<RecordType>(Val: T); |
7591 | break; |
7592 | case Type::ConstantArray: |
7593 | case Type::IncompleteArray: |
7594 | case Type::VariableArray: |
7595 | case Type::DependentSizedArray: |
7596 | T = cast<ArrayType>(Val: T)->getElementType().getTypePtr(); |
7597 | break; |
7598 | default: |
7599 | return E; |
7600 | } |
7601 | } |
7602 | |
7603 | // That should be enough to guarantee that this type is complete, if we're |
7604 | // not processing a decltype expression. |
7605 | CXXRecordDecl *RD = cast<CXXRecordDecl>(Val: RT->getDecl()); |
7606 | if (RD->isInvalidDecl() || RD->isDependentContext()) |
7607 | return E; |
7608 | |
7609 | bool IsDecltype = ExprEvalContexts.back().ExprContext == |
7610 | ExpressionEvaluationContextRecord::EK_Decltype; |
7611 | CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(Class: RD); |
7612 | |
7613 | if (Destructor) { |
7614 | MarkFunctionReferenced(E->getExprLoc(), Destructor); |
7615 | CheckDestructorAccess(E->getExprLoc(), Destructor, |
7616 | PDiag(diag::err_access_dtor_temp) |
7617 | << E->getType()); |
7618 | if (DiagnoseUseOfDecl(Destructor, E->getExprLoc())) |
7619 | return ExprError(); |
7620 | |
7621 | // If destructor is trivial, we can avoid the extra copy. |
7622 | if (Destructor->isTrivial()) |
7623 | return E; |
7624 | |
7625 | // We need a cleanup, but we don't need to remember the temporary. |
7626 | Cleanup.setExprNeedsCleanups(true); |
7627 | } |
7628 | |
7629 | CXXTemporary *Temp = CXXTemporary::Create(C: Context, Destructor); |
7630 | CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(C: Context, Temp, SubExpr: E); |
7631 | |
7632 | if (IsDecltype) |
7633 | ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Elt: Bind); |
7634 | |
7635 | return Bind; |
7636 | } |
7637 | |
7638 | ExprResult |
7639 | Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) { |
7640 | if (SubExpr.isInvalid()) |
7641 | return ExprError(); |
7642 | |
7643 | return MaybeCreateExprWithCleanups(SubExpr: SubExpr.get()); |
7644 | } |
7645 | |
7646 | Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) { |
7647 | assert(SubExpr && "subexpression can't be null!" ); |
7648 | |
7649 | CleanupVarDeclMarking(); |
7650 | |
7651 | unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects; |
7652 | assert(ExprCleanupObjects.size() >= FirstCleanup); |
7653 | assert(Cleanup.exprNeedsCleanups() || |
7654 | ExprCleanupObjects.size() == FirstCleanup); |
7655 | if (!Cleanup.exprNeedsCleanups()) |
7656 | return SubExpr; |
7657 | |
7658 | auto Cleanups = llvm::ArrayRef(ExprCleanupObjects.begin() + FirstCleanup, |
7659 | ExprCleanupObjects.size() - FirstCleanup); |
7660 | |
7661 | auto *E = ExprWithCleanups::Create( |
7662 | C: Context, subexpr: SubExpr, CleanupsHaveSideEffects: Cleanup.cleanupsHaveSideEffects(), objects: Cleanups); |
7663 | DiscardCleanupsInEvaluationContext(); |
7664 | |
7665 | return E; |
7666 | } |
7667 | |
7668 | Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) { |
7669 | assert(SubStmt && "sub-statement can't be null!" ); |
7670 | |
7671 | CleanupVarDeclMarking(); |
7672 | |
7673 | if (!Cleanup.exprNeedsCleanups()) |
7674 | return SubStmt; |
7675 | |
7676 | // FIXME: In order to attach the temporaries, wrap the statement into |
7677 | // a StmtExpr; currently this is only used for asm statements. |
7678 | // This is hacky, either create a new CXXStmtWithTemporaries statement or |
7679 | // a new AsmStmtWithTemporaries. |
7680 | CompoundStmt *CompStmt = |
7681 | CompoundStmt::Create(C: Context, Stmts: SubStmt, FPFeatures: FPOptionsOverride(), |
7682 | LB: SourceLocation(), RB: SourceLocation()); |
7683 | Expr *E = new (Context) |
7684 | StmtExpr(CompStmt, Context.VoidTy, SourceLocation(), SourceLocation(), |
7685 | /*FIXME TemplateDepth=*/0); |
7686 | return MaybeCreateExprWithCleanups(SubExpr: E); |
7687 | } |
7688 | |
7689 | /// Process the expression contained within a decltype. For such expressions, |
7690 | /// certain semantic checks on temporaries are delayed until this point, and |
7691 | /// are omitted for the 'topmost' call in the decltype expression. If the |
7692 | /// topmost call bound a temporary, strip that temporary off the expression. |
7693 | ExprResult Sema::ActOnDecltypeExpression(Expr *E) { |
7694 | assert(ExprEvalContexts.back().ExprContext == |
7695 | ExpressionEvaluationContextRecord::EK_Decltype && |
7696 | "not in a decltype expression" ); |
7697 | |
7698 | ExprResult Result = CheckPlaceholderExpr(E); |
7699 | if (Result.isInvalid()) |
7700 | return ExprError(); |
7701 | E = Result.get(); |
7702 | |
7703 | // C++11 [expr.call]p11: |
7704 | // If a function call is a prvalue of object type, |
7705 | // -- if the function call is either |
7706 | // -- the operand of a decltype-specifier, or |
7707 | // -- the right operand of a comma operator that is the operand of a |
7708 | // decltype-specifier, |
7709 | // a temporary object is not introduced for the prvalue. |
7710 | |
7711 | // Recursively rebuild ParenExprs and comma expressions to strip out the |
7712 | // outermost CXXBindTemporaryExpr, if any. |
7713 | if (ParenExpr *PE = dyn_cast<ParenExpr>(Val: E)) { |
7714 | ExprResult SubExpr = ActOnDecltypeExpression(E: PE->getSubExpr()); |
7715 | if (SubExpr.isInvalid()) |
7716 | return ExprError(); |
7717 | if (SubExpr.get() == PE->getSubExpr()) |
7718 | return E; |
7719 | return ActOnParenExpr(L: PE->getLParen(), R: PE->getRParen(), E: SubExpr.get()); |
7720 | } |
7721 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) { |
7722 | if (BO->getOpcode() == BO_Comma) { |
7723 | ExprResult RHS = ActOnDecltypeExpression(E: BO->getRHS()); |
7724 | if (RHS.isInvalid()) |
7725 | return ExprError(); |
7726 | if (RHS.get() == BO->getRHS()) |
7727 | return E; |
7728 | return BinaryOperator::Create(C: Context, lhs: BO->getLHS(), rhs: RHS.get(), opc: BO_Comma, |
7729 | ResTy: BO->getType(), VK: BO->getValueKind(), |
7730 | OK: BO->getObjectKind(), opLoc: BO->getOperatorLoc(), |
7731 | FPFeatures: BO->getFPFeatures()); |
7732 | } |
7733 | } |
7734 | |
7735 | CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(Val: E); |
7736 | CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(Val: TopBind->getSubExpr()) |
7737 | : nullptr; |
7738 | if (TopCall) |
7739 | E = TopCall; |
7740 | else |
7741 | TopBind = nullptr; |
7742 | |
7743 | // Disable the special decltype handling now. |
7744 | ExprEvalContexts.back().ExprContext = |
7745 | ExpressionEvaluationContextRecord::EK_Other; |
7746 | |
7747 | Result = CheckUnevaluatedOperand(E); |
7748 | if (Result.isInvalid()) |
7749 | return ExprError(); |
7750 | E = Result.get(); |
7751 | |
7752 | // In MS mode, don't perform any extra checking of call return types within a |
7753 | // decltype expression. |
7754 | if (getLangOpts().MSVCCompat) |
7755 | return E; |
7756 | |
7757 | // Perform the semantic checks we delayed until this point. |
7758 | for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size(); |
7759 | I != N; ++I) { |
7760 | CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I]; |
7761 | if (Call == TopCall) |
7762 | continue; |
7763 | |
7764 | if (CheckCallReturnType(ReturnType: Call->getCallReturnType(Ctx: Context), |
7765 | Loc: Call->getBeginLoc(), CE: Call, FD: Call->getDirectCallee())) |
7766 | return ExprError(); |
7767 | } |
7768 | |
7769 | // Now all relevant types are complete, check the destructors are accessible |
7770 | // and non-deleted, and annotate them on the temporaries. |
7771 | for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size(); |
7772 | I != N; ++I) { |
7773 | CXXBindTemporaryExpr *Bind = |
7774 | ExprEvalContexts.back().DelayedDecltypeBinds[I]; |
7775 | if (Bind == TopBind) |
7776 | continue; |
7777 | |
7778 | CXXTemporary *Temp = Bind->getTemporary(); |
7779 | |
7780 | CXXRecordDecl *RD = |
7781 | Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); |
7782 | CXXDestructorDecl *Destructor = LookupDestructor(Class: RD); |
7783 | Temp->setDestructor(Destructor); |
7784 | |
7785 | MarkFunctionReferenced(Loc: Bind->getExprLoc(), Func: Destructor); |
7786 | CheckDestructorAccess(Bind->getExprLoc(), Destructor, |
7787 | PDiag(diag::err_access_dtor_temp) |
7788 | << Bind->getType()); |
7789 | if (DiagnoseUseOfDecl(D: Destructor, Locs: Bind->getExprLoc())) |
7790 | return ExprError(); |
7791 | |
7792 | // We need a cleanup, but we don't need to remember the temporary. |
7793 | Cleanup.setExprNeedsCleanups(true); |
7794 | } |
7795 | |
7796 | // Possibly strip off the top CXXBindTemporaryExpr. |
7797 | return E; |
7798 | } |
7799 | |
7800 | /// Note a set of 'operator->' functions that were used for a member access. |
7801 | static void noteOperatorArrows(Sema &S, |
7802 | ArrayRef<FunctionDecl *> OperatorArrows) { |
7803 | unsigned SkipStart = OperatorArrows.size(), SkipCount = 0; |
7804 | // FIXME: Make this configurable? |
7805 | unsigned Limit = 9; |
7806 | if (OperatorArrows.size() > Limit) { |
7807 | // Produce Limit-1 normal notes and one 'skipping' note. |
7808 | SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2; |
7809 | SkipCount = OperatorArrows.size() - (Limit - 1); |
7810 | } |
7811 | |
7812 | for (unsigned I = 0; I < OperatorArrows.size(); /**/) { |
7813 | if (I == SkipStart) { |
7814 | S.Diag(OperatorArrows[I]->getLocation(), |
7815 | diag::note_operator_arrows_suppressed) |
7816 | << SkipCount; |
7817 | I += SkipCount; |
7818 | } else { |
7819 | S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here) |
7820 | << OperatorArrows[I]->getCallResultType(); |
7821 | ++I; |
7822 | } |
7823 | } |
7824 | } |
7825 | |
7826 | ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, |
7827 | SourceLocation OpLoc, |
7828 | tok::TokenKind OpKind, |
7829 | ParsedType &ObjectType, |
7830 | bool &MayBePseudoDestructor) { |
7831 | // Since this might be a postfix expression, get rid of ParenListExprs. |
7832 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: Base); |
7833 | if (Result.isInvalid()) return ExprError(); |
7834 | Base = Result.get(); |
7835 | |
7836 | Result = CheckPlaceholderExpr(E: Base); |
7837 | if (Result.isInvalid()) return ExprError(); |
7838 | Base = Result.get(); |
7839 | |
7840 | QualType BaseType = Base->getType(); |
7841 | MayBePseudoDestructor = false; |
7842 | if (BaseType->isDependentType()) { |
7843 | // If we have a pointer to a dependent type and are using the -> operator, |
7844 | // the object type is the type that the pointer points to. We might still |
7845 | // have enough information about that type to do something useful. |
7846 | if (OpKind == tok::arrow) |
7847 | if (const PointerType *Ptr = BaseType->getAs<PointerType>()) |
7848 | BaseType = Ptr->getPointeeType(); |
7849 | |
7850 | ObjectType = ParsedType::make(P: BaseType); |
7851 | MayBePseudoDestructor = true; |
7852 | return Base; |
7853 | } |
7854 | |
7855 | // C++ [over.match.oper]p8: |
7856 | // [...] When operator->returns, the operator-> is applied to the value |
7857 | // returned, with the original second operand. |
7858 | if (OpKind == tok::arrow) { |
7859 | QualType StartingType = BaseType; |
7860 | bool NoArrowOperatorFound = false; |
7861 | bool FirstIteration = true; |
7862 | FunctionDecl *CurFD = dyn_cast<FunctionDecl>(Val: CurContext); |
7863 | // The set of types we've considered so far. |
7864 | llvm::SmallPtrSet<CanQualType,8> CTypes; |
7865 | SmallVector<FunctionDecl*, 8> OperatorArrows; |
7866 | CTypes.insert(Ptr: Context.getCanonicalType(T: BaseType)); |
7867 | |
7868 | while (BaseType->isRecordType()) { |
7869 | if (OperatorArrows.size() >= getLangOpts().ArrowDepth) { |
7870 | Diag(OpLoc, diag::err_operator_arrow_depth_exceeded) |
7871 | << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange(); |
7872 | noteOperatorArrows(S&: *this, OperatorArrows); |
7873 | Diag(OpLoc, diag::note_operator_arrow_depth) |
7874 | << getLangOpts().ArrowDepth; |
7875 | return ExprError(); |
7876 | } |
7877 | |
7878 | Result = BuildOverloadedArrowExpr( |
7879 | S, Base, OpLoc, |
7880 | // When in a template specialization and on the first loop iteration, |
7881 | // potentially give the default diagnostic (with the fixit in a |
7882 | // separate note) instead of having the error reported back to here |
7883 | // and giving a diagnostic with a fixit attached to the error itself. |
7884 | NoArrowOperatorFound: (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization()) |
7885 | ? nullptr |
7886 | : &NoArrowOperatorFound); |
7887 | if (Result.isInvalid()) { |
7888 | if (NoArrowOperatorFound) { |
7889 | if (FirstIteration) { |
7890 | Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) |
7891 | << BaseType << 1 << Base->getSourceRange() |
7892 | << FixItHint::CreateReplacement(OpLoc, "." ); |
7893 | OpKind = tok::period; |
7894 | break; |
7895 | } |
7896 | Diag(OpLoc, diag::err_typecheck_member_reference_arrow) |
7897 | << BaseType << Base->getSourceRange(); |
7898 | CallExpr *CE = dyn_cast<CallExpr>(Val: Base); |
7899 | if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) { |
7900 | Diag(CD->getBeginLoc(), |
7901 | diag::note_member_reference_arrow_from_operator_arrow); |
7902 | } |
7903 | } |
7904 | return ExprError(); |
7905 | } |
7906 | Base = Result.get(); |
7907 | if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Val: Base)) |
7908 | OperatorArrows.push_back(Elt: OpCall->getDirectCallee()); |
7909 | BaseType = Base->getType(); |
7910 | CanQualType CBaseType = Context.getCanonicalType(T: BaseType); |
7911 | if (!CTypes.insert(Ptr: CBaseType).second) { |
7912 | Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType; |
7913 | noteOperatorArrows(S&: *this, OperatorArrows); |
7914 | return ExprError(); |
7915 | } |
7916 | FirstIteration = false; |
7917 | } |
7918 | |
7919 | if (OpKind == tok::arrow) { |
7920 | if (BaseType->isPointerType()) |
7921 | BaseType = BaseType->getPointeeType(); |
7922 | else if (auto *AT = Context.getAsArrayType(T: BaseType)) |
7923 | BaseType = AT->getElementType(); |
7924 | } |
7925 | } |
7926 | |
7927 | // Objective-C properties allow "." access on Objective-C pointer types, |
7928 | // so adjust the base type to the object type itself. |
7929 | if (BaseType->isObjCObjectPointerType()) |
7930 | BaseType = BaseType->getPointeeType(); |
7931 | |
7932 | // C++ [basic.lookup.classref]p2: |
7933 | // [...] If the type of the object expression is of pointer to scalar |
7934 | // type, the unqualified-id is looked up in the context of the complete |
7935 | // postfix-expression. |
7936 | // |
7937 | // This also indicates that we could be parsing a pseudo-destructor-name. |
7938 | // Note that Objective-C class and object types can be pseudo-destructor |
7939 | // expressions or normal member (ivar or property) access expressions, and |
7940 | // it's legal for the type to be incomplete if this is a pseudo-destructor |
7941 | // call. We'll do more incomplete-type checks later in the lookup process, |
7942 | // so just skip this check for ObjC types. |
7943 | if (!BaseType->isRecordType()) { |
7944 | ObjectType = ParsedType::make(P: BaseType); |
7945 | MayBePseudoDestructor = true; |
7946 | return Base; |
7947 | } |
7948 | |
7949 | // The object type must be complete (or dependent), or |
7950 | // C++11 [expr.prim.general]p3: |
7951 | // Unlike the object expression in other contexts, *this is not required to |
7952 | // be of complete type for purposes of class member access (5.2.5) outside |
7953 | // the member function body. |
7954 | if (!BaseType->isDependentType() && |
7955 | !isThisOutsideMemberFunctionBody(BaseType) && |
7956 | RequireCompleteType(OpLoc, BaseType, |
7957 | diag::err_incomplete_member_access)) { |
7958 | return CreateRecoveryExpr(Begin: Base->getBeginLoc(), End: Base->getEndLoc(), SubExprs: {Base}); |
7959 | } |
7960 | |
7961 | // C++ [basic.lookup.classref]p2: |
7962 | // If the id-expression in a class member access (5.2.5) is an |
7963 | // unqualified-id, and the type of the object expression is of a class |
7964 | // type C (or of pointer to a class type C), the unqualified-id is looked |
7965 | // up in the scope of class C. [...] |
7966 | ObjectType = ParsedType::make(P: BaseType); |
7967 | return Base; |
7968 | } |
7969 | |
7970 | static bool CheckArrow(Sema &S, QualType &ObjectType, Expr *&Base, |
7971 | tok::TokenKind &OpKind, SourceLocation OpLoc) { |
7972 | if (Base->hasPlaceholderType()) { |
7973 | ExprResult result = S.CheckPlaceholderExpr(E: Base); |
7974 | if (result.isInvalid()) return true; |
7975 | Base = result.get(); |
7976 | } |
7977 | ObjectType = Base->getType(); |
7978 | |
7979 | // C++ [expr.pseudo]p2: |
7980 | // The left-hand side of the dot operator shall be of scalar type. The |
7981 | // left-hand side of the arrow operator shall be of pointer to scalar type. |
7982 | // This scalar type is the object type. |
7983 | // Note that this is rather different from the normal handling for the |
7984 | // arrow operator. |
7985 | if (OpKind == tok::arrow) { |
7986 | // The operator requires a prvalue, so perform lvalue conversions. |
7987 | // Only do this if we might plausibly end with a pointer, as otherwise |
7988 | // this was likely to be intended to be a '.'. |
7989 | if (ObjectType->isPointerType() || ObjectType->isArrayType() || |
7990 | ObjectType->isFunctionType()) { |
7991 | ExprResult BaseResult = S.DefaultFunctionArrayLvalueConversion(E: Base); |
7992 | if (BaseResult.isInvalid()) |
7993 | return true; |
7994 | Base = BaseResult.get(); |
7995 | ObjectType = Base->getType(); |
7996 | } |
7997 | |
7998 | if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) { |
7999 | ObjectType = Ptr->getPointeeType(); |
8000 | } else if (!Base->isTypeDependent()) { |
8001 | // The user wrote "p->" when they probably meant "p."; fix it. |
8002 | S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) |
8003 | << ObjectType << true |
8004 | << FixItHint::CreateReplacement(OpLoc, "." ); |
8005 | if (S.isSFINAEContext()) |
8006 | return true; |
8007 | |
8008 | OpKind = tok::period; |
8009 | } |
8010 | } |
8011 | |
8012 | return false; |
8013 | } |
8014 | |
8015 | /// Check if it's ok to try and recover dot pseudo destructor calls on |
8016 | /// pointer objects. |
8017 | static bool |
8018 | canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef, |
8019 | QualType DestructedType) { |
8020 | // If this is a record type, check if its destructor is callable. |
8021 | if (auto *RD = DestructedType->getAsCXXRecordDecl()) { |
8022 | if (RD->hasDefinition()) |
8023 | if (CXXDestructorDecl *D = SemaRef.LookupDestructor(Class: RD)) |
8024 | return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false); |
8025 | return false; |
8026 | } |
8027 | |
8028 | // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor. |
8029 | return DestructedType->isDependentType() || DestructedType->isScalarType() || |
8030 | DestructedType->isVectorType(); |
8031 | } |
8032 | |
8033 | ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base, |
8034 | SourceLocation OpLoc, |
8035 | tok::TokenKind OpKind, |
8036 | const CXXScopeSpec &SS, |
8037 | TypeSourceInfo *ScopeTypeInfo, |
8038 | SourceLocation CCLoc, |
8039 | SourceLocation TildeLoc, |
8040 | PseudoDestructorTypeStorage Destructed) { |
8041 | TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo(); |
8042 | |
8043 | QualType ObjectType; |
8044 | if (CheckArrow(S&: *this, ObjectType, Base, OpKind, OpLoc)) |
8045 | return ExprError(); |
8046 | |
8047 | if (!ObjectType->isDependentType() && !ObjectType->isScalarType() && |
8048 | !ObjectType->isVectorType()) { |
8049 | if (getLangOpts().MSVCCompat && ObjectType->isVoidType()) |
8050 | Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange(); |
8051 | else { |
8052 | Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar) |
8053 | << ObjectType << Base->getSourceRange(); |
8054 | return ExprError(); |
8055 | } |
8056 | } |
8057 | |
8058 | // C++ [expr.pseudo]p2: |
8059 | // [...] The cv-unqualified versions of the object type and of the type |
8060 | // designated by the pseudo-destructor-name shall be the same type. |
8061 | if (DestructedTypeInfo) { |
8062 | QualType DestructedType = DestructedTypeInfo->getType(); |
8063 | SourceLocation DestructedTypeStart = |
8064 | DestructedTypeInfo->getTypeLoc().getBeginLoc(); |
8065 | if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) { |
8066 | if (!Context.hasSameUnqualifiedType(T1: DestructedType, T2: ObjectType)) { |
8067 | // Detect dot pseudo destructor calls on pointer objects, e.g.: |
8068 | // Foo *foo; |
8069 | // foo.~Foo(); |
8070 | if (OpKind == tok::period && ObjectType->isPointerType() && |
8071 | Context.hasSameUnqualifiedType(T1: DestructedType, |
8072 | T2: ObjectType->getPointeeType())) { |
8073 | auto Diagnostic = |
8074 | Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) |
8075 | << ObjectType << /*IsArrow=*/0 << Base->getSourceRange(); |
8076 | |
8077 | // Issue a fixit only when the destructor is valid. |
8078 | if (canRecoverDotPseudoDestructorCallsOnPointerObjects( |
8079 | SemaRef&: *this, DestructedType)) |
8080 | Diagnostic << FixItHint::CreateReplacement(RemoveRange: OpLoc, Code: "->" ); |
8081 | |
8082 | // Recover by setting the object type to the destructed type and the |
8083 | // operator to '->'. |
8084 | ObjectType = DestructedType; |
8085 | OpKind = tok::arrow; |
8086 | } else { |
8087 | Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch) |
8088 | << ObjectType << DestructedType << Base->getSourceRange() |
8089 | << DestructedTypeInfo->getTypeLoc().getSourceRange(); |
8090 | |
8091 | // Recover by setting the destructed type to the object type. |
8092 | DestructedType = ObjectType; |
8093 | DestructedTypeInfo = |
8094 | Context.getTrivialTypeSourceInfo(T: ObjectType, Loc: DestructedTypeStart); |
8095 | Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); |
8096 | } |
8097 | } else if (DestructedType.getObjCLifetime() != |
8098 | ObjectType.getObjCLifetime()) { |
8099 | |
8100 | if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) { |
8101 | // Okay: just pretend that the user provided the correctly-qualified |
8102 | // type. |
8103 | } else { |
8104 | Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals) |
8105 | << ObjectType << DestructedType << Base->getSourceRange() |
8106 | << DestructedTypeInfo->getTypeLoc().getSourceRange(); |
8107 | } |
8108 | |
8109 | // Recover by setting the destructed type to the object type. |
8110 | DestructedType = ObjectType; |
8111 | DestructedTypeInfo = Context.getTrivialTypeSourceInfo(T: ObjectType, |
8112 | Loc: DestructedTypeStart); |
8113 | Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); |
8114 | } |
8115 | } |
8116 | } |
8117 | |
8118 | // C++ [expr.pseudo]p2: |
8119 | // [...] Furthermore, the two type-names in a pseudo-destructor-name of the |
8120 | // form |
8121 | // |
8122 | // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name |
8123 | // |
8124 | // shall designate the same scalar type. |
8125 | if (ScopeTypeInfo) { |
8126 | QualType ScopeType = ScopeTypeInfo->getType(); |
8127 | if (!ScopeType->isDependentType() && !ObjectType->isDependentType() && |
8128 | !Context.hasSameUnqualifiedType(T1: ScopeType, T2: ObjectType)) { |
8129 | |
8130 | Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(), |
8131 | diag::err_pseudo_dtor_type_mismatch) |
8132 | << ObjectType << ScopeType << Base->getSourceRange() |
8133 | << ScopeTypeInfo->getTypeLoc().getSourceRange(); |
8134 | |
8135 | ScopeType = QualType(); |
8136 | ScopeTypeInfo = nullptr; |
8137 | } |
8138 | } |
8139 | |
8140 | Expr *Result |
8141 | = new (Context) CXXPseudoDestructorExpr(Context, Base, |
8142 | OpKind == tok::arrow, OpLoc, |
8143 | SS.getWithLocInContext(Context), |
8144 | ScopeTypeInfo, |
8145 | CCLoc, |
8146 | TildeLoc, |
8147 | Destructed); |
8148 | |
8149 | return Result; |
8150 | } |
8151 | |
8152 | ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, |
8153 | SourceLocation OpLoc, |
8154 | tok::TokenKind OpKind, |
8155 | CXXScopeSpec &SS, |
8156 | UnqualifiedId &FirstTypeName, |
8157 | SourceLocation CCLoc, |
8158 | SourceLocation TildeLoc, |
8159 | UnqualifiedId &SecondTypeName) { |
8160 | assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || |
8161 | FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && |
8162 | "Invalid first type name in pseudo-destructor" ); |
8163 | assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || |
8164 | SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && |
8165 | "Invalid second type name in pseudo-destructor" ); |
8166 | |
8167 | QualType ObjectType; |
8168 | if (CheckArrow(S&: *this, ObjectType, Base, OpKind, OpLoc)) |
8169 | return ExprError(); |
8170 | |
8171 | // Compute the object type that we should use for name lookup purposes. Only |
8172 | // record types and dependent types matter. |
8173 | ParsedType ObjectTypePtrForLookup; |
8174 | if (!SS.isSet()) { |
8175 | if (ObjectType->isRecordType()) |
8176 | ObjectTypePtrForLookup = ParsedType::make(P: ObjectType); |
8177 | else if (ObjectType->isDependentType()) |
8178 | ObjectTypePtrForLookup = ParsedType::make(P: Context.DependentTy); |
8179 | } |
8180 | |
8181 | // Convert the name of the type being destructed (following the ~) into a |
8182 | // type (with source-location information). |
8183 | QualType DestructedType; |
8184 | TypeSourceInfo *DestructedTypeInfo = nullptr; |
8185 | PseudoDestructorTypeStorage Destructed; |
8186 | if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) { |
8187 | ParsedType T = getTypeName(II: *SecondTypeName.Identifier, |
8188 | NameLoc: SecondTypeName.StartLocation, |
8189 | S, SS: &SS, isClassName: true, HasTrailingDot: false, ObjectType: ObjectTypePtrForLookup, |
8190 | /*IsCtorOrDtorName*/true); |
8191 | if (!T && |
8192 | ((SS.isSet() && !computeDeclContext(SS, EnteringContext: false)) || |
8193 | (!SS.isSet() && ObjectType->isDependentType()))) { |
8194 | // The name of the type being destroyed is a dependent name, and we |
8195 | // couldn't find anything useful in scope. Just store the identifier and |
8196 | // it's location, and we'll perform (qualified) name lookup again at |
8197 | // template instantiation time. |
8198 | Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier, |
8199 | SecondTypeName.StartLocation); |
8200 | } else if (!T) { |
8201 | Diag(SecondTypeName.StartLocation, |
8202 | diag::err_pseudo_dtor_destructor_non_type) |
8203 | << SecondTypeName.Identifier << ObjectType; |
8204 | if (isSFINAEContext()) |
8205 | return ExprError(); |
8206 | |
8207 | // Recover by assuming we had the right type all along. |
8208 | DestructedType = ObjectType; |
8209 | } else |
8210 | DestructedType = GetTypeFromParser(Ty: T, TInfo: &DestructedTypeInfo); |
8211 | } else { |
8212 | // Resolve the template-id to a type. |
8213 | TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId; |
8214 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), |
8215 | TemplateId->NumArgs); |
8216 | TypeResult T = ActOnTemplateIdType(S, |
8217 | SS, |
8218 | TemplateKWLoc: TemplateId->TemplateKWLoc, |
8219 | Template: TemplateId->Template, |
8220 | TemplateII: TemplateId->Name, |
8221 | TemplateIILoc: TemplateId->TemplateNameLoc, |
8222 | LAngleLoc: TemplateId->LAngleLoc, |
8223 | TemplateArgs: TemplateArgsPtr, |
8224 | RAngleLoc: TemplateId->RAngleLoc, |
8225 | /*IsCtorOrDtorName*/true); |
8226 | if (T.isInvalid() || !T.get()) { |
8227 | // Recover by assuming we had the right type all along. |
8228 | DestructedType = ObjectType; |
8229 | } else |
8230 | DestructedType = GetTypeFromParser(Ty: T.get(), TInfo: &DestructedTypeInfo); |
8231 | } |
8232 | |
8233 | // If we've performed some kind of recovery, (re-)build the type source |
8234 | // information. |
8235 | if (!DestructedType.isNull()) { |
8236 | if (!DestructedTypeInfo) |
8237 | DestructedTypeInfo = Context.getTrivialTypeSourceInfo(T: DestructedType, |
8238 | Loc: SecondTypeName.StartLocation); |
8239 | Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); |
8240 | } |
8241 | |
8242 | // Convert the name of the scope type (the type prior to '::') into a type. |
8243 | TypeSourceInfo *ScopeTypeInfo = nullptr; |
8244 | QualType ScopeType; |
8245 | if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || |
8246 | FirstTypeName.Identifier) { |
8247 | if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) { |
8248 | ParsedType T = getTypeName(II: *FirstTypeName.Identifier, |
8249 | NameLoc: FirstTypeName.StartLocation, |
8250 | S, SS: &SS, isClassName: true, HasTrailingDot: false, ObjectType: ObjectTypePtrForLookup, |
8251 | /*IsCtorOrDtorName*/true); |
8252 | if (!T) { |
8253 | Diag(FirstTypeName.StartLocation, |
8254 | diag::err_pseudo_dtor_destructor_non_type) |
8255 | << FirstTypeName.Identifier << ObjectType; |
8256 | |
8257 | if (isSFINAEContext()) |
8258 | return ExprError(); |
8259 | |
8260 | // Just drop this type. It's unnecessary anyway. |
8261 | ScopeType = QualType(); |
8262 | } else |
8263 | ScopeType = GetTypeFromParser(Ty: T, TInfo: &ScopeTypeInfo); |
8264 | } else { |
8265 | // Resolve the template-id to a type. |
8266 | TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId; |
8267 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), |
8268 | TemplateId->NumArgs); |
8269 | TypeResult T = ActOnTemplateIdType(S, |
8270 | SS, |
8271 | TemplateKWLoc: TemplateId->TemplateKWLoc, |
8272 | Template: TemplateId->Template, |
8273 | TemplateII: TemplateId->Name, |
8274 | TemplateIILoc: TemplateId->TemplateNameLoc, |
8275 | LAngleLoc: TemplateId->LAngleLoc, |
8276 | TemplateArgs: TemplateArgsPtr, |
8277 | RAngleLoc: TemplateId->RAngleLoc, |
8278 | /*IsCtorOrDtorName*/true); |
8279 | if (T.isInvalid() || !T.get()) { |
8280 | // Recover by dropping this type. |
8281 | ScopeType = QualType(); |
8282 | } else |
8283 | ScopeType = GetTypeFromParser(Ty: T.get(), TInfo: &ScopeTypeInfo); |
8284 | } |
8285 | } |
8286 | |
8287 | if (!ScopeType.isNull() && !ScopeTypeInfo) |
8288 | ScopeTypeInfo = Context.getTrivialTypeSourceInfo(T: ScopeType, |
8289 | Loc: FirstTypeName.StartLocation); |
8290 | |
8291 | |
8292 | return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS, |
8293 | ScopeTypeInfo, CCLoc, TildeLoc, |
8294 | Destructed); |
8295 | } |
8296 | |
8297 | ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, |
8298 | SourceLocation OpLoc, |
8299 | tok::TokenKind OpKind, |
8300 | SourceLocation TildeLoc, |
8301 | const DeclSpec& DS) { |
8302 | QualType ObjectType; |
8303 | QualType T; |
8304 | TypeLocBuilder TLB; |
8305 | if (CheckArrow(S&: *this, ObjectType, Base, OpKind, OpLoc)) |
8306 | return ExprError(); |
8307 | |
8308 | switch (DS.getTypeSpecType()) { |
8309 | case DeclSpec::TST_decltype_auto: { |
8310 | Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); |
8311 | return true; |
8312 | } |
8313 | case DeclSpec::TST_decltype: { |
8314 | T = BuildDecltypeType(E: DS.getRepAsExpr(), /*AsUnevaluated=*/false); |
8315 | DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T); |
8316 | DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc()); |
8317 | DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd()); |
8318 | break; |
8319 | } |
8320 | case DeclSpec::TST_typename_pack_indexing: { |
8321 | T = ActOnPackIndexingType(Pattern: DS.getRepAsType().get(), IndexExpr: DS.getPackIndexingExpr(), |
8322 | Loc: DS.getBeginLoc(), EllipsisLoc: DS.getEllipsisLoc()); |
8323 | TLB.pushTrivial(Context&: getASTContext(), |
8324 | T: cast<PackIndexingType>(Val: T.getTypePtr())->getPattern(), |
8325 | Loc: DS.getBeginLoc()); |
8326 | PackIndexingTypeLoc PITL = TLB.push<PackIndexingTypeLoc>(T); |
8327 | PITL.setEllipsisLoc(DS.getEllipsisLoc()); |
8328 | break; |
8329 | } |
8330 | default: |
8331 | llvm_unreachable("Unsupported type in pseudo destructor" ); |
8332 | } |
8333 | TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T); |
8334 | PseudoDestructorTypeStorage Destructed(DestructedTypeInfo); |
8335 | |
8336 | return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS: CXXScopeSpec(), |
8337 | ScopeTypeInfo: nullptr, CCLoc: SourceLocation(), TildeLoc, |
8338 | Destructed); |
8339 | } |
8340 | |
8341 | ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, |
8342 | SourceLocation RParen) { |
8343 | // If the operand is an unresolved lookup expression, the expression is ill- |
8344 | // formed per [over.over]p1, because overloaded function names cannot be used |
8345 | // without arguments except in explicit contexts. |
8346 | ExprResult R = CheckPlaceholderExpr(E: Operand); |
8347 | if (R.isInvalid()) |
8348 | return R; |
8349 | |
8350 | R = CheckUnevaluatedOperand(E: R.get()); |
8351 | if (R.isInvalid()) |
8352 | return ExprError(); |
8353 | |
8354 | Operand = R.get(); |
8355 | |
8356 | if (!inTemplateInstantiation() && !Operand->isInstantiationDependent() && |
8357 | Operand->HasSideEffects(Ctx: Context, IncludePossibleEffects: false)) { |
8358 | // The expression operand for noexcept is in an unevaluated expression |
8359 | // context, so side effects could result in unintended consequences. |
8360 | Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context); |
8361 | } |
8362 | |
8363 | CanThrowResult CanThrow = canThrow(Operand); |
8364 | return new (Context) |
8365 | CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen); |
8366 | } |
8367 | |
8368 | ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation, |
8369 | Expr *Operand, SourceLocation RParen) { |
8370 | return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen); |
8371 | } |
8372 | |
8373 | static void MaybeDecrementCount( |
8374 | Expr *E, llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { |
8375 | DeclRefExpr *LHS = nullptr; |
8376 | bool IsCompoundAssign = false; |
8377 | bool isIncrementDecrementUnaryOp = false; |
8378 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) { |
8379 | if (BO->getLHS()->getType()->isDependentType() || |
8380 | BO->getRHS()->getType()->isDependentType()) { |
8381 | if (BO->getOpcode() != BO_Assign) |
8382 | return; |
8383 | } else if (!BO->isAssignmentOp()) |
8384 | return; |
8385 | else |
8386 | IsCompoundAssign = BO->isCompoundAssignmentOp(); |
8387 | LHS = dyn_cast<DeclRefExpr>(Val: BO->getLHS()); |
8388 | } else if (CXXOperatorCallExpr *COCE = dyn_cast<CXXOperatorCallExpr>(Val: E)) { |
8389 | if (COCE->getOperator() != OO_Equal) |
8390 | return; |
8391 | LHS = dyn_cast<DeclRefExpr>(COCE->getArg(0)); |
8392 | } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: E)) { |
8393 | if (!UO->isIncrementDecrementOp()) |
8394 | return; |
8395 | isIncrementDecrementUnaryOp = true; |
8396 | LHS = dyn_cast<DeclRefExpr>(Val: UO->getSubExpr()); |
8397 | } |
8398 | if (!LHS) |
8399 | return; |
8400 | VarDecl *VD = dyn_cast<VarDecl>(Val: LHS->getDecl()); |
8401 | if (!VD) |
8402 | return; |
8403 | // Don't decrement RefsMinusAssignments if volatile variable with compound |
8404 | // assignment (+=, ...) or increment/decrement unary operator to avoid |
8405 | // potential unused-but-set-variable warning. |
8406 | if ((IsCompoundAssign || isIncrementDecrementUnaryOp) && |
8407 | VD->getType().isVolatileQualified()) |
8408 | return; |
8409 | auto iter = RefsMinusAssignments.find(Val: VD); |
8410 | if (iter == RefsMinusAssignments.end()) |
8411 | return; |
8412 | iter->getSecond()--; |
8413 | } |
8414 | |
8415 | /// Perform the conversions required for an expression used in a |
8416 | /// context that ignores the result. |
8417 | ExprResult Sema::IgnoredValueConversions(Expr *E) { |
8418 | MaybeDecrementCount(E, RefsMinusAssignments); |
8419 | |
8420 | if (E->hasPlaceholderType()) { |
8421 | ExprResult result = CheckPlaceholderExpr(E); |
8422 | if (result.isInvalid()) return E; |
8423 | E = result.get(); |
8424 | } |
8425 | |
8426 | if (getLangOpts().CPlusPlus) { |
8427 | // The C++11 standard defines the notion of a discarded-value expression; |
8428 | // normally, we don't need to do anything to handle it, but if it is a |
8429 | // volatile lvalue with a special form, we perform an lvalue-to-rvalue |
8430 | // conversion. |
8431 | if (getLangOpts().CPlusPlus11 && E->isReadIfDiscardedInCPlusPlus11()) { |
8432 | ExprResult Res = DefaultLvalueConversion(E); |
8433 | if (Res.isInvalid()) |
8434 | return E; |
8435 | E = Res.get(); |
8436 | } else { |
8437 | // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if |
8438 | // it occurs as a discarded-value expression. |
8439 | CheckUnusedVolatileAssignment(E); |
8440 | } |
8441 | |
8442 | // C++1z: |
8443 | // If the expression is a prvalue after this optional conversion, the |
8444 | // temporary materialization conversion is applied. |
8445 | // |
8446 | // We do not materialize temporaries by default in order to avoid creating |
8447 | // unnecessary temporary objects. If we skip this step, IR generation is |
8448 | // able to synthesize the storage for itself in the aggregate case, and |
8449 | // adding the extra node to the AST is just clutter. |
8450 | if (isInLifetimeExtendingContext() && getLangOpts().CPlusPlus17 && |
8451 | E->isPRValue() && !E->getType()->isVoidType()) { |
8452 | ExprResult Res = TemporaryMaterializationConversion(E); |
8453 | if (Res.isInvalid()) |
8454 | return E; |
8455 | E = Res.get(); |
8456 | } |
8457 | return E; |
8458 | } |
8459 | |
8460 | // C99 6.3.2.1: |
8461 | // [Except in specific positions,] an lvalue that does not have |
8462 | // array type is converted to the value stored in the |
8463 | // designated object (and is no longer an lvalue). |
8464 | if (E->isPRValue()) { |
8465 | // In C, function designators (i.e. expressions of function type) |
8466 | // are r-values, but we still want to do function-to-pointer decay |
8467 | // on them. This is both technically correct and convenient for |
8468 | // some clients. |
8469 | if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType()) |
8470 | return DefaultFunctionArrayConversion(E); |
8471 | |
8472 | return E; |
8473 | } |
8474 | |
8475 | // GCC seems to also exclude expressions of incomplete enum type. |
8476 | if (const EnumType *T = E->getType()->getAs<EnumType>()) { |
8477 | if (!T->getDecl()->isComplete()) { |
8478 | // FIXME: stupid workaround for a codegen bug! |
8479 | E = ImpCastExprToType(E, Type: Context.VoidTy, CK: CK_ToVoid).get(); |
8480 | return E; |
8481 | } |
8482 | } |
8483 | |
8484 | ExprResult Res = DefaultFunctionArrayLvalueConversion(E); |
8485 | if (Res.isInvalid()) |
8486 | return E; |
8487 | E = Res.get(); |
8488 | |
8489 | if (!E->getType()->isVoidType()) |
8490 | RequireCompleteType(E->getExprLoc(), E->getType(), |
8491 | diag::err_incomplete_type); |
8492 | return E; |
8493 | } |
8494 | |
8495 | ExprResult Sema::CheckUnevaluatedOperand(Expr *E) { |
8496 | // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if |
8497 | // it occurs as an unevaluated operand. |
8498 | CheckUnusedVolatileAssignment(E); |
8499 | |
8500 | return E; |
8501 | } |
8502 | |
8503 | // If we can unambiguously determine whether Var can never be used |
8504 | // in a constant expression, return true. |
8505 | // - if the variable and its initializer are non-dependent, then |
8506 | // we can unambiguously check if the variable is a constant expression. |
8507 | // - if the initializer is not value dependent - we can determine whether |
8508 | // it can be used to initialize a constant expression. If Init can not |
8509 | // be used to initialize a constant expression we conclude that Var can |
8510 | // never be a constant expression. |
8511 | // - FXIME: if the initializer is dependent, we can still do some analysis and |
8512 | // identify certain cases unambiguously as non-const by using a Visitor: |
8513 | // - such as those that involve odr-use of a ParmVarDecl, involve a new |
8514 | // delete, lambda-expr, dynamic-cast, reinterpret-cast etc... |
8515 | static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var, |
8516 | ASTContext &Context) { |
8517 | if (isa<ParmVarDecl>(Val: Var)) return true; |
8518 | const VarDecl *DefVD = nullptr; |
8519 | |
8520 | // If there is no initializer - this can not be a constant expression. |
8521 | const Expr *Init = Var->getAnyInitializer(D&: DefVD); |
8522 | if (!Init) |
8523 | return true; |
8524 | assert(DefVD); |
8525 | if (DefVD->isWeak()) |
8526 | return false; |
8527 | |
8528 | if (Var->getType()->isDependentType() || Init->isValueDependent()) { |
8529 | // FIXME: Teach the constant evaluator to deal with the non-dependent parts |
8530 | // of value-dependent expressions, and use it here to determine whether the |
8531 | // initializer is a potential constant expression. |
8532 | return false; |
8533 | } |
8534 | |
8535 | return !Var->isUsableInConstantExpressions(C: Context); |
8536 | } |
8537 | |
8538 | /// Check if the current lambda has any potential captures |
8539 | /// that must be captured by any of its enclosing lambdas that are ready to |
8540 | /// capture. If there is a lambda that can capture a nested |
8541 | /// potential-capture, go ahead and do so. Also, check to see if any |
8542 | /// variables are uncaptureable or do not involve an odr-use so do not |
8543 | /// need to be captured. |
8544 | |
8545 | static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures( |
8546 | Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) { |
8547 | |
8548 | assert(!S.isUnevaluatedContext()); |
8549 | assert(S.CurContext->isDependentContext()); |
8550 | #ifndef NDEBUG |
8551 | DeclContext *DC = S.CurContext; |
8552 | while (DC && isa<CapturedDecl>(Val: DC)) |
8553 | DC = DC->getParent(); |
8554 | assert( |
8555 | CurrentLSI->CallOperator == DC && |
8556 | "The current call operator must be synchronized with Sema's CurContext" ); |
8557 | #endif // NDEBUG |
8558 | |
8559 | const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent(); |
8560 | |
8561 | // All the potentially captureable variables in the current nested |
8562 | // lambda (within a generic outer lambda), must be captured by an |
8563 | // outer lambda that is enclosed within a non-dependent context. |
8564 | CurrentLSI->visitPotentialCaptures(Callback: [&](ValueDecl *Var, Expr *VarExpr) { |
8565 | // If the variable is clearly identified as non-odr-used and the full |
8566 | // expression is not instantiation dependent, only then do we not |
8567 | // need to check enclosing lambda's for speculative captures. |
8568 | // For e.g.: |
8569 | // Even though 'x' is not odr-used, it should be captured. |
8570 | // int test() { |
8571 | // const int x = 10; |
8572 | // auto L = [=](auto a) { |
8573 | // (void) +x + a; |
8574 | // }; |
8575 | // } |
8576 | if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(CapturingVarExpr: VarExpr) && |
8577 | !IsFullExprInstantiationDependent) |
8578 | return; |
8579 | |
8580 | VarDecl *UnderlyingVar = Var->getPotentiallyDecomposedVarDecl(); |
8581 | if (!UnderlyingVar) |
8582 | return; |
8583 | |
8584 | // If we have a capture-capable lambda for the variable, go ahead and |
8585 | // capture the variable in that lambda (and all its enclosing lambdas). |
8586 | if (const std::optional<unsigned> Index = |
8587 | getStackIndexOfNearestEnclosingCaptureCapableLambda( |
8588 | FunctionScopes: S.FunctionScopes, VarToCapture: Var, S)) |
8589 | S.MarkCaptureUsedInEnclosingContext(Capture: Var, Loc: VarExpr->getExprLoc(), CapturingScopeIndex: *Index); |
8590 | const bool IsVarNeverAConstantExpression = |
8591 | VariableCanNeverBeAConstantExpression(Var: UnderlyingVar, Context&: S.Context); |
8592 | if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) { |
8593 | // This full expression is not instantiation dependent or the variable |
8594 | // can not be used in a constant expression - which means |
8595 | // this variable must be odr-used here, so diagnose a |
8596 | // capture violation early, if the variable is un-captureable. |
8597 | // This is purely for diagnosing errors early. Otherwise, this |
8598 | // error would get diagnosed when the lambda becomes capture ready. |
8599 | QualType CaptureType, DeclRefType; |
8600 | SourceLocation ExprLoc = VarExpr->getExprLoc(); |
8601 | if (S.tryCaptureVariable(Var, Loc: ExprLoc, Kind: S.TryCapture_Implicit, |
8602 | /*EllipsisLoc*/ SourceLocation(), |
8603 | /*BuildAndDiagnose*/false, CaptureType, |
8604 | DeclRefType, FunctionScopeIndexToStopAt: nullptr)) { |
8605 | // We will never be able to capture this variable, and we need |
8606 | // to be able to in any and all instantiations, so diagnose it. |
8607 | S.tryCaptureVariable(Var, Loc: ExprLoc, Kind: S.TryCapture_Implicit, |
8608 | /*EllipsisLoc*/ SourceLocation(), |
8609 | /*BuildAndDiagnose*/true, CaptureType, |
8610 | DeclRefType, FunctionScopeIndexToStopAt: nullptr); |
8611 | } |
8612 | } |
8613 | }); |
8614 | |
8615 | // Check if 'this' needs to be captured. |
8616 | if (CurrentLSI->hasPotentialThisCapture()) { |
8617 | // If we have a capture-capable lambda for 'this', go ahead and capture |
8618 | // 'this' in that lambda (and all its enclosing lambdas). |
8619 | if (const std::optional<unsigned> Index = |
8620 | getStackIndexOfNearestEnclosingCaptureCapableLambda( |
8621 | FunctionScopes: S.FunctionScopes, /*0 is 'this'*/ VarToCapture: nullptr, S)) { |
8622 | const unsigned FunctionScopeIndexOfCapturableLambda = *Index; |
8623 | S.CheckCXXThisCapture(Loc: CurrentLSI->PotentialThisCaptureLocation, |
8624 | /*Explicit*/ false, /*BuildAndDiagnose*/ true, |
8625 | FunctionScopeIndexToStopAt: &FunctionScopeIndexOfCapturableLambda); |
8626 | } |
8627 | } |
8628 | |
8629 | // Reset all the potential captures at the end of each full-expression. |
8630 | CurrentLSI->clearPotentialCaptures(); |
8631 | } |
8632 | |
8633 | static ExprResult attemptRecovery(Sema &SemaRef, |
8634 | const TypoCorrectionConsumer &Consumer, |
8635 | const TypoCorrection &TC) { |
8636 | LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(), |
8637 | Consumer.getLookupResult().getLookupKind()); |
8638 | const CXXScopeSpec *SS = Consumer.getSS(); |
8639 | CXXScopeSpec NewSS; |
8640 | |
8641 | // Use an approprate CXXScopeSpec for building the expr. |
8642 | if (auto *NNS = TC.getCorrectionSpecifier()) |
8643 | NewSS.MakeTrivial(Context&: SemaRef.Context, Qualifier: NNS, R: TC.getCorrectionRange()); |
8644 | else if (SS && !TC.WillReplaceSpecifier()) |
8645 | NewSS = *SS; |
8646 | |
8647 | if (auto *ND = TC.getFoundDecl()) { |
8648 | R.setLookupName(ND->getDeclName()); |
8649 | R.addDecl(D: ND); |
8650 | if (ND->isCXXClassMember()) { |
8651 | // Figure out the correct naming class to add to the LookupResult. |
8652 | CXXRecordDecl *Record = nullptr; |
8653 | if (auto *NNS = TC.getCorrectionSpecifier()) |
8654 | Record = NNS->getAsType()->getAsCXXRecordDecl(); |
8655 | if (!Record) |
8656 | Record = |
8657 | dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext()); |
8658 | if (Record) |
8659 | R.setNamingClass(Record); |
8660 | |
8661 | // Detect and handle the case where the decl might be an implicit |
8662 | // member. |
8663 | if (SemaRef.isPotentialImplicitMemberAccess( |
8664 | SS: NewSS, R, IsAddressOfOperand: Consumer.isAddressOfOperand())) |
8665 | return SemaRef.BuildPossibleImplicitMemberExpr( |
8666 | SS: NewSS, /*TemplateKWLoc*/ SourceLocation(), R, |
8667 | /*TemplateArgs*/ nullptr, /*S*/ nullptr); |
8668 | } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Val: ND)) { |
8669 | return SemaRef.LookupInObjCMethod(LookUp&: R, S: Consumer.getScope(), |
8670 | II: Ivar->getIdentifier()); |
8671 | } |
8672 | } |
8673 | |
8674 | return SemaRef.BuildDeclarationNameExpr(SS: NewSS, R, /*NeedsADL*/ false, |
8675 | /*AcceptInvalidDecl*/ true); |
8676 | } |
8677 | |
8678 | namespace { |
8679 | class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> { |
8680 | llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs; |
8681 | |
8682 | public: |
8683 | explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs) |
8684 | : TypoExprs(TypoExprs) {} |
8685 | bool VisitTypoExpr(TypoExpr *TE) { |
8686 | TypoExprs.insert(X: TE); |
8687 | return true; |
8688 | } |
8689 | }; |
8690 | |
8691 | class TransformTypos : public TreeTransform<TransformTypos> { |
8692 | typedef TreeTransform<TransformTypos> BaseTransform; |
8693 | |
8694 | VarDecl *InitDecl; // A decl to avoid as a correction because it is in the |
8695 | // process of being initialized. |
8696 | llvm::function_ref<ExprResult(Expr *)> ExprFilter; |
8697 | llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs; |
8698 | llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache; |
8699 | llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution; |
8700 | |
8701 | /// Emit diagnostics for all of the TypoExprs encountered. |
8702 | /// |
8703 | /// If the TypoExprs were successfully corrected, then the diagnostics should |
8704 | /// suggest the corrections. Otherwise the diagnostics will not suggest |
8705 | /// anything (having been passed an empty TypoCorrection). |
8706 | /// |
8707 | /// If we've failed to correct due to ambiguous corrections, we need to |
8708 | /// be sure to pass empty corrections and replacements. Otherwise it's |
8709 | /// possible that the Consumer has a TypoCorrection that failed to ambiguity |
8710 | /// and we don't want to report those diagnostics. |
8711 | void EmitAllDiagnostics(bool IsAmbiguous) { |
8712 | for (TypoExpr *TE : TypoExprs) { |
8713 | auto &State = SemaRef.getTypoExprState(TE); |
8714 | if (State.DiagHandler) { |
8715 | TypoCorrection TC = IsAmbiguous |
8716 | ? TypoCorrection() : State.Consumer->getCurrentCorrection(); |
8717 | ExprResult Replacement = IsAmbiguous ? ExprError() : TransformCache[TE]; |
8718 | |
8719 | // Extract the NamedDecl from the transformed TypoExpr and add it to the |
8720 | // TypoCorrection, replacing the existing decls. This ensures the right |
8721 | // NamedDecl is used in diagnostics e.g. in the case where overload |
8722 | // resolution was used to select one from several possible decls that |
8723 | // had been stored in the TypoCorrection. |
8724 | if (auto *ND = getDeclFromExpr( |
8725 | E: Replacement.isInvalid() ? nullptr : Replacement.get())) |
8726 | TC.setCorrectionDecl(ND); |
8727 | |
8728 | State.DiagHandler(TC); |
8729 | } |
8730 | SemaRef.clearDelayedTypo(TE); |
8731 | } |
8732 | } |
8733 | |
8734 | /// Try to advance the typo correction state of the first unfinished TypoExpr. |
8735 | /// We allow advancement of the correction stream by removing it from the |
8736 | /// TransformCache which allows `TransformTypoExpr` to advance during the |
8737 | /// next transformation attempt. |
8738 | /// |
8739 | /// Any substitution attempts for the previous TypoExprs (which must have been |
8740 | /// finished) will need to be retried since it's possible that they will now |
8741 | /// be invalid given the latest advancement. |
8742 | /// |
8743 | /// We need to be sure that we're making progress - it's possible that the |
8744 | /// tree is so malformed that the transform never makes it to the |
8745 | /// `TransformTypoExpr`. |
8746 | /// |
8747 | /// Returns true if there are any untried correction combinations. |
8748 | bool CheckAndAdvanceTypoExprCorrectionStreams() { |
8749 | for (auto *TE : TypoExprs) { |
8750 | auto &State = SemaRef.getTypoExprState(TE); |
8751 | TransformCache.erase(Val: TE); |
8752 | if (!State.Consumer->hasMadeAnyCorrectionProgress()) |
8753 | return false; |
8754 | if (!State.Consumer->finished()) |
8755 | return true; |
8756 | State.Consumer->resetCorrectionStream(); |
8757 | } |
8758 | return false; |
8759 | } |
8760 | |
8761 | NamedDecl *getDeclFromExpr(Expr *E) { |
8762 | if (auto *OE = dyn_cast_or_null<OverloadExpr>(Val: E)) |
8763 | E = OverloadResolution[OE]; |
8764 | |
8765 | if (!E) |
8766 | return nullptr; |
8767 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) |
8768 | return DRE->getFoundDecl(); |
8769 | if (auto *ME = dyn_cast<MemberExpr>(Val: E)) |
8770 | return ME->getFoundDecl(); |
8771 | // FIXME: Add any other expr types that could be seen by the delayed typo |
8772 | // correction TreeTransform for which the corresponding TypoCorrection could |
8773 | // contain multiple decls. |
8774 | return nullptr; |
8775 | } |
8776 | |
8777 | ExprResult TryTransform(Expr *E) { |
8778 | Sema::SFINAETrap Trap(SemaRef); |
8779 | ExprResult Res = TransformExpr(E); |
8780 | if (Trap.hasErrorOccurred() || Res.isInvalid()) |
8781 | return ExprError(); |
8782 | |
8783 | return ExprFilter(Res.get()); |
8784 | } |
8785 | |
8786 | // Since correcting typos may intoduce new TypoExprs, this function |
8787 | // checks for new TypoExprs and recurses if it finds any. Note that it will |
8788 | // only succeed if it is able to correct all typos in the given expression. |
8789 | ExprResult CheckForRecursiveTypos(ExprResult Res, bool &IsAmbiguous) { |
8790 | if (Res.isInvalid()) { |
8791 | return Res; |
8792 | } |
8793 | // Check to see if any new TypoExprs were created. If so, we need to recurse |
8794 | // to check their validity. |
8795 | Expr *FixedExpr = Res.get(); |
8796 | |
8797 | auto SavedTypoExprs = std::move(TypoExprs); |
8798 | auto SavedAmbiguousTypoExprs = std::move(AmbiguousTypoExprs); |
8799 | TypoExprs.clear(); |
8800 | AmbiguousTypoExprs.clear(); |
8801 | |
8802 | FindTypoExprs(TypoExprs).TraverseStmt(FixedExpr); |
8803 | if (!TypoExprs.empty()) { |
8804 | // Recurse to handle newly created TypoExprs. If we're not able to |
8805 | // handle them, discard these TypoExprs. |
8806 | ExprResult RecurResult = |
8807 | RecursiveTransformLoop(E: FixedExpr, IsAmbiguous); |
8808 | if (RecurResult.isInvalid()) { |
8809 | Res = ExprError(); |
8810 | // Recursive corrections didn't work, wipe them away and don't add |
8811 | // them to the TypoExprs set. Remove them from Sema's TypoExpr list |
8812 | // since we don't want to clear them twice. Note: it's possible the |
8813 | // TypoExprs were created recursively and thus won't be in our |
8814 | // Sema's TypoExprs - they were created in our `RecursiveTransformLoop`. |
8815 | auto &SemaTypoExprs = SemaRef.TypoExprs; |
8816 | for (auto *TE : TypoExprs) { |
8817 | TransformCache.erase(Val: TE); |
8818 | SemaRef.clearDelayedTypo(TE); |
8819 | |
8820 | auto SI = find(SemaTypoExprs, TE); |
8821 | if (SI != SemaTypoExprs.end()) { |
8822 | SemaTypoExprs.erase(SI); |
8823 | } |
8824 | } |
8825 | } else { |
8826 | // TypoExpr is valid: add newly created TypoExprs since we were |
8827 | // able to correct them. |
8828 | Res = RecurResult; |
8829 | SavedTypoExprs.set_union(TypoExprs); |
8830 | } |
8831 | } |
8832 | |
8833 | TypoExprs = std::move(SavedTypoExprs); |
8834 | AmbiguousTypoExprs = std::move(SavedAmbiguousTypoExprs); |
8835 | |
8836 | return Res; |
8837 | } |
8838 | |
8839 | // Try to transform the given expression, looping through the correction |
8840 | // candidates with `CheckAndAdvanceTypoExprCorrectionStreams`. |
8841 | // |
8842 | // If valid ambiguous typo corrections are seen, `IsAmbiguous` is set to |
8843 | // true and this method immediately will return an `ExprError`. |
8844 | ExprResult RecursiveTransformLoop(Expr *E, bool &IsAmbiguous) { |
8845 | ExprResult Res; |
8846 | auto SavedTypoExprs = std::move(SemaRef.TypoExprs); |
8847 | SemaRef.TypoExprs.clear(); |
8848 | |
8849 | while (true) { |
8850 | Res = CheckForRecursiveTypos(Res: TryTransform(E), IsAmbiguous); |
8851 | |
8852 | // Recursion encountered an ambiguous correction. This means that our |
8853 | // correction itself is ambiguous, so stop now. |
8854 | if (IsAmbiguous) |
8855 | break; |
8856 | |
8857 | // If the transform is still valid after checking for any new typos, |
8858 | // it's good to go. |
8859 | if (!Res.isInvalid()) |
8860 | break; |
8861 | |
8862 | // The transform was invalid, see if we have any TypoExprs with untried |
8863 | // correction candidates. |
8864 | if (!CheckAndAdvanceTypoExprCorrectionStreams()) |
8865 | break; |
8866 | } |
8867 | |
8868 | // If we found a valid result, double check to make sure it's not ambiguous. |
8869 | if (!IsAmbiguous && !Res.isInvalid() && !AmbiguousTypoExprs.empty()) { |
8870 | auto SavedTransformCache = |
8871 | llvm::SmallDenseMap<TypoExpr *, ExprResult, 2>(TransformCache); |
8872 | |
8873 | // Ensure none of the TypoExprs have multiple typo correction candidates |
8874 | // with the same edit length that pass all the checks and filters. |
8875 | while (!AmbiguousTypoExprs.empty()) { |
8876 | auto TE = AmbiguousTypoExprs.back(); |
8877 | |
8878 | // TryTransform itself can create new Typos, adding them to the TypoExpr map |
8879 | // and invalidating our TypoExprState, so always fetch it instead of storing. |
8880 | SemaRef.getTypoExprState(TE).Consumer->saveCurrentPosition(); |
8881 | |
8882 | TypoCorrection TC = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection(); |
8883 | TypoCorrection Next; |
8884 | do { |
8885 | // Fetch the next correction by erasing the typo from the cache and calling |
8886 | // `TryTransform` which will iterate through corrections in |
8887 | // `TransformTypoExpr`. |
8888 | TransformCache.erase(Val: TE); |
8889 | ExprResult AmbigRes = CheckForRecursiveTypos(Res: TryTransform(E), IsAmbiguous); |
8890 | |
8891 | if (!AmbigRes.isInvalid() || IsAmbiguous) { |
8892 | SemaRef.getTypoExprState(TE).Consumer->resetCorrectionStream(); |
8893 | SavedTransformCache.erase(Val: TE); |
8894 | Res = ExprError(); |
8895 | IsAmbiguous = true; |
8896 | break; |
8897 | } |
8898 | } while ((Next = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection()) && |
8899 | Next.getEditDistance(false) == TC.getEditDistance(false)); |
8900 | |
8901 | if (IsAmbiguous) |
8902 | break; |
8903 | |
8904 | AmbiguousTypoExprs.remove(X: TE); |
8905 | SemaRef.getTypoExprState(TE).Consumer->restoreSavedPosition(); |
8906 | TransformCache[TE] = SavedTransformCache[TE]; |
8907 | } |
8908 | TransformCache = std::move(SavedTransformCache); |
8909 | } |
8910 | |
8911 | // Wipe away any newly created TypoExprs that we don't know about. Since we |
8912 | // clear any invalid TypoExprs in `CheckForRecursiveTypos`, this is only |
8913 | // possible if a `TypoExpr` is created during a transformation but then |
8914 | // fails before we can discover it. |
8915 | auto &SemaTypoExprs = SemaRef.TypoExprs; |
8916 | for (auto Iterator = SemaTypoExprs.begin(); Iterator != SemaTypoExprs.end();) { |
8917 | auto TE = *Iterator; |
8918 | auto FI = find(TypoExprs, TE); |
8919 | if (FI != TypoExprs.end()) { |
8920 | Iterator++; |
8921 | continue; |
8922 | } |
8923 | SemaRef.clearDelayedTypo(TE); |
8924 | Iterator = SemaTypoExprs.erase(Iterator); |
8925 | } |
8926 | SemaRef.TypoExprs = std::move(SavedTypoExprs); |
8927 | |
8928 | return Res; |
8929 | } |
8930 | |
8931 | public: |
8932 | TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter) |
8933 | : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {} |
8934 | |
8935 | ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc, |
8936 | MultiExprArg Args, |
8937 | SourceLocation RParenLoc, |
8938 | Expr *ExecConfig = nullptr) { |
8939 | auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args, |
8940 | RParenLoc, ExecConfig); |
8941 | if (auto *OE = dyn_cast<OverloadExpr>(Val: Callee)) { |
8942 | if (Result.isUsable()) { |
8943 | Expr *ResultCall = Result.get(); |
8944 | if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall)) |
8945 | ResultCall = BE->getSubExpr(); |
8946 | if (auto *CE = dyn_cast<CallExpr>(ResultCall)) |
8947 | OverloadResolution[OE] = CE->getCallee(); |
8948 | } |
8949 | } |
8950 | return Result; |
8951 | } |
8952 | |
8953 | ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); } |
8954 | |
8955 | ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); } |
8956 | |
8957 | ExprResult Transform(Expr *E) { |
8958 | bool IsAmbiguous = false; |
8959 | ExprResult Res = RecursiveTransformLoop(E, IsAmbiguous); |
8960 | |
8961 | if (!Res.isUsable()) |
8962 | FindTypoExprs(TypoExprs).TraverseStmt(E); |
8963 | |
8964 | EmitAllDiagnostics(IsAmbiguous); |
8965 | |
8966 | return Res; |
8967 | } |
8968 | |
8969 | ExprResult TransformTypoExpr(TypoExpr *E) { |
8970 | // If the TypoExpr hasn't been seen before, record it. Otherwise, return the |
8971 | // cached transformation result if there is one and the TypoExpr isn't the |
8972 | // first one that was encountered. |
8973 | auto &CacheEntry = TransformCache[E]; |
8974 | if (!TypoExprs.insert(X: E) && !CacheEntry.isUnset()) { |
8975 | return CacheEntry; |
8976 | } |
8977 | |
8978 | auto &State = SemaRef.getTypoExprState(E); |
8979 | assert(State.Consumer && "Cannot transform a cleared TypoExpr" ); |
8980 | |
8981 | // For the first TypoExpr and an uncached TypoExpr, find the next likely |
8982 | // typo correction and return it. |
8983 | while (TypoCorrection TC = State.Consumer->getNextCorrection()) { |
8984 | if (InitDecl && TC.getFoundDecl() == InitDecl) |
8985 | continue; |
8986 | // FIXME: If we would typo-correct to an invalid declaration, it's |
8987 | // probably best to just suppress all errors from this typo correction. |
8988 | ExprResult NE = State.RecoveryHandler ? |
8989 | State.RecoveryHandler(SemaRef, E, TC) : |
8990 | attemptRecovery(SemaRef, *State.Consumer, TC); |
8991 | if (!NE.isInvalid()) { |
8992 | // Check whether there may be a second viable correction with the same |
8993 | // edit distance; if so, remember this TypoExpr may have an ambiguous |
8994 | // correction so it can be more thoroughly vetted later. |
8995 | TypoCorrection Next; |
8996 | if ((Next = State.Consumer->peekNextCorrection()) && |
8997 | Next.getEditDistance(Normalized: false) == TC.getEditDistance(Normalized: false)) { |
8998 | AmbiguousTypoExprs.insert(X: E); |
8999 | } else { |
9000 | AmbiguousTypoExprs.remove(X: E); |
9001 | } |
9002 | assert(!NE.isUnset() && |
9003 | "Typo was transformed into a valid-but-null ExprResult" ); |
9004 | return CacheEntry = NE; |
9005 | } |
9006 | } |
9007 | return CacheEntry = ExprError(); |
9008 | } |
9009 | }; |
9010 | } |
9011 | |
9012 | ExprResult |
9013 | Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl, |
9014 | bool RecoverUncorrectedTypos, |
9015 | llvm::function_ref<ExprResult(Expr *)> Filter) { |
9016 | // If the current evaluation context indicates there are uncorrected typos |
9017 | // and the current expression isn't guaranteed to not have typos, try to |
9018 | // resolve any TypoExpr nodes that might be in the expression. |
9019 | if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos && |
9020 | (E->isTypeDependent() || E->isValueDependent() || |
9021 | E->isInstantiationDependent())) { |
9022 | auto TyposResolved = DelayedTypos.size(); |
9023 | auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E); |
9024 | TyposResolved -= DelayedTypos.size(); |
9025 | if (Result.isInvalid() || Result.get() != E) { |
9026 | ExprEvalContexts.back().NumTypos -= TyposResolved; |
9027 | if (Result.isInvalid() && RecoverUncorrectedTypos) { |
9028 | struct TyposReplace : TreeTransform<TyposReplace> { |
9029 | TyposReplace(Sema &SemaRef) : TreeTransform(SemaRef) {} |
9030 | ExprResult TransformTypoExpr(clang::TypoExpr *E) { |
9031 | return this->SemaRef.CreateRecoveryExpr(E->getBeginLoc(), |
9032 | E->getEndLoc(), {}); |
9033 | } |
9034 | } TT(*this); |
9035 | return TT.TransformExpr(E); |
9036 | } |
9037 | return Result; |
9038 | } |
9039 | assert(TyposResolved == 0 && "Corrected typo but got same Expr back?" ); |
9040 | } |
9041 | return E; |
9042 | } |
9043 | |
9044 | ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC, |
9045 | bool DiscardedValue, bool IsConstexpr, |
9046 | bool IsTemplateArgument) { |
9047 | ExprResult FullExpr = FE; |
9048 | |
9049 | if (!FullExpr.get()) |
9050 | return ExprError(); |
9051 | |
9052 | if (!IsTemplateArgument && DiagnoseUnexpandedParameterPack(E: FullExpr.get())) |
9053 | return ExprError(); |
9054 | |
9055 | if (DiscardedValue) { |
9056 | // Top-level expressions default to 'id' when we're in a debugger. |
9057 | if (getLangOpts().DebuggerCastResultToId && |
9058 | FullExpr.get()->getType() == Context.UnknownAnyTy) { |
9059 | FullExpr = forceUnknownAnyToType(E: FullExpr.get(), ToType: Context.getObjCIdType()); |
9060 | if (FullExpr.isInvalid()) |
9061 | return ExprError(); |
9062 | } |
9063 | |
9064 | FullExpr = CheckPlaceholderExpr(E: FullExpr.get()); |
9065 | if (FullExpr.isInvalid()) |
9066 | return ExprError(); |
9067 | |
9068 | FullExpr = IgnoredValueConversions(E: FullExpr.get()); |
9069 | if (FullExpr.isInvalid()) |
9070 | return ExprError(); |
9071 | |
9072 | DiagnoseUnusedExprResult(FullExpr.get(), diag::warn_unused_expr); |
9073 | } |
9074 | |
9075 | FullExpr = CorrectDelayedTyposInExpr(E: FullExpr.get(), /*InitDecl=*/nullptr, |
9076 | /*RecoverUncorrectedTypos=*/true); |
9077 | if (FullExpr.isInvalid()) |
9078 | return ExprError(); |
9079 | |
9080 | CheckCompletedExpr(E: FullExpr.get(), CheckLoc: CC, IsConstexpr); |
9081 | |
9082 | // At the end of this full expression (which could be a deeply nested |
9083 | // lambda), if there is a potential capture within the nested lambda, |
9084 | // have the outer capture-able lambda try and capture it. |
9085 | // Consider the following code: |
9086 | // void f(int, int); |
9087 | // void f(const int&, double); |
9088 | // void foo() { |
9089 | // const int x = 10, y = 20; |
9090 | // auto L = [=](auto a) { |
9091 | // auto M = [=](auto b) { |
9092 | // f(x, b); <-- requires x to be captured by L and M |
9093 | // f(y, a); <-- requires y to be captured by L, but not all Ms |
9094 | // }; |
9095 | // }; |
9096 | // } |
9097 | |
9098 | // FIXME: Also consider what happens for something like this that involves |
9099 | // the gnu-extension statement-expressions or even lambda-init-captures: |
9100 | // void f() { |
9101 | // const int n = 0; |
9102 | // auto L = [&](auto a) { |
9103 | // +n + ({ 0; a; }); |
9104 | // }; |
9105 | // } |
9106 | // |
9107 | // Here, we see +n, and then the full-expression 0; ends, so we don't |
9108 | // capture n (and instead remove it from our list of potential captures), |
9109 | // and then the full-expression +n + ({ 0; }); ends, but it's too late |
9110 | // for us to see that we need to capture n after all. |
9111 | |
9112 | LambdaScopeInfo *const CurrentLSI = |
9113 | getCurLambda(/*IgnoreCapturedRegions=*/IgnoreNonLambdaCapturingScope: true); |
9114 | // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer |
9115 | // even if CurContext is not a lambda call operator. Refer to that Bug Report |
9116 | // for an example of the code that might cause this asynchrony. |
9117 | // By ensuring we are in the context of a lambda's call operator |
9118 | // we can fix the bug (we only need to check whether we need to capture |
9119 | // if we are within a lambda's body); but per the comments in that |
9120 | // PR, a proper fix would entail : |
9121 | // "Alternative suggestion: |
9122 | // - Add to Sema an integer holding the smallest (outermost) scope |
9123 | // index that we are *lexically* within, and save/restore/set to |
9124 | // FunctionScopes.size() in InstantiatingTemplate's |
9125 | // constructor/destructor. |
9126 | // - Teach the handful of places that iterate over FunctionScopes to |
9127 | // stop at the outermost enclosing lexical scope." |
9128 | DeclContext *DC = CurContext; |
9129 | while (DC && isa<CapturedDecl>(Val: DC)) |
9130 | DC = DC->getParent(); |
9131 | const bool IsInLambdaDeclContext = isLambdaCallOperator(DC); |
9132 | if (IsInLambdaDeclContext && CurrentLSI && |
9133 | CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid()) |
9134 | CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI, |
9135 | S&: *this); |
9136 | return MaybeCreateExprWithCleanups(SubExpr: FullExpr); |
9137 | } |
9138 | |
9139 | StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) { |
9140 | if (!FullStmt) return StmtError(); |
9141 | |
9142 | return MaybeCreateStmtWithCleanups(SubStmt: FullStmt); |
9143 | } |
9144 | |
9145 | Sema::IfExistsResult |
9146 | Sema::CheckMicrosoftIfExistsSymbol(Scope *S, |
9147 | CXXScopeSpec &SS, |
9148 | const DeclarationNameInfo &TargetNameInfo) { |
9149 | DeclarationName TargetName = TargetNameInfo.getName(); |
9150 | if (!TargetName) |
9151 | return IER_DoesNotExist; |
9152 | |
9153 | // If the name itself is dependent, then the result is dependent. |
9154 | if (TargetName.isDependentName()) |
9155 | return IER_Dependent; |
9156 | |
9157 | // Do the redeclaration lookup in the current scope. |
9158 | LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName, |
9159 | RedeclarationKind::NotForRedeclaration); |
9160 | LookupParsedName(R, S, SS: &SS); |
9161 | R.suppressDiagnostics(); |
9162 | |
9163 | switch (R.getResultKind()) { |
9164 | case LookupResult::Found: |
9165 | case LookupResult::FoundOverloaded: |
9166 | case LookupResult::FoundUnresolvedValue: |
9167 | case LookupResult::Ambiguous: |
9168 | return IER_Exists; |
9169 | |
9170 | case LookupResult::NotFound: |
9171 | return IER_DoesNotExist; |
9172 | |
9173 | case LookupResult::NotFoundInCurrentInstantiation: |
9174 | return IER_Dependent; |
9175 | } |
9176 | |
9177 | llvm_unreachable("Invalid LookupResult Kind!" ); |
9178 | } |
9179 | |
9180 | Sema::IfExistsResult |
9181 | Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, |
9182 | bool IsIfExists, CXXScopeSpec &SS, |
9183 | UnqualifiedId &Name) { |
9184 | DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); |
9185 | |
9186 | // Check for an unexpanded parameter pack. |
9187 | auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists; |
9188 | if (DiagnoseUnexpandedParameterPack(SS, UPPC) || |
9189 | DiagnoseUnexpandedParameterPack(NameInfo: TargetNameInfo, UPPC)) |
9190 | return IER_Error; |
9191 | |
9192 | return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo); |
9193 | } |
9194 | |
9195 | concepts::Requirement *Sema::ActOnSimpleRequirement(Expr *E) { |
9196 | return BuildExprRequirement(E, /*IsSimple=*/IsSatisfied: true, |
9197 | /*NoexceptLoc=*/SourceLocation(), |
9198 | /*ReturnTypeRequirement=*/{}); |
9199 | } |
9200 | |
9201 | concepts::Requirement *Sema::ActOnTypeRequirement( |
9202 | SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc, |
9203 | const IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId) { |
9204 | assert(((!TypeName && TemplateId) || (TypeName && !TemplateId)) && |
9205 | "Exactly one of TypeName and TemplateId must be specified." ); |
9206 | TypeSourceInfo *TSI = nullptr; |
9207 | if (TypeName) { |
9208 | QualType T = |
9209 | CheckTypenameType(Keyword: ElaboratedTypeKeyword::Typename, KeywordLoc: TypenameKWLoc, |
9210 | QualifierLoc: SS.getWithLocInContext(Context), II: *TypeName, IILoc: NameLoc, |
9211 | TSI: &TSI, /*DeducedTSTContext=*/false); |
9212 | if (T.isNull()) |
9213 | return nullptr; |
9214 | } else { |
9215 | ASTTemplateArgsPtr ArgsPtr(TemplateId->getTemplateArgs(), |
9216 | TemplateId->NumArgs); |
9217 | TypeResult T = ActOnTypenameType(S: CurScope, TypenameLoc: TypenameKWLoc, SS, |
9218 | TemplateLoc: TemplateId->TemplateKWLoc, |
9219 | TemplateName: TemplateId->Template, TemplateII: TemplateId->Name, |
9220 | TemplateIILoc: TemplateId->TemplateNameLoc, |
9221 | LAngleLoc: TemplateId->LAngleLoc, TemplateArgs: ArgsPtr, |
9222 | RAngleLoc: TemplateId->RAngleLoc); |
9223 | if (T.isInvalid()) |
9224 | return nullptr; |
9225 | if (GetTypeFromParser(Ty: T.get(), TInfo: &TSI).isNull()) |
9226 | return nullptr; |
9227 | } |
9228 | return BuildTypeRequirement(Type: TSI); |
9229 | } |
9230 | |
9231 | concepts::Requirement * |
9232 | Sema::ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc) { |
9233 | return BuildExprRequirement(E, /*IsSimple=*/IsSatisfied: false, NoexceptLoc, |
9234 | /*ReturnTypeRequirement=*/{}); |
9235 | } |
9236 | |
9237 | concepts::Requirement * |
9238 | Sema::ActOnCompoundRequirement( |
9239 | Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS, |
9240 | TemplateIdAnnotation *TypeConstraint, unsigned Depth) { |
9241 | // C++2a [expr.prim.req.compound] p1.3.3 |
9242 | // [..] the expression is deduced against an invented function template |
9243 | // F [...] F is a void function template with a single type template |
9244 | // parameter T declared with the constrained-parameter. Form a new |
9245 | // cv-qualifier-seq cv by taking the union of const and volatile specifiers |
9246 | // around the constrained-parameter. F has a single parameter whose |
9247 | // type-specifier is cv T followed by the abstract-declarator. [...] |
9248 | // |
9249 | // The cv part is done in the calling function - we get the concept with |
9250 | // arguments and the abstract declarator with the correct CV qualification and |
9251 | // have to synthesize T and the single parameter of F. |
9252 | auto &II = Context.Idents.get(Name: "expr-type" ); |
9253 | auto *TParam = TemplateTypeParmDecl::Create(C: Context, DC: CurContext, |
9254 | KeyLoc: SourceLocation(), |
9255 | NameLoc: SourceLocation(), D: Depth, |
9256 | /*Index=*/P: 0, Id: &II, |
9257 | /*Typename=*/true, |
9258 | /*ParameterPack=*/false, |
9259 | /*HasTypeConstraint=*/true); |
9260 | |
9261 | if (BuildTypeConstraint(SS, TypeConstraint, ConstrainedParameter: TParam, |
9262 | /*EllipsisLoc=*/SourceLocation(), |
9263 | /*AllowUnexpandedPack=*/true)) |
9264 | // Just produce a requirement with no type requirements. |
9265 | return BuildExprRequirement(E, /*IsSimple=*/IsSatisfied: false, NoexceptLoc, ReturnTypeRequirement: {}); |
9266 | |
9267 | auto *TPL = TemplateParameterList::Create(C: Context, TemplateLoc: SourceLocation(), |
9268 | LAngleLoc: SourceLocation(), |
9269 | Params: ArrayRef<NamedDecl *>(TParam), |
9270 | RAngleLoc: SourceLocation(), |
9271 | /*RequiresClause=*/nullptr); |
9272 | return BuildExprRequirement( |
9273 | E, /*IsSimple=*/IsSatisfied: false, NoexceptLoc, |
9274 | ReturnTypeRequirement: concepts::ExprRequirement::ReturnTypeRequirement(TPL)); |
9275 | } |
9276 | |
9277 | concepts::ExprRequirement * |
9278 | Sema::BuildExprRequirement( |
9279 | Expr *E, bool IsSimple, SourceLocation NoexceptLoc, |
9280 | concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) { |
9281 | auto Status = concepts::ExprRequirement::SS_Satisfied; |
9282 | ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr; |
9283 | if (E->isInstantiationDependent() || E->getType()->isPlaceholderType() || |
9284 | ReturnTypeRequirement.isDependent()) |
9285 | Status = concepts::ExprRequirement::SS_Dependent; |
9286 | else if (NoexceptLoc.isValid() && canThrow(E) == CanThrowResult::CT_Can) |
9287 | Status = concepts::ExprRequirement::SS_NoexceptNotMet; |
9288 | else if (ReturnTypeRequirement.isSubstitutionFailure()) |
9289 | Status = concepts::ExprRequirement::SS_TypeRequirementSubstitutionFailure; |
9290 | else if (ReturnTypeRequirement.isTypeConstraint()) { |
9291 | // C++2a [expr.prim.req]p1.3.3 |
9292 | // The immediately-declared constraint ([temp]) of decltype((E)) shall |
9293 | // be satisfied. |
9294 | TemplateParameterList *TPL = |
9295 | ReturnTypeRequirement.getTypeConstraintTemplateParameterList(); |
9296 | QualType MatchedType = |
9297 | Context.getReferenceQualifiedType(e: E).getCanonicalType(); |
9298 | llvm::SmallVector<TemplateArgument, 1> Args; |
9299 | Args.push_back(Elt: TemplateArgument(MatchedType)); |
9300 | |
9301 | auto *Param = cast<TemplateTypeParmDecl>(Val: TPL->getParam(Idx: 0)); |
9302 | |
9303 | MultiLevelTemplateArgumentList MLTAL(Param, Args, /*Final=*/false); |
9304 | MLTAL.addOuterRetainedLevels(Num: TPL->getDepth()); |
9305 | const TypeConstraint *TC = Param->getTypeConstraint(); |
9306 | assert(TC && "Type Constraint cannot be null here" ); |
9307 | auto *IDC = TC->getImmediatelyDeclaredConstraint(); |
9308 | assert(IDC && "ImmediatelyDeclaredConstraint can't be null here." ); |
9309 | ExprResult Constraint = SubstExpr(E: IDC, TemplateArgs: MLTAL); |
9310 | if (Constraint.isInvalid()) { |
9311 | return new (Context) concepts::ExprRequirement( |
9312 | concepts::createSubstDiagAt(S&: *this, Location: IDC->getExprLoc(), |
9313 | Printer: [&](llvm::raw_ostream &OS) { |
9314 | IDC->printPretty(OS, /*Helper=*/nullptr, |
9315 | getPrintingPolicy()); |
9316 | }), |
9317 | IsSimple, NoexceptLoc, ReturnTypeRequirement); |
9318 | } |
9319 | SubstitutedConstraintExpr = |
9320 | cast<ConceptSpecializationExpr>(Val: Constraint.get()); |
9321 | if (!SubstitutedConstraintExpr->isSatisfied()) |
9322 | Status = concepts::ExprRequirement::SS_ConstraintsNotSatisfied; |
9323 | } |
9324 | return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc, |
9325 | ReturnTypeRequirement, Status, |
9326 | SubstitutedConstraintExpr); |
9327 | } |
9328 | |
9329 | concepts::ExprRequirement * |
9330 | Sema::BuildExprRequirement( |
9331 | concepts::Requirement::SubstitutionDiagnostic *ExprSubstitutionDiagnostic, |
9332 | bool IsSimple, SourceLocation NoexceptLoc, |
9333 | concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) { |
9334 | return new (Context) concepts::ExprRequirement(ExprSubstitutionDiagnostic, |
9335 | IsSimple, NoexceptLoc, |
9336 | ReturnTypeRequirement); |
9337 | } |
9338 | |
9339 | concepts::TypeRequirement * |
9340 | Sema::BuildTypeRequirement(TypeSourceInfo *Type) { |
9341 | return new (Context) concepts::TypeRequirement(Type); |
9342 | } |
9343 | |
9344 | concepts::TypeRequirement * |
9345 | Sema::BuildTypeRequirement( |
9346 | concepts::Requirement::SubstitutionDiagnostic *SubstDiag) { |
9347 | return new (Context) concepts::TypeRequirement(SubstDiag); |
9348 | } |
9349 | |
9350 | concepts::Requirement *Sema::ActOnNestedRequirement(Expr *Constraint) { |
9351 | return BuildNestedRequirement(E: Constraint); |
9352 | } |
9353 | |
9354 | concepts::NestedRequirement * |
9355 | Sema::BuildNestedRequirement(Expr *Constraint) { |
9356 | ConstraintSatisfaction Satisfaction; |
9357 | if (!Constraint->isInstantiationDependent() && |
9358 | CheckConstraintSatisfaction(nullptr, {Constraint}, /*TemplateArgs=*/{}, |
9359 | Constraint->getSourceRange(), Satisfaction)) |
9360 | return nullptr; |
9361 | return new (Context) concepts::NestedRequirement(Context, Constraint, |
9362 | Satisfaction); |
9363 | } |
9364 | |
9365 | concepts::NestedRequirement * |
9366 | Sema::BuildNestedRequirement(StringRef InvalidConstraintEntity, |
9367 | const ASTConstraintSatisfaction &Satisfaction) { |
9368 | return new (Context) concepts::NestedRequirement( |
9369 | InvalidConstraintEntity, |
9370 | ASTConstraintSatisfaction::Rebuild(C: Context, Satisfaction)); |
9371 | } |
9372 | |
9373 | RequiresExprBodyDecl * |
9374 | Sema::ActOnStartRequiresExpr(SourceLocation RequiresKWLoc, |
9375 | ArrayRef<ParmVarDecl *> LocalParameters, |
9376 | Scope *BodyScope) { |
9377 | assert(BodyScope); |
9378 | |
9379 | RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(C&: Context, DC: CurContext, |
9380 | StartLoc: RequiresKWLoc); |
9381 | |
9382 | PushDeclContext(BodyScope, Body); |
9383 | |
9384 | for (ParmVarDecl *Param : LocalParameters) { |
9385 | if (Param->hasDefaultArg()) |
9386 | // C++2a [expr.prim.req] p4 |
9387 | // [...] A local parameter of a requires-expression shall not have a |
9388 | // default argument. [...] |
9389 | Diag(Param->getDefaultArgRange().getBegin(), |
9390 | diag::err_requires_expr_local_parameter_default_argument); |
9391 | // Ignore default argument and move on |
9392 | |
9393 | Param->setDeclContext(Body); |
9394 | // If this has an identifier, add it to the scope stack. |
9395 | if (Param->getIdentifier()) { |
9396 | CheckShadow(BodyScope, Param); |
9397 | PushOnScopeChains(Param, BodyScope); |
9398 | } |
9399 | } |
9400 | return Body; |
9401 | } |
9402 | |
9403 | void Sema::ActOnFinishRequiresExpr() { |
9404 | assert(CurContext && "DeclContext imbalance!" ); |
9405 | CurContext = CurContext->getLexicalParent(); |
9406 | assert(CurContext && "Popped translation unit!" ); |
9407 | } |
9408 | |
9409 | ExprResult Sema::ActOnRequiresExpr( |
9410 | SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body, |
9411 | SourceLocation LParenLoc, ArrayRef<ParmVarDecl *> LocalParameters, |
9412 | SourceLocation RParenLoc, ArrayRef<concepts::Requirement *> Requirements, |
9413 | SourceLocation ClosingBraceLoc) { |
9414 | auto *RE = RequiresExpr::Create(C&: Context, RequiresKWLoc, Body, LParenLoc, |
9415 | LocalParameters, RParenLoc, Requirements, |
9416 | RBraceLoc: ClosingBraceLoc); |
9417 | if (DiagnoseUnexpandedParameterPackInRequiresExpr(RE)) |
9418 | return ExprError(); |
9419 | return RE; |
9420 | } |
9421 | |