45#include "llvm/ADT/APInt.h"
46#include "llvm/ADT/STLExtras.h"
47#include "llvm/ADT/StringExtras.h"
48#include "llvm/Support/ErrorHandling.h"
49#include "llvm/Support/TypeSize.h"
83 llvm_unreachable(
"Nested name specifier is not a type for inheriting ctor");
95 bool EnteringContext) {
98 "not a constructor name");
120 auto *RD = dyn_cast<CXXRecordDecl>(ND);
121 if (RD && RD->isInjectedClassName()) {
122 InjectedClassName = RD;
126 if (!InjectedClassName) {
131 diag::err_incomplete_nested_name_spec) << CurClass << SS.
getRange();
146 bool EnteringContext) {
192 auto IsAcceptableResult = [&](
NamedDecl *D) ->
bool {
193 auto *
Type = dyn_cast<TypeDecl>(D->getUnderlyingDecl());
204 unsigned NumAcceptableResults = 0;
206 if (IsAcceptableResult(D))
207 ++NumAcceptableResults;
212 if (
auto *RD = dyn_cast<CXXRecordDecl>(D))
213 if (RD->isInjectedClassName())
214 D = cast<NamedDecl>(RD->getParent());
216 if (FoundDeclSet.insert(D).second)
217 FoundDecls.push_back(D);
225 if (Found.isAmbiguous() && NumAcceptableResults == 1) {
226 Diag(NameLoc, diag::ext_dtor_name_ambiguous);
236 if (!IsAcceptableResult(D))
242 if (Found.isAmbiguous())
246 if (IsAcceptableResult(
Type)) {
258 bool IsDependent =
false;
260 auto LookupInObjectType = [&]() ->
ParsedType {
261 if (Failed || SearchType.
isNull())
271 return CheckLookupResult(Found);
289 return CheckLookupResult(Found);
298 return CheckLookupResult(Found);
345 if (
ParsedType T = LookupInNestedNameSpec(PrefixSS))
375 unsigned NumNonExtensionDecls = FoundDecls.size();
383 if (
ParsedType T = LookupInNestedNameSpec(SS)) {
399 Diag(SS.
getEndLoc(), diag::ext_qualified_dtor_named_in_lexical_scope)
401 Diag(FoundDecls.back()->getLocation(), diag::note_destructor_type_here)
412 FoundDecls.resize(NumNonExtensionDecls);
415 std::stable_sort(FoundDecls.begin(), FoundDecls.end(),
417 return isa<TypeDecl>(A->getUnderlyingDecl()) >
418 isa<TypeDecl>(B->getUnderlyingDecl());
422 auto MakeFixItHint = [&]{
428 Destroyed = dyn_cast_or_null<CXXRecordDecl>(S->getEntity());
435 if (FoundDecls.empty()) {
437 Diag(NameLoc, diag::err_undeclared_destructor_name)
438 << &II << MakeFixItHint();
439 }
else if (!SearchType.
isNull() && FoundDecls.size() == 1) {
440 if (
auto *TD = dyn_cast<TypeDecl>(FoundDecls[0]->getUnderlyingDecl())) {
441 assert(!SearchType.
isNull() &&
442 "should only reject a type result if we have a search type");
444 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
445 << T << SearchType << MakeFixItHint();
447 Diag(NameLoc, diag::err_destructor_expr_nontype)
448 << &II << MakeFixItHint();
451 Diag(NameLoc, SearchType.
isNull() ? diag::err_destructor_name_nontype
452 : diag::err_destructor_expr_mismatch)
453 << &II << SearchType << MakeFixItHint();
457 if (
auto *TD = dyn_cast<TypeDecl>(FoundD->getUnderlyingDecl()))
458 Diag(FoundD->getLocation(), diag::note_destructor_type_here)
461 Diag(FoundD->getLocation(), diag::note_destructor_nontype_here)
479 "unexpected type in getDestructorType");
508 Name.getSourceRange(),
509 (StringRef(
"operator\"\"") + II->
getName()).str());
511 Diag(Loc, diag::warn_reserved_extern_symbol)
512 << II << static_cast<int>(Status) << Hint;
514 Diag(Loc, diag::warn_deprecated_literal_operator_id) << II << Hint;
530 Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)
541 llvm_unreachable(
"unknown nested name specifier kind");
563 return ExprError(
Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
577 bool WasEvaluated =
false;
587 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
633 return ExprError(
Diag(TypeidLoc, diag::err_variably_modified_typeid)
640 ? diag::warn_side_effects_typeid
641 : diag::warn_side_effects_unevaluated_context);
654 return ExprError(
Diag(OpLoc, diag::err_openclcxx_not_supported)
660 return ExprError(
Diag(OpLoc, diag::err_need_header_before_typeid));
674 return ExprError(
Diag(OpLoc, diag::err_need_header_before_typeid));
678 return ExprError(
Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
702 if (
auto *CTE = dyn_cast<CXXTypeidExpr>(
Result.get()))
703 if (CTE->isPotentiallyEvaluated() && !CTE->isMostDerived(
Context))
704 Diag(OpLoc, diag::warn_no_typeid_with_rtti_disabled)
726 if (
const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
727 UuidAttrs.insert(Uuid);
732 if (
const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
735 const UuidAttr *UuidForTA =
nullptr;
742 UuidAttrs.insert(UuidForTA);
753 if (!Operand->getType()->isDependentType()) {
756 if (UuidAttrs.empty())
757 return ExprError(
Diag(TypeidLoc, diag::err_uuidof_without_guid));
758 if (UuidAttrs.size() > 1)
759 return ExprError(
Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
760 Guid = UuidAttrs.back()->getGuidDecl();
778 if (UuidAttrs.empty())
779 return ExprError(
Diag(TypeidLoc, diag::err_uuidof_without_guid));
780 if (UuidAttrs.size() > 1)
781 return ExprError(
Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
782 Guid = UuidAttrs.back()->getGuidDecl();
818 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
819 "Unknown C++ Boolean value!");
833 bool IsThrownVarInScope =
false;
847 if (
VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
848 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
849 for( ; S; S = S->getParent()) {
850 if (S->isDeclScope(Var)) {
851 IsThrownVarInScope =
true;
869 bool IsThrownVarInScope) {
871 const bool IsOpenMPGPUTarget =
872 getLangOpts().OpenMPIsTargetDevice && (T.isNVPTX() || T.isAMDGCN());
875 if (!IsOpenMPGPUTarget && !
getLangOpts().CXXExceptions &&
878 targetDiag(OpLoc, diag::err_exceptions_disabled) <<
"throw";
882 if (IsOpenMPGPUTarget)
883 targetDiag(OpLoc, diag::warn_throw_not_valid_on_target) << T.str();
891 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) <<
"throw";
934 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
935 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
936 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
937 bool ParentIsPublic) {
939 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
944 NewSubobject = VBases.insert(BaseDecl).second;
949 ++SubobjectsSeen[BaseDecl];
952 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() ==
AS_public;
954 PublicSubobjectsSeen.insert(BaseDecl);
964 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
965 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
966 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
967 SubobjectsSeen[RD] = 1;
968 PublicSubobjectsSeen.insert(RD);
972 for (
CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
974 if (SubobjectsSeen[PublicSubobject] > 1)
977 Objects.push_back(PublicSubobject);
987 bool isPointer =
false;
1007 isPointer ? diag::err_throw_incomplete_ptr
1008 : diag::err_throw_incomplete,
1018 diag::err_throw_abstract_type, E))
1040 PDiag(diag::err_access_dtor_exception) << Ty);
1056 for (
CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
1083 for (
unsigned I = 1, E = CD->
getNumParams(); I != E; ++I) {
1097 if (ExnObjAlign < TypeAlign) {
1098 Diag(ThrowLoc, diag::warn_throw_underaligned_obj);
1099 Diag(ThrowLoc, diag::note_throw_underaligned_obj)
1104 if (!isPointer &&
getLangOpts().AssumeNothrowExceptionDtor) {
1106 auto Ty = Dtor->getType();
1110 Diag(ThrowLoc, diag::err_throw_object_throwing_dtor) << RD;
1162 for (
int I = FunctionScopes.size();
1163 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
1165 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
1167 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
1174 if (
C.isCopyCapture()) {
1186 "While computing 'this' capture-type for a generic lambda, when we "
1187 "run out of enclosing LSI's, yet the enclosing DC is a "
1188 "lambda-call-operator we must be (i.e. Current LSI) in a generic "
1189 "lambda call oeprator");
1192 auto IsThisCaptured =
1197 if (
C.capturesThis()) {
1208 bool IsByCopyCapture =
false;
1209 bool IsConstCapture =
false;
1212 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1213 if (IsByCopyCapture) {
1231 if (method && method->isImplicitObjectMemberFunction())
1232 ThisTy = method->getThisType().getNonReferenceType();
1260 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(
false)
1262 if (!Enabled || !ContextDecl)
1267 Record = Template->getTemplatedDecl();
1269 Record = cast<CXXRecordDecl>(ContextDecl);
1277 this->Enabled =
true;
1294 Sema.
Diag(DiagLoc, diag::note_lambda_this_capture_fixit)
1300 bool BuildAndDiagnose,
const unsigned *
const FunctionScopeIndexToStopAt,
1301 const bool ByCopy) {
1306 assert((!ByCopy || Explicit) &&
"cannot implicitly capture *this by value");
1308 const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1309 ? *FunctionScopeIndexToStopAt
1335 unsigned NumCapturingClosures = 0;
1336 for (
int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
1339 if (CSI->CXXThisCaptureIndex != 0) {
1341 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
1347 if (BuildAndDiagnose) {
1349 Diag(Loc, diag::err_this_capture)
1350 << (Explicit && idx == MaxFunctionScopesIndex);
1360 (Explicit && idx == MaxFunctionScopesIndex)) {
1366 NumCapturingClosures++;
1370 if (BuildAndDiagnose) {
1372 Diag(Loc, diag::err_this_capture)
1373 << (Explicit && idx == MaxFunctionScopesIndex);
1381 if (!BuildAndDiagnose)
return false;
1394 "Only a lambda can capture the enclosing object (referred to by "
1397 for (
int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1398 --idx, --NumCapturingClosures) {
1405 bool isNested = NumCapturingClosures > 1;
1420 if (
const auto *Method = dyn_cast<CXXMethodDecl>(DC);
1421 Method && Method->isExplicitObjectMemberFunction()) {
1422 return Diag(Loc, diag::err_invalid_this_use) << 1;
1426 return Diag(Loc, diag::err_invalid_this_use) << 1;
1428 return Diag(Loc, diag::err_invalid_this_use) << 0;
1466 bool ListInitialization) {
1476 RParenOrBraceLoc, ListInitialization);
1480 if (!
Result.isInvalid() &&
Result.get()->isInstantiationDependent() &&
1481 !
Result.get()->isTypeDependent())
1483 else if (
Result.isInvalid())
1485 RParenOrBraceLoc, exprs, Ty);
1494 bool ListInitialization) {
1498 assert((!ListInitialization || Exprs.size() == 1) &&
1499 "List initialization must have exactly one expression.");
1506 ? ListInitialization
1508 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1522 isa<DeducedTemplateSpecializationType>(Deduced)) {
1528 }
else if (Deduced && !Deduced->
isDeduced()) {
1530 if (ListInitialization) {
1531 auto *ILE = cast<InitListExpr>(Exprs[0]);
1532 Inits =
MultiExprArg(ILE->getInits(), ILE->getNumInits());
1536 return ExprError(
Diag(TyBeginLoc, diag::err_auto_expr_init_no_expression)
1537 << Ty << FullRange);
1538 if (Inits.size() > 1) {
1539 Expr *FirstBad = Inits[1];
1541 diag::err_auto_expr_init_multiple_expressions)
1542 << Ty << FullRange);
1546 Diag(TyBeginLoc, diag::warn_cxx20_compat_auto_expr) << FullRange;
1548 Expr *Deduce = Inits[0];
1549 if (isa<InitListExpr>(Deduce))
1552 << ListInitialization << Ty << FullRange);
1558 return ExprError(
Diag(TyBeginLoc, diag::err_auto_expr_deduction_failure)
1559 << Ty << Deduce->
getType() << FullRange
1573 RParenOrBraceLoc, ListInitialization);
1579 if (Exprs.size() == 1 && !ListInitialization &&
1580 !isa<InitListExpr>(Exprs[0])) {
1581 Expr *Arg = Exprs[0];
1589 if (!ListInitialization)
1590 return ExprError(
Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1600 return ExprError(
Diag(TyBeginLoc, diag::err_init_for_function_type)
1601 << Ty << FullRange);
1608 diag::err_invalid_incomplete_type_use, FullRange))
1621 Inner = BTE->getSubExpr();
1622 if (
auto *CE = dyn_cast<ConstantExpr>(Inner);
1623 CE && CE->isImmediateInvocation())
1624 Inner = CE->getSubExpr();
1625 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1626 !isa<CXXScalarValueInitExpr>(Inner)) {
1638 :
SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1660 for (
const auto *D : R) {
1661 if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
1678 return llvm::none_of(PreventedBy, [&](
const FunctionDecl *FD) {
1680 "Only single-operand functions should be in PreventedBy");
1695 unsigned UsualParams = 1;
1697 if (S.
getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1703 if (S.
getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1713 struct UsualDeallocFnInfo {
1714 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
1716 : Found(Found), FD(dyn_cast<
FunctionDecl>(Found->getUnderlyingDecl())),
1718 CUDAPref(
Sema::CFP_Native) {
1722 unsigned NumBaseParams = 1;
1723 if (FD->isDestroyingOperatorDelete()) {
1728 if (NumBaseParams < FD->getNumParams() &&
1730 FD->getParamDecl(NumBaseParams)->getType(),
1736 if (NumBaseParams < FD->getNumParams() &&
1737 FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) {
1739 HasAlignValT =
true;
1748 explicit operator bool()
const {
return FD; }
1750 bool isBetterThan(
const UsualDeallocFnInfo &
Other,
bool WantSize,
1751 bool WantAlign)
const {
1755 if (Destroying !=
Other.Destroying)
1762 if (HasAlignValT !=
Other.HasAlignValT)
1763 return HasAlignValT == WantAlign;
1765 if (HasSizeT !=
Other.HasSizeT)
1766 return HasSizeT == WantSize;
1769 return CUDAPref >
Other.CUDAPref;
1774 bool Destroying, HasSizeT, HasAlignValT;
1794 UsualDeallocFnInfo Best;
1796 for (
auto I = R.
begin(), E = R.
end(); I != E; ++I) {
1797 UsualDeallocFnInfo Info(S, I.getPair());
1805 BestFns->push_back(Info);
1809 if (Best.isBetterThan(Info, WantSize, WantAlign))
1814 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
1819 BestFns->push_back(Info);
1833 if (!record)
return false;
1846 if (ops.
empty())
return false;
1858 return Best && Best.HasSizeT;
1882 std::optional<Expr *> ArraySize;
1908 if (
Expr *NumElts = (
Expr *)Array.NumElts) {
1909 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1924 NumElts,
nullptr, diag::err_new_array_nonconst,
AllowFold)
1941 DirectInitRange =
List->getSourceRange();
1944 PlacementLParen, PlacementArgs, PlacementRParen,
1945 TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
1954 return PLE->getNumExprs() == 0;
1955 if (isa<ImplicitValueInitExpr>(
Init))
1958 return !CCE->isListInitialization() &&
1959 CCE->getConstructor()->isDefaultConstructor();
1961 assert(isa<InitListExpr>(
Init) &&
1962 "Shouldn't create list CXXConstructExprs for arrays.");
1974 std::optional<unsigned> AlignmentParam;
1987 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
1992 bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete;
1993 Diag(Loc, diag::err_aligned_allocation_unavailable)
1995 << OSVersion.getAsString() << OSVersion.empty();
1996 Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
2006 std::optional<Expr *> ArraySize,
2012 if (DirectInitRange.
isValid()) {
2013 assert(
Initializer &&
"Have parens but no initializer.");
2020 "Initializer expression that cannot have been implicitly created.");
2027 "paren init for non-call init");
2035 switch (InitStyle) {
2047 DirectInitRange.
getEnd());
2053 llvm_unreachable(
"Unknown initialization kind");
2058 if (Deduced && !Deduced->isDeduced() &&
2059 isa<DeducedTemplateSpecializationType>(Deduced)) {
2062 Diag(*ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.
getBegin(),
2063 diag::err_deduced_class_template_compound_type)
2065 << (*ArraySize ? (*ArraySize)->getSourceRange() : TypeRange));
2070 AllocTypeInfo, Entity, Kind, Exprs);
2073 }
else if (Deduced && !Deduced->isDeduced()) {
2077 auto *ILE = cast<InitListExpr>(Exprs[0]);
2078 Inits =
MultiExprArg(ILE->getInits(), ILE->getNumInits());
2083 return ExprError(
Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
2084 << AllocType << TypeRange);
2085 if (Inits.size() > 1) {
2086 Expr *FirstBad = Inits[1];
2088 diag::err_auto_new_ctor_multiple_expressions)
2089 << AllocType << TypeRange);
2093 << AllocType << TypeRange;
2094 Expr *Deduce = Inits[0];
2095 if (isa<InitListExpr>(Deduce))
2098 << Braced << AllocType << TypeRange);
2104 return ExprError(
Diag(StartLoc, diag::err_auto_new_deduction_failure)
2105 << AllocType << Deduce->
getType() << TypeRange
2122 AllocType = Array->getElementType();
2142 if (ArraySize && *ArraySize &&
2143 (*ArraySize)->getType()->isNonOverloadPlaceholderType()) {
2146 ArraySize = result.
get();
2155 std::optional<uint64_t> KnownArraySize;
2156 if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) {
2165 (*ArraySize)->getType()->getAs<
RecordType>())
2167 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
2168 << (*ArraySize)->getType() << 0 <<
"'size_t'";
2175 SizeConvertDiagnoser(
Expr *ArraySize)
2177 ArraySize(ArraySize) {}
2181 return S.
Diag(Loc, diag::err_array_size_not_integral)
2187 return S.
Diag(Loc, diag::err_array_size_incomplete_type)
2193 return S.
Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
2204 return S.
Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
2218 ? diag::warn_cxx98_compat_array_size_conversion
2219 : diag::ext_array_size_conversion)
2222 } SizeDiagnoser(*ArraySize);
2230 ArraySize = ConvertedSize.
get();
2231 QualType SizeType = (*ArraySize)->getType();
2249 if (std::optional<llvm::APSInt>
Value =
2250 (*ArraySize)->getIntegerConstantExpr(
Context)) {
2251 if (
Value->isSigned() &&
Value->isNegative()) {
2253 diag::err_typecheck_negative_array_size)
2254 << (*ArraySize)->getSourceRange());
2258 unsigned ActiveSizeBits =
2262 Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large)
2266 KnownArraySize =
Value->getZExtValue();
2267 }
else if (TypeIdParens.
isValid()) {
2269 Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2270 << (*ArraySize)->getSourceRange()
2283 unsigned Alignment =
2286 bool PassAlignment =
getLangOpts().AlignedAllocation &&
2287 Alignment > NewAlignment;
2294 AllocType, ArraySize.has_value(), PassAlignment, PlacementArgs,
2295 OperatorNew, OperatorDelete))
2300 bool UsualArrayDeleteWantsSize =
false;
2302 UsualArrayDeleteWantsSize =
2315 unsigned NumImplicitArgs = PassAlignment ? 2 : 1;
2317 NumImplicitArgs, PlacementArgs, AllPlaceArgs,
2321 if (!AllPlaceArgs.empty())
2322 PlacementArgs = AllPlaceArgs;
2332 llvm::APInt SingleEltSize(
2336 std::optional<llvm::APInt> AllocationSize;
2339 AllocationSize = SingleEltSize;
2343 AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize)
2344 .umul_ov(SingleEltSize, Overflow);
2348 "Expected that all the overflows would have been handled already.");
2352 Context, AllocationSize.value_or(llvm::APInt::getZero(SizeTyWidth)),
2371 CK_IntegralCast, &AlignmentLiteral,
2376 CallArgs.reserve(NumImplicitArgs + PlacementArgs.size());
2377 CallArgs.emplace_back(AllocationSize
2378 ?
static_cast<Expr *
>(&AllocationSizeLiteral)
2379 : &OpaqueAllocationSize);
2381 CallArgs.emplace_back(&DesiredAlignment);
2382 CallArgs.insert(CallArgs.end(), PlacementArgs.begin(), PlacementArgs.end());
2386 checkCall(OperatorNew, Proto,
nullptr, CallArgs,
2387 false, StartLoc, Range, CallType);
2391 if (PlacementArgs.empty() && !PassAlignment &&
2395 if (Alignment > NewAlignment)
2396 Diag(StartLoc, diag::warn_overaligned_type)
2407 SourceRange InitRange(Exprs.front()->getBeginLoc(),
2408 Exprs.back()->getEndLoc());
2409 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2429 InitType = AllocType;
2442 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.
get()))
2443 FullInit = Binder->getSubExpr();
2458 if (ArraySize && !*ArraySize) {
2466 Diag(TypeRange.
getEnd(), diag::err_new_array_size_unknown_from_init)
2478 if (OperatorDelete) {
2485 PassAlignment, UsualArrayDeleteWantsSize,
2486 PlacementArgs, TypeIdParens, ArraySize, InitStyle,
2498 return Diag(Loc, diag::err_bad_new_type)
2499 << AllocType << 0 << R;
2501 return Diag(Loc, diag::err_bad_new_type)
2502 << AllocType << 1 << R;
2505 Loc, AllocType, diag::err_new_incomplete_or_sizeless_type, R))
2508 diag::err_allocation_of_abstract_type))
2511 return Diag(Loc, diag::err_variably_modified_new_type)
2515 return Diag(Loc, diag::err_address_space_qualified_new)
2523 return Diag(Loc, diag::err_arc_new_array_without_ownership)
2538 Alloc != AllocEnd; ++Alloc) {
2575 if (PassAlignment) {
2576 PassAlignment =
false;
2578 Args.erase(Args.begin() + 1);
2580 Operator, &Candidates, AlignArg,
2606 (Args[1]->getType()->isObjectPointerType() ||
2607 Args[1]->getType()->isArrayType())) {
2608 S.
Diag(R.
getNameLoc(), diag::err_need_header_before_placement_new)
2623 if (AlignedCandidates) {
2625 return C.Function->getNumParams() > 1 &&
2626 C.Function->getParamDecl(1)->getType()->isAlignValT();
2630 AlignedArgs.reserve(Args.size() + 1);
2631 AlignedArgs.push_back(Args[0]);
2632 AlignedArgs.push_back(AlignArg);
2633 AlignedArgs.append(Args.begin() + 1, Args.end());
2646 if (AlignedCandidates)
2647 AlignedCandidates->
NoteCandidates(S, AlignedArgs, AlignedCands,
"",
2657 S.
PDiag(diag::err_ovl_ambiguous_call)
2667 S.
PDiag(diag::err_ovl_deleted_call)
2674 llvm_unreachable(
"Unreachable, bad result from BestViableFunction");
2696 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2706 AllocArgs.push_back(&Size);
2709 if (PassAlignment) {
2715 AllocArgs.push_back(&Align);
2717 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
2726 IsArray ? OO_Array_New : OO_New);
2758 if (PlaceArgs.empty()) {
2759 Diag(StartLoc, diag::err_openclcxx_not_supported) <<
"default new";
2761 Diag(StartLoc, diag::err_openclcxx_placement_new);
2766 assert(!R.
empty() &&
"implicitly declared allocation functions not found");
2767 assert(!R.
isAmbiguous() &&
"global allocation functions are ambiguous");
2773 OperatorNew,
nullptr,
2780 OperatorDelete =
nullptr;
2815 while (Filter.hasNext()) {
2816 auto *FD = dyn_cast<FunctionDecl>(Filter.next()->getUnderlyingDecl());
2817 if (FD && FD->isDestroyingOperatorDelete())
2823 bool FoundGlobalDelete = FoundDelete.
empty();
2824 if (FoundDelete.
empty()) {
2851 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->
param_size() != 1 ||
2854 if (isPlacementNew) {
2871 for (
unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2872 ArgTypes.push_back(Proto->getParamType(I));
2876 EPI.
Variadic = Proto->isVariadic();
2878 ExpectedFunctionType
2883 DEnd = FoundDelete.
end();
2887 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2895 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2898 ExpectedFunctionType,
2900 ExpectedFunctionType))
2901 Matches.push_back(std::make_pair(D.getPair(), Fn));
2917 *
this, FoundDelete, FoundGlobalDelete,
2921 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2925 for (
auto Fn : BestDeallocFns)
2926 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
2934 if (Matches.size() == 1) {
2935 OperatorDelete = Matches[0].second;
2945 UsualDeallocFnInfo Info(*
this,
2951 bool IsSizedDelete = Info.HasSizeT;
2952 if (IsSizedDelete && !FoundGlobalDelete) {
2953 auto NonSizedDelete =
2956 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2957 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2958 IsSizedDelete =
false;
2961 if (IsSizedDelete) {
2965 PlaceArgs.back()->getEndLoc());
2966 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2975 }
else if (!Matches.empty()) {
2979 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2980 << DeleteName << AllocElemType;
2982 for (
auto &Match : Matches)
2983 Diag(Match.second->getLocation(),
2984 diag::note_member_declared_here) << DeleteName;
3071 if (TheGlobalModuleFragment) {
3086 if (TheGlobalModuleFragment) {
3087 AlignValT->setModuleOwnershipKind(
3089 AlignValT->setLocalOwningModule(TheGlobalModuleFragment);
3094 AlignValT->setImplicit(
true);
3107 Params.push_back(Param);
3110 bool HasSizedVariant =
getLangOpts().SizedDeallocation &&
3111 (Kind == OO_Delete || Kind == OO_Array_Delete);
3112 bool HasAlignedVariant =
getLangOpts().AlignedAllocation;
3114 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
3115 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
3116 for (
int Sized = 0; Sized < NumSizeVariants; ++Sized) {
3118 Params.push_back(SizeT);
3120 for (
int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
3133 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
3134 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
3135 DeclareGlobalAllocationFunctions(OO_Delete,
Context.
VoidTy, VoidPtr);
3136 DeclareGlobalAllocationFunctions(OO_Array_Delete,
Context.
VoidTy, VoidPtr);
3139 PopGlobalModuleFragment();
3152 Alloc != AllocEnd; ++Alloc) {
3156 if (
Func->getNumParams() == Params.size()) {
3158 for (
auto *
P :
Func->parameters())
3159 FuncParams.push_back(
3165 Func->setVisibleDespiteOwningModule();
3173 false,
false,
true));
3176 bool HasBadAllocExceptionSpec
3177 = (Name.getCXXOverloadedOperator() == OO_New ||
3178 Name.getCXXOverloadedOperator() == OO_Array_New);
3179 if (HasBadAllocExceptionSpec) {
3182 assert(
StdBadAlloc &&
"Must have std::bad_alloc declared");
3194 auto CreateAllocationFunctionDecl = [&](
Attr *ExtraAttr) {
3204 if (HasBadAllocExceptionSpec &&
getLangOpts().NewInfallible &&
3219 if (TheGlobalModuleFragment) {
3225 Alloc->
addAttr(VisibilityAttr::CreateImplicit(
3227 ? VisibilityAttr::Hidden
3228 : VisibilityAttr::Default));
3235 ParamDecls.back()->setImplicit();
3237 Alloc->setParams(ParamDecls);
3246 CreateAllocationFunctionDecl(
nullptr);
3250 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(
Context));
3251 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(
Context));
3256 bool CanProvideSize,
3270 assert(
Result.FD &&
"operator delete missing from global scope?");
3282 return OperatorDelete;
3294 bool WantSize,
bool WantAligned) {
3312 Overaligned, &Matches);
3315 if (Matches.size() == 1) {
3316 Operator = cast<CXXMethodDecl>(Matches[0].FD);
3321 Diag(StartLoc, diag::err_deleted_function_use);
3337 if (!Matches.empty()) {
3339 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
3341 for (
auto &Match : Matches)
3342 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
3349 if (!Found.
empty()) {
3351 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
3355 Diag(D->getUnderlyingDecl()->getLocation(),
3356 diag::note_member_declared_here) << Name;
3368class MismatchingNewDeleteDetector {
3370 enum MismatchResult {
3376 MemberInitMismatches,
3385 explicit MismatchingNewDeleteDetector(
bool EndOfTU)
3386 : Field(nullptr), IsArrayForm(
false), EndOfTU(EndOfTU),
3387 HasUndefinedConstructors(
false) {}
3404 MismatchResult analyzeField(
FieldDecl *Field,
bool DeleteWasArrayForm);
3414 bool HasUndefinedConstructors;
3426 MismatchResult analyzeMemberExpr(
const MemberExpr *ME);
3449 MismatchResult analyzeInClassInitializer();
3453MismatchingNewDeleteDetector::MismatchResult
3454MismatchingNewDeleteDetector::analyzeDeleteExpr(
const CXXDeleteExpr *DE) {
3456 assert(DE &&
"Expected delete-expression");
3459 if (
const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3460 return analyzeMemberExpr(ME);
3461 }
else if (
const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3462 if (!hasMatchingVarInit(D))
3463 return VarInitMismatches;
3469MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(
const Expr *E) {
3470 assert(E !=
nullptr &&
"Expected a valid initializer expression");
3472 if (
const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3473 if (ILE->getNumInits() == 1)
3474 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3477 return dyn_cast_or_null<const CXXNewExpr>(E);
3480bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3484 (NE = getNewExprFromInitListOrExpr(CI->
getInit()))) {
3485 if (
NE->isArray() == IsArrayForm)
3488 NewExprs.push_back(NE);
3493bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3499 HasUndefinedConstructors =
true;
3502 for (
const auto *CI : cast<const CXXConstructorDecl>(
Definition)->inits()) {
3503 if (hasMatchingNewInCtorInit(CI))
3509MismatchingNewDeleteDetector::MismatchResult
3510MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3511 assert(Field !=
nullptr &&
"This should be called only for members");
3512 const Expr *InitExpr =
Field->getInClassInitializer();
3514 return EndOfTU ? NoMismatch : AnalyzeLater;
3515 if (
const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
3516 if (
NE->isArray() != IsArrayForm) {
3517 NewExprs.push_back(NE);
3518 return MemberInitMismatches;
3524MismatchingNewDeleteDetector::MismatchResult
3525MismatchingNewDeleteDetector::analyzeField(
FieldDecl *Field,
3526 bool DeleteWasArrayForm) {
3527 assert(Field !=
nullptr &&
"Analysis requires a valid class member.");
3528 this->Field =
Field;
3529 IsArrayForm = DeleteWasArrayForm;
3531 for (
const auto *CD : RD->
ctors()) {
3532 if (hasMatchingNewInCtor(CD))
3535 if (HasUndefinedConstructors)
3536 return EndOfTU ? NoMismatch : AnalyzeLater;
3537 if (!NewExprs.empty())
3538 return MemberInitMismatches;
3539 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3543MismatchingNewDeleteDetector::MismatchResult
3544MismatchingNewDeleteDetector::analyzeMemberExpr(
const MemberExpr *ME) {
3545 assert(ME !=
nullptr &&
"Expected a member expression");
3547 return analyzeField(F, IsArrayForm);
3551bool MismatchingNewDeleteDetector::hasMatchingVarInit(
const DeclRefExpr *D) {
3554 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3555 NE->isArray() != IsArrayForm) {
3556 NewExprs.push_back(NE);
3559 return NewExprs.empty();
3564 const MismatchingNewDeleteDetector &Detector) {
3567 if (!Detector.IsArrayForm)
3576 SemaRef.
Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3577 << Detector.IsArrayForm << H;
3579 for (
const auto *NE : Detector.NewExprs)
3580 SemaRef.
Diag(NE->getExprLoc(), diag::note_allocated_here)
3581 << Detector.IsArrayForm;
3584void Sema::AnalyzeDeleteExprMismatch(
const CXXDeleteExpr *DE) {
3587 MismatchingNewDeleteDetector Detector(
false);
3588 switch (Detector.analyzeDeleteExpr(DE)) {
3589 case MismatchingNewDeleteDetector::VarInitMismatches:
3590 case MismatchingNewDeleteDetector::MemberInitMismatches: {
3594 case MismatchingNewDeleteDetector::AnalyzeLater: {
3599 case MismatchingNewDeleteDetector::NoMismatch:
3605 bool DeleteWasArrayForm) {
3606 MismatchingNewDeleteDetector Detector(
true);
3607 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3608 case MismatchingNewDeleteDetector::VarInitMismatches:
3609 llvm_unreachable(
"This analysis should have been done for class members.");
3610 case MismatchingNewDeleteDetector::AnalyzeLater:
3611 llvm_unreachable(
"Analysis cannot be postponed any point beyond end of "
3612 "translation unit.");
3613 case MismatchingNewDeleteDetector::MemberInitMismatches:
3616 case MismatchingNewDeleteDetector::NoMismatch:
3627 bool ArrayForm,
Expr *ExE) {
3637 bool ArrayFormAsWritten = ArrayForm;
3638 bool UsualArrayDeleteWantsSize =
false;
3656 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
3663 return S.
Diag(Loc, diag::err_delete_operand) << T;
3668 return S.
Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3674 return S.
Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3685 return S.
Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3697 llvm_unreachable(
"conversion functions are permitted");
3705 if (!Converter.match(
Type))
3716 diag::err_address_space_qualified_delete)
3725 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
3735 diag::warn_delete_incomplete, Ex.
get())) {
3737 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3742 Diag(StartLoc, diag::warn_delete_array_type)
3749 ArrayForm ? OO_Array_Delete : OO_Delete);
3763 UsualArrayDeleteWantsSize =
3768 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
3769 UsualArrayDeleteWantsSize =
3770 UsualDeallocFnInfo(*
this,
3789 if (!OperatorDelete) {
3791 Diag(StartLoc, diag::err_openclcxx_not_supported) <<
"default delete";
3796 bool CanProvideSize =
3797 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3803 Overaligned, DeleteName);
3810 bool IsVirtualDelete =
false;
3814 PDiag(diag::err_access_dtor) << PointeeElem);
3815 IsVirtualDelete = Dtor->isVirtual();
3844 UsualArrayDeleteWantsSize, OperatorDelete, Ex.
get(), StartLoc);
3845 AnalyzeDeleteExprMismatch(
Result);
3854 IsDelete ? OO_Delete : OO_New);
3858 assert(!R.
empty() &&
"implicitly declared allocation functions not found");
3859 assert(!R.
isAmbiguous() &&
"global allocation functions are ambiguous");
3868 FnOvl != FnOvlEnd; ++FnOvl) {
3871 NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3895 "class members should not be considered");
3898 S.
Diag(R.
getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3899 << (IsDelete ? 1 : 0) << Range;
3900 S.
Diag(FnDecl->
getLocation(), diag::note_non_usual_function_declared_here)
3912 S.
PDiag(diag::err_ovl_no_viable_function_in_call)
3920 S.
PDiag(diag::err_ovl_ambiguous_call)
3933 llvm_unreachable(
"Unreachable, bad result from BestViableFunction");
3937Sema::SemaBuiltinOperatorNewDeleteOverloaded(
ExprResult TheCallResult,
3939 CallExpr *TheCall = cast<CallExpr>(TheCallResult.
get());
3942 << (IsDelete ?
"__builtin_operator_delete" :
"__builtin_operator_new")
3952 OperatorNewOrDelete))
3954 assert(OperatorNewOrDelete &&
"should be found");
3960 for (
unsigned i = 0; i != TheCall->
getNumArgs(); ++i) {
3971 assert(Callee &&
Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
3972 "Callee expected to be implicit cast to a builtin function pointer");
3975 return TheCallResult;
3979 bool IsDelete,
bool CallCanBeVirtual,
3980 bool WarnOnNonAbstractTypes,
4007 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
4009 }
else if (WarnOnNonAbstractTypes) {
4012 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
4016 std::string TypeStr;
4018 Diag(DtorLoc, diag::note_delete_non_virtual)
4048 diag::err_invalid_use_of_function_type)
4052 diag::err_invalid_use_of_array_type)
4070 llvm_unreachable(
"unexpected condition kind");
4097 diag::err_constexpr_if_condition_expression_is_not_constant);
4109 From = Cast->getSubExpr();
4121 if (!ToPtrType->getPointeeType().hasQualifiers()) {
4122 switch (StrLit->getKind()) {
4129 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
4130 ToPointeeType->getKind() == BuiltinType::Char_S);
4135 assert(
false &&
"Unevaluated string literal in expression");
4150 bool HadMultipleCandidates,
4153 default: llvm_unreachable(
"Unhandled cast kind!");
4154 case CK_ConstructorConversion: {
4159 diag::err_allocation_of_abstract_type))
4172 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
4173 ConstructorArgs, HadMultipleCandidates,
4174 false,
false,
false,
4182 case CK_UserDefinedConversion: {
4192 HadMultipleCandidates);
4197 CK_UserDefinedConversion,
Result.get(),
4198 nullptr,
Result.get()->getValueKind(),
4235 assert(FD &&
"no conversion function for user-defined conversion seq");
4237 CastKind = CK_UserDefinedConversion;
4245 CastKind = CK_ConstructorConversion;
4273 From = CastArg.
get();
4287 PDiag(diag::err_typecheck_ambiguous_condition)
4293 llvm_unreachable(
"bad conversion");
4300 ToType, From->
getType(), From, Action);
4301 assert(Diagnosed &&
"failed to diagnose bad conversion"); (void)Diagnosed;
4340 false,
false,
false,
4347 false,
false,
false,
4380 ToAtomicType = ToType;
4381 ToType = ToAtomic->getValueType();
4384 QualType InitialFromType = FromType;
4386 switch (SCS.
First) {
4389 FromType = FromAtomic->getValueType().getUnqualifiedType();
4402 From = FromRes.
get();
4422 llvm_unreachable(
"Improper first standard conversion");
4459 "only enums with fixed underlying type can promote to bool");
4484 CK = CK_FloatingComplexCast;
4486 CK = CK_FloatingComplexToIntegralComplex;
4488 CK = CK_IntegralComplexToFloatingComplex;
4490 CK = CK_IntegralComplexCast;
4511 "Attempting implicit fixed point conversion without a fixed "
4516 nullptr, CCK).
get();
4520 nullptr, CCK).
get();
4524 nullptr, CCK).
get();
4528 nullptr, CCK).
get();
4532 nullptr, CCK).
get();
4536 nullptr, CCK).
get();
4541 nullptr, CCK).
get();
4550 diag::ext_typecheck_convert_incompatible_pointer)
4555 diag::ext_typecheck_convert_incompatible_pointer)
4562 }
else if (
getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4568 Diag(From->
getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4597 if (Kind == CK_BlockPointerToObjCPointerCast) {
4651 &BasePath, CCK).
get();
4680 QualType ElType = ToComplex->getElementType();
4688 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).
get();
4692 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).
get();
4696 isFloatingComplex ? CK_FloatingRealToComplex
4697 : CK_IntegralRealToComplex).
get();
4702 QualType ElType = FromComplex->getElementType();
4707 isFloatingComplex ? CK_FloatingComplexToReal
4708 : CK_IntegralComplexToReal,
4717 isFloatingComplex ? CK_FloatingCast
4718 : CK_IntegralToFloating,
4724 isFloatingComplex ? CK_FloatingToIntegral
4740 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
4753 From = FromRes.
get();
4755 "Improper transparent union conversion");
4763 CK_ZeroToOCLOpaqueType,
4775 llvm_unreachable(
"Improper second standard conversion");
4778 switch (SCS.
Third) {
4801 CK = CK_AddressSpaceConversion;
4806 CK = CK_AddressSpaceConversion;
4812 << InitialFromType << ToType;
4823 ? diag::ext_deprecated_string_literal_conversion
4824 : diag::warn_deprecated_string_literal_conversion)
4832 llvm_unreachable(
"Improper third standard conversion");
4837 if (!ToAtomicType.
isNull()) {
4883 default: llvm_unreachable(
"not a UTT");
4885 case UTT_IsCompleteType:
4893 case UTT_IsIntegral:
4894 case UTT_IsFloatingPoint:
4896 case UTT_IsBoundedArray:
4898 case UTT_IsNullPointer:
4899 case UTT_IsReferenceable:
4900 case UTT_IsLvalueReference:
4901 case UTT_IsRvalueReference:
4902 case UTT_IsMemberFunctionPointer:
4903 case UTT_IsMemberObjectPointer:
4905 case UTT_IsScopedEnum:
4908 case UTT_IsFunction:
4909 case UTT_IsReference:
4910 case UTT_IsArithmetic:
4911 case UTT_IsFundamental:
4914 case UTT_IsCompound:
4915 case UTT_IsMemberPointer:
4924 case UTT_IsVolatile:
4926 case UTT_IsUnboundedA