clang 19.0.0git
SemaExprCXX.cpp
Go to the documentation of this file.
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"
17#include "clang/AST/ASTLambda.h"
19#include "clang/AST/CharUnits.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/ExprCXX.h"
23#include "clang/AST/ExprObjC.h"
25#include "clang/AST/Type.h"
26#include "clang/AST/TypeLoc.h"
34#include "clang/Sema/DeclSpec.h"
37#include "clang/Sema/Lookup.h"
39#include "clang/Sema/Scope.h"
41#include "clang/Sema/SemaCUDA.h"
44#include "clang/Sema/SemaObjC.h"
45#include "clang/Sema/Template.h"
47#include "llvm/ADT/APInt.h"
48#include "llvm/ADT/STLExtras.h"
49#include "llvm/ADT/STLForwardCompat.h"
50#include "llvm/ADT/StringExtras.h"
51#include "llvm/Support/ErrorHandling.h"
52#include "llvm/Support/TypeSize.h"
53#include <optional>
54using namespace clang;
55using namespace sema;
56
57/// Handle the result of the special case name lookup for inheriting
58/// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
59/// constructor names in member using declarations, even if 'X' is not the
60/// name of the corresponding type.
62 SourceLocation NameLoc,
63 const IdentifierInfo &Name) {
65
66 // Convert the nested-name-specifier into a type.
68 switch (NNS->getKind()) {
71 Type = QualType(NNS->getAsType(), 0);
72 break;
73
75 // Strip off the last layer of the nested-name-specifier and build a
76 // typename type for it.
77 assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
80 break;
81
86 llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
87 }
88
89 // This reference to the type is located entirely at the location of the
90 // final identifier in the qualified-id.
93}
94
96 SourceLocation NameLoc, Scope *S,
97 CXXScopeSpec &SS, bool EnteringContext) {
98 CXXRecordDecl *CurClass = getCurrentClass(S, &SS);
99 assert(CurClass && &II == CurClass->getIdentifier() &&
100 "not a constructor name");
101
102 // When naming a constructor as a member of a dependent context (eg, in a
103 // friend declaration or an inherited constructor declaration), form an
104 // unresolved "typename" type.
105 if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) {
107 SS.getScopeRep(), &II);
108 return ParsedType::make(T);
109 }
110
111 if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass))
112 return ParsedType();
113
114 // Find the injected-class-name declaration. Note that we make no attempt to
115 // diagnose cases where the injected-class-name is shadowed: the only
116 // declaration that can validly shadow the injected-class-name is a
117 // non-static data member, and if the class contains both a non-static data
118 // member and a constructor then it is ill-formed (we check that in
119 // CheckCompletedCXXClass).
120 CXXRecordDecl *InjectedClassName = nullptr;
121 for (NamedDecl *ND : CurClass->lookup(&II)) {
122 auto *RD = dyn_cast<CXXRecordDecl>(ND);
123 if (RD && RD->isInjectedClassName()) {
124 InjectedClassName = RD;
125 break;
126 }
127 }
128 if (!InjectedClassName) {
129 if (!CurClass->isInvalidDecl()) {
130 // FIXME: RequireCompleteDeclContext doesn't check dependent contexts
131 // properly. Work around it here for now.
133 diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange();
134 }
135 return ParsedType();
136 }
137
138 QualType T = Context.getTypeDeclType(InjectedClassName);
139 DiagnoseUseOfDecl(InjectedClassName, NameLoc);
140 MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false);
141
142 return ParsedType::make(T);
143}
144
146 SourceLocation NameLoc, Scope *S,
147 CXXScopeSpec &SS, ParsedType ObjectTypePtr,
148 bool EnteringContext) {
149 // Determine where to perform name lookup.
150
151 // FIXME: This area of the standard is very messy, and the current
152 // wording is rather unclear about which scopes we search for the
153 // destructor name; see core issues 399 and 555. Issue 399 in
154 // particular shows where the current description of destructor name
155 // lookup is completely out of line with existing practice, e.g.,
156 // this appears to be ill-formed:
157 //
158 // namespace N {
159 // template <typename T> struct S {
160 // ~S();
161 // };
162 // }
163 //
164 // void f(N::S<int>* s) {
165 // s->N::S<int>::~S();
166 // }
167 //
168 // See also PR6358 and PR6359.
169 //
170 // For now, we accept all the cases in which the name given could plausibly
171 // be interpreted as a correct destructor name, issuing off-by-default
172 // extension diagnostics on the cases that don't strictly conform to the
173 // C++20 rules. This basically means we always consider looking in the
174 // nested-name-specifier prefix, the complete nested-name-specifier, and
175 // the scope, and accept if we find the expected type in any of the three
176 // places.
177
178 if (SS.isInvalid())
179 return nullptr;
180
181 // Whether we've failed with a diagnostic already.
182 bool Failed = false;
183
186
187 // If we have an object type, it's because we are in a
188 // pseudo-destructor-expression or a member access expression, and
189 // we know what type we're looking for.
190 QualType SearchType =
191 ObjectTypePtr ? GetTypeFromParser(ObjectTypePtr) : QualType();
192
193 auto CheckLookupResult = [&](LookupResult &Found) -> ParsedType {
194 auto IsAcceptableResult = [&](NamedDecl *D) -> bool {
195 auto *Type = dyn_cast<TypeDecl>(D->getUnderlyingDecl());
196 if (!Type)
197 return false;
198
199 if (SearchType.isNull() || SearchType->isDependentType())
200 return true;
201
203 return Context.hasSameUnqualifiedType(T, SearchType);
204 };
205
206 unsigned NumAcceptableResults = 0;
207 for (NamedDecl *D : Found) {
208 if (IsAcceptableResult(D))
209 ++NumAcceptableResults;
210
211 // Don't list a class twice in the lookup failure diagnostic if it's
212 // found by both its injected-class-name and by the name in the enclosing
213 // scope.
214 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
215 if (RD->isInjectedClassName())
216 D = cast<NamedDecl>(RD->getParent());
217
218 if (FoundDeclSet.insert(D).second)
219 FoundDecls.push_back(D);
220 }
221
222 // As an extension, attempt to "fix" an ambiguity by erasing all non-type
223 // results, and all non-matching results if we have a search type. It's not
224 // clear what the right behavior is if destructor lookup hits an ambiguity,
225 // but other compilers do generally accept at least some kinds of
226 // ambiguity.
227 if (Found.isAmbiguous() && NumAcceptableResults == 1) {
228 Diag(NameLoc, diag::ext_dtor_name_ambiguous);
229 LookupResult::Filter F = Found.makeFilter();
230 while (F.hasNext()) {
231 NamedDecl *D = F.next();
232 if (auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))
233 Diag(D->getLocation(), diag::note_destructor_type_here)
235 else
236 Diag(D->getLocation(), diag::note_destructor_nontype_here);
237
238 if (!IsAcceptableResult(D))
239 F.erase();
240 }
241 F.done();
242 }
243
244 if (Found.isAmbiguous())
245 Failed = true;
246
247 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
248 if (IsAcceptableResult(Type)) {
250 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
251 return CreateParsedType(
254 }
255 }
256
257 return nullptr;
258 };
259
260 bool IsDependent = false;
261
262 auto LookupInObjectType = [&]() -> ParsedType {
263 if (Failed || SearchType.isNull())
264 return nullptr;
265
266 IsDependent |= SearchType->isDependentType();
267
268 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
269 DeclContext *LookupCtx = computeDeclContext(SearchType);
270 if (!LookupCtx)
271 return nullptr;
272 LookupQualifiedName(Found, LookupCtx);
273 return CheckLookupResult(Found);
274 };
275
276 auto LookupInNestedNameSpec = [&](CXXScopeSpec &LookupSS) -> ParsedType {
277 if (Failed)
278 return nullptr;
279
280 IsDependent |= isDependentScopeSpecifier(LookupSS);
281 DeclContext *LookupCtx = computeDeclContext(LookupSS, EnteringContext);
282 if (!LookupCtx)
283 return nullptr;
284
285 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
286 if (RequireCompleteDeclContext(LookupSS, LookupCtx)) {
287 Failed = true;
288 return nullptr;
289 }
290 LookupQualifiedName(Found, LookupCtx);
291 return CheckLookupResult(Found);
292 };
293
294 auto LookupInScope = [&]() -> ParsedType {
295 if (Failed || !S)
296 return nullptr;
297
298 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
299 LookupName(Found, S);
300 return CheckLookupResult(Found);
301 };
302
303 // C++2a [basic.lookup.qual]p6:
304 // In a qualified-id of the form
305 //
306 // nested-name-specifier[opt] type-name :: ~ type-name
307 //
308 // the second type-name is looked up in the same scope as the first.
309 //
310 // We interpret this as meaning that if you do a dual-scope lookup for the
311 // first name, you also do a dual-scope lookup for the second name, per
312 // C++ [basic.lookup.classref]p4:
313 //
314 // If the id-expression in a class member access is a qualified-id of the
315 // form
316 //
317 // class-name-or-namespace-name :: ...
318 //
319 // the class-name-or-namespace-name following the . or -> is first looked
320 // up in the class of the object expression and the name, if found, is used.
321 // Otherwise, it is looked up in the context of the entire
322 // postfix-expression.
323 //
324 // This looks in the same scopes as for an unqualified destructor name:
325 //
326 // C++ [basic.lookup.classref]p3:
327 // If the unqualified-id is ~ type-name, the type-name is looked up
328 // in the context of the entire postfix-expression. If the type T
329 // of the object expression is of a class type C, the type-name is
330 // also looked up in the scope of class C. At least one of the
331 // lookups shall find a name that refers to cv T.
332 //
333 // FIXME: The intent is unclear here. Should type-name::~type-name look in
334 // the scope anyway if it finds a non-matching name declared in the class?
335 // If both lookups succeed and find a dependent result, which result should
336 // we retain? (Same question for p->~type-name().)
337
338 if (NestedNameSpecifier *Prefix =
339 SS.isSet() ? SS.getScopeRep()->getPrefix() : nullptr) {
340 // This is
341 //
342 // nested-name-specifier type-name :: ~ type-name
343 //
344 // Look for the second type-name in the nested-name-specifier.
345 CXXScopeSpec PrefixSS;
346 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
347 if (ParsedType T = LookupInNestedNameSpec(PrefixSS))
348 return T;
349 } else {
350 // This is one of
351 //
352 // type-name :: ~ type-name
353 // ~ type-name
354 //
355 // Look in the scope and (if any) the object type.
356 if (ParsedType T = LookupInScope())
357 return T;
358 if (ParsedType T = LookupInObjectType())
359 return T;
360 }
361
362 if (Failed)
363 return nullptr;
364
365 if (IsDependent) {
366 // We didn't find our type, but that's OK: it's dependent anyway.
367
368 // FIXME: What if we have no nested-name-specifier?
369 QualType T =
371 SS.getWithLocInContext(Context), II, NameLoc);
372 return ParsedType::make(T);
373 }
374
375 // The remaining cases are all non-standard extensions imitating the behavior
376 // of various other compilers.
377 unsigned NumNonExtensionDecls = FoundDecls.size();
378
379 if (SS.isSet()) {
380 // For compatibility with older broken C++ rules and existing code,
381 //
382 // nested-name-specifier :: ~ type-name
383 //
384 // also looks for type-name within the nested-name-specifier.
385 if (ParsedType T = LookupInNestedNameSpec(SS)) {
386 Diag(SS.getEndLoc(), diag::ext_dtor_named_in_wrong_scope)
387 << SS.getRange()
389 ("::" + II.getName()).str());
390 return T;
391 }
392
393 // For compatibility with other compilers and older versions of Clang,
394 //
395 // nested-name-specifier type-name :: ~ type-name
396 //
397 // also looks for type-name in the scope. Unfortunately, we can't
398 // reasonably apply this fallback for dependent nested-name-specifiers.
399 if (SS.isValid() && SS.getScopeRep()->getPrefix()) {
400 if (ParsedType T = LookupInScope()) {
401 Diag(SS.getEndLoc(), diag::ext_qualified_dtor_named_in_lexical_scope)
403 Diag(FoundDecls.back()->getLocation(), diag::note_destructor_type_here)
405 return T;
406 }
407 }
408 }
409
410 // We didn't find anything matching; tell the user what we did find (if
411 // anything).
412
413 // Don't tell the user about declarations we shouldn't have found.
414 FoundDecls.resize(NumNonExtensionDecls);
415
416 // List types before non-types.
417 std::stable_sort(FoundDecls.begin(), FoundDecls.end(),
418 [](NamedDecl *A, NamedDecl *B) {
419 return isa<TypeDecl>(A->getUnderlyingDecl()) >
420 isa<TypeDecl>(B->getUnderlyingDecl());
421 });
422
423 // Suggest a fixit to properly name the destroyed type.
424 auto MakeFixItHint = [&]{
425 const CXXRecordDecl *Destroyed = nullptr;
426 // FIXME: If we have a scope specifier, suggest its last component?
427 if (!SearchType.isNull())
428 Destroyed = SearchType->getAsCXXRecordDecl();
429 else if (S)
430 Destroyed = dyn_cast_or_null<CXXRecordDecl>(S->getEntity());
431 if (Destroyed)
433 Destroyed->getNameAsString());
434 return FixItHint();
435 };
436
437 if (FoundDecls.empty()) {
438 // FIXME: Attempt typo-correction?
439 Diag(NameLoc, diag::err_undeclared_destructor_name)
440 << &II << MakeFixItHint();
441 } else if (!SearchType.isNull() && FoundDecls.size() == 1) {
442 if (auto *TD = dyn_cast<TypeDecl>(FoundDecls[0]->getUnderlyingDecl())) {
443 assert(!SearchType.isNull() &&
444 "should only reject a type result if we have a search type");
446 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
447 << T << SearchType << MakeFixItHint();
448 } else {
449 Diag(NameLoc, diag::err_destructor_expr_nontype)
450 << &II << MakeFixItHint();
451 }
452 } else {
453 Diag(NameLoc, SearchType.isNull() ? diag::err_destructor_name_nontype
454 : diag::err_destructor_expr_mismatch)
455 << &II << SearchType << MakeFixItHint();
456 }
457
458 for (NamedDecl *FoundD : FoundDecls) {
459 if (auto *TD = dyn_cast<TypeDecl>(FoundD->getUnderlyingDecl()))
460 Diag(FoundD->getLocation(), diag::note_destructor_type_here)
462 else
463 Diag(FoundD->getLocation(), diag::note_destructor_nontype_here)
464 << FoundD;
465 }
466
467 return nullptr;
468}
469
471 ParsedType ObjectType) {
473 return nullptr;
474
476 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
477 return nullptr;
478 }
479
481 "unexpected type in getDestructorType");
483
484 // If we know the type of the object, check that the correct destructor
485 // type was named now; we can give better diagnostics this way.
486 QualType SearchType = GetTypeFromParser(ObjectType);
487 if (!SearchType.isNull() && !SearchType->isDependentType() &&
488 !Context.hasSameUnqualifiedType(T, SearchType)) {
489 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
490 << T << SearchType;
491 return nullptr;
492 }
493
494 return ParsedType::make(T);
495}
496
498 const UnqualifiedId &Name, bool IsUDSuffix) {
499 assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId);
500 if (!IsUDSuffix) {
501 // [over.literal] p8
502 //
503 // double operator""_Bq(long double); // OK: not a reserved identifier
504 // double operator"" _Bq(long double); // ill-formed, no diagnostic required
505 const IdentifierInfo *II = Name.Identifier;
507 SourceLocation Loc = Name.getEndLoc();
509 if (auto Hint = FixItHint::CreateReplacement(
510 Name.getSourceRange(),
511 (StringRef("operator\"\"") + II->getName()).str());
512 isReservedInAllContexts(Status)) {
513 Diag(Loc, diag::warn_reserved_extern_symbol)
514 << II << static_cast<int>(Status) << Hint;
515 } else {
516 Diag(Loc, diag::warn_deprecated_literal_operator_id) << II << Hint;
517 }
518 }
519 }
520
521 if (!SS.isValid())
522 return false;
523
524 switch (SS.getScopeRep()->getKind()) {
528 // Per C++11 [over.literal]p2, literal operators can only be declared at
529 // namespace scope. Therefore, this unqualified-id cannot name anything.
530 // Reject it early, because we have no AST representation for this in the
531 // case where the scope is dependent.
532 Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)
533 << SS.getScopeRep();
534 return true;
535
540 return false;
541 }
542
543 llvm_unreachable("unknown nested name specifier kind");
544}
545
546/// Build a C++ typeid expression with a type operand.
548 SourceLocation TypeidLoc,
549 TypeSourceInfo *Operand,
550 SourceLocation RParenLoc) {
551 // C++ [expr.typeid]p4:
552 // The top-level cv-qualifiers of the lvalue expression or the type-id
553 // that is the operand of typeid are always ignored.
554 // If the type of the type-id is a class type or a reference to a class
555 // type, the class shall be completely-defined.
556 Qualifiers Quals;
557 QualType T
558 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
559 Quals);
560 if (T->getAs<RecordType>() &&
561 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
562 return ExprError();
563
565 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
566
567 if (CheckQualifiedFunctionForTypeId(T, TypeidLoc))
568 return ExprError();
569
570 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
571 SourceRange(TypeidLoc, RParenLoc));
572}
573
574/// Build a C++ typeid expression with an expression operand.
576 SourceLocation TypeidLoc,
577 Expr *E,
578 SourceLocation RParenLoc) {
579 bool WasEvaluated = false;
580 if (E && !E->isTypeDependent()) {
581 if (E->hasPlaceholderType()) {
583 if (result.isInvalid()) return ExprError();
584 E = result.get();
585 }
586
587 QualType T = E->getType();
588 if (const RecordType *RecordT = T->getAs<RecordType>()) {
589 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
590 // C++ [expr.typeid]p3:
591 // [...] If the type of the expression is a class type, the class
592 // shall be completely-defined.
593 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
594 return ExprError();
595
596 // C++ [expr.typeid]p3:
597 // When typeid is applied to an expression other than an glvalue of a
598 // polymorphic class type [...] [the] expression is an unevaluated
599 // operand. [...]
600 if (RecordD->isPolymorphic() && E->isGLValue()) {
601 if (isUnevaluatedContext()) {
602 // The operand was processed in unevaluated context, switch the
603 // context and recheck the subexpression.
605 if (Result.isInvalid())
606 return ExprError();
607 E = Result.get();
608 }
609
610 // We require a vtable to query the type at run time.
611 MarkVTableUsed(TypeidLoc, RecordD);
612 WasEvaluated = true;
613 }
614 }
615
617 if (Result.isInvalid())
618 return ExprError();
619 E = Result.get();
620
621 // C++ [expr.typeid]p4:
622 // [...] If the type of the type-id is a reference to a possibly
623 // cv-qualified type, the result of the typeid expression refers to a
624 // std::type_info object representing the cv-unqualified referenced
625 // type.
626 Qualifiers Quals;
627 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
628 if (!Context.hasSameType(T, UnqualT)) {
629 T = UnqualT;
630 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
631 }
632 }
633
635 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
636 << E->getType());
637 else if (!inTemplateInstantiation() &&
638 E->HasSideEffects(Context, WasEvaluated)) {
639 // The expression operand for typeid is in an unevaluated expression
640 // context, so side effects could result in unintended consequences.
641 Diag(E->getExprLoc(), WasEvaluated
642 ? diag::warn_side_effects_typeid
643 : diag::warn_side_effects_unevaluated_context);
644 }
645
646 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
647 SourceRange(TypeidLoc, RParenLoc));
648}
649
650/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
653 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
654 // typeid is not supported in OpenCL.
655 if (getLangOpts().OpenCLCPlusPlus) {
656 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
657 << "typeid");
658 }
659
660 // Find the std::type_info type.
661 if (!getStdNamespace())
662 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
663
664 if (!CXXTypeInfoDecl) {
665 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
666 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
669 // Microsoft's typeinfo doesn't have type_info in std but in the global
670 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
671 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
674 }
675 if (!CXXTypeInfoDecl)
676 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
677 }
678
679 if (!getLangOpts().RTTI) {
680 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
681 }
682
684
685 if (isType) {
686 // The operand is a type; handle it as such.
687 TypeSourceInfo *TInfo = nullptr;
689 &TInfo);
690 if (T.isNull())
691 return ExprError();
692
693 if (!TInfo)
694 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
695
696 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
697 }
698
699 // The operand is an expression.
701 BuildCXXTypeId(TypeInfoType, OpLoc, (Expr *)TyOrExpr, RParenLoc);
702
703 if (!getLangOpts().RTTIData && !Result.isInvalid())
704 if (auto *CTE = dyn_cast<CXXTypeidExpr>(Result.get()))
705 if (CTE->isPotentiallyEvaluated() && !CTE->isMostDerived(Context))
706 Diag(OpLoc, diag::warn_no_typeid_with_rtti_disabled)
707 << (getDiagnostics().getDiagnosticOptions().getFormat() ==
709 return Result;
710}
711
712/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
713/// a single GUID.
714static void
717 // Optionally remove one level of pointer, reference or array indirection.
718 const Type *Ty = QT.getTypePtr();
719 if (QT->isPointerType() || QT->isReferenceType())
720 Ty = QT->getPointeeType().getTypePtr();
721 else if (QT->isArrayType())
722 Ty = Ty->getBaseElementTypeUnsafe();
723
724 const auto *TD = Ty->getAsTagDecl();
725 if (!TD)
726 return;
727
728 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
729 UuidAttrs.insert(Uuid);
730 return;
731 }
732
733 // __uuidof can grab UUIDs from template arguments.
734 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
735 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
736 for (const TemplateArgument &TA : TAL.asArray()) {
737 const UuidAttr *UuidForTA = nullptr;
738 if (TA.getKind() == TemplateArgument::Type)
739 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
740 else if (TA.getKind() == TemplateArgument::Declaration)
741 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
742
743 if (UuidForTA)
744 UuidAttrs.insert(UuidForTA);
745 }
746 }
747}
748
749/// Build a Microsoft __uuidof expression with a type operand.
751 SourceLocation TypeidLoc,
752 TypeSourceInfo *Operand,
753 SourceLocation RParenLoc) {
754 MSGuidDecl *Guid = nullptr;
755 if (!Operand->getType()->isDependentType()) {
757 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
758 if (UuidAttrs.empty())
759 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
760 if (UuidAttrs.size() > 1)
761 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
762 Guid = UuidAttrs.back()->getGuidDecl();
763 }
764
765 return new (Context)
766 CXXUuidofExpr(Type, Operand, Guid, SourceRange(TypeidLoc, RParenLoc));
767}
768
769/// Build a Microsoft __uuidof expression with an expression operand.
771 Expr *E, SourceLocation RParenLoc) {
772 MSGuidDecl *Guid = nullptr;
773 if (!E->getType()->isDependentType()) {
775 // A null pointer results in {00000000-0000-0000-0000-000000000000}.
777 } else {
779 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
780 if (UuidAttrs.empty())
781 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
782 if (UuidAttrs.size() > 1)
783 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
784 Guid = UuidAttrs.back()->getGuidDecl();
785 }
786 }
787
788 return new (Context)
789 CXXUuidofExpr(Type, E, Guid, SourceRange(TypeidLoc, RParenLoc));
790}
791
792/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
795 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
796 QualType GuidType = Context.getMSGuidType();
797 GuidType.addConst();
798
799 if (isType) {
800 // The operand is a type; handle it as such.
801 TypeSourceInfo *TInfo = nullptr;
803 &TInfo);
804 if (T.isNull())
805 return ExprError();
806
807 if (!TInfo)
808 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
809
810 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
811 }
812
813 // The operand is an expression.
814 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
815}
816
817/// ActOnCXXBoolLiteral - Parse {true,false} literals.
820 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
821 "Unknown C++ Boolean value!");
822 return new (Context)
823 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
824}
825
826/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
830}
831
832/// ActOnCXXThrow - Parse throw expressions.
835 bool IsThrownVarInScope = false;
836 if (Ex) {
837 // C++0x [class.copymove]p31:
838 // When certain criteria are met, an implementation is allowed to omit the
839 // copy/move construction of a class object [...]
840 //
841 // - in a throw-expression, when the operand is the name of a
842 // non-volatile automatic object (other than a function or catch-
843 // clause parameter) whose scope does not extend beyond the end of the
844 // innermost enclosing try-block (if there is one), the copy/move
845 // operation from the operand to the exception object (15.1) can be
846 // omitted by constructing the automatic object directly into the
847 // exception object
848 if (const auto *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
849 if (const auto *Var = dyn_cast<VarDecl>(DRE->getDecl());
850 Var && Var->hasLocalStorage() &&
851 !Var->getType().isVolatileQualified()) {
852 for (; S; S = S->getParent()) {
853 if (S->isDeclScope(Var)) {
854 IsThrownVarInScope = true;
855 break;
856 }
857
858 // FIXME: Many of the scope checks here seem incorrect.
859 if (S->getFlags() &
862 break;
863 }
864 }
865 }
866
867 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
868}
869
871 bool IsThrownVarInScope) {
872 const llvm::Triple &T = Context.getTargetInfo().getTriple();
873 const bool IsOpenMPGPUTarget =
874 getLangOpts().OpenMPIsTargetDevice && (T.isNVPTX() || T.isAMDGCN());
875 // Don't report an error if 'throw' is used in system headers or in an OpenMP
876 // target region compiled for a GPU architecture.
877 if (!IsOpenMPGPUTarget && !getLangOpts().CXXExceptions &&
878 !getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) {
879 // Delay error emission for the OpenMP device code.
880 targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw";
881 }
882
883 // In OpenMP target regions, we replace 'throw' with a trap on GPU targets.
884 if (IsOpenMPGPUTarget)
885 targetDiag(OpLoc, diag::warn_throw_not_valid_on_target) << T.str();
886
887 // Exceptions aren't allowed in CUDA device code.
888 if (getLangOpts().CUDA)
889 CUDA().DiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
890 << "throw" << llvm::to_underlying(CUDA().CurrentTarget());
891
892 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
893 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
894
895 // Exceptions that escape a compute construct are ill-formed.
896 if (getLangOpts().OpenACC && getCurScope() &&
897 getCurScope()->isInOpenACCComputeConstructScope(Scope::TryScope))
898 Diag(OpLoc, diag::err_acc_branch_in_out_compute_construct)
899 << /*throw*/ 2 << /*out of*/ 0;
900
901 if (Ex && !Ex->isTypeDependent()) {
902 // Initialize the exception result. This implicitly weeds out
903 // abstract types or types with inaccessible copy constructors.
904
905 // C++0x [class.copymove]p31:
906 // When certain criteria are met, an implementation is allowed to omit the
907 // copy/move construction of a class object [...]
908 //
909 // - in a throw-expression, when the operand is the name of a
910 // non-volatile automatic object (other than a function or
911 // catch-clause
912 // parameter) whose scope does not extend beyond the end of the
913 // innermost enclosing try-block (if there is one), the copy/move
914 // operation from the operand to the exception object (15.1) can be
915 // omitted by constructing the automatic object directly into the
916 // exception object
917 NamedReturnInfo NRInfo =
918 IsThrownVarInScope ? getNamedReturnInfo(Ex) : NamedReturnInfo();
919
920 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
921 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
922 return ExprError();
923
924 InitializedEntity Entity =
925 InitializedEntity::InitializeException(OpLoc, ExceptionObjectTy);
926 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRInfo, Ex);
927 if (Res.isInvalid())
928 return ExprError();
929 Ex = Res.get();
930 }
931
932 // PPC MMA non-pointer types are not allowed as throw expr types.
933 if (Ex && Context.getTargetInfo().getTriple().isPPC64())
934 CheckPPCMMAType(Ex->getType(), Ex->getBeginLoc());
935
936 return new (Context)
937 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
938}
939
940static void
942 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
943 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
944 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
945 bool ParentIsPublic) {
946 for (const CXXBaseSpecifier &BS : RD->bases()) {
947 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
948 bool NewSubobject;
949 // Virtual bases constitute the same subobject. Non-virtual bases are
950 // always distinct subobjects.
951 if (BS.isVirtual())
952 NewSubobject = VBases.insert(BaseDecl).second;
953 else
954 NewSubobject = true;
955
956 if (NewSubobject)
957 ++SubobjectsSeen[BaseDecl];
958
959 // Only add subobjects which have public access throughout the entire chain.
960 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
961 if (PublicPath)
962 PublicSubobjectsSeen.insert(BaseDecl);
963
964 // Recurse on to each base subobject.
965 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
966 PublicPath);
967 }
968}
969
972 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
973 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
974 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
975 SubobjectsSeen[RD] = 1;
976 PublicSubobjectsSeen.insert(RD);
977 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
978 /*ParentIsPublic=*/true);
979
980 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
981 // Skip ambiguous objects.
982 if (SubobjectsSeen[PublicSubobject] > 1)
983 continue;
984
985 Objects.push_back(PublicSubobject);
986 }
987}
988
989/// CheckCXXThrowOperand - Validate the operand of a throw.
991 QualType ExceptionObjectTy, Expr *E) {
992 // If the type of the exception would be an incomplete type or a pointer
993 // to an incomplete type other than (cv) void the program is ill-formed.
994 QualType Ty = ExceptionObjectTy;
995 bool isPointer = false;
996 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
997 Ty = Ptr->getPointeeType();
998 isPointer = true;
999 }
1000
1001 // Cannot throw WebAssembly reference type.
1002 if (Ty.isWebAssemblyReferenceType()) {
1003 Diag(ThrowLoc, diag::err_wasm_reftype_tc) << 0 << E->getSourceRange();
1004 return true;
1005 }
1006
1007 // Cannot throw WebAssembly table.
1008 if (isPointer && Ty.isWebAssemblyReferenceType()) {
1009 Diag(ThrowLoc, diag::err_wasm_table_art) << 2 << E->getSourceRange();
1010 return true;
1011 }
1012
1013 if (!isPointer || !Ty->isVoidType()) {
1014 if (RequireCompleteType(ThrowLoc, Ty,
1015 isPointer ? diag::err_throw_incomplete_ptr
1016 : diag::err_throw_incomplete,
1017 E->getSourceRange()))
1018 return true;
1019
1020 if (!isPointer && Ty->isSizelessType()) {
1021 Diag(ThrowLoc, diag::err_throw_sizeless) << Ty << E->getSourceRange();
1022 return true;
1023 }
1024
1025 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
1026 diag::err_throw_abstract_type, E))
1027 return true;
1028 }
1029
1030 // If the exception has class type, we need additional handling.
1032 if (!RD)
1033 return false;
1034
1035 // If we are throwing a polymorphic class type or pointer thereof,
1036 // exception handling will make use of the vtable.
1037 MarkVTableUsed(ThrowLoc, RD);
1038
1039 // If a pointer is thrown, the referenced object will not be destroyed.
1040 if (isPointer)
1041 return false;
1042
1043 // If the class has a destructor, we must be able to call it.
1044 if (!RD->hasIrrelevantDestructor()) {
1048 PDiag(diag::err_access_dtor_exception) << Ty);
1050 return true;
1051 }
1052 }
1053
1054 // The MSVC ABI creates a list of all types which can catch the exception
1055 // object. This list also references the appropriate copy constructor to call
1056 // if the object is caught by value and has a non-trivial copy constructor.
1058 // We are only interested in the public, unambiguous bases contained within
1059 // the exception object. Bases which are ambiguous or otherwise
1060 // inaccessible are not catchable types.
1061 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
1062 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
1063
1064 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
1065 // Attempt to lookup the copy constructor. Various pieces of machinery
1066 // will spring into action, like template instantiation, which means this
1067 // cannot be a simple walk of the class's decls. Instead, we must perform
1068 // lookup and overload resolution.
1069 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
1070 if (!CD || CD->isDeleted())
1071 continue;
1072
1073 // Mark the constructor referenced as it is used by this throw expression.
1075
1076 // Skip this copy constructor if it is trivial, we don't need to record it
1077 // in the catchable type data.
1078 if (CD->isTrivial())
1079 continue;
1080
1081 // The copy constructor is non-trivial, create a mapping from this class
1082 // type to this constructor.
1083 // N.B. The selection of copy constructor is not sensitive to this
1084 // particular throw-site. Lookup will be performed at the catch-site to
1085 // ensure that the copy constructor is, in fact, accessible (via
1086 // friendship or any other means).
1088
1089 // We don't keep the instantiated default argument expressions around so
1090 // we must rebuild them here.
1091 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
1092 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
1093 return true;
1094 }
1095 }
1096 }
1097
1098 // Under the Itanium C++ ABI, memory for the exception object is allocated by
1099 // the runtime with no ability for the compiler to request additional
1100 // alignment. Warn if the exception type requires alignment beyond the minimum
1101 // guaranteed by the target C++ runtime.
1103 CharUnits TypeAlign = Context.getTypeAlignInChars(Ty);
1104 CharUnits ExnObjAlign = Context.getExnObjectAlignment();
1105 if (ExnObjAlign < TypeAlign) {
1106 Diag(ThrowLoc, diag::warn_throw_underaligned_obj);
1107 Diag(ThrowLoc, diag::note_throw_underaligned_obj)
1108 << Ty << (unsigned)TypeAlign.getQuantity()
1109 << (unsigned)ExnObjAlign.getQuantity();
1110 }
1111 }
1112 if (!isPointer && getLangOpts().AssumeNothrowExceptionDtor) {
1113 if (CXXDestructorDecl *Dtor = RD->getDestructor()) {
1114 auto Ty = Dtor->getType();
1115 if (auto *FT = Ty.getTypePtr()->getAs<FunctionProtoType>()) {
1116 if (!isUnresolvedExceptionSpec(FT->getExceptionSpecType()) &&
1117 !FT->isNothrow())
1118 Diag(ThrowLoc, diag::err_throw_object_throwing_dtor) << RD;
1119 }
1120 }
1121 }
1122
1123 return false;
1124}
1125
1127 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
1128 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
1129
1130 QualType ClassType = ThisTy->getPointeeType();
1131 LambdaScopeInfo *CurLSI = nullptr;
1132 DeclContext *CurDC = CurSemaContext;
1133
1134 // Iterate through the stack of lambdas starting from the innermost lambda to
1135 // the outermost lambda, checking if '*this' is ever captured by copy - since
1136 // that could change the cv-qualifiers of the '*this' object.
1137 // The object referred to by '*this' starts out with the cv-qualifiers of its
1138 // member function. We then start with the innermost lambda and iterate
1139 // outward checking to see if any lambda performs a by-copy capture of '*this'
1140 // - and if so, any nested lambda must respect the 'constness' of that
1141 // capturing lamdbda's call operator.
1142 //
1143
1144 // Since the FunctionScopeInfo stack is representative of the lexical
1145 // nesting of the lambda expressions during initial parsing (and is the best
1146 // place for querying information about captures about lambdas that are
1147 // partially processed) and perhaps during instantiation of function templates
1148 // that contain lambda expressions that need to be transformed BUT not
1149 // necessarily during instantiation of a nested generic lambda's function call
1150 // operator (which might even be instantiated at the end of the TU) - at which
1151 // time the DeclContext tree is mature enough to query capture information
1152 // reliably - we use a two pronged approach to walk through all the lexically
1153 // enclosing lambda expressions:
1154 //
1155 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
1156 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
1157 // enclosed by the call-operator of the LSI below it on the stack (while
1158 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
1159 // the stack represents the innermost lambda.
1160 //
1161 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
1162 // represents a lambda's call operator. If it does, we must be instantiating
1163 // a generic lambda's call operator (represented by the Current LSI, and
1164 // should be the only scenario where an inconsistency between the LSI and the
1165 // DeclContext should occur), so climb out the DeclContexts if they
1166 // represent lambdas, while querying the corresponding closure types
1167 // regarding capture information.
1168
1169 // 1) Climb down the function scope info stack.
1170 for (int I = FunctionScopes.size();
1171 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
1172 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
1173 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
1174 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
1175 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
1176
1177 if (!CurLSI->isCXXThisCaptured())
1178 continue;
1179
1180 auto C = CurLSI->getCXXThisCapture();
1181
1182 if (C.isCopyCapture()) {
1183 if (CurLSI->lambdaCaptureShouldBeConst())
1184 ClassType.addConst();
1185 return ASTCtx.getPointerType(ClassType);
1186 }
1187 }
1188
1189 // 2) We've run out of ScopeInfos but check 1. if CurDC is a lambda (which
1190 // can happen during instantiation of its nested generic lambda call
1191 // operator); 2. if we're in a lambda scope (lambda body).
1192 if (CurLSI && isLambdaCallOperator(CurDC)) {
1194 "While computing 'this' capture-type for a generic lambda, when we "
1195 "run out of enclosing LSI's, yet the enclosing DC is a "
1196 "lambda-call-operator we must be (i.e. Current LSI) in a generic "
1197 "lambda call oeprator");
1198 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
1199
1200 auto IsThisCaptured =
1201 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1202 IsConst = false;
1203 IsByCopy = false;
1204 for (auto &&C : Closure->captures()) {
1205 if (C.capturesThis()) {
1206 if (C.getCaptureKind() == LCK_StarThis)
1207 IsByCopy = true;
1208 if (Closure->getLambdaCallOperator()->isConst())
1209 IsConst = true;
1210 return true;
1211 }
1212 }
1213 return false;
1214 };
1215
1216 bool IsByCopyCapture = false;
1217 bool IsConstCapture = false;
1218 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1219 while (Closure &&
1220 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1221 if (IsByCopyCapture) {
1222 if (IsConstCapture)
1223 ClassType.addConst();
1224 return ASTCtx.getPointerType(ClassType);
1225 }
1226 Closure = isLambdaCallOperator(Closure->getParent())
1227 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1228 : nullptr;
1229 }
1230 }
1231 return ThisTy;
1232}
1233
1237
1238 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1239 if (method && method->isImplicitObjectMemberFunction())
1240 ThisTy = method->getThisType().getNonReferenceType();
1241 }
1242
1244 inTemplateInstantiation() && isa<CXXRecordDecl>(DC)) {
1245
1246 // This is a lambda call operator that is being instantiated as a default
1247 // initializer. DC must point to the enclosing class type, so we can recover
1248 // the 'this' type from it.
1249 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1250 // There are no cv-qualifiers for 'this' within default initializers,
1251 // per [expr.prim.general]p4.
1252 ThisTy = Context.getPointerType(ClassTy);
1253 }
1254
1255 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1256 // might need to be adjusted if the lambda or any of its enclosing lambda's
1257 // captures '*this' by copy.
1258 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1261 return ThisTy;
1262}
1263
1265 Decl *ContextDecl,
1266 Qualifiers CXXThisTypeQuals,
1267 bool Enabled)
1268 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1269{
1270 if (!Enabled || !ContextDecl)
1271 return;
1272
1273 CXXRecordDecl *Record = nullptr;
1274 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1275 Record = Template->getTemplatedDecl();
1276 else
1277 Record = cast<CXXRecordDecl>(ContextDecl);
1278
1280 T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals);
1281
1283 S.Context.getLangOpts().HLSL ? T : S.Context.getPointerType(T);
1284
1285 this->Enabled = true;
1286}
1287
1288
1290 if (Enabled) {
1291 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1292 }
1293}
1294
1296 SourceLocation DiagLoc = LSI->IntroducerRange.getEnd();
1297 assert(!LSI->isCXXThisCaptured());
1298 // [=, this] {}; // until C++20: Error: this when = is the default
1300 !Sema.getLangOpts().CPlusPlus20)
1301 return;
1302 Sema.Diag(DiagLoc, diag::note_lambda_this_capture_fixit)
1304 DiagLoc, LSI->NumExplicitCaptures > 0 ? ", this" : "this");
1305}
1306
1308 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1309 const bool ByCopy) {
1310 // We don't need to capture this in an unevaluated context.
1311 if (isUnevaluatedContext() && !Explicit)
1312 return true;
1313
1314 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
1315
1316 const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1317 ? *FunctionScopeIndexToStopAt
1318 : FunctionScopes.size() - 1;
1319
1320 // Check that we can capture the *enclosing object* (referred to by '*this')
1321 // by the capturing-entity/closure (lambda/block/etc) at
1322 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1323
1324 // Note: The *enclosing object* can only be captured by-value by a
1325 // closure that is a lambda, using the explicit notation:
1326 // [*this] { ... }.
1327 // Every other capture of the *enclosing object* results in its by-reference
1328 // capture.
1329
1330 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1331 // stack), we can capture the *enclosing object* only if:
1332 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1333 // - or, 'L' has an implicit capture.
1334 // AND
1335 // -- there is no enclosing closure
1336 // -- or, there is some enclosing closure 'E' that has already captured the
1337 // *enclosing object*, and every intervening closure (if any) between 'E'
1338 // and 'L' can implicitly capture the *enclosing object*.
1339 // -- or, every enclosing closure can implicitly capture the
1340 // *enclosing object*
1341
1342
1343 unsigned NumCapturingClosures = 0;
1344 for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
1345 if (CapturingScopeInfo *CSI =
1346 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1347 if (CSI->CXXThisCaptureIndex != 0) {
1348 // 'this' is already being captured; there isn't anything more to do.
1349 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
1350 break;
1351 }
1352 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1354 // This context can't implicitly capture 'this'; fail out.
1355 if (BuildAndDiagnose) {
1357 Diag(Loc, diag::err_this_capture)
1358 << (Explicit && idx == MaxFunctionScopesIndex);
1359 if (!Explicit)
1360 buildLambdaThisCaptureFixit(*this, LSI);
1361 }
1362 return true;
1363 }
1364 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
1365 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
1366 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
1367 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
1368 (Explicit && idx == MaxFunctionScopesIndex)) {
1369 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1370 // iteration through can be an explicit capture, all enclosing closures,
1371 // if any, must perform implicit captures.
1372
1373 // This closure can capture 'this'; continue looking upwards.
1374 NumCapturingClosures++;
1375 continue;
1376 }
1377 // This context can't implicitly capture 'this'; fail out.
1378 if (BuildAndDiagnose) {
1380 Diag(Loc, diag::err_this_capture)
1381 << (Explicit && idx == MaxFunctionScopesIndex);
1382 }
1383 if (!Explicit)
1384 buildLambdaThisCaptureFixit(*this, LSI);
1385 return true;
1386 }
1387 break;
1388 }
1389 if (!BuildAndDiagnose) return false;
1390
1391 // If we got here, then the closure at MaxFunctionScopesIndex on the
1392 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1393 // (including implicit by-reference captures in any enclosing closures).
1394
1395 // In the loop below, respect the ByCopy flag only for the closure requesting
1396 // the capture (i.e. first iteration through the loop below). Ignore it for
1397 // all enclosing closure's up to NumCapturingClosures (since they must be
1398 // implicitly capturing the *enclosing object* by reference (see loop
1399 // above)).
1400 assert((!ByCopy ||
1401 isa<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1402 "Only a lambda can capture the enclosing object (referred to by "
1403 "*this) by copy");
1404 QualType ThisTy = getCurrentThisType();
1405 for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1406 --idx, --NumCapturingClosures) {
1407 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
1408
1409 // The type of the corresponding data member (not a 'this' pointer if 'by
1410 // copy').
1411 QualType CaptureType = ByCopy ? ThisTy->getPointeeType() : ThisTy;
1412
1413 bool isNested = NumCapturingClosures > 1;
1414 CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy);
1415 }
1416 return false;
1417}
1418
1420 // C++20 [expr.prim.this]p1:
1421 // The keyword this names a pointer to the object for which an
1422 // implicit object member function is invoked or a non-static
1423 // data member's initializer is evaluated.
1424 QualType ThisTy = getCurrentThisType();
1425
1426 if (CheckCXXThisType(Loc, ThisTy))
1427 return ExprError();
1428
1429 return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false);
1430}
1431
1433 if (!Type.isNull())
1434 return false;
1435
1436 // C++20 [expr.prim.this]p3:
1437 // If a declaration declares a member function or member function template
1438 // of a class X, the expression this is a prvalue of type
1439 // "pointer to cv-qualifier-seq X" wherever X is the current class between
1440 // the optional cv-qualifier-seq and the end of the function-definition,
1441 // member-declarator, or declarator. It shall not appear within the
1442 // declaration of either a static member function or an explicit object
1443 // member function of the current class (although its type and value
1444 // category are defined within such member functions as they are within
1445 // an implicit object member function).
1447 if (const auto *Method = dyn_cast<CXXMethodDecl>(DC);
1448 Method && Method->isExplicitObjectMemberFunction()) {
1449 Diag(Loc, diag::err_invalid_this_use) << 1;
1451 Diag(Loc, diag::err_invalid_this_use) << 1;
1452 } else {
1453 Diag(Loc, diag::err_invalid_this_use) << 0;
1454 }
1455 return true;
1456}
1457
1459 bool IsImplicit) {
1460 auto *This = CXXThisExpr::Create(Context, Loc, Type, IsImplicit);
1461 MarkThisReferenced(This);
1462 return This;
1463}
1464
1466 CheckCXXThisCapture(This->getExprLoc());
1467 if (This->isTypeDependent())
1468 return;
1469
1470 // Check if 'this' is captured by value in a lambda with a dependent explicit
1471 // object parameter, and mark it as type-dependent as well if so.
1472 auto IsDependent = [&]() {
1473 for (auto *Scope : llvm::reverse(FunctionScopes)) {
1474 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
1475 if (!LSI)
1476 continue;
1477
1478 if (LSI->Lambda && !LSI->Lambda->Encloses(CurContext) &&
1479 LSI->AfterParameterList)
1480 return false;
1481
1482 // If this lambda captures 'this' by value, then 'this' is dependent iff
1483 // this lambda has a dependent explicit object parameter. If we can't
1484 // determine whether it does (e.g. because the CXXMethodDecl's type is
1485 // null), assume it doesn't.
1486 if (LSI->isCXXThisCaptured()) {
1487 if (!LSI->getCXXThisCapture().isCopyCapture())
1488 continue;
1489
1490 const auto *MD = LSI->CallOperator;
1491 if (MD->getType().isNull())
1492 return false;
1493
1494 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
1495 return Ty && MD->isExplicitObjectMemberFunction() &&
1496 Ty->getParamType(0)->isDependentType();
1497 }
1498 }
1499 return false;
1500 }();
1501
1502 This->setCapturedByCopyInLambdaWithExplicitObjectParameter(IsDependent);
1503}
1504
1506 // If we're outside the body of a member function, then we'll have a specified
1507 // type for 'this'.
1509 return false;
1510
1511 // Determine whether we're looking into a class that's currently being
1512 // defined.
1513 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1514 return Class && Class->isBeingDefined();
1515}
1516
1517/// Parse construction of a specified type.
1518/// Can be interpreted either as function-style casting ("int(x)")
1519/// or class type construction ("ClassType(x,y,z)")
1520/// or creation of a value-initialized type ("int()").
1523 SourceLocation LParenOrBraceLoc,
1524 MultiExprArg exprs,
1525 SourceLocation RParenOrBraceLoc,
1526 bool ListInitialization) {
1527 if (!TypeRep)
1528 return ExprError();
1529
1530 TypeSourceInfo *TInfo;
1531 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1532 if (!TInfo)
1534
1535 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1536 RParenOrBraceLoc, ListInitialization);
1537 // Avoid creating a non-type-dependent expression that contains typos.
1538 // Non-type-dependent expressions are liable to be discarded without
1539 // checking for embedded typos.
1540 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1541 !Result.get()->isTypeDependent())
1543 else if (Result.isInvalid())
1545 RParenOrBraceLoc, exprs, Ty);
1546 return Result;
1547}
1548
1551 SourceLocation LParenOrBraceLoc,
1552 MultiExprArg Exprs,
1553 SourceLocation RParenOrBraceLoc,
1554 bool ListInitialization) {
1555 QualType Ty = TInfo->getType();
1556 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
1557 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
1558
1559 InitializedEntity Entity =
1561 InitializationKind Kind =
1562 Exprs.size()
1563 ? ListInitialization
1565 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1566 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1567 RParenOrBraceLoc)
1568 : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1569 RParenOrBraceLoc);
1570
1571 // C++17 [expr.type.conv]p1:
1572 // If the type is a placeholder for a deduced class type, [...perform class
1573 // template argument deduction...]
1574 // C++23:
1575 // Otherwise, if the type contains a placeholder type, it is replaced by the
1576 // type determined by placeholder type deduction.
1577 DeducedType *Deduced = Ty->getContainedDeducedType();
1578 if (Deduced && !Deduced->isDeduced() &&
1579 isa<DeducedTemplateSpecializationType>(Deduced)) {
1581 Kind, Exprs);
1582 if (Ty.isNull())
1583 return ExprError();
1584 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1585 } else if (Deduced && !Deduced->isDeduced()) {
1586 MultiExprArg Inits = Exprs;
1587 if (ListInitialization) {
1588 auto *ILE = cast<InitListExpr>(Exprs[0]);
1589 Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits());
1590 }
1591
1592 if (Inits.empty())
1593 return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_init_no_expression)
1594 << Ty << FullRange);
1595 if (Inits.size() > 1) {
1596 Expr *FirstBad = Inits[1];
1597 return ExprError(Diag(FirstBad->getBeginLoc(),
1598 diag::err_auto_expr_init_multiple_expressions)
1599 << Ty << FullRange);
1600 }
1601 if (getLangOpts().CPlusPlus23) {
1602 if (Ty->getAs<AutoType>())
1603 Diag(TyBeginLoc, diag::warn_cxx20_compat_auto_expr) << FullRange;
1604 }
1605 Expr *Deduce = Inits[0];
1606 if (isa<InitListExpr>(Deduce))
1607 return ExprError(
1608 Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces)
1609 << ListInitialization << Ty << FullRange);
1611 TemplateDeductionInfo Info(Deduce->getExprLoc());
1613 DeduceAutoType(TInfo->getTypeLoc(), Deduce, DeducedType, Info);
1616 return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_deduction_failure)
1617 << Ty << Deduce->getType() << FullRange
1618 << Deduce->getSourceRange());
1619 if (DeducedType.isNull()) {
1621 return ExprError();
1622 }
1623
1624 Ty = DeducedType;
1625 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1626 }
1627
1630 Context, Ty.getNonReferenceType(), TInfo, LParenOrBraceLoc, Exprs,
1631 RParenOrBraceLoc, ListInitialization);
1632
1633 // C++ [expr.type.conv]p1:
1634 // If the expression list is a parenthesized single expression, the type
1635 // conversion expression is equivalent (in definedness, and if defined in
1636 // meaning) to the corresponding cast expression.
1637 if (Exprs.size() == 1 && !ListInitialization &&
1638 !isa<InitListExpr>(Exprs[0])) {
1639 Expr *Arg = Exprs[0];
1640 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1641 RParenOrBraceLoc);
1642 }
1643
1644 // For an expression of the form T(), T shall not be an array type.
1645 QualType ElemTy = Ty;
1646 if (Ty->isArrayType()) {
1647 if (!ListInitialization)
1648 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1649 << FullRange);
1650 ElemTy = Context.getBaseElementType(Ty);
1651 }
1652
1653 // Only construct objects with object types.
1654 // The standard doesn't explicitly forbid function types here, but that's an
1655 // obvious oversight, as there's no way to dynamically construct a function
1656 // in general.
1657 if (Ty->isFunctionType())
1658 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1659 << Ty << FullRange);
1660
1661 // C++17 [expr.type.conv]p2:
1662 // If the type is cv void and the initializer is (), the expression is a
1663 // prvalue of the specified type that performs no initialization.
1664 if (!Ty->isVoidType() &&
1665 RequireCompleteType(TyBeginLoc, ElemTy,
1666 diag::err_invalid_incomplete_type_use, FullRange))
1667 return ExprError();
1668
1669 // Otherwise, the expression is a prvalue of the specified type whose
1670 // result object is direct-initialized (11.6) with the initializer.
1671 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1672 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
1673
1674 if (Result.isInvalid())
1675 return Result;
1676
1677 Expr *Inner = Result.get();
1678 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1679 Inner = BTE->getSubExpr();
1680 if (auto *CE = dyn_cast<ConstantExpr>(Inner);
1681 CE && CE->isImmediateInvocation())
1682 Inner = CE->getSubExpr();
1683 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1684 !isa<CXXScalarValueInitExpr>(Inner)) {
1685 // If we created a CXXTemporaryObjectExpr, that node also represents the
1686 // functional cast. Otherwise, create an explicit cast to represent
1687 // the syntactic form of a functional-style cast that was used here.
1688 //
1689 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1690 // would give a more consistent AST representation than using a
1691 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1692 // is sometimes handled by initialization and sometimes not.
1693 QualType ResultType = Result.get()->getType();
1694 SourceRange Locs = ListInitialization
1695 ? SourceRange()
1696 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1698 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1699 Result.get(), /*Path=*/nullptr, CurFPFeatureOverrides(),
1700 Locs.getBegin(), Locs.getEnd());
1701 }
1702
1703 return Result;
1704}
1705
1707 // [CUDA] Ignore this function, if we can't call it.
1708 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
1709 if (getLangOpts().CUDA) {
1710 auto CallPreference = CUDA().IdentifyPreference(Caller, Method);
1711 // If it's not callable at all, it's not the right function.
1712 if (CallPreference < SemaCUDA::CFP_WrongSide)
1713 return false;
1714 if (CallPreference == SemaCUDA::CFP_WrongSide) {
1715 // Maybe. We have to check if there are better alternatives.
1717 Method->getDeclContext()->lookup(Method->getDeclName());
1718 for (const auto *D : R) {
1719 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1720 if (CUDA().IdentifyPreference(Caller, FD) > SemaCUDA::CFP_WrongSide)
1721 return false;
1722 }
1723 }
1724 // We've found no better variants.
1725 }
1726 }
1727
1729 bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1730
1731 if (Result || !getLangOpts().CUDA || PreventedBy.empty())
1732 return Result;
1733
1734 // In case of CUDA, return true if none of the 1-argument deallocator
1735 // functions are actually callable.
1736 return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {
1737 assert(FD->getNumParams() == 1 &&
1738 "Only single-operand functions should be in PreventedBy");
1739 return CUDA().IdentifyPreference(Caller, FD) >= SemaCUDA::CFP_HostDevice;
1740 });
1741}
1742
1743/// Determine whether the given function is a non-placement
1744/// deallocation function.
1746 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1747 return S.isUsualDeallocationFunction(Method);
1748
1749 if (FD->getOverloadedOperator() != OO_Delete &&
1750 FD->getOverloadedOperator() != OO_Array_Delete)
1751 return false;
1752
1753 unsigned UsualParams = 1;
1754
1755 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1757 FD->getParamDecl(UsualParams)->getType(),
1758 S.Context.getSizeType()))
1759 ++UsualParams;
1760
1761 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1763 FD->getParamDecl(UsualParams)->getType(),
1765 ++UsualParams;
1766
1767 return UsualParams == FD->getNumParams();
1768}
1769
1770namespace {
1771 struct UsualDeallocFnInfo {
1772 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
1773 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
1774 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
1775 Destroying(false), HasSizeT(false), HasAlignValT(false),
1776 CUDAPref(SemaCUDA::CFP_Native) {
1777 // A function template declaration is never a usual deallocation function.
1778 if (!FD)
1779 return;
1780 unsigned NumBaseParams = 1;
1781 if (FD->isDestroyingOperatorDelete()) {
1782 Destroying = true;
1783 ++NumBaseParams;
1784 }
1785
1786 if (NumBaseParams < FD->getNumParams() &&
1788 FD->getParamDecl(NumBaseParams)->getType(),
1789 S.Context.getSizeType())) {
1790 ++NumBaseParams;
1791 HasSizeT = true;
1792 }
1793
1794 if (NumBaseParams < FD->getNumParams() &&
1795 FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) {
1796 ++NumBaseParams;
1797 HasAlignValT = true;
1798 }
1799
1800 // In CUDA, determine how much we'd like / dislike to call this.
1801 if (S.getLangOpts().CUDA)
1802 CUDAPref = S.CUDA().IdentifyPreference(
1803 S.getCurFunctionDecl(/*AllowLambda=*/true), FD);
1804 }
1805
1806 explicit operator bool() const { return FD; }
1807
1808 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1809 bool WantAlign) const {
1810 // C++ P0722:
1811 // A destroying operator delete is preferred over a non-destroying
1812 // operator delete.
1813 if (Destroying != Other.Destroying)
1814 return Destroying;
1815
1816 // C++17 [expr.delete]p10:
1817 // If the type has new-extended alignment, a function with a parameter
1818 // of type std::align_val_t is preferred; otherwise a function without
1819 // such a parameter is preferred
1820 if (HasAlignValT != Other.HasAlignValT)
1821 return HasAlignValT == WantAlign;
1822
1823 if (HasSizeT != Other.HasSizeT)
1824 return HasSizeT == WantSize;
1825
1826 // Use CUDA call preference as a tiebreaker.
1827 return CUDAPref > Other.CUDAPref;
1828 }
1829
1830 DeclAccessPair Found;
1831 FunctionDecl *FD;
1832 bool Destroying, HasSizeT, HasAlignValT;
1834 };
1835}
1836
1837/// Determine whether a type has new-extended alignment. This may be called when
1838/// the type is incomplete (for a delete-expression with an incomplete pointee
1839/// type), in which case it will conservatively return false if the alignment is
1840/// not known.
1841static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1842 return S.getLangOpts().AlignedAllocation &&
1843 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1845}
1846
1847/// Select the correct "usual" deallocation function to use from a selection of
1848/// deallocation functions (either global or class-scope).
1849static UsualDeallocFnInfo resolveDeallocationOverload(
1850 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1851 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1852 UsualDeallocFnInfo Best;
1853
1854 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1855 UsualDeallocFnInfo Info(S, I.getPair());
1856 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1857 Info.CUDAPref == SemaCUDA::CFP_Never)
1858 continue;
1859
1860 if (!Best) {
1861 Best = Info;
1862 if (BestFns)
1863 BestFns->push_back(Info);
1864 continue;
1865 }
1866
1867 if (Best.isBetterThan(Info, WantSize, WantAlign))
1868 continue;
1869
1870 // If more than one preferred function is found, all non-preferred
1871 // functions are eliminated from further consideration.
1872 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
1873 BestFns->clear();
1874
1875 Best = Info;
1876 if (BestFns)
1877 BestFns->push_back(Info);
1878 }
1879
1880 return Best;
1881}
1882
1883/// Determine whether a given type is a class for which 'delete[]' would call
1884/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1885/// we need to store the array size (even if the type is
1886/// trivially-destructible).
1888 QualType allocType) {
1889 const RecordType *record =
1890 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1891 if (!record) return false;
1892
1893 // Try to find an operator delete[] in class scope.
1894
1895 DeclarationName deleteName =
1896 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1897 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1898 S.LookupQualifiedName(ops, record->getDecl());
1899
1900 // We're just doing this for information.
1901 ops.suppressDiagnostics();
1902
1903 // Very likely: there's no operator delete[].
1904 if (ops.empty()) return false;
1905
1906 // If it's ambiguous, it should be illegal to call operator delete[]
1907 // on this thing, so it doesn't matter if we allocate extra space or not.
1908 if (ops.isAmbiguous()) return false;
1909
1910 // C++17 [expr.delete]p10:
1911 // If the deallocation functions have class scope, the one without a
1912 // parameter of type std::size_t is selected.
1913 auto Best = resolveDeallocationOverload(
1914 S, ops, /*WantSize*/false,
1915 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1916 return Best && Best.HasSizeT;
1917}
1918
1919/// Parsed a C++ 'new' expression (C++ 5.3.4).
1920///
1921/// E.g.:
1922/// @code new (memory) int[size][4] @endcode
1923/// or
1924/// @code ::new Foo(23, "hello") @endcode
1925///
1926/// \param StartLoc The first location of the expression.
1927/// \param UseGlobal True if 'new' was prefixed with '::'.
1928/// \param PlacementLParen Opening paren of the placement arguments.
1929/// \param PlacementArgs Placement new arguments.
1930/// \param PlacementRParen Closing paren of the placement arguments.
1931/// \param TypeIdParens If the type is in parens, the source range.
1932/// \param D The type to be allocated, as well as array dimensions.
1933/// \param Initializer The initializing expression or initializer-list, or null
1934/// if there is none.
1936Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1937 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1938 SourceLocation PlacementRParen, SourceRange TypeIdParens,
1940 std::optional<Expr *> ArraySize;
1941 // If the specified type is an array, unwrap it and save the expression.
1942 if (D.getNumTypeObjects() > 0 &&
1944 DeclaratorChunk &Chunk = D.getTypeObject(0);
1945 if (D.getDeclSpec().hasAutoTypeSpec())
1946 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1947 << D.getSourceRange());
1948 if (Chunk.Arr.hasStatic)
1949 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1950 << D.getSourceRange());
1951 if (!Chunk.Arr.NumElts && !Initializer)
1952 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1953 << D.getSourceRange());
1954
1955 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1957 }
1958
1959 // Every dimension shall be of constant size.
1960 if (ArraySize) {
1961 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
1963 break;
1964
1966 if (Expr *NumElts = (Expr *)Array.NumElts) {
1967 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1968 // FIXME: GCC permits constant folding here. We should either do so consistently
1969 // or not do so at all, rather than changing behavior in C++14 onwards.
1970 if (getLangOpts().CPlusPlus14) {
1971 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1972 // shall be a converted constant expression (5.19) of type std::size_t
1973 // and shall evaluate to a strictly positive value.
1974 llvm::APSInt Value(Context.getIntWidth(Context.getSizeType()));
1975 Array.NumElts
1978 .get();
1979 } else {
1980 Array.NumElts =
1982 NumElts, nullptr, diag::err_new_array_nonconst, AllowFold)
1983 .get();
1984 }
1985 if (!Array.NumElts)
1986 return ExprError();
1987 }
1988 }
1989 }
1990 }
1991
1993 QualType AllocType = TInfo->getType();
1994 if (D.isInvalidType())
1995 return ExprError();
1996
1997 SourceRange DirectInitRange;
1998 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1999 DirectInitRange = List->getSourceRange();
2000
2001 return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
2002 PlacementLParen, PlacementArgs, PlacementRParen,
2003 TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
2004 Initializer);
2005}
2006
2008 Expr *Init, bool IsCPlusPlus20) {
2009 if (!Init)
2010 return true;
2011 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
2012 return IsCPlusPlus20 || PLE->getNumExprs() == 0;
2013 if (isa<ImplicitValueInitExpr>(Init))
2014 return true;
2015 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
2016 return !CCE->isListInitialization() &&
2017 CCE->getConstructor()->isDefaultConstructor();
2018 else if (Style == CXXNewInitializationStyle::Braces) {
2019 assert(isa<InitListExpr>(Init) &&
2020 "Shouldn't create list CXXConstructExprs for arrays.");
2021 return true;
2022 }
2023 return false;
2024}
2025
2026bool
2028 if (!getLangOpts().AlignedAllocationUnavailable)
2029 return false;
2030 if (FD.isDefined())
2031 return false;
2032 std::optional<unsigned> AlignmentParam;
2033 if (FD.isReplaceableGlobalAllocationFunction(&AlignmentParam) &&
2034 AlignmentParam)
2035 return true;
2036 return false;
2037}
2038
2039// Emit a diagnostic if an aligned allocation/deallocation function that is not
2040// implemented in the standard library is selected.
2044 const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
2045 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
2046 getASTContext().getTargetInfo().getPlatformName());
2047 VersionTuple OSVersion = alignedAllocMinVersion(T.getOS());
2048
2050 bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete;
2051 Diag(Loc, diag::err_aligned_allocation_unavailable)
2052 << IsDelete << FD.getType().getAsString() << OSName
2053 << OSVersion.getAsString() << OSVersion.empty();
2054 Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
2055 }
2056}
2057
2059 SourceLocation PlacementLParen,
2060 MultiExprArg PlacementArgs,
2061 SourceLocation PlacementRParen,
2062 SourceRange TypeIdParens, QualType AllocType,
2063 TypeSourceInfo *AllocTypeInfo,
2064 std::optional<Expr *> ArraySize,
2065 SourceRange DirectInitRange, Expr *Initializer) {
2066 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
2067 SourceLocation StartLoc = Range.getBegin();
2068
2069 CXXNewInitializationStyle InitStyle;
2070 if (DirectInitRange.isValid()) {
2071 assert(Initializer && "Have parens but no initializer.");
2073 } else if (Initializer && isa<InitListExpr>(Initializer))
2075 else {
2076 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
2077 isa<CXXConstructExpr>(Initializer)) &&
2078 "Initializer expression that cannot have been implicitly created.");
2080 }
2081
2082 MultiExprArg Exprs(&Initializer, Initializer ? 1 : 0);
2083 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
2084 assert(InitStyle == CXXNewInitializationStyle::Parens &&
2085 "paren init for non-call init");
2086 Exprs = MultiExprArg(List->getExprs(), List->getNumExprs());
2087 }
2088
2089 // C++11 [expr.new]p15:
2090 // A new-expression that creates an object of type T initializes that
2091 // object as follows:
2092 InitializationKind Kind = [&] {
2093 switch (InitStyle) {
2094 // - If the new-initializer is omitted, the object is default-
2095 // initialized (8.5); if no initialization is performed,
2096 // the object has indeterminate value
2098 return InitializationKind::CreateDefault(TypeRange.getBegin());
2099 // - Otherwise, the new-initializer is interpreted according to the
2100 // initialization rules of 8.5 for direct-initialization.
2102 return InitializationKind::CreateDirect(TypeRange.getBegin(),
2103 DirectInitRange.getBegin(),
2104 DirectInitRange.getEnd());
2107 Initializer->getBeginLoc(),
2108 Initializer->getEndLoc());
2109 }
2110 llvm_unreachable("Unknown initialization kind");
2111 }();
2112
2113 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
2114 auto *Deduced = AllocType->getContainedDeducedType();
2115 if (Deduced && !Deduced->isDeduced() &&
2116 isa<DeducedTemplateSpecializationType>(Deduced)) {
2117 if (ArraySize)
2118 return ExprError(
2119 Diag(*ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(),
2120 diag::err_deduced_class_template_compound_type)
2121 << /*array*/ 2
2122 << (*ArraySize ? (*ArraySize)->getSourceRange() : TypeRange));
2123
2124 InitializedEntity Entity
2125 = InitializedEntity::InitializeNew(StartLoc, AllocType);
2127 AllocTypeInfo, Entity, Kind, Exprs);
2128 if (AllocType.isNull())
2129 return ExprError();
2130 } else if (Deduced && !Deduced->isDeduced()) {
2131 MultiExprArg Inits = Exprs;
2132 bool Braced = (InitStyle == CXXNewInitializationStyle::Braces);
2133 if (Braced) {
2134 auto *ILE = cast<InitListExpr>(Exprs[0]);
2135 Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits());
2136 }
2137
2138 if (InitStyle == CXXNewInitializationStyle::None || Inits.empty())
2139 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
2140 << AllocType << TypeRange);
2141 if (Inits.size() > 1) {
2142 Expr *FirstBad = Inits[1];
2143 return ExprError(Diag(FirstBad->getBeginLoc(),
2144 diag::err_auto_new_ctor_multiple_expressions)
2145 << AllocType << TypeRange);
2146 }
2147 if (Braced && !getLangOpts().CPlusPlus17)
2148 Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
2149 << AllocType << TypeRange;
2150 Expr *Deduce = Inits[0];
2151 if (isa<InitListExpr>(Deduce))
2152 return ExprError(
2153 Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces)
2154 << Braced << AllocType << TypeRange);
2156 TemplateDeductionInfo Info(Deduce->getExprLoc());
2158 DeduceAutoType(AllocTypeInfo->getTypeLoc(), Deduce, DeducedType, Info);
2161 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
2162 << AllocType << Deduce->getType() << TypeRange
2163 << Deduce->getSourceRange());
2164 if (DeducedType.isNull()) {
2166 return ExprError();
2167 }
2168 AllocType = DeducedType;
2169 }
2170
2171 // Per C++0x [expr.new]p5, the type being constructed may be a
2172 // typedef of an array type.
2173 if (!ArraySize) {
2174 if (const ConstantArrayType *Array
2175 = Context.getAsConstantArrayType(AllocType)) {
2176 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
2178 TypeRange.getEnd());
2179 AllocType = Array->getElementType();
2180 }
2181 }
2182
2183 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
2184 return ExprError();
2185
2186 if (ArraySize && !checkArrayElementAlignment(AllocType, TypeRange.getBegin()))
2187 return ExprError();
2188
2189 // In ARC, infer 'retaining' for the allocated
2190 if (getLangOpts().ObjCAutoRefCount &&
2191 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2192 AllocType->isObjCLifetimeType()) {
2193 AllocType = Context.getLifetimeQualifiedType(AllocType,
2194 AllocType->getObjCARCImplicitLifetime());
2195 }
2196
2197 QualType ResultType = Context.getPointerType(AllocType);
2198
2199 if (ArraySize && *ArraySize &&
2200 (*ArraySize)->getType()->isNonOverloadPlaceholderType()) {
2201 ExprResult result = CheckPlaceholderExpr(*ArraySize);
2202 if (result.isInvalid()) return ExprError();
2203 ArraySize = result.get();
2204 }
2205 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
2206 // integral or enumeration type with a non-negative value."
2207 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
2208 // enumeration type, or a class type for which a single non-explicit
2209 // conversion function to integral or unscoped enumeration type exists.
2210 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
2211 // std::size_t.
2212 std::optional<uint64_t> KnownArraySize;
2213 if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) {
2214 ExprResult ConvertedSize;
2215 if (getLangOpts().CPlusPlus14) {
2216 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
2217
2218 ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(),
2220
2221 if (!ConvertedSize.isInvalid() &&
2222 (*ArraySize)->getType()->getAs<RecordType>())
2223 // Diagnose the compatibility of this conversion.
2224 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
2225 << (*ArraySize)->getType() << 0 << "'size_t'";
2226 } else {
2227 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
2228 protected:
2229 Expr *ArraySize;
2230
2231 public:
2232 SizeConvertDiagnoser(Expr *ArraySize)
2233 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
2234 ArraySize(ArraySize) {}
2235
2236 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
2237 QualType T) override {
2238 return S.Diag(Loc, diag::err_array_size_not_integral)
2239 << S.getLangOpts().CPlusPlus11 << T;
2240 }
2241
2242 SemaDiagnosticBuilder diagnoseIncomplete(
2243 Sema &S, SourceLocation Loc, QualType T) override {
2244 return S.Diag(Loc, diag::err_array_size_incomplete_type)
2245 << T << ArraySize->getSourceRange();
2246 }
2247
2248 SemaDiagnosticBuilder diagnoseExplicitConv(
2249 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
2250 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
2251 }
2252
2253 SemaDiagnosticBuilder noteExplicitConv(
2254 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2255 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2256 << ConvTy->isEnumeralType() << ConvTy;
2257 }
2258
2259 SemaDiagnosticBuilder diagnoseAmbiguous(
2260 Sema &S, SourceLocation Loc, QualType T) override {
2261 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
2262 }
2263
2264 SemaDiagnosticBuilder noteAmbiguous(
2265 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2266 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2267 << ConvTy->isEnumeralType() << ConvTy;
2268 }
2269
2270 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2271 QualType T,
2272 QualType ConvTy) override {
2273 return S.Diag(Loc,
2274 S.getLangOpts().CPlusPlus11
2275 ? diag::warn_cxx98_compat_array_size_conversion
2276 : diag::ext_array_size_conversion)
2277 << T << ConvTy->isEnumeralType() << ConvTy;
2278 }
2279 } SizeDiagnoser(*ArraySize);
2280
2281 ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize,
2282 SizeDiagnoser);
2283 }
2284 if (ConvertedSize.isInvalid())
2285 return ExprError();
2286
2287 ArraySize = ConvertedSize.get();
2288 QualType SizeType = (*ArraySize)->getType();
2289
2290 if (!SizeType->isIntegralOrUnscopedEnumerationType())
2291 return ExprError();
2292
2293 // C++98 [expr.new]p7:
2294 // The expression in a direct-new-declarator shall have integral type
2295 // with a non-negative value.
2296 //
2297 // Let's see if this is a constant < 0. If so, we reject it out of hand,
2298 // per CWG1464. Otherwise, if it's not a constant, we must have an
2299 // unparenthesized array type.
2300
2301 // We've already performed any required implicit conversion to integer or
2302 // unscoped enumeration type.
2303 // FIXME: Per CWG1464, we are required to check the value prior to
2304 // converting to size_t. This will never find a negative array size in
2305 // C++14 onwards, because Value is always unsigned here!
2306 if (std::optional<llvm::APSInt> Value =
2307 (*ArraySize)->getIntegerConstantExpr(Context)) {
2308 if (Value->isSigned() && Value->isNegative()) {
2309 return ExprError(Diag((*ArraySize)->getBeginLoc(),
2310 diag::err_typecheck_negative_array_size)
2311 << (*ArraySize)->getSourceRange());
2312 }
2313
2314 if (!AllocType->isDependentType()) {
2315 unsigned ActiveSizeBits =
2317 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
2318 return ExprError(
2319 Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large)
2320 << toString(*Value, 10) << (*ArraySize)->getSourceRange());
2321 }
2322
2323 KnownArraySize = Value->getZExtValue();
2324 } else if (TypeIdParens.isValid()) {
2325 // Can't have dynamic array size when the type-id is in parentheses.
2326 Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2327 << (*ArraySize)->getSourceRange()
2328 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2329 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
2330
2331 TypeIdParens = SourceRange();
2332 }
2333
2334 // Note that we do *not* convert the argument in any way. It can
2335 // be signed, larger than size_t, whatever.
2336 }
2337
2338 FunctionDecl *OperatorNew = nullptr;
2339 FunctionDecl *OperatorDelete = nullptr;
2340 unsigned Alignment =
2341 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2342 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2343 bool PassAlignment = getLangOpts().AlignedAllocation &&
2344 Alignment > NewAlignment;
2345
2346 if (CheckArgsForPlaceholders(PlacementArgs))
2347 return ExprError();
2348
2350 if (!AllocType->isDependentType() &&
2351 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
2353 StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope,
2354 AllocType, ArraySize.has_value(), PassAlignment, PlacementArgs,
2355 OperatorNew, OperatorDelete))
2356 return ExprError();
2357
2358 // If this is an array allocation, compute whether the usual array
2359 // deallocation function for the type has a size_t parameter.
2360 bool UsualArrayDeleteWantsSize = false;
2361 if (ArraySize && !AllocType->isDependentType())
2362 UsualArrayDeleteWantsSize =
2363 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
2364
2365 SmallVector<Expr *, 8> AllPlaceArgs;
2366 if (OperatorNew) {
2367 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
2368 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2370
2371 // We've already converted the placement args, just fill in any default
2372 // arguments. Skip the first parameter because we don't have a corresponding
2373 // argument. Skip the second parameter too if we're passing in the
2374 // alignment; we've already filled it in.
2375 unsigned NumImplicitArgs = PassAlignment ? 2 : 1;
2376 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2377 NumImplicitArgs, PlacementArgs, AllPlaceArgs,
2378 CallType))
2379 return ExprError();
2380
2381 if (!AllPlaceArgs.empty())
2382 PlacementArgs = AllPlaceArgs;
2383
2384 // We would like to perform some checking on the given `operator new` call,
2385 // but the PlacementArgs does not contain the implicit arguments,
2386 // namely allocation size and maybe allocation alignment,
2387 // so we need to conjure them.
2388
2389 QualType SizeTy = Context.getSizeType();
2390 unsigned SizeTyWidth = Context.getTypeSize(SizeTy);
2391
2392 llvm::APInt SingleEltSize(
2393 SizeTyWidth, Context.getTypeSizeInChars(AllocType).getQuantity());
2394
2395 // How many bytes do we want to allocate here?
2396 std::optional<llvm::APInt> AllocationSize;
2397 if (!ArraySize && !AllocType->isDependentType()) {
2398 // For non-array operator new, we only want to allocate one element.
2399 AllocationSize = SingleEltSize;
2400 } else if (KnownArraySize && !AllocType->isDependentType()) {
2401 // For array operator new, only deal with static array size case.
2402 bool Overflow;
2403 AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize)
2404 .umul_ov(SingleEltSize, Overflow);
2405 (void)Overflow;
2406 assert(
2407 !Overflow &&
2408 "Expected that all the overflows would have been handled already.");
2409 }
2410
2411 IntegerLiteral AllocationSizeLiteral(
2412 Context, AllocationSize.value_or(llvm::APInt::getZero(SizeTyWidth)),
2413 SizeTy, SourceLocation());
2414 // Otherwise, if we failed to constant-fold the allocation size, we'll
2415 // just give up and pass-in something opaque, that isn't a null pointer.
2416 OpaqueValueExpr OpaqueAllocationSize(SourceLocation(), SizeTy, VK_PRValue,
2417 OK_Ordinary, /*SourceExpr=*/nullptr);
2418
2419 // Let's synthesize the alignment argument in case we will need it.
2420 // Since we *really* want to allocate these on stack, this is slightly ugly
2421 // because there might not be a `std::align_val_t` type.
2423 QualType AlignValT =
2425 IntegerLiteral AlignmentLiteral(
2426 Context,
2427 llvm::APInt(Context.getTypeSize(SizeTy),
2428 Alignment / Context.getCharWidth()),
2429 SizeTy, SourceLocation());
2430 ImplicitCastExpr DesiredAlignment(ImplicitCastExpr::OnStack, AlignValT,
2431 CK_IntegralCast, &AlignmentLiteral,
2433
2434 // Adjust placement args by prepending conjured size and alignment exprs.
2436 CallArgs.reserve(NumImplicitArgs + PlacementArgs.size());
2437 CallArgs.emplace_back(AllocationSize
2438 ? static_cast<Expr *>(&AllocationSizeLiteral)
2439 : &OpaqueAllocationSize);
2440 if (PassAlignment)
2441 CallArgs.emplace_back(&DesiredAlignment);
2442 CallArgs.insert(CallArgs.end(), PlacementArgs.begin(), PlacementArgs.end());
2443
2444 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, CallArgs);
2445
2446 checkCall(OperatorNew, Proto, /*ThisArg=*/nullptr, CallArgs,
2447 /*IsMemberFunction=*/false, StartLoc, Range, CallType);
2448
2449 // Warn if the type is over-aligned and is being allocated by (unaligned)
2450 // global operator new.
2451 if (PlacementArgs.empty() && !PassAlignment &&
2452 (OperatorNew->isImplicit() ||
2453 (OperatorNew->getBeginLoc().isValid() &&
2454 getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
2455 if (Alignment > NewAlignment)
2456 Diag(StartLoc, diag::warn_overaligned_type)
2457 << AllocType
2458 << unsigned(Alignment / Context.getCharWidth())
2459 << unsigned(NewAlignment / Context.getCharWidth());
2460 }
2461 }
2462
2463 // Array 'new' can't have any initializers except empty parentheses.
2464 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2465 // dialect distinction.
2466 if (ArraySize && !isLegalArrayNewInitializer(InitStyle, Initializer,
2468 SourceRange InitRange(Exprs.front()->getBeginLoc(),
2469 Exprs.back()->getEndLoc());
2470 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2471 return ExprError();
2472 }
2473
2474 // If we can perform the initialization, and we've not already done so,
2475 // do it now.
2476 if (!AllocType->isDependentType() &&
2478 // The type we initialize is the complete type, including the array bound.
2479 QualType InitType;
2480 if (KnownArraySize)
2481 InitType = Context.getConstantArrayType(
2482 AllocType,
2483 llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2484 *KnownArraySize),
2485 *ArraySize, ArraySizeModifier::Normal, 0);
2486 else if (ArraySize)
2487 InitType = Context.getIncompleteArrayType(AllocType,
2489 else
2490 InitType = AllocType;
2491
2492 InitializedEntity Entity
2493 = InitializedEntity::InitializeNew(StartLoc, InitType);
2494 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
2495 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, Exprs);
2496 if (FullInit.isInvalid())
2497 return ExprError();
2498
2499 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2500 // we don't want the initialized object to be destructed.
2501 // FIXME: We should not create these in the first place.
2502 if (CXXBindTemporaryExpr *Binder =
2503 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
2504 FullInit = Binder->getSubExpr();
2505
2506 Initializer = FullInit.get();
2507
2508 // FIXME: If we have a KnownArraySize, check that the array bound of the
2509 // initializer is no greater than that constant value.
2510
2511 if (ArraySize && !*ArraySize) {
2512 auto *CAT = Context.getAsConstantArrayType(Initializer->getType());
2513 if (CAT) {
2514 // FIXME: Track that the array size was inferred rather than explicitly
2515 // specified.
2516 ArraySize = IntegerLiteral::Create(
2517 Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd());
2518 } else {
2519 Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init)
2520 << Initializer->getSourceRange();
2521 }
2522 }
2523 }
2524
2525 // Mark the new and delete operators as referenced.
2526 if (OperatorNew) {
2527 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2528 return ExprError();
2529 MarkFunctionReferenced(StartLoc, OperatorNew);
2530 }
2531 if (OperatorDelete) {
2532 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2533 return ExprError();
2534 MarkFunctionReferenced(StartLoc, OperatorDelete);
2535 }
2536
2537 return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete,
2538 PassAlignment, UsualArrayDeleteWantsSize,
2539 PlacementArgs, TypeIdParens, ArraySize, InitStyle,
2540 Initializer, ResultType, AllocTypeInfo, Range,
2541 DirectInitRange);
2542}
2543
2544/// Checks that a type is suitable as the allocated type
2545/// in a new-expression.
2547 SourceRange R) {
2548 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2549 // abstract class type or array thereof.
2550 if (AllocType->isFunctionType())
2551 return Diag(Loc, diag::err_bad_new_type)
2552 << AllocType << 0 << R;
2553 else if (AllocType->isReferenceType())
2554 return Diag(Loc, diag::err_bad_new_type)
2555 << AllocType << 1 << R;
2556 else if (!AllocType->isDependentType() &&
2558 Loc, AllocType, diag::err_new_incomplete_or_sizeless_type, R))
2559 return true;
2560 else if (RequireNonAbstractType(Loc, AllocType,
2561 diag::err_allocation_of_abstract_type))
2562 return true;
2563 else if (AllocType->isVariablyModifiedType())
2564 return Diag(Loc, diag::err_variably_modified_new_type)
2565 << AllocType;
2566 else if (AllocType.getAddressSpace() != LangAS::Default &&
2567 !getLangOpts().OpenCLCPlusPlus)
2568 return Diag(Loc, diag::err_address_space_qualified_new)
2569 << AllocType.getUnqualifiedType()
2571 else if (getLangOpts().ObjCAutoRefCount) {
2572 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2573 QualType BaseAllocType = Context.getBaseElementType(AT);
2574 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2575 BaseAllocType->isObjCLifetimeType())
2576 return Diag(Loc, diag::err_arc_new_array_without_ownership)
2577 << BaseAllocType;
2578 }
2579 }
2580
2581 return false;
2582}
2583
2586 bool &PassAlignment, FunctionDecl *&Operator,
2587 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
2588 OverloadCandidateSet Candidates(R.getNameLoc(),
2590 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2591 Alloc != AllocEnd; ++Alloc) {
2592 // Even member operator new/delete are implicitly treated as
2593 // static, so don't use AddMemberCandidate.
2594 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2595
2596 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2597 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2598 /*ExplicitTemplateArgs=*/nullptr, Args,
2599 Candidates,
2600 /*SuppressUserConversions=*/false);
2601 continue;
2602 }
2603
2604 FunctionDecl *Fn = cast<FunctionDecl>(D);
2605 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2606 /*SuppressUserConversions=*/false);
2607 }
2608
2609 // Do the resolution.
2611 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2612 case OR_Success: {
2613 // Got one!
2614 FunctionDecl *FnDecl = Best->Function;
2616 Best->FoundDecl) == Sema::AR_inaccessible)
2617 return true;
2618
2619 Operator = FnDecl;
2620 return false;
2621 }
2622
2624 // C++17 [expr.new]p13:
2625 // If no matching function is found and the allocated object type has
2626 // new-extended alignment, the alignment argument is removed from the
2627 // argument list, and overload resolution is performed again.
2628 if (PassAlignment) {
2629 PassAlignment = false;
2630 AlignArg = Args[1];
2631 Args.erase(Args.begin() + 1);
2632 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2633 Operator, &Candidates, AlignArg,
2634 Diagnose);
2635 }
2636
2637 // MSVC will fall back on trying to find a matching global operator new
2638 // if operator new[] cannot be found. Also, MSVC will leak by not
2639 // generating a call to operator delete or operator delete[], but we
2640 // will not replicate that bug.
2641 // FIXME: Find out how this interacts with the std::align_val_t fallback
2642 // once MSVC implements it.
2643 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2644 S.Context.getLangOpts().MSVCCompat) {
2645 R.clear();
2648 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2649 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2650 Operator, /*Candidates=*/nullptr,
2651 /*AlignArg=*/nullptr, Diagnose);
2652 }
2653
2654 if (Diagnose) {
2655 // If this is an allocation of the form 'new (p) X' for some object
2656 // pointer p (or an expression that will decay to such a pointer),
2657 // diagnose the missing inclusion of <new>.
2658 if (!R.isClassLookup() && Args.size() == 2 &&
2659 (Args[1]->getType()->isObjectPointerType() ||
2660 Args[1]->getType()->isArrayType())) {
2661 S.Diag(R.getNameLoc(), diag::err_need_header_before_placement_new)
2662 << R.getLookupName() << Range;
2663 // Listing the candidates is unlikely to be useful; skip it.
2664 return true;
2665 }
2666
2667 // Finish checking all candidates before we note any. This checking can
2668 // produce additional diagnostics so can't be interleaved with our
2669 // emission of notes.
2670 //
2671 // For an aligned allocation, separately check the aligned and unaligned
2672 // candidates with their respective argument lists.
2675 llvm::SmallVector<Expr*, 4> AlignedArgs;
2676 if (AlignedCandidates) {
2677 auto IsAligned = [](OverloadCandidate &C) {
2678 return C.Function->getNumParams() > 1 &&
2679 C.Function->getParamDecl(1)->getType()->isAlignValT();
2680 };
2681 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2682
2683 AlignedArgs.reserve(Args.size() + 1);
2684 AlignedArgs.push_back(Args[0]);
2685 AlignedArgs.push_back(AlignArg);
2686 AlignedArgs.append(Args.begin() + 1, Args.end());
2687 AlignedCands = AlignedCandidates->CompleteCandidates(
2688 S, OCD_AllCandidates, AlignedArgs, R.getNameLoc(), IsAligned);
2689
2690 Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,
2691 R.getNameLoc(), IsUnaligned);
2692 } else {
2693 Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,
2694 R.getNameLoc());
2695 }
2696
2697 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2698 << R.getLookupName() << Range;
2699 if (AlignedCandidates)
2700 AlignedCandidates->NoteCandidates(S, AlignedArgs, AlignedCands, "",
2701 R.getNameLoc());
2702 Candidates.NoteCandidates(S, Args, Cands, "", R.getNameLoc());
2703 }
2704 return true;
2705
2706 case OR_Ambiguous:
2707 if (Diagnose) {
2708 Candidates.NoteCandidates(
2710 S.PDiag(diag::err_ovl_ambiguous_call)
2711 << R.getLookupName() << Range),
2712 S, OCD_AmbiguousCandidates, Args);
2713 }
2714 return true;
2715
2716 case OR_Deleted: {
2717 if (Diagnose)
2719 Candidates, Best->Function, Args);
2720 return true;
2721 }
2722 }
2723 llvm_unreachable("Unreachable, bad result from BestViableFunction");
2724}
2725
2727 AllocationFunctionScope NewScope,
2728 AllocationFunctionScope DeleteScope,
2729 QualType AllocType, bool IsArray,
2730 bool &PassAlignment, MultiExprArg PlaceArgs,
2731 FunctionDecl *&OperatorNew,
2732 FunctionDecl *&OperatorDelete,
2733 bool Diagnose) {
2734 // --- Choosing an allocation function ---
2735 // C++ 5.3.4p8 - 14 & 18
2736 // 1) If looking in AFS_Global scope for allocation functions, only look in
2737 // the global scope. Else, if AFS_Class, only look in the scope of the
2738 // allocated class. If AFS_Both, look in both.
2739 // 2) If an array size is given, look for operator new[], else look for
2740 // operator new.
2741 // 3) The first argument is always size_t. Append the arguments from the
2742 // placement form.
2743
2744 SmallVector<Expr*, 8> AllocArgs;
2745 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2746
2747 // We don't care about the actual value of these arguments.
2748 // FIXME: Should the Sema create the expression and embed it in the syntax
2749 // tree? Or should the consumer just recalculate the value?
2750 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
2751 QualType SizeTy = Context.getSizeType();
2752 unsigned SizeTyWidth = Context.getTypeSize(SizeTy);
2753 IntegerLiteral Size(Context, llvm::APInt::getZero(SizeTyWidth), SizeTy,
2754 SourceLocation());
2755 AllocArgs.push_back(&Size);
2756
2757 QualType AlignValT = Context.VoidTy;
2758 if (PassAlignment) {
2761 }
2762 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2763 if (PassAlignment)
2764 AllocArgs.push_back(&Align);
2765
2766 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
2767
2768 // C++ [expr.new]p8:
2769 // If the allocated type is a non-array type, the allocation
2770 // function's name is operator new and the deallocation function's
2771 // name is operator delete. If the allocated type is an array
2772 // type, the allocation function's name is operator new[] and the
2773 // deallocation function's name is operator delete[].
2775 IsArray ? OO_Array_New : OO_New);
2776
2777 QualType AllocElemType = Context.getBaseElementType(AllocType);
2778
2779 // Find the allocation function.
2780 {
2781 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2782
2783 // C++1z [expr.new]p9:
2784 // If the new-expression begins with a unary :: operator, the allocation
2785 // function's name is looked up in the global scope. Otherwise, if the
2786 // allocated type is a class type T or array thereof, the allocation
2787 // function's name is looked up in the scope of T.
2788 if (AllocElemType->isRecordType() && NewScope != AFS_Global)
2789 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2790
2791 // We can see ambiguity here if the allocation function is found in
2792 // multiple base classes.
2793 if (R.isAmbiguous())
2794 return true;
2795
2796 // If this lookup fails to find the name, or if the allocated type is not
2797 // a class type, the allocation function's name is looked up in the
2798 // global scope.
2799 if (R.empty()) {
2800 if (NewScope == AFS_Class)
2801 return true;
2802
2804 }
2805
2806 if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
2807 if (PlaceArgs.empty()) {
2808 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2809 } else {
2810 Diag(StartLoc, diag::err_openclcxx_placement_new);
2811 }
2812 return true;
2813 }
2814
2815 assert(!R.empty() && "implicitly declared allocation functions not found");
2816 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2817
2818 // We do our own custom access checks below.
2820
2821 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2822 OperatorNew, /*Candidates=*/nullptr,
2823 /*AlignArg=*/nullptr, Diagnose))
2824 return true;
2825 }
2826
2827 // We don't need an operator delete if we're running under -fno-exceptions.
2828 if (!getLangOpts().Exceptions) {
2829 OperatorDelete = nullptr;
2830 return false;
2831 }
2832
2833 // Note, the name of OperatorNew might have been changed from array to
2834 // non-array by resolveAllocationOverload.
2836 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2837 ? OO_Array_Delete
2838 : OO_Delete);
2839
2840 // C++ [expr.new]p19:
2841 //
2842 // If the new-expression begins with a unary :: operator, the
2843 // deallocation function's name is looked up in the global
2844 // scope. Otherwise, if the allocated type is a class type T or an
2845 // array thereof, the deallocation function's name is looked up in
2846 // the scope of T. If this lookup fails to find the name, or if
2847 // the allocated type is not a class type or array thereof, the
2848 // deallocation function's name is looked up in the global scope.
2849 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
2850 if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
2851 auto *RD =
2852 cast<CXXRecordDecl>(AllocElemType->castAs<RecordType>()->getDecl());
2853 LookupQualifiedName(FoundDelete, RD);
2854 }
2855 if (FoundDelete.isAmbiguous())
2856 return true; // FIXME: clean up expressions?
2857
2858 // Filter out any destroying operator deletes. We can't possibly call such a
2859 // function in this context, because we're handling the case where the object
2860 // was not successfully constructed.
2861 // FIXME: This is not covered by the language rules yet.
2862 {
2863 LookupResult::Filter Filter = FoundDelete.makeFilter();
2864 while (Filter.hasNext()) {
2865 auto *FD = dyn_cast<FunctionDecl>(Filter.next()->getUnderlyingDecl());
2866 if (FD && FD->isDestroyingOperatorDelete())
2867 Filter.erase();
2868 }
2869 Filter.done();
2870 }
2871
2872 bool FoundGlobalDelete = FoundDelete.empty();
2873 if (FoundDelete.empty()) {
2874 FoundDelete.clear(LookupOrdinaryName);
2875
2876 if (DeleteScope == AFS_Class)
2877 return true;
2878
2881 }
2882
2883 FoundDelete.suppressDiagnostics();
2884
2886
2887 // Whether we're looking for a placement operator delete is dictated
2888 // by whether we selected a placement operator new, not by whether
2889 // we had explicit placement arguments. This matters for things like
2890 // struct A { void *operator new(size_t, int = 0); ... };
2891 // A *a = new A()
2892 //
2893 // We don't have any definition for what a "placement allocation function"
2894 // is, but we assume it's any allocation function whose
2895 // parameter-declaration-clause is anything other than (size_t).
2896 //
2897 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2898 // This affects whether an exception from the constructor of an overaligned
2899 // type uses the sized or non-sized form of aligned operator delete.
2900 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2901 OperatorNew->isVariadic();
2902
2903 if (isPlacementNew) {
2904 // C++ [expr.new]p20:
2905 // A declaration of a placement deallocation function matches the
2906 // declaration of a placement allocation function if it has the
2907 // same number of parameters and, after parameter transformations
2908 // (8.3.5), all parameter types except the first are
2909 // identical. [...]
2910 //
2911 // To perform this comparison, we compute the function type that
2912 // the deallocation function should have, and use that type both
2913 // for template argument deduction and for comparison purposes.
2914 QualType ExpectedFunctionType;
2915 {
2916 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
2917
2918 SmallVector<QualType, 4> ArgTypes;
2919 ArgTypes.push_back(Context.VoidPtrTy);
2920 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2921 ArgTypes.push_back(Proto->getParamType(I));
2922
2924 // FIXME: This is not part of the standard's rule.
2925 EPI.Variadic = Proto->isVariadic();
2926
2927 ExpectedFunctionType
2928 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
2929 }
2930
2931 for (LookupResult::iterator D = FoundDelete.begin(),
2932 DEnd = FoundDelete.end();
2933 D != DEnd; ++D) {
2934 FunctionDecl *Fn = nullptr;
2935 if (FunctionTemplateDecl *FnTmpl =
2936 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2937 // Perform template argument deduction to try to match the
2938 // expected function type.
2939 TemplateDeductionInfo Info(StartLoc);
2940 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2942 continue;
2943 } else
2944 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2945
2947 ExpectedFunctionType,
2948 /*AdjustExcpetionSpec*/true),
2949 ExpectedFunctionType))
2950 Matches.push_back(std::make_pair(D.getPair(), Fn));
2951 }
2952
2953 if (getLangOpts().CUDA)
2954 CUDA().EraseUnwantedMatches(getCurFunctionDecl(/*AllowLambda=*/true),
2955 Matches);
2956 } else {
2957 // C++1y [expr.new]p22:
2958 // For a non-placement allocation function, the normal deallocation
2959 // function lookup is used
2960 //
2961 // Per [expr.delete]p10, this lookup prefers a member operator delete
2962 // without a size_t argument, but prefers a non-member operator delete
2963 // with a size_t where possible (which it always is in this case).
2965 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2966 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2967 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2968 &BestDeallocFns);
2969 if (Selected)
2970 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2971 else {
2972 // If we failed to select an operator, all remaining functions are viable
2973 // but ambiguous.
2974 for (auto Fn : BestDeallocFns)
2975 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
2976 }
2977 }
2978
2979 // C++ [expr.new]p20:
2980 // [...] If the lookup finds a single matching deallocation
2981 // function, that function will be called; otherwise, no
2982 // deallocation function will be called.
2983 if (Matches.size() == 1) {
2984 OperatorDelete = Matches[0].second;
2985
2986 // C++1z [expr.new]p23:
2987 // If the lookup finds a usual deallocation function (3.7.4.2)
2988 // with a parameter of type std::size_t and that function, considered
2989 // as a placement deallocation function, would have been
2990 // selected as a match for the allocation function, the program
2991 // is ill-formed.
2992 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
2993 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
2994 UsualDeallocFnInfo Info(*this,
2995 DeclAccessPair::make(OperatorDelete, AS_public));
2996 // Core issue, per mail to core reflector, 2016-10-09:
2997 // If this is a member operator delete, and there is a corresponding
2998 // non-sized member operator delete, this isn't /really/ a sized
2999 // deallocation function, it just happens to have a size_t parameter.
3000 bool IsSizedDelete = Info.HasSizeT;
3001 if (IsSizedDelete && !FoundGlobalDelete) {
3002 auto NonSizedDelete =
3003 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
3004 /*WantAlign*/Info.HasAlignValT);
3005 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
3006 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
3007 IsSizedDelete = false;
3008 }
3009
3010 if (IsSizedDelete) {
3011 SourceRange R = PlaceArgs.empty()
3012 ? SourceRange()
3013 : SourceRange(PlaceArgs.front()->getBeginLoc(),
3014 PlaceArgs.back()->getEndLoc());
3015 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
3016 if (!OperatorDelete->isImplicit())
3017 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
3018 << DeleteName;
3019 }
3020 }
3021
3022 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
3023 Matches[0].first);
3024 } else if (!Matches.empty()) {
3025 // We found multiple suitable operators. Per [expr.new]p20, that means we
3026 // call no 'operator delete' function, but we should at least warn the user.
3027 // FIXME: Suppress this warning if the construction cannot throw.
3028 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
3029 << DeleteName << AllocElemType;
3030
3031 for (auto &Match : Matches)
3032 Diag(Match.second->getLocation(),
3033 diag::note_member_declared_here) << DeleteName;
3034 }
3035
3036 return false;
3037}
3038
3039/// DeclareGlobalNewDelete - Declare the global forms of operator new and
3040/// delete. These are:
3041/// @code
3042/// // C++03:
3043/// void* operator new(std::size_t) throw(std::bad_alloc);
3044/// void* operator new[](std::size_t) throw(std::bad_alloc);
3045/// void operator delete(void *) throw();
3046/// void operator delete[](void *) throw();
3047/// // C++11:
3048/// void* operator new(std::size_t);
3049/// void* operator new[](std::size_t);
3050/// void operator delete(void *) noexcept;
3051/// void operator delete[](void *) noexcept;
3052/// // C++1y:
3053/// void* operator new(std::size_t);
3054/// void* operator new[](std::size_t);
3055/// void operator delete(void *) noexcept;
3056/// void operator delete[](void *) noexcept;
3057/// void operator delete(void *, std::size_t) noexcept;
3058/// void operator delete[](void *, std::size_t) noexcept;
3059/// @endcode
3060/// Note that the placement and nothrow forms of new are *not* implicitly
3061/// declared. Their use requires including <new>.
3064 return;
3065
3066 // The implicitly declared new and delete operators
3067 // are not supported in OpenCL.
3068 if (getLangOpts().OpenCLCPlusPlus)
3069 return;
3070
3071 // C++ [basic.stc.dynamic.general]p2:
3072 // The library provides default definitions for the global allocation
3073 // and deallocation functions. Some global allocation and deallocation
3074 // functions are replaceable ([new.delete]); these are attached to the
3075 // global module ([module.unit]).
3076 if (getLangOpts().CPlusPlusModules && getCurrentModule())
3077 PushGlobalModuleFragment(SourceLocation());
3078
3079 // C++ [basic.std.dynamic]p2:
3080 // [...] The following allocation and deallocation functions (18.4) are
3081 // implicitly declared in global scope in each translation unit of a
3082 // program
3083 //
3084 // C++03:
3085 // void* operator new(std::size_t) throw(std::bad_alloc);
3086 // void* operator new[](std::size_t) throw(std::bad_alloc);
3087 // void operator delete(void*) throw();
3088 // void operator delete[](void*) throw();
3089 // C++11:
3090 // void* operator new(std::size_t);
3091 // void* operator new[](std::size_t);
3092 // void operator delete(void*) noexcept;
3093 // void operator delete[](void*) noexcept;
3094 // C++1y:
3095 // void* operator new(std::size_t);
3096 // void* operator new[](std::size_t);
3097 // void operator delete(void*) noexcept;
3098 // void operator delete[](void*) noexcept;
3099 // void operator delete(void*, std::size_t) noexcept;
3100 // void operator delete[](void*, std::size_t) noexcept;
3101 //
3102 // These implicit declarations introduce only the function names operator
3103 // new, operator new[], operator delete, operator delete[].
3104 //
3105 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
3106 // "std" or "bad_alloc" as necessary to form the exception specification.
3107 // However, we do not make these implicit declarations visible to name
3108 // lookup.
3109 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
3110 // The "std::bad_alloc" class has not yet been declared, so build it
3111 // implicitly.
3115 &PP.getIdentifierTable().get("bad_alloc"), nullptr);
3116 getStdBadAlloc()->setImplicit(true);
3117
3118 // The implicitly declared "std::bad_alloc" should live in global module
3119 // fragment.
3120 if (TheGlobalModuleFragment) {
3123 getStdBadAlloc()->setLocalOwningModule(TheGlobalModuleFragment);
3124 }
3125 }
3126 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
3127 // The "std::align_val_t" enum class has not yet been declared, so build it
3128 // implicitly.
3129 auto *AlignValT = EnumDecl::Create(
3131 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
3132
3133 // The implicitly declared "std::align_val_t" should live in global module
3134 // fragment.
3135 if (TheGlobalModuleFragment) {
3136 AlignValT->setModuleOwnershipKind(
3138 AlignValT->setLocalOwningModule(TheGlobalModuleFragment);
3139 }
3140
3141 AlignValT->setIntegerType(Context.getSizeType());
3142 AlignValT->setPromotionType(Context.getSizeType());
3143 AlignValT->setImplicit(true);
3144
3145 StdAlignValT = AlignValT;
3146 }
3147
3149
3151 QualType SizeT = Context.getSizeType();
3152
3153 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
3154 QualType Return, QualType Param) {
3156 Params.push_back(Param);
3157
3158 // Create up to four variants of the function (sized/aligned).
3159 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
3160 (Kind == OO_Delete || Kind == OO_Array_Delete);
3161 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
3162
3163 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
3164 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
3165 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
3166 if (Sized)
3167 Params.push_back(SizeT);
3168
3169 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
3170 if (Aligned)
3171 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
3172
3174 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
3175
3176 if (Aligned)
3177 Params.pop_back();
3178 }
3179 }
3180 };
3181
3182 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
3183 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
3184 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
3185 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
3186
3187 if (getLangOpts().CPlusPlusModules && getCurrentModule())
3188 PopGlobalModuleFragment();
3189}
3190
3191/// DeclareGlobalAllocationFunction - Declares a single implicit global
3192/// allocation function if it doesn't already exist.
3194 QualType Return,
3195 ArrayRef<QualType> Params) {
3197
3198 // Check if this function is already declared.
3199 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
3200 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
3201 Alloc != AllocEnd; ++Alloc) {
3202 // Only look at non-template functions, as it is the predefined,
3203 // non-templated allocation function we are trying to declare here.
3204 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
3205 if (Func->getNumParams() == Params.size()) {
3207 for (auto *P : Func->parameters())
3208 FuncParams.push_back(
3209 Context.getCanonicalType(P->getType().getUnqualifiedType()));
3210 if (llvm::ArrayRef(FuncParams) == Params) {
3211 // Make the function visible to name lookup, even if we found it in
3212 // an unimported module. It either is an implicitly-declared global
3213 // allocation function, or is suppressing that function.
3214 Func->setVisibleDespiteOwningModule();
3215 return;
3216 }
3217 }
3218 }
3219 }
3220
3222 /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
3223
3224 QualType BadAllocType;
3225 bool HasBadAllocExceptionSpec
3226 = (Name.getCXXOverloadedOperator() == OO_New ||
3227 Name.getCXXOverloadedOperator() == OO_Array_New);
3228 if (HasBadAllocExceptionSpec) {
3229 if (!getLangOpts().CPlusPlus11) {
3230 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
3231 assert(StdBadAlloc && "Must have std::bad_alloc declared");
3233 EPI.ExceptionSpec.Exceptions = llvm::ArrayRef(BadAllocType);
3234 }
3235 if (getLangOpts().NewInfallible) {
3237 }
3238 } else {
3239 EPI.ExceptionSpec =
3241 }
3242
3243 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
3244 QualType FnType = Context.getFunctionType(Return, Params, EPI);
3246 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name, FnType,
3247 /*TInfo=*/nullptr, SC_None, getCurFPFeatures().isFPConstrained(), false,
3248 true);
3249 Alloc->setImplicit();
3250 // Global allocation functions should always be visible.
3252
3253 if (HasBadAllocExceptionSpec && getLangOpts().NewInfallible &&
3254 !getLangOpts().CheckNew)
3255 Alloc->addAttr(
3256 ReturnsNonNullAttr::CreateImplicit(Context, Alloc->getLocation()));
3257
3258 // C++ [basic.stc.dynamic.general]p2:
3259 // The library provides default definitions for the global allocation
3260 // and deallocation functions. Some global allocation and deallocation
3261 // functions are replaceable ([new.delete]); these are attached to the
3262 // global module ([module.unit]).
3263 //
3264 // In the language wording, these functions are attched to the global
3265 // module all the time. But in the implementation, the global module
3266 // is only meaningful when we're in a module unit. So here we attach
3267 // these allocation functions to global module conditionally.
3268 if (TheGlobalModuleFragment) {
3271 Alloc->setLocalOwningModule(TheGlobalModuleFragment);
3272 }
3273
3275 Alloc->addAttr(VisibilityAttr::CreateImplicit(
3277 ? VisibilityAttr::Hidden
3279 ? VisibilityAttr::Protected
3280 : VisibilityAttr::Default));
3281
3283 for (QualType T : Params) {
3284 ParamDecls.push_back(ParmVarDecl::Create(
3285 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
3286 /*TInfo=*/nullptr, SC_None, nullptr));
3287 ParamDecls.back()->setImplicit();
3288 }
3289 Alloc->setParams(ParamDecls);
3290 if (ExtraAttr)
3291 Alloc->addAttr(ExtraAttr);
3294 IdResolver.tryAddTopLevelDecl(Alloc, Name);
3295 };
3296
3297 if (!LangOpts.CUDA)
3298 CreateAllocationFunctionDecl(nullptr);
3299 else {
3300 // Host and device get their own declaration so each can be
3301 // defined or re-declared independently.
3302 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
3303 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
3304 }
3305}
3306
3308 bool CanProvideSize,
3309 bool Overaligned,
3310 DeclarationName Name) {
3312
3313 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
3315
3316 // FIXME: It's possible for this to result in ambiguity, through a
3317 // user-declared variadic operator delete or the enable_if attribute. We
3318 // should probably not consider those cases to be usual deallocation
3319 // functions. But for now we just make an arbitrary choice in that case.
3320 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
3321 Overaligned);
3322 assert(Result.FD && "operator delete missing from global scope?");
3323 return Result.FD;
3324}
3325
3327 CXXRecordDecl *RD) {
3329
3330 FunctionDecl *OperatorDelete = nullptr;
3331 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
3332 return nullptr;
3333 if (OperatorDelete)
3334 return OperatorDelete;
3335
3336 // If there's no class-specific operator delete, look up the global
3337 // non-array delete.
3340 Name);
3341}
3342
3344 DeclarationName Name,
3345 FunctionDecl *&Operator, bool Diagnose,
3346 bool WantSize, bool WantAligned) {
3347 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
3348 // Try to find operator delete/operator delete[] in class scope.
3349 LookupQualifiedName(Found, RD);
3350
3351 if (Found.isAmbiguous())
3352 return true;
3353
3354 Found.suppressDiagnostics();
3355
3356 bool Overaligned =
3357 WantAligned || hasNewExtendedAlignment(*this, Context.getRecordType(RD));
3358
3359 // C++17 [expr.delete]p10:
3360 // If the deallocation functions have class scope, the one without a
3361 // parameter of type std::size_t is selected.
3363 resolveDeallocationOverload(*this, Found, /*WantSize*/ WantSize,
3364 /*WantAlign*/ Overaligned, &Matches);
3365
3366 // If we could find an overload, use it.
3367 if (Matches.size() == 1) {
3368 Operator = cast<CXXMethodDecl>(Matches[0].FD);
3369
3370 // FIXME: DiagnoseUseOfDecl?
3371 if (Operator->isDeleted()) {
3372 if (Diagnose) {
3373 StringLiteral *Msg = Operator->getDeletedMessage();
3374 Diag(StartLoc, diag::err_deleted_function_use)
3375 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
3376 NoteDeletedFunction(Operator);
3377 }
3378 return true;
3379 }
3380
3381 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
3382 Matches[0].Found, Diagnose) == AR_inaccessible)
3383 return true;
3384
3385 return false;
3386 }
3387
3388 // We found multiple suitable operators; complain about the ambiguity.
3389 // FIXME: The standard doesn't say to do this; it appears that the intent
3390 // is that this should never happen.
3391 if (!Matches.empty()) {
3392 if (Diagnose) {
3393 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
3394 << Name << RD;
3395 for (auto &Match : Matches)
3396 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
3397 }
3398 return true;
3399 }
3400
3401 // We did find operator delete/operator delete[] declarations, but
3402 // none of them were suitable.
3403 if (!Found.empty()) {
3404 if (Diagnose) {
3405 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
3406 << Name << RD;
3407
3408 for (NamedDecl *D : Found)
3409 Diag(D->getUnderlyingDecl()->getLocation(),
3410 diag::note_member_declared_here) << Name;
3411 }
3412 return true;
3413 }
3414
3415 Operator = nullptr;
3416 return false;
3417}
3418
3419namespace {
3420/// Checks whether delete-expression, and new-expression used for
3421/// initializing deletee have the same array form.
3422class MismatchingNewDeleteDetector {
3423public:
3424 enum MismatchResult {
3425 /// Indicates that there is no mismatch or a mismatch cannot be proven.
3426 NoMismatch,
3427 /// Indicates that variable is initialized with mismatching form of \a new.
3428 VarInitMismatches,
3429 /// Indicates that member is initialized with mismatching form of \a new.
3430 MemberInitMismatches,
3431 /// Indicates that 1 or more constructors' definitions could not been
3432 /// analyzed, and they will be checked again at the end of translation unit.
3433 AnalyzeLater
3434 };
3435
3436 /// \param EndOfTU True, if this is the final analysis at the end of
3437 /// translation unit. False, if this is the initial analysis at the point
3438 /// delete-expression was encountered.
3439 explicit MismatchingNewDeleteDetector(bool EndOfTU)
3440 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
3441 HasUndefinedConstructors(false) {}
3442
3443 /// Checks whether pointee of a delete-expression is initialized with
3444 /// matching form of new-expression.
3445 ///
3446 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
3447 /// point where delete-expression is encountered, then a warning will be
3448 /// issued immediately. If return value is \c AnalyzeLater at the point where
3449 /// delete-expression is seen, then member will be analyzed at the end of
3450 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
3451 /// couldn't be analyzed. If at least one constructor initializes the member
3452 /// with matching type of new, the return value is \c NoMismatch.
3453 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
3454 /// Analyzes a class member.
3455 /// \param Field Class member to analyze.
3456 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
3457 /// for deleting the \p Field.
3458 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
3460 /// List of mismatching new-expressions used for initialization of the pointee
3462 /// Indicates whether delete-expression was in array form.
3463 bool IsArrayForm;
3464
3465private:
3466 const bool EndOfTU;
3467 /// Indicates that there is at least one constructor without body.
3468 bool HasUndefinedConstructors;
3469 /// Returns \c CXXNewExpr from given initialization expression.
3470 /// \param E Expression used for initializing pointee in delete-expression.
3471 /// E can be a single-element \c InitListExpr consisting of new-expression.
3472 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
3473 /// Returns whether member is initialized with mismatching form of
3474 /// \c new either by the member initializer or in-class initialization.
3475 ///
3476 /// If bodies of all constructors are not visible at the end of translation
3477 /// unit or at least one constructor initializes member with the matching
3478 /// form of \c new, mismatch cannot be proven, and this function will return
3479 /// \c NoMismatch.
3480 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
3481 /// Returns whether variable is initialized with mismatching form of
3482 /// \c new.
3483 ///
3484 /// If variable is initialized with matching form of \c new or variable is not
3485 /// initialized with a \c new expression, this function will return true.
3486 /// If variable is initialized with mismatching form of \c new, returns false.
3487 /// \param D Variable to analyze.
3488 bool hasMatchingVarInit(const DeclRefExpr *D);
3489 /// Checks whether the constructor initializes pointee with mismatching
3490 /// form of \c new.
3491 ///
3492 /// Returns true, if member is initialized with matching form of \c new in
3493 /// member initializer list. Returns false, if member is initialized with the
3494 /// matching form of \c new in this constructor's initializer or given
3495 /// constructor isn't defined at the point where delete-expression is seen, or
3496 /// member isn't initialized by the constructor.
3497 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
3498 /// Checks whether member is initialized with matching form of
3499 /// \c new in member initializer list.
3500 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3501 /// Checks whether member is initialized with mismatching form of \c new by
3502 /// in-class initializer.
3503 MismatchResult analyzeInClassInitializer();
3504};
3505}
3506
3507MismatchingNewDeleteDetector::MismatchResult
3508MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3509 NewExprs.clear();
3510 assert(DE && "Expected delete-expression");
3511 IsArrayForm = DE->isArrayForm();
3512 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3513 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3514 return analyzeMemberExpr(ME);
3515 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3516 if (!hasMatchingVarInit(D))
3517 return VarInitMismatches;
3518 }
3519 return NoMismatch;
3520}
3521
3522const CXXNewExpr *
3523MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3524 assert(E != nullptr && "Expected a valid initializer expression");
3525 E = E->IgnoreParenImpCasts();
3526 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3527 if (ILE->getNumInits() == 1)
3528 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3529 }
3530
3531 return dyn_cast_or_null<const CXXNewExpr>(E);
3532}
3533
3534bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3535 const CXXCtorInitializer *CI) {
3536 const CXXNewExpr *NE = nullptr;
3537 if (Field == CI->getMember() &&
3538 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3539 if (NE->isArray() == IsArrayForm)
3540 return true;
3541 else
3542 NewExprs.push_back(NE);
3543 }
3544 return false;
3545}
3546
3547bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3548 const CXXConstructorDecl *CD) {
3549 if (CD->isImplicit())
3550 return false;
3551 const FunctionDecl *Definition = CD;
3553 HasUndefinedConstructors = true;
3554 return EndOfTU;
3555 }
3556 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3557 if (hasMatchingNewInCtorInit(CI))
3558 return true;
3559 }
3560 return false;
3561}
3562
3563MismatchingNewDeleteDetector::MismatchResult
3564MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3565 assert(Field != nullptr && "This should be called only for members");
3566 const Expr *InitExpr = Field->getInClassInitializer();
3567 if (!InitExpr)
3568 return EndOfTU ? NoMismatch : AnalyzeLater;
3569 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
3570 if (NE->isArray() != IsArrayForm) {
3571 NewExprs.push_back(NE);
3572 return MemberInitMismatches;
3573 }
3574 }
3575 return NoMismatch;
3576}
3577
3578MismatchingNewDeleteDetector::MismatchResult
3579MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3580 bool DeleteWasArrayForm) {
3581 assert(Field != nullptr && "Analysis requires a valid class member.");
3582 this->Field = Field;
3583 IsArrayForm = DeleteWasArrayForm;
3584 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3585 for (const auto *CD : RD->ctors()) {
3586 if (hasMatchingNewInCtor(CD))
3587 return NoMismatch;
3588 }
3589 if (HasUndefinedConstructors)
3590 return EndOfTU ? NoMismatch : AnalyzeLater;
3591 if (!NewExprs.empty())
3592 return MemberInitMismatches;
3593 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3594 : NoMismatch;
3595}
3596
3597MismatchingNewDeleteDetector::MismatchResult
3598MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3599 assert(ME != nullptr && "Expected a member expression");
3600 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3601 return analyzeField(F, IsArrayForm);
3602 return NoMismatch;
3603}
3604
3605bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3606 const CXXNewExpr *NE = nullptr;
3607 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3608 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3609 NE->isArray() != IsArrayForm) {
3610 NewExprs.push_back(NE);
3611 }
3612 }
3613 return NewExprs.empty();
3614}
3615
3616static void
3618 const MismatchingNewDeleteDetector &Detector) {
3619 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3620 FixItHint H;
3621 if (!Detector.IsArrayForm)
3622 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3623 else {
3625 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3626 SemaRef.getLangOpts(), true);
3627 if (RSquare.isValid())
3628 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3629 }
3630 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3631 << Detector.IsArrayForm << H;
3632
3633 for (const auto *NE : Detector.NewExprs)
3634 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3635 << Detector.IsArrayForm;
3636}
3637
3638void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3639 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3640 return;
3641 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3642 switch (Detector.analyzeDeleteExpr(DE)) {
3643 case MismatchingNewDeleteDetector::VarInitMismatches:
3644 case MismatchingNewDeleteDetector::MemberInitMismatches: {
3645 DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
3646 break;
3647 }
3648 case MismatchingNewDeleteDetector::AnalyzeLater: {
3649 DeleteExprs[Detector.Field].push_back(
3650 std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
3651 break;
3652 }
3653 case MismatchingNewDeleteDetector::NoMismatch:
3654 break;
3655 }
3656}
3657
3658void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3659 bool DeleteWasArrayForm) {
3660 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3661 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3662 case MismatchingNewDeleteDetector::VarInitMismatches:
3663 llvm_unreachable("This analysis should have been done for class members.");
3664 case MismatchingNewDeleteDetector::AnalyzeLater:
3665 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3666 "translation unit.");
3667 case MismatchingNewDeleteDetector::MemberInitMismatches:
3668 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3669 break;
3670 case MismatchingNewDeleteDetector::NoMismatch:
3671 break;
3672 }
3673}
3674
3675/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3676/// @code ::delete ptr; @endcode
3677/// or
3678/// @code delete [] ptr; @endcode
3680Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
3681 bool ArrayForm, Expr *ExE) {
3682 // C++ [expr.delete]p1:
3683 // The operand shall have a pointer type, or a class type having a single
3684 // non-explicit conversion function to a pointer type. The result has type
3685 // void.
3686 //
3687 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3688
3689 ExprResult Ex = ExE;
3690 FunctionDecl *OperatorDelete = nullptr;
3691 bool ArrayFormAsWritten = ArrayForm;
3692 bool UsualArrayDeleteWantsSize = false;
3693
3694 if (!Ex.get()->isTypeDependent()) {
3695 // Perform lvalue-to-rvalue cast, if needed.
3696 Ex = DefaultLvalueConversion(Ex.get());
3697 if (Ex.isInvalid())
3698 return ExprError();
3699
3700 QualType Type = Ex.get()->getType();
3701
3702 class DeleteConverter : public ContextualImplicitConverter {
3703 public:
3704 DeleteConverter() : ContextualImplicitConverter(false, true) {}
3705
3706 bool match(QualType ConvType) override {
3707 // FIXME: If we have an operator T* and an operator void*, we must pick
3708 // the operator T*.
3709 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
3710 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
3711 return true;
3712 return false;
3713 }
3714
3715 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
3716 QualType T) override {
3717 return S.Diag(Loc, diag::err_delete_operand) << T;
3718 }
3719
3720 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
3721 QualType T) override {
3722 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3723 }
3724
3725 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
3726 QualType T,
3727 QualType ConvTy) override {
3728 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3729 }
3730
3731 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
3732 QualType ConvTy) override {
3733 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3734 << ConvTy;
3735 }
3736
3737 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
3738 QualType T) override {
3739 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3740 }
3741
3742 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
3743 QualType ConvTy) override {
3744 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3745 << ConvTy;
3746 }
3747
3748 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
3749 QualType T,
3750 QualType ConvTy) override {
3751 llvm_unreachable("conversion functions are permitted");
3752 }
3753 } Converter;
3754
3755 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
3756 if (Ex.isInvalid())
3757 return ExprError();
3758 Type = Ex.get()->getType();
3759 if (!Converter.match(Type))
3760 // FIXME: PerformContextualImplicitConversion should return ExprError
3761 // itself in this case.
3762 return ExprError();
3763
3764 QualType Pointee = Type->castAs<PointerType>()->getPointeeType();
3765 QualType PointeeElem = Context.getBaseElementType(Pointee);
3766
3767 if (Pointee.getAddressSpace() != LangAS::Default &&
3768 !getLangOpts().OpenCLCPlusPlus)
3769 return Diag(Ex.get()->getBeginLoc(),
3770 diag::err_address_space_qualified_delete)
3771 << Pointee.getUnqualifiedType()
3773
3774 CXXRecordDecl *PointeeRD = nullptr;
3775 if (Pointee->isVoidType() && !isSFINAEContext()) {
3776 // The C++ standard bans deleting a pointer to a non-object type, which
3777 // effectively bans deletion of "void*". However, most compilers support
3778 // this, so we treat it as a warning unless we're in a SFINAE context.
3779 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
3780 << Type << Ex.get()->getSourceRange();
3781 } else if (Pointee->isFunctionType() || Pointee->isVoidType() ||
3782 Pointee->isSizelessType()) {
3783 return ExprError(Diag(StartLoc, diag::err_delete_operand)
3784 << Type << Ex.get()->getSourceRange());
3785 } else if (!Pointee->isDependentType()) {
3786 // FIXME: This can result in errors if the definition was imported from a
3787 // module but is hidden.
3788 if (!RequireCompleteType(StartLoc, Pointee,
3789 diag::warn_delete_incomplete, Ex.get())) {
3790 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3791 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3792 }
3793 }
3794
3795 if (Pointee->isArrayType() && !ArrayForm) {
3796 Diag(StartLoc, diag::warn_delete_array_type)
3797 << Type << Ex.get()->getSourceRange()
3799 ArrayForm = true;
3800 }
3801
3803 ArrayForm ? OO_Array_Delete : OO_Delete);
3804
3805 if (PointeeRD) {
3806 if (!UseGlobal &&
3807 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3808 OperatorDelete))
3809 return ExprError();
3810
3811 // If we're allocating an array of records, check whether the
3812 // usual operator delete[] has a size_t parameter.
3813 if (ArrayForm) {
3814 // If the user specifically asked to use the global allocator,
3815 // we'll need to do the lookup into the class.
3816 if (UseGlobal)
3817 UsualArrayDeleteWantsSize =
3818 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3819
3820 // Otherwise, the usual operator delete[] should be the
3821 // function we just found.
3822 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
3823 UsualArrayDeleteWantsSize =
3824 UsualDeallocFnInfo(*this,
3825 DeclAccessPair::make(OperatorDelete, AS_public))
3826 .HasSizeT;
3827 }
3828
3829 if (!PointeeRD->hasIrrelevantDestructor())
3830 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3831 MarkFunctionReferenced(StartLoc,
3832 const_cast<CXXDestructorDecl*>(Dtor));
3833 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3834 return ExprError();
3835 }
3836
3837 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3838 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3839 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3840 SourceLocation());
3841 }
3842
3843 if (!OperatorDelete) {
3844 if (getLangOpts().OpenCLCPlusPlus) {
3845 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3846 return ExprError();
3847 }
3848
3849 bool IsComplete = isCompleteType(StartLoc, Pointee);
3850 bool CanProvideSize =
3851 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3852 Pointee.isDestructedType());
3853 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3854
3855 // Look for a global declaration.
3856 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3857 Overaligned, DeleteName);
3858 }
3859
3860 MarkFunctionReferenced(StartLoc, OperatorDelete);
3861
3862 // Check access and ambiguity of destructor if we're going to call it.
3863 // Note that this is required even for a virtual delete.
3864 bool IsVirtualDelete = false;
3865 if (PointeeRD) {
3866 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3867 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3868 PDiag(diag::err_access_dtor) << PointeeElem);
3869 IsVirtualDelete = Dtor->isVirtual();
3870 }
3871 }
3872
3873 DiagnoseUseOfDecl(OperatorDelete, StartLoc);
3874
3875 // Convert the operand to the type of the first parameter of operator
3876 // delete. This is only necessary if we selected a destroying operator
3877 // delete that we are going to call (non-virtually); converting to void*
3878 // is trivial and left to AST consumers to handle.
3879 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3880 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
3881 Qualifiers Qs = Pointee.getQualifiers();
3882 if (Qs.hasCVRQualifiers()) {
3883 // Qualifiers are irrelevant to this conversion; we're only looking
3884 // for access and ambiguity.
3888 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3889 }
3890 Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3891 if (Ex.isInvalid())
3892 return ExprError();
3893 }
3894 }
3895
3897 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3898 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
3899 AnalyzeDeleteExprMismatch(Result);
3900 return Result;
3901}
3902
3904 bool IsDelete,
3905 FunctionDecl *&Operator) {
3906
3908 IsDelete ? OO_Delete : OO_New);
3909
3910 LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
3912 assert(!R.empty() && "implicitly declared allocation functions not found");
3913 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3914
3915 // We do our own custom access checks below.
3917
3918 SmallVector<Expr *, 8> Args(TheCall->arguments());
3919 OverloadCandidateSet Candidates(R.getNameLoc(),
3921 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3922 FnOvl != FnOvlEnd; ++FnOvl) {
3923 // Even member operator new/delete are implicitly treated as
3924 // static, so don't use AddMemberCandidate.
3925 NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3926
3927 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3928 S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3929 /*ExplicitTemplateArgs=*/nullptr, Args,
3930 Candidates,
3931 /*SuppressUserConversions=*/false);
3932 continue;
3933 }
3934
3935 FunctionDecl *Fn = cast<FunctionDecl>(D);
3936 S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3937 /*SuppressUserConversions=*/false);
3938 }
3939
3940 SourceRange Range = TheCall->getSourceRange();
3941
3942 // Do the resolution.
3944 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3945 case OR_Success: {
3946 // Got one!
3947 FunctionDecl *FnDecl = Best->Function;
3948 assert(R.getNamingClass() == nullptr &&
3949 "class members should not be considered");
3950
3952 S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3953 << (IsDelete ? 1 : 0) << Range;
3954 S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3955 << R.getLookupName() << FnDecl->getSourceRange();
3956 return true;
3957 }
3958
3959 Operator = FnDecl;
3960 return false;
3961 }
3962
3964 Candidates.NoteCandidates(
3966 S.PDiag(diag::err_ovl_no_viable_function_in_call)
3967 << R.getLookupName() << Range),
3968 S, OCD_AllCandidates, Args);
3969 return true;
3970
3971 case OR_Ambiguous:
3972 Candidates.NoteCandidates(
3974 S.PDiag(diag::err_ovl_ambiguous_call)
3975 << R.getLookupName() << Range),
3976 S, OCD_AmbiguousCandidates, Args);
3977 return true;
3978
3979 case OR_Deleted:
3981 Candidates, Best->Function, Args);
3982 return true;
3983 }
3984 llvm_unreachable("Unreachable, bad result from BestViableFunction");
3985}
3986
3987ExprResult Sema::BuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3988 bool IsDelete) {
3989 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3990 if (!getLangOpts().CPlusPlus) {
3991 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3992 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3993 << "C++";
3994 return ExprError();
3995 }
3996 // CodeGen assumes it can find the global new and delete to call,
3997 // so ensure that they are declared.
3999
4000 FunctionDecl *OperatorNewOrDelete = nullptr;
4001 if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
4002 OperatorNewOrDelete))
4003 return ExprError();
4004 assert(OperatorNewOrDelete && "should be found");
4005
4006 DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
4007 MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
4008
4009 TheCall->setType(OperatorNewOrDelete->getReturnType());
4010 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
4011 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
4012 InitializedEntity Entity =
4015 Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
4016 if (Arg.isInvalid())
4017 return ExprError();
4018 TheCall->setArg(i, Arg.get());
4019 }
4020 auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
4021 assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
4022 "Callee expected to be implicit cast to a builtin function pointer");
4023 Callee->setType(OperatorNewOrDelete->getType());
4024
4025 return TheCallResult;
4026}
4027
4029 bool IsDelete, bool CallCanBeVirtual,
4030 bool WarnOnNonAbstractTypes,
4031 SourceLocation DtorLoc) {
4032 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
4033 return;
4034
4035 // C++ [expr.delete]p3:
4036 // In the first alternative (delete object), if the static type of the
4037 // object to be deleted is different from its dynamic type, the static
4038 // type shall be a base class of the dynamic type of the object to be
4039 // deleted and the static type shall have a virtual destructor or the
4040 // behavior is undefined.
4041 //
4042 const CXXRecordDecl *PointeeRD = dtor->getParent();
4043 // Note: a final class cannot be derived from, no issue there
4044 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
4045 return;
4046
4047 // If the superclass is in a system header, there's nothing that can be done.
4048 // The `delete` (where we emit the warning) can be in a system header,
4049 // what matters for this warning is where the deleted type is defined.
4050 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
4051 return;
4052
4053 QualType ClassType = dtor->getFunctionObjectParameterType();
4054 if (PointeeRD->isAbstract()) {
4055 // If the class is abstract, we warn by default, because we're
4056 // sure the code has undefined behavior.
4057 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
4058 << ClassType;
4059 } else if (WarnOnNonAbstractTypes) {
4060 // Otherwise, if this is not an array delete, it's a bit suspect,
4061 // but not necessarily wrong.
4062 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
4063 << ClassType;
4064 }
4065 if (!IsDelete) {
4066 std::string TypeStr;
4067 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
4068 Diag(DtorLoc, diag::note_delete_non_virtual)
4069 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
4070 }
4071}
4072
4074 SourceLocation StmtLoc,
4075 ConditionKind CK) {
4076 ExprResult E =
4077 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
4078 if (E.isInvalid())
4079 return ConditionError();
4080 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
4082}
4083
4084/// Check the use of the given variable as a C++ condition in an if,
4085/// while, do-while, or switch statement.
4087 SourceLocation StmtLoc,
4088 ConditionKind CK) {
4089 if (ConditionVar->isInvalidDecl())
4090 return ExprError();
4091
4092 QualType T = ConditionVar->getType();
4093
4094 // C++ [stmt.select]p2:
4095 // The declarator shall not specify a function or an array.
4096 if (T->isFunctionType())
4097 return ExprError(Diag(ConditionVar->getLocation(),
4098 diag::err_invalid_use_of_function_type)
4099 << ConditionVar->getSourceRange());
4100 else if (T->isArrayType())
4101 return ExprError(Diag(ConditionVar->getLocation(),
4102 diag::err_invalid_use_of_array_type)
4103 << ConditionVar->getSourceRange());
4104
4106 ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,
4107 ConditionVar->getLocation());
4108
4109 switch (CK) {
4111 return CheckBooleanCondition(StmtLoc, Condition.get());
4112
4114 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
4115
4117 return CheckSwitchCondition(StmtLoc, Condition.get());
4118 }
4119
4120 llvm_unreachable("unexpected condition kind");
4121}
4122
4123/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
4124ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
4125 // C++11 6.4p4:
4126 // The value of a condition that is an initialized declaration in a statement
4127 // other than a switch statement is the value of the declared variable
4128 // implicitly converted to type bool. If that conversion is ill-formed, the
4129 // program is ill-formed.
4130 // The value of a condition that is an expression is the value of the
4131 // expression, implicitly converted to bool.
4132 //
4133 // C++23 8.5.2p2
4134 // If the if statement is of the form if constexpr, the value of the condition
4135 // is contextually converted to bool and the converted expression shall be
4136 // a constant expression.
4137 //
4138
4140 if (!IsConstexpr || E.isInvalid() || E.get()->isValueDependent())
4141 return E;
4142
4143 // FIXME: Return this value to the caller so they don't need to recompute it.
4144 llvm::APSInt Cond;
4146 E.get(), &Cond,
4147 diag::err_constexpr_if_condition_expression_is_not_constant);
4148 return E;
4149}
4150
4151/// Helper function to determine whether this is the (deprecated) C++
4152/// conversion from a string literal to a pointer to non-const char or
4153/// non-const wchar_t (for narrow and wide string literals,
4154/// respectively).
4155bool
4157 // Look inside the implicit cast, if it exists.
4158 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
4159 From = Cast->getSubExpr();
4160
4161 // A string literal (2.13.4) that is not a wide string literal can
4162 // be converted to an rvalue of type "pointer to char"; a wide
4163 // string literal can be converted to an rvalue of type "pointer
4164 // to wchar_t" (C++ 4.2p2).
4165 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
4166 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
4167 if (const BuiltinType *ToPointeeType
4168 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
4169 // This conversion is considered only when there is an
4170 // explicit appropriate pointer target type (C++ 4.2p2).
4171 if (!ToPtrType->getPointeeType().hasQualifiers()) {
4172 switch (StrLit->getKind()) {
4176 // We don't allow UTF literals to be implicitly converted
4177 break;
4179 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
4180 ToPointeeType->getKind() == BuiltinType::Char_S);
4183 QualType(ToPointeeType, 0));
4185 assert(false && "Unevaluated string literal in expression");
4186 break;
4187 }
4188 }
4189 }
4190
4191 return false;
4192}
4193
4195 SourceLocation CastLoc,
4196 QualType Ty,
4197 CastKind Kind,
4198 CXXMethodDecl *Method,
4199 DeclAccessPair FoundDecl,
4200 bool HadMultipleCandidates,
4201 Expr *From) {
4202 switch (Kind) {
4203 default: llvm_unreachable("Unhandled cast kind!");
4204 case CK_ConstructorConversion: {
4205 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
4206 SmallVector<Expr*, 8> ConstructorArgs;
4207
4208 if (S.RequireNonAbstractType(CastLoc, Ty,
4209 diag::err_allocation_of_abstract_type))
4210 return ExprError();
4211
4212 if (S.CompleteConstructorCall(Constructor, Ty, From, CastLoc,
4213 ConstructorArgs))
4214 return ExprError();
4215
4216 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
4218 if (S.DiagnoseUseOfDecl(Method, CastLoc))
4219 return ExprError();
4220
4222 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
4223 ConstructorArgs, HadMultipleCandidates,
4224 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4226 if (Result.isInvalid())
4227 return ExprError();
4228
4229 return S.MaybeBindToTemporary(Result.getAs<Expr>());
4230 }
4231
4232 case CK_UserDefinedConversion: {
4233 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
4234
4235 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
4236 if (S.DiagnoseUseOfDecl(Method, CastLoc))
4237 return ExprError();
4238
4239 // Create an implicit call expr that calls it.
4240 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
4241 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
4242 HadMultipleCandidates);
4243 if (Result.isInvalid())
4244 return ExprError();
4245 // Record usage of conversion in an implicit cast.
4246 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
4247 CK_UserDefinedConversion, Result.get(),
4248 nullptr, Result.get()->getValueKind(),
4250
4251 return S.MaybeBindToTemporary(Result.get());
4252 }
4253 }
4254}
4255
4256/// PerformImplicitConversion - Perform an implicit conversion of the
4257/// expression From to the type ToType using the pre-computed implicit
4258/// conversion sequence ICS. Returns the converted
4259/// expression. Action is the kind of conversion we're performing,
4260/// used in the error message.
4263 const ImplicitConversionSequence &ICS,
4264 AssignmentAction Action,
4266 // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
4268 !From->getType()->isRecordType())
4269 return From;
4270
4271 switch (ICS.getKind()) {
4273 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
4274 Action, CCK);
4275 if (Res.isInvalid())
4276 return ExprError();
4277 From = Res.get();
4278 break;
4279 }
4280
4282
4285 QualType BeforeToType;
4286 assert(FD && "no conversion function for user-defined conversion seq");
4287 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
4288 CastKind = CK_UserDefinedConversion;
4289
4290 // If the user-defined conversion is specified by a conversion function,
4291 // the initial standard conversion sequence converts the source type to
4292 // the implicit object parameter of the conversion function.
4293 BeforeToType = Context.getTagDeclType(Conv->getParent());
4294 } else {
4295 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
4296 CastKind = CK_ConstructorConversion;
4297 // Do no conversion if dealing with ... for the first conversion.
4299 // If the user-defined conversion is specified by a constructor, the
4300 // initial standard conversion sequence converts the source type to
4301 // the type required by the argument of the constructor
4302 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
4303 }
4304 }
4305 // Watch out for ellipsis conversion.
4307 ExprResult Res =
4308 PerformImplicitConversion(From, BeforeToType,
4310 CCK);
4311 if (Res.isInvalid())
4312 return ExprError();
4313 From = Res.get();
4314 }
4315
4317 *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
4318 cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
4320
4321 if (CastArg.isInvalid())
4322 return ExprError();
4323
4324 From = CastArg.get();
4325
4326 // C++ [over.match.oper]p7:
4327 // [...] the second standard conversion sequence of a user-defined
4328 // conversion sequence is not applied.
4330 return From;
4331
4332 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
4333 AA_Converting, CCK);
4334 }
4335
4337 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
4338 PDiag(diag::err_typecheck_ambiguous_condition)
4339 << From->getSourceRange());
4340 return ExprError();
4341
4344 llvm_unreachable("bad conversion");
4345
4348 CheckAssignmentConstraints(From->getExprLoc(), ToType, From->getType());
4349 bool Diagnosed = DiagnoseAssignmentResult(
4350 ConvTy == Compatible ? Incompatible : ConvTy, From->getExprLoc(),
4351 ToType, From->getType(), From, Action);
4352 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
4353 return ExprError();
4354 }
4355
4356 // Everything went well.
4357 return From;
4358}
4359
4360/// PerformImplicitConversion - Perform an implicit conversion of the
4361/// expression From to the type ToType by following the standard
4362/// conversion sequence SCS. Returns the converted
4363/// expression. Flavor is the context in which we're performing this
4364/// conversion, for use in error messages.
4367 const StandardConversionSequence& SCS,
4368 AssignmentAction Action,
4370 bool CStyle = (CCK == CheckedConversionKind::CStyleCast ||
4372
4373 // Overall FIXME: we are recomputing too many types here and doing far too
4374 // much extra work. What this means is that we need to keep track of more
4375 // information that is computed when we try the implicit conversion initially,
4376 // so that we don't need to recompute anything here.
4377 QualType FromType = From->getType();
4378
4379 if (SCS.CopyConstructor) {
4380 // FIXME: When can ToType be a reference type?
4381 assert(!ToType->isReferenceType());
4382 if (SCS.Second == ICK_Derived_To_Base) {
4383 SmallVector<Expr*, 8> ConstructorArgs;
4385 cast<CXXConstructorDecl>(SCS.CopyConstructor), ToType, From,
4386 /*FIXME:ConstructLoc*/ SourceLocation(), ConstructorArgs))
4387 return ExprError();
4388 return BuildCXXConstructExpr(
4389 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4390 SCS.FoundCopyConstructor, SCS.CopyConstructor, ConstructorArgs,
4391 /*HadMultipleCandidates*/ false,
4392 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4394 }
4395 return BuildCXXConstructExpr(
4396 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4398 /*HadMultipleCandidates*/ false,
4399 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4401 }
4402
4403 // Resolve overloaded function references.
4404 if (Context.hasSameType(FromType, Context.OverloadTy)) {
4405 DeclAccessPair Found;
4407 true, Found);
4408 if (!Fn)
4409 return ExprError();
4410
4411 if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
4412 return ExprError();
4413
4414 ExprResult Res = FixOverloadedFunctionReference(From, Found, Fn);
4415 if (Res.isInvalid())
4416 return ExprError();
4417
4418 // We might get back another placeholder expression if we resolved to a
4419 // builtin.
4420 Res = CheckPlaceholderExpr(Res.get());
4421 if (Res.isInvalid())
4422 return ExprError();
4423
4424 From = Res.get();
4425 FromType = From->getType();
4426 }
4427
4428 // If we're converting to an atomic type, first convert to the corresponding
4429 // non-atomic type.
4430 QualType ToAtomicType;
4431 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
4432 ToAtomicType = ToType;
4433 ToType = ToAtomic->getValueType();
4434 }
4435
4436 QualType InitialFromType = FromType;
4437 // Perform the first implicit conversion.
4438 switch (SCS.First) {
4439 case ICK_Identity:
4440 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
4441 FromType = FromAtomic->getValueType().getUnqualifiedType();
4442 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
4443 From, /*BasePath=*/nullptr, VK_PRValue,
4445 }
4446 break;
4447
4448 case ICK_Lvalue_To_Rvalue: {
4449 assert(From->getObjectKind() != OK_ObjCProperty);
4450 ExprResult FromRes = DefaultLvalueConversion(From);
4451 if (FromRes.isInvalid())
4452 return ExprError();
4453
4454 From = FromRes.get();
4455 FromType = From->getType();
4456 break;
4457 }
4458
4460 FromType = Context.getArrayDecayedType(FromType);
4461 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, VK_PRValue,
4462 /*BasePath=*/nullptr, CCK)
4463 .get();
4464 break;
4465
4467 FromType = Context.getArrayParameterType(FromType);
4468 From = ImpCastExprToType(From, FromType, CK_HLSLArrayRValue, VK_PRValue,
4469 /*BasePath=*/nullptr, CCK)
4470 .get();
4471 break;
4472
4474 FromType = Context.getPointerType(FromType);
4475 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
4476 VK_PRValue, /*BasePath=*/nullptr, CCK)
4477 .get();
4478 break;
4479
4480 default:
4481 llvm_unreachable("Improper first standard conversion");
4482 }
4483
4484 // Perform the second implicit conversion
4485 switch (SCS.Second) {
4486 case ICK_Identity:
4487 // C++ [except.spec]p5:
4488 // [For] assignment to and initialization of pointers to functions,
4489 // pointers to member functions, and references to functions: the
4490 // target entity shall allow at least the exceptions allowed by the
4491 // source value in the assignment or initialization.
4492 switch (Action) {
4493 case AA_Assigning:
4494 case AA_Initializing:
4495 // Note, function argument passing and returning are initialization.
4496 case AA_Passing:
4497 case AA_Returning:
4498 case AA_Sending:
4500 if (CheckExceptionSpecCompatibility(From, ToType))
4501 return ExprError();
4502 break;
4503
4504 case AA_Casting:
4505 case AA_Converting:
4506 // Casts and implicit conversions are not initialization, so are not
4507 // checked for exception specification mismatches.
4508 break;
4509 }
4510 // Nothing else to do.
4511 break;
4512
4515 if (ToType->isBooleanType()) {
4516 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
4518 "only enums with fixed underlying type can promote to bool");
4519 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean, VK_PRValue,
4520 /*BasePath=*/nullptr, CCK)
4521 .get();
4522 } else {
4523 From = ImpCastExprToType(From, ToType, CK_IntegralCast, VK_PRValue,
4524 /*BasePath=*/nullptr, CCK)
4525 .get();
4526 }
4527 break;
4528
4531 From = ImpCastExprToType(From, ToType, CK_FloatingCast, VK_PRValue,
4532 /*BasePath=*/nullptr, CCK)
4533 .get();
4534 break;
4535
4538 QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType();
4539 QualType ToEl = ToType->castAs<ComplexType>()->getElementType();
4540 CastKind CK;
4541 if (FromEl->isRealFloatingType()) {
4542 if (ToEl->isRealFloatingType())
4543 CK = CK_FloatingComplexCast;
4544 else
4545 CK = CK_FloatingComplexToIntegralComplex;
4546 } else if (ToEl->isRealFloatingType()) {
4547 CK = CK_IntegralComplexToFloatingComplex;
4548 } else {
4549 CK = CK_IntegralComplexCast;
4550 }
4551 From = ImpCastExprToType(From, ToType, CK, VK_PRValue, /*BasePath=*/nullptr,
4552 CCK)
4553 .get();
4554 break;
4555 }
4556
4558 if (ToType->isRealFloatingType())
4559 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating, VK_PRValue,
4560 /*BasePath=*/nullptr, CCK)
4561 .get();
4562 else
4563 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral, VK_PRValue,
4564 /*BasePath=*/nullptr, CCK)
4565 .get();
4566 break;
4567
4569 assert((FromType->isFixedPointType() || ToType->isFixedPointType()) &&
4570 "Attempting implicit fixed point conversion without a fixed "
4571 "point operand");
4572 if (FromType->isFloatingType())
4573 From = ImpCastExprToType(From, ToType, CK_FloatingToFixedPoint,
4574 VK_PRValue,
4575 /*BasePath=*/nullptr, CCK).get();
4576 else if (ToType->isFloatingType())
4577 From = ImpCastExprToType(From, ToType, CK_FixedPointToFloating,
4578 VK_PRValue,
4579 /*BasePath=*/nullptr, CCK).get();
4580 else if (FromType->isIntegralType(Context))
4581 From = ImpCastExprToType(From, ToType, CK_IntegralToFixedPoint,
4582 VK_PRValue,
4583 /*BasePath=*/nullptr, CCK).get();
4584 else if (ToType->isIntegralType(Context))
4585 From = ImpCastExprToType(From, ToType, CK_FixedPointToIntegral,
4586 VK_PRValue,
4587 /*BasePath=*/nullptr, CCK).get();
4588 else if (ToType->isBooleanType())
4589 From = ImpCastExprToType(From, ToType, CK_FixedPointToBoolean,
4590 VK_PRValue,
4591 /*BasePath=*/nullptr, CCK).get();
4592 else
4593 From = ImpCastExprToType(From, ToType, CK_FixedPointCast,
4594 VK_PRValue,
4595 /*BasePath=*/nullptr, CCK).get();
4596 break;
4597
4599 From = ImpCastExprToType(From, ToType, CK_NoOp, From->getValueKind(),
4600 /*BasePath=*/nullptr, CCK).get();
4601 break;
4602
4605 if (SCS.IncompatibleObjC && Action != AA_Casting) {
4606 // Diagnose incompatible Objective-C conversions
4607 if (Action == AA_Initializing || Action == AA_Assigning)
4608 Diag(From->getBeginLoc(),
4609 diag::ext_typecheck_convert_incompatible_pointer)
4610 << ToType << From->getType() << Action << From->getSourceRange()
4611 << 0;
4612 else
4613 Diag(From->getBeginLoc(),
4614 diag::ext_typecheck_convert_incompatible_pointer)
4615 << From->getType() << ToType << Action << From->getSourceRange()
4616 << 0;
4617
4618 if (From->getType()->isObjCObjectPointerType() &&
4619 ToType->isObjCObjectPointerType())
4621 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4622 !ObjC().CheckObjCARCUnavailableWeakConversion(ToType,
4623 From->getType())) {
4624 if (Action == AA_Initializing)
4625 Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
4626 else
4627 Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4628 << (Action == AA_Casting) << From->getType() << ToType
4629 << From->getSourceRange();
4630 }
4631
4632 // Defer address space conversion to the third conversion.
4633 QualType FromPteeType = From->getType()->getPointeeType();
4634 QualType ToPteeType = ToType->getPointeeType();
4635 QualType NewToType = ToType;
4636 if (!FromPteeType.isNull() && !ToPteeType.isNull() &&
4637 FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) {
4638 NewToType = Context.removeAddrSpaceQualType(ToPteeType);
4639 NewToType = Context.getAddrSpaceQualType(NewToType,
4640 FromPteeType.getAddressSpace());
4641 if (ToType->isObjCObjectPointerType())
4642 NewToType = Context.getObjCObjectPointerType(NewToType);
4643 else if (ToType->isBlockPointerType())
4644 NewToType = Context.getBlockPointerType(NewToType);
4645 else
4646 NewToType = Context.getPointerType(NewToType);
4647 }
4648
4649 CastKind Kind;
4650 CXXCastPath BasePath;
4651 if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle))
4652 return ExprError();
4653
4654 // Make sure we extend blocks if necessary.
4655 // FIXME: doing this here is really ugly.
4656 if (Kind == CK_BlockPointerToObjCPointerCast) {
4657 ExprResult E = From;
4659 From = E.get();
4660 }
4662 ObjC().CheckObjCConversion(SourceRange(), NewToType, From, CCK);
4663 From = ImpCastExprToType(From, NewToType, Kind, VK_PRValue, &BasePath, CCK)
4664 .get();
4665 break;
4666 }
4667
4668 case ICK_Pointer_Member: {
4669 CastKind Kind;
4670 CXXCastPath BasePath;
4671 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
4672 return ExprError();
4673 if (CheckExceptionSpecCompatibility(From, ToType))
4674 return ExprError();
4675
4676 // We may not have been able to figure out what this member pointer resolved
4677 // to up until this exact point. Attempt to lock-in it's inheritance model.
4679 (void)isCompleteType(From->getExprLoc(), From->getType());
4680 (void)isCompleteType(From->getExprLoc(), ToType);
4681 }
4682
4683 From =
4684 ImpCastExprToType(From, ToType, Kind, VK_PRValue, &BasePath, CCK).get();
4685 break;
4686 }
4687
4689 // Perform half-to-boolean conversion via float.
4690 if (From->getType()->isHalfType()) {
4691 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
4692 FromType = Context.FloatTy;
4693 }
4694
4695 From = ImpCastExprToType(From, Context.BoolTy,
4697 /*BasePath=*/nullptr, CCK)
4698 .get();
4699 break;
4700
4701 case ICK_Derived_To_Base: {
4702 CXXCastPath BasePath;
4704 From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
4705 From->getSourceRange(), &BasePath, CStyle))
4706 return ExprError();
4707
4708 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4709 CK_DerivedToBase, From->getValueKind(),
4710 &BasePath, CCK).get();
4711 break;
4712 }
4713
4715 From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
4716 /*BasePath=*/nullptr, CCK)
4717 .get();
4718 break;
4719
4722 From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
4723 /*BasePath=*/nullptr, CCK)
4724 .get();
4725 break;
4726
4727 case ICK_Vector_Splat: {
4728 // Vector splat from any arithmetic type to a vector.
4729 Expr *Elem = prepareVectorSplat(ToType, From).get();
4730 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue,
4731 /*BasePath=*/nullptr, CCK)
4732 .get();
4733 break;
4734 }
4735
4736 case ICK_Complex_Real:
4737 // Case 1. x -> _Complex y
4738 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4739 QualType ElType = ToComplex->getElementType();
4740 bool isFloatingComplex = ElType->isRealFloatingType();
4741
4742 // x -> y
4743 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4744 // do nothing
4745 } else if (From->getType()->isRealFloatingType()) {
4746 From = ImpCastExprToType(From, ElType,
4747 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
4748 } else {
4749 assert(From->getType()->isIntegerType());
4750 From = ImpCastExprToType(From, ElType,
4751 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
4752 }
4753 // y -> _Complex y
4754 From = ImpCastExprToType(From, ToType,
4755 isFloatingComplex ? CK_FloatingRealToComplex
4756 : CK_IntegralRealToComplex).get();
4757
4758 // Case 2. _Complex x -> y
4759 } else {
4760 auto *FromComplex = From->getType()->castAs<ComplexType>();
4761 QualType ElType = FromComplex->getElementType();
4762 bool isFloatingComplex = ElType->isRealFloatingType();
4763
4764 // _Complex x -> x
4765 From = ImpCastExprToType(From, ElType,
4766 isFloatingComplex ? CK_FloatingComplexToReal
4767 : CK_IntegralComplexToReal,
4768 VK_PRValue, /*BasePath=*/nullptr, CCK)
4769 .get();
4770
4771 // x -> y
4772 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4773 // do nothing
4774 } else if (ToType->isRealFloatingType()) {
4775 From = ImpCastExprToType(From, ToType,
4776 isFloatingComplex ? CK_FloatingCast
4777 : CK_IntegralToFloating,
4778 VK_PRValue, /*BasePath=*/nullptr, CCK)
4779 .get();
4780 } else {
4781 assert(ToType->isIntegerType());
4782 From = ImpCastExprToType(From, ToType,
4783 isFloatingComplex ? CK_FloatingToIntegral
4784 : CK_IntegralCast,
4785 VK_PRValue, /*BasePath=*/nullptr, CCK)
4786 .get();
4787 }
4788 }
4789 break;
4790
4792 LangAS AddrSpaceL =
4793 ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4794 LangAS AddrSpaceR =
4795 FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4796 assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) &&
4797 "Invalid cast");
4798 CastKind Kind =
4799 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
4800 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind,
4801 VK_PRValue, /*BasePath=*/nullptr, CCK)
4802 .get();
4803 break;
4804 }
4805
4807 ExprResult FromRes = From;
4810 if (FromRes.isInvalid())
4811 return ExprError();
4812 From = FromRes.get();
4813 assert ((ConvTy == Sema::Compatible) &&
4814 "Improper transparent union conversion");
4815 (void)ConvTy;
4816 break;
4817 }
4818
4821 From = ImpCastExprToType(From, ToType,
4822 CK_ZeroToOCLOpaqueType,
4823 From->getValueKind()).get();
4824 break;
4826 // Note: HLSL built-in vectors are ExtVectors. Since this truncates a vector
4827 // to a smaller vector, this can only operate on arguments where the source
4828 // and destination types are ExtVectors.
4829 assert(From->getType()->isExtVectorType() && ToType->isExtVectorType() &&
4830 "HLSL vector truncation should only apply to ExtVectors");
4831 auto *FromVec = From->getType()->castAs<VectorType>();
4832 auto *ToVec = ToType->castAs<VectorType>();
4833 QualType ElType = FromVec->getElementType();
4834 QualType TruncTy =
4835 Context.getExtVectorType(ElType, ToVec