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/DeclCXX.h" |
21 | #include "clang/AST/DeclObjC.h" |
22 | #include "clang/AST/DynamicRecursiveASTVisitor.h" |
23 | #include "clang/AST/ExprCXX.h" |
24 | #include "clang/AST/ExprConcepts.h" |
25 | #include "clang/AST/ExprObjC.h" |
26 | #include "clang/AST/Type.h" |
27 | #include "clang/AST/TypeLoc.h" |
28 | #include "clang/Basic/AlignedAllocation.h" |
29 | #include "clang/Basic/DiagnosticSema.h" |
30 | #include "clang/Basic/PartialDiagnostic.h" |
31 | #include "clang/Basic/TargetInfo.h" |
32 | #include "clang/Basic/TokenKinds.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/SemaHLSL.h" |
43 | #include "clang/Sema/SemaInternal.h" |
44 | #include "clang/Sema/SemaLambda.h" |
45 | #include "clang/Sema/SemaObjC.h" |
46 | #include "clang/Sema/SemaPPC.h" |
47 | #include "clang/Sema/Template.h" |
48 | #include "clang/Sema/TemplateDeduction.h" |
49 | #include "llvm/ADT/APInt.h" |
50 | #include "llvm/ADT/STLExtras.h" |
51 | #include "llvm/ADT/StringExtras.h" |
52 | #include "llvm/Support/ErrorHandling.h" |
53 | #include "llvm/Support/TypeSize.h" |
54 | #include <optional> |
55 | using namespace clang; |
56 | using namespace sema; |
57 | |
58 | ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS, |
59 | SourceLocation NameLoc, |
60 | const IdentifierInfo &Name) { |
61 | NestedNameSpecifier *NNS = SS.getScopeRep(); |
62 | if ([[maybe_unused]] const IdentifierInfo *II = NNS->getAsIdentifier()) |
63 | assert(II == &Name && "not a constructor name"); |
64 | |
65 | QualType Type(NNS->translateToType(Context), 0); |
66 | // This reference to the type is located entirely at the location of the |
67 | // final identifier in the qualified-id. |
68 | return CreateParsedType(T: Type, |
69 | TInfo: Context.getTrivialTypeSourceInfo(T: Type, Loc: NameLoc)); |
70 | } |
71 | |
72 | ParsedType Sema::getConstructorName(const IdentifierInfo &II, |
73 | SourceLocation NameLoc, Scope *S, |
74 | CXXScopeSpec &SS, bool EnteringContext) { |
75 | CXXRecordDecl *CurClass = getCurrentClass(S, SS: &SS); |
76 | assert(CurClass && &II == CurClass->getIdentifier() && |
77 | "not a constructor name"); |
78 | |
79 | // When naming a constructor as a member of a dependent context (eg, in a |
80 | // friend declaration or an inherited constructor declaration), form an |
81 | // unresolved "typename" type. |
82 | if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) { |
83 | QualType T = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None, |
84 | NNS: SS.getScopeRep(), Name: &II); |
85 | return ParsedType::make(P: T); |
86 | } |
87 | |
88 | if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass)) |
89 | return ParsedType(); |
90 | |
91 | // Find the injected-class-name declaration. Note that we make no attempt to |
92 | // diagnose cases where the injected-class-name is shadowed: the only |
93 | // declaration that can validly shadow the injected-class-name is a |
94 | // non-static data member, and if the class contains both a non-static data |
95 | // member and a constructor then it is ill-formed (we check that in |
96 | // CheckCompletedCXXClass). |
97 | CXXRecordDecl *InjectedClassName = nullptr; |
98 | for (NamedDecl *ND : CurClass->lookup(&II)) { |
99 | auto *RD = dyn_cast<CXXRecordDecl>(ND); |
100 | if (RD && RD->isInjectedClassName()) { |
101 | InjectedClassName = RD; |
102 | break; |
103 | } |
104 | } |
105 | if (!InjectedClassName) { |
106 | if (!CurClass->isInvalidDecl()) { |
107 | // FIXME: RequireCompleteDeclContext doesn't check dependent contexts |
108 | // properly. Work around it here for now. |
109 | Diag(SS.getLastQualifierNameLoc(), |
110 | diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange(); |
111 | } |
112 | return ParsedType(); |
113 | } |
114 | |
115 | QualType T = Context.getTypeDeclType(InjectedClassName); |
116 | DiagnoseUseOfDecl(InjectedClassName, NameLoc); |
117 | MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false); |
118 | |
119 | return ParsedType::make(P: T); |
120 | } |
121 | |
122 | ParsedType Sema::getDestructorName(const IdentifierInfo &II, |
123 | SourceLocation NameLoc, Scope *S, |
124 | CXXScopeSpec &SS, ParsedType ObjectTypePtr, |
125 | bool EnteringContext) { |
126 | // Determine where to perform name lookup. |
127 | |
128 | // FIXME: This area of the standard is very messy, and the current |
129 | // wording is rather unclear about which scopes we search for the |
130 | // destructor name; see core issues 399 and 555. Issue 399 in |
131 | // particular shows where the current description of destructor name |
132 | // lookup is completely out of line with existing practice, e.g., |
133 | // this appears to be ill-formed: |
134 | // |
135 | // namespace N { |
136 | // template <typename T> struct S { |
137 | // ~S(); |
138 | // }; |
139 | // } |
140 | // |
141 | // void f(N::S<int>* s) { |
142 | // s->N::S<int>::~S(); |
143 | // } |
144 | // |
145 | // See also PR6358 and PR6359. |
146 | // |
147 | // For now, we accept all the cases in which the name given could plausibly |
148 | // be interpreted as a correct destructor name, issuing off-by-default |
149 | // extension diagnostics on the cases that don't strictly conform to the |
150 | // C++20 rules. This basically means we always consider looking in the |
151 | // nested-name-specifier prefix, the complete nested-name-specifier, and |
152 | // the scope, and accept if we find the expected type in any of the three |
153 | // places. |
154 | |
155 | if (SS.isInvalid()) |
156 | return nullptr; |
157 | |
158 | // Whether we've failed with a diagnostic already. |
159 | bool Failed = false; |
160 | |
161 | llvm::SmallVector<NamedDecl*, 8> FoundDecls; |
162 | llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 8> FoundDeclSet; |
163 | |
164 | // If we have an object type, it's because we are in a |
165 | // pseudo-destructor-expression or a member access expression, and |
166 | // we know what type we're looking for. |
167 | QualType SearchType = |
168 | ObjectTypePtr ? GetTypeFromParser(Ty: ObjectTypePtr) : QualType(); |
169 | |
170 | auto CheckLookupResult = [&](LookupResult &Found) -> ParsedType { |
171 | auto IsAcceptableResult = [&](NamedDecl *D) -> bool { |
172 | auto *Type = dyn_cast<TypeDecl>(Val: D->getUnderlyingDecl()); |
173 | if (!Type) |
174 | return false; |
175 | |
176 | if (SearchType.isNull() || SearchType->isDependentType()) |
177 | return true; |
178 | |
179 | QualType T = Context.getTypeDeclType(Decl: Type); |
180 | return Context.hasSameUnqualifiedType(T1: T, T2: SearchType); |
181 | }; |
182 | |
183 | unsigned NumAcceptableResults = 0; |
184 | for (NamedDecl *D : Found) { |
185 | if (IsAcceptableResult(D)) |
186 | ++NumAcceptableResults; |
187 | |
188 | // Don't list a class twice in the lookup failure diagnostic if it's |
189 | // found by both its injected-class-name and by the name in the enclosing |
190 | // scope. |
191 | if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) |
192 | if (RD->isInjectedClassName()) |
193 | D = cast<NamedDecl>(RD->getParent()); |
194 | |
195 | if (FoundDeclSet.insert(D).second) |
196 | FoundDecls.push_back(Elt: D); |
197 | } |
198 | |
199 | // As an extension, attempt to "fix" an ambiguity by erasing all non-type |
200 | // results, and all non-matching results if we have a search type. It's not |
201 | // clear what the right behavior is if destructor lookup hits an ambiguity, |
202 | // but other compilers do generally accept at least some kinds of |
203 | // ambiguity. |
204 | if (Found.isAmbiguous() && NumAcceptableResults == 1) { |
205 | Diag(NameLoc, diag::ext_dtor_name_ambiguous); |
206 | LookupResult::Filter F = Found.makeFilter(); |
207 | while (F.hasNext()) { |
208 | NamedDecl *D = F.next(); |
209 | if (auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl())) |
210 | Diag(D->getLocation(), diag::note_destructor_type_here) |
211 | << Context.getTypeDeclType(TD); |
212 | else |
213 | Diag(D->getLocation(), diag::note_destructor_nontype_here); |
214 | |
215 | if (!IsAcceptableResult(D)) |
216 | F.erase(); |
217 | } |
218 | F.done(); |
219 | } |
220 | |
221 | if (Found.isAmbiguous()) |
222 | Failed = true; |
223 | |
224 | if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) { |
225 | if (IsAcceptableResult(Type)) { |
226 | QualType T = Context.getTypeDeclType(Decl: Type); |
227 | MarkAnyDeclReferenced(Loc: Type->getLocation(), D: Type, /*OdrUse=*/MightBeOdrUse: false); |
228 | return CreateParsedType( |
229 | T: Context.getElaboratedType(Keyword: ElaboratedTypeKeyword::None, NNS: nullptr, NamedType: T), |
230 | TInfo: Context.getTrivialTypeSourceInfo(T, Loc: NameLoc)); |
231 | } |
232 | } |
233 | |
234 | return nullptr; |
235 | }; |
236 | |
237 | bool IsDependent = false; |
238 | |
239 | auto LookupInObjectType = [&]() -> ParsedType { |
240 | if (Failed || SearchType.isNull()) |
241 | return nullptr; |
242 | |
243 | IsDependent |= SearchType->isDependentType(); |
244 | |
245 | LookupResult Found(*this, &II, NameLoc, LookupDestructorName); |
246 | DeclContext *LookupCtx = computeDeclContext(T: SearchType); |
247 | if (!LookupCtx) |
248 | return nullptr; |
249 | LookupQualifiedName(R&: Found, LookupCtx); |
250 | return CheckLookupResult(Found); |
251 | }; |
252 | |
253 | auto LookupInNestedNameSpec = [&](CXXScopeSpec &LookupSS) -> ParsedType { |
254 | if (Failed) |
255 | return nullptr; |
256 | |
257 | IsDependent |= isDependentScopeSpecifier(SS: LookupSS); |
258 | DeclContext *LookupCtx = computeDeclContext(SS: LookupSS, EnteringContext); |
259 | if (!LookupCtx) |
260 | return nullptr; |
261 | |
262 | LookupResult Found(*this, &II, NameLoc, LookupDestructorName); |
263 | if (RequireCompleteDeclContext(SS&: LookupSS, DC: LookupCtx)) { |
264 | Failed = true; |
265 | return nullptr; |
266 | } |
267 | LookupQualifiedName(R&: Found, LookupCtx); |
268 | return CheckLookupResult(Found); |
269 | }; |
270 | |
271 | auto LookupInScope = [&]() -> ParsedType { |
272 | if (Failed || !S) |
273 | return nullptr; |
274 | |
275 | LookupResult Found(*this, &II, NameLoc, LookupDestructorName); |
276 | LookupName(R&: Found, S); |
277 | return CheckLookupResult(Found); |
278 | }; |
279 | |
280 | // C++2a [basic.lookup.qual]p6: |
281 | // In a qualified-id of the form |
282 | // |
283 | // nested-name-specifier[opt] type-name :: ~ type-name |
284 | // |
285 | // the second type-name is looked up in the same scope as the first. |
286 | // |
287 | // We interpret this as meaning that if you do a dual-scope lookup for the |
288 | // first name, you also do a dual-scope lookup for the second name, per |
289 | // C++ [basic.lookup.classref]p4: |
290 | // |
291 | // If the id-expression in a class member access is a qualified-id of the |
292 | // form |
293 | // |
294 | // class-name-or-namespace-name :: ... |
295 | // |
296 | // the class-name-or-namespace-name following the . or -> is first looked |
297 | // up in the class of the object expression and the name, if found, is used. |
298 | // Otherwise, it is looked up in the context of the entire |
299 | // postfix-expression. |
300 | // |
301 | // This looks in the same scopes as for an unqualified destructor name: |
302 | // |
303 | // C++ [basic.lookup.classref]p3: |
304 | // If the unqualified-id is ~ type-name, the type-name is looked up |
305 | // in the context of the entire postfix-expression. If the type T |
306 | // of the object expression is of a class type C, the type-name is |
307 | // also looked up in the scope of class C. At least one of the |
308 | // lookups shall find a name that refers to cv T. |
309 | // |
310 | // FIXME: The intent is unclear here. Should type-name::~type-name look in |
311 | // the scope anyway if it finds a non-matching name declared in the class? |
312 | // If both lookups succeed and find a dependent result, which result should |
313 | // we retain? (Same question for p->~type-name().) |
314 | |
315 | if (NestedNameSpecifier *Prefix = |
316 | SS.isSet() ? SS.getScopeRep()->getPrefix() : nullptr) { |
317 | // This is |
318 | // |
319 | // nested-name-specifier type-name :: ~ type-name |
320 | // |
321 | // Look for the second type-name in the nested-name-specifier. |
322 | CXXScopeSpec PrefixSS; |
323 | PrefixSS.Adopt(Other: NestedNameSpecifierLoc(Prefix, SS.location_data())); |
324 | if (ParsedType T = LookupInNestedNameSpec(PrefixSS)) |
325 | return T; |
326 | } else { |
327 | // This is one of |
328 | // |
329 | // type-name :: ~ type-name |
330 | // ~ type-name |
331 | // |
332 | // Look in the scope and (if any) the object type. |
333 | if (ParsedType T = LookupInScope()) |
334 | return T; |
335 | if (ParsedType T = LookupInObjectType()) |
336 | return T; |
337 | } |
338 | |
339 | if (Failed) |
340 | return nullptr; |
341 | |
342 | if (IsDependent) { |
343 | // We didn't find our type, but that's OK: it's dependent anyway. |
344 | |
345 | // FIXME: What if we have no nested-name-specifier? |
346 | TypeSourceInfo *TSI = nullptr; |
347 | QualType T = |
348 | CheckTypenameType(Keyword: ElaboratedTypeKeyword::None, KeywordLoc: SourceLocation(), |
349 | QualifierLoc: SS.getWithLocInContext(Context), II, IILoc: NameLoc, TSI: &TSI, |
350 | /*DeducedTSTContext=*/true); |
351 | return CreateParsedType(T, TInfo: TSI); |
352 | } |
353 | |
354 | // The remaining cases are all non-standard extensions imitating the behavior |
355 | // of various other compilers. |
356 | unsigned NumNonExtensionDecls = FoundDecls.size(); |
357 | |
358 | if (SS.isSet()) { |
359 | // For compatibility with older broken C++ rules and existing code, |
360 | // |
361 | // nested-name-specifier :: ~ type-name |
362 | // |
363 | // also looks for type-name within the nested-name-specifier. |
364 | if (ParsedType T = LookupInNestedNameSpec(SS)) { |
365 | Diag(SS.getEndLoc(), diag::ext_dtor_named_in_wrong_scope) |
366 | << SS.getRange() |
367 | << FixItHint::CreateInsertion(SS.getEndLoc(), |
368 | ("::"+ II.getName()).str()); |
369 | return T; |
370 | } |
371 | |
372 | // For compatibility with other compilers and older versions of Clang, |
373 | // |
374 | // nested-name-specifier type-name :: ~ type-name |
375 | // |
376 | // also looks for type-name in the scope. Unfortunately, we can't |
377 | // reasonably apply this fallback for dependent nested-name-specifiers. |
378 | if (SS.isValid() && SS.getScopeRep()->getPrefix()) { |
379 | if (ParsedType T = LookupInScope()) { |
380 | Diag(SS.getEndLoc(), diag::ext_qualified_dtor_named_in_lexical_scope) |
381 | << FixItHint::CreateRemoval(SS.getRange()); |
382 | Diag(FoundDecls.back()->getLocation(), diag::note_destructor_type_here) |
383 | << GetTypeFromParser(T); |
384 | return T; |
385 | } |
386 | } |
387 | } |
388 | |
389 | // We didn't find anything matching; tell the user what we did find (if |
390 | // anything). |
391 | |
392 | // Don't tell the user about declarations we shouldn't have found. |
393 | FoundDecls.resize(N: NumNonExtensionDecls); |
394 | |
395 | // List types before non-types. |
396 | llvm::stable_sort(Range&: FoundDecls, C: [](NamedDecl *A, NamedDecl *B) { |
397 | return isa<TypeDecl>(Val: A->getUnderlyingDecl()) > |
398 | isa<TypeDecl>(Val: B->getUnderlyingDecl()); |
399 | }); |
400 | |
401 | // Suggest a fixit to properly name the destroyed type. |
402 | auto MakeFixItHint = [&]{ |
403 | const CXXRecordDecl *Destroyed = nullptr; |
404 | // FIXME: If we have a scope specifier, suggest its last component? |
405 | if (!SearchType.isNull()) |
406 | Destroyed = SearchType->getAsCXXRecordDecl(); |
407 | else if (S) |
408 | Destroyed = dyn_cast_or_null<CXXRecordDecl>(Val: S->getEntity()); |
409 | if (Destroyed) |
410 | return FixItHint::CreateReplacement(SourceRange(NameLoc), |
411 | Destroyed->getNameAsString()); |
412 | return FixItHint(); |
413 | }; |
414 | |
415 | if (FoundDecls.empty()) { |
416 | // FIXME: Attempt typo-correction? |
417 | Diag(NameLoc, diag::err_undeclared_destructor_name) |
418 | << &II << MakeFixItHint(); |
419 | } else if (!SearchType.isNull() && FoundDecls.size() == 1) { |
420 | if (auto *TD = dyn_cast<TypeDecl>(Val: FoundDecls[0]->getUnderlyingDecl())) { |
421 | assert(!SearchType.isNull() && |
422 | "should only reject a type result if we have a search type"); |
423 | QualType T = Context.getTypeDeclType(Decl: TD); |
424 | Diag(NameLoc, diag::err_destructor_expr_type_mismatch) |
425 | << T << SearchType << MakeFixItHint(); |
426 | } else { |
427 | Diag(NameLoc, diag::err_destructor_expr_nontype) |
428 | << &II << MakeFixItHint(); |
429 | } |
430 | } else { |
431 | Diag(NameLoc, SearchType.isNull() ? diag::err_destructor_name_nontype |
432 | : diag::err_destructor_expr_mismatch) |
433 | << &II << SearchType << MakeFixItHint(); |
434 | } |
435 | |
436 | for (NamedDecl *FoundD : FoundDecls) { |
437 | if (auto *TD = dyn_cast<TypeDecl>(FoundD->getUnderlyingDecl())) |
438 | Diag(FoundD->getLocation(), diag::note_destructor_type_here) |
439 | << Context.getTypeDeclType(TD); |
440 | else |
441 | Diag(FoundD->getLocation(), diag::note_destructor_nontype_here) |
442 | << FoundD; |
443 | } |
444 | |
445 | return nullptr; |
446 | } |
447 | |
448 | ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS, |
449 | ParsedType ObjectType) { |
450 | if (DS.getTypeSpecType() == DeclSpec::TST_error) |
451 | return nullptr; |
452 | |
453 | if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) { |
454 | Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); |
455 | return nullptr; |
456 | } |
457 | |
458 | assert(DS.getTypeSpecType() == DeclSpec::TST_decltype && |
459 | "unexpected type in getDestructorType"); |
460 | QualType T = BuildDecltypeType(E: DS.getRepAsExpr()); |
461 | |
462 | // If we know the type of the object, check that the correct destructor |
463 | // type was named now; we can give better diagnostics this way. |
464 | QualType SearchType = GetTypeFromParser(Ty: ObjectType); |
465 | if (!SearchType.isNull() && !SearchType->isDependentType() && |
466 | !Context.hasSameUnqualifiedType(T1: T, T2: SearchType)) { |
467 | Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch) |
468 | << T << SearchType; |
469 | return nullptr; |
470 | } |
471 | |
472 | return ParsedType::make(P: T); |
473 | } |
474 | |
475 | bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS, |
476 | const UnqualifiedId &Name, bool IsUDSuffix) { |
477 | assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId); |
478 | if (!IsUDSuffix) { |
479 | // [over.literal] p8 |
480 | // |
481 | // double operator""_Bq(long double); // OK: not a reserved identifier |
482 | // double operator"" _Bq(long double); // ill-formed, no diagnostic required |
483 | const IdentifierInfo *II = Name.Identifier; |
484 | ReservedIdentifierStatus Status = II->isReserved(LangOpts: PP.getLangOpts()); |
485 | SourceLocation Loc = Name.getEndLoc(); |
486 | |
487 | auto Hint = FixItHint::CreateReplacement( |
488 | RemoveRange: Name.getSourceRange(), |
489 | Code: (StringRef("operator\"\"") + II->getName()).str()); |
490 | |
491 | // Only emit this diagnostic if we start with an underscore, else the |
492 | // diagnostic for C++11 requiring a space between the quotes and the |
493 | // identifier conflicts with this and gets confusing. The diagnostic stating |
494 | // this is a reserved name should force the underscore, which gets this |
495 | // back. |
496 | if (II->isReservedLiteralSuffixId() != |
497 | ReservedLiteralSuffixIdStatus::NotStartsWithUnderscore) |
498 | Diag(Loc, diag::warn_deprecated_literal_operator_id) << II << Hint; |
499 | |
500 | if (isReservedInAllContexts(Status)) |
501 | Diag(Loc, diag::warn_reserved_extern_symbol) |
502 | << II << static_cast<int>(Status) << Hint; |
503 | } |
504 | |
505 | if (!SS.isValid()) |
506 | return false; |
507 | |
508 | switch (SS.getScopeRep()->getKind()) { |
509 | case NestedNameSpecifier::Identifier: |
510 | case NestedNameSpecifier::TypeSpec: |
511 | // Per C++11 [over.literal]p2, literal operators can only be declared at |
512 | // namespace scope. Therefore, this unqualified-id cannot name anything. |
513 | // Reject it early, because we have no AST representation for this in the |
514 | // case where the scope is dependent. |
515 | Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace) |
516 | << SS.getScopeRep(); |
517 | return true; |
518 | |
519 | case NestedNameSpecifier::Global: |
520 | case NestedNameSpecifier::Super: |
521 | case NestedNameSpecifier::Namespace: |
522 | case NestedNameSpecifier::NamespaceAlias: |
523 | return false; |
524 | } |
525 | |
526 | llvm_unreachable("unknown nested name specifier kind"); |
527 | } |
528 | |
529 | ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, |
530 | SourceLocation TypeidLoc, |
531 | TypeSourceInfo *Operand, |
532 | SourceLocation RParenLoc) { |
533 | // C++ [expr.typeid]p4: |
534 | // The top-level cv-qualifiers of the lvalue expression or the type-id |
535 | // that is the operand of typeid are always ignored. |
536 | // If the type of the type-id is a class type or a reference to a class |
537 | // type, the class shall be completely-defined. |
538 | Qualifiers Quals; |
539 | QualType T |
540 | = Context.getUnqualifiedArrayType(T: Operand->getType().getNonReferenceType(), |
541 | Quals); |
542 | if (T->getAs<RecordType>() && |
543 | RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) |
544 | return ExprError(); |
545 | |
546 | if (T->isVariablyModifiedType()) |
547 | return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T); |
548 | |
549 | if (CheckQualifiedFunctionForTypeId(T, Loc: TypeidLoc)) |
550 | return ExprError(); |
551 | |
552 | return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand, |
553 | SourceRange(TypeidLoc, RParenLoc)); |
554 | } |
555 | |
556 | ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, |
557 | SourceLocation TypeidLoc, |
558 | Expr *E, |
559 | SourceLocation RParenLoc) { |
560 | bool WasEvaluated = false; |
561 | if (E && !E->isTypeDependent()) { |
562 | if (E->hasPlaceholderType()) { |
563 | ExprResult result = CheckPlaceholderExpr(E); |
564 | if (result.isInvalid()) return ExprError(); |
565 | E = result.get(); |
566 | } |
567 | |
568 | QualType T = E->getType(); |
569 | if (const RecordType *RecordT = T->getAs<RecordType>()) { |
570 | CXXRecordDecl *RecordD = cast<CXXRecordDecl>(Val: RecordT->getDecl()); |
571 | // C++ [expr.typeid]p3: |
572 | // [...] If the type of the expression is a class type, the class |
573 | // shall be completely-defined. |
574 | if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) |
575 | return ExprError(); |
576 | |
577 | // C++ [expr.typeid]p3: |
578 | // When typeid is applied to an expression other than an glvalue of a |
579 | // polymorphic class type [...] [the] expression is an unevaluated |
580 | // operand. [...] |
581 | if (RecordD->isPolymorphic() && E->isGLValue()) { |
582 | if (isUnevaluatedContext()) { |
583 | // The operand was processed in unevaluated context, switch the |
584 | // context and recheck the subexpression. |
585 | ExprResult Result = TransformToPotentiallyEvaluated(E); |
586 | if (Result.isInvalid()) |
587 | return ExprError(); |
588 | E = Result.get(); |
589 | } |
590 | |
591 | // We require a vtable to query the type at run time. |
592 | MarkVTableUsed(Loc: TypeidLoc, Class: RecordD); |
593 | WasEvaluated = true; |
594 | } |
595 | } |
596 | |
597 | ExprResult Result = CheckUnevaluatedOperand(E); |
598 | if (Result.isInvalid()) |
599 | return ExprError(); |
600 | E = Result.get(); |
601 | |
602 | // C++ [expr.typeid]p4: |
603 | // [...] If the type of the type-id is a reference to a possibly |
604 | // cv-qualified type, the result of the typeid expression refers to a |
605 | // std::type_info object representing the cv-unqualified referenced |
606 | // type. |
607 | Qualifiers Quals; |
608 | QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals); |
609 | if (!Context.hasSameType(T1: T, T2: UnqualT)) { |
610 | T = UnqualT; |
611 | E = ImpCastExprToType(E, Type: UnqualT, CK: CK_NoOp, VK: E->getValueKind()).get(); |
612 | } |
613 | } |
614 | |
615 | if (E->getType()->isVariablyModifiedType()) |
616 | return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) |
617 | << E->getType()); |
618 | else if (!inTemplateInstantiation() && |
619 | E->HasSideEffects(Ctx: Context, IncludePossibleEffects: WasEvaluated)) { |
620 | // The expression operand for typeid is in an unevaluated expression |
621 | // context, so side effects could result in unintended consequences. |
622 | Diag(E->getExprLoc(), WasEvaluated |
623 | ? diag::warn_side_effects_typeid |
624 | : diag::warn_side_effects_unevaluated_context); |
625 | } |
626 | |
627 | return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E, |
628 | SourceRange(TypeidLoc, RParenLoc)); |
629 | } |
630 | |
631 | /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression); |
632 | ExprResult |
633 | Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, |
634 | bool isType, void *TyOrExpr, SourceLocation RParenLoc) { |
635 | // typeid is not supported in OpenCL. |
636 | if (getLangOpts().OpenCLCPlusPlus) { |
637 | return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported) |
638 | << "typeid"); |
639 | } |
640 | |
641 | // Find the std::type_info type. |
642 | if (!getStdNamespace()) |
643 | return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); |
644 | |
645 | if (!CXXTypeInfoDecl) { |
646 | IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get(Name: "type_info"); |
647 | LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName); |
648 | LookupQualifiedName(R, getStdNamespace()); |
649 | CXXTypeInfoDecl = R.getAsSingle<RecordDecl>(); |
650 | // Microsoft's typeinfo doesn't have type_info in std but in the global |
651 | // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153. |
652 | if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) { |
653 | LookupQualifiedName(R, Context.getTranslationUnitDecl()); |
654 | CXXTypeInfoDecl = R.getAsSingle<RecordDecl>(); |
655 | } |
656 | if (!CXXTypeInfoDecl) |
657 | return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); |
658 | } |
659 | |
660 | if (!getLangOpts().RTTI) { |
661 | return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti)); |
662 | } |
663 | |
664 | QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl); |
665 | |
666 | if (isType) { |
667 | // The operand is a type; handle it as such. |
668 | TypeSourceInfo *TInfo = nullptr; |
669 | QualType T = GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: TyOrExpr), |
670 | TInfo: &TInfo); |
671 | if (T.isNull()) |
672 | return ExprError(); |
673 | |
674 | if (!TInfo) |
675 | TInfo = Context.getTrivialTypeSourceInfo(T, Loc: OpLoc); |
676 | |
677 | return BuildCXXTypeId(TypeInfoType, TypeidLoc: OpLoc, Operand: TInfo, RParenLoc); |
678 | } |
679 | |
680 | // The operand is an expression. |
681 | ExprResult Result = |
682 | BuildCXXTypeId(TypeInfoType, TypeidLoc: OpLoc, E: (Expr *)TyOrExpr, RParenLoc); |
683 | |
684 | if (!getLangOpts().RTTIData && !Result.isInvalid()) |
685 | if (auto *CTE = dyn_cast<CXXTypeidExpr>(Result.get())) |
686 | if (CTE->isPotentiallyEvaluated() && !CTE->isMostDerived(Context)) |
687 | Diag(OpLoc, diag::warn_no_typeid_with_rtti_disabled) |
688 | << (getDiagnostics().getDiagnosticOptions().getFormat() == |
689 | DiagnosticOptions::MSVC); |
690 | return Result; |
691 | } |
692 | |
693 | /// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to |
694 | /// a single GUID. |
695 | static void |
696 | getUuidAttrOfType(Sema &SemaRef, QualType QT, |
697 | llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) { |
698 | // Optionally remove one level of pointer, reference or array indirection. |
699 | const Type *Ty = QT.getTypePtr(); |
700 | if (QT->isPointerOrReferenceType()) |
701 | Ty = QT->getPointeeType().getTypePtr(); |
702 | else if (QT->isArrayType()) |
703 | Ty = Ty->getBaseElementTypeUnsafe(); |
704 | |
705 | const auto *TD = Ty->getAsTagDecl(); |
706 | if (!TD) |
707 | return; |
708 | |
709 | if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) { |
710 | UuidAttrs.insert(Uuid); |
711 | return; |
712 | } |
713 | |
714 | // __uuidof can grab UUIDs from template arguments. |
715 | if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: TD)) { |
716 | const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); |
717 | for (const TemplateArgument &TA : TAL.asArray()) { |
718 | const UuidAttr *UuidForTA = nullptr; |
719 | if (TA.getKind() == TemplateArgument::Type) |
720 | getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs); |
721 | else if (TA.getKind() == TemplateArgument::Declaration) |
722 | getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs); |
723 | |
724 | if (UuidForTA) |
725 | UuidAttrs.insert(UuidForTA); |
726 | } |
727 | } |
728 | } |
729 | |
730 | ExprResult Sema::BuildCXXUuidof(QualType Type, |
731 | SourceLocation TypeidLoc, |
732 | TypeSourceInfo *Operand, |
733 | SourceLocation RParenLoc) { |
734 | MSGuidDecl *Guid = nullptr; |
735 | if (!Operand->getType()->isDependentType()) { |
736 | llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs; |
737 | getUuidAttrOfType(*this, Operand->getType(), UuidAttrs); |
738 | if (UuidAttrs.empty()) |
739 | return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid)); |
740 | if (UuidAttrs.size() > 1) |
741 | return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids)); |
742 | Guid = UuidAttrs.back()->getGuidDecl(); |
743 | } |
744 | |
745 | return new (Context) |
746 | CXXUuidofExpr(Type, Operand, Guid, SourceRange(TypeidLoc, RParenLoc)); |
747 | } |
748 | |
749 | ExprResult Sema::BuildCXXUuidof(QualType Type, SourceLocation TypeidLoc, |
750 | Expr *E, SourceLocation RParenLoc) { |
751 | MSGuidDecl *Guid = nullptr; |
752 | if (!E->getType()->isDependentType()) { |
753 | if (E->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull)) { |
754 | // A null pointer results in {00000000-0000-0000-0000-000000000000}. |
755 | Guid = Context.getMSGuidDecl(Parts: MSGuidDecl::Parts{}); |
756 | } else { |
757 | llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs; |
758 | getUuidAttrOfType(*this, E->getType(), UuidAttrs); |
759 | if (UuidAttrs.empty()) |
760 | return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid)); |
761 | if (UuidAttrs.size() > 1) |
762 | return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids)); |
763 | Guid = UuidAttrs.back()->getGuidDecl(); |
764 | } |
765 | } |
766 | |
767 | return new (Context) |
768 | CXXUuidofExpr(Type, E, Guid, SourceRange(TypeidLoc, RParenLoc)); |
769 | } |
770 | |
771 | /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression); |
772 | ExprResult |
773 | Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, |
774 | bool isType, void *TyOrExpr, SourceLocation RParenLoc) { |
775 | QualType GuidType = Context.getMSGuidType(); |
776 | GuidType.addConst(); |
777 | |
778 | if (isType) { |
779 | // The operand is a type; handle it as such. |
780 | TypeSourceInfo *TInfo = nullptr; |
781 | QualType T = GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: TyOrExpr), |
782 | TInfo: &TInfo); |
783 | if (T.isNull()) |
784 | return ExprError(); |
785 | |
786 | if (!TInfo) |
787 | TInfo = Context.getTrivialTypeSourceInfo(T, Loc: OpLoc); |
788 | |
789 | return BuildCXXUuidof(Type: GuidType, TypeidLoc: OpLoc, Operand: TInfo, RParenLoc); |
790 | } |
791 | |
792 | // The operand is an expression. |
793 | return BuildCXXUuidof(Type: GuidType, TypeidLoc: OpLoc, E: (Expr*)TyOrExpr, RParenLoc); |
794 | } |
795 | |
796 | ExprResult |
797 | Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { |
798 | assert((Kind == tok::kw_true || Kind == tok::kw_false) && |
799 | "Unknown C++ Boolean value!"); |
800 | return new (Context) |
801 | CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc); |
802 | } |
803 | |
804 | ExprResult |
805 | Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) { |
806 | return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc); |
807 | } |
808 | |
809 | ExprResult |
810 | Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) { |
811 | bool IsThrownVarInScope = false; |
812 | if (Ex) { |
813 | // C++0x [class.copymove]p31: |
814 | // When certain criteria are met, an implementation is allowed to omit the |
815 | // copy/move construction of a class object [...] |
816 | // |
817 | // - in a throw-expression, when the operand is the name of a |
818 | // non-volatile automatic object (other than a function or catch- |
819 | // clause parameter) whose scope does not extend beyond the end of the |
820 | // innermost enclosing try-block (if there is one), the copy/move |
821 | // operation from the operand to the exception object (15.1) can be |
822 | // omitted by constructing the automatic object directly into the |
823 | // exception object |
824 | if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: Ex->IgnoreParens())) |
825 | if (const auto *Var = dyn_cast<VarDecl>(Val: DRE->getDecl()); |
826 | Var && Var->hasLocalStorage() && |
827 | !Var->getType().isVolatileQualified()) { |
828 | for (; S; S = S->getParent()) { |
829 | if (S->isDeclScope(Var)) { |
830 | IsThrownVarInScope = true; |
831 | break; |
832 | } |
833 | |
834 | // FIXME: Many of the scope checks here seem incorrect. |
835 | if (S->getFlags() & |
836 | (Scope::FnScope | Scope::ClassScope | Scope::BlockScope | |
837 | Scope::ObjCMethodScope | Scope::TryScope)) |
838 | break; |
839 | } |
840 | } |
841 | } |
842 | |
843 | return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope); |
844 | } |
845 | |
846 | ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, |
847 | bool IsThrownVarInScope) { |
848 | const llvm::Triple &T = Context.getTargetInfo().getTriple(); |
849 | const bool IsOpenMPGPUTarget = |
850 | getLangOpts().OpenMPIsTargetDevice && (T.isNVPTX() || T.isAMDGCN()); |
851 | |
852 | DiagnoseExceptionUse(Loc: OpLoc, /* IsTry= */ false); |
853 | |
854 | // In OpenMP target regions, we replace 'throw' with a trap on GPU targets. |
855 | if (IsOpenMPGPUTarget) |
856 | targetDiag(OpLoc, diag::warn_throw_not_valid_on_target) << T.str(); |
857 | |
858 | // Exceptions aren't allowed in CUDA device code. |
859 | if (getLangOpts().CUDA) |
860 | CUDA().DiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions) |
861 | << "throw"<< CUDA().CurrentTarget(); |
862 | |
863 | if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope()) |
864 | Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw"; |
865 | |
866 | // Exceptions that escape a compute construct are ill-formed. |
867 | if (getLangOpts().OpenACC && getCurScope() && |
868 | getCurScope()->isInOpenACCComputeConstructScope(Scope::TryScope)) |
869 | Diag(OpLoc, diag::err_acc_branch_in_out_compute_construct) |
870 | << /*throw*/ 2 << /*out of*/ 0; |
871 | |
872 | if (Ex && !Ex->isTypeDependent()) { |
873 | // Initialize the exception result. This implicitly weeds out |
874 | // abstract types or types with inaccessible copy constructors. |
875 | |
876 | // C++0x [class.copymove]p31: |
877 | // When certain criteria are met, an implementation is allowed to omit the |
878 | // copy/move construction of a class object [...] |
879 | // |
880 | // - in a throw-expression, when the operand is the name of a |
881 | // non-volatile automatic object (other than a function or |
882 | // catch-clause |
883 | // parameter) whose scope does not extend beyond the end of the |
884 | // innermost enclosing try-block (if there is one), the copy/move |
885 | // operation from the operand to the exception object (15.1) can be |
886 | // omitted by constructing the automatic object directly into the |
887 | // exception object |
888 | NamedReturnInfo NRInfo = |
889 | IsThrownVarInScope ? getNamedReturnInfo(E&: Ex) : NamedReturnInfo(); |
890 | |
891 | QualType ExceptionObjectTy = Context.getExceptionObjectType(T: Ex->getType()); |
892 | if (CheckCXXThrowOperand(ThrowLoc: OpLoc, ThrowTy: ExceptionObjectTy, E: Ex)) |
893 | return ExprError(); |
894 | |
895 | InitializedEntity Entity = |
896 | InitializedEntity::InitializeException(ThrowLoc: OpLoc, Type: ExceptionObjectTy); |
897 | ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRInfo, Value: Ex); |
898 | if (Res.isInvalid()) |
899 | return ExprError(); |
900 | Ex = Res.get(); |
901 | } |
902 | |
903 | // PPC MMA non-pointer types are not allowed as throw expr types. |
904 | if (Ex && Context.getTargetInfo().getTriple().isPPC64()) |
905 | PPC().CheckPPCMMAType(Type: Ex->getType(), TypeLoc: Ex->getBeginLoc()); |
906 | |
907 | return new (Context) |
908 | CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope); |
909 | } |
910 | |
911 | static void |
912 | collectPublicBases(CXXRecordDecl *RD, |
913 | llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen, |
914 | llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases, |
915 | llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen, |
916 | bool ParentIsPublic) { |
917 | for (const CXXBaseSpecifier &BS : RD->bases()) { |
918 | CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); |
919 | bool NewSubobject; |
920 | // Virtual bases constitute the same subobject. Non-virtual bases are |
921 | // always distinct subobjects. |
922 | if (BS.isVirtual()) |
923 | NewSubobject = VBases.insert(Ptr: BaseDecl).second; |
924 | else |
925 | NewSubobject = true; |
926 | |
927 | if (NewSubobject) |
928 | ++SubobjectsSeen[BaseDecl]; |
929 | |
930 | // Only add subobjects which have public access throughout the entire chain. |
931 | bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public; |
932 | if (PublicPath) |
933 | PublicSubobjectsSeen.insert(X: BaseDecl); |
934 | |
935 | // Recurse on to each base subobject. |
936 | collectPublicBases(RD: BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen, |
937 | ParentIsPublic: PublicPath); |
938 | } |
939 | } |
940 | |
941 | static void getUnambiguousPublicSubobjects( |
942 | CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) { |
943 | llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen; |
944 | llvm::SmallSet<CXXRecordDecl *, 2> VBases; |
945 | llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen; |
946 | SubobjectsSeen[RD] = 1; |
947 | PublicSubobjectsSeen.insert(X: RD); |
948 | collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen, |
949 | /*ParentIsPublic=*/true); |
950 | |
951 | for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) { |
952 | // Skip ambiguous objects. |
953 | if (SubobjectsSeen[PublicSubobject] > 1) |
954 | continue; |
955 | |
956 | Objects.push_back(Elt: PublicSubobject); |
957 | } |
958 | } |
959 | |
960 | bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, |
961 | QualType ExceptionObjectTy, Expr *E) { |
962 | // If the type of the exception would be an incomplete type or a pointer |
963 | // to an incomplete type other than (cv) void the program is ill-formed. |
964 | QualType Ty = ExceptionObjectTy; |
965 | bool isPointer = false; |
966 | if (const PointerType* Ptr = Ty->getAs<PointerType>()) { |
967 | Ty = Ptr->getPointeeType(); |
968 | isPointer = true; |
969 | } |
970 | |
971 | // Cannot throw WebAssembly reference type. |
972 | if (Ty.isWebAssemblyReferenceType()) { |
973 | Diag(ThrowLoc, diag::err_wasm_reftype_tc) << 0 << E->getSourceRange(); |
974 | return true; |
975 | } |
976 | |
977 | // Cannot throw WebAssembly table. |
978 | if (isPointer && Ty.isWebAssemblyReferenceType()) { |
979 | Diag(ThrowLoc, diag::err_wasm_table_art) << 2 << E->getSourceRange(); |
980 | return true; |
981 | } |
982 | |
983 | if (!isPointer || !Ty->isVoidType()) { |
984 | if (RequireCompleteType(ThrowLoc, Ty, |
985 | isPointer ? diag::err_throw_incomplete_ptr |
986 | : diag::err_throw_incomplete, |
987 | E->getSourceRange())) |
988 | return true; |
989 | |
990 | if (!isPointer && Ty->isSizelessType()) { |
991 | Diag(ThrowLoc, diag::err_throw_sizeless) << Ty << E->getSourceRange(); |
992 | return true; |
993 | } |
994 | |
995 | if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy, |
996 | diag::err_throw_abstract_type, E)) |
997 | return true; |
998 | } |
999 | |
1000 | // If the exception has class type, we need additional handling. |
1001 | CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); |
1002 | if (!RD) |
1003 | return false; |
1004 | |
1005 | // If we are throwing a polymorphic class type or pointer thereof, |
1006 | // exception handling will make use of the vtable. |
1007 | MarkVTableUsed(Loc: ThrowLoc, Class: RD); |
1008 | |
1009 | // If a pointer is thrown, the referenced object will not be destroyed. |
1010 | if (isPointer) |
1011 | return false; |
1012 | |
1013 | // If the class has a destructor, we must be able to call it. |
1014 | if (!RD->hasIrrelevantDestructor()) { |
1015 | if (CXXDestructorDecl *Destructor = LookupDestructor(Class: RD)) { |
1016 | MarkFunctionReferenced(E->getExprLoc(), Destructor); |
1017 | CheckDestructorAccess(E->getExprLoc(), Destructor, |
1018 | PDiag(diag::err_access_dtor_exception) << Ty); |
1019 | if (DiagnoseUseOfDecl(Destructor, E->getExprLoc())) |
1020 | return true; |
1021 | } |
1022 | } |
1023 | |
1024 | // The MSVC ABI creates a list of all types which can catch the exception |
1025 | // object. This list also references the appropriate copy constructor to call |
1026 | // if the object is caught by value and has a non-trivial copy constructor. |
1027 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { |
1028 | // We are only interested in the public, unambiguous bases contained within |
1029 | // the exception object. Bases which are ambiguous or otherwise |
1030 | // inaccessible are not catchable types. |
1031 | llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects; |
1032 | getUnambiguousPublicSubobjects(RD, Objects&: UnambiguousPublicSubobjects); |
1033 | |
1034 | for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) { |
1035 | // Attempt to lookup the copy constructor. Various pieces of machinery |
1036 | // will spring into action, like template instantiation, which means this |
1037 | // cannot be a simple walk of the class's decls. Instead, we must perform |
1038 | // lookup and overload resolution. |
1039 | CXXConstructorDecl *CD = LookupCopyingConstructor(Class: Subobject, Quals: 0); |
1040 | if (!CD || CD->isDeleted()) |
1041 | continue; |
1042 | |
1043 | // Mark the constructor referenced as it is used by this throw expression. |
1044 | MarkFunctionReferenced(E->getExprLoc(), CD); |
1045 | |
1046 | // Skip this copy constructor if it is trivial, we don't need to record it |
1047 | // in the catchable type data. |
1048 | if (CD->isTrivial()) |
1049 | continue; |
1050 | |
1051 | // The copy constructor is non-trivial, create a mapping from this class |
1052 | // type to this constructor. |
1053 | // N.B. The selection of copy constructor is not sensitive to this |
1054 | // particular throw-site. Lookup will be performed at the catch-site to |
1055 | // ensure that the copy constructor is, in fact, accessible (via |
1056 | // friendship or any other means). |
1057 | Context.addCopyConstructorForExceptionObject(RD: Subobject, CD); |
1058 | |
1059 | // We don't keep the instantiated default argument expressions around so |
1060 | // we must rebuild them here. |
1061 | for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) { |
1062 | if (CheckCXXDefaultArgExpr(CallLoc: ThrowLoc, FD: CD, Param: CD->getParamDecl(I))) |
1063 | return true; |
1064 | } |
1065 | } |
1066 | } |
1067 | |
1068 | // Under the Itanium C++ ABI, memory for the exception object is allocated by |
1069 | // the runtime with no ability for the compiler to request additional |
1070 | // alignment. Warn if the exception type requires alignment beyond the minimum |
1071 | // guaranteed by the target C++ runtime. |
1072 | if (Context.getTargetInfo().getCXXABI().isItaniumFamily()) { |
1073 | CharUnits TypeAlign = Context.getTypeAlignInChars(T: Ty); |
1074 | CharUnits ExnObjAlign = Context.getExnObjectAlignment(); |
1075 | if (ExnObjAlign < TypeAlign) { |
1076 | Diag(ThrowLoc, diag::warn_throw_underaligned_obj); |
1077 | Diag(ThrowLoc, diag::note_throw_underaligned_obj) |
1078 | << Ty << (unsigned)TypeAlign.getQuantity() |
1079 | << (unsigned)ExnObjAlign.getQuantity(); |
1080 | } |
1081 | } |
1082 | if (!isPointer && getLangOpts().AssumeNothrowExceptionDtor) { |
1083 | if (CXXDestructorDecl *Dtor = RD->getDestructor()) { |
1084 | auto Ty = Dtor->getType(); |
1085 | if (auto *FT = Ty.getTypePtr()->getAs<FunctionProtoType>()) { |
1086 | if (!isUnresolvedExceptionSpec(FT->getExceptionSpecType()) && |
1087 | !FT->isNothrow()) |
1088 | Diag(ThrowLoc, diag::err_throw_object_throwing_dtor) << RD; |
1089 | } |
1090 | } |
1091 | } |
1092 | |
1093 | return false; |
1094 | } |
1095 | |
1096 | static QualType adjustCVQualifiersForCXXThisWithinLambda( |
1097 | ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy, |
1098 | DeclContext *CurSemaContext, ASTContext &ASTCtx) { |
1099 | |
1100 | QualType ClassType = ThisTy->getPointeeType(); |
1101 | LambdaScopeInfo *CurLSI = nullptr; |
1102 | DeclContext *CurDC = CurSemaContext; |
1103 | |
1104 | // Iterate through the stack of lambdas starting from the innermost lambda to |
1105 | // the outermost lambda, checking if '*this' is ever captured by copy - since |
1106 | // that could change the cv-qualifiers of the '*this' object. |
1107 | // The object referred to by '*this' starts out with the cv-qualifiers of its |
1108 | // member function. We then start with the innermost lambda and iterate |
1109 | // outward checking to see if any lambda performs a by-copy capture of '*this' |
1110 | // - and if so, any nested lambda must respect the 'constness' of that |
1111 | // capturing lamdbda's call operator. |
1112 | // |
1113 | |
1114 | // Since the FunctionScopeInfo stack is representative of the lexical |
1115 | // nesting of the lambda expressions during initial parsing (and is the best |
1116 | // place for querying information about captures about lambdas that are |
1117 | // partially processed) and perhaps during instantiation of function templates |
1118 | // that contain lambda expressions that need to be transformed BUT not |
1119 | // necessarily during instantiation of a nested generic lambda's function call |
1120 | // operator (which might even be instantiated at the end of the TU) - at which |
1121 | // time the DeclContext tree is mature enough to query capture information |
1122 | // reliably - we use a two pronged approach to walk through all the lexically |
1123 | // enclosing lambda expressions: |
1124 | // |
1125 | // 1) Climb down the FunctionScopeInfo stack as long as each item represents |
1126 | // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically |
1127 | // enclosed by the call-operator of the LSI below it on the stack (while |
1128 | // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on |
1129 | // the stack represents the innermost lambda. |
1130 | // |
1131 | // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext |
1132 | // represents a lambda's call operator. If it does, we must be instantiating |
1133 | // a generic lambda's call operator (represented by the Current LSI, and |
1134 | // should be the only scenario where an inconsistency between the LSI and the |
1135 | // DeclContext should occur), so climb out the DeclContexts if they |
1136 | // represent lambdas, while querying the corresponding closure types |
1137 | // regarding capture information. |
1138 | |
1139 | // 1) Climb down the function scope info stack. |
1140 | for (int I = FunctionScopes.size(); |
1141 | I-- && isa<LambdaScopeInfo>(Val: FunctionScopes[I]) && |
1142 | (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() == |
1143 | cast<LambdaScopeInfo>(Val: FunctionScopes[I])->CallOperator); |
1144 | CurDC = getLambdaAwareParentOfDeclContext(DC: CurDC)) { |
1145 | CurLSI = cast<LambdaScopeInfo>(Val: FunctionScopes[I]); |
1146 | |
1147 | if (!CurLSI->isCXXThisCaptured()) |
1148 | continue; |
1149 | |
1150 | auto C = CurLSI->getCXXThisCapture(); |
1151 | |
1152 | if (C.isCopyCapture()) { |
1153 | if (CurLSI->lambdaCaptureShouldBeConst()) |
1154 | ClassType.addConst(); |
1155 | return ASTCtx.getPointerType(T: ClassType); |
1156 | } |
1157 | } |
1158 | |
1159 | // 2) We've run out of ScopeInfos but check 1. if CurDC is a lambda (which |
1160 | // can happen during instantiation of its nested generic lambda call |
1161 | // operator); 2. if we're in a lambda scope (lambda body). |
1162 | if (CurLSI && isLambdaCallOperator(DC: CurDC)) { |
1163 | assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && |
1164 | "While computing 'this' capture-type for a generic lambda, when we " |
1165 | "run out of enclosing LSI's, yet the enclosing DC is a " |
1166 | "lambda-call-operator we must be (i.e. Current LSI) in a generic " |
1167 | "lambda call oeprator"); |
1168 | assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator)); |
1169 | |
1170 | auto IsThisCaptured = |
1171 | [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) { |
1172 | IsConst = false; |
1173 | IsByCopy = false; |
1174 | for (auto &&C : Closure->captures()) { |
1175 | if (C.capturesThis()) { |
1176 | if (C.getCaptureKind() == LCK_StarThis) |
1177 | IsByCopy = true; |
1178 | if (Closure->getLambdaCallOperator()->isConst()) |
1179 | IsConst = true; |
1180 | return true; |
1181 | } |
1182 | } |
1183 | return false; |
1184 | }; |
1185 | |
1186 | bool IsByCopyCapture = false; |
1187 | bool IsConstCapture = false; |
1188 | CXXRecordDecl *Closure = cast<CXXRecordDecl>(Val: CurDC->getParent()); |
1189 | while (Closure && |
1190 | IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) { |
1191 | if (IsByCopyCapture) { |
1192 | if (IsConstCapture) |
1193 | ClassType.addConst(); |
1194 | return ASTCtx.getPointerType(T: ClassType); |
1195 | } |
1196 | Closure = isLambdaCallOperator(Closure->getParent()) |
1197 | ? cast<CXXRecordDecl>(Closure->getParent()->getParent()) |
1198 | : nullptr; |
1199 | } |
1200 | } |
1201 | return ThisTy; |
1202 | } |
1203 | |
1204 | QualType Sema::getCurrentThisType() { |
1205 | DeclContext *DC = getFunctionLevelDeclContext(); |
1206 | QualType ThisTy = CXXThisTypeOverride; |
1207 | |
1208 | if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(Val: DC)) { |
1209 | if (method && method->isImplicitObjectMemberFunction()) |
1210 | ThisTy = method->getThisType().getNonReferenceType(); |
1211 | } |
1212 | |
1213 | if (ThisTy.isNull() && isLambdaCallWithImplicitObjectParameter(DC: CurContext) && |
1214 | inTemplateInstantiation() && isa<CXXRecordDecl>(Val: DC)) { |
1215 | |
1216 | // This is a lambda call operator that is being instantiated as a default |
1217 | // initializer. DC must point to the enclosing class type, so we can recover |
1218 | // the 'this' type from it. |
1219 | QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(Val: DC)); |
1220 | // There are no cv-qualifiers for 'this' within default initializers, |
1221 | // per [expr.prim.general]p4. |
1222 | ThisTy = Context.getPointerType(T: ClassTy); |
1223 | } |
1224 | |
1225 | // If we are within a lambda's call operator, the cv-qualifiers of 'this' |
1226 | // might need to be adjusted if the lambda or any of its enclosing lambda's |
1227 | // captures '*this' by copy. |
1228 | if (!ThisTy.isNull() && isLambdaCallOperator(DC: CurContext)) |
1229 | return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy, |
1230 | CurSemaContext: CurContext, ASTCtx&: Context); |
1231 | return ThisTy; |
1232 | } |
1233 | |
1234 | Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S, |
1235 | Decl *ContextDecl, |
1236 | Qualifiers CXXThisTypeQuals, |
1237 | bool Enabled) |
1238 | : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false) |
1239 | { |
1240 | if (!Enabled || !ContextDecl) |
1241 | return; |
1242 | |
1243 | CXXRecordDecl *Record = nullptr; |
1244 | if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(Val: ContextDecl)) |
1245 | Record = Template->getTemplatedDecl(); |
1246 | else |
1247 | Record = cast<CXXRecordDecl>(Val: ContextDecl); |
1248 | |
1249 | QualType T = S.Context.getRecordType(Record); |
1250 | T = S.getASTContext().getQualifiedType(T, Qs: CXXThisTypeQuals); |
1251 | |
1252 | S.CXXThisTypeOverride = |
1253 | S.Context.getLangOpts().HLSL ? T : S.Context.getPointerType(T); |
1254 | |
1255 | this->Enabled = true; |
1256 | } |
1257 | |
1258 | |
1259 | Sema::CXXThisScopeRAII::~CXXThisScopeRAII() { |
1260 | if (Enabled) { |
1261 | S.CXXThisTypeOverride = OldCXXThisTypeOverride; |
1262 | } |
1263 | } |
1264 | |
1265 | static void buildLambdaThisCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI) { |
1266 | SourceLocation DiagLoc = LSI->IntroducerRange.getEnd(); |
1267 | assert(!LSI->isCXXThisCaptured()); |
1268 | // [=, this] {}; // until C++20: Error: this when = is the default |
1269 | if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval && |
1270 | !Sema.getLangOpts().CPlusPlus20) |
1271 | return; |
1272 | Sema.Diag(DiagLoc, diag::note_lambda_this_capture_fixit) |
1273 | << FixItHint::CreateInsertion( |
1274 | DiagLoc, LSI->NumExplicitCaptures > 0 ? ", this": "this"); |
1275 | } |
1276 | |
1277 | bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit, |
1278 | bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt, |
1279 | const bool ByCopy) { |
1280 | // We don't need to capture this in an unevaluated context. |
1281 | if (isUnevaluatedContext() && !Explicit) |
1282 | return true; |
1283 | |
1284 | assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value"); |
1285 | |
1286 | const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt |
1287 | ? *FunctionScopeIndexToStopAt |
1288 | : FunctionScopes.size() - 1; |
1289 | |
1290 | // Check that we can capture the *enclosing object* (referred to by '*this') |
1291 | // by the capturing-entity/closure (lambda/block/etc) at |
1292 | // MaxFunctionScopesIndex-deep on the FunctionScopes stack. |
1293 | |
1294 | // Note: The *enclosing object* can only be captured by-value by a |
1295 | // closure that is a lambda, using the explicit notation: |
1296 | // [*this] { ... }. |
1297 | // Every other capture of the *enclosing object* results in its by-reference |
1298 | // capture. |
1299 | |
1300 | // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes |
1301 | // stack), we can capture the *enclosing object* only if: |
1302 | // - 'L' has an explicit byref or byval capture of the *enclosing object* |
1303 | // - or, 'L' has an implicit capture. |
1304 | // AND |
1305 | // -- there is no enclosing closure |
1306 | // -- or, there is some enclosing closure 'E' that has already captured the |
1307 | // *enclosing object*, and every intervening closure (if any) between 'E' |
1308 | // and 'L' can implicitly capture the *enclosing object*. |
1309 | // -- or, every enclosing closure can implicitly capture the |
1310 | // *enclosing object* |
1311 | |
1312 | |
1313 | unsigned NumCapturingClosures = 0; |
1314 | for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) { |
1315 | if (CapturingScopeInfo *CSI = |
1316 | dyn_cast<CapturingScopeInfo>(Val: FunctionScopes[idx])) { |
1317 | if (CSI->CXXThisCaptureIndex != 0) { |
1318 | // 'this' is already being captured; there isn't anything more to do. |
1319 | CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(IsODRUse: BuildAndDiagnose); |
1320 | break; |
1321 | } |
1322 | LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(Val: CSI); |
1323 | if (LSI && isGenericLambdaCallOperatorSpecialization(MD: LSI->CallOperator)) { |
1324 | // This context can't implicitly capture 'this'; fail out. |
1325 | if (BuildAndDiagnose) { |
1326 | LSI->CallOperator->setInvalidDecl(); |
1327 | Diag(Loc, diag::err_this_capture) |
1328 | << (Explicit && idx == MaxFunctionScopesIndex); |
1329 | if (!Explicit) |
1330 | buildLambdaThisCaptureFixit(Sema&: *this, LSI); |
1331 | } |
1332 | return true; |
1333 | } |
1334 | if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref || |
1335 | CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval || |
1336 | CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block || |
1337 | CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion || |
1338 | (Explicit && idx == MaxFunctionScopesIndex)) { |
1339 | // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first |
1340 | // iteration through can be an explicit capture, all enclosing closures, |
1341 | // if any, must perform implicit captures. |
1342 | |
1343 | // This closure can capture 'this'; continue looking upwards. |
1344 | NumCapturingClosures++; |
1345 | continue; |
1346 | } |
1347 | // This context can't implicitly capture 'this'; fail out. |
1348 | if (BuildAndDiagnose) { |
1349 | LSI->CallOperator->setInvalidDecl(); |
1350 | Diag(Loc, diag::err_this_capture) |
1351 | << (Explicit && idx == MaxFunctionScopesIndex); |
1352 | } |
1353 | if (!Explicit) |
1354 | buildLambdaThisCaptureFixit(Sema&: *this, LSI); |
1355 | return true; |
1356 | } |
1357 | break; |
1358 | } |
1359 | if (!BuildAndDiagnose) return false; |
1360 | |
1361 | // If we got here, then the closure at MaxFunctionScopesIndex on the |
1362 | // FunctionScopes stack, can capture the *enclosing object*, so capture it |
1363 | // (including implicit by-reference captures in any enclosing closures). |
1364 | |
1365 | // In the loop below, respect the ByCopy flag only for the closure requesting |
1366 | // the capture (i.e. first iteration through the loop below). Ignore it for |
1367 | // all enclosing closure's up to NumCapturingClosures (since they must be |
1368 | // implicitly capturing the *enclosing object* by reference (see loop |
1369 | // above)). |
1370 | assert((!ByCopy || |
1371 | isa<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && |
1372 | "Only a lambda can capture the enclosing object (referred to by " |
1373 | "*this) by copy"); |
1374 | QualType ThisTy = getCurrentThisType(); |
1375 | for (int idx = MaxFunctionScopesIndex; NumCapturingClosures; |
1376 | --idx, --NumCapturingClosures) { |
1377 | CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(Val: FunctionScopes[idx]); |
1378 | |
1379 | // The type of the corresponding data member (not a 'this' pointer if 'by |
1380 | // copy'). |
1381 | QualType CaptureType = ByCopy ? ThisTy->getPointeeType() : ThisTy; |
1382 | |
1383 | bool isNested = NumCapturingClosures > 1; |
1384 | CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy); |
1385 | } |
1386 | return false; |
1387 | } |
1388 | |
1389 | ExprResult Sema::ActOnCXXThis(SourceLocation Loc) { |
1390 | // C++20 [expr.prim.this]p1: |
1391 | // The keyword this names a pointer to the object for which an |
1392 | // implicit object member function is invoked or a non-static |
1393 | // data member's initializer is evaluated. |
1394 | QualType ThisTy = getCurrentThisType(); |
1395 | |
1396 | if (CheckCXXThisType(Loc, Type: ThisTy)) |
1397 | return ExprError(); |
1398 | |
1399 | return BuildCXXThisExpr(Loc, Type: ThisTy, /*IsImplicit=*/false); |
1400 | } |
1401 | |
1402 | bool Sema::CheckCXXThisType(SourceLocation Loc, QualType Type) { |
1403 | if (!Type.isNull()) |
1404 | return false; |
1405 | |
1406 | // C++20 [expr.prim.this]p3: |
1407 | // If a declaration declares a member function or member function template |
1408 | // of a class X, the expression this is a prvalue of type |
1409 | // "pointer to cv-qualifier-seq X" wherever X is the current class between |
1410 | // the optional cv-qualifier-seq and the end of the function-definition, |
1411 | // member-declarator, or declarator. It shall not appear within the |
1412 | // declaration of either a static member function or an explicit object |
1413 | // member function of the current class (although its type and value |
1414 | // category are defined within such member functions as they are within |
1415 | // an implicit object member function). |
1416 | DeclContext *DC = getFunctionLevelDeclContext(); |
1417 | const auto *Method = dyn_cast<CXXMethodDecl>(Val: DC); |
1418 | if (Method && Method->isExplicitObjectMemberFunction()) { |
1419 | Diag(Loc, diag::err_invalid_this_use) << 1; |
1420 | } else if (Method && isLambdaCallWithExplicitObjectParameter(DC: CurContext)) { |
1421 | Diag(Loc, diag::err_invalid_this_use) << 1; |
1422 | } else { |
1423 | Diag(Loc, diag::err_invalid_this_use) << 0; |
1424 | } |
1425 | return true; |
1426 | } |
1427 | |
1428 | Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type, |
1429 | bool IsImplicit) { |
1430 | auto *This = CXXThisExpr::Create(Ctx: Context, L: Loc, Ty: Type, IsImplicit); |
1431 | MarkThisReferenced(This); |
1432 | return This; |
1433 | } |
1434 | |
1435 | void Sema::MarkThisReferenced(CXXThisExpr *This) { |
1436 | CheckCXXThisCapture(Loc: This->getExprLoc()); |
1437 | if (This->isTypeDependent()) |
1438 | return; |
1439 | |
1440 | // Check if 'this' is captured by value in a lambda with a dependent explicit |
1441 | // object parameter, and mark it as type-dependent as well if so. |
1442 | auto IsDependent = [&]() { |
1443 | for (auto *Scope : llvm::reverse(C&: FunctionScopes)) { |
1444 | auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Val: Scope); |
1445 | if (!LSI) |
1446 | continue; |
1447 | |
1448 | if (LSI->Lambda && !LSI->Lambda->Encloses(CurContext) && |
1449 | LSI->AfterParameterList) |
1450 | return false; |
1451 | |
1452 | // If this lambda captures 'this' by value, then 'this' is dependent iff |
1453 | // this lambda has a dependent explicit object parameter. If we can't |
1454 | // determine whether it does (e.g. because the CXXMethodDecl's type is |
1455 | // null), assume it doesn't. |
1456 | if (LSI->isCXXThisCaptured()) { |
1457 | if (!LSI->getCXXThisCapture().isCopyCapture()) |
1458 | continue; |
1459 | |
1460 | const auto *MD = LSI->CallOperator; |
1461 | if (MD->getType().isNull()) |
1462 | return false; |
1463 | |
1464 | const auto *Ty = MD->getType()->getAs<FunctionProtoType>(); |
1465 | return Ty && MD->isExplicitObjectMemberFunction() && |
1466 | Ty->getParamType(0)->isDependentType(); |
1467 | } |
1468 | } |
1469 | return false; |
1470 | }(); |
1471 | |
1472 | This->setCapturedByCopyInLambdaWithExplicitObjectParameter(IsDependent); |
1473 | } |
1474 | |
1475 | bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) { |
1476 | // If we're outside the body of a member function, then we'll have a specified |
1477 | // type for 'this'. |
1478 | if (CXXThisTypeOverride.isNull()) |
1479 | return false; |
1480 | |
1481 | // Determine whether we're looking into a class that's currently being |
1482 | // defined. |
1483 | CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl(); |
1484 | return Class && Class->isBeingDefined(); |
1485 | } |
1486 | |
1487 | ExprResult |
1488 | Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep, |
1489 | SourceLocation LParenOrBraceLoc, |
1490 | MultiExprArg exprs, |
1491 | SourceLocation RParenOrBraceLoc, |
1492 | bool ListInitialization) { |
1493 | if (!TypeRep) |
1494 | return ExprError(); |
1495 | |
1496 | TypeSourceInfo *TInfo; |
1497 | QualType Ty = GetTypeFromParser(Ty: TypeRep, TInfo: &TInfo); |
1498 | if (!TInfo) |
1499 | TInfo = Context.getTrivialTypeSourceInfo(T: Ty, Loc: SourceLocation()); |
1500 | |
1501 | auto Result = BuildCXXTypeConstructExpr(Type: TInfo, LParenLoc: LParenOrBraceLoc, Exprs: exprs, |
1502 | RParenLoc: RParenOrBraceLoc, ListInitialization); |
1503 | // Avoid creating a non-type-dependent expression that contains typos. |
1504 | // Non-type-dependent expressions are liable to be discarded without |
1505 | // checking for embedded typos. |
1506 | if (!Result.isInvalid() && Result.get()->isInstantiationDependent() && |
1507 | !Result.get()->isTypeDependent()) |
1508 | Result = CorrectDelayedTyposInExpr(E: Result.get()); |
1509 | else if (Result.isInvalid()) |
1510 | Result = CreateRecoveryExpr(Begin: TInfo->getTypeLoc().getBeginLoc(), |
1511 | End: RParenOrBraceLoc, SubExprs: exprs, T: Ty); |
1512 | return Result; |
1513 | } |
1514 | |
1515 | ExprResult |
1516 | Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo, |
1517 | SourceLocation LParenOrBraceLoc, |
1518 | MultiExprArg Exprs, |
1519 | SourceLocation RParenOrBraceLoc, |
1520 | bool ListInitialization) { |
1521 | QualType Ty = TInfo->getType(); |
1522 | SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc(); |
1523 | SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc); |
1524 | |
1525 | InitializedEntity Entity = |
1526 | InitializedEntity::InitializeTemporary(Context, TypeInfo: TInfo); |
1527 | InitializationKind Kind = |
1528 | Exprs.size() |
1529 | ? ListInitialization |
1530 | ? InitializationKind::CreateDirectList( |
1531 | InitLoc: TyBeginLoc, LBraceLoc: LParenOrBraceLoc, RBraceLoc: RParenOrBraceLoc) |
1532 | : InitializationKind::CreateDirect(InitLoc: TyBeginLoc, LParenLoc: LParenOrBraceLoc, |
1533 | RParenLoc: RParenOrBraceLoc) |
1534 | : InitializationKind::CreateValue(InitLoc: TyBeginLoc, LParenLoc: LParenOrBraceLoc, |
1535 | RParenLoc: RParenOrBraceLoc); |
1536 | |
1537 | // C++17 [expr.type.conv]p1: |
1538 | // If the type is a placeholder for a deduced class type, [...perform class |
1539 | // template argument deduction...] |
1540 | // C++23: |
1541 | // Otherwise, if the type contains a placeholder type, it is replaced by the |
1542 | // type determined by placeholder type deduction. |
1543 | DeducedType *Deduced = Ty->getContainedDeducedType(); |
1544 | if (Deduced && !Deduced->isDeduced() && |
1545 | isa<DeducedTemplateSpecializationType>(Val: Deduced)) { |
1546 | Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity, |
1547 | Kind, Init: Exprs); |
1548 | if (Ty.isNull()) |
1549 | return ExprError(); |
1550 | Entity = InitializedEntity::InitializeTemporary(TypeInfo: TInfo, Type: Ty); |
1551 | } else if (Deduced && !Deduced->isDeduced()) { |
1552 | MultiExprArg Inits = Exprs; |
1553 | if (ListInitialization) { |
1554 | auto *ILE = cast<InitListExpr>(Val: Exprs[0]); |
1555 | Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits()); |
1556 | } |
1557 | |
1558 | if (Inits.empty()) |
1559 | return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_init_no_expression) |
1560 | << Ty << FullRange); |
1561 | if (Inits.size() > 1) { |
1562 | Expr *FirstBad = Inits[1]; |
1563 | return ExprError(Diag(FirstBad->getBeginLoc(), |
1564 | diag::err_auto_expr_init_multiple_expressions) |
1565 | << Ty << FullRange); |
1566 | } |
1567 | if (getLangOpts().CPlusPlus23) { |
1568 | if (Ty->getAs<AutoType>()) |
1569 | Diag(TyBeginLoc, diag::warn_cxx20_compat_auto_expr) << FullRange; |
1570 | } |
1571 | Expr *Deduce = Inits[0]; |
1572 | if (isa<InitListExpr>(Deduce)) |
1573 | return ExprError( |
1574 | Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces) |
1575 | << ListInitialization << Ty << FullRange); |
1576 | QualType DeducedType; |
1577 | TemplateDeductionInfo Info(Deduce->getExprLoc()); |
1578 | TemplateDeductionResult Result = |
1579 | DeduceAutoType(AutoTypeLoc: TInfo->getTypeLoc(), Initializer: Deduce, Result&: DeducedType, Info); |
1580 | if (Result != TemplateDeductionResult::Success && |
1581 | Result != TemplateDeductionResult::AlreadyDiagnosed) |
1582 | return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_deduction_failure) |
1583 | << Ty << Deduce->getType() << FullRange |
1584 | << Deduce->getSourceRange()); |
1585 | if (DeducedType.isNull()) { |
1586 | assert(Result == TemplateDeductionResult::AlreadyDiagnosed); |
1587 | return ExprError(); |
1588 | } |
1589 | |
1590 | Ty = DeducedType; |
1591 | Entity = InitializedEntity::InitializeTemporary(TypeInfo: TInfo, Type: Ty); |
1592 | } |
1593 | |
1594 | if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) |
1595 | return CXXUnresolvedConstructExpr::Create( |
1596 | Context, T: Ty.getNonReferenceType(), TSI: TInfo, LParenLoc: LParenOrBraceLoc, Args: Exprs, |
1597 | RParenLoc: RParenOrBraceLoc, IsListInit: ListInitialization); |
1598 | |
1599 | // C++ [expr.type.conv]p1: |
1600 | // If the expression list is a parenthesized single expression, the type |
1601 | // conversion expression is equivalent (in definedness, and if defined in |
1602 | // meaning) to the corresponding cast expression. |
1603 | if (Exprs.size() == 1 && !ListInitialization && |
1604 | !isa<InitListExpr>(Val: Exprs[0])) { |
1605 | Expr *Arg = Exprs[0]; |
1606 | return BuildCXXFunctionalCastExpr(TInfo, Type: Ty, LParenLoc: LParenOrBraceLoc, CastExpr: Arg, |
1607 | RParenLoc: RParenOrBraceLoc); |
1608 | } |
1609 | |
1610 | // For an expression of the form T(), T shall not be an array type. |
1611 | QualType ElemTy = Ty; |
1612 | if (Ty->isArrayType()) { |
1613 | if (!ListInitialization) |
1614 | return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type) |
1615 | << FullRange); |
1616 | ElemTy = Context.getBaseElementType(QT: Ty); |
1617 | } |
1618 | |
1619 | // Only construct objects with object types. |
1620 | // The standard doesn't explicitly forbid function types here, but that's an |
1621 | // obvious oversight, as there's no way to dynamically construct a function |
1622 | // in general. |
1623 | if (Ty->isFunctionType()) |
1624 | return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type) |
1625 | << Ty << FullRange); |
1626 | |
1627 | // C++17 [expr.type.conv]p2, per DR2351: |
1628 | // If the type is cv void and the initializer is () or {}, the expression is |
1629 | // a prvalue of the specified type that performs no initialization. |
1630 | if (Ty->isVoidType()) { |
1631 | if (Exprs.empty()) |
1632 | return new (Context) CXXScalarValueInitExpr( |
1633 | Ty.getUnqualifiedType(), TInfo, Kind.getRange().getEnd()); |
1634 | if (ListInitialization && |
1635 | cast<InitListExpr>(Val: Exprs[0])->getNumInits() == 0) { |
1636 | return CXXFunctionalCastExpr::Create( |
1637 | Context, T: Ty.getUnqualifiedType(), VK: VK_PRValue, Written: TInfo, Kind: CK_ToVoid, |
1638 | Op: Exprs[0], /*Path=*/nullptr, FPO: CurFPFeatureOverrides(), |
1639 | LPLoc: Exprs[0]->getBeginLoc(), RPLoc: Exprs[0]->getEndLoc()); |
1640 | } |
1641 | } else if (RequireCompleteType(TyBeginLoc, ElemTy, |
1642 | diag::err_invalid_incomplete_type_use, |
1643 | FullRange)) |
1644 | return ExprError(); |
1645 | |
1646 | // Otherwise, the expression is a prvalue of the specified type whose |
1647 | // result object is direct-initialized (11.6) with the initializer. |
1648 | InitializationSequence InitSeq(*this, Entity, Kind, Exprs); |
1649 | ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: Exprs); |
1650 | |
1651 | if (Result.isInvalid()) |
1652 | return Result; |
1653 | |
1654 | Expr *Inner = Result.get(); |
1655 | if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Val: Inner)) |
1656 | Inner = BTE->getSubExpr(); |
1657 | if (auto *CE = dyn_cast<ConstantExpr>(Val: Inner); |
1658 | CE && CE->isImmediateInvocation()) |
1659 | Inner = CE->getSubExpr(); |
1660 | if (!isa<CXXTemporaryObjectExpr>(Val: Inner) && |
1661 | !isa<CXXScalarValueInitExpr>(Val: Inner)) { |
1662 | // If we created a CXXTemporaryObjectExpr, that node also represents the |
1663 | // functional cast. Otherwise, create an explicit cast to represent |
1664 | // the syntactic form of a functional-style cast that was used here. |
1665 | // |
1666 | // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr |
1667 | // would give a more consistent AST representation than using a |
1668 | // CXXTemporaryObjectExpr. It's also weird that the functional cast |
1669 | // is sometimes handled by initialization and sometimes not. |
1670 | QualType ResultType = Result.get()->getType(); |
1671 | SourceRange Locs = ListInitialization |
1672 | ? SourceRange() |
1673 | : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc); |
1674 | Result = CXXFunctionalCastExpr::Create( |
1675 | Context, T: ResultType, VK: Expr::getValueKindForType(T: Ty), Written: TInfo, Kind: CK_NoOp, |
1676 | Op: Result.get(), /*Path=*/nullptr, FPO: CurFPFeatureOverrides(), |
1677 | LPLoc: Locs.getBegin(), RPLoc: Locs.getEnd()); |
1678 | } |
1679 | |
1680 | return Result; |
1681 | } |
1682 | |
1683 | bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) { |
1684 | // [CUDA] Ignore this function, if we can't call it. |
1685 | const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true); |
1686 | if (getLangOpts().CUDA) { |
1687 | auto CallPreference = CUDA().IdentifyPreference(Caller, Method); |
1688 | // If it's not callable at all, it's not the right function. |
1689 | if (CallPreference < SemaCUDA::CFP_WrongSide) |
1690 | return false; |
1691 | if (CallPreference == SemaCUDA::CFP_WrongSide) { |
1692 | // Maybe. We have to check if there are better alternatives. |
1693 | DeclContext::lookup_result R = |
1694 | Method->getDeclContext()->lookup(Method->getDeclName()); |
1695 | for (const auto *D : R) { |
1696 | if (const auto *FD = dyn_cast<FunctionDecl>(D)) { |
1697 | if (CUDA().IdentifyPreference(Caller, FD) > SemaCUDA::CFP_WrongSide) |
1698 | return false; |
1699 | } |
1700 | } |
1701 | // We've found no better variants. |
1702 | } |
1703 | } |
1704 | |
1705 | SmallVector<const FunctionDecl*, 4> PreventedBy; |
1706 | bool Result = Method->isUsualDeallocationFunction(PreventedBy); |
1707 | |
1708 | if (Result || !getLangOpts().CUDA || PreventedBy.empty()) |
1709 | return Result; |
1710 | |
1711 | // In case of CUDA, return true if none of the 1-argument deallocator |
1712 | // functions are actually callable. |
1713 | return llvm::none_of(Range&: PreventedBy, P: [&](const FunctionDecl *FD) { |
1714 | assert(FD->getNumParams() == 1 && |
1715 | "Only single-operand functions should be in PreventedBy"); |
1716 | return CUDA().IdentifyPreference(Caller, Callee: FD) >= SemaCUDA::CFP_HostDevice; |
1717 | }); |
1718 | } |
1719 | |
1720 | /// Determine whether the given function is a non-placement |
1721 | /// deallocation function. |
1722 | static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) { |
1723 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: FD)) |
1724 | return S.isUsualDeallocationFunction(Method); |
1725 | |
1726 | if (!FD->getDeclName().isAnyOperatorDelete()) |
1727 | return false; |
1728 | |
1729 | if (FD->isTypeAwareOperatorNewOrDelete()) |
1730 | return FunctionDecl::RequiredTypeAwareDeleteParameterCount == |
1731 | FD->getNumParams(); |
1732 | |
1733 | unsigned UsualParams = 1; |
1734 | if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() && |
1735 | S.Context.hasSameUnqualifiedType( |
1736 | T1: FD->getParamDecl(i: UsualParams)->getType(), |
1737 | T2: S.Context.getSizeType())) |
1738 | ++UsualParams; |
1739 | |
1740 | if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() && |
1741 | S.Context.hasSameUnqualifiedType( |
1742 | T1: FD->getParamDecl(i: UsualParams)->getType(), |
1743 | T2: S.Context.getTypeDeclType(S.getStdAlignValT()))) |
1744 | ++UsualParams; |
1745 | |
1746 | return UsualParams == FD->getNumParams(); |
1747 | } |
1748 | |
1749 | namespace { |
1750 | struct UsualDeallocFnInfo { |
1751 | UsualDeallocFnInfo() |
1752 | : Found(), FD(nullptr), |
1753 | IDP(AlignedAllocationMode::No, SizedDeallocationMode::No) {} |
1754 | UsualDeallocFnInfo(Sema &S, DeclAccessPair Found, QualType AllocType, |
1755 | SourceLocation Loc) |
1756 | : Found(Found), FD(dyn_cast<FunctionDecl>(Val: Found->getUnderlyingDecl())), |
1757 | Destroying(false), |
1758 | IDP({AllocType, TypeAwareAllocationMode::No, |
1759 | AlignedAllocationMode::No, SizedDeallocationMode::No}), |
1760 | CUDAPref(SemaCUDA::CFP_Native) { |
1761 | // A function template declaration is only a usual deallocation function |
1762 | // if it is a typed delete. |
1763 | if (!FD) { |
1764 | if (AllocType.isNull()) |
1765 | return; |
1766 | auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: Found->getUnderlyingDecl()); |
1767 | if (!FTD) |
1768 | return; |
1769 | FunctionDecl *InstantiatedDecl = |
1770 | S.BuildTypeAwareUsualDelete(FnDecl: FTD, AllocType, Loc); |
1771 | if (!InstantiatedDecl) |
1772 | return; |
1773 | FD = InstantiatedDecl; |
1774 | } |
1775 | unsigned NumBaseParams = 1; |
1776 | if (FD->isTypeAwareOperatorNewOrDelete()) { |
1777 | // If this is a type aware operator delete we instantiate an appropriate |
1778 | // specialization of std::type_identity<>. If we do not know the |
1779 | // type being deallocated, or if the type-identity parameter of the |
1780 | // deallocation function does not match the constructed type_identity |
1781 | // specialization we reject the declaration. |
1782 | if (AllocType.isNull()) { |
1783 | FD = nullptr; |
1784 | return; |
1785 | } |
1786 | QualType TypeIdentityTag = FD->getParamDecl(i: 0)->getType(); |
1787 | QualType ExpectedTypeIdentityTag = |
1788 | S.tryBuildStdTypeIdentity(Type: AllocType, Loc); |
1789 | if (ExpectedTypeIdentityTag.isNull()) { |
1790 | FD = nullptr; |
1791 | return; |
1792 | } |
1793 | if (!S.Context.hasSameType(T1: TypeIdentityTag, T2: ExpectedTypeIdentityTag)) { |
1794 | FD = nullptr; |
1795 | return; |
1796 | } |
1797 | IDP.PassTypeIdentity = TypeAwareAllocationMode::Yes; |
1798 | ++NumBaseParams; |
1799 | } |
1800 | |
1801 | if (FD->isDestroyingOperatorDelete()) { |
1802 | Destroying = true; |
1803 | ++NumBaseParams; |
1804 | } |
1805 | |
1806 | if (NumBaseParams < FD->getNumParams() && |
1807 | S.Context.hasSameUnqualifiedType( |
1808 | T1: FD->getParamDecl(i: NumBaseParams)->getType(), |
1809 | T2: S.Context.getSizeType())) { |
1810 | ++NumBaseParams; |
1811 | IDP.PassSize = SizedDeallocationMode::Yes; |
1812 | } |
1813 | |
1814 | if (NumBaseParams < FD->getNumParams() && |
1815 | FD->getParamDecl(i: NumBaseParams)->getType()->isAlignValT()) { |
1816 | ++NumBaseParams; |
1817 | IDP.PassAlignment = AlignedAllocationMode::Yes; |
1818 | } |
1819 | |
1820 | // In CUDA, determine how much we'd like / dislike to call this. |
1821 | if (S.getLangOpts().CUDA) |
1822 | CUDAPref = S.CUDA().IdentifyPreference( |
1823 | Caller: S.getCurFunctionDecl(/*AllowLambda=*/true), Callee: FD); |
1824 | } |
1825 | |
1826 | explicit operator bool() const { return FD; } |
1827 | |
1828 | int Compare(Sema &S, const UsualDeallocFnInfo &Other, |
1829 | ImplicitDeallocationParameters TargetIDP) const { |
1830 | assert(!TargetIDP.Type.isNull() || |
1831 | !isTypeAwareAllocation(Other.IDP.PassTypeIdentity)); |
1832 | |
1833 | // C++ P0722: |
1834 | // A destroying operator delete is preferred over a non-destroying |
1835 | // operator delete. |
1836 | if (Destroying != Other.Destroying) |
1837 | return Destroying ? 1 : -1; |
1838 | |
1839 | const ImplicitDeallocationParameters &OtherIDP = Other.IDP; |
1840 | // Selection for type awareness has priority over alignment and size |
1841 | if (IDP.PassTypeIdentity != OtherIDP.PassTypeIdentity) |
1842 | return IDP.PassTypeIdentity == TargetIDP.PassTypeIdentity ? 1 : -1; |
1843 | |
1844 | // C++17 [expr.delete]p10: |
1845 | // If the type has new-extended alignment, a function with a parameter |
1846 | // of type std::align_val_t is preferred; otherwise a function without |
1847 | // such a parameter is preferred |
1848 | if (IDP.PassAlignment != OtherIDP.PassAlignment) |
1849 | return IDP.PassAlignment == TargetIDP.PassAlignment ? 1 : -1; |
1850 | |
1851 | if (IDP.PassSize != OtherIDP.PassSize) |
1852 | return IDP.PassSize == TargetIDP.PassSize ? 1 : -1; |
1853 | |
1854 | if (isTypeAwareAllocation(IDP.PassTypeIdentity)) { |
1855 | // Type aware allocation involves templates so we need to choose |
1856 | // the best type |
1857 | FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate(); |
1858 | FunctionTemplateDecl *OtherPrimaryTemplate = |
1859 | Other.FD->getPrimaryTemplate(); |
1860 | if ((!PrimaryTemplate) != (!OtherPrimaryTemplate)) |
1861 | return OtherPrimaryTemplate ? 1 : -1; |
1862 | |
1863 | if (PrimaryTemplate && OtherPrimaryTemplate) { |
1864 | const auto *DC = dyn_cast<CXXRecordDecl>(Found->getDeclContext()); |
1865 | const auto *OtherDC = |
1866 | dyn_cast<CXXRecordDecl>(Other.Found->getDeclContext()); |
1867 | unsigned ImplicitArgCount = Destroying + IDP.getNumImplicitArgs(); |
1868 | if (FunctionTemplateDecl *Best = S.getMoreSpecializedTemplate( |
1869 | FT1: PrimaryTemplate, FT2: OtherPrimaryTemplate, Loc: SourceLocation(), |
1870 | TPOC: TPOC_Call, NumCallArguments1: ImplicitArgCount, |
1871 | RawObj1Ty: DC ? QualType(DC->getTypeForDecl(), 0) : QualType{}, |
1872 | RawObj2Ty: OtherDC ? QualType(OtherDC->getTypeForDecl(), 0) : QualType{}, |
1873 | Reversed: false)) { |
1874 | return Best == PrimaryTemplate ? 1 : -1; |
1875 | } |
1876 | } |
1877 | } |
1878 | |
1879 | // Use CUDA call preference as a tiebreaker. |
1880 | if (CUDAPref > Other.CUDAPref) |
1881 | return 1; |
1882 | if (CUDAPref == Other.CUDAPref) |
1883 | return 0; |
1884 | return -1; |
1885 | } |
1886 | |
1887 | DeclAccessPair Found; |
1888 | FunctionDecl *FD; |
1889 | bool Destroying; |
1890 | ImplicitDeallocationParameters IDP; |
1891 | SemaCUDA::CUDAFunctionPreference CUDAPref; |
1892 | }; |
1893 | } |
1894 | |
1895 | /// Determine whether a type has new-extended alignment. This may be called when |
1896 | /// the type is incomplete (for a delete-expression with an incomplete pointee |
1897 | /// type), in which case it will conservatively return false if the alignment is |
1898 | /// not known. |
1899 | static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) { |
1900 | return S.getLangOpts().AlignedAllocation && |
1901 | S.getASTContext().getTypeAlignIfKnown(T: AllocType) > |
1902 | S.getASTContext().getTargetInfo().getNewAlign(); |
1903 | } |
1904 | |
1905 | static bool CheckDeleteOperator(Sema &S, SourceLocation StartLoc, |
1906 | SourceRange Range, bool Diagnose, |
1907 | CXXRecordDecl *NamingClass, DeclAccessPair Decl, |
1908 | FunctionDecl *Operator) { |
1909 | if (Operator->isTypeAwareOperatorNewOrDelete()) { |
1910 | QualType SelectedTypeIdentityParameter = |
1911 | Operator->getParamDecl(i: 0)->getType(); |
1912 | if (S.RequireCompleteType(StartLoc, SelectedTypeIdentityParameter, |
1913 | diag::err_incomplete_type)) |
1914 | return true; |
1915 | } |
1916 | |
1917 | // FIXME: DiagnoseUseOfDecl? |
1918 | if (Operator->isDeleted()) { |
1919 | if (Diagnose) { |
1920 | StringLiteral *Msg = Operator->getDeletedMessage(); |
1921 | S.Diag(StartLoc, diag::err_deleted_function_use) |
1922 | << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef()); |
1923 | S.NoteDeletedFunction(FD: Operator); |
1924 | } |
1925 | return true; |
1926 | } |
1927 | Sema::AccessResult Accessible = |
1928 | S.CheckAllocationAccess(OperatorLoc: StartLoc, PlacementRange: Range, NamingClass, FoundDecl: Decl, Diagnose); |
1929 | return Accessible == Sema::AR_inaccessible; |
1930 | } |
1931 | |
1932 | /// Select the correct "usual" deallocation function to use from a selection of |
1933 | /// deallocation functions (either global or class-scope). |
1934 | static UsualDeallocFnInfo resolveDeallocationOverload( |
1935 | Sema &S, LookupResult &R, const ImplicitDeallocationParameters &IDP, |
1936 | SourceLocation Loc, |
1937 | llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) { |
1938 | |
1939 | UsualDeallocFnInfo Best; |
1940 | for (auto I = R.begin(), E = R.end(); I != E; ++I) { |
1941 | UsualDeallocFnInfo Info(S, I.getPair(), IDP.Type, Loc); |
1942 | if (!Info || !isNonPlacementDeallocationFunction(S, FD: Info.FD) || |
1943 | Info.CUDAPref == SemaCUDA::CFP_Never) |
1944 | continue; |
1945 | |
1946 | if (!isTypeAwareAllocation(Mode: IDP.PassTypeIdentity) && |
1947 | isTypeAwareAllocation(Info.IDP.PassTypeIdentity)) |
1948 | continue; |
1949 | if (!Best) { |
1950 | Best = Info; |
1951 | if (BestFns) |
1952 | BestFns->push_back(Elt: Info); |
1953 | continue; |
1954 | } |
1955 | int ComparisonResult = Best.Compare(S, Other: Info, TargetIDP: IDP); |
1956 | if (ComparisonResult > 0) |
1957 | continue; |
1958 | |
1959 | // If more than one preferred function is found, all non-preferred |
1960 | // functions are eliminated from further consideration. |
1961 | if (BestFns && ComparisonResult < 0) |
1962 | BestFns->clear(); |
1963 | |
1964 | Best = Info; |
1965 | if (BestFns) |
1966 | BestFns->push_back(Elt: Info); |
1967 | } |
1968 | |
1969 | return Best; |
1970 | } |
1971 | |
1972 | /// Determine whether a given type is a class for which 'delete[]' would call |
1973 | /// a member 'operator delete[]' with a 'size_t' parameter. This implies that |
1974 | /// we need to store the array size (even if the type is |
1975 | /// trivially-destructible). |
1976 | static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc, |
1977 | TypeAwareAllocationMode PassType, |
1978 | QualType allocType) { |
1979 | const RecordType *record = |
1980 | allocType->getBaseElementTypeUnsafe()->getAs<RecordType>(); |
1981 | if (!record) return false; |
1982 | |
1983 | // Try to find an operator delete[] in class scope. |
1984 | |
1985 | DeclarationName deleteName = |
1986 | S.Context.DeclarationNames.getCXXOperatorName(Op: OO_Array_Delete); |
1987 | LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName); |
1988 | S.LookupQualifiedName(ops, record->getDecl()); |
1989 | |
1990 | // We're just doing this for information. |
1991 | ops.suppressDiagnostics(); |
1992 | |
1993 | // Very likely: there's no operator delete[]. |
1994 | if (ops.empty()) return false; |
1995 | |
1996 | // If it's ambiguous, it should be illegal to call operator delete[] |
1997 | // on this thing, so it doesn't matter if we allocate extra space or not. |
1998 | if (ops.isAmbiguous()) return false; |
1999 | |
2000 | // C++17 [expr.delete]p10: |
2001 | // If the deallocation functions have class scope, the one without a |
2002 | // parameter of type std::size_t is selected. |
2003 | ImplicitDeallocationParameters IDP = { |
2004 | allocType, PassType, |
2005 | alignedAllocationModeFromBool(IsAligned: hasNewExtendedAlignment(S, AllocType: allocType)), |
2006 | SizedDeallocationMode::No}; |
2007 | auto Best = resolveDeallocationOverload(S, R&: ops, IDP, Loc: loc); |
2008 | return Best && isSizedDeallocation(Best.IDP.PassSize); |
2009 | } |
2010 | |
2011 | ExprResult |
2012 | Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, |
2013 | SourceLocation PlacementLParen, MultiExprArg PlacementArgs, |
2014 | SourceLocation PlacementRParen, SourceRange TypeIdParens, |
2015 | Declarator &D, Expr *Initializer) { |
2016 | std::optional<Expr *> ArraySize; |
2017 | // If the specified type is an array, unwrap it and save the expression. |
2018 | if (D.getNumTypeObjects() > 0 && |
2019 | D.getTypeObject(i: 0).Kind == DeclaratorChunk::Array) { |
2020 | DeclaratorChunk &Chunk = D.getTypeObject(i: 0); |
2021 | if (D.getDeclSpec().hasAutoTypeSpec()) |
2022 | return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto) |
2023 | << D.getSourceRange()); |
2024 | if (Chunk.Arr.hasStatic) |
2025 | return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new) |
2026 | << D.getSourceRange()); |
2027 | if (!Chunk.Arr.NumElts && !Initializer) |
2028 | return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size) |
2029 | << D.getSourceRange()); |
2030 | |
2031 | ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts); |
2032 | D.DropFirstTypeObject(); |
2033 | } |
2034 | |
2035 | // Every dimension shall be of constant size. |
2036 | if (ArraySize) { |
2037 | for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) { |
2038 | if (D.getTypeObject(i: I).Kind != DeclaratorChunk::Array) |
2039 | break; |
2040 | |
2041 | DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(i: I).Arr; |
2042 | if (Expr *NumElts = (Expr *)Array.NumElts) { |
2043 | if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) { |
2044 | // FIXME: GCC permits constant folding here. We should either do so consistently |
2045 | // or not do so at all, rather than changing behavior in C++14 onwards. |
2046 | if (getLangOpts().CPlusPlus14) { |
2047 | // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator |
2048 | // shall be a converted constant expression (5.19) of type std::size_t |
2049 | // and shall evaluate to a strictly positive value. |
2050 | llvm::APSInt Value(Context.getIntWidth(T: Context.getSizeType())); |
2051 | Array.NumElts = |
2052 | CheckConvertedConstantExpression(From: NumElts, T: Context.getSizeType(), |
2053 | Value, CCE: CCEKind::ArrayBound) |
2054 | .get(); |
2055 | } else { |
2056 | Array.NumElts = VerifyIntegerConstantExpression( |
2057 | NumElts, nullptr, diag::err_new_array_nonconst, |
2058 | AllowFoldKind::Allow) |
2059 | .get(); |
2060 | } |
2061 | if (!Array.NumElts) |
2062 | return ExprError(); |
2063 | } |
2064 | } |
2065 | } |
2066 | } |
2067 | |
2068 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D); |
2069 | QualType AllocType = TInfo->getType(); |
2070 | if (D.isInvalidType()) |
2071 | return ExprError(); |
2072 | |
2073 | SourceRange DirectInitRange; |
2074 | if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Val: Initializer)) |
2075 | DirectInitRange = List->getSourceRange(); |
2076 | |
2077 | return BuildCXXNew(Range: SourceRange(StartLoc, D.getEndLoc()), UseGlobal, |
2078 | PlacementLParen, PlacementArgs, PlacementRParen, |
2079 | TypeIdParens, AllocType, AllocTypeInfo: TInfo, ArraySize, DirectInitRange, |
2080 | Initializer); |
2081 | } |
2082 | |
2083 | static bool isLegalArrayNewInitializer(CXXNewInitializationStyle Style, |
2084 | Expr *Init, bool IsCPlusPlus20) { |
2085 | if (!Init) |
2086 | return true; |
2087 | if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Val: Init)) |
2088 | return IsCPlusPlus20 || PLE->getNumExprs() == 0; |
2089 | if (isa<ImplicitValueInitExpr>(Val: Init)) |
2090 | return true; |
2091 | else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Val: Init)) |
2092 | return !CCE->isListInitialization() && |
2093 | CCE->getConstructor()->isDefaultConstructor(); |
2094 | else if (Style == CXXNewInitializationStyle::Braces) { |
2095 | assert(isa<InitListExpr>(Init) && |
2096 | "Shouldn't create list CXXConstructExprs for arrays."); |
2097 | return true; |
2098 | } |
2099 | return false; |
2100 | } |
2101 | |
2102 | bool |
2103 | Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const { |
2104 | if (!getLangOpts().AlignedAllocationUnavailable) |
2105 | return false; |
2106 | if (FD.isDefined()) |
2107 | return false; |
2108 | UnsignedOrNone AlignmentParam = std::nullopt; |
2109 | if (FD.isReplaceableGlobalAllocationFunction(AlignmentParam: &AlignmentParam) && |
2110 | AlignmentParam) |
2111 | return true; |
2112 | return false; |
2113 | } |
2114 | |
2115 | // Emit a diagnostic if an aligned allocation/deallocation function that is not |
2116 | // implemented in the standard library is selected. |
2117 | void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, |
2118 | SourceLocation Loc) { |
2119 | if (isUnavailableAlignedAllocationFunction(FD)) { |
2120 | const llvm::Triple &T = getASTContext().getTargetInfo().getTriple(); |
2121 | StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling( |
2122 | getASTContext().getTargetInfo().getPlatformName()); |
2123 | VersionTuple OSVersion = alignedAllocMinVersion(OS: T.getOS()); |
2124 | |
2125 | bool IsDelete = FD.getDeclName().isAnyOperatorDelete(); |
2126 | Diag(Loc, diag::err_aligned_allocation_unavailable) |
2127 | << IsDelete << FD.getType().getAsString() << OSName |
2128 | << OSVersion.getAsString() << OSVersion.empty(); |
2129 | Diag(Loc, diag::note_silence_aligned_allocation_unavailable); |
2130 | } |
2131 | } |
2132 | |
2133 | ExprResult Sema::BuildCXXNew(SourceRange Range, bool UseGlobal, |
2134 | SourceLocation PlacementLParen, |
2135 | MultiExprArg PlacementArgs, |
2136 | SourceLocation PlacementRParen, |
2137 | SourceRange TypeIdParens, QualType AllocType, |
2138 | TypeSourceInfo *AllocTypeInfo, |
2139 | std::optional<Expr *> ArraySize, |
2140 | SourceRange DirectInitRange, Expr *Initializer) { |
2141 | SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange(); |
2142 | SourceLocation StartLoc = Range.getBegin(); |
2143 | |
2144 | CXXNewInitializationStyle InitStyle; |
2145 | if (DirectInitRange.isValid()) { |
2146 | assert(Initializer && "Have parens but no initializer."); |
2147 | InitStyle = CXXNewInitializationStyle::Parens; |
2148 | } else if (isa_and_nonnull<InitListExpr>(Val: Initializer)) |
2149 | InitStyle = CXXNewInitializationStyle::Braces; |
2150 | else { |
2151 | assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) || |
2152 | isa<CXXConstructExpr>(Initializer)) && |
2153 | "Initializer expression that cannot have been implicitly created."); |
2154 | InitStyle = CXXNewInitializationStyle::None; |
2155 | } |
2156 | |
2157 | MultiExprArg Exprs(&Initializer, Initializer ? 1 : 0); |
2158 | if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Val: Initializer)) { |
2159 | assert(InitStyle == CXXNewInitializationStyle::Parens && |
2160 | "paren init for non-call init"); |
2161 | Exprs = MultiExprArg(List->getExprs(), List->getNumExprs()); |
2162 | } else if (auto *List = dyn_cast_or_null<CXXParenListInitExpr>(Val: Initializer)) { |
2163 | assert(InitStyle == CXXNewInitializationStyle::Parens && |
2164 | "paren init for non-call init"); |
2165 | Exprs = List->getInitExprs(); |
2166 | } |
2167 | |
2168 | // C++11 [expr.new]p15: |
2169 | // A new-expression that creates an object of type T initializes that |
2170 | // object as follows: |
2171 | InitializationKind Kind = [&] { |
2172 | switch (InitStyle) { |
2173 | // - If the new-initializer is omitted, the object is default- |
2174 | // initialized (8.5); if no initialization is performed, |
2175 | // the object has indeterminate value |
2176 | case CXXNewInitializationStyle::None: |
2177 | return InitializationKind::CreateDefault(InitLoc: TypeRange.getBegin()); |
2178 | // - Otherwise, the new-initializer is interpreted according to the |
2179 | // initialization rules of 8.5 for direct-initialization. |
2180 | case CXXNewInitializationStyle::Parens: |
2181 | return InitializationKind::CreateDirect(InitLoc: TypeRange.getBegin(), |
2182 | LParenLoc: DirectInitRange.getBegin(), |
2183 | RParenLoc: DirectInitRange.getEnd()); |
2184 | case CXXNewInitializationStyle::Braces: |
2185 | return InitializationKind::CreateDirectList(TypeRange.getBegin(), |
2186 | Initializer->getBeginLoc(), |
2187 | Initializer->getEndLoc()); |
2188 | } |
2189 | llvm_unreachable("Unknown initialization kind"); |
2190 | }(); |
2191 | |
2192 | // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for. |
2193 | auto *Deduced = AllocType->getContainedDeducedType(); |
2194 | if (Deduced && !Deduced->isDeduced() && |
2195 | isa<DeducedTemplateSpecializationType>(Deduced)) { |
2196 | if (ArraySize) |
2197 | return ExprError( |
2198 | Diag(*ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(), |
2199 | diag::err_deduced_class_template_compound_type) |
2200 | << /*array*/ 2 |
2201 | << (*ArraySize ? (*ArraySize)->getSourceRange() : TypeRange)); |
2202 | |
2203 | InitializedEntity Entity |
2204 | = InitializedEntity::InitializeNew(NewLoc: StartLoc, Type: AllocType); |
2205 | AllocType = DeduceTemplateSpecializationFromInitializer( |
2206 | TInfo: AllocTypeInfo, Entity, Kind, Init: Exprs); |
2207 | if (AllocType.isNull()) |
2208 | return ExprError(); |
2209 | } else if (Deduced && !Deduced->isDeduced()) { |
2210 | MultiExprArg Inits = Exprs; |
2211 | bool Braced = (InitStyle == CXXNewInitializationStyle::Braces); |
2212 | if (Braced) { |
2213 | auto *ILE = cast<InitListExpr>(Val: Exprs[0]); |
2214 | Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits()); |
2215 | } |
2216 | |
2217 | if (InitStyle == CXXNewInitializationStyle::None || Inits.empty()) |
2218 | return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg) |
2219 | << AllocType << TypeRange); |
2220 | if (Inits.size() > 1) { |
2221 | Expr *FirstBad = Inits[1]; |
2222 | return ExprError(Diag(FirstBad->getBeginLoc(), |
2223 | diag::err_auto_new_ctor_multiple_expressions) |
2224 | << AllocType << TypeRange); |
2225 | } |
2226 | if (Braced && !getLangOpts().CPlusPlus17) |
2227 | Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init) |
2228 | << AllocType << TypeRange; |
2229 | Expr *Deduce = Inits[0]; |
2230 | if (isa<InitListExpr>(Deduce)) |
2231 | return ExprError( |
2232 | Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces) |
2233 | << Braced << AllocType << TypeRange); |
2234 | QualType DeducedType; |
2235 | TemplateDeductionInfo Info(Deduce->getExprLoc()); |
2236 | TemplateDeductionResult Result = |
2237 | DeduceAutoType(AutoTypeLoc: AllocTypeInfo->getTypeLoc(), Initializer: Deduce, Result&: DeducedType, Info); |
2238 | if (Result != TemplateDeductionResult::Success && |
2239 | Result != TemplateDeductionResult::AlreadyDiagnosed) |
2240 | return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure) |
2241 | << AllocType << Deduce->getType() << TypeRange |
2242 | << Deduce->getSourceRange()); |
2243 | if (DeducedType.isNull()) { |
2244 | assert(Result == TemplateDeductionResult::AlreadyDiagnosed); |
2245 | return ExprError(); |
2246 | } |
2247 | AllocType = DeducedType; |
2248 | } |
2249 | |
2250 | // Per C++0x [expr.new]p5, the type being constructed may be a |
2251 | // typedef of an array type. |
2252 | // Dependent case will be handled separately. |
2253 | if (!ArraySize && !AllocType->isDependentType()) { |
2254 | if (const ConstantArrayType *Array |
2255 | = Context.getAsConstantArrayType(T: AllocType)) { |
2256 | ArraySize = IntegerLiteral::Create(C: Context, V: Array->getSize(), |
2257 | type: Context.getSizeType(), |
2258 | l: TypeRange.getEnd()); |
2259 | AllocType = Array->getElementType(); |
2260 | } |
2261 | } |
2262 | |
2263 | if (CheckAllocatedType(AllocType, Loc: TypeRange.getBegin(), R: TypeRange)) |
2264 | return ExprError(); |
2265 | |
2266 | if (ArraySize && !checkArrayElementAlignment(EltTy: AllocType, Loc: TypeRange.getBegin())) |
2267 | return ExprError(); |
2268 | |
2269 | // In ARC, infer 'retaining' for the allocated |
2270 | if (getLangOpts().ObjCAutoRefCount && |
2271 | AllocType.getObjCLifetime() == Qualifiers::OCL_None && |
2272 | AllocType->isObjCLifetimeType()) { |
2273 | AllocType = Context.getLifetimeQualifiedType(type: AllocType, |
2274 | lifetime: AllocType->getObjCARCImplicitLifetime()); |
2275 | } |
2276 | |
2277 | QualType ResultType = Context.getPointerType(T: AllocType); |
2278 | |
2279 | if (ArraySize && *ArraySize && |
2280 | (*ArraySize)->getType()->isNonOverloadPlaceholderType()) { |
2281 | ExprResult result = CheckPlaceholderExpr(E: *ArraySize); |
2282 | if (result.isInvalid()) return ExprError(); |
2283 | ArraySize = result.get(); |
2284 | } |
2285 | // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have |
2286 | // integral or enumeration type with a non-negative value." |
2287 | // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped |
2288 | // enumeration type, or a class type for which a single non-explicit |
2289 | // conversion function to integral or unscoped enumeration type exists. |
2290 | // C++1y [expr.new]p6: The expression [...] is implicitly converted to |
2291 | // std::size_t. |
2292 | std::optional<uint64_t> KnownArraySize; |
2293 | if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) { |
2294 | ExprResult ConvertedSize; |
2295 | if (getLangOpts().CPlusPlus14) { |
2296 | assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?"); |
2297 | |
2298 | ConvertedSize = PerformImplicitConversion( |
2299 | From: *ArraySize, ToType: Context.getSizeType(), Action: AssignmentAction::Converting); |
2300 | |
2301 | if (!ConvertedSize.isInvalid() && |
2302 | (*ArraySize)->getType()->getAs<RecordType>()) |
2303 | // Diagnose the compatibility of this conversion. |
2304 | Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion) |
2305 | << (*ArraySize)->getType() << 0 << "'size_t'"; |
2306 | } else { |
2307 | class SizeConvertDiagnoser : public ICEConvertDiagnoser { |
2308 | protected: |
2309 | Expr *ArraySize; |
2310 | |
2311 | public: |
2312 | SizeConvertDiagnoser(Expr *ArraySize) |
2313 | : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false), |
2314 | ArraySize(ArraySize) {} |
2315 | |
2316 | SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, |
2317 | QualType T) override { |
2318 | return S.Diag(Loc, diag::err_array_size_not_integral) |
2319 | << S.getLangOpts().CPlusPlus11 << T; |
2320 | } |
2321 | |
2322 | SemaDiagnosticBuilder diagnoseIncomplete( |
2323 | Sema &S, SourceLocation Loc, QualType T) override { |
2324 | return S.Diag(Loc, diag::err_array_size_incomplete_type) |
2325 | << T << ArraySize->getSourceRange(); |
2326 | } |
2327 | |
2328 | SemaDiagnosticBuilder diagnoseExplicitConv( |
2329 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { |
2330 | return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy; |
2331 | } |
2332 | |
2333 | SemaDiagnosticBuilder noteExplicitConv( |
2334 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { |
2335 | return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) |
2336 | << ConvTy->isEnumeralType() << ConvTy; |
2337 | } |
2338 | |
2339 | SemaDiagnosticBuilder diagnoseAmbiguous( |
2340 | Sema &S, SourceLocation Loc, QualType T) override { |
2341 | return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T; |
2342 | } |
2343 | |
2344 | SemaDiagnosticBuilder noteAmbiguous( |
2345 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { |
2346 | return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) |
2347 | << ConvTy->isEnumeralType() << ConvTy; |
2348 | } |
2349 | |
2350 | SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, |
2351 | QualType T, |
2352 | QualType ConvTy) override { |
2353 | return S.Diag(Loc, |
2354 | S.getLangOpts().CPlusPlus11 |
2355 | ? diag::warn_cxx98_compat_array_size_conversion |
2356 | : diag::ext_array_size_conversion) |
2357 | << T << ConvTy->isEnumeralType() << ConvTy; |
2358 | } |
2359 | } SizeDiagnoser(*ArraySize); |
2360 | |
2361 | ConvertedSize = PerformContextualImplicitConversion(Loc: StartLoc, FromE: *ArraySize, |
2362 | Converter&: SizeDiagnoser); |
2363 | } |
2364 | if (ConvertedSize.isInvalid()) |
2365 | return ExprError(); |
2366 | |
2367 | ArraySize = ConvertedSize.get(); |
2368 | QualType SizeType = (*ArraySize)->getType(); |
2369 | |
2370 | if (!SizeType->isIntegralOrUnscopedEnumerationType()) |
2371 | return ExprError(); |
2372 | |
2373 | // C++98 [expr.new]p7: |
2374 | // The expression in a direct-new-declarator shall have integral type |
2375 | // with a non-negative value. |
2376 | // |
2377 | // Let's see if this is a constant < 0. If so, we reject it out of hand, |
2378 | // per CWG1464. Otherwise, if it's not a constant, we must have an |
2379 | // unparenthesized array type. |
2380 | |
2381 | // We've already performed any required implicit conversion to integer or |
2382 | // unscoped enumeration type. |
2383 | // FIXME: Per CWG1464, we are required to check the value prior to |
2384 | // converting to size_t. This will never find a negative array size in |
2385 | // C++14 onwards, because Value is always unsigned here! |
2386 | if (std::optional<llvm::APSInt> Value = |
2387 | (*ArraySize)->getIntegerConstantExpr(Ctx: Context)) { |
2388 | if (Value->isSigned() && Value->isNegative()) { |
2389 | return ExprError(Diag((*ArraySize)->getBeginLoc(), |
2390 | diag::err_typecheck_negative_array_size) |
2391 | << (*ArraySize)->getSourceRange()); |
2392 | } |
2393 | |
2394 | if (!AllocType->isDependentType()) { |
2395 | unsigned ActiveSizeBits = |
2396 | ConstantArrayType::getNumAddressingBits(Context, ElementType: AllocType, NumElements: *Value); |
2397 | if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) |
2398 | return ExprError( |
2399 | Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large) |
2400 | << toString(*Value, 10) << (*ArraySize)->getSourceRange()); |
2401 | } |
2402 | |
2403 | KnownArraySize = Value->getZExtValue(); |
2404 | } else if (TypeIdParens.isValid()) { |
2405 | // Can't have dynamic array size when the type-id is in parentheses. |
2406 | Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst) |
2407 | << (*ArraySize)->getSourceRange() |
2408 | << FixItHint::CreateRemoval(TypeIdParens.getBegin()) |
2409 | << FixItHint::CreateRemoval(TypeIdParens.getEnd()); |
2410 | |
2411 | TypeIdParens = SourceRange(); |
2412 | } |
2413 | |
2414 | // Note that we do *not* convert the argument in any way. It can |
2415 | // be signed, larger than size_t, whatever. |
2416 | } |
2417 | |
2418 | FunctionDecl *OperatorNew = nullptr; |
2419 | FunctionDecl *OperatorDelete = nullptr; |
2420 | unsigned Alignment = |
2421 | AllocType->isDependentType() ? 0 : Context.getTypeAlign(T: AllocType); |
2422 | unsigned NewAlignment = Context.getTargetInfo().getNewAlign(); |
2423 | ImplicitAllocationParameters IAP = { |
2424 | AllocType, ShouldUseTypeAwareOperatorNewOrDelete(), |
2425 | alignedAllocationModeFromBool(IsAligned: getLangOpts().AlignedAllocation && |
2426 | Alignment > NewAlignment)}; |
2427 | |
2428 | if (CheckArgsForPlaceholders(args: PlacementArgs)) |
2429 | return ExprError(); |
2430 | |
2431 | AllocationFunctionScope Scope = UseGlobal ? AllocationFunctionScope::Global |
2432 | : AllocationFunctionScope::Both; |
2433 | SourceRange AllocationParameterRange = Range; |
2434 | if (PlacementLParen.isValid() && PlacementRParen.isValid()) |
2435 | AllocationParameterRange = SourceRange(PlacementLParen, PlacementRParen); |
2436 | if (!AllocType->isDependentType() && |
2437 | !Expr::hasAnyTypeDependentArguments(Exprs: PlacementArgs) && |
2438 | FindAllocationFunctions(StartLoc, Range: AllocationParameterRange, NewScope: Scope, DeleteScope: Scope, |
2439 | AllocType, IsArray: ArraySize.has_value(), IAP, |
2440 | PlaceArgs: PlacementArgs, OperatorNew, OperatorDelete)) |
2441 | return ExprError(); |
2442 | |
2443 | // If this is an array allocation, compute whether the usual array |
2444 | // deallocation function for the type has a size_t parameter. |
2445 | bool UsualArrayDeleteWantsSize = false; |
2446 | if (ArraySize && !AllocType->isDependentType()) |
2447 | UsualArrayDeleteWantsSize = doesUsualArrayDeleteWantSize( |
2448 | S&: *this, loc: StartLoc, PassType: IAP.PassTypeIdentity, allocType: AllocType); |
2449 | |
2450 | SmallVector<Expr *, 8> AllPlaceArgs; |
2451 | if (OperatorNew) { |
2452 | auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>(); |
2453 | VariadicCallType CallType = Proto->isVariadic() |
2454 | ? VariadicCallType::Function |
2455 | : VariadicCallType::DoesNotApply; |
2456 | |
2457 | // We've already converted the placement args, just fill in any default |
2458 | // arguments. Skip the first parameter because we don't have a corresponding |
2459 | // argument. Skip the second parameter too if we're passing in the |
2460 | // alignment; we've already filled it in. |
2461 | unsigned NumImplicitArgs = 1; |
2462 | if (isTypeAwareAllocation(Mode: IAP.PassTypeIdentity)) { |
2463 | assert(OperatorNew->isTypeAwareOperatorNewOrDelete()); |
2464 | NumImplicitArgs++; |
2465 | } |
2466 | if (isAlignedAllocation(Mode: IAP.PassAlignment)) |
2467 | NumImplicitArgs++; |
2468 | if (GatherArgumentsForCall(CallLoc: AllocationParameterRange.getBegin(), FDecl: OperatorNew, |
2469 | Proto: Proto, FirstParam: NumImplicitArgs, Args: PlacementArgs, |
2470 | AllArgs&: AllPlaceArgs, CallType)) |
2471 | return ExprError(); |
2472 | |
2473 | if (!AllPlaceArgs.empty()) |
2474 | PlacementArgs = AllPlaceArgs; |
2475 | |
2476 | // We would like to perform some checking on the given `operator new` call, |
2477 | // but the PlacementArgs does not contain the implicit arguments, |
2478 | // namely allocation size and maybe allocation alignment, |
2479 | // so we need to conjure them. |
2480 | |
2481 | QualType SizeTy = Context.getSizeType(); |
2482 | unsigned SizeTyWidth = Context.getTypeSize(T: SizeTy); |
2483 | |
2484 | llvm::APInt SingleEltSize( |
2485 | SizeTyWidth, Context.getTypeSizeInChars(T: AllocType).getQuantity()); |
2486 | |
2487 | // How many bytes do we want to allocate here? |
2488 | std::optional<llvm::APInt> AllocationSize; |
2489 | if (!ArraySize && !AllocType->isDependentType()) { |
2490 | // For non-array operator new, we only want to allocate one element. |
2491 | AllocationSize = SingleEltSize; |
2492 | } else if (KnownArraySize && !AllocType->isDependentType()) { |
2493 | // For array operator new, only deal with static array size case. |
2494 | bool Overflow; |
2495 | AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize) |
2496 | .umul_ov(RHS: SingleEltSize, Overflow); |
2497 | (void)Overflow; |
2498 | assert( |
2499 | !Overflow && |
2500 | "Expected that all the overflows would have been handled already."); |
2501 | } |
2502 | |
2503 | IntegerLiteral AllocationSizeLiteral( |
2504 | Context, AllocationSize.value_or(u: llvm::APInt::getZero(numBits: SizeTyWidth)), |
2505 | SizeTy, StartLoc); |
2506 | // Otherwise, if we failed to constant-fold the allocation size, we'll |
2507 | // just give up and pass-in something opaque, that isn't a null pointer. |
2508 | OpaqueValueExpr OpaqueAllocationSize(StartLoc, SizeTy, VK_PRValue, |
2509 | OK_Ordinary, /*SourceExpr=*/nullptr); |
2510 | |
2511 | // Let's synthesize the alignment argument in case we will need it. |
2512 | // Since we *really* want to allocate these on stack, this is slightly ugly |
2513 | // because there might not be a `std::align_val_t` type. |
2514 | EnumDecl *StdAlignValT = getStdAlignValT(); |
2515 | QualType AlignValT = |
2516 | StdAlignValT ? Context.getTypeDeclType(StdAlignValT) : SizeTy; |
2517 | IntegerLiteral AlignmentLiteral( |
2518 | Context, |
2519 | llvm::APInt(Context.getTypeSize(T: SizeTy), |
2520 | Alignment / Context.getCharWidth()), |
2521 | SizeTy, StartLoc); |
2522 | ImplicitCastExpr DesiredAlignment(ImplicitCastExpr::OnStack, AlignValT, |
2523 | CK_IntegralCast, &AlignmentLiteral, |
2524 | VK_PRValue, FPOptionsOverride()); |
2525 | |
2526 | // Adjust placement args by prepending conjured size and alignment exprs. |
2527 | llvm::SmallVector<Expr *, 8> CallArgs; |
2528 | CallArgs.reserve(N: NumImplicitArgs + PlacementArgs.size()); |
2529 | CallArgs.emplace_back(AllocationSize |
2530 | ? static_cast<Expr *>(&AllocationSizeLiteral) |
2531 | : &OpaqueAllocationSize); |
2532 | if (isAlignedAllocation(Mode: IAP.PassAlignment)) |
2533 | CallArgs.emplace_back(Args: &DesiredAlignment); |
2534 | llvm::append_range(C&: CallArgs, R&: PlacementArgs); |
2535 | |
2536 | DiagnoseSentinelCalls(OperatorNew, PlacementLParen, CallArgs); |
2537 | |
2538 | checkCall(FDecl: OperatorNew, Proto: Proto, /*ThisArg=*/nullptr, Args: CallArgs, |
2539 | /*IsMemberFunction=*/false, Loc: StartLoc, Range, CallType); |
2540 | |
2541 | // Warn if the type is over-aligned and is being allocated by (unaligned) |
2542 | // global operator new. |
2543 | if (PlacementArgs.empty() && !isAlignedAllocation(Mode: IAP.PassAlignment) && |
2544 | (OperatorNew->isImplicit() || |
2545 | (OperatorNew->getBeginLoc().isValid() && |
2546 | getSourceManager().isInSystemHeader(Loc: OperatorNew->getBeginLoc())))) { |
2547 | if (Alignment > NewAlignment) |
2548 | Diag(StartLoc, diag::warn_overaligned_type) |
2549 | << AllocType |
2550 | << unsigned(Alignment / Context.getCharWidth()) |
2551 | << unsigned(NewAlignment / Context.getCharWidth()); |
2552 | } |
2553 | } |
2554 | |
2555 | // Array 'new' can't have any initializers except empty parentheses. |
2556 | // Initializer lists are also allowed, in C++11. Rely on the parser for the |
2557 | // dialect distinction. |
2558 | if (ArraySize && !isLegalArrayNewInitializer(Style: InitStyle, Init: Initializer, |
2559 | IsCPlusPlus20: getLangOpts().CPlusPlus20)) { |
2560 | SourceRange InitRange(Exprs.front()->getBeginLoc(), |
2561 | Exprs.back()->getEndLoc()); |
2562 | Diag(StartLoc, diag::err_new_array_init_args) << InitRange; |
2563 | return ExprError(); |
2564 | } |
2565 | |
2566 | // If we can perform the initialization, and we've not already done so, |
2567 | // do it now. |
2568 | if (!AllocType->isDependentType() && |
2569 | !Expr::hasAnyTypeDependentArguments(Exprs)) { |
2570 | // The type we initialize is the complete type, including the array bound. |
2571 | QualType InitType; |
2572 | if (KnownArraySize) |
2573 | InitType = Context.getConstantArrayType( |
2574 | EltTy: AllocType, |
2575 | ArySize: llvm::APInt(Context.getTypeSize(T: Context.getSizeType()), |
2576 | *KnownArraySize), |
2577 | SizeExpr: *ArraySize, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0); |
2578 | else if (ArraySize) |
2579 | InitType = Context.getIncompleteArrayType(EltTy: AllocType, |
2580 | ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0); |
2581 | else |
2582 | InitType = AllocType; |
2583 | |
2584 | InitializedEntity Entity |
2585 | = InitializedEntity::InitializeNew(NewLoc: StartLoc, Type: InitType); |
2586 | InitializationSequence InitSeq(*this, Entity, Kind, Exprs); |
2587 | ExprResult FullInit = InitSeq.Perform(S&: *this, Entity, Kind, Args: Exprs); |
2588 | if (FullInit.isInvalid()) |
2589 | return ExprError(); |
2590 | |
2591 | // FullInit is our initializer; strip off CXXBindTemporaryExprs, because |
2592 | // we don't want the initialized object to be destructed. |
2593 | // FIXME: We should not create these in the first place. |
2594 | if (CXXBindTemporaryExpr *Binder = |
2595 | dyn_cast_or_null<CXXBindTemporaryExpr>(Val: FullInit.get())) |
2596 | FullInit = Binder->getSubExpr(); |
2597 | |
2598 | Initializer = FullInit.get(); |
2599 | |
2600 | // FIXME: If we have a KnownArraySize, check that the array bound of the |
2601 | // initializer is no greater than that constant value. |
2602 | |
2603 | if (ArraySize && !*ArraySize) { |
2604 | auto *CAT = Context.getAsConstantArrayType(T: Initializer->getType()); |
2605 | if (CAT) { |
2606 | // FIXME: Track that the array size was inferred rather than explicitly |
2607 | // specified. |
2608 | ArraySize = IntegerLiteral::Create( |
2609 | C: Context, V: CAT->getSize(), type: Context.getSizeType(), l: TypeRange.getEnd()); |
2610 | } else { |
2611 | Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init) |
2612 | << Initializer->getSourceRange(); |
2613 | } |
2614 | } |
2615 | } |
2616 | |
2617 | // Mark the new and delete operators as referenced. |
2618 | if (OperatorNew) { |
2619 | if (DiagnoseUseOfDecl(OperatorNew, StartLoc)) |
2620 | return ExprError(); |
2621 | MarkFunctionReferenced(Loc: StartLoc, Func: OperatorNew); |
2622 | } |
2623 | if (OperatorDelete) { |
2624 | if (DiagnoseUseOfDecl(OperatorDelete, StartLoc)) |
2625 | return ExprError(); |
2626 | MarkFunctionReferenced(Loc: StartLoc, Func: OperatorDelete); |
2627 | } |
2628 | |
2629 | return CXXNewExpr::Create(Ctx: Context, IsGlobalNew: UseGlobal, OperatorNew, OperatorDelete, |
2630 | IAP, UsualArrayDeleteWantsSize, PlacementArgs, |
2631 | TypeIdParens, ArraySize, InitializationStyle: InitStyle, Initializer, |
2632 | Ty: ResultType, AllocatedTypeInfo: AllocTypeInfo, Range, DirectInitRange); |
2633 | } |
2634 | |
2635 | bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc, |
2636 | SourceRange R) { |
2637 | // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an |
2638 | // abstract class type or array thereof. |
2639 | if (AllocType->isFunctionType()) |
2640 | return Diag(Loc, diag::err_bad_new_type) |
2641 | << AllocType << 0 << R; |
2642 | else if (AllocType->isReferenceType()) |
2643 | return Diag(Loc, diag::err_bad_new_type) |
2644 | << AllocType << 1 << R; |
2645 | else if (!AllocType->isDependentType() && |
2646 | RequireCompleteSizedType( |
2647 | Loc, AllocType, diag::err_new_incomplete_or_sizeless_type, R)) |
2648 | return true; |
2649 | else if (RequireNonAbstractType(Loc, AllocType, |
2650 | diag::err_allocation_of_abstract_type)) |
2651 | return true; |
2652 | else if (AllocType->isVariablyModifiedType()) |
2653 | return Diag(Loc, diag::err_variably_modified_new_type) |
2654 | << AllocType; |
2655 | else if (AllocType.getAddressSpace() != LangAS::Default && |
2656 | !getLangOpts().OpenCLCPlusPlus) |
2657 | return Diag(Loc, diag::err_address_space_qualified_new) |
2658 | << AllocType.getUnqualifiedType() |
2659 | << AllocType.getQualifiers().getAddressSpaceAttributePrintValue(); |
2660 | else if (getLangOpts().ObjCAutoRefCount) { |
2661 | if (const ArrayType *AT = Context.getAsArrayType(T: AllocType)) { |
2662 | QualType BaseAllocType = Context.getBaseElementType(VAT: AT); |
2663 | if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None && |
2664 | BaseAllocType->isObjCLifetimeType()) |
2665 | return Diag(Loc, diag::err_arc_new_array_without_ownership) |
2666 | << BaseAllocType; |
2667 | } |
2668 | } |
2669 | |
2670 | return false; |
2671 | } |
2672 | |
2673 | enum class ResolveMode { Typed, Untyped }; |
2674 | static bool resolveAllocationOverloadInterior( |
2675 | Sema &S, LookupResult &R, SourceRange Range, ResolveMode Mode, |
2676 | SmallVectorImpl<Expr *> &Args, AlignedAllocationMode &PassAlignment, |
2677 | FunctionDecl *&Operator, OverloadCandidateSet *AlignedCandidates, |
2678 | Expr *AlignArg, bool Diagnose) { |
2679 | unsigned NonTypeArgumentOffset = 0; |
2680 | if (Mode == ResolveMode::Typed) { |
2681 | ++NonTypeArgumentOffset; |
2682 | } |
2683 | |
2684 | OverloadCandidateSet Candidates(R.getNameLoc(), |
2685 | OverloadCandidateSet::CSK_Normal); |
2686 | for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end(); |
2687 | Alloc != AllocEnd; ++Alloc) { |
2688 | // Even member operator new/delete are implicitly treated as |
2689 | // static, so don't use AddMemberCandidate. |
2690 | NamedDecl *D = (*Alloc)->getUnderlyingDecl(); |
2691 | bool IsTypeAware = D->getAsFunction()->isTypeAwareOperatorNewOrDelete(); |
2692 | if (IsTypeAware == (Mode != ResolveMode::Typed)) |
2693 | continue; |
2694 | |
2695 | if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(Val: D)) { |
2696 | S.AddTemplateOverloadCandidate(FunctionTemplate: FnTemplate, FoundDecl: Alloc.getPair(), |
2697 | /*ExplicitTemplateArgs=*/nullptr, Args, |
2698 | CandidateSet&: Candidates, |
2699 | /*SuppressUserConversions=*/false); |
2700 | continue; |
2701 | } |
2702 | |
2703 | FunctionDecl *Fn = cast<FunctionDecl>(Val: D); |
2704 | S.AddOverloadCandidate(Function: Fn, FoundDecl: Alloc.getPair(), Args, CandidateSet&: Candidates, |
2705 | /*SuppressUserConversions=*/false); |
2706 | } |
2707 | |
2708 | // Do the resolution. |
2709 | OverloadCandidateSet::iterator Best; |
2710 | switch (Candidates.BestViableFunction(S, Loc: R.getNameLoc(), Best)) { |
2711 | case OR_Success: { |
2712 | // Got one! |
2713 | FunctionDecl *FnDecl = Best->Function; |
2714 | if (S.CheckAllocationAccess(OperatorLoc: R.getNameLoc(), PlacementRange: Range, NamingClass: R.getNamingClass(), |
2715 | FoundDecl: Best->FoundDecl) == Sema::AR_inaccessible) |
2716 | return true; |
2717 | |
2718 | Operator = FnDecl; |
2719 | return false; |
2720 | } |
2721 | |
2722 | case OR_No_Viable_Function: |
2723 | // C++17 [expr.new]p13: |
2724 | // If no matching function is found and the allocated object type has |
2725 | // new-extended alignment, the alignment argument is removed from the |
2726 | // argument list, and overload resolution is performed again. |
2727 | if (isAlignedAllocation(Mode: PassAlignment)) { |
2728 | PassAlignment = AlignedAllocationMode::No; |
2729 | AlignArg = Args[NonTypeArgumentOffset + 1]; |
2730 | Args.erase(CI: Args.begin() + NonTypeArgumentOffset + 1); |
2731 | return resolveAllocationOverloadInterior(S, R, Range, Mode, Args, |
2732 | PassAlignment, Operator, |
2733 | AlignedCandidates: &Candidates, AlignArg, Diagnose); |
2734 | } |
2735 | |
2736 | // MSVC will fall back on trying to find a matching global operator new |
2737 | // if operator new[] cannot be found. Also, MSVC will leak by not |
2738 | // generating a call to operator delete or operator delete[], but we |
2739 | // will not replicate that bug. |
2740 | // FIXME: Find out how this interacts with the std::align_val_t fallback |
2741 | // once MSVC implements it. |
2742 | if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New && |
2743 | S.Context.getLangOpts().MSVCCompat && Mode != ResolveMode::Typed) { |
2744 | R.clear(); |
2745 | R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(Op: OO_New)); |
2746 | S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl()); |
2747 | // FIXME: This will give bad diagnostics pointing at the wrong functions. |
2748 | return resolveAllocationOverloadInterior(S, R, Range, Mode, Args, |
2749 | PassAlignment, Operator, |
2750 | /*Candidates=*/AlignedCandidates: nullptr, |
2751 | /*AlignArg=*/nullptr, Diagnose); |
2752 | } |
2753 | if (Mode == ResolveMode::Typed) { |
2754 | // If we can't find a matching type aware operator we don't consider this |
2755 | // a failure. |
2756 | Operator = nullptr; |
2757 | return false; |
2758 | } |
2759 | if (Diagnose) { |
2760 | // If this is an allocation of the form 'new (p) X' for some object |
2761 | // pointer p (or an expression that will decay to such a pointer), |
2762 | // diagnose the missing inclusion of <new>. |
2763 | if (!R.isClassLookup() && Args.size() == 2 && |
2764 | (Args[1]->getType()->isObjectPointerType() || |
2765 | Args[1]->getType()->isArrayType())) { |
2766 | S.Diag(R.getNameLoc(), diag::err_need_header_before_placement_new) |
2767 | << R.getLookupName() << Range; |
2768 | // Listing the candidates is unlikely to be useful; skip it. |
2769 | return true; |
2770 | } |
2771 | |
2772 | // Finish checking all candidates before we note any. This checking can |
2773 | // produce additional diagnostics so can't be interleaved with our |
2774 | // emission of notes. |
2775 | // |
2776 | // For an aligned allocation, separately check the aligned and unaligned |
2777 | // candidates with their respective argument lists. |
2778 | SmallVector<OverloadCandidate*, 32> Cands; |
2779 | SmallVector<OverloadCandidate*, 32> AlignedCands; |
2780 | llvm::SmallVector<Expr*, 4> AlignedArgs; |
2781 | if (AlignedCandidates) { |
2782 | auto IsAligned = [NonTypeArgumentOffset](OverloadCandidate &C) { |
2783 | auto AlignArgOffset = NonTypeArgumentOffset + 1; |
2784 | return C.Function->getNumParams() > AlignArgOffset && |
2785 | C.Function->getParamDecl(AlignArgOffset) |
2786 | ->getType() |
2787 | ->isAlignValT(); |
2788 | }; |
2789 | auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); }; |
2790 | |
2791 | AlignedArgs.reserve(N: Args.size() + NonTypeArgumentOffset + 1); |
2792 | for (unsigned Idx = 0; Idx < NonTypeArgumentOffset + 1; ++Idx) |
2793 | AlignedArgs.push_back(Elt: Args[Idx]); |
2794 | AlignedArgs.push_back(Elt: AlignArg); |
2795 | AlignedArgs.append(in_start: Args.begin() + NonTypeArgumentOffset + 1, |
2796 | in_end: Args.end()); |
2797 | AlignedCands = AlignedCandidates->CompleteCandidates( |
2798 | S, OCD_AllCandidates, AlignedArgs, R.getNameLoc(), IsAligned); |
2799 | |
2800 | Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args, |
2801 | R.getNameLoc(), IsUnaligned); |
2802 | } else { |
2803 | Cands = Candidates.CompleteCandidates(S, OCD: OCD_AllCandidates, Args, |
2804 | OpLoc: R.getNameLoc()); |
2805 | } |
2806 | |
2807 | S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call) |
2808 | << R.getLookupName() << Range; |
2809 | if (AlignedCandidates) |
2810 | AlignedCandidates->NoteCandidates(S, Args: AlignedArgs, Cands: AlignedCands, Opc: "", |
2811 | OpLoc: R.getNameLoc()); |
2812 | Candidates.NoteCandidates(S, Args, Cands, Opc: "", OpLoc: R.getNameLoc()); |
2813 | } |
2814 | return true; |
2815 | |
2816 | case OR_Ambiguous: |
2817 | if (Diagnose) { |
2818 | Candidates.NoteCandidates( |
2819 | PartialDiagnosticAt(R.getNameLoc(), |
2820 | S.PDiag(diag::err_ovl_ambiguous_call) |
2821 | << R.getLookupName() << Range), |
2822 | S, OCD_AmbiguousCandidates, Args); |
2823 | } |
2824 | return true; |
2825 | |
2826 | case OR_Deleted: { |
2827 | if (Diagnose) |
2828 | S.DiagnoseUseOfDeletedFunction(Loc: R.getNameLoc(), Range, Name: R.getLookupName(), |
2829 | CandidateSet&: Candidates, Fn: Best->Function, Args); |
2830 | return true; |
2831 | } |
2832 | } |
2833 | llvm_unreachable("Unreachable, bad result from BestViableFunction"); |
2834 | } |
2835 | |
2836 | enum class DeallocLookupMode { Untyped, OptionallyTyped }; |
2837 | |
2838 | static void LookupGlobalDeallocationFunctions(Sema &S, SourceLocation Loc, |
2839 | LookupResult &FoundDelete, |
2840 | DeallocLookupMode Mode, |
2841 | DeclarationName Name) { |
2842 | S.LookupQualifiedName(FoundDelete, S.Context.getTranslationUnitDecl()); |
2843 | if (Mode != DeallocLookupMode::OptionallyTyped) { |
2844 | // We're going to remove either the typed or the non-typed |
2845 | bool RemoveTypedDecl = Mode == DeallocLookupMode::Untyped; |
2846 | LookupResult::Filter Filter = FoundDelete.makeFilter(); |
2847 | while (Filter.hasNext()) { |
2848 | FunctionDecl *FD = Filter.next()->getUnderlyingDecl()->getAsFunction(); |
2849 | if (FD->isTypeAwareOperatorNewOrDelete() == RemoveTypedDecl) |
2850 | Filter.erase(); |
2851 | } |
2852 | Filter.done(); |
2853 | } |
2854 | } |
2855 | |
2856 | static bool resolveAllocationOverload( |
2857 | Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args, |
2858 | ImplicitAllocationParameters &IAP, FunctionDecl *&Operator, |
2859 | OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) { |
2860 | Operator = nullptr; |
2861 | if (isTypeAwareAllocation(Mode: IAP.PassTypeIdentity)) { |
2862 | assert(S.isStdTypeIdentity(Args[0]->getType(), nullptr)); |
2863 | // The internal overload resolution work mutates the argument list |
2864 | // in accordance with the spec. We may want to change that in future, |
2865 | // but for now we deal with this by making a copy of the non-type-identity |
2866 | // arguments. |
2867 | SmallVector<Expr *> UntypedParameters; |
2868 | UntypedParameters.reserve(N: Args.size() - 1); |
2869 | UntypedParameters.push_back(Elt: Args[1]); |
2870 | // Type aware allocation implicitly includes the alignment parameter so |
2871 | // only include it in the untyped parameter list if alignment was explicitly |
2872 | // requested |
2873 | if (isAlignedAllocation(Mode: IAP.PassAlignment)) |
2874 | UntypedParameters.push_back(Elt: Args[2]); |
2875 | UntypedParameters.append(in_start: Args.begin() + 3, in_end: Args.end()); |
2876 | |
2877 | AlignedAllocationMode InitialAlignmentMode = IAP.PassAlignment; |
2878 | IAP.PassAlignment = AlignedAllocationMode::Yes; |
2879 | if (resolveAllocationOverloadInterior( |
2880 | S, R, Range, Mode: ResolveMode::Typed, Args, PassAlignment&: IAP.PassAlignment, Operator, |
2881 | AlignedCandidates, AlignArg, Diagnose)) |
2882 | return true; |
2883 | if (Operator) |
2884 | return false; |
2885 | |
2886 | // If we got to this point we could not find a matching typed operator |
2887 | // so we update the IAP flags, and revert to our stored copy of the |
2888 | // type-identity-less argument list. |
2889 | IAP.PassTypeIdentity = TypeAwareAllocationMode::No; |
2890 | IAP.PassAlignment = InitialAlignmentMode; |
2891 | Args = std::move(UntypedParameters); |
2892 | } |
2893 | assert(!S.isStdTypeIdentity(Args[0]->getType(), nullptr)); |
2894 | return resolveAllocationOverloadInterior( |
2895 | S, R, Range, Mode: ResolveMode::Untyped, Args, PassAlignment&: IAP.PassAlignment, Operator, |
2896 | AlignedCandidates, AlignArg, Diagnose); |
2897 | } |
2898 | |
2899 | bool Sema::FindAllocationFunctions( |
2900 | SourceLocation StartLoc, SourceRange Range, |
2901 | AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope, |
2902 | QualType AllocType, bool IsArray, ImplicitAllocationParameters &IAP, |
2903 | MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew, |
2904 | FunctionDecl *&OperatorDelete, bool Diagnose) { |
2905 | // --- Choosing an allocation function --- |
2906 | // C++ 5.3.4p8 - 14 & 18 |
2907 | // 1) If looking in AllocationFunctionScope::Global scope for allocation |
2908 | // functions, only look in |
2909 | // the global scope. Else, if AllocationFunctionScope::Class, only look in |
2910 | // the scope of the allocated class. If AllocationFunctionScope::Both, look |
2911 | // in both. |
2912 | // 2) If an array size is given, look for operator new[], else look for |
2913 | // operator new. |
2914 | // 3) The first argument is always size_t. Append the arguments from the |
2915 | // placement form. |
2916 | |
2917 | SmallVector<Expr*, 8> AllocArgs; |
2918 | AllocArgs.reserve(N: IAP.getNumImplicitArgs() + PlaceArgs.size()); |
2919 | |
2920 | // C++ [expr.new]p8: |
2921 | // If the allocated type is a non-array type, the allocation |
2922 | // function's name is operator new and the deallocation function's |
2923 | // name is operator delete. If the allocated type is an array |
2924 | // type, the allocation function's name is operator new[] and the |
2925 | // deallocation function's name is operator delete[]. |
2926 | DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName( |
2927 | Op: IsArray ? OO_Array_New : OO_New); |
2928 | |
2929 | QualType AllocElemType = Context.getBaseElementType(QT: AllocType); |
2930 | |
2931 | // We don't care about the actual value of these arguments. |
2932 | // FIXME: Should the Sema create the expression and embed it in the syntax |
2933 | // tree? Or should the consumer just recalculate the value? |
2934 | // FIXME: Using a dummy value will interact poorly with attribute enable_if. |
2935 | |
2936 | // We use size_t as a stand in so that we can construct the init |
2937 | // expr on the stack |
2938 | QualType TypeIdentity = Context.getSizeType(); |
2939 | if (isTypeAwareAllocation(Mode: IAP.PassTypeIdentity)) { |
2940 | QualType SpecializedTypeIdentity = |
2941 | tryBuildStdTypeIdentity(Type: IAP.Type, Loc: StartLoc); |
2942 | if (!SpecializedTypeIdentity.isNull()) { |
2943 | TypeIdentity = SpecializedTypeIdentity; |
2944 | if (RequireCompleteType(StartLoc, TypeIdentity, |
2945 | diag::err_incomplete_type)) |
2946 | return true; |
2947 | } else |
2948 | IAP.PassTypeIdentity = TypeAwareAllocationMode::No; |
2949 | } |
2950 | TypeAwareAllocationMode OriginalTypeAwareState = IAP.PassTypeIdentity; |
2951 | |
2952 | CXXScalarValueInitExpr TypeIdentityParam(TypeIdentity, nullptr, StartLoc); |
2953 | if (isTypeAwareAllocation(Mode: IAP.PassTypeIdentity)) |
2954 | AllocArgs.push_back(&TypeIdentityParam); |
2955 | |
2956 | QualType SizeTy = Context.getSizeType(); |
2957 | unsigned SizeTyWidth = Context.getTypeSize(T: SizeTy); |
2958 | IntegerLiteral Size(Context, llvm::APInt::getZero(numBits: SizeTyWidth), SizeTy, |
2959 | SourceLocation()); |
2960 | AllocArgs.push_back(&Size); |
2961 | |
2962 | QualType AlignValT = Context.VoidTy; |
2963 | bool IncludeAlignParam = isAlignedAllocation(Mode: IAP.PassAlignment) || |
2964 | isTypeAwareAllocation(Mode: IAP.PassTypeIdentity); |
2965 | if (IncludeAlignParam) { |
2966 | DeclareGlobalNewDelete(); |
2967 | AlignValT = Context.getTypeDeclType(getStdAlignValT()); |
2968 | } |
2969 | CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation()); |
2970 | if (IncludeAlignParam) |
2971 | AllocArgs.push_back(&Align); |
2972 | |
2973 | llvm::append_range(C&: AllocArgs, R&: PlaceArgs); |
2974 | |
2975 | // Find the allocation function. |
2976 | { |
2977 | LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName); |
2978 | |
2979 | // C++1z [expr.new]p9: |
2980 | // If the new-expression begins with a unary :: operator, the allocation |
2981 | // function's name is looked up in the global scope. Otherwise, if the |
2982 | // allocated type is a class type T or array thereof, the allocation |
2983 | // function's name is looked up in the scope of T. |
2984 | if (AllocElemType->isRecordType() && |
2985 | NewScope != AllocationFunctionScope::Global) |
2986 | LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl()); |
2987 | |
2988 | // We can see ambiguity here if the allocation function is found in |
2989 | // multiple base classes. |
2990 | if (R.isAmbiguous()) |
2991 | return true; |
2992 | |
2993 | // If this lookup fails to find the name, or if the allocated type is not |
2994 | // a class type, the allocation function's name is looked up in the |
2995 | // global scope. |
2996 | if (R.empty()) { |
2997 | if (NewScope == AllocationFunctionScope::Class) |
2998 | return true; |
2999 | |
3000 | LookupQualifiedName(R, Context.getTranslationUnitDecl()); |
3001 | } |
3002 | |
3003 | if (getLangOpts().OpenCLCPlusPlus && R.empty()) { |
3004 | if (PlaceArgs.empty()) { |
3005 | Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new"; |
3006 | } else { |
3007 | Diag(StartLoc, diag::err_openclcxx_placement_new); |
3008 | } |
3009 | return true; |
3010 | } |
3011 | |
3012 | assert(!R.empty() && "implicitly declared allocation functions not found"); |
3013 | assert(!R.isAmbiguous() && "global allocation functions are ambiguous"); |
3014 | |
3015 | // We do our own custom access checks below. |
3016 | R.suppressDiagnostics(); |
3017 | |
3018 | if (resolveAllocationOverload(S&: *this, R, Range, Args&: AllocArgs, IAP, Operator&: OperatorNew, |
3019 | /*Candidates=*/AlignedCandidates: nullptr, |
3020 | /*AlignArg=*/nullptr, Diagnose)) |
3021 | return true; |
3022 | } |
3023 | |
3024 | // We don't need an operator delete if we're running under -fno-exceptions. |
3025 | if (!getLangOpts().Exceptions) { |
3026 | OperatorDelete = nullptr; |
3027 | return false; |
3028 | } |
3029 | |
3030 | // Note, the name of OperatorNew might have been changed from array to |
3031 | // non-array by resolveAllocationOverload. |
3032 | DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( |
3033 | Op: OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New |
3034 | ? OO_Array_Delete |
3035 | : OO_Delete); |
3036 | |
3037 | // C++ [expr.new]p19: |
3038 | // |
3039 | // If the new-expression begins with a unary :: operator, the |
3040 | // deallocation function's name is looked up in the global |
3041 | // scope. Otherwise, if the allocated type is a class type T or an |
3042 | // array thereof, the deallocation function's name is looked up in |
3043 | // the scope of T. If this lookup fails to find the name, or if |
3044 | // the allocated type is not a class type or array thereof, the |
3045 | // deallocation function's name is looked up in the global scope. |
3046 | LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName); |
3047 | if (AllocElemType->isRecordType() && |
3048 | DeleteScope != AllocationFunctionScope::Global) { |
3049 | auto *RD = |
3050 | cast<CXXRecordDecl>(Val: AllocElemType->castAs<RecordType>()->getDecl()); |
3051 | LookupQualifiedName(FoundDelete, RD); |
3052 | } |
3053 | if (FoundDelete.isAmbiguous()) |
3054 | return true; // FIXME: clean up expressions? |
3055 | |
3056 | // Filter out any destroying operator deletes. We can't possibly call such a |
3057 | // function in this context, because we're handling the case where the object |
3058 | // was not successfully constructed. |
3059 | // FIXME: This is not covered by the language rules yet. |
3060 | { |
3061 | LookupResult::Filter Filter = FoundDelete.makeFilter(); |
3062 | while (Filter.hasNext()) { |
3063 | auto *FD = dyn_cast<FunctionDecl>(Val: Filter.next()->getUnderlyingDecl()); |
3064 | if (FD && FD->isDestroyingOperatorDelete()) |
3065 | Filter.erase(); |
3066 | } |
3067 | Filter.done(); |
3068 | } |
3069 | |
3070 | auto GetRedeclContext = [](Decl *D) { |
3071 | return D->getDeclContext()->getRedeclContext(); |
3072 | }; |
3073 | |
3074 | DeclContext *OperatorNewContext = GetRedeclContext(OperatorNew); |
3075 | |
3076 | bool FoundGlobalDelete = FoundDelete.empty(); |
3077 | bool IsClassScopedTypeAwareNew = |
3078 | isTypeAwareAllocation(Mode: IAP.PassTypeIdentity) && |
3079 | OperatorNewContext->isRecord(); |
3080 | auto DiagnoseMissingTypeAwareCleanupOperator = [&](bool IsPlacementOperator) { |
3081 | assert(isTypeAwareAllocation(IAP.PassTypeIdentity)); |
3082 | if (Diagnose) { |
3083 | Diag(StartLoc, diag::err_mismatching_type_aware_cleanup_deallocator) |
3084 | << OperatorNew->getDeclName() << IsPlacementOperator << DeleteName; |
3085 | Diag(OperatorNew->getLocation(), diag::note_type_aware_operator_declared) |
3086 | << OperatorNew->isTypeAwareOperatorNewOrDelete() |
3087 | << OperatorNew->getDeclName() << OperatorNewContext; |
3088 | } |
3089 | }; |
3090 | if (IsClassScopedTypeAwareNew && FoundDelete.empty()) { |
3091 | DiagnoseMissingTypeAwareCleanupOperator(/*isPlacementNew=*/false); |
3092 | return true; |
3093 | } |
3094 | if (FoundDelete.empty()) { |
3095 | FoundDelete.clear(Kind: LookupOrdinaryName); |
3096 | |
3097 | if (DeleteScope == AllocationFunctionScope::Class) |
3098 | return true; |
3099 | |
3100 | DeclareGlobalNewDelete(); |
3101 | DeallocLookupMode LookupMode = isTypeAwareAllocation(Mode: OriginalTypeAwareState) |
3102 | ? DeallocLookupMode::OptionallyTyped |
3103 | : DeallocLookupMode::Untyped; |
3104 | LookupGlobalDeallocationFunctions(S&: *this, Loc: StartLoc, FoundDelete, Mode: LookupMode, |
3105 | Name: DeleteName); |
3106 | } |
3107 | |
3108 | FoundDelete.suppressDiagnostics(); |
3109 | |
3110 | SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches; |
3111 | |
3112 | // Whether we're looking for a placement operator delete is dictated |
3113 | // by whether we selected a placement operator new, not by whether |
3114 | // we had explicit placement arguments. This matters for things like |
3115 | // struct A { void *operator new(size_t, int = 0); ... }; |
3116 | // A *a = new A() |
3117 | // |
3118 | // We don't have any definition for what a "placement allocation function" |
3119 | // is, but we assume it's any allocation function whose |
3120 | // parameter-declaration-clause is anything other than (size_t). |
3121 | // |
3122 | // FIXME: Should (size_t, std::align_val_t) also be considered non-placement? |
3123 | // This affects whether an exception from the constructor of an overaligned |
3124 | // type uses the sized or non-sized form of aligned operator delete. |
3125 | |
3126 | unsigned NonPlacementNewArgCount = 1; // size parameter |
3127 | if (isTypeAwareAllocation(Mode: IAP.PassTypeIdentity)) |
3128 | NonPlacementNewArgCount = |
3129 | /* type-identity */ 1 + /* size */ 1 + /* alignment */ 1; |
3130 | bool isPlacementNew = !PlaceArgs.empty() || |
3131 | OperatorNew->param_size() != NonPlacementNewArgCount || |
3132 | OperatorNew->isVariadic(); |
3133 | |
3134 | if (isPlacementNew) { |
3135 | // C++ [expr.new]p20: |
3136 | // A declaration of a placement deallocation function matches the |
3137 | // declaration of a placement allocation function if it has the |
3138 | // same number of parameters and, after parameter transformations |
3139 | // (8.3.5), all parameter types except the first are |
3140 | // identical. [...] |
3141 | // |
3142 | // To perform this comparison, we compute the function type that |
3143 | // the deallocation function should have, and use that type both |
3144 | // for template argument deduction and for comparison purposes. |
3145 | QualType ExpectedFunctionType; |
3146 | { |
3147 | auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>(); |
3148 | |
3149 | SmallVector<QualType, 6> ArgTypes; |
3150 | int InitialParamOffset = 0; |
3151 | if (isTypeAwareAllocation(Mode: IAP.PassTypeIdentity)) { |
3152 | ArgTypes.push_back(Elt: TypeIdentity); |
3153 | InitialParamOffset = 1; |
3154 | } |
3155 | ArgTypes.push_back(Elt: Context.VoidPtrTy); |
3156 | for (unsigned I = ArgTypes.size() - InitialParamOffset, |
3157 | N = Proto->getNumParams(); |
3158 | I < N; ++I) |
3159 | ArgTypes.push_back(Elt: Proto->getParamType(I)); |
3160 | |
3161 | FunctionProtoType::ExtProtoInfo EPI; |
3162 | // FIXME: This is not part of the standard's rule. |
3163 | EPI.Variadic = Proto->isVariadic(); |
3164 | |
3165 | ExpectedFunctionType |
3166 | = Context.getFunctionType(ResultTy: Context.VoidTy, Args: ArgTypes, EPI); |
3167 | } |
3168 | |
3169 | for (LookupResult::iterator D = FoundDelete.begin(), |
3170 | DEnd = FoundDelete.end(); |
3171 | D != DEnd; ++D) { |
3172 | FunctionDecl *Fn = nullptr; |
3173 | if (FunctionTemplateDecl *FnTmpl = |
3174 | dyn_cast<FunctionTemplateDecl>(Val: (*D)->getUnderlyingDecl())) { |
3175 | // Perform template argument deduction to try to match the |
3176 | // expected function type. |
3177 | TemplateDeductionInfo Info(StartLoc); |
3178 | if (DeduceTemplateArguments(FunctionTemplate: FnTmpl, ExplicitTemplateArgs: nullptr, ArgFunctionType: ExpectedFunctionType, Specialization&: Fn, |
3179 | Info) != TemplateDeductionResult::Success) |
3180 | continue; |
3181 | } else |
3182 | Fn = cast<FunctionDecl>(Val: (*D)->getUnderlyingDecl()); |
3183 | |
3184 | if (Context.hasSameType(adjustCCAndNoReturn(ArgFunctionType: Fn->getType(), |
3185 | FunctionType: ExpectedFunctionType, |
3186 | /*AdjustExcpetionSpec*/AdjustExceptionSpec: true), |
3187 | ExpectedFunctionType)) |
3188 | Matches.push_back(Elt: std::make_pair(x: D.getPair(), y&: Fn)); |
3189 | } |
3190 | |
3191 | if (getLangOpts().CUDA) |
3192 | CUDA().EraseUnwantedMatches(Caller: getCurFunctionDecl(/*AllowLambda=*/true), |
3193 | Matches); |
3194 | if (Matches.empty() && isTypeAwareAllocation(Mode: IAP.PassTypeIdentity)) { |
3195 | DiagnoseMissingTypeAwareCleanupOperator(isPlacementNew); |
3196 | return true; |
3197 | } |
3198 | } else { |
3199 | // C++1y [expr.new]p22: |
3200 | // For a non-placement allocation function, the normal deallocation |
3201 | // function lookup is used |
3202 | // |
3203 | // Per [expr.delete]p10, this lookup prefers a member operator delete |
3204 | // without a size_t argument, but prefers a non-member operator delete |
3205 | // with a size_t where possible (which it always is in this case). |
3206 | llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns; |
3207 | ImplicitDeallocationParameters IDP = { |
3208 | AllocElemType, OriginalTypeAwareState, |
3209 | alignedAllocationModeFromBool( |
3210 | IsAligned: hasNewExtendedAlignment(S&: *this, AllocType: AllocElemType)), |
3211 | sizedDeallocationModeFromBool(IsSized: FoundGlobalDelete)}; |
3212 | UsualDeallocFnInfo Selected = resolveDeallocationOverload( |
3213 | S&: *this, R&: FoundDelete, IDP, Loc: StartLoc, BestFns: &BestDeallocFns); |
3214 | if (Selected && BestDeallocFns.empty()) |
3215 | Matches.push_back(Elt: std::make_pair(x&: Selected.Found, y&: Selected.FD)); |
3216 | else { |
3217 | // If we failed to select an operator, all remaining functions are viable |
3218 | // but ambiguous. |
3219 | for (auto Fn : BestDeallocFns) |
3220 | Matches.push_back(Elt: std::make_pair(x&: Fn.Found, y&: Fn.FD)); |
3221 | } |
3222 | } |
3223 | |
3224 | // C++ [expr.new]p20: |
3225 | // [...] If the lookup finds a single matching deallocation |
3226 | // function, that function will be called; otherwise, no |
3227 | // deallocation function will be called. |
3228 | if (Matches.size() == 1) { |
3229 | OperatorDelete = Matches[0].second; |
3230 | DeclContext *OperatorDeleteContext = GetRedeclContext(OperatorDelete); |
3231 | bool FoundTypeAwareOperator = |
3232 | OperatorDelete->isTypeAwareOperatorNewOrDelete() || |
3233 | OperatorNew->isTypeAwareOperatorNewOrDelete(); |
3234 | if (Diagnose && FoundTypeAwareOperator) { |
3235 | bool MismatchedTypeAwareness = |
3236 | OperatorDelete->isTypeAwareOperatorNewOrDelete() != |
3237 | OperatorNew->isTypeAwareOperatorNewOrDelete(); |
3238 | bool MismatchedContext = OperatorDeleteContext != OperatorNewContext; |
3239 | if (MismatchedTypeAwareness || MismatchedContext) { |
3240 | FunctionDecl *Operators[] = {OperatorDelete, OperatorNew}; |
3241 | bool TypeAwareOperatorIndex = |
3242 | OperatorNew->isTypeAwareOperatorNewOrDelete(); |
3243 | Diag(StartLoc, diag::err_mismatching_type_aware_cleanup_deallocator) |
3244 | << Operators[TypeAwareOperatorIndex]->getDeclName() |
3245 | << isPlacementNew |
3246 | << Operators[!TypeAwareOperatorIndex]->getDeclName() |
3247 | << GetRedeclContext(Operators[TypeAwareOperatorIndex]); |
3248 | Diag(OperatorNew->getLocation(), |
3249 | diag::note_type_aware_operator_declared) |
3250 | << OperatorNew->isTypeAwareOperatorNewOrDelete() |
3251 | << OperatorNew->getDeclName() << OperatorNewContext; |
3252 | Diag(OperatorDelete->getLocation(), |
3253 | diag::note_type_aware_operator_declared) |
3254 | << OperatorDelete->isTypeAwareOperatorNewOrDelete() |
3255 | << OperatorDelete->getDeclName() << OperatorDeleteContext; |
3256 | } |
3257 | } |
3258 | |
3259 | // C++1z [expr.new]p23: |
3260 | // If the lookup finds a usual deallocation function (3.7.4.2) |
3261 | // with a parameter of type std::size_t and that function, considered |
3262 | // as a placement deallocation function, would have been |
3263 | // selected as a match for the allocation function, the program |
3264 | // is ill-formed. |
3265 | if (getLangOpts().CPlusPlus11 && isPlacementNew && |
3266 | isNonPlacementDeallocationFunction(S&: *this, FD: OperatorDelete)) { |
3267 | UsualDeallocFnInfo Info(*this, |
3268 | DeclAccessPair::make(OperatorDelete, AS_public), |
3269 | AllocElemType, StartLoc); |
3270 | // Core issue, per mail to core reflector, 2016-10-09: |
3271 | // If this is a member operator delete, and there is a corresponding |
3272 | // non-sized member operator delete, this isn't /really/ a sized |
3273 | // deallocation function, it just happens to have a size_t parameter. |
3274 | bool IsSizedDelete = isSizedDeallocation(Info.IDP.PassSize); |
3275 | if (IsSizedDelete && !FoundGlobalDelete) { |
3276 | ImplicitDeallocationParameters SizeTestingIDP = { |
3277 | AllocElemType, Info.IDP.PassTypeIdentity, Info.IDP.PassAlignment, |
3278 | SizedDeallocationMode::No}; |
3279 | auto NonSizedDelete = resolveDeallocationOverload( |
3280 | S&: *this, R&: FoundDelete, IDP: SizeTestingIDP, Loc: StartLoc); |
3281 | if (NonSizedDelete && |
3282 | !isSizedDeallocation(NonSizedDelete.IDP.PassSize) && |
3283 | NonSizedDelete.IDP.PassAlignment == Info.IDP.PassAlignment) |
3284 | IsSizedDelete = false; |
3285 | } |
3286 | |
3287 | if (IsSizedDelete && !isTypeAwareAllocation(Mode: IAP.PassTypeIdentity)) { |
3288 | SourceRange R = PlaceArgs.empty() |
3289 | ? SourceRange() |
3290 | : SourceRange(PlaceArgs.front()->getBeginLoc(), |
3291 | PlaceArgs.back()->getEndLoc()); |
3292 | Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R; |
3293 | if (!OperatorDelete->isImplicit()) |
3294 | Diag(OperatorDelete->getLocation(), diag::note_previous_decl) |
3295 | << DeleteName; |
3296 | } |
3297 | } |
3298 | if (CheckDeleteOperator(S&: *this, StartLoc, Range, Diagnose, |
3299 | NamingClass: FoundDelete.getNamingClass(), Decl: Matches[0].first, |
3300 | Operator: Matches[0].second)) |
3301 | return true; |
3302 | |
3303 | } else if (!Matches.empty()) { |
3304 | // We found multiple suitable operators. Per [expr.new]p20, that means we |
3305 | // call no 'operator delete' function, but we should at least warn the user. |
3306 | // FIXME: Suppress this warning if the construction cannot throw. |
3307 | Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found) |
3308 | << DeleteName << AllocElemType; |
3309 | |
3310 | for (auto &Match : Matches) |
3311 | Diag(Match.second->getLocation(), |
3312 | diag::note_member_declared_here) << DeleteName; |
3313 | } |
3314 | |
3315 | return false; |
3316 | } |
3317 | |
3318 | void Sema::DeclareGlobalNewDelete() { |
3319 | if (GlobalNewDeleteDeclared) |
3320 | return; |
3321 | |
3322 | // The implicitly declared new and delete operators |
3323 | // are not supported in OpenCL. |
3324 | if (getLangOpts().OpenCLCPlusPlus) |
3325 | return; |
3326 | |
3327 | // C++ [basic.stc.dynamic.general]p2: |
3328 | // The library provides default definitions for the global allocation |
3329 | // and deallocation functions. Some global allocation and deallocation |
3330 | // functions are replaceable ([new.delete]); these are attached to the |
3331 | // global module ([module.unit]). |
3332 | if (getLangOpts().CPlusPlusModules && getCurrentModule()) |
3333 | PushGlobalModuleFragment(BeginLoc: SourceLocation()); |
3334 | |
3335 | // C++ [basic.std.dynamic]p2: |
3336 | // [...] The following allocation and deallocation functions (18.4) are |
3337 | // implicitly declared in global scope in each translation unit of a |
3338 | // program |
3339 | // |
3340 | // C++03: |
3341 | // void* operator new(std::size_t) throw(std::bad_alloc); |
3342 | // void* operator new[](std::size_t) throw(std::bad_alloc); |
3343 | // void operator delete(void*) throw(); |
3344 | // void operator delete[](void*) throw(); |
3345 | // C++11: |
3346 | // void* operator new(std::size_t); |
3347 | // void* operator new[](std::size_t); |
3348 | // void operator delete(void*) noexcept; |
3349 | // void operator delete[](void*) noexcept; |
3350 | // C++1y: |
3351 | // void* operator new(std::size_t); |
3352 | // void* operator new[](std::size_t); |
3353 | // void operator delete(void*) noexcept; |
3354 | // void operator delete[](void*) noexcept; |
3355 | // void operator delete(void*, std::size_t) noexcept; |
3356 | // void operator delete[](void*, std::size_t) noexcept; |
3357 | // |
3358 | // These implicit declarations introduce only the function names operator |
3359 | // new, operator new[], operator delete, operator delete[]. |
3360 | // |
3361 | // Here, we need to refer to std::bad_alloc, so we will implicitly declare |
3362 | // "std" or "bad_alloc" as necessary to form the exception specification. |
3363 | // However, we do not make these implicit declarations visible to name |
3364 | // lookup. |
3365 | if (!StdBadAlloc && !getLangOpts().CPlusPlus11) { |
3366 | // The "std::bad_alloc" class has not yet been declared, so build it |
3367 | // implicitly. |
3368 | StdBadAlloc = CXXRecordDecl::Create( |
3369 | Context, TagTypeKind::Class, getOrCreateStdNamespace(), |
3370 | SourceLocation(), SourceLocation(), |
3371 | &PP.getIdentifierTable().get(Name: "bad_alloc"), nullptr); |
3372 | getStdBadAlloc()->setImplicit(true); |
3373 | |
3374 | // The implicitly declared "std::bad_alloc" should live in global module |
3375 | // fragment. |
3376 | if (TheGlobalModuleFragment) { |
3377 | getStdBadAlloc()->setModuleOwnershipKind( |
3378 | Decl::ModuleOwnershipKind::ReachableWhenImported); |
3379 | getStdBadAlloc()->setLocalOwningModule(TheGlobalModuleFragment); |
3380 | } |
3381 | } |
3382 | if (!StdAlignValT && getLangOpts().AlignedAllocation) { |
3383 | // The "std::align_val_t" enum class has not yet been declared, so build it |
3384 | // implicitly. |
3385 | auto *AlignValT = EnumDecl::Create( |
3386 | Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(), |
3387 | &PP.getIdentifierTable().get(Name: "align_val_t"), nullptr, true, true, true); |
3388 | |
3389 | // The implicitly declared "std::align_val_t" should live in global module |
3390 | // fragment. |
3391 | if (TheGlobalModuleFragment) { |
3392 | AlignValT->setModuleOwnershipKind( |
3393 | Decl::ModuleOwnershipKind::ReachableWhenImported); |
3394 | AlignValT->setLocalOwningModule(TheGlobalModuleFragment); |
3395 | } |
3396 | |
3397 | AlignValT->setIntegerType(Context.getSizeType()); |
3398 | AlignValT->setPromotionType(Context.getSizeType()); |
3399 | AlignValT->setImplicit(true); |
3400 | |
3401 | StdAlignValT = AlignValT; |
3402 | } |
3403 | |
3404 | GlobalNewDeleteDeclared = true; |
3405 | |
3406 | QualType VoidPtr = Context.getPointerType(Context.VoidTy); |
3407 | QualType SizeT = Context.getSizeType(); |
3408 | |
3409 | auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind, |
3410 | QualType Return, QualType Param) { |
3411 | llvm::SmallVector<QualType, 3> Params; |
3412 | Params.push_back(Elt: Param); |
3413 | |
3414 | // Create up to four variants of the function (sized/aligned). |
3415 | bool HasSizedVariant = getLangOpts().SizedDeallocation && |
3416 | (Kind == OO_Delete || Kind == OO_Array_Delete); |
3417 | bool HasAlignedVariant = getLangOpts().AlignedAllocation; |
3418 | |
3419 | int NumSizeVariants = (HasSizedVariant ? 2 : 1); |
3420 | int NumAlignVariants = (HasAlignedVariant ? 2 : 1); |
3421 | for (int Sized = 0; Sized < NumSizeVariants; ++Sized) { |
3422 | if (Sized) |
3423 | Params.push_back(Elt: SizeT); |
3424 | |
3425 | for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) { |
3426 | if (Aligned) |
3427 | Params.push_back(Elt: Context.getTypeDeclType(getStdAlignValT())); |
3428 | |
3429 | DeclareGlobalAllocationFunction( |
3430 | Name: Context.DeclarationNames.getCXXOperatorName(Op: Kind), Return, Params); |
3431 | |
3432 | if (Aligned) |
3433 | Params.pop_back(); |
3434 | } |
3435 | } |
3436 | }; |
3437 | |
3438 | DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT); |
3439 | DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT); |
3440 | DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr); |
3441 | DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr); |
3442 | |
3443 | if (getLangOpts().CPlusPlusModules && getCurrentModule()) |
3444 | PopGlobalModuleFragment(); |
3445 | } |
3446 | |
3447 | /// DeclareGlobalAllocationFunction - Declares a single implicit global |
3448 | /// allocation function if it doesn't already exist. |
3449 | void Sema::DeclareGlobalAllocationFunction(DeclarationName Name, |
3450 | QualType Return, |
3451 | ArrayRef<QualType> Params) { |
3452 | DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); |
3453 | |
3454 | // Check if this function is already declared. |
3455 | DeclContext::lookup_result R = GlobalCtx->lookup(Name); |
3456 | for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end(); |
3457 | Alloc != AllocEnd; ++Alloc) { |
3458 | // Only look at non-template functions, as it is the predefined, |
3459 | // non-templated allocation function we are trying to declare here. |
3460 | if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Val: *Alloc)) { |
3461 | if (Func->getNumParams() == Params.size()) { |
3462 | llvm::SmallVector<QualType, 3> FuncParams; |
3463 | for (auto *P : Func->parameters()) |
3464 | FuncParams.push_back( |
3465 | Context.getCanonicalType(P->getType().getUnqualifiedType())); |
3466 | if (llvm::ArrayRef(FuncParams) == Params) { |
3467 | // Make the function visible to name lookup, even if we found it in |
3468 | // an unimported module. It either is an implicitly-declared global |
3469 | // allocation function, or is suppressing that function. |
3470 | Func->setVisibleDespiteOwningModule(); |
3471 | return; |
3472 | } |
3473 | } |
3474 | } |
3475 | } |
3476 | |
3477 | FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention( |
3478 | /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true)); |
3479 | |
3480 | QualType BadAllocType; |
3481 | bool HasBadAllocExceptionSpec = Name.isAnyOperatorNew(); |
3482 | if (HasBadAllocExceptionSpec) { |
3483 | if (!getLangOpts().CPlusPlus11) { |
3484 | BadAllocType = Context.getTypeDeclType(getStdBadAlloc()); |
3485 | assert(StdBadAlloc && "Must have std::bad_alloc declared"); |
3486 | EPI.ExceptionSpec.Type = EST_Dynamic; |
3487 | EPI.ExceptionSpec.Exceptions = llvm::ArrayRef(BadAllocType); |
3488 | } |
3489 | if (getLangOpts().NewInfallible) { |
3490 | EPI.ExceptionSpec.Type = EST_DynamicNone; |
3491 | } |
3492 | } else { |
3493 | EPI.ExceptionSpec = |
3494 | getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone; |
3495 | } |
3496 | |
3497 | auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) { |
3498 | QualType FnType = Context.getFunctionType(ResultTy: Return, Args: Params, EPI); |
3499 | FunctionDecl *Alloc = FunctionDecl::Create( |
3500 | C&: Context, DC: GlobalCtx, StartLoc: SourceLocation(), NLoc: SourceLocation(), N: Name, T: FnType, |
3501 | /*TInfo=*/nullptr, SC: SC_None, UsesFPIntrin: getCurFPFeatures().isFPConstrained(), isInlineSpecified: false, |
3502 | hasWrittenPrototype: true); |
3503 | Alloc->setImplicit(); |
3504 | // Global allocation functions should always be visible. |
3505 | Alloc->setVisibleDespiteOwningModule(); |
3506 | |
3507 | if (HasBadAllocExceptionSpec && getLangOpts().NewInfallible && |
3508 | !getLangOpts().CheckNew) |
3509 | Alloc->addAttr( |
3510 | ReturnsNonNullAttr::CreateImplicit(Context, Alloc->getLocation())); |
3511 | |
3512 | // C++ [basic.stc.dynamic.general]p2: |
3513 | // The library provides default definitions for the global allocation |
3514 | // and deallocation functions. Some global allocation and deallocation |
3515 | // functions are replaceable ([new.delete]); these are attached to the |
3516 | // global module ([module.unit]). |
3517 | // |
3518 | // In the language wording, these functions are attched to the global |
3519 | // module all the time. But in the implementation, the global module |
3520 | // is only meaningful when we're in a module unit. So here we attach |
3521 | // these allocation functions to global module conditionally. |
3522 | if (TheGlobalModuleFragment) { |
3523 | Alloc->setModuleOwnershipKind( |
3524 | Decl::ModuleOwnershipKind::ReachableWhenImported); |
3525 | Alloc->setLocalOwningModule(TheGlobalModuleFragment); |
3526 | } |
3527 | |
3528 | if (LangOpts.hasGlobalAllocationFunctionVisibility()) |
3529 | Alloc->addAttr(VisibilityAttr::CreateImplicit( |
3530 | Context, LangOpts.hasHiddenGlobalAllocationFunctionVisibility() |
3531 | ? VisibilityAttr::Hidden |
3532 | : LangOpts.hasProtectedGlobalAllocationFunctionVisibility() |
3533 | ? VisibilityAttr::Protected |
3534 | : VisibilityAttr::Default)); |
3535 | |
3536 | llvm::SmallVector<ParmVarDecl *, 3> ParamDecls; |
3537 | for (QualType T : Params) { |
3538 | ParamDecls.push_back(Elt: ParmVarDecl::Create( |
3539 | Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T, |
3540 | /*TInfo=*/nullptr, SC_None, nullptr)); |
3541 | ParamDecls.back()->setImplicit(); |
3542 | } |
3543 | Alloc->setParams(ParamDecls); |
3544 | if (ExtraAttr) |
3545 | Alloc->addAttr(ExtraAttr); |
3546 | AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD: Alloc); |
3547 | Context.getTranslationUnitDecl()->addDecl(Alloc); |
3548 | IdResolver.tryAddTopLevelDecl(Alloc, Name); |
3549 | }; |
3550 | |
3551 | if (!LangOpts.CUDA) |
3552 | CreateAllocationFunctionDecl(nullptr); |
3553 | else { |
3554 | // Host and device get their own declaration so each can be |
3555 | // defined or re-declared independently. |
3556 | CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context)); |
3557 | CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context)); |
3558 | } |
3559 | } |
3560 | |
3561 | FunctionDecl * |
3562 | Sema::FindUsualDeallocationFunction(SourceLocation StartLoc, |
3563 | ImplicitDeallocationParameters IDP, |
3564 | DeclarationName Name) { |
3565 | DeclareGlobalNewDelete(); |
3566 | |
3567 | LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName); |
3568 | LookupGlobalDeallocationFunctions(S&: *this, Loc: StartLoc, FoundDelete, |
3569 | Mode: DeallocLookupMode::OptionallyTyped, Name); |
3570 | |
3571 | // FIXME: It's possible for this to result in ambiguity, through a |
3572 | // user-declared variadic operator delete or the enable_if attribute. We |
3573 | // should probably not consider those cases to be usual deallocation |
3574 | // functions. But for now we just make an arbitrary choice in that case. |
3575 | auto Result = resolveDeallocationOverload(S&: *this, R&: FoundDelete, IDP, Loc: StartLoc); |
3576 | if (!Result) |
3577 | return nullptr; |
3578 | |
3579 | if (CheckDeleteOperator(S&: *this, StartLoc, Range: StartLoc, /*Diagnose=*/true, |
3580 | NamingClass: FoundDelete.getNamingClass(), Decl: Result.Found, |
3581 | Operator: Result.FD)) |
3582 | return nullptr; |
3583 | |
3584 | assert(Result.FD && "operator delete missing from global scope?"); |
3585 | return Result.FD; |
3586 | } |
3587 | |
3588 | FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc, |
3589 | CXXRecordDecl *RD, |
3590 | bool Diagnose) { |
3591 | DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op: OO_Delete); |
3592 | |
3593 | FunctionDecl *OperatorDelete = nullptr; |
3594 | QualType DeallocType = Context.getRecordType(RD); |
3595 | ImplicitDeallocationParameters IDP = { |
3596 | DeallocType, ShouldUseTypeAwareOperatorNewOrDelete(), |
3597 | AlignedAllocationMode::No, SizedDeallocationMode::No}; |
3598 | |
3599 | if (FindDeallocationFunction(StartLoc: Loc, RD, Name, Operator&: OperatorDelete, IDP, Diagnose)) |
3600 | return nullptr; |
3601 | |
3602 | if (OperatorDelete) |
3603 | return OperatorDelete; |
3604 | |
3605 | // If there's no class-specific operator delete, look up the global |
3606 | // non-array delete. |
3607 | IDP.PassAlignment = alignedAllocationModeFromBool( |
3608 | IsAligned: hasNewExtendedAlignment(S&: *this, AllocType: DeallocType)); |
3609 | IDP.PassSize = SizedDeallocationMode::Yes; |
3610 | return FindUsualDeallocationFunction(StartLoc: Loc, IDP, Name); |
3611 | } |
3612 | |
3613 | bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, |
3614 | DeclarationName Name, |
3615 | FunctionDecl *&Operator, |
3616 | ImplicitDeallocationParameters IDP, |
3617 | bool Diagnose) { |
3618 | LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName); |
3619 | // Try to find operator delete/operator delete[] in class scope. |
3620 | LookupQualifiedName(Found, RD); |
3621 | |
3622 | if (Found.isAmbiguous()) |
3623 | return true; |
3624 | |
3625 | Found.suppressDiagnostics(); |
3626 | |
3627 | if (!isAlignedAllocation(Mode: IDP.PassAlignment) && |
3628 | hasNewExtendedAlignment(S&: *this, AllocType: Context.getRecordType(RD))) |
3629 | IDP.PassAlignment = AlignedAllocationMode::Yes; |
3630 | |
3631 | // C++17 [expr.delete]p10: |
3632 | // If the deallocation functions have class scope, the one without a |
3633 | // parameter of type std::size_t is selected. |
3634 | llvm::SmallVector<UsualDeallocFnInfo, 4> Matches; |
3635 | resolveDeallocationOverload(S&: *this, R&: Found, IDP, Loc: StartLoc, BestFns: &Matches); |
3636 | |
3637 | // If we could find an overload, use it. |
3638 | if (Matches.size() == 1) { |
3639 | Operator = cast<CXXMethodDecl>(Val: Matches[0].FD); |
3640 | return CheckDeleteOperator(S&: *this, StartLoc, Range: StartLoc, Diagnose, |
3641 | NamingClass: Found.getNamingClass(), Decl: Matches[0].Found, |
3642 | Operator); |
3643 | } |
3644 | |
3645 | // We found multiple suitable operators; complain about the ambiguity. |
3646 | // FIXME: The standard doesn't say to do this; it appears that the intent |
3647 | // is that this should never happen. |
3648 | if (!Matches.empty()) { |
3649 | if (Diagnose) { |
3650 | Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found) |
3651 | << Name << RD; |
3652 | for (auto &Match : Matches) |
3653 | Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name; |
3654 | } |
3655 | return true; |
3656 | } |
3657 | |
3658 | // We did find operator delete/operator delete[] declarations, but |
3659 | // none of them were suitable. |
3660 | if (!Found.empty()) { |
3661 | if (Diagnose) { |
3662 | Diag(StartLoc, diag::err_no_suitable_delete_member_function_found) |
3663 | << Name << RD; |
3664 | |
3665 | for (NamedDecl *D : Found) |
3666 | Diag(D->getUnderlyingDecl()->getLocation(), |
3667 | diag::note_member_declared_here) << Name; |
3668 | } |
3669 | return true; |
3670 | } |
3671 | |
3672 | Operator = nullptr; |
3673 | return false; |
3674 | } |
3675 | |
3676 | namespace { |
3677 | /// Checks whether delete-expression, and new-expression used for |
3678 | /// initializing deletee have the same array form. |
3679 | class MismatchingNewDeleteDetector { |
3680 | public: |
3681 | enum MismatchResult { |
3682 | /// Indicates that there is no mismatch or a mismatch cannot be proven. |
3683 | NoMismatch, |
3684 | /// Indicates that variable is initialized with mismatching form of \a new. |
3685 | VarInitMismatches, |
3686 | /// Indicates that member is initialized with mismatching form of \a new. |
3687 | MemberInitMismatches, |
3688 | /// Indicates that 1 or more constructors' definitions could not been |
3689 | /// analyzed, and they will be checked again at the end of translation unit. |
3690 | AnalyzeLater |
3691 | }; |
3692 | |
3693 | /// \param EndOfTU True, if this is the final analysis at the end of |
3694 | /// translation unit. False, if this is the initial analysis at the point |
3695 | /// delete-expression was encountered. |
3696 | explicit MismatchingNewDeleteDetector(bool EndOfTU) |
3697 | : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU), |
3698 | HasUndefinedConstructors(false) {} |
3699 | |
3700 | /// Checks whether pointee of a delete-expression is initialized with |
3701 | /// matching form of new-expression. |
3702 | /// |
3703 | /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the |
3704 | /// point where delete-expression is encountered, then a warning will be |
3705 | /// issued immediately. If return value is \c AnalyzeLater at the point where |
3706 | /// delete-expression is seen, then member will be analyzed at the end of |
3707 | /// translation unit. \c AnalyzeLater is returned iff at least one constructor |
3708 | /// couldn't be analyzed. If at least one constructor initializes the member |
3709 | /// with matching type of new, the return value is \c NoMismatch. |
3710 | MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE); |
3711 | /// Analyzes a class member. |
3712 | /// \param Field Class member to analyze. |
3713 | /// \param DeleteWasArrayForm Array form-ness of the delete-expression used |
3714 | /// for deleting the \p Field. |
3715 | MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm); |
3716 | FieldDecl *Field; |
3717 | /// List of mismatching new-expressions used for initialization of the pointee |
3718 | llvm::SmallVector<const CXXNewExpr *, 4> NewExprs; |
3719 | /// Indicates whether delete-expression was in array form. |
3720 | bool IsArrayForm; |
3721 | |
3722 | private: |
3723 | const bool EndOfTU; |
3724 | /// Indicates that there is at least one constructor without body. |
3725 | bool HasUndefinedConstructors; |
3726 | /// Returns \c CXXNewExpr from given initialization expression. |
3727 | /// \param E Expression used for initializing pointee in delete-expression. |
3728 | /// E can be a single-element \c InitListExpr consisting of new-expression. |
3729 | const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E); |
3730 | /// Returns whether member is initialized with mismatching form of |
3731 | /// \c new either by the member initializer or in-class initialization. |
3732 | /// |
3733 | /// If bodies of all constructors are not visible at the end of translation |
3734 | /// unit or at least one constructor initializes member with the matching |
3735 | /// form of \c new, mismatch cannot be proven, and this function will return |
3736 | /// \c NoMismatch. |
3737 | MismatchResult analyzeMemberExpr(const MemberExpr *ME); |
3738 | /// Returns whether variable is initialized with mismatching form of |
3739 | /// \c new. |
3740 | /// |
3741 | /// If variable is initialized with matching form of \c new or variable is not |
3742 | /// initialized with a \c new expression, this function will return true. |
3743 | /// If variable is initialized with mismatching form of \c new, returns false. |
3744 | /// \param D Variable to analyze. |
3745 | bool hasMatchingVarInit(const DeclRefExpr *D); |
3746 | /// Checks whether the constructor initializes pointee with mismatching |
3747 | /// form of \c new. |
3748 | /// |
3749 | /// Returns true, if member is initialized with matching form of \c new in |
3750 | /// member initializer list. Returns false, if member is initialized with the |
3751 | /// matching form of \c new in this constructor's initializer or given |
3752 | /// constructor isn't defined at the point where delete-expression is seen, or |
3753 | /// member isn't initialized by the constructor. |
3754 | bool hasMatchingNewInCtor(const CXXConstructorDecl *CD); |
3755 | /// Checks whether member is initialized with matching form of |
3756 | /// \c new in member initializer list. |
3757 | bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI); |
3758 | /// Checks whether member is initialized with mismatching form of \c new by |
3759 | /// in-class initializer. |
3760 | MismatchResult analyzeInClassInitializer(); |
3761 | }; |
3762 | } |
3763 | |
3764 | MismatchingNewDeleteDetector::MismatchResult |
3765 | MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) { |
3766 | NewExprs.clear(); |
3767 | assert(DE && "Expected delete-expression"); |
3768 | IsArrayForm = DE->isArrayForm(); |
3769 | const Expr *E = DE->getArgument()->IgnoreParenImpCasts(); |
3770 | if (const MemberExpr *ME = dyn_cast<const MemberExpr>(Val: E)) { |
3771 | return analyzeMemberExpr(ME); |
3772 | } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(Val: E)) { |
3773 | if (!hasMatchingVarInit(D)) |
3774 | return VarInitMismatches; |
3775 | } |
3776 | return NoMismatch; |
3777 | } |
3778 | |
3779 | const CXXNewExpr * |
3780 | MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) { |
3781 | assert(E != nullptr && "Expected a valid initializer expression"); |
3782 | E = E->IgnoreParenImpCasts(); |
3783 | if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(Val: E)) { |
3784 | if (ILE->getNumInits() == 1) |
3785 | E = dyn_cast<const CXXNewExpr>(Val: ILE->getInit(Init: 0)->IgnoreParenImpCasts()); |
3786 | } |
3787 | |
3788 | return dyn_cast_or_null<const CXXNewExpr>(Val: E); |
3789 | } |
3790 | |
3791 | bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit( |
3792 | const CXXCtorInitializer *CI) { |
3793 | const CXXNewExpr *NE = nullptr; |
3794 | if (Field == CI->getMember() && |
3795 | (NE = getNewExprFromInitListOrExpr(E: CI->getInit()))) { |
3796 | if (NE->isArray() == IsArrayForm) |
3797 | return true; |
3798 | else |
3799 | NewExprs.push_back(Elt: NE); |
3800 | } |
3801 | return false; |
3802 | } |
3803 | |
3804 | bool MismatchingNewDeleteDetector::hasMatchingNewInCtor( |
3805 | const CXXConstructorDecl *CD) { |
3806 | if (CD->isImplicit()) |
3807 | return false; |
3808 | const FunctionDecl *Definition = CD; |
3809 | if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) { |
3810 | HasUndefinedConstructors = true; |
3811 | return EndOfTU; |
3812 | } |
3813 | for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) { |
3814 | if (hasMatchingNewInCtorInit(CI)) |
3815 | return true; |
3816 | } |
3817 | return false; |
3818 | } |
3819 | |
3820 | MismatchingNewDeleteDetector::MismatchResult |
3821 | MismatchingNewDeleteDetector::analyzeInClassInitializer() { |
3822 | assert(Field != nullptr && "This should be called only for members"); |
3823 | const Expr *InitExpr = Field->getInClassInitializer(); |
3824 | if (!InitExpr) |
3825 | return EndOfTU ? NoMismatch : AnalyzeLater; |
3826 | if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(E: InitExpr)) { |
3827 | if (NE->isArray() != IsArrayForm) { |
3828 | NewExprs.push_back(Elt: NE); |
3829 | return MemberInitMismatches; |
3830 | } |
3831 | } |
3832 | return NoMismatch; |
3833 | } |
3834 | |
3835 | MismatchingNewDeleteDetector::MismatchResult |
3836 | MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field, |
3837 | bool DeleteWasArrayForm) { |
3838 | assert(Field != nullptr && "Analysis requires a valid class member."); |
3839 | this->Field = Field; |
3840 | IsArrayForm = DeleteWasArrayForm; |
3841 | const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Val: Field->getParent()); |
3842 | for (const auto *CD : RD->ctors()) { |
3843 | if (hasMatchingNewInCtor(CD)) |
3844 | return NoMismatch; |
3845 | } |
3846 | if (HasUndefinedConstructors) |
3847 | return EndOfTU ? NoMismatch : AnalyzeLater; |
3848 | if (!NewExprs.empty()) |
3849 | return MemberInitMismatches; |
3850 | return Field->hasInClassInitializer() ? analyzeInClassInitializer() |
3851 | : NoMismatch; |
3852 | } |
3853 | |
3854 | MismatchingNewDeleteDetector::MismatchResult |
3855 | MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) { |
3856 | assert(ME != nullptr && "Expected a member expression"); |
3857 | if (FieldDecl *F = dyn_cast<FieldDecl>(Val: ME->getMemberDecl())) |
3858 | return analyzeField(Field: F, DeleteWasArrayForm: IsArrayForm); |
3859 | return NoMismatch; |
3860 | } |
3861 | |
3862 | bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) { |
3863 | const CXXNewExpr *NE = nullptr; |
3864 | if (const VarDecl *VD = dyn_cast<const VarDecl>(Val: D->getDecl())) { |
3865 | if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(E: VD->getInit())) && |
3866 | NE->isArray() != IsArrayForm) { |
3867 | NewExprs.push_back(Elt: NE); |
3868 | } |
3869 | } |
3870 | return NewExprs.empty(); |
3871 | } |
3872 | |
3873 | static void |
3874 | DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc, |
3875 | const MismatchingNewDeleteDetector &Detector) { |
3876 | SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(Loc: DeleteLoc); |
3877 | FixItHint H; |
3878 | if (!Detector.IsArrayForm) |
3879 | H = FixItHint::CreateInsertion(InsertionLoc: EndOfDelete, Code: "[]"); |
3880 | else { |
3881 | SourceLocation RSquare = Lexer::findLocationAfterToken( |
3882 | loc: DeleteLoc, TKind: tok::l_square, SM: SemaRef.getSourceManager(), |
3883 | LangOpts: SemaRef.getLangOpts(), SkipTrailingWhitespaceAndNewLine: true); |
3884 | if (RSquare.isValid()) |
3885 | H = FixItHint::CreateRemoval(RemoveRange: SourceRange(EndOfDelete, RSquare)); |
3886 | } |
3887 | SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new) |
3888 | << Detector.IsArrayForm << H; |
3889 | |
3890 | for (const auto *NE : Detector.NewExprs) |
3891 | SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here) |
3892 | << Detector.IsArrayForm; |
3893 | } |
3894 | |
3895 | void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) { |
3896 | if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) |
3897 | return; |
3898 | MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false); |
3899 | switch (Detector.analyzeDeleteExpr(DE)) { |
3900 | case MismatchingNewDeleteDetector::VarInitMismatches: |
3901 | case MismatchingNewDeleteDetector::MemberInitMismatches: { |
3902 | DiagnoseMismatchedNewDelete(SemaRef&: *this, DeleteLoc: DE->getBeginLoc(), Detector); |
3903 | break; |
3904 | } |
3905 | case MismatchingNewDeleteDetector::AnalyzeLater: { |
3906 | DeleteExprs[Detector.Field].push_back( |
3907 | Elt: std::make_pair(x: DE->getBeginLoc(), y: DE->isArrayForm())); |
3908 | break; |
3909 | } |
3910 | case MismatchingNewDeleteDetector::NoMismatch: |
3911 | break; |
3912 | } |
3913 | } |
3914 | |
3915 | void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, |
3916 | bool DeleteWasArrayForm) { |
3917 | MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true); |
3918 | switch (Detector.analyzeField(Field, DeleteWasArrayForm)) { |
3919 | case MismatchingNewDeleteDetector::VarInitMismatches: |
3920 | llvm_unreachable("This analysis should have been done for class members."); |
3921 | case MismatchingNewDeleteDetector::AnalyzeLater: |
3922 | llvm_unreachable("Analysis cannot be postponed any point beyond end of " |
3923 | "translation unit."); |
3924 | case MismatchingNewDeleteDetector::MemberInitMismatches: |
3925 | DiagnoseMismatchedNewDelete(SemaRef&: *this, DeleteLoc, Detector); |
3926 | break; |
3927 | case MismatchingNewDeleteDetector::NoMismatch: |
3928 | break; |
3929 | } |
3930 | } |
3931 | |
3932 | ExprResult |
3933 | Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, |
3934 | bool ArrayForm, Expr *ExE) { |
3935 | // C++ [expr.delete]p1: |
3936 | // The operand shall have a pointer type, or a class type having a single |
3937 | // non-explicit conversion function to a pointer type. The result has type |
3938 | // void. |
3939 | // |
3940 | // DR599 amends "pointer type" to "pointer to object type" in both cases. |
3941 | |
3942 | ExprResult Ex = ExE; |
3943 | FunctionDecl *OperatorDelete = nullptr; |
3944 | bool ArrayFormAsWritten = ArrayForm; |
3945 | bool UsualArrayDeleteWantsSize = false; |
3946 | |
3947 | if (!Ex.get()->isTypeDependent()) { |
3948 | // Perform lvalue-to-rvalue cast, if needed. |
3949 | Ex = DefaultLvalueConversion(E: Ex.get()); |
3950 | if (Ex.isInvalid()) |
3951 | return ExprError(); |
3952 | |
3953 | QualType Type = Ex.get()->getType(); |
3954 | |
3955 | class DeleteConverter : public ContextualImplicitConverter { |
3956 | public: |
3957 | DeleteConverter() : ContextualImplicitConverter(false, true) {} |
3958 | |
3959 | bool match(QualType ConvType) override { |
3960 | // FIXME: If we have an operator T* and an operator void*, we must pick |
3961 | // the operator T*. |
3962 | if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) |
3963 | if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType()) |
3964 | return true; |
3965 | return false; |
3966 | } |
3967 | |
3968 | SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, |
3969 | QualType T) override { |
3970 | return S.Diag(Loc, diag::err_delete_operand) << T; |
3971 | } |
3972 | |
3973 | SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, |
3974 | QualType T) override { |
3975 | return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T; |
3976 | } |
3977 | |
3978 | SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, |
3979 | QualType T, |
3980 | QualType ConvTy) override { |
3981 | return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy; |
3982 | } |
3983 | |
3984 | SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, |
3985 | QualType ConvTy) override { |
3986 | return S.Diag(Conv->getLocation(), diag::note_delete_conversion) |
3987 | << ConvTy; |
3988 | } |
3989 | |
3990 | SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, |
3991 | QualType T) override { |
3992 | return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T; |
3993 | } |
3994 | |
3995 | SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, |
3996 | QualType ConvTy) override { |
3997 | return S.Diag(Conv->getLocation(), diag::note_delete_conversion) |
3998 | << ConvTy; |
3999 | } |
4000 | |
4001 | SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, |
4002 | QualType T, |
4003 | QualType ConvTy) override { |
4004 | llvm_unreachable("conversion functions are permitted"); |
4005 | } |
4006 | } Converter; |
4007 | |
4008 | Ex = PerformContextualImplicitConversion(Loc: StartLoc, FromE: Ex.get(), Converter); |
4009 | if (Ex.isInvalid()) |
4010 | return ExprError(); |
4011 | Type = Ex.get()->getType(); |
4012 | if (!Converter.match(ConvType: Type)) |
4013 | // FIXME: PerformContextualImplicitConversion should return ExprError |
4014 | // itself in this case. |
4015 | return ExprError(); |
4016 | |
4017 | QualType Pointee = Type->castAs<PointerType>()->getPointeeType(); |
4018 | QualType PointeeElem = Context.getBaseElementType(QT: Pointee); |
4019 | |
4020 | if (Pointee.getAddressSpace() != LangAS::Default && |
4021 | !getLangOpts().OpenCLCPlusPlus) |
4022 | return Diag(Ex.get()->getBeginLoc(), |
4023 | diag::err_address_space_qualified_delete) |
4024 | << Pointee.getUnqualifiedType() |
4025 | << Pointee.getQualifiers().getAddressSpaceAttributePrintValue(); |
4026 | |
4027 | CXXRecordDecl *PointeeRD = nullptr; |
4028 | if (Pointee->isVoidType() && !isSFINAEContext()) { |
4029 | // The C++ standard bans deleting a pointer to a non-object type, which |
4030 | // effectively bans deletion of "void*". However, most compilers support |
4031 | // this, so we treat it as a warning unless we're in a SFINAE context. |
4032 | // But we still prohibit this since C++26. |
4033 | Diag(StartLoc, LangOpts.CPlusPlus26 ? diag::err_delete_incomplete |
4034 | : diag::ext_delete_void_ptr_operand) |
4035 | << (LangOpts.CPlusPlus26 ? Pointee : Type) |
4036 | << Ex.get()->getSourceRange(); |
4037 | } else if (Pointee->isFunctionType() || Pointee->isVoidType() || |
4038 | Pointee->isSizelessType()) { |
4039 | return ExprError(Diag(StartLoc, diag::err_delete_operand) |
4040 | << Type << Ex.get()->getSourceRange()); |
4041 | } else if (!Pointee->isDependentType()) { |
4042 | // FIXME: This can result in errors if the definition was imported from a |
4043 | // module but is hidden. |
4044 | if (Pointee->isEnumeralType() || |
4045 | !RequireCompleteType(StartLoc, Pointee, |
4046 | LangOpts.CPlusPlus26 |
4047 | ? diag::err_delete_incomplete |
4048 | : diag::warn_delete_incomplete, |
4049 | Ex.get())) { |
4050 | if (const RecordType *RT = PointeeElem->getAs<RecordType>()) |
4051 | PointeeRD = cast<CXXRecordDecl>(Val: RT->getDecl()); |
4052 | } |
4053 | } |
4054 | |
4055 | if (Pointee->isArrayType() && !ArrayForm) { |
4056 | Diag(StartLoc, diag::warn_delete_array_type) |
4057 | << Type << Ex.get()->getSourceRange() |
4058 | << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]"); |
4059 | ArrayForm = true; |
4060 | } |
4061 | |
4062 | DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( |
4063 | Op: ArrayForm ? OO_Array_Delete : OO_Delete); |
4064 | |
4065 | if (PointeeRD) { |
4066 | ImplicitDeallocationParameters IDP = { |
4067 | Pointee, ShouldUseTypeAwareOperatorNewOrDelete(), |
4068 | AlignedAllocationMode::No, SizedDeallocationMode::No}; |
4069 | if (!UseGlobal && |
4070 | FindDeallocationFunction(StartLoc, RD: PointeeRD, Name: DeleteName, |
4071 | Operator&: OperatorDelete, IDP)) |
4072 | return ExprError(); |
4073 | |
4074 | // If we're allocating an array of records, check whether the |
4075 | // usual operator delete[] has a size_t parameter. |
4076 | if (ArrayForm) { |
4077 | // If the user specifically asked to use the global allocator, |
4078 | // we'll need to do the lookup into the class. |
4079 | if (UseGlobal) |
4080 | UsualArrayDeleteWantsSize = doesUsualArrayDeleteWantSize( |
4081 | S&: *this, loc: StartLoc, PassType: IDP.PassTypeIdentity, allocType: PointeeElem); |
4082 | |
4083 | // Otherwise, the usual operator delete[] should be the |
4084 | // function we just found. |
4085 | else if (isa_and_nonnull<CXXMethodDecl>(Val: OperatorDelete)) { |
4086 | UsualDeallocFnInfo UDFI( |
4087 | *this, DeclAccessPair::make(OperatorDelete, AS_public), Pointee, |
4088 | StartLoc); |
4089 | UsualArrayDeleteWantsSize = isSizedDeallocation(UDFI.IDP.PassSize); |
4090 | } |
4091 | } |
4092 | |
4093 | if (!PointeeRD->hasIrrelevantDestructor()) { |
4094 | if (CXXDestructorDecl *Dtor = LookupDestructor(Class: PointeeRD)) { |
4095 | if (Dtor->isCalledByDelete(OpDel: OperatorDelete)) { |
4096 | MarkFunctionReferenced(StartLoc, |
4097 | const_cast<CXXDestructorDecl *>(Dtor)); |
4098 | if (DiagnoseUseOfDecl(Dtor, StartLoc)) |
4099 | return ExprError(); |
4100 | } |
4101 | } |
4102 | } |
4103 | |
4104 | CheckVirtualDtorCall(dtor: PointeeRD->getDestructor(), Loc: StartLoc, |
4105 | /*IsDelete=*/true, /*CallCanBeVirtual=*/true, |
4106 | /*WarnOnNonAbstractTypes=*/!ArrayForm, |
4107 | DtorLoc: SourceLocation()); |
4108 | } |
4109 | |
4110 | if (!OperatorDelete) { |
4111 | if (getLangOpts().OpenCLCPlusPlus) { |
4112 | Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete"; |
4113 | return ExprError(); |
4114 | } |
4115 | |
4116 | bool IsComplete = isCompleteType(Loc: StartLoc, T: Pointee); |
4117 | bool CanProvideSize = |
4118 | IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize || |
4119 | Pointee.isDestructedType()); |
4120 | bool Overaligned = hasNewExtendedAlignment(S&: *this, AllocType: Pointee); |
4121 | |
4122 | // Look for a global declaration. |
4123 | ImplicitDeallocationParameters IDP = { |
4124 | Pointee, ShouldUseTypeAwareOperatorNewOrDelete(), |
4125 | alignedAllocationModeFromBool(IsAligned: Overaligned), |
4126 | sizedDeallocationModeFromBool(IsSized: CanProvideSize)}; |
4127 | OperatorDelete = FindUsualDeallocationFunction(StartLoc, IDP, Name: DeleteName); |
4128 | if (!OperatorDelete) |
4129 | return ExprError(); |
4130 | } |
4131 | |
4132 | if (OperatorDelete->isInvalidDecl()) |
4133 | return ExprError(); |
4134 | |
4135 | MarkFunctionReferenced(Loc: StartLoc, Func: OperatorDelete); |
4136 | |
4137 | // Check access and ambiguity of destructor if we're going to call it. |
4138 | // Note that this is required even for a virtual delete. |
4139 | bool IsVirtualDelete = false; |
4140 | if (PointeeRD) { |
4141 | if (CXXDestructorDecl *Dtor = LookupDestructor(Class: PointeeRD)) { |
4142 | if (Dtor->isCalledByDelete(OperatorDelete)) |
4143 | CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor, |
4144 | PDiag(diag::err_access_dtor) << PointeeElem); |
4145 | IsVirtualDelete = Dtor->isVirtual(); |
4146 | } |
4147 | } |
4148 | |
4149 | DiagnoseUseOfDecl(OperatorDelete, StartLoc); |
4150 | |
4151 | unsigned AddressParamIdx = 0; |
4152 | if (OperatorDelete->isTypeAwareOperatorNewOrDelete()) { |
4153 | QualType TypeIdentity = OperatorDelete->getParamDecl(i: 0)->getType(); |
4154 | if (RequireCompleteType(StartLoc, TypeIdentity, |
4155 | diag::err_incomplete_type)) |
4156 | return ExprError(); |
4157 | AddressParamIdx = 1; |
4158 | } |
4159 | |
4160 | // Convert the operand to the type of the first parameter of operator |
4161 | // delete. This is only necessary if we selected a destroying operator |
4162 | // delete that we are going to call (non-virtually); converting to void* |
4163 | // is trivial and left to AST consumers to handle. |
4164 | QualType ParamType = |
4165 | OperatorDelete->getParamDecl(i: AddressParamIdx)->getType(); |
4166 | if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) { |
4167 | Qualifiers Qs = Pointee.getQualifiers(); |
4168 | if (Qs.hasCVRQualifiers()) { |
4169 | // Qualifiers are irrelevant to this conversion; we're only looking |
4170 | // for access and ambiguity. |
4171 | Qs.removeCVRQualifiers(); |
4172 | QualType Unqual = Context.getPointerType( |
4173 | T: Context.getQualifiedType(T: Pointee.getUnqualifiedType(), Qs)); |
4174 | Ex = ImpCastExprToType(E: Ex.get(), Type: Unqual, CK: CK_NoOp); |
4175 | } |
4176 | Ex = PerformImplicitConversion(From: Ex.get(), ToType: ParamType, |
4177 | Action: AssignmentAction::Passing); |
4178 | if (Ex.isInvalid()) |
4179 | return ExprError(); |
4180 | } |
4181 | } |
4182 | |
4183 | CXXDeleteExpr *Result = new (Context) CXXDeleteExpr( |
4184 | Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten, |
4185 | UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc); |
4186 | AnalyzeDeleteExprMismatch(DE: Result); |
4187 | return Result; |
4188 | } |
4189 | |
4190 | static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall, |
4191 | bool IsDelete, |
4192 | FunctionDecl *&Operator) { |
4193 | |
4194 | DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName( |
4195 | Op: IsDelete ? OO_Delete : OO_New); |
4196 | |
4197 | LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName); |
4198 | S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl()); |
4199 | assert(!R.empty() && "implicitly declared allocation functions not found"); |
4200 | assert(!R.isAmbiguous() && "global allocation functions are ambiguous"); |
4201 | |
4202 | // We do our own custom access checks below. |
4203 | R.suppressDiagnostics(); |
4204 | |
4205 | SmallVector<Expr *, 8> Args(TheCall->arguments()); |
4206 | OverloadCandidateSet Candidates(R.getNameLoc(), |
4207 | OverloadCandidateSet::CSK_Normal); |
4208 | for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end(); |
4209 | FnOvl != FnOvlEnd; ++FnOvl) { |
4210 | // Even member operator new/delete are implicitly treated as |
4211 | // static, so don't use AddMemberCandidate. |
4212 | NamedDecl *D = (*FnOvl)->getUnderlyingDecl(); |
4213 | |
4214 | if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(Val: D)) { |
4215 | S.AddTemplateOverloadCandidate(FunctionTemplate: FnTemplate, FoundDecl: FnOvl.getPair(), |
4216 | /*ExplicitTemplateArgs=*/nullptr, Args, |
4217 | CandidateSet&: Candidates, |
4218 | /*SuppressUserConversions=*/false); |
4219 | continue; |
4220 | } |
4221 | |
4222 | FunctionDecl *Fn = cast<FunctionDecl>(Val: D); |
4223 | S.AddOverloadCandidate(Function: Fn, FoundDecl: FnOvl.getPair(), Args, CandidateSet&: Candidates, |
4224 | /*SuppressUserConversions=*/false); |
4225 | } |
4226 | |
4227 | SourceRange Range = TheCall->getSourceRange(); |
4228 | |
4229 | // Do the resolution. |
4230 | OverloadCandidateSet::iterator Best; |
4231 | switch (Candidates.BestViableFunction(S, Loc: R.getNameLoc(), Best)) { |
4232 | case OR_Success: { |
4233 | // Got one! |
4234 | FunctionDecl *FnDecl = Best->Function; |
4235 | assert(R.getNamingClass() == nullptr && |
4236 | "class members should not be considered"); |
4237 | |
4238 | if (!FnDecl->isReplaceableGlobalAllocationFunction()) { |
4239 | S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual) |
4240 | << (IsDelete ? 1 : 0) << Range; |
4241 | S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here) |
4242 | << R.getLookupName() << FnDecl->getSourceRange(); |
4243 | return true; |
4244 | } |
4245 | |
4246 | Operator = FnDecl; |
4247 | return false; |
4248 | } |
4249 | |
4250 | case OR_No_Viable_Function: |
4251 | Candidates.NoteCandidates( |
4252 | PartialDiagnosticAt(R.getNameLoc(), |
4253 | S.PDiag(diag::err_ovl_no_viable_function_in_call) |
4254 | << R.getLookupName() << Range), |
4255 | S, OCD_AllCandidates, Args); |
4256 | return true; |
4257 | |
4258 | case OR_Ambiguous: |
4259 | Candidates.NoteCandidates( |
4260 | PartialDiagnosticAt(R.getNameLoc(), |
4261 | S.PDiag(diag::err_ovl_ambiguous_call) |
4262 | << R.getLookupName() << Range), |
4263 | S, OCD_AmbiguousCandidates, Args); |
4264 | return true; |
4265 | |
4266 | case OR_Deleted: |
4267 | S.DiagnoseUseOfDeletedFunction(Loc: R.getNameLoc(), Range, Name: R.getLookupName(), |
4268 | CandidateSet&: Candidates, Fn: Best->Function, Args); |
4269 | return true; |
4270 | } |
4271 | llvm_unreachable("Unreachable, bad result from BestViableFunction"); |
4272 | } |
4273 | |
4274 | ExprResult Sema::BuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, |
4275 | bool IsDelete) { |
4276 | CallExpr *TheCall = cast<CallExpr>(Val: TheCallResult.get()); |
4277 | if (!getLangOpts().CPlusPlus) { |
4278 | Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language) |
4279 | << (IsDelete ? "__builtin_operator_delete": "__builtin_operator_new") |
4280 | << "C++"; |
4281 | return ExprError(); |
4282 | } |
4283 | // CodeGen assumes it can find the global new and delete to call, |
4284 | // so ensure that they are declared. |
4285 | DeclareGlobalNewDelete(); |
4286 | |
4287 | FunctionDecl *OperatorNewOrDelete = nullptr; |
4288 | if (resolveBuiltinNewDeleteOverload(S&: *this, TheCall, IsDelete, |
4289 | Operator&: OperatorNewOrDelete)) |
4290 | return ExprError(); |
4291 | assert(OperatorNewOrDelete && "should be found"); |
4292 | |
4293 | DiagnoseUseOfDecl(D: OperatorNewOrDelete, Locs: TheCall->getExprLoc()); |
4294 | MarkFunctionReferenced(Loc: TheCall->getExprLoc(), Func: OperatorNewOrDelete); |
4295 | |
4296 | TheCall->setType(OperatorNewOrDelete->getReturnType()); |
4297 | for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) { |
4298 | QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType(); |
4299 | InitializedEntity Entity = |
4300 | InitializedEntity::InitializeParameter(Context, Type: ParamTy, Consumed: false); |
4301 | ExprResult Arg = PerformCopyInitialization( |
4302 | Entity, EqualLoc: TheCall->getArg(Arg: i)->getBeginLoc(), Init: TheCall->getArg(Arg: i)); |
4303 | if (Arg.isInvalid()) |
4304 | return ExprError(); |
4305 | TheCall->setArg(Arg: i, ArgExpr: Arg.get()); |
4306 | } |
4307 | auto Callee = dyn_cast<ImplicitCastExpr>(Val: TheCall->getCallee()); |
4308 | assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr && |
4309 | "Callee expected to be implicit cast to a builtin function pointer"); |
4310 | Callee->setType(OperatorNewOrDelete->getType()); |
4311 | |
4312 | return TheCallResult; |
4313 | } |
4314 | |
4315 | void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, |
4316 | bool IsDelete, bool CallCanBeVirtual, |
4317 | bool WarnOnNonAbstractTypes, |
4318 | SourceLocation DtorLoc) { |
4319 | if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext()) |
4320 | return; |
4321 | |
4322 | // C++ [expr.delete]p3: |
4323 | // In the first alternative (delete object), if the static type of the |
4324 | // object to be deleted is different from its dynamic type, the static |
4325 | // type shall be a base class of the dynamic type of the object to be |
4326 | // deleted and the static type shall have a virtual destructor or the |
4327 | // behavior is undefined. |
4328 | // |
4329 | const CXXRecordDecl *PointeeRD = dtor->getParent(); |
4330 | // Note: a final class cannot be derived from, no issue there |
4331 | if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>()) |
4332 | return; |
4333 | |
4334 | // If the superclass is in a system header, there's nothing that can be done. |
4335 | // The `delete` (where we emit the warning) can be in a system header, |
4336 | // what matters for this warning is where the deleted type is defined. |
4337 | if (getSourceManager().isInSystemHeader(Loc: PointeeRD->getLocation())) |
4338 | return; |
4339 | |
4340 | QualType ClassType = dtor->getFunctionObjectParameterType(); |
4341 | if (PointeeRD->isAbstract()) { |
4342 | // If the class is abstract, we warn by default, because we're |
4343 | // sure the code has undefined behavior. |
4344 | Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1) |
4345 | << ClassType; |
4346 | } else if (WarnOnNonAbstractTypes) { |
4347 | // Otherwise, if this is not an array delete, it's a bit suspect, |
4348 | // but not necessarily wrong. |
4349 | Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1) |
4350 | << ClassType; |
4351 | } |
4352 | if (!IsDelete) { |
4353 | std::string TypeStr; |
4354 | ClassType.getAsStringInternal(Str&: TypeStr, Policy: getPrintingPolicy()); |
4355 | Diag(DtorLoc, diag::note_delete_non_virtual) |
4356 | << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::"); |
4357 | } |
4358 | } |
4359 | |
4360 | Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar, |
4361 | SourceLocation StmtLoc, |
4362 | ConditionKind CK) { |
4363 | ExprResult E = |
4364 | CheckConditionVariable(ConditionVar: cast<VarDecl>(Val: ConditionVar), StmtLoc, CK); |
4365 | if (E.isInvalid()) |
4366 | return ConditionError(); |
4367 | return ConditionResult(*this, ConditionVar, MakeFullExpr(Arg: E.get(), CC: StmtLoc), |
4368 | CK == ConditionKind::ConstexprIf); |
4369 | } |
4370 | |
4371 | ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar, |
4372 | SourceLocation StmtLoc, |
4373 | ConditionKind CK) { |
4374 | if (ConditionVar->isInvalidDecl()) |
4375 | return ExprError(); |
4376 | |
4377 | QualType T = ConditionVar->getType(); |
4378 | |
4379 | // C++ [stmt.select]p2: |
4380 | // The declarator shall not specify a function or an array. |
4381 | if (T->isFunctionType()) |
4382 | return ExprError(Diag(ConditionVar->getLocation(), |
4383 | diag::err_invalid_use_of_function_type) |
4384 | << ConditionVar->getSourceRange()); |
4385 | else if (T->isArrayType()) |
4386 | return ExprError(Diag(ConditionVar->getLocation(), |
4387 | diag::err_invalid_use_of_array_type) |
4388 | << ConditionVar->getSourceRange()); |
4389 | |
4390 | ExprResult Condition = BuildDeclRefExpr( |
4391 | ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue, |
4392 | ConditionVar->getLocation()); |
4393 | |
4394 | switch (CK) { |
4395 | case ConditionKind::Boolean: |
4396 | return CheckBooleanCondition(Loc: StmtLoc, E: Condition.get()); |
4397 | |
4398 | case ConditionKind::ConstexprIf: |
4399 | return CheckBooleanCondition(Loc: StmtLoc, E: Condition.get(), IsConstexpr: true); |
4400 | |
4401 | case ConditionKind::Switch: |
4402 | return CheckSwitchCondition(SwitchLoc: StmtLoc, Cond: Condition.get()); |
4403 | } |
4404 | |
4405 | llvm_unreachable("unexpected condition kind"); |
4406 | } |
4407 | |
4408 | ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) { |
4409 | // C++11 6.4p4: |
4410 | // The value of a condition that is an initialized declaration in a statement |
4411 | // other than a switch statement is the value of the declared variable |
4412 | // implicitly converted to type bool. If that conversion is ill-formed, the |
4413 | // program is ill-formed. |
4414 | // The value of a condition that is an expression is the value of the |
4415 | // expression, implicitly converted to bool. |
4416 | // |
4417 | // C++23 8.5.2p2 |
4418 | // If the if statement is of the form if constexpr, the value of the condition |
4419 | // is contextually converted to bool and the converted expression shall be |
4420 | // a constant expression. |
4421 | // |
4422 | |
4423 | ExprResult E = PerformContextuallyConvertToBool(From: CondExpr); |
4424 | if (!IsConstexpr || E.isInvalid() || E.get()->isValueDependent()) |
4425 | return E; |
4426 | |
4427 | // FIXME: Return this value to the caller so they don't need to recompute it. |
4428 | llvm::APSInt Cond; |
4429 | E = VerifyIntegerConstantExpression( |
4430 | E.get(), &Cond, |
4431 | diag::err_constexpr_if_condition_expression_is_not_constant); |
4432 | return E; |
4433 | } |
4434 | |
4435 | bool |
4436 | Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { |
4437 | // Look inside the implicit cast, if it exists. |
4438 | if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Val: From)) |
4439 | From = Cast->getSubExpr(); |
4440 | |
4441 | // A string literal (2.13.4) that is not a wide string literal can |
4442 | // be converted to an rvalue of type "pointer to char"; a wide |
4443 | // string literal can be converted to an rvalue of type "pointer |
4444 | // to wchar_t" (C++ 4.2p2). |
4445 | if (StringLiteral *StrLit = dyn_cast<StringLiteral>(Val: From->IgnoreParens())) |
4446 | if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) |
4447 | if (const BuiltinType *ToPointeeType |
4448 | = ToPtrType->getPointeeType()->getAs<BuiltinType>()) { |
4449 | // This conversion is considered only when there is an |
4450 | // explicit appropriate pointer target type (C++ 4.2p2). |
4451 | if (!ToPtrType->getPointeeType().hasQualifiers()) { |
4452 | switch (StrLit->getKind()) { |
4453 | case StringLiteralKind::UTF8: |
4454 | case StringLiteralKind::UTF16: |
4455 | case StringLiteralKind::UTF32: |
4456 | // We don't allow UTF literals to be implicitly converted |
4457 | break; |
4458 | case StringLiteralKind::Ordinary: |
4459 | case StringLiteralKind::Binary: |
4460 | return (ToPointeeType->getKind() == BuiltinType::Char_U || |
4461 | ToPointeeType->getKind() == BuiltinType::Char_S); |
4462 | case StringLiteralKind::Wide: |
4463 | return Context.typesAreCompatible(T1: Context.getWideCharType(), |
4464 | T2: QualType(ToPointeeType, 0)); |
4465 | case StringLiteralKind::Unevaluated: |
4466 | assert(false && "Unevaluated string literal in expression"); |
4467 | break; |
4468 | } |
4469 | } |
4470 | } |
4471 | |
4472 | return false; |
4473 | } |
4474 | |
4475 | static ExprResult BuildCXXCastArgument(Sema &S, |
4476 | SourceLocation CastLoc, |
4477 | QualType Ty, |
4478 | CastKind Kind, |
4479 | CXXMethodDecl *Method, |
4480 | DeclAccessPair FoundDecl, |
4481 | bool HadMultipleCandidates, |
4482 | Expr *From) { |
4483 | switch (Kind) { |
4484 | default: llvm_unreachable("Unhandled cast kind!"); |
4485 | case CK_ConstructorConversion: { |
4486 | CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Val: Method); |
4487 | SmallVector<Expr*, 8> ConstructorArgs; |
4488 | |
4489 | if (S.RequireNonAbstractType(CastLoc, Ty, |
4490 | diag::err_allocation_of_abstract_type)) |
4491 | return ExprError(); |
4492 | |
4493 | if (S.CompleteConstructorCall(Constructor, DeclInitType: Ty, ArgsPtr: From, Loc: CastLoc, |
4494 | ConvertedArgs&: ConstructorArgs)) |
4495 | return ExprError(); |
4496 | |
4497 | S.CheckConstructorAccess(Loc: CastLoc, D: Constructor, FoundDecl, |
4498 | Entity: InitializedEntity::InitializeTemporary(Type: Ty)); |
4499 | if (S.DiagnoseUseOfDecl(Method, CastLoc)) |
4500 | return ExprError(); |
4501 | |
4502 | ExprResult Result = S.BuildCXXConstructExpr( |
4503 | ConstructLoc: CastLoc, DeclInitType: Ty, FoundDecl, Constructor: cast<CXXConstructorDecl>(Val: Method), |
4504 | Exprs: ConstructorArgs, HadMultipleCandidates, |
4505 | /*ListInit*/ IsListInitialization: false, /*StdInitListInit*/ IsStdInitListInitialization: false, /*ZeroInit*/ RequiresZeroInit: false, |
4506 | ConstructKind: CXXConstructionKind::Complete, ParenRange: SourceRange()); |
4507 | if (Result.isInvalid()) |
4508 | return ExprError(); |
4509 | |
4510 | return S.MaybeBindToTemporary(E: Result.getAs<Expr>()); |
4511 | } |
4512 | |
4513 | case CK_UserDefinedConversion: { |
4514 | assert(!From->getType()->isPointerType() && "Arg can't have pointer type!"); |
4515 | |
4516 | S.CheckMemberOperatorAccess(Loc: CastLoc, ObjectExpr: From, /*arg*/ ArgExpr: nullptr, FoundDecl); |
4517 | if (S.DiagnoseUseOfDecl(Method, CastLoc)) |
4518 | return ExprError(); |
4519 | |
4520 | // Create an implicit call expr that calls it. |
4521 | CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: Method); |
4522 | ExprResult Result = S.BuildCXXMemberCallExpr(Exp: From, FoundDecl, Method: Conv, |
4523 | HadMultipleCandidates); |
4524 | if (Result.isInvalid()) |
4525 | return ExprError(); |
4526 | // Record usage of conversion in an implicit cast. |
4527 | Result = ImplicitCastExpr::Create(Context: S.Context, T: Result.get()->getType(), |
4528 | Kind: CK_UserDefinedConversion, Operand: Result.get(), |
4529 | BasePath: nullptr, Cat: Result.get()->getValueKind(), |
4530 | FPO: S.CurFPFeatureOverrides()); |
4531 | |
4532 | return S.MaybeBindToTemporary(E: Result.get()); |
4533 | } |
4534 | } |
4535 | } |
4536 | |
4537 | ExprResult |
4538 | Sema::PerformImplicitConversion(Expr *From, QualType ToType, |
4539 | const ImplicitConversionSequence &ICS, |
4540 | AssignmentAction Action, |
4541 | CheckedConversionKind CCK) { |
4542 | // C++ [over.match.oper]p7: [...] operands of class type are converted [...] |
4543 | if (CCK == CheckedConversionKind::ForBuiltinOverloadedOp && |
4544 | !From->getType()->isRecordType()) |
4545 | return From; |
4546 | |
4547 | switch (ICS.getKind()) { |
4548 | case ImplicitConversionSequence::StandardConversion: { |
4549 | ExprResult Res = PerformImplicitConversion(From, ToType, SCS: ICS.Standard, |
4550 | Action, CCK); |
4551 | if (Res.isInvalid()) |
4552 | return ExprError(); |
4553 | From = Res.get(); |
4554 | break; |
4555 | } |
4556 | |
4557 | case ImplicitConversionSequence::UserDefinedConversion: { |
4558 | |
4559 | FunctionDecl *FD = ICS.UserDefined.ConversionFunction; |
4560 | CastKind CastKind; |
4561 | QualType BeforeToType; |
4562 | assert(FD && "no conversion function for user-defined conversion seq"); |
4563 | if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Val: FD)) { |
4564 | CastKind = CK_UserDefinedConversion; |
4565 | |
4566 | // If the user-defined conversion is specified by a conversion function, |
4567 | // the initial standard conversion sequence converts the source type to |
4568 | // the implicit object parameter of the conversion function. |
4569 | BeforeToType = Context.getTagDeclType(Decl: Conv->getParent()); |
4570 | } else { |
4571 | const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(Val: FD); |
4572 | CastKind = CK_ConstructorConversion; |
4573 | // Do no conversion if dealing with ... for the first conversion. |
4574 | if (!ICS.UserDefined.EllipsisConversion) { |
4575 | // If the user-defined conversion is specified by a constructor, the |
4576 | // initial standard conversion sequence converts the source type to |
4577 | // the type required by the argument of the constructor |
4578 | BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType(); |
4579 | } |
4580 | } |
4581 | // Watch out for ellipsis conversion. |
4582 | if (!ICS.UserDefined.EllipsisConversion) { |
4583 | ExprResult Res = PerformImplicitConversion( |
4584 | From, ToType: BeforeToType, SCS: ICS.UserDefined.Before, |
4585 | Action: AssignmentAction::Converting, CCK); |
4586 | if (Res.isInvalid()) |
4587 | return ExprError(); |
4588 | From = Res.get(); |
4589 | } |
4590 | |
4591 | ExprResult CastArg = BuildCXXCastArgument( |
4592 | *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind, |
4593 | cast<CXXMethodDecl>(Val: FD), ICS.UserDefined.FoundConversionFunction, |
4594 | ICS.UserDefined.HadMultipleCandidates, From); |
4595 | |
4596 | if (CastArg.isInvalid()) |
4597 | return ExprError(); |
4598 | |
4599 | From = CastArg.get(); |
4600 | |
4601 | // C++ [over.match.oper]p7: |
4602 | // [...] the second standard conversion sequence of a user-defined |
4603 | // conversion sequence is not applied. |
4604 | if (CCK == CheckedConversionKind::ForBuiltinOverloadedOp) |
4605 | return From; |
4606 | |
4607 | return PerformImplicitConversion(From, ToType, SCS: ICS.UserDefined.After, |
4608 | Action: AssignmentAction::Converting, CCK); |
4609 | } |
4610 | |
4611 | case ImplicitConversionSequence::AmbiguousConversion: |
4612 | ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(), |
4613 | PDiag(diag::err_typecheck_ambiguous_condition) |
4614 | << From->getSourceRange()); |
4615 | return ExprError(); |
4616 | |
4617 | case ImplicitConversionSequence::EllipsisConversion: |
4618 | case ImplicitConversionSequence::StaticObjectArgumentConversion: |
4619 | llvm_unreachable("bad conversion"); |
4620 | |
4621 | case ImplicitConversionSequence::BadConversion: |
4622 | AssignConvertType ConvTy = |
4623 | CheckAssignmentConstraints(Loc: From->getExprLoc(), LHSType: ToType, RHSType: From->getType()); |
4624 | bool Diagnosed = DiagnoseAssignmentResult( |
4625 | ConvTy: ConvTy == AssignConvertType::Compatible |
4626 | ? AssignConvertType::Incompatible |
4627 | : ConvTy, |
4628 | Loc: From->getExprLoc(), DstType: ToType, SrcType: From->getType(), SrcExpr: From, Action); |
4629 | assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed; |
4630 | return ExprError(); |
4631 | } |
4632 | |
4633 | // Everything went well. |
4634 | return From; |
4635 | } |
4636 | |
4637 | // adjustVectorType - Compute the intermediate cast type casting elements of the |
4638 | // from type to the elements of the to type without resizing the vector. |
4639 | static QualType adjustVectorType(ASTContext &Context, QualType FromTy, |
4640 | QualType ToType, QualType *ElTy = nullptr) { |
4641 | QualType ElType = ToType; |
4642 | if (auto *ToVec = ToType->getAs<VectorType>()) |
4643 | ElType = ToVec->getElementType(); |
4644 | |
4645 | if (ElTy) |
4646 | *ElTy = ElType; |
4647 | if (!FromTy->isVectorType()) |
4648 | return ElType; |
4649 | auto *FromVec = FromTy->castAs<VectorType>(); |
4650 | return Context.getExtVectorType(VectorType: ElType, NumElts: FromVec->getNumElements()); |
4651 | } |
4652 | |
4653 | ExprResult |
4654 | Sema::PerformImplicitConversion(Expr *From, QualType ToType, |
4655 | const StandardConversionSequence& SCS, |
4656 | AssignmentAction Action, |
4657 | CheckedConversionKind CCK) { |
4658 | bool CStyle = (CCK == CheckedConversionKind::CStyleCast || |
4659 | CCK == CheckedConversionKind::FunctionalCast); |
4660 | |
4661 | // Overall FIXME: we are recomputing too many types here and doing far too |
4662 | // much extra work. What this means is that we need to keep track of more |
4663 | // information that is computed when we try the implicit conversion initially, |
4664 | // so that we don't need to recompute anything here. |
4665 | QualType FromType = From->getType(); |
4666 | |
4667 | if (SCS.CopyConstructor) { |
4668 | // FIXME: When can ToType be a reference type? |
4669 | assert(!ToType->isReferenceType()); |
4670 | if (SCS.Second == ICK_Derived_To_Base) { |
4671 | SmallVector<Expr*, 8> ConstructorArgs; |
4672 | if (CompleteConstructorCall( |
4673 | Constructor: cast<CXXConstructorDecl>(Val: SCS.CopyConstructor), DeclInitType: ToType, ArgsPtr: From, |
4674 | /*FIXME:ConstructLoc*/ Loc: SourceLocation(), ConvertedArgs&: ConstructorArgs)) |
4675 | return ExprError(); |
4676 | return BuildCXXConstructExpr( |
4677 | /*FIXME:ConstructLoc*/ ConstructLoc: SourceLocation(), DeclInitType: ToType, |
4678 | FoundDecl: SCS.FoundCopyConstructor, Constructor: SCS.CopyConstructor, Exprs: ConstructorArgs, |
4679 | /*HadMultipleCandidates*/ false, |
4680 | /*ListInit*/ IsListInitialization: false, /*StdInitListInit*/ IsStdInitListInitialization: false, /*ZeroInit*/ RequiresZeroInit: false, |
4681 | ConstructKind: CXXConstructionKind::Complete, ParenRange: SourceRange()); |
4682 | } |
4683 | return BuildCXXConstructExpr( |
4684 | /*FIXME:ConstructLoc*/ ConstructLoc: SourceLocation(), DeclInitType: ToType, |
4685 | FoundDecl: SCS.FoundCopyConstructor, Constructor: SCS.CopyConstructor, Exprs: From, |
4686 | /*HadMultipleCandidates*/ false, |
4687 | /*ListInit*/ IsListInitialization: false, /*StdInitListInit*/ IsStdInitListInitialization: false, /*ZeroInit*/ RequiresZeroInit: false, |
4688 | ConstructKind: CXXConstructionKind::Complete, ParenRange: SourceRange()); |
4689 | } |
4690 | |
4691 | // Resolve overloaded function references. |
4692 | if (Context.hasSameType(FromType, Context.OverloadTy)) { |
4693 | DeclAccessPair Found; |
4694 | FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(AddressOfExpr: From, TargetType: ToType, |
4695 | Complain: true, Found); |
4696 | if (!Fn) |
4697 | return ExprError(); |
4698 | |
4699 | if (DiagnoseUseOfDecl(D: Fn, Locs: From->getBeginLoc())) |
4700 | return ExprError(); |
4701 | |
4702 | ExprResult Res = FixOverloadedFunctionReference(E: From, FoundDecl: Found, Fn); |
4703 | if (Res.isInvalid()) |
4704 | return ExprError(); |
4705 | |
4706 | // We might get back another placeholder expression if we resolved to a |
4707 | // builtin. |
4708 | Res = CheckPlaceholderExpr(E: Res.get()); |
4709 | if (Res.isInvalid()) |
4710 | return ExprError(); |
4711 | |
4712 | From = Res.get(); |
4713 | FromType = From->getType(); |
4714 | } |
4715 | |
4716 | // If we're converting to an atomic type, first convert to the corresponding |
4717 | // non-atomic type. |
4718 | QualType ToAtomicType; |
4719 | if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) { |
4720 | ToAtomicType = ToType; |
4721 | ToType = ToAtomic->getValueType(); |
4722 | } |
4723 | |
4724 | QualType InitialFromType = FromType; |
4725 | // Perform the first implicit conversion. |
4726 | switch (SCS.First) { |
4727 | case ICK_Identity: |
4728 | if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) { |
4729 | FromType = FromAtomic->getValueType().getUnqualifiedType(); |
4730 | From = ImplicitCastExpr::Create(Context, T: FromType, Kind: CK_AtomicToNonAtomic, |
4731 | Operand: From, /*BasePath=*/nullptr, Cat: VK_PRValue, |
4732 | FPO: FPOptionsOverride()); |
4733 | } |
4734 | break; |
4735 | |
4736 | case ICK_Lvalue_To_Rvalue: { |
4737 | assert(From->getObjectKind() != OK_ObjCProperty); |
4738 | ExprResult FromRes = DefaultLvalueConversion(E: From); |
4739 | if (FromRes.isInvalid()) |
4740 | return ExprError(); |
4741 | |
4742 | From = FromRes.get(); |
4743 | FromType = From->getType(); |
4744 | break; |
4745 | } |
4746 | |
4747 | case ICK_Array_To_Pointer: |
4748 | FromType = Context.getArrayDecayedType(T: FromType); |
4749 | From = ImpCastExprToType(E: From, Type: FromType, CK: CK_ArrayToPointerDecay, VK: VK_PRValue, |
4750 | /*BasePath=*/nullptr, CCK) |
4751 | .get(); |
4752 | break; |
4753 | |
4754 | case ICK_HLSL_Array_RValue: |
4755 | if (ToType->isArrayParameterType()) { |
4756 | FromType = Context.getArrayParameterType(Ty: FromType); |
4757 | } else if (FromType->isArrayParameterType()) { |
4758 | const ArrayParameterType *APT = cast<ArrayParameterType>(Val&: FromType); |
4759 | FromType = APT->getConstantArrayType(Ctx: Context); |
4760 | } |
4761 | From = ImpCastExprToType(E: From, Type: FromType, CK: CK_HLSLArrayRValue, VK: VK_PRValue, |
4762 | /*BasePath=*/nullptr, CCK) |
4763 | .get(); |
4764 | break; |
4765 | |
4766 | case ICK_Function_To_Pointer: |
4767 | FromType = Context.getPointerType(T: FromType); |
4768 | From = ImpCastExprToType(E: From, Type: FromType, CK: CK_FunctionToPointerDecay, |
4769 | VK: VK_PRValue, /*BasePath=*/nullptr, CCK) |
4770 | .get(); |
4771 | break; |
4772 | |
4773 | default: |
4774 | llvm_unreachable("Improper first standard conversion"); |
4775 | } |
4776 | |
4777 | // Perform the second implicit conversion |
4778 | switch (SCS.Second) { |
4779 | case ICK_Identity: |
4780 | // C++ [except.spec]p5: |
4781 | // [For] assignment to and initialization of pointers to functions, |
4782 | // pointers to member functions, and references to functions: the |
4783 | // target entity shall allow at least the exceptions allowed by the |
4784 | // source value in the assignment or initialization. |
4785 | switch (Action) { |
4786 | case AssignmentAction::Assigning: |
4787 | case AssignmentAction::Initializing: |
4788 | // Note, function argument passing and returning are initialization. |
4789 | case AssignmentAction::Passing: |
4790 | case AssignmentAction::Returning: |
4791 | case AssignmentAction::Sending: |
4792 | case AssignmentAction::Passing_CFAudited: |
4793 | if (CheckExceptionSpecCompatibility(From, ToType)) |
4794 | return ExprError(); |
4795 | break; |
4796 | |
4797 | case AssignmentAction::Casting: |
4798 | case AssignmentAction::Converting: |
4799 | // Casts and implicit conversions are not initialization, so are not |
4800 | // checked for exception specification mismatches. |
4801 | break; |
4802 | } |
4803 | // Nothing else to do. |
4804 | break; |
4805 | |
4806 | case ICK_Integral_Promotion: |
4807 | case ICK_Integral_Conversion: { |
4808 | QualType ElTy = ToType; |
4809 | QualType StepTy = ToType; |
4810 | if (FromType->isVectorType() || ToType->isVectorType()) |
4811 | StepTy = adjustVectorType(Context, FromTy: FromType, ToType, ElTy: &ElTy); |
4812 | if (ElTy->isBooleanType()) { |
4813 | assert(FromType->castAs<EnumType>()->getDecl()->isFixed() && |
4814 | SCS.Second == ICK_Integral_Promotion && |
4815 | "only enums with fixed underlying type can promote to bool"); |
4816 | From = ImpCastExprToType(E: From, Type: StepTy, CK: CK_IntegralToBoolean, VK: VK_PRValue, |
4817 | /*BasePath=*/nullptr, CCK) |
4818 | .get(); |
4819 | } else { |
4820 | From = ImpCastExprToType(E: From, Type: StepTy, CK: CK_IntegralCast, VK: VK_PRValue, |
4821 | /*BasePath=*/nullptr, CCK) |
4822 | .get(); |
4823 | } |
4824 | break; |
4825 | } |
4826 | |
4827 | case ICK_Floating_Promotion: |
4828 | case ICK_Floating_Conversion: { |
4829 | QualType StepTy = ToType; |
4830 | if (FromType->isVectorType() || ToType->isVectorType()) |
4831 | StepTy = adjustVectorType(Context, FromTy: FromType, ToType); |
4832 | From = ImpCastExprToType(E: From, Type: StepTy, CK: CK_FloatingCast, VK: VK_PRValue, |
4833 | /*BasePath=*/nullptr, CCK) |
4834 | .get(); |
4835 | break; |
4836 | } |
4837 | |
4838 | case ICK_Complex_Promotion: |
4839 | case ICK_Complex_Conversion: { |
4840 | QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType(); |
4841 | QualType ToEl = ToType->castAs<ComplexType>()->getElementType(); |
4842 | CastKind CK; |
4843 | if (FromEl->isRealFloatingType()) { |
4844 | if (ToEl->isRealFloatingType()) |
4845 | CK = CK_FloatingComplexCast; |
4846 | else |
4847 | CK = CK_FloatingComplexToIntegralComplex; |
4848 | } else if (ToEl->isRealFloatingType()) { |
4849 | CK = CK_IntegralComplexToFloatingComplex; |
4850 | } else { |
4851 | CK = CK_IntegralComplexCast; |
4852 | } |
4853 | From = ImpCastExprToType(E: From, Type: ToType, CK, VK: VK_PRValue, /*BasePath=*/nullptr, |
4854 | CCK) |
4855 | .get(); |
4856 | break; |
4857 | } |
4858 | |
4859 | case ICK_Floating_Integral: { |
4860 | QualType ElTy = ToType; |
4861 | QualType StepTy = ToType; |
4862 | if (FromType->isVectorType() || ToType->isVectorType()) |
4863 | StepTy = adjustVectorType(Context, FromTy: FromType, ToType, ElTy: &ElTy); |
4864 | if (ElTy->isRealFloatingType()) |
4865 | From = ImpCastExprToType(E: From, Type: StepTy, CK: CK_IntegralToFloating, VK: VK_PRValue, |
4866 | /*BasePath=*/nullptr, CCK) |
4867 | .get(); |
4868 | else |
4869 | From = ImpCastExprToType(E: From, Type: StepTy, CK: CK_FloatingToIntegral, VK: VK_PRValue, |
4870 | /*BasePath=*/nullptr, CCK) |
4871 | .get(); |
4872 | break; |
4873 | } |
4874 | |
4875 | case ICK_Fixed_Point_Conversion: |
4876 | assert((FromType->isFixedPointType() || ToType->isFixedPointType()) && |
4877 | "Attempting implicit fixed point conversion without a fixed " |
4878 | "point operand"); |
4879 | if (FromType->isFloatingType()) |
4880 | From = ImpCastExprToType(E: From, Type: ToType, CK: CK_FloatingToFixedPoint, |
4881 | VK: VK_PRValue, |
4882 | /*BasePath=*/nullptr, CCK).get(); |
4883 | else if (ToType->isFloatingType()) |
4884 | From = ImpCastExprToType(E: From, Type: ToType, CK: CK_FixedPointToFloating, |
4885 | VK: VK_PRValue, |
4886 | /*BasePath=*/nullptr, CCK).get(); |
4887 | else if (FromType->isIntegralType(Ctx: Context)) |
4888 | From = ImpCastExprToType(E: From, Type: ToType, CK: CK_IntegralToFixedPoint, |
4889 | VK: VK_PRValue, |
4890 | /*BasePath=*/nullptr, CCK).get(); |
4891 | else if (ToType->isIntegralType(Ctx: Context)) |
4892 | From = ImpCastExprToType(E: From, Type: ToType, CK: CK_FixedPointToIntegral, |
4893 | VK: VK_PRValue, |
4894 | /*BasePath=*/nullptr, CCK).get(); |
4895 | else if (ToType->isBooleanType()) |
4896 | From = ImpCastExprToType(E: From, Type: ToType, CK: CK_FixedPointToBoolean, |
4897 | VK: VK_PRValue, |
4898 | /*BasePath=*/nullptr, CCK).get(); |
4899 | else |
4900 | From = ImpCastExprToType(E: From, Type: ToType, CK: CK_FixedPointCast, |
4901 | VK: VK_PRValue, |
4902 | /*BasePath=*/nullptr, CCK).get(); |
4903 | break; |
4904 | |
4905 | case ICK_Compatible_Conversion: |
4906 | From = ImpCastExprToType(E: From, Type: ToType, CK: CK_NoOp, VK: From->getValueKind(), |
4907 | /*BasePath=*/nullptr, CCK).get(); |
4908 | break; |
4909 | |
4910 | case ICK_Writeback_Conversion: |
4911 | case ICK_Pointer_Conversion: { |
4912 | if (SCS.IncompatibleObjC && Action != AssignmentAction::Casting) { |
4913 | // Diagnose incompatible Objective-C conversions |
4914 | if (Action == AssignmentAction::Initializing || |
4915 | Action == AssignmentAction::Assigning) |
4916 | Diag(From->getBeginLoc(), |
4917 | diag::ext_typecheck_convert_incompatible_pointer) |
4918 | << ToType << From->getType() << Action << From->getSourceRange() |
4919 | << 0; |
4920 | else |
4921 | Diag(From->getBeginLoc(), |
4922 | diag::ext_typecheck_convert_incompatible_pointer) |
4923 | << From->getType() << ToType << Action << From->getSourceRange() |
4924 | << 0; |
4925 | |
4926 | if (From->getType()->isObjCObjectPointerType() && |
4927 | ToType->isObjCObjectPointerType()) |
4928 | ObjC().EmitRelatedResultTypeNote(E: From); |
4929 | } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && |
4930 | !ObjC().CheckObjCARCUnavailableWeakConversion(castType: ToType, |
4931 | ExprType: From->getType())) { |
4932 | if (Action == AssignmentAction::Initializing) |
4933 | Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign); |
4934 | else |
4935 | Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable) |
4936 | << (Action == AssignmentAction::Casting) << From->getType() |
4937 | << ToType << From->getSourceRange(); |
4938 | } |
4939 | |
4940 | // Defer address space conversion to the third conversion. |
4941 | QualType FromPteeType = From->getType()->getPointeeType(); |
4942 | QualType ToPteeType = ToType->getPointeeType(); |
4943 | QualType NewToType = ToType; |
4944 | if (!FromPteeType.isNull() && !ToPteeType.isNull() && |
4945 | FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) { |
4946 | NewToType = Context.removeAddrSpaceQualType(T: ToPteeType); |
4947 | NewToType = Context.getAddrSpaceQualType(T: NewToType, |
4948 | AddressSpace: FromPteeType.getAddressSpace()); |
4949 | if (ToType->isObjCObjectPointerType()) |
4950 | NewToType = Context.getObjCObjectPointerType(OIT: NewToType); |
4951 | else if (ToType->isBlockPointerType()) |
4952 | NewToType = Context.getBlockPointerType(T: NewToType); |
4953 | else |
4954 | NewToType = Context.getPointerType(T: NewToType); |
4955 | } |
4956 | |
4957 | CastKind Kind; |
4958 | CXXCastPath BasePath; |
4959 | if (CheckPointerConversion(From, ToType: NewToType, Kind, BasePath, IgnoreBaseAccess: CStyle)) |
4960 | return ExprError(); |
4961 | |
4962 | // Make sure we extend blocks if necessary. |
4963 | // FIXME: doing this here is really ugly. |
4964 | if (Kind == CK_BlockPointerToObjCPointerCast) { |
4965 | ExprResult E = From; |
4966 | (void)ObjC().PrepareCastToObjCObjectPointer(E); |
4967 | From = E.get(); |
4968 | } |
4969 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) |
4970 | ObjC().CheckObjCConversion(castRange: SourceRange(), castType: NewToType, op&: From, CCK); |
4971 | From = ImpCastExprToType(E: From, Type: NewToType, CK: Kind, VK: VK_PRValue, BasePath: &BasePath, CCK) |
4972 | .get(); |
4973 | break; |
4974 | } |
4975 | |
4976 | case ICK_Pointer_Member: { |
4977 | CastKind Kind; |
4978 | CXXCastPath BasePath; |
4979 | switch (CheckMemberPointerConversion( |
4980 | FromType: From->getType(), ToPtrType: ToType->castAs<MemberPointerType>(), Kind, BasePath, |
4981 | CheckLoc: From->getExprLoc(), OpRange: From->getSourceRange(), IgnoreBaseAccess: CStyle, |
4982 | Direction: MemberPointerConversionDirection::Downcast)) { |
4983 | case MemberPointerConversionResult::Success: |
4984 | assert((Kind != CK_NullToMemberPointer || |
4985 | From->isNullPointerConstant(Context, |
4986 | Expr::NPC_ValueDependentIsNull)) && |
4987 | "Expr must be null pointer constant!"); |
4988 | break; |
4989 | case MemberPointerConversionResult::Inaccessible: |
4990 | break; |
4991 | case MemberPointerConversionResult::DifferentPointee: |
4992 | llvm_unreachable("unexpected result"); |
4993 | case MemberPointerConversionResult::NotDerived: |
4994 | llvm_unreachable("Should not have been called if derivation isn't OK."); |
4995 | case MemberPointerConversionResult::Ambiguous: |
4996 | case MemberPointerConversionResult::Virtual: |
4997 | return ExprError(); |
4998 | } |
4999 | if (CheckExceptionSpecCompatibility(From, ToType)) |
5000 | return ExprError(); |
5001 | |
5002 | From = |
5003 | ImpCastExprToType(E: From, Type: ToType, CK: Kind, VK: VK_PRValue, BasePath: &BasePath, CCK).get(); |
5004 | break; |
5005 | } |
5006 | |
5007 | case ICK_Boolean_Conversion: { |
5008 | // Perform half-to-boolean conversion via float. |
5009 | if (From->getType()->isHalfType()) { |
5010 | From = ImpCastExprToType(E: From, Type: Context.FloatTy, CK: CK_FloatingCast).get(); |
5011 | FromType = Context.FloatTy; |
5012 | } |
5013 | QualType ElTy = FromType; |
5014 | QualType StepTy = ToType; |
5015 | if (FromType->isVectorType()) |
5016 | ElTy = FromType->castAs<VectorType>()->getElementType(); |
5017 | if (getLangOpts().HLSL && |
5018 | (FromType->isVectorType() || ToType->isVectorType())) |
5019 | StepTy = adjustVectorType(Context, FromTy: FromType, ToType); |
5020 | |
5021 | From = ImpCastExprToType(E: From, Type: StepTy, CK: ScalarTypeToBooleanCastKind(ScalarTy: ElTy), |
5022 | VK: VK_PRValue, |
5023 | /*BasePath=*/nullptr, CCK) |
5024 | .get(); |
5025 | break; |
5026 | } |
5027 | |
5028 | case ICK_Derived_To_Base: { |
5029 | CXXCastPath BasePath; |
5030 | if (CheckDerivedToBaseConversion( |
5031 | From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(), |
5032 | From->getSourceRange(), &BasePath, CStyle)) |
5033 | return ExprError(); |
5034 | |
5035 | From = ImpCastExprToType(E: From, Type: ToType.getNonReferenceType(), |
5036 | CK: CK_DerivedToBase, VK: From->getValueKind(), |
5037 | BasePath: &BasePath, CCK).get(); |
5038 | break; |
5039 | } |
5040 | |
5041 | case ICK_Vector_Conversion: |
5042 | From = ImpCastExprToType(E: From, Type: ToType, CK: CK_BitCast, VK: VK_PRValue, |
5043 | /*BasePath=*/nullptr, CCK) |
5044 | .get(); |
5045 | break; |
5046 | |
5047 | case ICK_SVE_Vector_Conversion: |
5048 | case ICK_RVV_Vector_Conversion: |
5049 | From = ImpCastExprToType(E: From, Type: ToType, CK: CK_BitCast, VK: VK_PRValue, |
5050 | /*BasePath=*/nullptr, CCK) |
5051 | .get(); |
5052 | break; |
5053 | |
5054 | case ICK_Vector_Splat: { |
5055 | // Vector splat from any arithmetic type to a vector. |
5056 | Expr *Elem = prepareVectorSplat(VectorTy: ToType, SplattedExpr: From).get(); |
5057 | From = ImpCastExprToType(E: Elem, Type: ToType, CK: CK_VectorSplat, VK: VK_PRValue, |
5058 | /*BasePath=*/nullptr, CCK) |
5059 | .get(); |
5060 | break; |
5061 | } |
5062 | |
5063 | case ICK_Complex_Real: |
5064 | // Case 1. x -> _Complex y |
5065 | if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) { |
5066 | QualType ElType = ToComplex->getElementType(); |
5067 | bool isFloatingComplex = ElType->isRealFloatingType(); |
5068 | |
5069 | // x -> y |
5070 | if (Context.hasSameUnqualifiedType(T1: ElType, T2: From->getType())) { |
5071 | // do nothing |
5072 | } else if (From->getType()->isRealFloatingType()) { |
5073 | From = ImpCastExprToType(E: From, Type: ElType, |
5074 | CK: isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get(); |
5075 | } else { |
5076 | assert(From->getType()->isIntegerType()); |
5077 | From = ImpCastExprToType(E: From, Type: ElType, |
5078 | CK: isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get(); |
5079 | } |
5080 | // y -> _Complex y |
5081 | From = ImpCastExprToType(E: From, Type: ToType, |
5082 | CK: isFloatingComplex ? CK_FloatingRealToComplex |
5083 | : CK_IntegralRealToComplex).get(); |
5084 | |
5085 | // Case 2. _Complex x -> y |
5086 | } else { |
5087 | auto *FromComplex = From->getType()->castAs<ComplexType>(); |
5088 | QualType ElType = FromComplex->getElementType(); |
5089 | bool isFloatingComplex = ElType->isRealFloatingType(); |
5090 | |
5091 | // _Complex x -> x |
5092 | From = ImpCastExprToType(E: From, Type: ElType, |
5093 | CK: isFloatingComplex ? CK_FloatingComplexToReal |
5094 | : CK_IntegralComplexToReal, |
5095 | VK: VK_PRValue, /*BasePath=*/nullptr, CCK) |
5096 | .get(); |
5097 | |
5098 | // x -> y |
5099 | if (Context.hasSameUnqualifiedType(T1: ElType, T2: ToType)) { |
5100 | // do nothing |
5101 | } else if (ToType->isRealFloatingType()) { |
5102 | From = ImpCastExprToType(E: From, Type: ToType, |
5103 | CK: isFloatingComplex ? CK_FloatingCast |
5104 | : CK_IntegralToFloating, |
5105 | VK: VK_PRValue, /*BasePath=*/nullptr, CCK) |
5106 | .get(); |
5107 | } else { |
5108 | assert(ToType->isIntegerType()); |
5109 | From = ImpCastExprToType(E: From, Type: ToType, |
5110 | CK: isFloatingComplex ? CK_FloatingToIntegral |
5111 | : CK_IntegralCast, |
5112 | VK: VK_PRValue, /*BasePath=*/nullptr, CCK) |
5113 | .get(); |
5114 | } |
5115 | } |
5116 | break; |
5117 | |
5118 | case ICK_Block_Pointer_Conversion: { |
5119 | LangAS AddrSpaceL = |
5120 | ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace(); |
5121 | LangAS AddrSpaceR = |
5122 | FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace(); |
5123 | assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR, |
5124 | getASTContext()) && |
5125 | "Invalid cast"); |
5126 | CastKind Kind = |
5127 | AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; |
5128 | From = ImpCastExprToType(E: From, Type: ToType.getUnqualifiedType(), CK: Kind, |
5129 | VK: VK_PRValue, /*BasePath=*/nullptr, CCK) |
5130 | .get(); |
5131 | break; |
5132 | } |
5133 | |
5134 | case ICK_TransparentUnionConversion: { |
5135 | ExprResult FromRes = From; |
5136 | AssignConvertType ConvTy = |
5137 | CheckTransparentUnionArgumentConstraints(ArgType: ToType, RHS&: FromRes); |
5138 | if (FromRes.isInvalid()) |
5139 | return ExprError(); |
5140 | From = FromRes.get(); |
5141 | assert((ConvTy == AssignConvertType::Compatible) && |
5142 | "Improper transparent union conversion"); |
5143 | (void)ConvTy; |
5144 | break; |
5145 | } |
5146 | |
5147 | case ICK_Zero_Event_Conversion: |
5148 | case ICK_Zero_Queue_Conversion: |
5149 | From = ImpCastExprToType(E: From, Type: ToType, |
5150 | CK: CK_ZeroToOCLOpaqueType, |
5151 | VK: From->getValueKind()).get(); |
5152 | break; |
5153 | |
5154 | case ICK_Lvalue_To_Rvalue: |
5155 | case ICK_Array_To_Pointer: |
5156 | case ICK_Function_To_Pointer: |
5157 | case ICK_Function_Conversion: |
5158 | case ICK_Qualification: |
5159 | case ICK_Num_Conversion_Kinds: |
5160 | case ICK_C_Only_Conversion: |
5161 | case ICK_Incompatible_Pointer_Conversion: |
5162 | case ICK_HLSL_Array_RValue: |
5163 | case ICK_HLSL_Vector_Truncation: |
5164 | case ICK_HLSL_Vector_Splat: |
5165 | llvm_unreachable("Improper second standard conversion"); |
5166 | } |
5167 | |
5168 | if (SCS.Dimension != ICK_Identity) { |
5169 | // If SCS.Element is not ICK_Identity the To and From types must be HLSL |
5170 | // vectors or matrices. |
5171 | |
5172 | // TODO: Support HLSL matrices. |
5173 | assert((!From->getType()->isMatrixType() && !ToType->isMatrixType()) && |
5174 | "Dimension conversion for matrix types is not implemented yet."); |
5175 | assert((ToType->isVectorType() || ToType->isBuiltinType()) && |
5176 | "Dimension conversion output must be vector or scalar type."); |
5177 | switch (SCS.Dimension) { |
5178 | case ICK_HLSL_Vector_Splat: { |
5179 | // Vector splat from any arithmetic type to a vector. |
5180 | Expr *Elem = prepareVectorSplat(VectorTy: ToType, SplattedExpr: From).get(); |
5181 | From = ImpCastExprToType(E: Elem, Type: ToType, CK: CK_VectorSplat, VK: VK_PRValue, |
5182 | /*BasePath=*/nullptr, CCK) |
5183 | .get(); |
5184 | break; |
5185 | } |
5186 | case ICK_HLSL_Vector_Truncation: { |
5187 | // Note: HLSL built-in vectors are ExtVectors. Since this truncates a |
5188 | // vector to a smaller vector or to a scalar, this can only operate on |
5189 | // arguments where the source type is an ExtVector and the destination |
5190 | // type is destination type is either an ExtVectorType or a builtin scalar |
5191 | // type. |
5192 | auto *FromVec = From->getType()->castAs<VectorType>(); |
5193 | QualType TruncTy = FromVec->getElementType(); |
5194 | if (auto *ToVec = ToType->getAs<VectorType>()) |
5195 | TruncTy = Context.getExtVectorType(VectorType: TruncTy, NumElts: ToVec->getNumElements()); |
5196 | From = ImpCastExprToType(E: From, Type: TruncTy, CK: CK_HLSLVectorTruncation, |
5197 | VK: From->getValueKind()) |
5198 | .get(); |
5199 | |
5200 | break; |
5201 | } |
5202 | case ICK_Identity: |
5203 | default: |
5204 | llvm_unreachable("Improper element standard conversion"); |
5205 | } |
5206 | } |
5207 | |
5208 | switch (SCS.Third) { |
5209 | case ICK_Identity: |
5210 | // Nothing to do. |
5211 | break; |
5212 | |
5213 | case ICK_Function_Conversion: |
5214 | // If both sides are functions (or pointers/references to them), there could |
5215 | // be incompatible exception declarations. |
5216 | if (CheckExceptionSpecCompatibility(From, ToType)) |
5217 | return ExprError(); |
5218 | |
5219 | From = ImpCastExprToType(E: From, Type: ToType, CK: CK_NoOp, VK: VK_PRValue, |
5220 | /*BasePath=*/nullptr, CCK) |
5221 | .get(); |
5222 | break; |
5223 | |
5224 | case ICK_Qualification: { |
5225 | ExprValueKind VK = From->getValueKind(); |
5226 | CastKind CK = CK_NoOp; |
5227 | |
5228 | if (ToType->isReferenceType() && |
5229 | ToType->getPointeeType().getAddressSpace() != |
5230 | From->getType().getAddressSpace()) |
5231 | CK = CK_AddressSpaceConversion; |
5232 | |
5233 | if (ToType->isPointerType() && |
5234 | ToType->getPointeeType().getAddressSpace() != |
5235 | From->getType()->getPointeeType().getAddressSpace()) |
5236 | CK = CK_AddressSpaceConversion; |
5237 | |
5238 | if (!isCast(CCK) && |
5239 | !ToType->getPointeeType().getQualifiers().hasUnaligned() && |
5240 | From->getType()->getPointeeType().getQualifiers().hasUnaligned()) { |
5241 | Diag(From->getBeginLoc(), diag::warn_imp_cast_drops_unaligned) |
5242 | << InitialFromType << ToType; |
5243 | } |
5244 | |
5245 | From = ImpCastExprToType(E: From, Type: ToType.getNonLValueExprType(Context), CK, VK, |
5246 | /*BasePath=*/nullptr, CCK) |
5247 | .get(); |
5248 | |
5249 | if (SCS.DeprecatedStringLiteralToCharPtr && |
5250 | !getLangOpts().WritableStrings) { |
5251 | Diag(From->getBeginLoc(), |
5252 | getLangOpts().CPlusPlus11 |
5253 | ? diag::ext_deprecated_string_literal_conversion |
5254 | : diag::warn_deprecated_string_literal_conversion) |
5255 | << ToType.getNonReferenceType(); |
5256 | } |
5257 | |
5258 | break; |
5259 | } |
5260 | |
5261 | default: |
5262 | llvm_unreachable("Improper third standard conversion"); |
5263 | } |
5264 | |
5265 | // If this conversion sequence involved a scalar -> atomic conversion, perform |
5266 | // that conversion now. |
5267 | if (!ToAtomicType.isNull()) { |
5268 | assert(Context.hasSameType( |
5269 | ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType())); |
5270 | From = ImpCastExprToType(E: From, Type: ToAtomicType, CK: CK_NonAtomicToAtomic, |
5271 | VK: VK_PRValue, BasePath: nullptr, CCK) |
5272 | .get(); |
5273 | } |
5274 | |
5275 | // Materialize a temporary if we're implicitly converting to a reference |
5276 | // type. This is not required by the C++ rules but is necessary to maintain |
5277 | // AST invariants. |
5278 | if (ToType->isReferenceType() && From->isPRValue()) { |
5279 | ExprResult Res = TemporaryMaterializationConversion(E: From); |
5280 | if (Res.isInvalid()) |
5281 | return ExprError(); |
5282 | From = Res.get(); |
5283 | } |
5284 | |
5285 | // If this conversion sequence succeeded and involved implicitly converting a |
5286 | // _Nullable type to a _Nonnull one, complain. |
5287 | if (!isCast(CCK)) |
5288 | diagnoseNullableToNonnullConversion(DstType: ToType, SrcType: InitialFromType, |
5289 | Loc: From->getBeginLoc()); |
5290 | |
5291 | return From; |
5292 | } |
5293 | |
5294 | QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, |
5295 | ExprValueKind &VK, |
5296 | SourceLocation Loc, |
5297 | bool isIndirect) { |
5298 | assert(!LHS.get()->hasPlaceholderType() && !RHS.get()->hasPlaceholderType() && |
5299 | "placeholders should have been weeded out by now"); |
5300 | |
5301 | // The LHS undergoes lvalue conversions if this is ->*, and undergoes the |
5302 | // temporary materialization conversion otherwise. |
5303 | if (isIndirect) |
5304 | LHS = DefaultLvalueConversion(E: LHS.get()); |
5305 | else if (LHS.get()->isPRValue()) |
5306 | LHS = TemporaryMaterializationConversion(E: LHS.get()); |
5307 | if (LHS.isInvalid()) |
5308 | return QualType(); |
5309 | |
5310 | // The RHS always undergoes lvalue conversions. |
5311 | RHS = DefaultLvalueConversion(E: RHS.get()); |
5312 | if (RHS.isInvalid()) return QualType(); |
5313 | |
5314 | const char *OpSpelling = isIndirect ? "->*": ".*"; |
5315 | // C++ 5.5p2 |
5316 | // The binary operator .* [p3: ->*] binds its second operand, which shall |
5317 | // be of type "pointer to member of T" (where T is a completely-defined |
5318 | // class type) [...] |
5319 | QualType RHSType = RHS.get()->getType(); |
5320 | const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>(); |
5321 | if (!MemPtr) { |
5322 | Diag(Loc, diag::err_bad_memptr_rhs) |
5323 | << OpSpelling << RHSType << RHS.get()->getSourceRange(); |
5324 | return QualType(); |
5325 | } |
5326 | |
5327 | CXXRecordDecl *RHSClass = MemPtr->getMostRecentCXXRecordDecl(); |
5328 | |
5329 | // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the |
5330 | // member pointer points must be completely-defined. However, there is no |
5331 | // reason for this semantic distinction, and the rule is not enforced by |
5332 | // other compilers. Therefore, we do not check this property, as it is |
5333 | // likely to be considered a defect. |
5334 | |
5335 | // C++ 5.5p2 |
5336 | // [...] to its first operand, which shall be of class T or of a class of |
5337 | // which T is an unambiguous and accessible base class. [p3: a pointer to |
5338 | // such a class] |
5339 | QualType LHSType = LHS.get()->getType(); |
5340 | if (isIndirect) { |
5341 | if (const PointerType *Ptr = LHSType->getAs<PointerType>()) |
5342 | LHSType = Ptr->getPointeeType(); |
5343 | else { |
5344 | Diag(Loc, diag::err_bad_memptr_lhs) |
5345 | << OpSpelling << 1 << LHSType |
5346 | << FixItHint::CreateReplacement(SourceRange(Loc), ".*"); |
5347 | return QualType(); |
5348 | } |
5349 | } |
5350 | CXXRecordDecl *LHSClass = LHSType->getAsCXXRecordDecl(); |
5351 | |
5352 | if (!declaresSameEntity(LHSClass, RHSClass)) { |
5353 | // If we want to check the hierarchy, we need a complete type. |
5354 | if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs, |
5355 | OpSpelling, (int)isIndirect)) { |
5356 | return QualType(); |
5357 | } |
5358 | |
5359 | if (!IsDerivedFrom(Loc, Derived: LHSClass, Base: RHSClass)) { |
5360 | Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling |
5361 | << (int)isIndirect << LHS.get()->getType(); |
5362 | return QualType(); |
5363 | } |
5364 | |
5365 | CXXCastPath BasePath; |
5366 | if (CheckDerivedToBaseConversion( |
5367 | Derived: LHSType, Base: QualType(RHSClass->getTypeForDecl(), 0), Loc, |
5368 | Range: SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()), |
5369 | BasePath: &BasePath)) |
5370 | return QualType(); |
5371 | |
5372 | // Cast LHS to type of use. |
5373 | QualType UseType = Context.getQualifiedType(RHSClass->getTypeForDecl(), |
5374 | LHSType.getQualifiers()); |
5375 | if (isIndirect) |
5376 | UseType = Context.getPointerType(T: UseType); |
5377 | ExprValueKind VK = isIndirect ? VK_PRValue : LHS.get()->getValueKind(); |
5378 | LHS = ImpCastExprToType(E: LHS.get(), Type: UseType, CK: CK_DerivedToBase, VK, |
5379 | BasePath: &BasePath); |
5380 | } |
5381 | |
5382 | if (isa<CXXScalarValueInitExpr>(Val: RHS.get()->IgnoreParens())) { |
5383 | // Diagnose use of pointer-to-member type which when used as |
5384 | // the functional cast in a pointer-to-member expression. |
5385 | Diag(Loc, diag::err_pointer_to_member_type) << isIndirect; |
5386 | return QualType(); |
5387 | } |
5388 | |
5389 | // C++ 5.5p2 |
5390 | // The result is an object or a function of the type specified by the |
5391 | // second operand. |
5392 | // The cv qualifiers are the union of those in the pointer and the left side, |
5393 | // in accordance with 5.5p5 and 5.2.5. |
5394 | QualType Result = MemPtr->getPointeeType(); |
5395 | Result = Context.getCVRQualifiedType(T: Result, CVR: LHSType.getCVRQualifiers()); |
5396 | |
5397 | // C++0x [expr.mptr.oper]p6: |
5398 | // In a .* expression whose object expression is an rvalue, the program is |
5399 | // ill-formed if the second operand is a pointer to member function with |
5400 | // ref-qualifier &. In a ->* expression or in a .* expression whose object |
5401 | // expression is an lvalue, the program is ill-formed if the second operand |
5402 | // is a pointer to member function with ref-qualifier &&. |
5403 | if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) { |
5404 | switch (Proto->getRefQualifier()) { |
5405 | case RQ_None: |
5406 | // Do nothing |
5407 | break; |
5408 | |
5409 | case RQ_LValue: |
5410 | if (!isIndirect && !LHS.get()->Classify(Ctx&: Context).isLValue()) { |
5411 | // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq |
5412 | // is (exactly) 'const'. |
5413 | if (Proto->isConst() && !Proto->isVolatile()) |
5414 | Diag(Loc, getLangOpts().CPlusPlus20 |
5415 | ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue |
5416 | : diag::ext_pointer_to_const_ref_member_on_rvalue); |
5417 | else |
5418 | Diag(Loc, diag::err_pointer_to_member_oper_value_classify) |
5419 | << RHSType << 1 << LHS.get()->getSourceRange(); |
5420 | } |
5421 | break; |
5422 | |
5423 | case RQ_RValue: |
5424 | if (isIndirect || !LHS.get()->Classify(Context).isRValue()) |
5425 | Diag(Loc, diag::err_pointer_to_member_oper_value_classify) |
5426 | << RHSType << 0 << LHS.get()->getSourceRange(); |
5427 | break; |
5428 | } |
5429 | } |
5430 | |
5431 | // C++ [expr.mptr.oper]p6: |
5432 | // The result of a .* expression whose second operand is a pointer |
5433 | // to a data member is of the same value category as its |
5434 | // first operand. The result of a .* expression whose second |
5435 | // operand is a pointer to a member function is a prvalue. The |
5436 | // result of an ->* expression is an lvalue if its second operand |
5437 | // is a pointer to data member and a prvalue otherwise. |
5438 | if (Result->isFunctionType()) { |
5439 | VK = VK_PRValue; |
5440 | return Context.BoundMemberTy; |
5441 | } else if (isIndirect) { |
5442 | VK = VK_LValue; |
5443 | } else { |
5444 | VK = LHS.get()->getValueKind(); |
5445 | } |
5446 | |
5447 | return Result; |
5448 | } |
5449 | |
5450 | /// Try to convert a type to another according to C++11 5.16p3. |
5451 | /// |
5452 | /// This is part of the parameter validation for the ? operator. If either |
5453 | /// value operand is a class type, the two operands are attempted to be |
5454 | /// converted to each other. This function does the conversion in one direction. |
5455 | /// It returns true if the program is ill-formed and has already been diagnosed |
5456 | /// as such. |
5457 | static bool TryClassUnification(Sema &Self, Expr *From, Expr *To, |
5458 | SourceLocation QuestionLoc, |
5459 | bool &HaveConversion, |
5460 | QualType &ToType) { |
5461 | HaveConversion = false; |
5462 | ToType = To->getType(); |
5463 | |
5464 | InitializationKind Kind = |
5465 | InitializationKind::CreateCopy(InitLoc: To->getBeginLoc(), EqualLoc: SourceLocation()); |
5466 | // C++11 5.16p3 |
5467 | // The process for determining whether an operand expression E1 of type T1 |
5468 | // can be converted to match an operand expression E2 of type T2 is defined |
5469 | // as follows: |
5470 | // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be |
5471 | // implicitly converted to type "lvalue reference to T2", subject to the |
5472 | // constraint that in the conversion the reference must bind directly to |
5473 | // an lvalue. |
5474 | // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be |
5475 | // implicitly converted to the type "rvalue reference to R2", subject to |
5476 | // the constraint that the reference must bind directly. |
5477 | if (To->isGLValue()) { |
5478 | QualType T = Self.Context.getReferenceQualifiedType(e: To); |
5479 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(Type: T); |
5480 | |
5481 | InitializationSequence InitSeq(Self, Entity, Kind, From); |
5482 | if (InitSeq.isDirectReferenceBinding()) { |
5483 | ToType = T; |
5484 | HaveConversion = true; |
5485 | return false; |
5486 | } |
5487 | |
5488 | if (InitSeq.isAmbiguous()) |
5489 | return InitSeq.Diagnose(S&: Self, Entity, Kind, Args: From); |
5490 | } |
5491 | |
5492 | // -- If E2 is an rvalue, or if the conversion above cannot be done: |
5493 | // -- if E1 and E2 have class type, and the underlying class types are |
5494 | // the same or one is a base class of the other: |
5495 | QualType FTy = From->getType(); |
5496 | QualType TTy = To->getType(); |
5497 | const RecordType *FRec = FTy->getAs<RecordType>(); |
5498 | const RecordType *TRec = TTy->getAs<RecordType>(); |
5499 | bool FDerivedFromT = FRec && TRec && FRec != TRec && |
5500 | Self.IsDerivedFrom(Loc: QuestionLoc, Derived: FTy, Base: TTy); |
5501 | if (FRec && TRec && (FRec == TRec || FDerivedFromT || |
5502 | Self.IsDerivedFrom(Loc: QuestionLoc, Derived: TTy, Base: FTy))) { |
5503 | // E1 can be converted to match E2 if the class of T2 is the |
5504 | // same type as, or a base class of, the class of T1, and |
5505 | // [cv2 > cv1]. |
5506 | if (FRec == TRec || FDerivedFromT) { |
5507 | if (TTy.isAtLeastAsQualifiedAs(other: FTy, Ctx: Self.getASTContext())) { |
5508 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(Type: TTy); |
5509 | InitializationSequence InitSeq(Self, Entity, Kind, From); |
5510 | if (InitSeq) { |
5511 | HaveConversion = true; |
5512 | return false; |
5513 | } |
5514 | |
5515 | if (InitSeq.isAmbiguous()) |
5516 | return InitSeq.Diagnose(S&: Self, Entity, Kind, Args: From); |
5517 | } |
5518 | } |
5519 | |
5520 | return false; |
5521 | } |
5522 | |
5523 | // -- Otherwise: E1 can be converted to match E2 if E1 can be |
5524 | // implicitly converted to the type that expression E2 would have |
5525 | // if E2 were converted to an rvalue (or the type it has, if E2 is |
5526 | // an rvalue). |
5527 | // |
5528 | // This actually refers very narrowly to the lvalue-to-rvalue conversion, not |
5529 | // to the array-to-pointer or function-to-pointer conversions. |
5530 | TTy = TTy.getNonLValueExprType(Context: Self.Context); |
5531 | |
5532 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(Type: TTy); |
5533 | InitializationSequence InitSeq(Self, Entity, Kind, From); |
5534 | HaveConversion = !InitSeq.Failed(); |
5535 | ToType = TTy; |
5536 | if (InitSeq.isAmbiguous()) |
5537 | return InitSeq.Diagnose(S&: Self, Entity, Kind, Args: From); |
5538 | |
5539 | return false; |
5540 | } |
5541 | |
5542 | /// Try to find a common type for two according to C++0x 5.16p5. |
5543 | /// |
5544 | /// This is part of the parameter validation for the ? operator. If either |
5545 | /// value operand is a class type, overload resolution is used to find a |
5546 | /// conversion to a common type. |
5547 | static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS, |
5548 | SourceLocation QuestionLoc) { |
5549 | Expr *Args[2] = { LHS.get(), RHS.get() }; |
5550 | OverloadCandidateSet CandidateSet(QuestionLoc, |
5551 | OverloadCandidateSet::CSK_Operator); |
5552 | Self.AddBuiltinOperatorCandidates(Op: OO_Conditional, OpLoc: QuestionLoc, Args, |
5553 | CandidateSet); |
5554 | |
5555 | OverloadCandidateSet::iterator Best; |
5556 | switch (CandidateSet.BestViableFunction(S&: Self, Loc: QuestionLoc, Best)) { |
5557 | case OR_Success: { |
5558 | // We found a match. Perform the conversions on the arguments and move on. |
5559 | ExprResult LHSRes = Self.PerformImplicitConversion( |
5560 | LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0], |
5561 | AssignmentAction::Converting); |
5562 | if (LHSRes.isInvalid()) |
5563 | break; |
5564 | LHS = LHSRes; |
5565 | |
5566 | ExprResult RHSRes = Self.PerformImplicitConversion( |
5567 | RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1], |
5568 | AssignmentAction::Converting); |
5569 | if (RHSRes.isInvalid()) |
5570 | break; |
5571 | RHS = RHSRes; |
5572 | if (Best->Function) |
5573 | Self.MarkFunctionReferenced(Loc: QuestionLoc, Func: Best->Function); |
5574 | return false; |
5575 | } |
5576 | |
5577 | case OR_No_Viable_Function: |
5578 | |
5579 | // Emit a better diagnostic if one of the expressions is a null pointer |
5580 | // constant and the other is a pointer type. In this case, the user most |
5581 | // likely forgot to take the address of the other expression. |
5582 | if (Self.DiagnoseConditionalForNull(LHSExpr: LHS.get(), RHSExpr: RHS.get(), QuestionLoc)) |
5583 | return true; |
5584 | |
5585 | Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) |
5586 | << LHS.get()->getType() << RHS.get()->getType() |
5587 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
5588 | return true; |
5589 | |
5590 | case OR_Ambiguous: |
5591 | Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl) |
5592 | << LHS.get()->getType() << RHS.get()->getType() |
5593 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
5594 | // FIXME: Print the possible common types by printing the return types of |
5595 | // the viable candidates. |
5596 | break; |
5597 | |
5598 | case OR_Deleted: |
5599 | llvm_unreachable("Conditional operator has only built-in overloads"); |
5600 | } |
5601 | return true; |
5602 | } |
5603 | |
5604 | /// Perform an "extended" implicit conversion as returned by |
5605 | /// TryClassUnification. |
5606 | static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) { |
5607 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(Type: T); |
5608 | InitializationKind Kind = |
5609 | InitializationKind::CreateCopy(InitLoc: E.get()->getBeginLoc(), EqualLoc: SourceLocation()); |
5610 | Expr *Arg = E.get(); |
5611 | InitializationSequence InitSeq(Self, Entity, Kind, Arg); |
5612 | ExprResult Result = InitSeq.Perform(S&: Self, Entity, Kind, Args: Arg); |
5613 | if (Result.isInvalid()) |
5614 | return true; |
5615 | |
5616 | E = Result; |
5617 | return false; |
5618 | } |
5619 | |
5620 | // Check the condition operand of ?: to see if it is valid for the GCC |
5621 | // extension. |
5622 | static bool isValidVectorForConditionalCondition(ASTContext &Ctx, |
5623 | QualType CondTy) { |
5624 | if (!CondTy->isVectorType() && !CondTy->isExtVectorType()) |
5625 | return false; |
5626 | const QualType EltTy = |
5627 | cast<VectorType>(Val: CondTy.getCanonicalType())->getElementType(); |
5628 | assert(!EltTy->isEnumeralType() && "Vectors cant be enum types"); |
5629 | return EltTy->isIntegralType(Ctx); |
5630 | } |
5631 | |
5632 | static bool isValidSizelessVectorForConditionalCondition(ASTContext &Ctx, |
5633 | QualType CondTy) { |
5634 | if (!CondTy->isSveVLSBuiltinType()) |
5635 | return false; |
5636 | const QualType EltTy = |
5637 | cast<BuiltinType>(Val: CondTy.getCanonicalType())->getSveEltType(Ctx); |
5638 | assert(!EltTy->isEnumeralType() && "Vectors cant be enum types"); |
5639 | return EltTy->isIntegralType(Ctx); |
5640 | } |
5641 | |
5642 | QualType Sema::CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, |
5643 | ExprResult &RHS, |
5644 | SourceLocation QuestionLoc) { |
5645 | LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get()); |
5646 | RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get()); |
5647 | |
5648 | QualType CondType = Cond.get()->getType(); |
5649 | const auto *CondVT = CondType->castAs<VectorType>(); |
5650 | QualType CondElementTy = CondVT->getElementType(); |
5651 | unsigned CondElementCount = CondVT->getNumElements(); |
5652 | QualType LHSType = LHS.get()->getType(); |
5653 | const auto *LHSVT = LHSType->getAs<VectorType>(); |
5654 | QualType RHSType = RHS.get()->getType(); |
5655 | const auto *RHSVT = RHSType->getAs<VectorType>(); |
5656 | |
5657 | QualType ResultType; |
5658 | |
5659 | |
5660 | if (LHSVT && RHSVT) { |
5661 | if (isa<ExtVectorType>(Val: CondVT) != isa<ExtVectorType>(Val: LHSVT)) { |
5662 | Diag(QuestionLoc, diag::err_conditional_vector_cond_result_mismatch) |
5663 | << /*isExtVector*/ isa<ExtVectorType>(CondVT); |
5664 | return {}; |
5665 | } |
5666 | |
5667 | // If both are vector types, they must be the same type. |
5668 | if (!Context.hasSameType(T1: LHSType, T2: RHSType)) { |
5669 | Diag(QuestionLoc, diag::err_conditional_vector_mismatched) |
5670 | << LHSType << RHSType; |
5671 | return {}; |
5672 | } |
5673 | ResultType = Context.getCommonSugaredType(X: LHSType, Y: RHSType); |
5674 | } else if (LHSVT || RHSVT) { |
5675 | ResultType = CheckVectorOperands( |
5676 | LHS, RHS, Loc: QuestionLoc, /*isCompAssign*/ IsCompAssign: false, /*AllowBothBool*/ true, |
5677 | /*AllowBoolConversions*/ AllowBoolConversion: false, |
5678 | /*AllowBoolOperation*/ true, |
5679 | /*ReportInvalid*/ true); |
5680 | if (ResultType.isNull()) |
5681 | return {}; |
5682 | } else { |
5683 | // Both are scalar. |
5684 | LHSType = LHSType.getUnqualifiedType(); |
5685 | RHSType = RHSType.getUnqualifiedType(); |
5686 | QualType ResultElementTy = |
5687 | Context.hasSameType(T1: LHSType, T2: RHSType) |
5688 | ? Context.getCommonSugaredType(X: LHSType, Y: RHSType) |
5689 | : UsualArithmeticConversions(LHS, RHS, Loc: QuestionLoc, |
5690 | ACK: ArithConvKind::Conditional); |
5691 | |
5692 | if (ResultElementTy->isEnumeralType()) { |
5693 | Diag(QuestionLoc, diag::err_conditional_vector_operand_type) |
5694 | << ResultElementTy; |
5695 | return {}; |
5696 | } |
5697 | if (CondType->isExtVectorType()) |
5698 | ResultType = |
5699 | Context.getExtVectorType(VectorType: ResultElementTy, NumElts: CondVT->getNumElements()); |
5700 | else |
5701 | ResultType = Context.getVectorType( |
5702 | VectorType: ResultElementTy, NumElts: CondVT->getNumElements(), VecKind: VectorKind::Generic); |
5703 | |
5704 | LHS = ImpCastExprToType(E: LHS.get(), Type: ResultType, CK: CK_VectorSplat); |
5705 | RHS = ImpCastExprToType(E: RHS.get(), Type: ResultType, CK: CK_VectorSplat); |
5706 | } |
5707 | |
5708 | assert(!ResultType.isNull() && ResultType->isVectorType() && |
5709 | (!CondType->isExtVectorType() || ResultType->isExtVectorType()) && |
5710 | "Result should have been a vector type"); |
5711 | auto *ResultVectorTy = ResultType->castAs<VectorType>(); |
5712 | QualType ResultElementTy = ResultVectorTy->getElementType(); |
5713 | unsigned ResultElementCount = ResultVectorTy->getNumElements(); |
5714 | |
5715 | if (ResultElementCount != CondElementCount) { |
5716 | Diag(QuestionLoc, diag::err_conditional_vector_size) << CondType |
5717 | << ResultType; |
5718 | return {}; |
5719 | } |
5720 | |
5721 | if (Context.getTypeSize(T: ResultElementTy) != |
5722 | Context.getTypeSize(T: CondElementTy)) { |
5723 | Diag(QuestionLoc, diag::err_conditional_vector_element_size) << CondType |
5724 | << ResultType; |
5725 | return {}; |
5726 | } |
5727 | |
5728 | return ResultType; |
5729 | } |
5730 | |
5731 | QualType Sema::CheckSizelessVectorConditionalTypes(ExprResult &Cond, |
5732 | ExprResult &LHS, |
5733 | ExprResult &RHS, |
5734 | SourceLocation QuestionLoc) { |
5735 | LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get()); |
5736 | RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get()); |
5737 | |
5738 | QualType CondType = Cond.get()->getType(); |
5739 | const auto *CondBT = CondType->castAs<BuiltinType>(); |
5740 | QualType CondElementTy = CondBT->getSveEltType(Context); |
5741 | llvm::ElementCount CondElementCount = |
5742 | Context.getBuiltinVectorTypeInfo(VecTy: CondBT).EC; |
5743 | |
5744 | QualType LHSType = LHS.get()->getType(); |
5745 | const auto *LHSBT = |
5746 | LHSType->isSveVLSBuiltinType() ? LHSType->getAs<BuiltinType>() : nullptr; |
5747 | QualType RHSType = RHS.get()->getType(); |
5748 | const auto *RHSBT = |
5749 | RHSType->isSveVLSBuiltinType() ? RHSType->getAs<BuiltinType>() : nullptr; |
5750 | |
5751 | QualType ResultType; |
5752 | |
5753 | if (LHSBT && RHSBT) { |
5754 | // If both are sizeless vector types, they must be the same type. |
5755 | if (!Context.hasSameType(T1: LHSType, T2: RHSType)) { |
5756 | Diag(QuestionLoc, diag::err_conditional_vector_mismatched) |
5757 | << LHSType << RHSType; |
5758 | return QualType(); |
5759 | } |
5760 | ResultType = LHSType; |
5761 | } else if (LHSBT || RHSBT) { |
5762 | ResultType = CheckSizelessVectorOperands(LHS, RHS, Loc: QuestionLoc, |
5763 | /*IsCompAssign*/ false, |
5764 | OperationKind: ArithConvKind::Conditional); |
5765 | if (ResultType.isNull()) |
5766 | return QualType(); |
5767 | } else { |
5768 | // Both are scalar so splat |
5769 | QualType ResultElementTy; |
5770 | LHSType = LHSType.getCanonicalType().getUnqualifiedType(); |
5771 | RHSType = RHSType.getCanonicalType().getUnqualifiedType(); |
5772 | |
5773 | if (Context.hasSameType(T1: LHSType, T2: RHSType)) |
5774 | ResultElementTy = LHSType; |
5775 | else |
5776 | ResultElementTy = UsualArithmeticConversions(LHS, RHS, Loc: QuestionLoc, |
5777 | ACK: ArithConvKind::Conditional); |
5778 | |
5779 | if (ResultElementTy->isEnumeralType()) { |
5780 | Diag(QuestionLoc, diag::err_conditional_vector_operand_type) |
5781 | << ResultElementTy; |
5782 | return QualType(); |
5783 | } |
5784 | |
5785 | ResultType = Context.getScalableVectorType( |
5786 | EltTy: ResultElementTy, NumElts: CondElementCount.getKnownMinValue()); |
5787 | |
5788 | LHS = ImpCastExprToType(E: LHS.get(), Type: ResultType, CK: CK_VectorSplat); |
5789 | RHS = ImpCastExprToType(E: RHS.get(), Type: ResultType, CK: CK_VectorSplat); |
5790 | } |
5791 | |
5792 | assert(!ResultType.isNull() && ResultType->isSveVLSBuiltinType() && |
5793 | "Result should have been a vector type"); |
5794 | auto *ResultBuiltinTy = ResultType->castAs<BuiltinType>(); |
5795 | QualType ResultElementTy = ResultBuiltinTy->getSveEltType(Context); |
5796 | llvm::ElementCount ResultElementCount = |
5797 | Context.getBuiltinVectorTypeInfo(VecTy: ResultBuiltinTy).EC; |
5798 | |
5799 | if (ResultElementCount != CondElementCount) { |
5800 | Diag(QuestionLoc, diag::err_conditional_vector_size) |
5801 | << CondType << ResultType; |
5802 | return QualType(); |
5803 | } |
5804 | |
5805 | if (Context.getTypeSize(T: ResultElementTy) != |
5806 | Context.getTypeSize(T: CondElementTy)) { |
5807 | Diag(QuestionLoc, diag::err_conditional_vector_element_size) |
5808 | << CondType << ResultType; |
5809 | return QualType(); |
5810 | } |
5811 | |
5812 | return ResultType; |
5813 | } |
5814 | |
5815 | QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, |
5816 | ExprResult &RHS, ExprValueKind &VK, |
5817 | ExprObjectKind &OK, |
5818 | SourceLocation QuestionLoc) { |
5819 | // FIXME: Handle C99's complex types, block pointers and Obj-C++ interface |
5820 | // pointers. |
5821 | |
5822 | // Assume r-value. |
5823 | VK = VK_PRValue; |
5824 | OK = OK_Ordinary; |
5825 | bool IsVectorConditional = |
5826 | isValidVectorForConditionalCondition(Ctx&: Context, CondTy: Cond.get()->getType()); |
5827 | |
5828 | bool IsSizelessVectorConditional = |
5829 | isValidSizelessVectorForConditionalCondition(Ctx&: Context, |
5830 | CondTy: Cond.get()->getType()); |
5831 | |
5832 | // C++11 [expr.cond]p1 |
5833 | // The first expression is contextually converted to bool. |
5834 | if (!Cond.get()->isTypeDependent()) { |
5835 | ExprResult CondRes = IsVectorConditional || IsSizelessVectorConditional |
5836 | ? DefaultFunctionArrayLvalueConversion(E: Cond.get()) |
5837 | : CheckCXXBooleanCondition(CondExpr: Cond.get()); |
5838 | if (CondRes.isInvalid()) |
5839 | return QualType(); |
5840 | Cond = CondRes; |
5841 | } else { |
5842 | // To implement C++, the first expression typically doesn't alter the result |
5843 | // type of the conditional, however the GCC compatible vector extension |
5844 | // changes the result type to be that of the conditional. Since we cannot |
5845 | // know if this is a vector extension here, delay the conversion of the |
5846 | // LHS/RHS below until later. |
5847 | return Context.DependentTy; |
5848 | } |
5849 | |
5850 | |
5851 | // Either of the arguments dependent? |
5852 | if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent()) |
5853 | return Context.DependentTy; |
5854 | |
5855 | // C++11 [expr.cond]p2 |
5856 | // If either the second or the third operand has type (cv) void, ... |
5857 | QualType LTy = LHS.get()->getType(); |
5858 | QualType RTy = RHS.get()->getType(); |
5859 | bool LVoid = LTy->isVoidType(); |
5860 | bool RVoid = RTy->isVoidType(); |
5861 | if (LVoid || RVoid) { |
5862 | // ... one of the following shall hold: |
5863 | // -- The second or the third operand (but not both) is a (possibly |
5864 | // parenthesized) throw-expression; the result is of the type |
5865 | // and value category of the other. |
5866 | bool LThrow = isa<CXXThrowExpr>(Val: LHS.get()->IgnoreParenImpCasts()); |
5867 | bool RThrow = isa<CXXThrowExpr>(Val: RHS.get()->IgnoreParenImpCasts()); |
5868 | |
5869 | // Void expressions aren't legal in the vector-conditional expressions. |
5870 | if (IsVectorConditional) { |
5871 | SourceRange DiagLoc = |
5872 | LVoid ? LHS.get()->getSourceRange() : RHS.get()->getSourceRange(); |
5873 | bool IsThrow = LVoid ? LThrow : RThrow; |
5874 | Diag(DiagLoc.getBegin(), diag::err_conditional_vector_has_void) |
5875 | << DiagLoc << IsThrow; |
5876 | return QualType(); |
5877 | } |
5878 | |
5879 | if (LThrow != RThrow) { |
5880 | Expr *NonThrow = LThrow ? RHS.get() : LHS.get(); |
5881 | VK = NonThrow->getValueKind(); |
5882 | // DR (no number yet): the result is a bit-field if the |
5883 | // non-throw-expression operand is a bit-field. |
5884 | OK = NonThrow->getObjectKind(); |
5885 | return NonThrow->getType(); |
5886 | } |
5887 | |
5888 | // -- Both the second and third operands have type void; the result is of |
5889 | // type void and is a prvalue. |
5890 | if (LVoid && RVoid) |
5891 | return Context.getCommonSugaredType(X: LTy, Y: RTy); |
5892 | |
5893 | // Neither holds, error. |
5894 | Diag(QuestionLoc, diag::err_conditional_void_nonvoid) |
5895 | << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1) |
5896 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
5897 | return QualType(); |
5898 | } |
5899 | |
5900 | // Neither is void. |
5901 | if (IsVectorConditional) |
5902 | return CheckVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc); |
5903 | |
5904 | if (IsSizelessVectorConditional) |
5905 | return CheckSizelessVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc); |
5906 | |
5907 | // WebAssembly tables are not allowed as conditional LHS or RHS. |
5908 | if (LTy->isWebAssemblyTableType() || RTy->isWebAssemblyTableType()) { |
5909 | Diag(QuestionLoc, diag::err_wasm_table_conditional_expression) |
5910 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
5911 | return QualType(); |
5912 | } |
5913 | |
5914 | // C++11 [expr.cond]p3 |
5915 | // Otherwise, if the second and third operand have different types, and |
5916 | // either has (cv) class type [...] an attempt is made to convert each of |
5917 | // those operands to the type of the other. |
5918 | if (!Context.hasSameType(T1: LTy, T2: RTy) && |
5919 | (LTy->isRecordType() || RTy->isRecordType())) { |
5920 | // These return true if a single direction is already ambiguous. |
5921 | QualType L2RType, R2LType; |
5922 | bool HaveL2R, HaveR2L; |
5923 | if (TryClassUnification(Self&: *this, From: LHS.get(), To: RHS.get(), QuestionLoc, HaveConversion&: HaveL2R, ToType&: L2RType)) |
5924 | return QualType(); |
5925 | if (TryClassUnification(Self&: *this, From: RHS.get(), To: LHS.get(), QuestionLoc, HaveConversion&: HaveR2L, ToType&: R2LType)) |
5926 | return QualType(); |
5927 | |
5928 | // If both can be converted, [...] the program is ill-formed. |
5929 | if (HaveL2R && HaveR2L) { |
5930 | Diag(QuestionLoc, diag::err_conditional_ambiguous) |
5931 | << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
5932 | return QualType(); |
5933 | } |
5934 | |
5935 | // If exactly one conversion is possible, that conversion is applied to |
5936 | // the chosen operand and the converted operands are used in place of the |
5937 | // original operands for the remainder of this section. |
5938 | if (HaveL2R) { |
5939 | if (ConvertForConditional(Self&: *this, E&: LHS, T: L2RType) || LHS.isInvalid()) |
5940 | return QualType(); |
5941 | LTy = LHS.get()->getType(); |
5942 | } else if (HaveR2L) { |
5943 | if (ConvertForConditional(Self&: *this, E&: RHS, T: R2LType) || RHS.isInvalid()) |
5944 | return QualType(); |
5945 | RTy = RHS.get()->getType(); |
5946 | } |
5947 | } |
5948 | |
5949 | // C++11 [expr.cond]p3 |
5950 | // if both are glvalues of the same value category and the same type except |
5951 | // for cv-qualification, an attempt is made to convert each of those |
5952 | // operands to the type of the other. |
5953 | // FIXME: |
5954 | // Resolving a defect in P0012R1: we extend this to cover all cases where |
5955 | // one of the operands is reference-compatible with the other, in order |
5956 | // to support conditionals between functions differing in noexcept. This |
5957 | // will similarly cover difference in array bounds after P0388R4. |
5958 | // FIXME: If LTy and RTy have a composite pointer type, should we convert to |
5959 | // that instead? |
5960 | ExprValueKind LVK = LHS.get()->getValueKind(); |
5961 | ExprValueKind RVK = RHS.get()->getValueKind(); |
5962 | if (!Context.hasSameType(T1: LTy, T2: RTy) && LVK == RVK && LVK != VK_PRValue) { |
5963 | // DerivedToBase was already handled by the class-specific case above. |
5964 | // FIXME: Should we allow ObjC conversions here? |
5965 | const ReferenceConversions AllowedConversions = |
5966 | ReferenceConversions::Qualification | |
5967 | ReferenceConversions::NestedQualification | |
5968 | ReferenceConversions::Function; |
5969 | |
5970 | ReferenceConversions RefConv; |
5971 | if (CompareReferenceRelationship(Loc: QuestionLoc, T1: LTy, T2: RTy, Conv: &RefConv) == |
5972 | Ref_Compatible && |
5973 | !(RefConv & ~AllowedConversions) && |
5974 | // [...] subject to the constraint that the reference must bind |
5975 | // directly [...] |
5976 | !RHS.get()->refersToBitField() && !RHS.get()->refersToVectorElement()) { |
5977 | RHS = ImpCastExprToType(E: RHS.get(), Type: LTy, CK: CK_NoOp, VK: RVK); |
5978 | RTy = RHS.get()->getType(); |
5979 | } else if (CompareReferenceRelationship(Loc: QuestionLoc, T1: RTy, T2: LTy, Conv: &RefConv) == |
5980 | Ref_Compatible && |
5981 | !(RefConv & ~AllowedConversions) && |
5982 | !LHS.get()->refersToBitField() && |
5983 | !LHS.get()->refersToVectorElement()) { |
5984 | LHS = ImpCastExprToType(E: LHS.get(), Type: RTy, CK: CK_NoOp, VK: LVK); |
5985 | LTy = LHS.get()->getType(); |
5986 | } |
5987 | } |
5988 | |
5989 | // C++11 [expr.cond]p4 |
5990 | // If the second and third operands are glvalues of the same value |
5991 | // category and have the same type, the result is of that type and |
5992 | // value category and it is a bit-field if the second or the third |
5993 | // operand is a bit-field, or if both are bit-fields. |
5994 | // We only extend this to bitfields, not to the crazy other kinds of |
5995 | // l-values. |
5996 | bool Same = Context.hasSameType(T1: LTy, T2: RTy); |
5997 | if (Same && LVK == RVK && LVK != VK_PRValue && |
5998 | LHS.get()->isOrdinaryOrBitFieldObject() && |
5999 | RHS.get()->isOrdinaryOrBitFieldObject()) { |
6000 | VK = LHS.get()->getValueKind(); |
6001 | if (LHS.get()->getObjectKind() == OK_BitField || |
6002 | RHS.get()->getObjectKind() == OK_BitField) |
6003 | OK = OK_BitField; |
6004 | return Context.getCommonSugaredType(X: LTy, Y: RTy); |
6005 | } |
6006 | |
6007 | // C++11 [expr.cond]p5 |
6008 | // Otherwise, the result is a prvalue. If the second and third operands |
6009 | // do not have the same type, and either has (cv) class type, ... |
6010 | if (!Same && (LTy->isRecordType() || RTy->isRecordType())) { |
6011 | // ... overload resolution is used to determine the conversions (if any) |
6012 | // to be applied to the operands. If the overload resolution fails, the |
6013 | // program is ill-formed. |
6014 | if (FindConditionalOverload(Self&: *this, LHS, RHS, QuestionLoc)) |
6015 | return QualType(); |
6016 | } |
6017 | |
6018 | // C++11 [expr.cond]p6 |
6019 | // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard |
6020 | // conversions are performed on the second and third operands. |
6021 | LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get()); |
6022 | RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get()); |
6023 | if (LHS.isInvalid() || RHS.isInvalid()) |
6024 | return QualType(); |
6025 | LTy = LHS.get()->getType(); |
6026 | RTy = RHS.get()->getType(); |
6027 | |
6028 | // After those conversions, one of the following shall hold: |
6029 | // -- The second and third operands have the same type; the result |
6030 | // is of that type. If the operands have class type, the result |
6031 | // is a prvalue temporary of the result type, which is |
6032 | // copy-initialized from either the second operand or the third |
6033 | // operand depending on the value of the first operand. |
6034 | if (Context.hasSameType(T1: LTy, T2: RTy)) { |
6035 | if (LTy->isRecordType()) { |
6036 | // The operands have class type. Make a temporary copy. |
6037 | ExprResult LHSCopy = PerformCopyInitialization( |
6038 | Entity: InitializedEntity::InitializeTemporary(Type: LTy), EqualLoc: SourceLocation(), Init: LHS); |
6039 | if (LHSCopy.isInvalid()) |
6040 | return QualType(); |
6041 | |
6042 | ExprResult RHSCopy = PerformCopyInitialization( |
6043 | Entity: InitializedEntity::InitializeTemporary(Type: RTy), EqualLoc: SourceLocation(), Init: RHS); |
6044 | if (RHSCopy.isInvalid()) |
6045 | return QualType(); |
6046 | |
6047 | LHS = LHSCopy; |
6048 | RHS = RHSCopy; |
6049 | } |
6050 | return Context.getCommonSugaredType(X: LTy, Y: RTy); |
6051 | } |
6052 | |
6053 | // Extension: conditional operator involving vector types. |
6054 | if (LTy->isVectorType() || RTy->isVectorType()) |
6055 | return CheckVectorOperands(LHS, RHS, Loc: QuestionLoc, /*isCompAssign*/ IsCompAssign: false, |
6056 | /*AllowBothBool*/ true, |
6057 | /*AllowBoolConversions*/ AllowBoolConversion: false, |
6058 | /*AllowBoolOperation*/ false, |
6059 | /*ReportInvalid*/ true); |
6060 | |
6061 | // -- The second and third operands have arithmetic or enumeration type; |
6062 | // the usual arithmetic conversions are performed to bring them to a |
6063 | // common type, and the result is of that type. |
6064 | if (LTy->isArithmeticType() && RTy->isArithmeticType()) { |
6065 | QualType ResTy = UsualArithmeticConversions(LHS, RHS, Loc: QuestionLoc, |
6066 | ACK: ArithConvKind::Conditional); |
6067 | if (LHS.isInvalid() || RHS.isInvalid()) |
6068 | return QualType(); |
6069 | if (ResTy.isNull()) { |
6070 | Diag(QuestionLoc, |
6071 | diag::err_typecheck_cond_incompatible_operands) << LTy << RTy |
6072 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
6073 | return QualType(); |
6074 | } |
6075 | |
6076 | LHS = ImpCastExprToType(E: LHS.get(), Type: ResTy, CK: PrepareScalarCast(src&: LHS, destType: ResTy)); |
6077 | RHS = ImpCastExprToType(E: RHS.get(), Type: ResTy, CK: PrepareScalarCast(src&: RHS, destType: ResTy)); |
6078 | |
6079 | return ResTy; |
6080 | } |
6081 | |
6082 | // -- The second and third operands have pointer type, or one has pointer |
6083 | // type and the other is a null pointer constant, or both are null |
6084 | // pointer constants, at least one of which is non-integral; pointer |
6085 | // conversions and qualification conversions are performed to bring them |
6086 | // to their composite pointer type. The result is of the composite |
6087 | // pointer type. |
6088 | // -- The second and third operands have pointer to member type, or one has |
6089 | // pointer to member type and the other is a null pointer constant; |
6090 | // pointer to member conversions and qualification conversions are |
6091 | // performed to bring them to a common type, whose cv-qualification |
6092 | // shall match the cv-qualification of either the second or the third |
6093 | // operand. The result is of the common type. |
6094 | QualType Composite = FindCompositePointerType(Loc: QuestionLoc, E1&: LHS, E2&: RHS); |
6095 | if (!Composite.isNull()) |
6096 | return Composite; |
6097 | |
6098 | // Similarly, attempt to find composite type of two objective-c pointers. |
6099 | Composite = ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc); |
6100 | if (LHS.isInvalid() || RHS.isInvalid()) |
6101 | return QualType(); |
6102 | if (!Composite.isNull()) |
6103 | return Composite; |
6104 | |
6105 | // Check if we are using a null with a non-pointer type. |
6106 | if (DiagnoseConditionalForNull(LHSExpr: LHS.get(), RHSExpr: RHS.get(), QuestionLoc)) |
6107 | return QualType(); |
6108 | |
6109 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) |
6110 | << LHS.get()->getType() << RHS.get()->getType() |
6111 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
6112 | return QualType(); |
6113 | } |
6114 | |
6115 | QualType Sema::FindCompositePointerType(SourceLocation Loc, |
6116 | Expr *&E1, Expr *&E2, |
6117 | bool ConvertArgs) { |
6118 | assert(getLangOpts().CPlusPlus && "This function assumes C++"); |
6119 | |
6120 | // C++1z [expr]p14: |
6121 | // The composite pointer type of two operands p1 and p2 having types T1 |
6122 | // and T2 |
6123 | QualType T1 = E1->getType(), T2 = E2->getType(); |
6124 | |
6125 | // where at least one is a pointer or pointer to member type or |
6126 | // std::nullptr_t is: |
6127 | bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() || |
6128 | T1->isNullPtrType(); |
6129 | bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() || |
6130 | T2->isNullPtrType(); |
6131 | if (!T1IsPointerLike && !T2IsPointerLike) |
6132 | return QualType(); |
6133 | |
6134 | // - if both p1 and p2 are null pointer constants, std::nullptr_t; |
6135 | // This can't actually happen, following the standard, but we also use this |
6136 | // to implement the end of [expr.conv], which hits this case. |
6137 | // |
6138 | // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively; |
6139 | if (T1IsPointerLike && |
6140 | E2->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull)) { |
6141 | if (ConvertArgs) |
6142 | E2 = ImpCastExprToType(E: E2, Type: T1, CK: T1->isMemberPointerType() |
6143 | ? CK_NullToMemberPointer |
6144 | : CK_NullToPointer).get(); |
6145 | return T1; |
6146 | } |
6147 | if (T2IsPointerLike && |
6148 | E1->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull)) { |
6149 | if (ConvertArgs) |
6150 | E1 = ImpCastExprToType(E: E1, Type: T2, CK: T2->isMemberPointerType() |
6151 | ? CK_NullToMemberPointer |
6152 | : CK_NullToPointer).get(); |
6153 | return T2; |
6154 | } |
6155 | |
6156 | // Now both have to be pointers or member pointers. |
6157 | if (!T1IsPointerLike || !T2IsPointerLike) |
6158 | return QualType(); |
6159 | assert(!T1->isNullPtrType() && !T2->isNullPtrType() && |
6160 | "nullptr_t should be a null pointer constant"); |
6161 | |
6162 | struct Step { |
6163 | enum Kind { Pointer, ObjCPointer, MemberPointer, Array } K; |
6164 | // Qualifiers to apply under the step kind. |
6165 | Qualifiers Quals; |
6166 | /// The class for a pointer-to-member; a constant array type with a bound |
6167 | /// (if any) for an array. |
6168 | /// FIXME: Store Qualifier for pointer-to-member. |
6169 | const Type *ClassOrBound; |
6170 | |
6171 | Step(Kind K, const Type *ClassOrBound = nullptr) |
6172 | : K(K), ClassOrBound(ClassOrBound) {} |
6173 | QualType rebuild(ASTContext &Ctx, QualType T) const { |
6174 | T = Ctx.getQualifiedType(T, Qs: Quals); |
6175 | switch (K) { |
6176 | case Pointer: |
6177 | return Ctx.getPointerType(T); |
6178 | case MemberPointer: |
6179 | return Ctx.getMemberPointerType(T, /*Qualifier=*/nullptr, |
6180 | Cls: ClassOrBound->getAsCXXRecordDecl()); |
6181 | case ObjCPointer: |
6182 | return Ctx.getObjCObjectPointerType(OIT: T); |
6183 | case Array: |
6184 | if (auto *CAT = cast_or_null<ConstantArrayType>(Val: ClassOrBound)) |
6185 | return Ctx.getConstantArrayType(EltTy: T, ArySize: CAT->getSize(), SizeExpr: nullptr, |
6186 | ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0); |
6187 | else |
6188 | return Ctx.getIncompleteArrayType(EltTy: T, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0); |
6189 | } |
6190 | llvm_unreachable("unknown step kind"); |
6191 | } |
6192 | }; |
6193 | |
6194 | SmallVector<Step, 8> Steps; |
6195 | |
6196 | // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1 |
6197 | // is reference-related to C2 or C2 is reference-related to C1 (8.6.3), |
6198 | // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1, |
6199 | // respectively; |
6200 | // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer |
6201 | // to member of C2 of type cv2 U2" for some non-function type U, where |
6202 | // C1 is reference-related to C2 or C2 is reference-related to C1, the |
6203 | // cv-combined type of T2 and T1 or the cv-combined type of T1 and T2, |
6204 | // respectively; |
6205 | // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and |
6206 | // T2; |
6207 | // |
6208 | // Dismantle T1 and T2 to simultaneously determine whether they are similar |
6209 | // and to prepare to form the cv-combined type if so. |
6210 | QualType Composite1 = T1; |
6211 | QualType Composite2 = T2; |
6212 | unsigned NeedConstBefore = 0; |
6213 | while (true) { |
6214 | assert(!Composite1.isNull() && !Composite2.isNull()); |
6215 | |
6216 | Qualifiers Q1, Q2; |
6217 | Composite1 = Context.getUnqualifiedArrayType(T: Composite1, Quals&: Q1); |
6218 | Composite2 = Context.getUnqualifiedArrayType(T: Composite2, Quals&: Q2); |
6219 | |
6220 | // Top-level qualifiers are ignored. Merge at all lower levels. |
6221 | if (!Steps.empty()) { |
6222 | // Find the qualifier union: (approximately) the unique minimal set of |
6223 | // qualifiers that is compatible with both types. |
6224 | Qualifiers Quals = Qualifiers::fromCVRUMask(CVRU: Q1.getCVRUQualifiers() | |
6225 | Q2.getCVRUQualifiers()); |
6226 | |
6227 | // Under one level of pointer or pointer-to-member, we can change to an |
6228 | // unambiguous compatible address space. |
6229 | if (Q1.getAddressSpace() == Q2.getAddressSpace()) { |
6230 | Quals.setAddressSpace(Q1.getAddressSpace()); |
6231 | } else if (Steps.size() == 1) { |
6232 | bool MaybeQ1 = Q1.isAddressSpaceSupersetOf(other: Q2, Ctx: getASTContext()); |
6233 | bool MaybeQ2 = Q2.isAddressSpaceSupersetOf(other: Q1, Ctx: getASTContext()); |
6234 | if (MaybeQ1 == MaybeQ2) { |
6235 | // Exception for ptr size address spaces. Should be able to choose |
6236 | // either address space during comparison. |
6237 | if (isPtrSizeAddressSpace(AS: Q1.getAddressSpace()) || |
6238 | isPtrSizeAddressSpace(AS: Q2.getAddressSpace())) |
6239 | MaybeQ1 = true; |
6240 | else |
6241 | return QualType(); // No unique best address space. |
6242 | } |
6243 | Quals.setAddressSpace(MaybeQ1 ? Q1.getAddressSpace() |
6244 | : Q2.getAddressSpace()); |
6245 | } else { |
6246 | return QualType(); |
6247 | } |
6248 | |
6249 | // FIXME: In C, we merge __strong and none to __strong at the top level. |
6250 | if (Q1.getObjCGCAttr() == Q2.getObjCGCAttr()) |
6251 | Quals.setObjCGCAttr(Q1.getObjCGCAttr()); |
6252 | else if (T1->isVoidPointerType() || T2->isVoidPointerType()) |
6253 | assert(Steps.size() == 1); |
6254 | else |
6255 | return QualType(); |
6256 | |
6257 | // Mismatched lifetime qualifiers never compatibly include each other. |
6258 | if (Q1.getObjCLifetime() == Q2.getObjCLifetime()) |
6259 | Quals.setObjCLifetime(Q1.getObjCLifetime()); |
6260 | else if (T1->isVoidPointerType() || T2->isVoidPointerType()) |
6261 | assert(Steps.size() == 1); |
6262 | else |
6263 | return QualType(); |
6264 | |
6265 | if (Q1.getPointerAuth().isEquivalent(Other: Q2.getPointerAuth())) |
6266 | Quals.setPointerAuth(Q1.getPointerAuth()); |
6267 | else |
6268 | return QualType(); |
6269 | |
6270 | Steps.back().Quals = Quals; |
6271 | if (Q1 != Quals || Q2 != Quals) |
6272 | NeedConstBefore = Steps.size() - 1; |
6273 | } |
6274 | |
6275 | // FIXME: Can we unify the following with UnwrapSimilarTypes? |
6276 | |
6277 | const ArrayType *Arr1, *Arr2; |
6278 | if ((Arr1 = Context.getAsArrayType(T: Composite1)) && |
6279 | (Arr2 = Context.getAsArrayType(T: Composite2))) { |
6280 | auto *CAT1 = dyn_cast<ConstantArrayType>(Val: Arr1); |
6281 | auto *CAT2 = dyn_cast<ConstantArrayType>(Val: Arr2); |
6282 | if (CAT1 && CAT2 && CAT1->getSize() == CAT2->getSize()) { |
6283 | Composite1 = Arr1->getElementType(); |
6284 | Composite2 = Arr2->getElementType(); |
6285 | Steps.emplace_back(Args: Step::Array, Args&: CAT1); |
6286 | continue; |
6287 | } |
6288 | bool IAT1 = isa<IncompleteArrayType>(Val: Arr1); |
6289 | bool IAT2 = isa<IncompleteArrayType>(Val: Arr2); |
6290 | if ((IAT1 && IAT2) || |
6291 | (getLangOpts().CPlusPlus20 && (IAT1 != IAT2) && |
6292 | ((bool)CAT1 != (bool)CAT2) && |
6293 | (Steps.empty() || Steps.back().K != Step::Array))) { |
6294 | // In C++20 onwards, we can unify an array of N T with an array of |
6295 | // a different or unknown bound. But we can't form an array whose |
6296 | // element type is an array of unknown bound by doing so. |
6297 | Composite1 = Arr1->getElementType(); |
6298 | Composite2 = Arr2->getElementType(); |
6299 | Steps.emplace_back(Args: Step::Array); |
6300 | if (CAT1 || CAT2) |
6301 | NeedConstBefore = Steps.size(); |
6302 | continue; |
6303 | } |
6304 | } |
6305 | |
6306 | const PointerType *Ptr1, *Ptr2; |
6307 | if ((Ptr1 = Composite1->getAs<PointerType>()) && |
6308 | (Ptr2 = Composite2->getAs<PointerType>())) { |
6309 | Composite1 = Ptr1->getPointeeType(); |
6310 | Composite2 = Ptr2->getPointeeType(); |
6311 | Steps.emplace_back(Args: Step::Pointer); |
6312 | continue; |
6313 | } |
6314 | |
6315 | const ObjCObjectPointerType *ObjPtr1, *ObjPtr2; |
6316 | if ((ObjPtr1 = Composite1->getAs<ObjCObjectPointerType>()) && |
6317 | (ObjPtr2 = Composite2->getAs<ObjCObjectPointerType>())) { |
6318 | Composite1 = ObjPtr1->getPointeeType(); |
6319 | Composite2 = ObjPtr2->getPointeeType(); |
6320 | Steps.emplace_back(Args: Step::ObjCPointer); |
6321 | continue; |
6322 | } |
6323 | |
6324 | const MemberPointerType *MemPtr1, *MemPtr2; |
6325 | if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) && |
6326 | (MemPtr2 = Composite2->getAs<MemberPointerType>())) { |
6327 | Composite1 = MemPtr1->getPointeeType(); |
6328 | Composite2 = MemPtr2->getPointeeType(); |
6329 | |
6330 | // At the top level, we can perform a base-to-derived pointer-to-member |
6331 | // conversion: |
6332 | // |
6333 | // - [...] where C1 is reference-related to C2 or C2 is |
6334 | // reference-related to C1 |
6335 | // |
6336 | // (Note that the only kinds of reference-relatedness in scope here are |
6337 | // "same type or derived from".) At any other level, the class must |
6338 | // exactly match. |
6339 | CXXRecordDecl *Cls = nullptr, |
6340 | *Cls1 = MemPtr1->getMostRecentCXXRecordDecl(), |
6341 | *Cls2 = MemPtr2->getMostRecentCXXRecordDecl(); |
6342 | if (declaresSameEntity(Cls1, Cls2)) |
6343 | Cls = Cls1; |
6344 | else if (Steps.empty()) |
6345 | Cls = IsDerivedFrom(Loc, Derived: Cls1, Base: Cls2) ? Cls1 |
6346 | : IsDerivedFrom(Loc, Derived: Cls2, Base: Cls1) ? Cls2 |
6347 | : nullptr; |
6348 | if (!Cls) |
6349 | return QualType(); |
6350 | |
6351 | Steps.emplace_back(Args: Step::MemberPointer, |
6352 | Args: Context.getTypeDeclType(Cls).getTypePtr()); |
6353 | continue; |
6354 | } |
6355 | |
6356 | // Special case: at the top level, we can decompose an Objective-C pointer |
6357 | // and a 'cv void *'. Unify the qualifiers. |
6358 | if (Steps.empty() && ((Composite1->isVoidPointerType() && |
6359 | Composite2->isObjCObjectPointerType()) || |
6360 | (Composite1->isObjCObjectPointerType() && |
6361 | Composite2->isVoidPointerType()))) { |
6362 | Composite1 = Composite1->getPointeeType(); |
6363 | Composite2 = Composite2->getPointeeType(); |
6364 | Steps.emplace_back(Args: Step::Pointer); |
6365 | continue; |
6366 | } |
6367 | |
6368 | // FIXME: block pointer types? |
6369 | |
6370 | // Cannot unwrap any more types. |
6371 | break; |
6372 | } |
6373 | |
6374 | // - if T1 or T2 is "pointer to noexcept function" and the other type is |
6375 | // "pointer to function", where the function types are otherwise the same, |
6376 | // "pointer to function"; |
6377 | // - if T1 or T2 is "pointer to member of C1 of type function", the other |
6378 | // type is "pointer to member of C2 of type noexcept function", and C1 |
6379 | // is reference-related to C2 or C2 is reference-related to C1, where |
6380 | // the function types are otherwise the same, "pointer to member of C2 of |
6381 | // type function" or "pointer to member of C1 of type function", |
6382 | // respectively; |
6383 | // |
6384 | // We also support 'noreturn' here, so as a Clang extension we generalize the |
6385 | // above to: |
6386 | // |
6387 | // - [Clang] If T1 and T2 are both of type "pointer to function" or |
6388 | // "pointer to member function" and the pointee types can be unified |
6389 | // by a function pointer conversion, that conversion is applied |
6390 | // before checking the following rules. |
6391 | // |
6392 | // We've already unwrapped down to the function types, and we want to merge |
6393 | // rather than just convert, so do this ourselves rather than calling |
6394 | // IsFunctionConversion. |
6395 | // |
6396 | // FIXME: In order to match the standard wording as closely as possible, we |
6397 | // currently only do this under a single level of pointers. Ideally, we would |
6398 | // allow this in general, and set NeedConstBefore to the relevant depth on |
6399 | // the side(s) where we changed anything. If we permit that, we should also |
6400 | // consider this conversion when determining type similarity and model it as |
6401 | // a qualification conversion. |
6402 | if (Steps.size() == 1) { |
6403 | if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) { |
6404 | if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) { |
6405 | FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo(); |
6406 | FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo(); |
6407 | |
6408 | // The result is noreturn if both operands are. |
6409 | bool Noreturn = |
6410 | EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn(); |
6411 | EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(noReturn: Noreturn); |
6412 | EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(noReturn: Noreturn); |
6413 | |
6414 | bool CFIUncheckedCallee = |
6415 | EPI1.CFIUncheckedCallee || EPI2.CFIUncheckedCallee; |
6416 | EPI1.CFIUncheckedCallee = CFIUncheckedCallee; |
6417 | EPI2.CFIUncheckedCallee = CFIUncheckedCallee; |
6418 | |
6419 | // The result is nothrow if both operands are. |
6420 | SmallVector<QualType, 8> ExceptionTypeStorage; |
6421 | EPI1.ExceptionSpec = EPI2.ExceptionSpec = Context.mergeExceptionSpecs( |
6422 | ESI1: EPI1.ExceptionSpec, ESI2: EPI2.ExceptionSpec, ExceptionTypeStorage, |
6423 | AcceptDependent: getLangOpts().CPlusPlus17); |
6424 | |
6425 | Composite1 = Context.getFunctionType(ResultTy: FPT1->getReturnType(), |
6426 | Args: FPT1->getParamTypes(), EPI: EPI1); |
6427 | Composite2 = Context.getFunctionType(ResultTy: FPT2->getReturnType(), |
6428 | Args: FPT2->getParamTypes(), EPI: EPI2); |
6429 | } |
6430 | } |
6431 | } |
6432 | |
6433 | // There are some more conversions we can perform under exactly one pointer. |
6434 | if (Steps.size() == 1 && Steps.front().K == Step::Pointer && |
6435 | !Context.hasSameType(T1: Composite1, T2: Composite2)) { |
6436 | // - if T1 or T2 is "pointer to cv1 void" and the other type is |
6437 | // "pointer to cv2 T", where T is an object type or void, |
6438 | // "pointer to cv12 void", where cv12 is the union of cv1 and cv2; |
6439 | if (Composite1->isVoidType() && Composite2->isObjectType()) |
6440 | Composite2 = Composite1; |
6441 | else if (Composite2->isVoidType() && Composite1->isObjectType()) |
6442 | Composite1 = Composite2; |
6443 | // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1 |
6444 | // is reference-related to C2 or C2 is reference-related to C1 (8.6.3), |
6445 | // the cv-combined type of T1 and T2 or the cv-combined type of T2 and |
6446 | // T1, respectively; |
6447 | // |
6448 | // The "similar type" handling covers all of this except for the "T1 is a |
6449 | // base class of T2" case in the definition of reference-related. |
6450 | else if (IsDerivedFrom(Loc, Derived: Composite1, Base: Composite2)) |
6451 | Composite1 = Composite2; |
6452 | else if (IsDerivedFrom(Loc, Derived: Composite2, Base: Composite1)) |
6453 | Composite2 = Composite1; |
6454 | } |
6455 | |
6456 | // At this point, either the inner types are the same or we have failed to |
6457 | // find a composite pointer type. |
6458 | if (!Context.hasSameType(T1: Composite1, T2: Composite2)) |
6459 | return QualType(); |
6460 | |
6461 | // Per C++ [conv.qual]p3, add 'const' to every level before the last |
6462 | // differing qualifier. |
6463 | for (unsigned I = 0; I != NeedConstBefore; ++I) |
6464 | Steps[I].Quals.addConst(); |
6465 | |
6466 | // Rebuild the composite type. |
6467 | QualType Composite = Context.getCommonSugaredType(X: Composite1, Y: Composite2); |
6468 | for (auto &S : llvm::reverse(C&: Steps)) |
6469 | Composite = S.rebuild(Ctx&: Context, T: Composite); |
6470 | |
6471 | if (ConvertArgs) { |
6472 | // Convert the expressions to the composite pointer type. |
6473 | InitializedEntity Entity = |
6474 | InitializedEntity::InitializeTemporary(Type: Composite); |
6475 | InitializationKind Kind = |
6476 | InitializationKind::CreateCopy(InitLoc: Loc, EqualLoc: SourceLocation()); |
6477 | |
6478 | InitializationSequence E1ToC(*this, Entity, Kind, E1); |
6479 | if (!E1ToC) |
6480 | return QualType(); |
6481 | |
6482 | InitializationSequence E2ToC(*this, Entity, Kind, E2); |
6483 | if (!E2ToC) |
6484 | return QualType(); |
6485 | |
6486 | // FIXME: Let the caller know if these fail to avoid duplicate diagnostics. |
6487 | ExprResult E1Result = E1ToC.Perform(S&: *this, Entity, Kind, Args: E1); |
6488 | if (E1Result.isInvalid()) |
6489 | return QualType(); |
6490 | E1 = E1Result.get(); |
6491 | |
6492 | ExprResult E2Result = E2ToC.Perform(S&: *this, Entity, Kind, Args: E2); |
6493 | if (E2Result.isInvalid()) |
6494 | return QualType(); |
6495 | E2 = E2Result.get(); |
6496 | } |
6497 | |
6498 | return Composite; |
6499 | } |
6500 | |
6501 | ExprResult Sema::MaybeBindToTemporary(Expr *E) { |
6502 | if (!E) |
6503 | return ExprError(); |
6504 | |
6505 | assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?"); |
6506 | |
6507 | // If the result is a glvalue, we shouldn't bind it. |
6508 | if (E->isGLValue()) |
6509 | return E; |
6510 | |
6511 | // In ARC, calls that return a retainable type can return retained, |
6512 | // in which case we have to insert a consuming cast. |
6513 | if (getLangOpts().ObjCAutoRefCount && |
6514 | E->getType()->isObjCRetainableType()) { |
6515 | |
6516 | bool ReturnsRetained; |
6517 | |
6518 | // For actual calls, we compute this by examining the type of the |
6519 | // called value. |
6520 | if (CallExpr *Call = dyn_cast<CallExpr>(Val: E)) { |
6521 | Expr *Callee = Call->getCallee()->IgnoreParens(); |
6522 | QualType T = Callee->getType(); |
6523 | |
6524 | if (T == Context.BoundMemberTy) { |
6525 | // Handle pointer-to-members. |
6526 | if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Val: Callee)) |
6527 | T = BinOp->getRHS()->getType(); |
6528 | else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Val: Callee)) |
6529 | T = Mem->getMemberDecl()->getType(); |
6530 | } |
6531 | |
6532 | if (const PointerType *Ptr = T->getAs<PointerType>()) |
6533 | T = Ptr->getPointeeType(); |
6534 | else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>()) |
6535 | T = Ptr->getPointeeType(); |
6536 | else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>()) |
6537 | T = MemPtr->getPointeeType(); |
6538 | |
6539 | auto *FTy = T->castAs<FunctionType>(); |
6540 | ReturnsRetained = FTy->getExtInfo().getProducesResult(); |
6541 | |
6542 | // ActOnStmtExpr arranges things so that StmtExprs of retainable |
6543 | // type always produce a +1 object. |
6544 | } else if (isa<StmtExpr>(Val: E)) { |
6545 | ReturnsRetained = true; |
6546 | |
6547 | // We hit this case with the lambda conversion-to-block optimization; |
6548 | // we don't want any extra casts here. |
6549 | } else if (isa<CastExpr>(Val: E) && |
6550 | isa<BlockExpr>(Val: cast<CastExpr>(Val: E)->getSubExpr())) { |
6551 | return E; |
6552 | |
6553 | // For message sends and property references, we try to find an |
6554 | // actual method. FIXME: we should infer retention by selector in |
6555 | // cases where we don't have an actual method. |
6556 | } else { |
6557 | ObjCMethodDecl *D = nullptr; |
6558 | if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(Val: E)) { |
6559 | D = Send->getMethodDecl(); |
6560 | } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(Val: E)) { |
6561 | D = BoxedExpr->getBoxingMethod(); |
6562 | } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(Val: E)) { |
6563 | // Don't do reclaims if we're using the zero-element array |
6564 | // constant. |
6565 | if (ArrayLit->getNumElements() == 0 && |
6566 | Context.getLangOpts().ObjCRuntime.hasEmptyCollections()) |
6567 | return E; |
6568 | |
6569 | D = ArrayLit->getArrayWithObjectsMethod(); |
6570 | } else if (ObjCDictionaryLiteral *DictLit |
6571 | = dyn_cast<ObjCDictionaryLiteral>(Val: E)) { |
6572 | // Don't do reclaims if we're using the zero-element dictionary |
6573 | // constant. |
6574 | if (DictLit->getNumElements() == 0 && |
6575 | Context.getLangOpts().ObjCRuntime.hasEmptyCollections()) |
6576 | return E; |
6577 | |
6578 | D = DictLit->getDictWithObjectsMethod(); |
6579 | } |
6580 | |
6581 | ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>()); |
6582 | |
6583 | // Don't do reclaims on performSelector calls; despite their |
6584 | // return type, the invoked method doesn't necessarily actually |
6585 | // return an object. |
6586 | if (!ReturnsRetained && |
6587 | D && D->getMethodFamily() == OMF_performSelector) |
6588 | return E; |
6589 | } |
6590 | |
6591 | // Don't reclaim an object of Class type. |
6592 | if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType()) |
6593 | return E; |
6594 | |
6595 | Cleanup.setExprNeedsCleanups(true); |
6596 | |
6597 | CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject |
6598 | : CK_ARCReclaimReturnedObject); |
6599 | return ImplicitCastExpr::Create(Context, T: E->getType(), Kind: ck, Operand: E, BasePath: nullptr, |
6600 | Cat: VK_PRValue, FPO: FPOptionsOverride()); |
6601 | } |
6602 | |
6603 | if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) |
6604 | Cleanup.setExprNeedsCleanups(true); |
6605 | |
6606 | if (!getLangOpts().CPlusPlus) |
6607 | return E; |
6608 | |
6609 | // Search for the base element type (cf. ASTContext::getBaseElementType) with |
6610 | // a fast path for the common case that the type is directly a RecordType. |
6611 | const Type *T = Context.getCanonicalType(T: E->getType().getTypePtr()); |
6612 | const RecordType *RT = nullptr; |
6613 | while (!RT) { |
6614 | switch (T->getTypeClass()) { |
6615 | case Type::Record: |
6616 | RT = cast<RecordType>(Val: T); |
6617 | break; |
6618 | case Type::ConstantArray: |
6619 | case Type::IncompleteArray: |
6620 | case Type::VariableArray: |
6621 | case Type::DependentSizedArray: |
6622 | T = cast<ArrayType>(Val: T)->getElementType().getTypePtr(); |
6623 | break; |
6624 | default: |
6625 | return E; |
6626 | } |
6627 | } |
6628 | |
6629 | // That should be enough to guarantee that this type is complete, if we're |
6630 | // not processing a decltype expression. |
6631 | CXXRecordDecl *RD = cast<CXXRecordDecl>(Val: RT->getDecl()); |
6632 | if (RD->isInvalidDecl() || RD->isDependentContext()) |
6633 | return E; |
6634 | |
6635 | bool IsDecltype = ExprEvalContexts.back().ExprContext == |
6636 | ExpressionEvaluationContextRecord::EK_Decltype; |
6637 | CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(Class: RD); |
6638 | |
6639 | if (Destructor) { |
6640 | MarkFunctionReferenced(E->getExprLoc(), Destructor); |
6641 | CheckDestructorAccess(E->getExprLoc(), Destructor, |
6642 | PDiag(diag::err_access_dtor_temp) |
6643 | << E->getType()); |
6644 | if (DiagnoseUseOfDecl(Destructor, E->getExprLoc())) |
6645 | return ExprError(); |
6646 | |
6647 | // If destructor is trivial, we can avoid the extra copy. |
6648 | if (Destructor->isTrivial()) |
6649 | return E; |
6650 | |
6651 | // We need a cleanup, but we don't need to remember the temporary. |
6652 | Cleanup.setExprNeedsCleanups(true); |
6653 | } |
6654 | |
6655 | CXXTemporary *Temp = CXXTemporary::Create(C: Context, Destructor); |
6656 | CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(C: Context, Temp, SubExpr: E); |
6657 | |
6658 | if (IsDecltype) |
6659 | ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Elt: Bind); |
6660 | |
6661 | return Bind; |
6662 | } |
6663 | |
6664 | ExprResult |
6665 | Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) { |
6666 | if (SubExpr.isInvalid()) |
6667 | return ExprError(); |
6668 | |
6669 | return MaybeCreateExprWithCleanups(SubExpr: SubExpr.get()); |
6670 | } |
6671 | |
6672 | Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) { |
6673 | assert(SubExpr && "subexpression can't be null!"); |
6674 | |
6675 | CleanupVarDeclMarking(); |
6676 | |
6677 | unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects; |
6678 | assert(ExprCleanupObjects.size() >= FirstCleanup); |
6679 | assert(Cleanup.exprNeedsCleanups() || |
6680 | ExprCleanupObjects.size() == FirstCleanup); |
6681 | if (!Cleanup.exprNeedsCleanups()) |
6682 | return SubExpr; |
6683 | |
6684 | auto Cleanups = llvm::ArrayRef(ExprCleanupObjects.begin() + FirstCleanup, |
6685 | ExprCleanupObjects.size() - FirstCleanup); |
6686 | |
6687 | auto *E = ExprWithCleanups::Create( |
6688 | C: Context, subexpr: SubExpr, CleanupsHaveSideEffects: Cleanup.cleanupsHaveSideEffects(), objects: Cleanups); |
6689 | DiscardCleanupsInEvaluationContext(); |
6690 | |
6691 | return E; |
6692 | } |
6693 | |
6694 | Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) { |
6695 | assert(SubStmt && "sub-statement can't be null!"); |
6696 | |
6697 | CleanupVarDeclMarking(); |
6698 | |
6699 | if (!Cleanup.exprNeedsCleanups()) |
6700 | return SubStmt; |
6701 | |
6702 | // FIXME: In order to attach the temporaries, wrap the statement into |
6703 | // a StmtExpr; currently this is only used for asm statements. |
6704 | // This is hacky, either create a new CXXStmtWithTemporaries statement or |
6705 | // a new AsmStmtWithTemporaries. |
6706 | CompoundStmt *CompStmt = |
6707 | CompoundStmt::Create(C: Context, Stmts: SubStmt, FPFeatures: FPOptionsOverride(), |
6708 | LB: SourceLocation(), RB: SourceLocation()); |
6709 | Expr *E = new (Context) |
6710 | StmtExpr(CompStmt, Context.VoidTy, SourceLocation(), SourceLocation(), |
6711 | /*FIXME TemplateDepth=*/0); |
6712 | return MaybeCreateExprWithCleanups(SubExpr: E); |
6713 | } |
6714 | |
6715 | ExprResult Sema::ActOnDecltypeExpression(Expr *E) { |
6716 | assert(ExprEvalContexts.back().ExprContext == |
6717 | ExpressionEvaluationContextRecord::EK_Decltype && |
6718 | "not in a decltype expression"); |
6719 | |
6720 | ExprResult Result = CheckPlaceholderExpr(E); |
6721 | if (Result.isInvalid()) |
6722 | return ExprError(); |
6723 | E = Result.get(); |
6724 | |
6725 | // C++11 [expr.call]p11: |
6726 | // If a function call is a prvalue of object type, |
6727 | // -- if the function call is either |
6728 | // -- the operand of a decltype-specifier, or |
6729 | // -- the right operand of a comma operator that is the operand of a |
6730 | // decltype-specifier, |
6731 | // a temporary object is not introduced for the prvalue. |
6732 | |
6733 | // Recursively rebuild ParenExprs and comma expressions to strip out the |
6734 | // outermost CXXBindTemporaryExpr, if any. |
6735 | if (ParenExpr *PE = dyn_cast<ParenExpr>(Val: E)) { |
6736 | ExprResult SubExpr = ActOnDecltypeExpression(E: PE->getSubExpr()); |
6737 | if (SubExpr.isInvalid()) |
6738 | return ExprError(); |
6739 | if (SubExpr.get() == PE->getSubExpr()) |
6740 | return E; |
6741 | return ActOnParenExpr(L: PE->getLParen(), R: PE->getRParen(), E: SubExpr.get()); |
6742 | } |
6743 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) { |
6744 | if (BO->getOpcode() == BO_Comma) { |
6745 | ExprResult RHS = ActOnDecltypeExpression(E: BO->getRHS()); |
6746 | if (RHS.isInvalid()) |
6747 | return ExprError(); |
6748 | if (RHS.get() == BO->getRHS()) |
6749 | return E; |
6750 | return BinaryOperator::Create(C: Context, lhs: BO->getLHS(), rhs: RHS.get(), opc: BO_Comma, |
6751 | ResTy: BO->getType(), VK: BO->getValueKind(), |
6752 | OK: BO->getObjectKind(), opLoc: BO->getOperatorLoc(), |
6753 | FPFeatures: BO->getFPFeatures()); |
6754 | } |
6755 | } |
6756 | |
6757 | CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(Val: E); |
6758 | CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(Val: TopBind->getSubExpr()) |
6759 | : nullptr; |
6760 | if (TopCall) |
6761 | E = TopCall; |
6762 | else |
6763 | TopBind = nullptr; |
6764 | |
6765 | // Disable the special decltype handling now. |
6766 | ExprEvalContexts.back().ExprContext = |
6767 | ExpressionEvaluationContextRecord::EK_Other; |
6768 | |
6769 | Result = CheckUnevaluatedOperand(E); |
6770 | if (Result.isInvalid()) |
6771 | return ExprError(); |
6772 | E = Result.get(); |
6773 | |
6774 | // In MS mode, don't perform any extra checking of call return types within a |
6775 | // decltype expression. |
6776 | if (getLangOpts().MSVCCompat) |
6777 | return E; |
6778 | |
6779 | // Perform the semantic checks we delayed until this point. |
6780 | for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size(); |
6781 | I != N; ++I) { |
6782 | CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I]; |
6783 | if (Call == TopCall) |
6784 | continue; |
6785 | |
6786 | if (CheckCallReturnType(ReturnType: Call->getCallReturnType(Ctx: Context), |
6787 | Loc: Call->getBeginLoc(), CE: Call, FD: Call->getDirectCallee())) |
6788 | return ExprError(); |
6789 | } |
6790 | |
6791 | // Now all relevant types are complete, check the destructors are accessible |
6792 | // and non-deleted, and annotate them on the temporaries. |
6793 | for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size(); |
6794 | I != N; ++I) { |
6795 | CXXBindTemporaryExpr *Bind = |
6796 | ExprEvalContexts.back().DelayedDecltypeBinds[I]; |
6797 | if (Bind == TopBind) |
6798 | continue; |
6799 | |
6800 | CXXTemporary *Temp = Bind->getTemporary(); |
6801 | |
6802 | CXXRecordDecl *RD = |
6803 | Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); |
6804 | CXXDestructorDecl *Destructor = LookupDestructor(Class: RD); |
6805 | Temp->setDestructor(Destructor); |
6806 | |
6807 | MarkFunctionReferenced(Loc: Bind->getExprLoc(), Func: Destructor); |
6808 | CheckDestructorAccess(Bind->getExprLoc(), Destructor, |
6809 | PDiag(diag::err_access_dtor_temp) |
6810 | << Bind->getType()); |
6811 | if (DiagnoseUseOfDecl(D: Destructor, Locs: Bind->getExprLoc())) |
6812 | return ExprError(); |
6813 | |
6814 | // We need a cleanup, but we don't need to remember the temporary. |
6815 | Cleanup.setExprNeedsCleanups(true); |
6816 | } |
6817 | |
6818 | // Possibly strip off the top CXXBindTemporaryExpr. |
6819 | return E; |
6820 | } |
6821 | |
6822 | /// Note a set of 'operator->' functions that were used for a member access. |
6823 | static void noteOperatorArrows(Sema &S, |
6824 | ArrayRef<FunctionDecl *> OperatorArrows) { |
6825 | unsigned SkipStart = OperatorArrows.size(), SkipCount = 0; |
6826 | // FIXME: Make this configurable? |
6827 | unsigned Limit = 9; |
6828 | if (OperatorArrows.size() > Limit) { |
6829 | // Produce Limit-1 normal notes and one 'skipping' note. |
6830 | SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2; |
6831 | SkipCount = OperatorArrows.size() - (Limit - 1); |
6832 | } |
6833 | |
6834 | for (unsigned I = 0; I < OperatorArrows.size(); /**/) { |
6835 | if (I == SkipStart) { |
6836 | S.Diag(OperatorArrows[I]->getLocation(), |
6837 | diag::note_operator_arrows_suppressed) |
6838 | << SkipCount; |
6839 | I += SkipCount; |
6840 | } else { |
6841 | S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here) |
6842 | << OperatorArrows[I]->getCallResultType(); |
6843 | ++I; |
6844 | } |
6845 | } |
6846 | } |
6847 | |
6848 | ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, |
6849 | SourceLocation OpLoc, |
6850 | tok::TokenKind OpKind, |
6851 | ParsedType &ObjectType, |
6852 | bool &MayBePseudoDestructor) { |
6853 | // Since this might be a postfix expression, get rid of ParenListExprs. |
6854 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: Base); |
6855 | if (Result.isInvalid()) return ExprError(); |
6856 | Base = Result.get(); |
6857 | |
6858 | Result = CheckPlaceholderExpr(E: Base); |
6859 | if (Result.isInvalid()) return ExprError(); |
6860 | Base = Result.get(); |
6861 | |
6862 | QualType BaseType = Base->getType(); |
6863 | MayBePseudoDestructor = false; |
6864 | if (BaseType->isDependentType()) { |
6865 | // If we have a pointer to a dependent type and are using the -> operator, |
6866 | // the object type is the type that the pointer points to. We might still |
6867 | // have enough information about that type to do something useful. |
6868 | if (OpKind == tok::arrow) |
6869 | if (const PointerType *Ptr = BaseType->getAs<PointerType>()) |
6870 | BaseType = Ptr->getPointeeType(); |
6871 | |
6872 | ObjectType = ParsedType::make(P: BaseType); |
6873 | MayBePseudoDestructor = true; |
6874 | return Base; |
6875 | } |
6876 | |
6877 | // C++ [over.match.oper]p8: |
6878 | // [...] When operator->returns, the operator-> is applied to the value |
6879 | // returned, with the original second operand. |
6880 | if (OpKind == tok::arrow) { |
6881 | QualType StartingType = BaseType; |
6882 | bool NoArrowOperatorFound = false; |
6883 | bool FirstIteration = true; |
6884 | FunctionDecl *CurFD = dyn_cast<FunctionDecl>(Val: CurContext); |
6885 | // The set of types we've considered so far. |
6886 | llvm::SmallPtrSet<CanQualType,8> CTypes; |
6887 | SmallVector<FunctionDecl*, 8> OperatorArrows; |
6888 | CTypes.insert(Ptr: Context.getCanonicalType(T: BaseType)); |
6889 | |
6890 | while (BaseType->isRecordType()) { |
6891 | if (OperatorArrows.size() >= getLangOpts().ArrowDepth) { |
6892 | Diag(OpLoc, diag::err_operator_arrow_depth_exceeded) |
6893 | << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange(); |
6894 | noteOperatorArrows(S&: *this, OperatorArrows); |
6895 | Diag(OpLoc, diag::note_operator_arrow_depth) |
6896 | << getLangOpts().ArrowDepth; |
6897 | return ExprError(); |
6898 | } |
6899 | |
6900 | Result = BuildOverloadedArrowExpr( |
6901 | S, Base, OpLoc, |
6902 | // When in a template specialization and on the first loop iteration, |
6903 | // potentially give the default diagnostic (with the fixit in a |
6904 | // separate note) instead of having the error reported back to here |
6905 | // and giving a diagnostic with a fixit attached to the error itself. |
6906 | NoArrowOperatorFound: (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization()) |
6907 | ? nullptr |
6908 | : &NoArrowOperatorFound); |
6909 | if (Result.isInvalid()) { |
6910 | if (NoArrowOperatorFound) { |
6911 | if (FirstIteration) { |
6912 | Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) |
6913 | << BaseType << 1 << Base->getSourceRange() |
6914 | << FixItHint::CreateReplacement(OpLoc, "."); |
6915 | OpKind = tok::period; |
6916 | break; |
6917 | } |
6918 | Diag(OpLoc, diag::err_typecheck_member_reference_arrow) |
6919 | << BaseType << Base->getSourceRange(); |
6920 | CallExpr *CE = dyn_cast<CallExpr>(Val: Base); |
6921 | if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) { |
6922 | Diag(CD->getBeginLoc(), |
6923 | diag::note_member_reference_arrow_from_operator_arrow); |
6924 | } |
6925 | } |
6926 | return ExprError(); |
6927 | } |
6928 | Base = Result.get(); |
6929 | if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Val: Base)) |
6930 | OperatorArrows.push_back(Elt: OpCall->getDirectCallee()); |
6931 | BaseType = Base->getType(); |
6932 | CanQualType CBaseType = Context.getCanonicalType(T: BaseType); |
6933 | if (!CTypes.insert(Ptr: CBaseType).second) { |
6934 | Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType; |
6935 | noteOperatorArrows(S&: *this, OperatorArrows); |
6936 | return ExprError(); |
6937 | } |
6938 | FirstIteration = false; |
6939 | } |
6940 | |
6941 | if (OpKind == tok::arrow) { |
6942 | if (BaseType->isPointerType()) |
6943 | BaseType = BaseType->getPointeeType(); |
6944 | else if (auto *AT = Context.getAsArrayType(T: BaseType)) |
6945 | BaseType = AT->getElementType(); |
6946 | } |
6947 | } |
6948 | |
6949 | // Objective-C properties allow "." access on Objective-C pointer types, |
6950 | // so adjust the base type to the object type itself. |
6951 | if (BaseType->isObjCObjectPointerType()) |
6952 | BaseType = BaseType->getPointeeType(); |
6953 | |
6954 | // C++ [basic.lookup.classref]p2: |
6955 | // [...] If the type of the object expression is of pointer to scalar |
6956 | // type, the unqualified-id is looked up in the context of the complete |
6957 | // postfix-expression. |
6958 | // |
6959 | // This also indicates that we could be parsing a pseudo-destructor-name. |
6960 | // Note that Objective-C class and object types can be pseudo-destructor |
6961 | // expressions or normal member (ivar or property) access expressions, and |
6962 | // it's legal for the type to be incomplete if this is a pseudo-destructor |
6963 | // call. We'll do more incomplete-type checks later in the lookup process, |
6964 | // so just skip this check for ObjC types. |
6965 | if (!BaseType->isRecordType()) { |
6966 | ObjectType = ParsedType::make(P: BaseType); |
6967 | MayBePseudoDestructor = true; |
6968 | return Base; |
6969 | } |
6970 | |
6971 | // The object type must be complete (or dependent), or |
6972 | // C++11 [expr.prim.general]p3: |
6973 | // Unlike the object expression in other contexts, *this is not required to |
6974 | // be of complete type for purposes of class member access (5.2.5) outside |
6975 | // the member function body. |
6976 | if (!BaseType->isDependentType() && |
6977 | !isThisOutsideMemberFunctionBody(BaseType) && |
6978 | RequireCompleteType(OpLoc, BaseType, |
6979 | diag::err_incomplete_member_access)) { |
6980 | return CreateRecoveryExpr(Begin: Base->getBeginLoc(), End: Base->getEndLoc(), SubExprs: {Base}); |
6981 | } |
6982 | |
6983 | // C++ [basic.lookup.classref]p2: |
6984 | // If the id-expression in a class member access (5.2.5) is an |
6985 | // unqualified-id, and the type of the object expression is of a class |
6986 | // type C (or of pointer to a class type C), the unqualified-id is looked |
6987 | // up in the scope of class C. [...] |
6988 | ObjectType = ParsedType::make(P: BaseType); |
6989 | return Base; |
6990 | } |
6991 | |
6992 | static bool CheckArrow(Sema &S, QualType &ObjectType, Expr *&Base, |
6993 | tok::TokenKind &OpKind, SourceLocation OpLoc) { |
6994 | if (Base->hasPlaceholderType()) { |
6995 | ExprResult result = S.CheckPlaceholderExpr(E: Base); |
6996 | if (result.isInvalid()) return true; |
6997 | Base = result.get(); |
6998 | } |
6999 | ObjectType = Base->getType(); |
7000 | |
7001 | // C++ [expr.pseudo]p2: |
7002 | // The left-hand side of the dot operator shall be of scalar type. The |
7003 | // left-hand side of the arrow operator shall be of pointer to scalar type. |
7004 | // This scalar type is the object type. |
7005 | // Note that this is rather different from the normal handling for the |
7006 | // arrow operator. |
7007 | if (OpKind == tok::arrow) { |
7008 | // The operator requires a prvalue, so perform lvalue conversions. |
7009 | // Only do this if we might plausibly end with a pointer, as otherwise |
7010 | // this was likely to be intended to be a '.'. |
7011 | if (ObjectType->isPointerType() || ObjectType->isArrayType() || |
7012 | ObjectType->isFunctionType()) { |
7013 | ExprResult BaseResult = S.DefaultFunctionArrayLvalueConversion(E: Base); |
7014 | if (BaseResult.isInvalid()) |
7015 | return true; |
7016 | Base = BaseResult.get(); |
7017 | ObjectType = Base->getType(); |
7018 | } |
7019 | |
7020 | if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) { |
7021 | ObjectType = Ptr->getPointeeType(); |
7022 | } else if (!Base->isTypeDependent()) { |
7023 | // The user wrote "p->" when they probably meant "p."; fix it. |
7024 | S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) |
7025 | << ObjectType << true |
7026 | << FixItHint::CreateReplacement(OpLoc, "."); |
7027 | if (S.isSFINAEContext()) |
7028 | return true; |
7029 | |
7030 | OpKind = tok::period; |
7031 | } |
7032 | } |
7033 | |
7034 | return false; |
7035 | } |
7036 | |
7037 | /// Check if it's ok to try and recover dot pseudo destructor calls on |
7038 | /// pointer objects. |
7039 | static bool |
7040 | canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef, |
7041 | QualType DestructedType) { |
7042 | // If this is a record type, check if its destructor is callable. |
7043 | if (auto *RD = DestructedType->getAsCXXRecordDecl()) { |
7044 | if (RD->hasDefinition()) |
7045 | if (CXXDestructorDecl *D = SemaRef.LookupDestructor(Class: RD)) |
7046 | return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false); |
7047 | return false; |
7048 | } |
7049 | |
7050 | // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor. |
7051 | return DestructedType->isDependentType() || DestructedType->isScalarType() || |
7052 | DestructedType->isVectorType(); |
7053 | } |
7054 | |
7055 | ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base, |
7056 | SourceLocation OpLoc, |
7057 | tok::TokenKind OpKind, |
7058 | const CXXScopeSpec &SS, |
7059 | TypeSourceInfo *ScopeTypeInfo, |
7060 | SourceLocation CCLoc, |
7061 | SourceLocation TildeLoc, |
7062 | PseudoDestructorTypeStorage Destructed) { |
7063 | TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo(); |
7064 | |
7065 | QualType ObjectType; |
7066 | if (CheckArrow(S&: *this, ObjectType, Base, OpKind, OpLoc)) |
7067 | return ExprError(); |
7068 | |
7069 | if (!ObjectType->isDependentType() && !ObjectType->isScalarType() && |
7070 | !ObjectType->isVectorType() && !ObjectType->isMatrixType()) { |
7071 | if (getLangOpts().MSVCCompat && ObjectType->isVoidType()) |
7072 | Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange(); |
7073 | else { |
7074 | Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar) |
7075 | << ObjectType << Base->getSourceRange(); |
7076 | return ExprError(); |
7077 | } |
7078 | } |
7079 | |
7080 | // C++ [expr.pseudo]p2: |
7081 | // [...] The cv-unqualified versions of the object type and of the type |
7082 | // designated by the pseudo-destructor-name shall be the same type. |
7083 | if (DestructedTypeInfo) { |
7084 | QualType DestructedType = DestructedTypeInfo->getType(); |
7085 | SourceLocation DestructedTypeStart = |
7086 | DestructedTypeInfo->getTypeLoc().getBeginLoc(); |
7087 | if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) { |
7088 | if (!Context.hasSameUnqualifiedType(T1: DestructedType, T2: ObjectType)) { |
7089 | // Detect dot pseudo destructor calls on pointer objects, e.g.: |
7090 | // Foo *foo; |
7091 | // foo.~Foo(); |
7092 | if (OpKind == tok::period && ObjectType->isPointerType() && |
7093 | Context.hasSameUnqualifiedType(T1: DestructedType, |
7094 | T2: ObjectType->getPointeeType())) { |
7095 | auto Diagnostic = |
7096 | Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) |
7097 | << ObjectType << /*IsArrow=*/0 << Base->getSourceRange(); |
7098 | |
7099 | // Issue a fixit only when the destructor is valid. |
7100 | if (canRecoverDotPseudoDestructorCallsOnPointerObjects( |
7101 | SemaRef&: *this, DestructedType)) |
7102 | Diagnostic << FixItHint::CreateReplacement(RemoveRange: OpLoc, Code: "->"); |
7103 | |
7104 | // Recover by setting the object type to the destructed type and the |
7105 | // operator to '->'. |
7106 | ObjectType = DestructedType; |
7107 | OpKind = tok::arrow; |
7108 | } else { |
7109 | Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch) |
7110 | << ObjectType << DestructedType << Base->getSourceRange() |
7111 | << DestructedTypeInfo->getTypeLoc().getSourceRange(); |
7112 | |
7113 | // Recover by setting the destructed type to the object type. |
7114 | DestructedType = ObjectType; |
7115 | DestructedTypeInfo = |
7116 | Context.getTrivialTypeSourceInfo(T: ObjectType, Loc: DestructedTypeStart); |
7117 | Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); |
7118 | } |
7119 | } else if (DestructedType.getObjCLifetime() != |
7120 | ObjectType.getObjCLifetime()) { |
7121 | |
7122 | if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) { |
7123 | // Okay: just pretend that the user provided the correctly-qualified |
7124 | // type. |
7125 | } else { |
7126 | Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals) |
7127 | << ObjectType << DestructedType << Base->getSourceRange() |
7128 | << DestructedTypeInfo->getTypeLoc().getSourceRange(); |
7129 | } |
7130 | |
7131 | // Recover by setting the destructed type to the object type. |
7132 | DestructedType = ObjectType; |
7133 | DestructedTypeInfo = Context.getTrivialTypeSourceInfo(T: ObjectType, |
7134 | Loc: DestructedTypeStart); |
7135 | Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); |
7136 | } |
7137 | } |
7138 | } |
7139 | |
7140 | // C++ [expr.pseudo]p2: |
7141 | // [...] Furthermore, the two type-names in a pseudo-destructor-name of the |
7142 | // form |
7143 | // |
7144 | // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name |
7145 | // |
7146 | // shall designate the same scalar type. |
7147 | if (ScopeTypeInfo) { |
7148 | QualType ScopeType = ScopeTypeInfo->getType(); |
7149 | if (!ScopeType->isDependentType() && !ObjectType->isDependentType() && |
7150 | !Context.hasSameUnqualifiedType(T1: ScopeType, T2: ObjectType)) { |
7151 | |
7152 | Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(), |
7153 | diag::err_pseudo_dtor_type_mismatch) |
7154 | << ObjectType << ScopeType << Base->getSourceRange() |
7155 | << ScopeTypeInfo->getTypeLoc().getSourceRange(); |
7156 | |
7157 | ScopeType = QualType(); |
7158 | ScopeTypeInfo = nullptr; |
7159 | } |
7160 | } |
7161 | |
7162 | Expr *Result |
7163 | = new (Context) CXXPseudoDestructorExpr(Context, Base, |
7164 | OpKind == tok::arrow, OpLoc, |
7165 | SS.getWithLocInContext(Context), |
7166 | ScopeTypeInfo, |
7167 | CCLoc, |
7168 | TildeLoc, |
7169 | Destructed); |
7170 | |
7171 | return Result; |
7172 | } |
7173 | |
7174 | ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, |
7175 | SourceLocation OpLoc, |
7176 | tok::TokenKind OpKind, |
7177 | CXXScopeSpec &SS, |
7178 | UnqualifiedId &FirstTypeName, |
7179 | SourceLocation CCLoc, |
7180 | SourceLocation TildeLoc, |
7181 | UnqualifiedId &SecondTypeName) { |
7182 | assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || |
7183 | FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && |
7184 | "Invalid first type name in pseudo-destructor"); |
7185 | assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || |
7186 | SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && |
7187 | "Invalid second type name in pseudo-destructor"); |
7188 | |
7189 | QualType ObjectType; |
7190 | if (CheckArrow(S&: *this, ObjectType, Base, OpKind, OpLoc)) |
7191 | return ExprError(); |
7192 | |
7193 | // Compute the object type that we should use for name lookup purposes. Only |
7194 | // record types and dependent types matter. |
7195 | ParsedType ObjectTypePtrForLookup; |
7196 | if (!SS.isSet()) { |
7197 | if (ObjectType->isRecordType()) |
7198 | ObjectTypePtrForLookup = ParsedType::make(P: ObjectType); |
7199 | else if (ObjectType->isDependentType()) |
7200 | ObjectTypePtrForLookup = ParsedType::make(P: Context.DependentTy); |
7201 | } |
7202 | |
7203 | // Convert the name of the type being destructed (following the ~) into a |
7204 | // type (with source-location information). |
7205 | QualType DestructedType; |
7206 | TypeSourceInfo *DestructedTypeInfo = nullptr; |
7207 | PseudoDestructorTypeStorage Destructed; |
7208 | if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) { |
7209 | ParsedType T = getTypeName(II: *SecondTypeName.Identifier, |
7210 | NameLoc: SecondTypeName.StartLocation, |
7211 | S, SS: &SS, isClassName: true, HasTrailingDot: false, ObjectType: ObjectTypePtrForLookup, |
7212 | /*IsCtorOrDtorName*/true); |
7213 | if (!T && |
7214 | ((SS.isSet() && !computeDeclContext(SS, EnteringContext: false)) || |
7215 | (!SS.isSet() && ObjectType->isDependentType()))) { |
7216 | // The name of the type being destroyed is a dependent name, and we |
7217 | // couldn't find anything useful in scope. Just store the identifier and |
7218 | // it's location, and we'll perform (qualified) name lookup again at |
7219 | // template instantiation time. |
7220 | Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier, |
7221 | SecondTypeName.StartLocation); |
7222 | } else if (!T) { |
7223 | Diag(SecondTypeName.StartLocation, |
7224 | diag::err_pseudo_dtor_destructor_non_type) |
7225 | << SecondTypeName.Identifier << ObjectType; |
7226 | if (isSFINAEContext()) |
7227 | return ExprError(); |
7228 | |
7229 | // Recover by assuming we had the right type all along. |
7230 | DestructedType = ObjectType; |
7231 | } else |
7232 | DestructedType = GetTypeFromParser(Ty: T, TInfo: &DestructedTypeInfo); |
7233 | } else { |
7234 | // Resolve the template-id to a type. |
7235 | TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId; |
7236 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), |
7237 | TemplateId->NumArgs); |
7238 | TypeResult T = ActOnTemplateIdType(S, |
7239 | SS, |
7240 | TemplateKWLoc: TemplateId->TemplateKWLoc, |
7241 | Template: TemplateId->Template, |
7242 | TemplateII: TemplateId->Name, |
7243 | TemplateIILoc: TemplateId->TemplateNameLoc, |
7244 | LAngleLoc: TemplateId->LAngleLoc, |
7245 | TemplateArgs: TemplateArgsPtr, |
7246 | RAngleLoc: TemplateId->RAngleLoc, |
7247 | /*IsCtorOrDtorName*/true); |
7248 | if (T.isInvalid() || !T.get()) { |
7249 | // Recover by assuming we had the right type all along. |
7250 | DestructedType = ObjectType; |
7251 | } else |
7252 | DestructedType = GetTypeFromParser(Ty: T.get(), TInfo: &DestructedTypeInfo); |
7253 | } |
7254 | |
7255 | // If we've performed some kind of recovery, (re-)build the type source |
7256 | // information. |
7257 | if (!DestructedType.isNull()) { |
7258 | if (!DestructedTypeInfo) |
7259 | DestructedTypeInfo = Context.getTrivialTypeSourceInfo(T: DestructedType, |
7260 | Loc: SecondTypeName.StartLocation); |
7261 | Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); |
7262 | } |
7263 | |
7264 | // Convert the name of the scope type (the type prior to '::') into a type. |
7265 | TypeSourceInfo *ScopeTypeInfo = nullptr; |
7266 | QualType ScopeType; |
7267 | if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || |
7268 | FirstTypeName.Identifier) { |
7269 | if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) { |
7270 | ParsedType T = getTypeName(II: *FirstTypeName.Identifier, |
7271 | NameLoc: FirstTypeName.StartLocation, |
7272 | S, SS: &SS, isClassName: true, HasTrailingDot: false, ObjectType: ObjectTypePtrForLookup, |
7273 | /*IsCtorOrDtorName*/true); |
7274 | if (!T) { |
7275 | Diag(FirstTypeName.StartLocation, |
7276 | diag::err_pseudo_dtor_destructor_non_type) |
7277 | << FirstTypeName.Identifier << ObjectType; |
7278 | |
7279 | if (isSFINAEContext()) |
7280 | return ExprError(); |
7281 | |
7282 | // Just drop this type. It's unnecessary anyway. |
7283 | ScopeType = QualType(); |
7284 | } else |
7285 | ScopeType = GetTypeFromParser(Ty: T, TInfo: &ScopeTypeInfo); |
7286 | } else { |
7287 | // Resolve the template-id to a type. |
7288 | TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId; |
7289 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), |
7290 | TemplateId->NumArgs); |
7291 | TypeResult T = ActOnTemplateIdType(S, |
7292 | SS, |
7293 | TemplateKWLoc: TemplateId->TemplateKWLoc, |
7294 | Template: TemplateId->Template, |
7295 | TemplateII: TemplateId->Name, |
7296 | TemplateIILoc: TemplateId->TemplateNameLoc, |
7297 | LAngleLoc: TemplateId->LAngleLoc, |
7298 | TemplateArgs: TemplateArgsPtr, |
7299 | RAngleLoc: TemplateId->RAngleLoc, |
7300 | /*IsCtorOrDtorName*/true); |
7301 | if (T.isInvalid() || !T.get()) { |
7302 | // Recover by dropping this type. |
7303 | ScopeType = QualType(); |
7304 | } else |
7305 | ScopeType = GetTypeFromParser(Ty: T.get(), TInfo: &ScopeTypeInfo); |
7306 | } |
7307 | } |
7308 | |
7309 | if (!ScopeType.isNull() && !ScopeTypeInfo) |
7310 | ScopeTypeInfo = Context.getTrivialTypeSourceInfo(T: ScopeType, |
7311 | Loc: FirstTypeName.StartLocation); |
7312 | |
7313 | |
7314 | return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS, |
7315 | ScopeTypeInfo, CCLoc, TildeLoc, |
7316 | Destructed); |
7317 | } |
7318 | |
7319 | ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, |
7320 | SourceLocation OpLoc, |
7321 | tok::TokenKind OpKind, |
7322 | SourceLocation TildeLoc, |
7323 | const DeclSpec& DS) { |
7324 | QualType ObjectType; |
7325 | QualType T; |
7326 | TypeLocBuilder TLB; |
7327 | if (CheckArrow(S&: *this, ObjectType, Base, OpKind, OpLoc) || |
7328 | DS.getTypeSpecType() == DeclSpec::TST_error) |
7329 | return ExprError(); |
7330 | |
7331 | switch (DS.getTypeSpecType()) { |
7332 | case DeclSpec::TST_decltype_auto: { |
7333 | Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); |
7334 | return true; |
7335 | } |
7336 | case DeclSpec::TST_decltype: { |
7337 | T = BuildDecltypeType(E: DS.getRepAsExpr(), /*AsUnevaluated=*/false); |
7338 | DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T); |
7339 | DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc()); |
7340 | DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd()); |
7341 | break; |
7342 | } |
7343 | case DeclSpec::TST_typename_pack_indexing: { |
7344 | T = ActOnPackIndexingType(Pattern: DS.getRepAsType().get(), IndexExpr: DS.getPackIndexingExpr(), |
7345 | Loc: DS.getBeginLoc(), EllipsisLoc: DS.getEllipsisLoc()); |
7346 | TLB.pushTrivial(Context&: getASTContext(), |
7347 | T: cast<PackIndexingType>(Val: T.getTypePtr())->getPattern(), |
7348 | Loc: DS.getBeginLoc()); |
7349 | PackIndexingTypeLoc PITL = TLB.push<PackIndexingTypeLoc>(T); |
7350 | PITL.setEllipsisLoc(DS.getEllipsisLoc()); |
7351 | break; |
7352 | } |
7353 | default: |
7354 | llvm_unreachable("Unsupported type in pseudo destructor"); |
7355 | } |
7356 | TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T); |
7357 | PseudoDestructorTypeStorage Destructed(DestructedTypeInfo); |
7358 | |
7359 | return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS: CXXScopeSpec(), |
7360 | ScopeTypeInfo: nullptr, CCLoc: SourceLocation(), TildeLoc, |
7361 | Destructed); |
7362 | } |
7363 | |
7364 | ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, |
7365 | SourceLocation RParen) { |
7366 | // If the operand is an unresolved lookup expression, the expression is ill- |
7367 | // formed per [over.over]p1, because overloaded function names cannot be used |
7368 | // without arguments except in explicit contexts. |
7369 | ExprResult R = CheckPlaceholderExpr(E: Operand); |
7370 | if (R.isInvalid()) |
7371 | return R; |
7372 | |
7373 | R = CheckUnevaluatedOperand(E: R.get()); |
7374 | if (R.isInvalid()) |
7375 | return ExprError(); |
7376 | |
7377 | Operand = R.get(); |
7378 | |
7379 | if (!inTemplateInstantiation() && !Operand->isInstantiationDependent() && |
7380 | Operand->HasSideEffects(Ctx: Context, IncludePossibleEffects: false)) { |
7381 | // The expression operand for noexcept is in an unevaluated expression |
7382 | // context, so side effects could result in unintended consequences. |
7383 | Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context); |
7384 | } |
7385 | |
7386 | CanThrowResult CanThrow = canThrow(Operand); |
7387 | return new (Context) |
7388 | CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen); |
7389 | } |
7390 | |
7391 | ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation, |
7392 | Expr *Operand, SourceLocation RParen) { |
7393 | return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen); |
7394 | } |
7395 | |
7396 | static void MaybeDecrementCount( |
7397 | Expr *E, llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { |
7398 | DeclRefExpr *LHS = nullptr; |
7399 | bool IsCompoundAssign = false; |
7400 | bool isIncrementDecrementUnaryOp = false; |
7401 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) { |
7402 | if (BO->getLHS()->getType()->isDependentType() || |
7403 | BO->getRHS()->getType()->isDependentType()) { |
7404 | if (BO->getOpcode() != BO_Assign) |
7405 | return; |
7406 | } else if (!BO->isAssignmentOp()) |
7407 | return; |
7408 | else |
7409 | IsCompoundAssign = BO->isCompoundAssignmentOp(); |
7410 | LHS = dyn_cast<DeclRefExpr>(Val: BO->getLHS()); |
7411 | } else if (CXXOperatorCallExpr *COCE = dyn_cast<CXXOperatorCallExpr>(Val: E)) { |
7412 | if (COCE->getOperator() != OO_Equal) |
7413 | return; |
7414 | LHS = dyn_cast<DeclRefExpr>(COCE->getArg(0)); |
7415 | } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: E)) { |
7416 | if (!UO->isIncrementDecrementOp()) |
7417 | return; |
7418 | isIncrementDecrementUnaryOp = true; |
7419 | LHS = dyn_cast<DeclRefExpr>(Val: UO->getSubExpr()); |
7420 | } |
7421 | if (!LHS) |
7422 | return; |
7423 | VarDecl *VD = dyn_cast<VarDecl>(Val: LHS->getDecl()); |
7424 | if (!VD) |
7425 | return; |
7426 | // Don't decrement RefsMinusAssignments if volatile variable with compound |
7427 | // assignment (+=, ...) or increment/decrement unary operator to avoid |
7428 | // potential unused-but-set-variable warning. |
7429 | if ((IsCompoundAssign || isIncrementDecrementUnaryOp) && |
7430 | VD->getType().isVolatileQualified()) |
7431 | return; |
7432 | auto iter = RefsMinusAssignments.find(Val: VD); |
7433 | if (iter == RefsMinusAssignments.end()) |
7434 | return; |
7435 | iter->getSecond()--; |
7436 | } |
7437 | |
7438 | /// Perform the conversions required for an expression used in a |
7439 | /// context that ignores the result. |
7440 | ExprResult Sema::IgnoredValueConversions(Expr *E) { |
7441 | MaybeDecrementCount(E, RefsMinusAssignments); |
7442 | |
7443 | if (E->hasPlaceholderType()) { |
7444 | ExprResult result = CheckPlaceholderExpr(E); |
7445 | if (result.isInvalid()) return E; |
7446 | E = result.get(); |
7447 | } |
7448 | |
7449 | if (getLangOpts().CPlusPlus) { |
7450 | // The C++11 standard defines the notion of a discarded-value expression; |
7451 | // normally, we don't need to do anything to handle it, but if it is a |
7452 | // volatile lvalue with a special form, we perform an lvalue-to-rvalue |
7453 | // conversion. |
7454 | if (getLangOpts().CPlusPlus11 && E->isReadIfDiscardedInCPlusPlus11()) { |
7455 | ExprResult Res = DefaultLvalueConversion(E); |
7456 | if (Res.isInvalid()) |
7457 | return E; |
7458 | E = Res.get(); |
7459 | } else { |
7460 | // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if |
7461 | // it occurs as a discarded-value expression. |
7462 | CheckUnusedVolatileAssignment(E); |
7463 | } |
7464 | |
7465 | // C++1z: |
7466 | // If the expression is a prvalue after this optional conversion, the |
7467 | // temporary materialization conversion is applied. |
7468 | // |
7469 | // We do not materialize temporaries by default in order to avoid creating |
7470 | // unnecessary temporary objects. If we skip this step, IR generation is |
7471 | // able to synthesize the storage for itself in the aggregate case, and |
7472 | // adding the extra node to the AST is just clutter. |
7473 | if (isInLifetimeExtendingContext() && getLangOpts().CPlusPlus17 && |
7474 | E->isPRValue() && !E->getType()->isVoidType()) { |
7475 | ExprResult Res = TemporaryMaterializationConversion(E); |
7476 | if (Res.isInvalid()) |
7477 | return E; |
7478 | E = Res.get(); |
7479 | } |
7480 | return E; |
7481 | } |
7482 | |
7483 | // C99 6.3.2.1: |
7484 | // [Except in specific positions,] an lvalue that does not have |
7485 | // array type is converted to the value stored in the |
7486 | // designated object (and is no longer an lvalue). |
7487 | if (E->isPRValue()) { |
7488 | // In C, function designators (i.e. expressions of function type) |
7489 | // are r-values, but we still want to do function-to-pointer decay |
7490 | // on them. This is both technically correct and convenient for |
7491 | // some clients. |
7492 | if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType()) |
7493 | return DefaultFunctionArrayConversion(E); |
7494 | |
7495 | return E; |
7496 | } |
7497 | |
7498 | // GCC seems to also exclude expressions of incomplete enum type. |
7499 | if (const EnumType *T = E->getType()->getAs<EnumType>()) { |
7500 | if (!T->getDecl()->isComplete()) { |
7501 | // FIXME: stupid workaround for a codegen bug! |
7502 | E = ImpCastExprToType(E, Type: Context.VoidTy, CK: CK_ToVoid).get(); |
7503 | return E; |
7504 | } |
7505 | } |
7506 | |
7507 | ExprResult Res = DefaultFunctionArrayLvalueConversion(E); |
7508 | if (Res.isInvalid()) |
7509 | return E; |
7510 | E = Res.get(); |
7511 | |
7512 | if (!E->getType()->isVoidType()) |
7513 | RequireCompleteType(E->getExprLoc(), E->getType(), |
7514 | diag::err_incomplete_type); |
7515 | return E; |
7516 | } |
7517 | |
7518 | ExprResult Sema::CheckUnevaluatedOperand(Expr *E) { |
7519 | // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if |
7520 | // it occurs as an unevaluated operand. |
7521 | CheckUnusedVolatileAssignment(E); |
7522 | |
7523 | return E; |
7524 | } |
7525 | |
7526 | // If we can unambiguously determine whether Var can never be used |
7527 | // in a constant expression, return true. |
7528 | // - if the variable and its initializer are non-dependent, then |
7529 | // we can unambiguously check if the variable is a constant expression. |
7530 | // - if the initializer is not value dependent - we can determine whether |
7531 | // it can be used to initialize a constant expression. If Init can not |
7532 | // be used to initialize a constant expression we conclude that Var can |
7533 | // never be a constant expression. |
7534 | // - FXIME: if the initializer is dependent, we can still do some analysis and |
7535 | // identify certain cases unambiguously as non-const by using a Visitor: |
7536 | // - such as those that involve odr-use of a ParmVarDecl, involve a new |
7537 | // delete, lambda-expr, dynamic-cast, reinterpret-cast etc... |
7538 | static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var, |
7539 | ASTContext &Context) { |
7540 | if (isa<ParmVarDecl>(Val: Var)) return true; |
7541 | const VarDecl *DefVD = nullptr; |
7542 | |
7543 | // If there is no initializer - this can not be a constant expression. |
7544 | const Expr *Init = Var->getAnyInitializer(D&: DefVD); |
7545 | if (!Init) |
7546 | return true; |
7547 | assert(DefVD); |
7548 | if (DefVD->isWeak()) |
7549 | return false; |
7550 | |
7551 | if (Var->getType()->isDependentType() || Init->isValueDependent()) { |
7552 | // FIXME: Teach the constant evaluator to deal with the non-dependent parts |
7553 | // of value-dependent expressions, and use it here to determine whether the |
7554 | // initializer is a potential constant expression. |
7555 | return false; |
7556 | } |
7557 | |
7558 | return !Var->isUsableInConstantExpressions(C: Context); |
7559 | } |
7560 | |
7561 | /// Check if the current lambda has any potential captures |
7562 | /// that must be captured by any of its enclosing lambdas that are ready to |
7563 | /// capture. If there is a lambda that can capture a nested |
7564 | /// potential-capture, go ahead and do so. Also, check to see if any |
7565 | /// variables are uncaptureable or do not involve an odr-use so do not |
7566 | /// need to be captured. |
7567 | |
7568 | static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures( |
7569 | Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) { |
7570 | |
7571 | assert(!S.isUnevaluatedContext()); |
7572 | assert(S.CurContext->isDependentContext()); |
7573 | #ifndef NDEBUG |
7574 | DeclContext *DC = S.CurContext; |
7575 | while (isa_and_nonnull<CapturedDecl>(Val: DC)) |
7576 | DC = DC->getParent(); |
7577 | assert( |
7578 | (CurrentLSI->CallOperator == DC || !CurrentLSI->AfterParameterList) && |
7579 | "The current call operator must be synchronized with Sema's CurContext"); |
7580 | #endif // NDEBUG |
7581 | |
7582 | const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent(); |
7583 | |
7584 | // All the potentially captureable variables in the current nested |
7585 | // lambda (within a generic outer lambda), must be captured by an |
7586 | // outer lambda that is enclosed within a non-dependent context. |
7587 | CurrentLSI->visitPotentialCaptures(Callback: [&](ValueDecl *Var, Expr *VarExpr) { |
7588 | // If the variable is clearly identified as non-odr-used and the full |
7589 | // expression is not instantiation dependent, only then do we not |
7590 | // need to check enclosing lambda's for speculative captures. |
7591 | // For e.g.: |
7592 | // Even though 'x' is not odr-used, it should be captured. |
7593 | // int test() { |
7594 | // const int x = 10; |
7595 | // auto L = [=](auto a) { |
7596 | // (void) +x + a; |
7597 | // }; |
7598 | // } |
7599 | if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(CapturingVarExpr: VarExpr) && |
7600 | !IsFullExprInstantiationDependent) |
7601 | return; |
7602 | |
7603 | VarDecl *UnderlyingVar = Var->getPotentiallyDecomposedVarDecl(); |
7604 | if (!UnderlyingVar) |
7605 | return; |
7606 | |
7607 | // If we have a capture-capable lambda for the variable, go ahead and |
7608 | // capture the variable in that lambda (and all its enclosing lambdas). |
7609 | if (const UnsignedOrNone Index = |
7610 | getStackIndexOfNearestEnclosingCaptureCapableLambda( |
7611 | FunctionScopes: S.FunctionScopes, VarToCapture: Var, S)) |
7612 | S.MarkCaptureUsedInEnclosingContext(Capture: Var, Loc: VarExpr->getExprLoc(), CapturingScopeIndex: *Index); |
7613 | const bool IsVarNeverAConstantExpression = |
7614 | VariableCanNeverBeAConstantExpression(Var: UnderlyingVar, Context&: S.Context); |
7615 | if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) { |
7616 | // This full expression is not instantiation dependent or the variable |
7617 | // can not be used in a constant expression - which means |
7618 | // this variable must be odr-used here, so diagnose a |
7619 | // capture violation early, if the variable is un-captureable. |
7620 | // This is purely for diagnosing errors early. Otherwise, this |
7621 | // error would get diagnosed when the lambda becomes capture ready. |
7622 | QualType CaptureType, DeclRefType; |
7623 | SourceLocation ExprLoc = VarExpr->getExprLoc(); |
7624 | if (S.tryCaptureVariable(Var, Loc: ExprLoc, Kind: TryCaptureKind::Implicit, |
7625 | /*EllipsisLoc*/ SourceLocation(), |
7626 | /*BuildAndDiagnose*/ false, CaptureType, |
7627 | DeclRefType, FunctionScopeIndexToStopAt: nullptr)) { |
7628 | // We will never be able to capture this variable, and we need |
7629 | // to be able to in any and all instantiations, so diagnose it. |
7630 | S.tryCaptureVariable(Var, Loc: ExprLoc, Kind: TryCaptureKind::Implicit, |
7631 | /*EllipsisLoc*/ SourceLocation(), |
7632 | /*BuildAndDiagnose*/ true, CaptureType, |
7633 | DeclRefType, FunctionScopeIndexToStopAt: nullptr); |
7634 | } |
7635 | } |
7636 | }); |
7637 | |
7638 | // Check if 'this' needs to be captured. |
7639 | if (CurrentLSI->hasPotentialThisCapture()) { |
7640 | // If we have a capture-capable lambda for 'this', go ahead and capture |
7641 | // 'this' in that lambda (and all its enclosing lambdas). |
7642 | if (const UnsignedOrNone Index = |
7643 | getStackIndexOfNearestEnclosingCaptureCapableLambda( |
7644 | FunctionScopes: S.FunctionScopes, /*0 is 'this'*/ VarToCapture: nullptr, S)) { |
7645 | const unsigned FunctionScopeIndexOfCapturableLambda = *Index; |
7646 | S.CheckCXXThisCapture(Loc: CurrentLSI->PotentialThisCaptureLocation, |
7647 | /*Explicit*/ false, /*BuildAndDiagnose*/ true, |
7648 | FunctionScopeIndexToStopAt: &FunctionScopeIndexOfCapturableLambda); |
7649 | } |
7650 | } |
7651 | |
7652 | // Reset all the potential captures at the end of each full-expression. |
7653 | CurrentLSI->clearPotentialCaptures(); |
7654 | } |
7655 | |
7656 | static ExprResult attemptRecovery(Sema &SemaRef, |
7657 | const TypoCorrectionConsumer &Consumer, |
7658 | const TypoCorrection &TC) { |
7659 | LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(), |
7660 | Consumer.getLookupResult().getLookupKind()); |
7661 | const CXXScopeSpec *SS = Consumer.getSS(); |
7662 | CXXScopeSpec NewSS; |
7663 | |
7664 | // Use an approprate CXXScopeSpec for building the expr. |
7665 | if (auto *NNS = TC.getCorrectionSpecifier()) |
7666 | NewSS.MakeTrivial(Context&: SemaRef.Context, Qualifier: NNS, R: TC.getCorrectionRange()); |
7667 | else if (SS && !TC.WillReplaceSpecifier()) |
7668 | NewSS = *SS; |
7669 | |
7670 | if (auto *ND = TC.getFoundDecl()) { |
7671 | R.setLookupName(ND->getDeclName()); |
7672 | R.addDecl(D: ND); |
7673 | if (ND->isCXXClassMember()) { |
7674 | // Figure out the correct naming class to add to the LookupResult. |
7675 | CXXRecordDecl *Record = nullptr; |
7676 | if (auto *NNS = TC.getCorrectionSpecifier()) |
7677 | Record = NNS->getAsType()->getAsCXXRecordDecl(); |
7678 | if (!Record) |
7679 | Record = |
7680 | dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext()); |
7681 | if (Record) |
7682 | R.setNamingClass(Record); |
7683 | |
7684 | // Detect and handle the case where the decl might be an implicit |
7685 | // member. |
7686 | if (SemaRef.isPotentialImplicitMemberAccess( |
7687 | SS: NewSS, R, IsAddressOfOperand: Consumer.isAddressOfOperand())) |
7688 | return SemaRef.BuildPossibleImplicitMemberExpr( |
7689 | SS: NewSS, /*TemplateKWLoc*/ SourceLocation(), R, |
7690 | /*TemplateArgs*/ nullptr, /*S*/ nullptr); |
7691 | } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Val: ND)) { |
7692 | return SemaRef.ObjC().LookupInObjCMethod(LookUp&: R, S: Consumer.getScope(), |
7693 | II: Ivar->getIdentifier()); |
7694 | } |
7695 | } |
7696 | |
7697 | return SemaRef.BuildDeclarationNameExpr(SS: NewSS, R, /*NeedsADL*/ false, |
7698 | /*AcceptInvalidDecl*/ true); |
7699 | } |
7700 | |
7701 | namespace { |
7702 | class FindTypoExprs : public DynamicRecursiveASTVisitor { |
7703 | llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs; |
7704 | |
7705 | public: |
7706 | explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs) |
7707 | : TypoExprs(TypoExprs) {} |
7708 | bool VisitTypoExpr(TypoExpr *TE) override { |
7709 | TypoExprs.insert(X: TE); |
7710 | return true; |
7711 | } |
7712 | }; |
7713 | |
7714 | class TransformTypos : public TreeTransform<TransformTypos> { |
7715 | typedef TreeTransform<TransformTypos> BaseTransform; |
7716 | |
7717 | VarDecl *InitDecl; // A decl to avoid as a correction because it is in the |
7718 | // process of being initialized. |
7719 | llvm::function_ref<ExprResult(Expr *)> ExprFilter; |
7720 | llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs; |
7721 | llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache; |
7722 | llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution; |
7723 | |
7724 | /// Emit diagnostics for all of the TypoExprs encountered. |
7725 | /// |
7726 | /// If the TypoExprs were successfully corrected, then the diagnostics should |
7727 | /// suggest the corrections. Otherwise the diagnostics will not suggest |
7728 | /// anything (having been passed an empty TypoCorrection). |
7729 | /// |
7730 | /// If we've failed to correct due to ambiguous corrections, we need to |
7731 | /// be sure to pass empty corrections and replacements. Otherwise it's |
7732 | /// possible that the Consumer has a TypoCorrection that failed to ambiguity |
7733 | /// and we don't want to report those diagnostics. |
7734 | void EmitAllDiagnostics(bool IsAmbiguous) { |
7735 | for (TypoExpr *TE : TypoExprs) { |
7736 | auto &State = SemaRef.getTypoExprState(TE); |
7737 | if (State.DiagHandler) { |
7738 | TypoCorrection TC = IsAmbiguous |
7739 | ? TypoCorrection() : State.Consumer->getCurrentCorrection(); |
7740 | ExprResult Replacement = IsAmbiguous ? ExprError() : TransformCache[TE]; |
7741 | |
7742 | // Extract the NamedDecl from the transformed TypoExpr and add it to the |
7743 | // TypoCorrection, replacing the existing decls. This ensures the right |
7744 | // NamedDecl is used in diagnostics e.g. in the case where overload |
7745 | // resolution was used to select one from several possible decls that |
7746 | // had been stored in the TypoCorrection. |
7747 | if (auto *ND = getDeclFromExpr( |
7748 | E: Replacement.isInvalid() ? nullptr : Replacement.get())) |
7749 | TC.setCorrectionDecl(ND); |
7750 | |
7751 | State.DiagHandler(TC); |
7752 | } |
7753 | SemaRef.clearDelayedTypo(TE); |
7754 | } |
7755 | } |
7756 | |
7757 | /// Try to advance the typo correction state of the first unfinished TypoExpr. |
7758 | /// We allow advancement of the correction stream by removing it from the |
7759 | /// TransformCache which allows `TransformTypoExpr` to advance during the |
7760 | /// next transformation attempt. |
7761 | /// |
7762 | /// Any substitution attempts for the previous TypoExprs (which must have been |
7763 | /// finished) will need to be retried since it's possible that they will now |
7764 | /// be invalid given the latest advancement. |
7765 | /// |
7766 | /// We need to be sure that we're making progress - it's possible that the |
7767 | /// tree is so malformed that the transform never makes it to the |
7768 | /// `TransformTypoExpr`. |
7769 | /// |
7770 | /// Returns true if there are any untried correction combinations. |
7771 | bool CheckAndAdvanceTypoExprCorrectionStreams() { |
7772 | for (auto *TE : TypoExprs) { |
7773 | auto &State = SemaRef.getTypoExprState(TE); |
7774 | TransformCache.erase(Val: TE); |
7775 | if (!State.Consumer->hasMadeAnyCorrectionProgress()) |
7776 | return false; |
7777 | if (!State.Consumer->finished()) |
7778 | return true; |
7779 | State.Consumer->resetCorrectionStream(); |
7780 | } |
7781 | return false; |
7782 | } |
7783 | |
7784 | NamedDecl *getDeclFromExpr(Expr *E) { |
7785 | if (auto *OE = dyn_cast_or_null<OverloadExpr>(Val: E)) |
7786 | E = OverloadResolution[OE]; |
7787 | |
7788 | if (!E) |
7789 | return nullptr; |
7790 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) |
7791 | return DRE->getFoundDecl(); |
7792 | if (auto *ME = dyn_cast<MemberExpr>(Val: E)) |
7793 | return ME->getFoundDecl(); |
7794 | // FIXME: Add any other expr types that could be seen by the delayed typo |
7795 | // correction TreeTransform for which the corresponding TypoCorrection could |
7796 | // contain multiple decls. |
7797 | return nullptr; |
7798 | } |
7799 | |
7800 | ExprResult TryTransform(Expr *E) { |
7801 | Sema::SFINAETrap Trap(SemaRef); |
7802 | ExprResult Res = TransformExpr(E); |
7803 | if (Trap.hasErrorOccurred() || Res.isInvalid()) |
7804 | return ExprError(); |
7805 | |
7806 | return ExprFilter(Res.get()); |
7807 | } |
7808 | |
7809 | // Since correcting typos may intoduce new TypoExprs, this function |
7810 | // checks for new TypoExprs and recurses if it finds any. Note that it will |
7811 | // only succeed if it is able to correct all typos in the given expression. |
7812 | ExprResult CheckForRecursiveTypos(ExprResult Res, bool &IsAmbiguous) { |
7813 | if (Res.isInvalid()) { |
7814 | return Res; |
7815 | } |
7816 | // Check to see if any new TypoExprs were created. If so, we need to recurse |
7817 | // to check their validity. |
7818 | Expr *FixedExpr = Res.get(); |
7819 | |
7820 | auto SavedTypoExprs = std::move(TypoExprs); |
7821 | auto SavedAmbiguousTypoExprs = std::move(AmbiguousTypoExprs); |
7822 | TypoExprs.clear(); |
7823 | AmbiguousTypoExprs.clear(); |
7824 | |
7825 | FindTypoExprs(TypoExprs).TraverseStmt(FixedExpr); |
7826 | if (!TypoExprs.empty()) { |
7827 | // Recurse to handle newly created TypoExprs. If we're not able to |
7828 | // handle them, discard these TypoExprs. |
7829 | ExprResult RecurResult = |
7830 | RecursiveTransformLoop(E: FixedExpr, IsAmbiguous); |
7831 | if (RecurResult.isInvalid()) { |
7832 | Res = ExprError(); |
7833 | // Recursive corrections didn't work, wipe them away and don't add |
7834 | // them to the TypoExprs set. Remove them from Sema's TypoExpr list |
7835 | // since we don't want to clear them twice. Note: it's possible the |
7836 | // TypoExprs were created recursively and thus won't be in our |
7837 | // Sema's TypoExprs - they were created in our `RecursiveTransformLoop`. |
7838 | auto &SemaTypoExprs = SemaRef.TypoExprs; |
7839 | for (auto *TE : TypoExprs) { |
7840 | TransformCache.erase(Val: TE); |
7841 | SemaRef.clearDelayedTypo(TE); |
7842 | |
7843 | auto SI = find(SemaTypoExprs, TE); |
7844 | if (SI != SemaTypoExprs.end()) { |
7845 | SemaTypoExprs.erase(SI); |
7846 | } |
7847 | } |
7848 | } else { |
7849 | // TypoExpr is valid: add newly created TypoExprs since we were |
7850 | // able to correct them. |
7851 | Res = RecurResult; |
7852 | SavedTypoExprs.set_union(TypoExprs); |
7853 | } |
7854 | } |
7855 | |
7856 | TypoExprs = std::move(SavedTypoExprs); |
7857 | AmbiguousTypoExprs = std::move(SavedAmbiguousTypoExprs); |
7858 | |
7859 | return Res; |
7860 | } |
7861 | |
7862 | // Try to transform the given expression, looping through the correction |
7863 | // candidates with `CheckAndAdvanceTypoExprCorrectionStreams`. |
7864 | // |
7865 | // If valid ambiguous typo corrections are seen, `IsAmbiguous` is set to |
7866 | // true and this method immediately will return an `ExprError`. |
7867 | ExprResult RecursiveTransformLoop(Expr *E, bool &IsAmbiguous) { |
7868 | ExprResult Res; |
7869 | auto SavedTypoExprs = std::move(SemaRef.TypoExprs); |
7870 | SemaRef.TypoExprs.clear(); |
7871 | |
7872 | while (true) { |
7873 | Res = CheckForRecursiveTypos(Res: TryTransform(E), IsAmbiguous); |
7874 | |
7875 | // Recursion encountered an ambiguous correction. This means that our |
7876 | // correction itself is ambiguous, so stop now. |
7877 | if (IsAmbiguous) |
7878 | break; |
7879 | |
7880 | // If the transform is still valid after checking for any new typos, |
7881 | // it's good to go. |
7882 | if (!Res.isInvalid()) |
7883 | break; |
7884 | |
7885 | // The transform was invalid, see if we have any TypoExprs with untried |
7886 | // correction candidates. |
7887 | if (!CheckAndAdvanceTypoExprCorrectionStreams()) |
7888 | break; |
7889 | } |
7890 | |
7891 | // If we found a valid result, double check to make sure it's not ambiguous. |
7892 | if (!IsAmbiguous && !Res.isInvalid() && !AmbiguousTypoExprs.empty()) { |
7893 | auto SavedTransformCache = |
7894 | llvm::SmallDenseMap<TypoExpr *, ExprResult, 2>(TransformCache); |
7895 | |
7896 | // Ensure none of the TypoExprs have multiple typo correction candidates |
7897 | // with the same edit length that pass all the checks and filters. |
7898 | while (!AmbiguousTypoExprs.empty()) { |
7899 | auto TE = AmbiguousTypoExprs.back(); |
7900 | |
7901 | // TryTransform itself can create new Typos, adding them to the TypoExpr map |
7902 | // and invalidating our TypoExprState, so always fetch it instead of storing. |
7903 | SemaRef.getTypoExprState(TE).Consumer->saveCurrentPosition(); |
7904 | |
7905 | TypoCorrection TC = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection(); |
7906 | TypoCorrection Next; |
7907 | do { |
7908 | // Fetch the next correction by erasing the typo from the cache and calling |
7909 | // `TryTransform` which will iterate through corrections in |
7910 | // `TransformTypoExpr`. |
7911 | TransformCache.erase(Val: TE); |
7912 | ExprResult AmbigRes = CheckForRecursiveTypos(Res: TryTransform(E), IsAmbiguous); |
7913 | |
7914 | if (!AmbigRes.isInvalid() || IsAmbiguous) { |
7915 | SemaRef.getTypoExprState(TE).Consumer->resetCorrectionStream(); |
7916 | SavedTransformCache.erase(Val: TE); |
7917 | Res = ExprError(); |
7918 | IsAmbiguous = true; |
7919 | break; |
7920 | } |
7921 | } while ((Next = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection()) && |
7922 | Next.getEditDistance(false) == TC.getEditDistance(false)); |
7923 | |
7924 | if (IsAmbiguous) |
7925 | break; |
7926 | |
7927 | AmbiguousTypoExprs.remove(X: TE); |
7928 | SemaRef.getTypoExprState(TE).Consumer->restoreSavedPosition(); |
7929 | TransformCache[TE] = SavedTransformCache[TE]; |
7930 | } |
7931 | TransformCache = std::move(SavedTransformCache); |
7932 | } |
7933 | |
7934 | // Wipe away any newly created TypoExprs that we don't know about. Since we |
7935 | // clear any invalid TypoExprs in `CheckForRecursiveTypos`, this is only |
7936 | // possible if a `TypoExpr` is created during a transformation but then |
7937 | // fails before we can discover it. |
7938 | auto &SemaTypoExprs = SemaRef.TypoExprs; |
7939 | for (auto Iterator = SemaTypoExprs.begin(); Iterator != SemaTypoExprs.end();) { |
7940 | auto TE = *Iterator; |
7941 | auto FI = find(TypoExprs, TE); |
7942 | if (FI != TypoExprs.end()) { |
7943 | Iterator++; |
7944 | continue; |
7945 | } |
7946 | SemaRef.clearDelayedTypo(TE); |
7947 | Iterator = SemaTypoExprs.erase(Iterator); |
7948 | } |
7949 | SemaRef.TypoExprs = std::move(SavedTypoExprs); |
7950 | |
7951 | return Res; |
7952 | } |
7953 | |
7954 | public: |
7955 | TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter) |
7956 | : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {} |
7957 | |
7958 | ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc, |
7959 | MultiExprArg Args, |
7960 | SourceLocation RParenLoc, |
7961 | Expr *ExecConfig = nullptr) { |
7962 | auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args, |
7963 | RParenLoc, ExecConfig); |
7964 | if (auto *OE = dyn_cast<OverloadExpr>(Val: Callee)) { |
7965 | if (Result.isUsable()) { |
7966 | Expr *ResultCall = Result.get(); |
7967 | if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall)) |
7968 | ResultCall = BE->getSubExpr(); |
7969 | if (auto *CE = dyn_cast<CallExpr>(ResultCall)) |
7970 | OverloadResolution[OE] = CE->getCallee(); |
7971 | } |
7972 | } |
7973 | return Result; |
7974 | } |
7975 | |
7976 | ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); } |
7977 | |
7978 | ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); } |
7979 | |
7980 | ExprResult Transform(Expr *E) { |
7981 | bool IsAmbiguous = false; |
7982 | ExprResult Res = RecursiveTransformLoop(E, IsAmbiguous); |
7983 | |
7984 | if (!Res.isUsable()) |
7985 | FindTypoExprs(TypoExprs).TraverseStmt(E); |
7986 | |
7987 | EmitAllDiagnostics(IsAmbiguous); |
7988 | |
7989 | return Res; |
7990 | } |
7991 | |
7992 | ExprResult TransformTypoExpr(TypoExpr *E) { |
7993 | // If the TypoExpr hasn't been seen before, record it. Otherwise, return the |
7994 | // cached transformation result if there is one and the TypoExpr isn't the |
7995 | // first one that was encountered. |
7996 | auto &CacheEntry = TransformCache[E]; |
7997 | if (!TypoExprs.insert(X: E) && !CacheEntry.isUnset()) { |
7998 | return CacheEntry; |
7999 | } |
8000 | |
8001 | auto &State = SemaRef.getTypoExprState(E); |
8002 | assert(State.Consumer && "Cannot transform a cleared TypoExpr"); |
8003 | |
8004 | // For the first TypoExpr and an uncached TypoExpr, find the next likely |
8005 | // typo correction and return it. |
8006 | while (TypoCorrection TC = State.Consumer->getNextCorrection()) { |
8007 | if (InitDecl && TC.getFoundDecl() == InitDecl) |
8008 | continue; |
8009 | // FIXME: If we would typo-correct to an invalid declaration, it's |
8010 | // probably best to just suppress all errors from this typo correction. |
8011 | ExprResult NE = State.RecoveryHandler ? |
8012 | State.RecoveryHandler(SemaRef, E, TC) : |
8013 | attemptRecovery(SemaRef, *State.Consumer, TC); |
8014 | if (!NE.isInvalid()) { |
8015 | // Check whether there may be a second viable correction with the same |
8016 | // edit distance; if so, remember this TypoExpr may have an ambiguous |
8017 | // correction so it can be more thoroughly vetted later. |
8018 | TypoCorrection Next; |
8019 | if ((Next = State.Consumer->peekNextCorrection()) && |
8020 | Next.getEditDistance(Normalized: false) == TC.getEditDistance(Normalized: false)) { |
8021 | AmbiguousTypoExprs.insert(X: E); |
8022 | } else { |
8023 | AmbiguousTypoExprs.remove(X: E); |
8024 | } |
8025 | assert(!NE.isUnset() && |
8026 | "Typo was transformed into a valid-but-null ExprResult"); |
8027 | return CacheEntry = NE; |
8028 | } |
8029 | } |
8030 | return CacheEntry = ExprError(); |
8031 | } |
8032 | }; |
8033 | } |
8034 | |
8035 | ExprResult |
8036 | Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl, |
8037 | bool RecoverUncorrectedTypos, |
8038 | llvm::function_ref<ExprResult(Expr *)> Filter) { |
8039 | // If the current evaluation context indicates there are uncorrected typos |
8040 | // and the current expression isn't guaranteed to not have typos, try to |
8041 | // resolve any TypoExpr nodes that might be in the expression. |
8042 | if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos && |
8043 | (E->isTypeDependent() || E->isValueDependent() || |
8044 | E->isInstantiationDependent())) { |
8045 | auto TyposResolved = DelayedTypos.size(); |
8046 | auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E); |
8047 | TyposResolved -= DelayedTypos.size(); |
8048 | if (Result.isInvalid() || Result.get() != E) { |
8049 | ExprEvalContexts.back().NumTypos -= TyposResolved; |
8050 | if (Result.isInvalid() && RecoverUncorrectedTypos) { |
8051 | struct TyposReplace : TreeTransform<TyposReplace> { |
8052 | TyposReplace(Sema &SemaRef) : TreeTransform(SemaRef) {} |
8053 | ExprResult TransformTypoExpr(clang::TypoExpr *E) { |
8054 | return this->SemaRef.CreateRecoveryExpr(E->getBeginLoc(), |
8055 | E->getEndLoc(), {}); |
8056 | } |
8057 | } TT(*this); |
8058 | return TT.TransformExpr(E); |
8059 | } |
8060 | return Result; |
8061 | } |
8062 | assert(TyposResolved == 0 && "Corrected typo but got same Expr back?"); |
8063 | } |
8064 | return E; |
8065 | } |
8066 | |
8067 | ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC, |
8068 | bool DiscardedValue, bool IsConstexpr, |
8069 | bool IsTemplateArgument) { |
8070 | ExprResult FullExpr = FE; |
8071 | |
8072 | if (!FullExpr.get()) |
8073 | return ExprError(); |
8074 | |
8075 | if (!IsTemplateArgument && DiagnoseUnexpandedParameterPack(E: FullExpr.get())) |
8076 | return ExprError(); |
8077 | |
8078 | if (DiscardedValue) { |
8079 | // Top-level expressions default to 'id' when we're in a debugger. |
8080 | if (getLangOpts().DebuggerCastResultToId && |
8081 | FullExpr.get()->getType() == Context.UnknownAnyTy) { |
8082 | FullExpr = forceUnknownAnyToType(E: FullExpr.get(), ToType: Context.getObjCIdType()); |
8083 | if (FullExpr.isInvalid()) |
8084 | return ExprError(); |
8085 | } |
8086 | |
8087 | FullExpr = CheckPlaceholderExpr(E: FullExpr.get()); |
8088 | if (FullExpr.isInvalid()) |
8089 | return ExprError(); |
8090 | |
8091 | FullExpr = IgnoredValueConversions(E: FullExpr.get()); |
8092 | if (FullExpr.isInvalid()) |
8093 | return ExprError(); |
8094 | |
8095 | DiagnoseUnusedExprResult(FullExpr.get(), diag::warn_unused_expr); |
8096 | } |
8097 | |
8098 | FullExpr = CorrectDelayedTyposInExpr(E: FullExpr.get(), /*InitDecl=*/nullptr, |
8099 | /*RecoverUncorrectedTypos=*/true); |
8100 | if (FullExpr.isInvalid()) |
8101 | return ExprError(); |
8102 | |
8103 | CheckCompletedExpr(E: FullExpr.get(), CheckLoc: CC, IsConstexpr); |
8104 | |
8105 | // At the end of this full expression (which could be a deeply nested |
8106 | // lambda), if there is a potential capture within the nested lambda, |
8107 | // have the outer capture-able lambda try and capture it. |
8108 | // Consider the following code: |
8109 | // void f(int, int); |
8110 | // void f(const int&, double); |
8111 | // void foo() { |
8112 | // const int x = 10, y = 20; |
8113 | // auto L = [=](auto a) { |
8114 | // auto M = [=](auto b) { |
8115 | // f(x, b); <-- requires x to be captured by L and M |
8116 | // f(y, a); <-- requires y to be captured by L, but not all Ms |
8117 | // }; |
8118 | // }; |
8119 | // } |
8120 | |
8121 | // FIXME: Also consider what happens for something like this that involves |
8122 | // the gnu-extension statement-expressions or even lambda-init-captures: |
8123 | // void f() { |
8124 | // const int n = 0; |
8125 | // auto L = [&](auto a) { |
8126 | // +n + ({ 0; a; }); |
8127 | // }; |
8128 | // } |
8129 | // |
8130 | // Here, we see +n, and then the full-expression 0; ends, so we don't |
8131 | // capture n (and instead remove it from our list of potential captures), |
8132 | // and then the full-expression +n + ({ 0; }); ends, but it's too late |
8133 | // for us to see that we need to capture n after all. |
8134 | |
8135 | LambdaScopeInfo *const CurrentLSI = |
8136 | getCurLambda(/*IgnoreCapturedRegions=*/IgnoreNonLambdaCapturingScope: true); |
8137 | // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer |
8138 | // even if CurContext is not a lambda call operator. Refer to that Bug Report |
8139 | // for an example of the code that might cause this asynchrony. |
8140 | // By ensuring we are in the context of a lambda's call operator |
8141 | // we can fix the bug (we only need to check whether we need to capture |
8142 | // if we are within a lambda's body); but per the comments in that |
8143 | // PR, a proper fix would entail : |
8144 | // "Alternative suggestion: |
8145 | // - Add to Sema an integer holding the smallest (outermost) scope |
8146 | // index that we are *lexically* within, and save/restore/set to |
8147 | // FunctionScopes.size() in InstantiatingTemplate's |
8148 | // constructor/destructor. |
8149 | // - Teach the handful of places that iterate over FunctionScopes to |
8150 | // stop at the outermost enclosing lexical scope." |
8151 | DeclContext *DC = CurContext; |
8152 | while (isa_and_nonnull<CapturedDecl>(Val: DC)) |
8153 | DC = DC->getParent(); |
8154 | const bool IsInLambdaDeclContext = isLambdaCallOperator(DC); |
8155 | if (IsInLambdaDeclContext && CurrentLSI && |
8156 | CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid()) |
8157 | CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI, |
8158 | S&: *this); |
8159 | return MaybeCreateExprWithCleanups(SubExpr: FullExpr); |
8160 | } |
8161 | |
8162 | StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) { |
8163 | if (!FullStmt) return StmtError(); |
8164 | |
8165 | return MaybeCreateStmtWithCleanups(SubStmt: FullStmt); |
8166 | } |
8167 | |
8168 | IfExistsResult |
8169 | Sema::CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, |
8170 | const DeclarationNameInfo &TargetNameInfo) { |
8171 | DeclarationName TargetName = TargetNameInfo.getName(); |
8172 | if (!TargetName) |
8173 | return IfExistsResult::DoesNotExist; |
8174 | |
8175 | // If the name itself is dependent, then the result is dependent. |
8176 | if (TargetName.isDependentName()) |
8177 | return IfExistsResult::Dependent; |
8178 | |
8179 | // Do the redeclaration lookup in the current scope. |
8180 | LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName, |
8181 | RedeclarationKind::NotForRedeclaration); |
8182 | LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType()); |
8183 | R.suppressDiagnostics(); |
8184 | |
8185 | switch (R.getResultKind()) { |
8186 | case LookupResultKind::Found: |
8187 | case LookupResultKind::FoundOverloaded: |
8188 | case LookupResultKind::FoundUnresolvedValue: |
8189 | case LookupResultKind::Ambiguous: |
8190 | return IfExistsResult::Exists; |
8191 | |
8192 | case LookupResultKind::NotFound: |
8193 | return IfExistsResult::DoesNotExist; |
8194 | |
8195 | case LookupResultKind::NotFoundInCurrentInstantiation: |
8196 | return IfExistsResult::Dependent; |
8197 | } |
8198 | |
8199 | llvm_unreachable("Invalid LookupResult Kind!"); |
8200 | } |
8201 | |
8202 | IfExistsResult Sema::CheckMicrosoftIfExistsSymbol(Scope *S, |
8203 | SourceLocation KeywordLoc, |
8204 | bool IsIfExists, |
8205 | CXXScopeSpec &SS, |
8206 | UnqualifiedId &Name) { |
8207 | DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); |
8208 | |
8209 | // Check for an unexpanded parameter pack. |
8210 | auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists; |
8211 | if (DiagnoseUnexpandedParameterPack(SS, UPPC) || |
8212 | DiagnoseUnexpandedParameterPack(NameInfo: TargetNameInfo, UPPC)) |
8213 | return IfExistsResult::Error; |
8214 | |
8215 | return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo); |
8216 | } |
8217 | |
8218 | concepts::Requirement *Sema::ActOnSimpleRequirement(Expr *E) { |
8219 | return BuildExprRequirement(E, /*IsSimple=*/IsSatisfied: true, |
8220 | /*NoexceptLoc=*/SourceLocation(), |
8221 | /*ReturnTypeRequirement=*/{}); |
8222 | } |
8223 | |
8224 | concepts::Requirement *Sema::ActOnTypeRequirement( |
8225 | SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc, |
8226 | const IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId) { |
8227 | assert(((!TypeName && TemplateId) || (TypeName && !TemplateId)) && |
8228 | "Exactly one of TypeName and TemplateId must be specified."); |
8229 | TypeSourceInfo *TSI = nullptr; |
8230 | if (TypeName) { |
8231 | QualType T = |
8232 | CheckTypenameType(Keyword: ElaboratedTypeKeyword::Typename, KeywordLoc: TypenameKWLoc, |
8233 | QualifierLoc: SS.getWithLocInContext(Context), II: *TypeName, IILoc: NameLoc, |
8234 | TSI: &TSI, /*DeducedTSTContext=*/false); |
8235 | if (T.isNull()) |
8236 | return nullptr; |
8237 | } else { |
8238 | ASTTemplateArgsPtr ArgsPtr(TemplateId->getTemplateArgs(), |
8239 | TemplateId->NumArgs); |
8240 | TypeResult T = ActOnTypenameType(S: CurScope, TypenameLoc: TypenameKWLoc, SS, |
8241 | TemplateLoc: TemplateId->TemplateKWLoc, |
8242 | TemplateName: TemplateId->Template, TemplateII: TemplateId->Name, |
8243 | TemplateIILoc: TemplateId->TemplateNameLoc, |
8244 | LAngleLoc: TemplateId->LAngleLoc, TemplateArgs: ArgsPtr, |
8245 | RAngleLoc: TemplateId->RAngleLoc); |
8246 | if (T.isInvalid()) |
8247 | return nullptr; |
8248 | if (GetTypeFromParser(Ty: T.get(), TInfo: &TSI).isNull()) |
8249 | return nullptr; |
8250 | } |
8251 | return BuildTypeRequirement(Type: TSI); |
8252 | } |
8253 | |
8254 | concepts::Requirement * |
8255 | Sema::ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc) { |
8256 | return BuildExprRequirement(E, /*IsSimple=*/IsSatisfied: false, NoexceptLoc, |
8257 | /*ReturnTypeRequirement=*/{}); |
8258 | } |
8259 | |
8260 | concepts::Requirement * |
8261 | Sema::ActOnCompoundRequirement( |
8262 | Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS, |
8263 | TemplateIdAnnotation *TypeConstraint, unsigned Depth) { |
8264 | // C++2a [expr.prim.req.compound] p1.3.3 |
8265 | // [..] the expression is deduced against an invented function template |
8266 | // F [...] F is a void function template with a single type template |
8267 | // parameter T declared with the constrained-parameter. Form a new |
8268 | // cv-qualifier-seq cv by taking the union of const and volatile specifiers |
8269 | // around the constrained-parameter. F has a single parameter whose |
8270 | // type-specifier is cv T followed by the abstract-declarator. [...] |
8271 | // |
8272 | // The cv part is done in the calling function - we get the concept with |
8273 | // arguments and the abstract declarator with the correct CV qualification and |
8274 | // have to synthesize T and the single parameter of F. |
8275 | auto &II = Context.Idents.get(Name: "expr-type"); |
8276 | auto *TParam = TemplateTypeParmDecl::Create(C: Context, DC: CurContext, |
8277 | KeyLoc: SourceLocation(), |
8278 | NameLoc: SourceLocation(), D: Depth, |
8279 | /*Index=*/P: 0, Id: &II, |
8280 | /*Typename=*/true, |
8281 | /*ParameterPack=*/false, |
8282 | /*HasTypeConstraint=*/true); |
8283 | |
8284 | if (BuildTypeConstraint(SS, TypeConstraint, ConstrainedParameter: TParam, |
8285 | /*EllipsisLoc=*/SourceLocation(), |
8286 | /*AllowUnexpandedPack=*/true)) |
8287 | // Just produce a requirement with no type requirements. |
8288 | return BuildExprRequirement(E, /*IsSimple=*/IsSatisfied: false, NoexceptLoc, ReturnTypeRequirement: {}); |
8289 | |
8290 | auto *TPL = TemplateParameterList::Create(C: Context, TemplateLoc: SourceLocation(), |
8291 | LAngleLoc: SourceLocation(), |
8292 | Params: ArrayRef<NamedDecl *>(TParam), |
8293 | RAngleLoc: SourceLocation(), |
8294 | /*RequiresClause=*/nullptr); |
8295 | return BuildExprRequirement( |
8296 | E, /*IsSimple=*/IsSatisfied: false, NoexceptLoc, |
8297 | ReturnTypeRequirement: concepts::ExprRequirement::ReturnTypeRequirement(TPL)); |
8298 | } |
8299 | |
8300 | concepts::ExprRequirement * |
8301 | Sema::BuildExprRequirement( |
8302 | Expr *E, bool IsSimple, SourceLocation NoexceptLoc, |
8303 | concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) { |
8304 | auto Status = concepts::ExprRequirement::SS_Satisfied; |
8305 | ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr; |
8306 | if (E->isInstantiationDependent() || E->getType()->isPlaceholderType() || |
8307 | ReturnTypeRequirement.isDependent()) |
8308 | Status = concepts::ExprRequirement::SS_Dependent; |
8309 | else if (NoexceptLoc.isValid() && canThrow(E) == CanThrowResult::CT_Can) |
8310 | Status = concepts::ExprRequirement::SS_NoexceptNotMet; |
8311 | else if (ReturnTypeRequirement.isSubstitutionFailure()) |
8312 | Status = concepts::ExprRequirement::SS_TypeRequirementSubstitutionFailure; |
8313 | else if (ReturnTypeRequirement.isTypeConstraint()) { |
8314 | // C++2a [expr.prim.req]p1.3.3 |
8315 | // The immediately-declared constraint ([temp]) of decltype((E)) shall |
8316 | // be satisfied. |
8317 | TemplateParameterList *TPL = |
8318 | ReturnTypeRequirement.getTypeConstraintTemplateParameterList(); |
8319 | QualType MatchedType = |
8320 | Context.getReferenceQualifiedType(e: E).getCanonicalType(); |
8321 | llvm::SmallVector<TemplateArgument, 1> Args; |
8322 | Args.push_back(Elt: TemplateArgument(MatchedType)); |
8323 | |
8324 | auto *Param = cast<TemplateTypeParmDecl>(Val: TPL->getParam(Idx: 0)); |
8325 | |
8326 | MultiLevelTemplateArgumentList MLTAL(Param, Args, /*Final=*/false); |
8327 | MLTAL.addOuterRetainedLevels(Num: TPL->getDepth()); |
8328 | const TypeConstraint *TC = Param->getTypeConstraint(); |
8329 | assert(TC && "Type Constraint cannot be null here"); |
8330 | auto *IDC = TC->getImmediatelyDeclaredConstraint(); |
8331 | assert(IDC && "ImmediatelyDeclaredConstraint can't be null here."); |
8332 | ExprResult Constraint = SubstExpr(E: IDC, TemplateArgs: MLTAL); |
8333 | if (Constraint.isInvalid()) { |
8334 | return new (Context) concepts::ExprRequirement( |
8335 | createSubstDiagAt(Location: IDC->getExprLoc(), |
8336 | Printer: [&](llvm::raw_ostream &OS) { |
8337 | IDC->printPretty(OS, /*Helper=*/nullptr, |
8338 | getPrintingPolicy()); |
8339 | }), |
8340 | IsSimple, NoexceptLoc, ReturnTypeRequirement); |
8341 | } |
8342 | SubstitutedConstraintExpr = |
8343 | cast<ConceptSpecializationExpr>(Val: Constraint.get()); |
8344 | if (!SubstitutedConstraintExpr->isSatisfied()) |
8345 | Status = concepts::ExprRequirement::SS_ConstraintsNotSatisfied; |
8346 | } |
8347 | return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc, |
8348 | ReturnTypeRequirement, Status, |
8349 | SubstitutedConstraintExpr); |
8350 | } |
8351 | |
8352 | concepts::ExprRequirement * |
8353 | Sema::BuildExprRequirement( |
8354 | concepts::Requirement::SubstitutionDiagnostic *ExprSubstitutionDiagnostic, |
8355 | bool IsSimple, SourceLocation NoexceptLoc, |
8356 | concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) { |
8357 | return new (Context) concepts::ExprRequirement(ExprSubstitutionDiagnostic, |
8358 | IsSimple, NoexceptLoc, |
8359 | ReturnTypeRequirement); |
8360 | } |
8361 | |
8362 | concepts::TypeRequirement * |
8363 | Sema::BuildTypeRequirement(TypeSourceInfo *Type) { |
8364 | return new (Context) concepts::TypeRequirement(Type); |
8365 | } |
8366 | |
8367 | concepts::TypeRequirement * |
8368 | Sema::BuildTypeRequirement( |
8369 | concepts::Requirement::SubstitutionDiagnostic *SubstDiag) { |
8370 | return new (Context) concepts::TypeRequirement(SubstDiag); |
8371 | } |
8372 | |
8373 | concepts::Requirement *Sema::ActOnNestedRequirement(Expr *Constraint) { |
8374 | return BuildNestedRequirement(E: Constraint); |
8375 | } |
8376 | |
8377 | concepts::NestedRequirement * |
8378 | Sema::BuildNestedRequirement(Expr *Constraint) { |
8379 | ConstraintSatisfaction Satisfaction; |
8380 | if (!Constraint->isInstantiationDependent() && |
8381 | CheckConstraintSatisfaction(nullptr, AssociatedConstraint(Constraint), |
8382 | /*TemplateArgs=*/{}, |
8383 | Constraint->getSourceRange(), Satisfaction)) |
8384 | return nullptr; |
8385 | return new (Context) concepts::NestedRequirement(Context, Constraint, |
8386 | Satisfaction); |
8387 | } |
8388 | |
8389 | concepts::NestedRequirement * |
8390 | Sema::BuildNestedRequirement(StringRef InvalidConstraintEntity, |
8391 | const ASTConstraintSatisfaction &Satisfaction) { |
8392 | return new (Context) concepts::NestedRequirement( |
8393 | InvalidConstraintEntity, |
8394 | ASTConstraintSatisfaction::Rebuild(C: Context, Satisfaction)); |
8395 | } |
8396 | |
8397 | RequiresExprBodyDecl * |
8398 | Sema::ActOnStartRequiresExpr(SourceLocation RequiresKWLoc, |
8399 | ArrayRef<ParmVarDecl *> LocalParameters, |
8400 | Scope *BodyScope) { |
8401 | assert(BodyScope); |
8402 | |
8403 | RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(C&: Context, DC: CurContext, |
8404 | StartLoc: RequiresKWLoc); |
8405 | |
8406 | PushDeclContext(BodyScope, Body); |
8407 | |
8408 | for (ParmVarDecl *Param : LocalParameters) { |
8409 | if (Param->getType()->isVoidType()) { |
8410 | if (LocalParameters.size() > 1) { |
8411 | Diag(Param->getBeginLoc(), diag::err_void_only_param); |
8412 | Param->setType(Context.IntTy); |
8413 | } else if (Param->getIdentifier()) { |
8414 | Diag(Param->getBeginLoc(), diag::err_param_with_void_type); |
8415 | Param->setType(Context.IntTy); |
8416 | } else if (Param->getType().hasQualifiers()) { |
8417 | Diag(Param->getBeginLoc(), diag::err_void_param_qualified); |
8418 | } |
8419 | } else if (Param->hasDefaultArg()) { |
8420 | // C++2a [expr.prim.req] p4 |
8421 | // [...] A local parameter of a requires-expression shall not have a |
8422 | // default argument. [...] |
8423 | Diag(Param->getDefaultArgRange().getBegin(), |
8424 | diag::err_requires_expr_local_parameter_default_argument); |
8425 | // Ignore default argument and move on |
8426 | } else if (Param->isExplicitObjectParameter()) { |
8427 | // C++23 [dcl.fct]p6: |
8428 | // An explicit-object-parameter-declaration is a parameter-declaration |
8429 | // with a this specifier. An explicit-object-parameter-declaration |
8430 | // shall appear only as the first parameter-declaration of a |
8431 | // parameter-declaration-list of either: |
8432 | // - a member-declarator that declares a member function, or |
8433 | // - a lambda-declarator. |
8434 | // |
8435 | // The parameter-declaration-list of a requires-expression is not such |
8436 | // a context. |
8437 | Diag(Param->getExplicitObjectParamThisLoc(), |
8438 | diag::err_requires_expr_explicit_object_parameter); |
8439 | Param->setExplicitObjectParameterLoc(SourceLocation()); |
8440 | } |
8441 | |
8442 | Param->setDeclContext(Body); |
8443 | // If this has an identifier, add it to the scope stack. |
8444 | if (Param->getIdentifier()) { |
8445 | CheckShadow(BodyScope, Param); |
8446 | PushOnScopeChains(Param, BodyScope); |
8447 | } |
8448 | } |
8449 | return Body; |
8450 | } |
8451 | |
8452 | void Sema::ActOnFinishRequiresExpr() { |
8453 | assert(CurContext && "DeclContext imbalance!"); |
8454 | CurContext = CurContext->getLexicalParent(); |
8455 | assert(CurContext && "Popped translation unit!"); |
8456 | } |
8457 | |
8458 | ExprResult Sema::ActOnRequiresExpr( |
8459 | SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body, |
8460 | SourceLocation LParenLoc, ArrayRef<ParmVarDecl *> LocalParameters, |
8461 | SourceLocation RParenLoc, ArrayRef<concepts::Requirement *> Requirements, |
8462 | SourceLocation ClosingBraceLoc) { |
8463 | auto *RE = RequiresExpr::Create(C&: Context, RequiresKWLoc, Body, LParenLoc, |
8464 | LocalParameters, RParenLoc, Requirements, |
8465 | RBraceLoc: ClosingBraceLoc); |
8466 | if (DiagnoseUnexpandedParameterPackInRequiresExpr(RE)) |
8467 | return ExprError(); |
8468 | return RE; |
8469 | } |
8470 |
Definitions
- getInheritingConstructorName
- getConstructorName
- getDestructorName
- getDestructorTypeForDecltype
- checkLiteralOperatorId
- BuildCXXTypeId
- BuildCXXTypeId
- ActOnCXXTypeid
- getUuidAttrOfType
- BuildCXXUuidof
- BuildCXXUuidof
- ActOnCXXUuidof
- ActOnCXXBoolLiteral
- ActOnCXXNullPtrLiteral
- ActOnCXXThrow
- BuildCXXThrow
- collectPublicBases
- getUnambiguousPublicSubobjects
- CheckCXXThrowOperand
- adjustCVQualifiersForCXXThisWithinLambda
- getCurrentThisType
- CXXThisScopeRAII
- ~CXXThisScopeRAII
- buildLambdaThisCaptureFixit
- CheckCXXThisCapture
- ActOnCXXThis
- CheckCXXThisType
- BuildCXXThisExpr
- MarkThisReferenced
- isThisOutsideMemberFunctionBody
- ActOnCXXTypeConstructExpr
- BuildCXXTypeConstructExpr
- isUsualDeallocationFunction
- isNonPlacementDeallocationFunction
- UsualDeallocFnInfo
- UsualDeallocFnInfo
- UsualDeallocFnInfo
- operator bool
- Compare
- hasNewExtendedAlignment
- CheckDeleteOperator
- resolveDeallocationOverload
- doesUsualArrayDeleteWantSize
- ActOnCXXNew
- isLegalArrayNewInitializer
- isUnavailableAlignedAllocationFunction
- diagnoseUnavailableAlignedAllocation
- BuildCXXNew
- CheckAllocatedType
- ResolveMode
- resolveAllocationOverloadInterior
- DeallocLookupMode
- LookupGlobalDeallocationFunctions
- resolveAllocationOverload
- FindAllocationFunctions
- DeclareGlobalNewDelete
- DeclareGlobalAllocationFunction
- FindUsualDeallocationFunction
- FindDeallocationFunctionForDestructor
- FindDeallocationFunction
- MismatchingNewDeleteDetector
- MismatchResult
- MismatchingNewDeleteDetector
- analyzeDeleteExpr
- getNewExprFromInitListOrExpr
- hasMatchingNewInCtorInit
- hasMatchingNewInCtor
- analyzeInClassInitializer
- analyzeField
- analyzeMemberExpr
- hasMatchingVarInit
- DiagnoseMismatchedNewDelete
- AnalyzeDeleteExprMismatch
- AnalyzeDeleteExprMismatch
- ActOnCXXDelete
- resolveBuiltinNewDeleteOverload
- BuiltinOperatorNewDeleteOverloaded
- CheckVirtualDtorCall
- ActOnConditionVariable
- CheckConditionVariable
- CheckCXXBooleanCondition
- IsStringLiteralToNonConstPointerConversion
- BuildCXXCastArgument
- PerformImplicitConversion
- adjustVectorType
- PerformImplicitConversion
- CheckPointerToMemberOperands
- TryClassUnification
- FindConditionalOverload
- ConvertForConditional
- isValidVectorForConditionalCondition
- isValidSizelessVectorForConditionalCondition
- CheckVectorConditionalTypes
- CheckSizelessVectorConditionalTypes
- CXXCheckConditionalOperands
- FindCompositePointerType
- MaybeBindToTemporary
- MaybeCreateExprWithCleanups
- MaybeCreateExprWithCleanups
- MaybeCreateStmtWithCleanups
- ActOnDecltypeExpression
- noteOperatorArrows
- ActOnStartCXXMemberReference
- CheckArrow
- canRecoverDotPseudoDestructorCallsOnPointerObjects
- BuildPseudoDestructorExpr
- ActOnPseudoDestructorExpr
- ActOnPseudoDestructorExpr
- BuildCXXNoexceptExpr
- ActOnNoexceptExpr
- MaybeDecrementCount
- IgnoredValueConversions
- CheckUnevaluatedOperand
- VariableCanNeverBeAConstantExpression
- CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures
- attemptRecovery
- FindTypoExprs
- FindTypoExprs
- VisitTypoExpr
- TransformTypos
- EmitAllDiagnostics
- CheckAndAdvanceTypoExprCorrectionStreams
- getDeclFromExpr
- TryTransform
- CheckForRecursiveTypos
- RecursiveTransformLoop
- TransformTypos
- RebuildCallExpr
- TransformLambdaExpr
- TransformBlockExpr
- Transform
- TransformTypoExpr
- CorrectDelayedTyposInExpr
- ActOnFinishFullExpr
- ActOnFinishFullStmt
- CheckMicrosoftIfExistsSymbol
- CheckMicrosoftIfExistsSymbol
- ActOnSimpleRequirement
- ActOnTypeRequirement
- ActOnCompoundRequirement
- ActOnCompoundRequirement
- BuildExprRequirement
- BuildExprRequirement
- BuildTypeRequirement
- BuildTypeRequirement
- ActOnNestedRequirement
- BuildNestedRequirement
- BuildNestedRequirement
- ActOnStartRequiresExpr
- ActOnFinishRequiresExpr
Update your C++ knowledge – Modern C++11/14/17 Training
Find out more