SemaExceptionSpec.cpp [plain text]
#include "clang/Sema/SemaInternal.h"
#include "clang/AST/ASTMutationListener.h"
#include "clang/AST/CXXInheritance.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/TypeLoc.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallString.h"
namespace clang {
static const FunctionProtoType *GetUnderlyingFunction(QualType T)
{
if (const PointerType *PtrTy = T->getAs<PointerType>())
T = PtrTy->getPointeeType();
else if (const ReferenceType *RefTy = T->getAs<ReferenceType>())
T = RefTy->getPointeeType();
else if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
T = MPTy->getPointeeType();
return T->getAs<FunctionProtoType>();
}
bool Sema::isLibstdcxxEagerExceptionSpecHack(const Declarator &D) {
auto *RD = dyn_cast<CXXRecordDecl>(CurContext);
if (!RD || RD->getEnclosingNamespaceContext() != getStdNamespace() ||
!RD->getIdentifier() || !RD->getDescribedClassTemplate() ||
!D.getIdentifier() || !D.getIdentifier()->isStr("swap"))
return false;
if (!Context.getSourceManager().isInSystemHeader(D.getLocStart()))
return false;
return llvm::StringSwitch<bool>(RD->getIdentifier()->getName())
.Case("array", true)
.Case("pair", true)
.Case("priority_queue", true)
.Case("stack", true)
.Case("queue", true)
.Default(false);
}
bool Sema::CheckSpecifiedExceptionType(QualType &T, SourceRange Range) {
if (T->isArrayType())
T = Context.getArrayDecayedType(T);
else if (T->isFunctionType())
T = Context.getPointerType(T);
int Kind = 0;
QualType PointeeT = T;
if (const PointerType *PT = T->getAs<PointerType>()) {
PointeeT = PT->getPointeeType();
Kind = 1;
if (PointeeT->isVoidType())
return false;
} else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
PointeeT = RT->getPointeeType();
Kind = 2;
if (RT->isRValueReferenceType()) {
Diag(Range.getBegin(), diag::err_rref_in_exception_spec)
<< T << Range;
return true;
}
}
if (!(PointeeT->isRecordType() &&
PointeeT->getAs<RecordType>()->isBeingDefined()) &&
RequireCompleteType(Range.getBegin(), PointeeT,
diag::err_incomplete_in_exception_spec, Kind, Range))
return true;
return false;
}
bool Sema::CheckDistantExceptionSpec(QualType T) {
if (const PointerType *PT = T->getAs<PointerType>())
T = PT->getPointeeType();
else if (const MemberPointerType *PT = T->getAs<MemberPointerType>())
T = PT->getPointeeType();
else
return false;
const FunctionProtoType *FnT = T->getAs<FunctionProtoType>();
if (!FnT)
return false;
return FnT->hasExceptionSpec();
}
const FunctionProtoType *
Sema::ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT) {
if (FPT->getExceptionSpecType() == EST_Unparsed) {
Diag(Loc, diag::err_exception_spec_not_parsed);
return nullptr;
}
if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
return FPT;
FunctionDecl *SourceDecl = FPT->getExceptionSpecDecl();
const FunctionProtoType *SourceFPT =
SourceDecl->getType()->castAs<FunctionProtoType>();
if (!isUnresolvedExceptionSpec(SourceFPT->getExceptionSpecType()))
return SourceFPT;
if (SourceFPT->getExceptionSpecType() == EST_Unevaluated)
EvaluateImplicitExceptionSpec(Loc, cast<CXXMethodDecl>(SourceDecl));
else
InstantiateExceptionSpec(Loc, SourceDecl);
const FunctionProtoType *Proto =
SourceDecl->getType()->castAs<FunctionProtoType>();
if (Proto->getExceptionSpecType() == clang::EST_Unparsed) {
Diag(Loc, diag::err_exception_spec_not_parsed);
Proto = nullptr;
}
return Proto;
}
void
Sema::UpdateExceptionSpec(FunctionDecl *FD,
const FunctionProtoType::ExceptionSpecInfo &ESI) {
if (!isUnresolvedExceptionSpec(ESI.Type))
if (auto *Listener = getASTMutationListener())
Listener->ResolvedExceptionSpec(FD);
for (auto *Redecl : FD->redecls())
Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
}
static bool hasImplicitExceptionSpec(FunctionDecl *Decl) {
if (!isa<CXXDestructorDecl>(Decl) &&
Decl->getDeclName().getCXXOverloadedOperator() != OO_Delete &&
Decl->getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
return false;
if (!Decl->getTypeSourceInfo())
return isa<CXXDestructorDecl>(Decl);
const FunctionProtoType *Ty =
Decl->getTypeSourceInfo()->getType()->getAs<FunctionProtoType>();
return !Ty->hasExceptionSpec();
}
bool Sema::CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New) {
OverloadedOperatorKind OO = New->getDeclName().getCXXOverloadedOperator();
bool IsOperatorNew = OO == OO_New || OO == OO_Array_New;
bool MissingExceptionSpecification = false;
bool MissingEmptyExceptionSpecification = false;
unsigned DiagID = diag::err_mismatched_exception_spec;
bool ReturnValueOnError = true;
if (getLangOpts().MicrosoftExt) {
DiagID = diag::ext_mismatched_exception_spec;
ReturnValueOnError = false;
}
if (!CheckEquivalentExceptionSpec(
PDiag(DiagID), PDiag(diag::note_previous_declaration),
Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
New->getType()->getAs<FunctionProtoType>(), New->getLocation(),
&MissingExceptionSpecification, &MissingEmptyExceptionSpecification,
true, IsOperatorNew)) {
if (getLangOpts().CPlusPlus11 &&
hasImplicitExceptionSpec(Old) != hasImplicitExceptionSpec(New)) {
Diag(New->getLocation(), diag::ext_implicit_exception_spec_mismatch)
<< hasImplicitExceptionSpec(Old);
if (Old->getLocation().isValid())
Diag(Old->getLocation(), diag::note_previous_declaration);
}
return false;
}
if (!MissingExceptionSpecification)
return ReturnValueOnError;
const FunctionProtoType *NewProto =
New->getType()->castAs<FunctionProtoType>();
if (MissingEmptyExceptionSpecification && NewProto &&
(Old->getLocation().isInvalid() ||
Context.getSourceManager().isInSystemHeader(Old->getLocation())) &&
Old->isExternC()) {
New->setType(Context.getFunctionType(
NewProto->getReturnType(), NewProto->getParamTypes(),
NewProto->getExtProtoInfo().withExceptionSpec(EST_DynamicNone)));
return false;
}
const FunctionProtoType *OldProto =
Old->getType()->castAs<FunctionProtoType>();
FunctionProtoType::ExceptionSpecInfo ESI = OldProto->getExceptionSpecType();
if (ESI.Type == EST_Dynamic) {
ESI.Exceptions = OldProto->exceptions();
}
if (ESI.Type == EST_ComputedNoexcept) {
New->setInvalidDecl();
} else {
New->setType(Context.getFunctionType(
NewProto->getReturnType(), NewProto->getParamTypes(),
NewProto->getExtProtoInfo().withExceptionSpec(ESI)));
}
if (getLangOpts().MicrosoftExt && ESI.Type != EST_ComputedNoexcept) {
DiagID = diag::ext_ms_missing_exception_specification;
ReturnValueOnError = false;
} else if (New->isReplaceableGlobalAllocationFunction() &&
ESI.Type != EST_ComputedNoexcept) {
DiagID = diag::ext_missing_exception_specification;
ReturnValueOnError = false;
} else {
DiagID = diag::err_missing_exception_specification;
ReturnValueOnError = true;
}
SmallString<128> ExceptionSpecString;
llvm::raw_svector_ostream OS(ExceptionSpecString);
switch (OldProto->getExceptionSpecType()) {
case EST_DynamicNone:
OS << "throw()";
break;
case EST_Dynamic: {
OS << "throw(";
bool OnFirstException = true;
for (const auto &E : OldProto->exceptions()) {
if (OnFirstException)
OnFirstException = false;
else
OS << ", ";
OS << E.getAsString(getPrintingPolicy());
}
OS << ")";
break;
}
case EST_BasicNoexcept:
OS << "noexcept";
break;
case EST_ComputedNoexcept:
OS << "noexcept(";
assert(OldProto->getNoexceptExpr() != nullptr && "Expected non-null Expr");
OldProto->getNoexceptExpr()->printPretty(OS, nullptr, getPrintingPolicy());
OS << ")";
break;
default:
llvm_unreachable("This spec type is compatible with none.");
}
SourceLocation FixItLoc;
if (TypeSourceInfo *TSInfo = New->getTypeSourceInfo()) {
TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
if (auto FTLoc = TL.getAs<FunctionProtoTypeLoc>())
if (!FTLoc.getTypePtr()->hasTrailingReturn())
FixItLoc = getLocForEndOfToken(FTLoc.getLocalRangeEnd());
}
if (FixItLoc.isInvalid())
Diag(New->getLocation(), DiagID)
<< New << OS.str();
else {
Diag(New->getLocation(), DiagID)
<< New << OS.str()
<< FixItHint::CreateInsertion(FixItLoc, " " + OS.str().str());
}
if (Old->getLocation().isValid())
Diag(Old->getLocation(), diag::note_previous_declaration);
return ReturnValueOnError;
}
bool Sema::CheckEquivalentExceptionSpec(
const FunctionProtoType *Old, SourceLocation OldLoc,
const FunctionProtoType *New, SourceLocation NewLoc) {
unsigned DiagID = diag::err_mismatched_exception_spec;
if (getLangOpts().MicrosoftExt)
DiagID = diag::ext_mismatched_exception_spec;
bool Result = CheckEquivalentExceptionSpec(PDiag(DiagID),
PDiag(diag::note_previous_declaration), Old, OldLoc, New, NewLoc);
if (getLangOpts().MicrosoftExt)
return false;
return Result;
}
bool Sema::CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
const PartialDiagnostic & NoteID,
const FunctionProtoType *Old,
SourceLocation OldLoc,
const FunctionProtoType *New,
SourceLocation NewLoc,
bool *MissingExceptionSpecification,
bool*MissingEmptyExceptionSpecification,
bool AllowNoexceptAllMatchWithNoSpec,
bool IsOperatorNew) {
if (!getLangOpts().CXXExceptions)
return false;
if (MissingExceptionSpecification)
*MissingExceptionSpecification = false;
if (MissingEmptyExceptionSpecification)
*MissingEmptyExceptionSpecification = false;
Old = ResolveExceptionSpec(NewLoc, Old);
if (!Old)
return false;
New = ResolveExceptionSpec(NewLoc, New);
if (!New)
return false;
ExceptionSpecificationType OldEST = Old->getExceptionSpecType();
ExceptionSpecificationType NewEST = New->getExceptionSpecType();
assert(!isUnresolvedExceptionSpec(OldEST) &&
!isUnresolvedExceptionSpec(NewEST) &&
"Shouldn't see unknown exception specifications here");
if (OldEST == EST_None && NewEST == EST_None)
return false;
FunctionProtoType::NoexceptResult OldNR = Old->getNoexceptSpec(Context);
FunctionProtoType::NoexceptResult NewNR = New->getNoexceptSpec(Context);
if (OldNR == FunctionProtoType::NR_BadNoexcept ||
NewNR == FunctionProtoType::NR_BadNoexcept)
return false;
if (OldNR == NewNR &&
OldNR != FunctionProtoType::NR_NoNoexcept &&
NewNR != FunctionProtoType::NR_NoNoexcept)
return false;
if (OldNR != NewNR &&
OldNR != FunctionProtoType::NR_NoNoexcept &&
NewNR != FunctionProtoType::NR_NoNoexcept) {
Diag(NewLoc, DiagID);
if (NoteID.getDiagID() != 0 && OldLoc.isValid())
Diag(OldLoc, NoteID);
return true;
}
if (OldEST == EST_MSAny && NewEST == EST_MSAny)
return false;
if ((OldEST == EST_None && NewEST == EST_MSAny) ||
(OldEST == EST_MSAny && NewEST == EST_None))
return false;
if (OldEST == EST_MSAny && NewNR == FunctionProtoType::NR_Throw)
return false;
if (NewEST == EST_MSAny && OldNR == FunctionProtoType::NR_Throw)
return false;
if (AllowNoexceptAllMatchWithNoSpec) {
if (OldEST == EST_None && NewNR == FunctionProtoType::NR_Throw)
return false;
if (NewEST == EST_None && OldNR == FunctionProtoType::NR_Throw)
return false;
}
bool OldNonThrowing = OldNR == FunctionProtoType::NR_Nothrow ||
OldEST == EST_DynamicNone;
bool NewNonThrowing = NewNR == FunctionProtoType::NR_Nothrow ||
NewEST == EST_DynamicNone;
if (OldNonThrowing && NewNonThrowing)
return false;
if (getLangOpts().CPlusPlus11 && IsOperatorNew) {
const FunctionProtoType *WithExceptions = nullptr;
if (OldEST == EST_None && NewEST == EST_Dynamic)
WithExceptions = New;
else if (OldEST == EST_Dynamic && NewEST == EST_None)
WithExceptions = Old;
if (WithExceptions && WithExceptions->getNumExceptions() == 1) {
QualType Exception = *WithExceptions->exception_begin();
if (CXXRecordDecl *ExRecord = Exception->getAsCXXRecordDecl()) {
IdentifierInfo* Name = ExRecord->getIdentifier();
if (Name && Name->getName() == "bad_alloc") {
if (ExRecord->isInStdNamespace()) {
return false;
}
}
}
}
}
if (OldEST != EST_Dynamic || NewEST != EST_Dynamic) {
if (MissingExceptionSpecification && Old->hasExceptionSpec() &&
!New->hasExceptionSpec()) {
*MissingExceptionSpecification = true;
if (MissingEmptyExceptionSpecification && OldNonThrowing) {
*MissingEmptyExceptionSpecification = true;
}
return true;
}
Diag(NewLoc, DiagID);
if (NoteID.getDiagID() != 0 && OldLoc.isValid())
Diag(OldLoc, NoteID);
return true;
}
assert(OldEST == EST_Dynamic && NewEST == EST_Dynamic &&
"Exception compatibility logic error: non-dynamic spec slipped through.");
bool Success = true;
llvm::SmallPtrSet<CanQualType, 8> OldTypes, NewTypes;
for (const auto &I : Old->exceptions())
OldTypes.insert(Context.getCanonicalType(I).getUnqualifiedType());
for (const auto &I : New->exceptions()) {
CanQualType TypePtr = Context.getCanonicalType(I).getUnqualifiedType();
if(OldTypes.count(TypePtr))
NewTypes.insert(TypePtr);
else
Success = false;
}
Success = Success && OldTypes.size() == NewTypes.size();
if (Success) {
return false;
}
Diag(NewLoc, DiagID);
if (NoteID.getDiagID() != 0 && OldLoc.isValid())
Diag(OldLoc, NoteID);
return true;
}
bool Sema::CheckExceptionSpecSubset(
const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
const FunctionProtoType *Superset, SourceLocation SuperLoc,
const FunctionProtoType *Subset, SourceLocation SubLoc) {
if (!getLangOpts().CXXExceptions)
return false;
if (!SubLoc.isValid())
SubLoc = SuperLoc;
Superset = ResolveExceptionSpec(SuperLoc, Superset);
if (!Superset)
return false;
Subset = ResolveExceptionSpec(SubLoc, Subset);
if (!Subset)
return false;
ExceptionSpecificationType SuperEST = Superset->getExceptionSpecType();
if (SuperEST == EST_None || SuperEST == EST_MSAny)
return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
FunctionProtoType::NoexceptResult SuperNR =Superset->getNoexceptSpec(Context);
if (SuperNR == FunctionProtoType::NR_BadNoexcept ||
SuperNR == FunctionProtoType::NR_Dependent)
return false;
if (SuperNR == FunctionProtoType::NR_Throw)
return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
ExceptionSpecificationType SubEST = Subset->getExceptionSpecType();
assert(!isUnresolvedExceptionSpec(SuperEST) &&
!isUnresolvedExceptionSpec(SubEST) &&
"Shouldn't see unknown exception specifications here");
if (SubEST == EST_None || SubEST == EST_MSAny) {
Diag(SubLoc, DiagID);
if (NoteID.getDiagID() != 0)
Diag(SuperLoc, NoteID);
return true;
}
FunctionProtoType::NoexceptResult SubNR = Subset->getNoexceptSpec(Context);
if (SubNR == FunctionProtoType::NR_BadNoexcept ||
SubNR == FunctionProtoType::NR_Dependent)
return false;
if (SubNR == FunctionProtoType::NR_Throw) {
Diag(SubLoc, DiagID);
if (NoteID.getDiagID() != 0)
Diag(SuperLoc, NoteID);
return true;
}
if (SubEST == EST_DynamicNone || SubNR == FunctionProtoType::NR_Nothrow)
return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
if (SuperEST == EST_DynamicNone || SuperNR == FunctionProtoType::NR_Nothrow) {
Diag(SubLoc, DiagID);
if (NoteID.getDiagID() != 0)
Diag(SuperLoc, NoteID);
return true;
}
assert(SuperEST == EST_Dynamic && SubEST == EST_Dynamic &&
"Exception spec subset: non-dynamic case slipped through.");
for (const auto &SubI : Subset->exceptions()) {
QualType CanonicalSubT = Context.getCanonicalType(SubI);
bool SubIsPointer = false;
if (const ReferenceType *RefTy = CanonicalSubT->getAs<ReferenceType>())
CanonicalSubT = RefTy->getPointeeType();
if (const PointerType *PtrTy = CanonicalSubT->getAs<PointerType>()) {
CanonicalSubT = PtrTy->getPointeeType();
SubIsPointer = true;
}
bool SubIsClass = CanonicalSubT->isRecordType();
CanonicalSubT = CanonicalSubT.getLocalUnqualifiedType();
CXXBasePaths Paths(true, true,
false);
bool Contained = false;
for (const auto &SuperI : Superset->exceptions()) {
QualType CanonicalSuperT = Context.getCanonicalType(SuperI);
if (const ReferenceType *RefTy = CanonicalSuperT->getAs<ReferenceType>())
CanonicalSuperT = RefTy->getPointeeType();
if (SubIsPointer) {
if (const PointerType *PtrTy = CanonicalSuperT->getAs<PointerType>())
CanonicalSuperT = PtrTy->getPointeeType();
else {
continue;
}
}
CanonicalSuperT = CanonicalSuperT.getLocalUnqualifiedType();
if (CanonicalSubT == CanonicalSuperT) {
Contained = true;
break;
}
if (!SubIsClass || !CanonicalSuperT->isRecordType())
continue;
Paths.clear();
if (!IsDerivedFrom(SubLoc, CanonicalSubT, CanonicalSuperT, Paths))
continue;
if (Paths.isAmbiguous(Context.getCanonicalType(CanonicalSuperT)))
continue;
switch (CheckBaseClassAccess(SourceLocation(),
CanonicalSuperT, CanonicalSubT,
Paths.front(),
0,
true,
true)) {
case AR_accessible: break;
case AR_inaccessible: continue;
case AR_dependent:
llvm_unreachable("access check dependent for unprivileged context");
case AR_delayed:
llvm_unreachable("access check delayed in non-declaration");
}
Contained = true;
break;
}
if (!Contained) {
Diag(SubLoc, DiagID);
if (NoteID.getDiagID() != 0)
Diag(SuperLoc, NoteID);
return true;
}
}
return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
}
static bool CheckSpecForTypesEquivalent(Sema &S,
const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
QualType Target, SourceLocation TargetLoc,
QualType Source, SourceLocation SourceLoc)
{
const FunctionProtoType *TFunc = GetUnderlyingFunction(Target);
if (!TFunc)
return false;
const FunctionProtoType *SFunc = GetUnderlyingFunction(Source);
if (!SFunc)
return false;
return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc,
SFunc, SourceLoc);
}
bool Sema::CheckParamExceptionSpec(const PartialDiagnostic &NoteID,
const FunctionProtoType *Target,
SourceLocation TargetLoc,
const FunctionProtoType *Source,
SourceLocation SourceLoc) {
if (CheckSpecForTypesEquivalent(
*this, PDiag(diag::err_deep_exception_specs_differ) << 0, PDiag(),
Target->getReturnType(), TargetLoc, Source->getReturnType(),
SourceLoc))
return true;
assert(Target->getNumParams() == Source->getNumParams() &&
"Functions have different argument counts.");
for (unsigned i = 0, E = Target->getNumParams(); i != E; ++i) {
if (CheckSpecForTypesEquivalent(
*this, PDiag(diag::err_deep_exception_specs_differ) << 1, PDiag(),
Target->getParamType(i), TargetLoc, Source->getParamType(i),
SourceLoc))
return true;
}
return false;
}
bool Sema::CheckExceptionSpecCompatibility(Expr *From, QualType ToType) {
const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType);
if (!ToFunc || ToFunc->hasDependentExceptionSpec())
return false;
const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType());
if (!FromFunc || FromFunc->hasDependentExceptionSpec())
return false;
return CheckExceptionSpecSubset(PDiag(diag::err_incompatible_exception_specs),
PDiag(), ToFunc,
From->getSourceRange().getBegin(),
FromFunc, SourceLocation());
}
bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
const CXXMethodDecl *Old) {
if (New->getType()->castAs<FunctionProtoType>()->getExceptionSpecType() ==
EST_Unparsed)
return false;
if (getLangOpts().CPlusPlus11 && isa<CXXDestructorDecl>(New)) {
if (New->getParent()->isDependentType())
return false;
if (New->getParent()->isBeingDefined()) {
DelayedExceptionSpecChecks.push_back(std::make_pair(New, Old));
return false;
}
}
if (Old->getType()->castAs<FunctionProtoType>()->getExceptionSpecType() ==
EST_Unparsed) {
DelayedExceptionSpecChecks.push_back(std::make_pair(New, Old));
return false;
}
unsigned DiagID = diag::err_override_exception_spec;
if (getLangOpts().MicrosoftExt)
DiagID = diag::ext_override_exception_spec;
return CheckExceptionSpecSubset(PDiag(DiagID),
PDiag(diag::note_overridden_virtual_function),
Old->getType()->getAs<FunctionProtoType>(),
Old->getLocation(),
New->getType()->getAs<FunctionProtoType>(),
New->getLocation());
}
static CanThrowResult canSubExprsThrow(Sema &S, const Expr *E) {
CanThrowResult R = CT_Cannot;
for (const Stmt *SubStmt : E->children()) {
R = mergeCanThrow(R, S.canThrow(cast<Expr>(SubStmt)));
if (R == CT_Can)
break;
}
return R;
}
static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D) {
assert(D && "Expected decl");
const ValueDecl *VD = dyn_cast<ValueDecl>(D);
if (!VD) return CT_Can;
if (isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())
return CT_Cannot;
QualType T = VD->getType();
const FunctionProtoType *FT;
if ((FT = T->getAs<FunctionProtoType>())) {
} else if (const PointerType *PT = T->getAs<PointerType>())
FT = PT->getPointeeType()->getAs<FunctionProtoType>();
else if (const ReferenceType *RT = T->getAs<ReferenceType>())
FT = RT->getPointeeType()->getAs<FunctionProtoType>();
else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
FT = MT->getPointeeType()->getAs<FunctionProtoType>();
else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
FT = BT->getPointeeType()->getAs<FunctionProtoType>();
if (!FT)
return CT_Can;
FT = S.ResolveExceptionSpec(E->getLocStart(), FT);
if (!FT)
return CT_Can;
return FT->isNothrow(S.Context) ? CT_Cannot : CT_Can;
}
static CanThrowResult canDynamicCastThrow(const CXXDynamicCastExpr *DC) {
if (DC->isTypeDependent())
return CT_Dependent;
if (!DC->getTypeAsWritten()->isReferenceType())
return CT_Cannot;
if (DC->getSubExpr()->isTypeDependent())
return CT_Dependent;
return DC->getCastKind() == clang::CK_Dynamic? CT_Can : CT_Cannot;
}
static CanThrowResult canTypeidThrow(Sema &S, const CXXTypeidExpr *DC) {
if (DC->isTypeOperand())
return CT_Cannot;
Expr *Op = DC->getExprOperand();
if (Op->isTypeDependent())
return CT_Dependent;
const RecordType *RT = Op->getType()->getAs<RecordType>();
if (!RT)
return CT_Cannot;
if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
return CT_Cannot;
if (Op->Classify(S.Context).isPRValue())
return CT_Cannot;
return CT_Can;
}
CanThrowResult Sema::canThrow(const Expr *E) {
switch (E->getStmtClass()) {
case Expr::CXXThrowExprClass:
return CT_Can;
case Expr::CXXDynamicCastExprClass: {
CanThrowResult CT = canDynamicCastThrow(cast<CXXDynamicCastExpr>(E));
if (CT == CT_Can)
return CT;
return mergeCanThrow(CT, canSubExprsThrow(*this, E));
}
case Expr::CXXTypeidExprClass:
return canTypeidThrow(*this, cast<CXXTypeidExpr>(E));
case Expr::CallExprClass:
case Expr::CXXMemberCallExprClass:
case Expr::CXXOperatorCallExprClass:
case Expr::UserDefinedLiteralClass: {
const CallExpr *CE = cast<CallExpr>(E);
CanThrowResult CT;
if (E->isTypeDependent())
CT = CT_Dependent;
else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens()))
CT = CT_Cannot;
else if (CE->getCalleeDecl())
CT = canCalleeThrow(*this, E, CE->getCalleeDecl());
else
CT = CT_Can;
if (CT == CT_Can)
return CT;
return mergeCanThrow(CT, canSubExprsThrow(*this, E));
}
case Expr::CXXConstructExprClass:
case Expr::CXXTemporaryObjectExprClass: {
CanThrowResult CT = canCalleeThrow(*this, E,
cast<CXXConstructExpr>(E)->getConstructor());
if (CT == CT_Can)
return CT;
return mergeCanThrow(CT, canSubExprsThrow(*this, E));
}
case Expr::LambdaExprClass: {
const LambdaExpr *Lambda = cast<LambdaExpr>(E);
CanThrowResult CT = CT_Cannot;
for (LambdaExpr::const_capture_init_iterator
Cap = Lambda->capture_init_begin(),
CapEnd = Lambda->capture_init_end();
Cap != CapEnd; ++Cap)
CT = mergeCanThrow(CT, canThrow(*Cap));
return CT;
}
case Expr::CXXNewExprClass: {
CanThrowResult CT;
if (E->isTypeDependent())
CT = CT_Dependent;
else
CT = canCalleeThrow(*this, E, cast<CXXNewExpr>(E)->getOperatorNew());
if (CT == CT_Can)
return CT;
return mergeCanThrow(CT, canSubExprsThrow(*this, E));
}
case Expr::CXXDeleteExprClass: {
CanThrowResult CT;
QualType DTy = cast<CXXDeleteExpr>(E)->getDestroyedType();
if (DTy.isNull() || DTy->isDependentType()) {
CT = CT_Dependent;
} else {
CT = canCalleeThrow(*this, E,
cast<CXXDeleteExpr>(E)->getOperatorDelete());
if (const RecordType *RT = DTy->getAs<RecordType>()) {
const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
const CXXDestructorDecl *DD = RD->getDestructor();
if (DD)
CT = mergeCanThrow(CT, canCalleeThrow(*this, E, DD));
}
if (CT == CT_Can)
return CT;
}
return mergeCanThrow(CT, canSubExprsThrow(*this, E));
}
case Expr::CXXBindTemporaryExprClass: {
CanThrowResult CT = canCalleeThrow(*this, E,
cast<CXXBindTemporaryExpr>(E)->getTemporary()->getDestructor());
if (CT == CT_Can)
return CT;
return mergeCanThrow(CT, canSubExprsThrow(*this, E));
}
case Expr::ObjCMessageExprClass:
case Expr::ObjCPropertyRefExprClass:
case Expr::ObjCSubscriptRefExprClass:
return CT_Can;
case Expr::ObjCArrayLiteralClass:
case Expr::ObjCDictionaryLiteralClass:
case Expr::ObjCBoxedExprClass:
return CT_Can;
case Expr::CoawaitExprClass:
case Expr::ConditionalOperatorClass:
case Expr::CompoundLiteralExprClass:
case Expr::CoyieldExprClass:
case Expr::CXXConstCastExprClass:
case Expr::CXXReinterpretCastExprClass:
case Expr::CXXStdInitializerListExprClass:
case Expr::DesignatedInitExprClass:
case Expr::DesignatedInitUpdateExprClass:
case Expr::ExprWithCleanupsClass:
case Expr::ExtVectorElementExprClass:
case Expr::InitListExprClass:
case Expr::MemberExprClass:
case Expr::ObjCIsaExprClass:
case Expr::ObjCIvarRefExprClass:
case Expr::ParenExprClass:
case Expr::ParenListExprClass:
case Expr::ShuffleVectorExprClass:
case Expr::ConvertVectorExprClass:
case Expr::VAArgExprClass:
return canSubExprsThrow(*this, E);
case Expr::ArraySubscriptExprClass:
case Expr::OMPArraySectionExprClass:
case Expr::BinaryOperatorClass:
case Expr::CompoundAssignOperatorClass:
case Expr::CStyleCastExprClass:
case Expr::CXXStaticCastExprClass:
case Expr::CXXFunctionalCastExprClass:
case Expr::ImplicitCastExprClass:
case Expr::MaterializeTemporaryExprClass:
case Expr::UnaryOperatorClass: {
CanThrowResult CT = E->isTypeDependent() ? CT_Dependent : CT_Cannot;
return mergeCanThrow(CT, canSubExprsThrow(*this, E));
}
case Expr::StmtExprClass:
return CT_Can;
case Expr::CXXDefaultArgExprClass:
return canThrow(cast<CXXDefaultArgExpr>(E)->getExpr());
case Expr::CXXDefaultInitExprClass:
return canThrow(cast<CXXDefaultInitExpr>(E)->getExpr());
case Expr::ChooseExprClass:
if (E->isTypeDependent() || E->isValueDependent())
return CT_Dependent;
return canThrow(cast<ChooseExpr>(E)->getChosenSubExpr());
case Expr::GenericSelectionExprClass:
if (cast<GenericSelectionExpr>(E)->isResultDependent())
return CT_Dependent;
return canThrow(cast<GenericSelectionExpr>(E)->getResultExpr());
case Expr::CXXDependentScopeMemberExprClass:
case Expr::CXXUnresolvedConstructExprClass:
case Expr::DependentScopeDeclRefExprClass:
case Expr::CXXFoldExprClass:
return CT_Dependent;
case Expr::AsTypeExprClass:
case Expr::BinaryConditionalOperatorClass:
case Expr::BlockExprClass:
case Expr::CUDAKernelCallExprClass:
case Expr::DeclRefExprClass:
case Expr::ObjCBridgedCastExprClass:
case Expr::ObjCIndirectCopyRestoreExprClass:
case Expr::ObjCProtocolExprClass:
case Expr::ObjCSelectorExprClass:
case Expr::OffsetOfExprClass:
case Expr::PackExpansionExprClass:
case Expr::PseudoObjectExprClass:
case Expr::SubstNonTypeTemplateParmExprClass:
case Expr::SubstNonTypeTemplateParmPackExprClass:
case Expr::FunctionParmPackExprClass:
case Expr::UnaryExprOrTypeTraitExprClass:
case Expr::UnresolvedLookupExprClass:
case Expr::UnresolvedMemberExprClass:
case Expr::TypoExprClass:
return CT_Cannot;
case Expr::AddrLabelExprClass:
case Expr::ArrayTypeTraitExprClass:
case Expr::AtomicExprClass:
case Expr::TypeTraitExprClass:
case Expr::CXXBoolLiteralExprClass:
case Expr::CXXNoexceptExprClass:
case Expr::CXXNullPtrLiteralExprClass:
case Expr::CXXPseudoDestructorExprClass:
case Expr::CXXScalarValueInitExprClass:
case Expr::CXXThisExprClass:
case Expr::CXXUuidofExprClass:
case Expr::CharacterLiteralClass:
case Expr::ExpressionTraitExprClass:
case Expr::FloatingLiteralClass:
case Expr::GNUNullExprClass:
case Expr::ImaginaryLiteralClass:
case Expr::ImplicitValueInitExprClass:
case Expr::IntegerLiteralClass:
case Expr::NoInitExprClass:
case Expr::ObjCEncodeExprClass:
case Expr::ObjCStringLiteralClass:
case Expr::ObjCBoolLiteralExprClass:
case Expr::OpaqueValueExprClass:
case Expr::PredefinedExprClass:
case Expr::SizeOfPackExprClass:
case Expr::StringLiteralClass:
return CT_Cannot;
case Expr::MSPropertyRefExprClass:
case Expr::MSPropertySubscriptExprClass:
llvm_unreachable("Invalid class for expression");
#define STMT(CLASS, PARENT) case Expr::CLASS##Class:
#define STMT_RANGE(Base, First, Last)
#define LAST_STMT_RANGE(BASE, FIRST, LAST)
#define EXPR(CLASS, PARENT)
#define ABSTRACT_STMT(STMT)
#include "clang/AST/StmtNodes.inc"
case Expr::NoStmtClass:
llvm_unreachable("Invalid class for expression");
}
llvm_unreachable("Bogus StmtClass");
}
}