1//===--- SemaExceptionSpec.cpp - C++ Exception Specifications ---*- C++ -*-===//
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// This file provides Sema routines for C++ exception specification testing.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/ASTMutationListener.h"
14#include "clang/AST/CXXInheritance.h"
15#include "clang/AST/Expr.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/AST/StmtObjC.h"
18#include "clang/AST/StmtSYCL.h"
19#include "clang/AST/TypeLoc.h"
20#include "clang/Basic/Diagnostic.h"
21#include "clang/Basic/SourceManager.h"
22#include "clang/Lex/Preprocessor.h"
23#include "clang/Sema/SemaInternal.h"
24#include "llvm/ADT/SmallPtrSet.h"
25#include <optional>
26
27namespace clang {
28
29static const FunctionProtoType *GetUnderlyingFunction(QualType T)
30{
31 if (const PointerType *PtrTy = T->getAs<PointerType>())
32 T = PtrTy->getPointeeType();
33 else if (const ReferenceType *RefTy = T->getAs<ReferenceType>())
34 T = RefTy->getPointeeType();
35 else if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
36 T = MPTy->getPointeeType();
37 return T->getAs<FunctionProtoType>();
38}
39
40/// HACK: 2014-11-14 libstdc++ had a bug where it shadows std::swap with a
41/// member swap function then tries to call std::swap unqualified from the
42/// exception specification of that function. This function detects whether
43/// we're in such a case and turns off delay-parsing of exception
44/// specifications. Libstdc++ 6.1 (released 2016-04-27) appears to have
45/// resolved it as side-effect of commit ddb63209a8d (2015-06-05).
46bool Sema::isLibstdcxxEagerExceptionSpecHack(const Declarator &D) {
47 auto *RD = dyn_cast<CXXRecordDecl>(Val: CurContext);
48
49 if (!getPreprocessor().NeedsStdLibCxxWorkaroundBefore(FixedVersion: 2016'04'27))
50 return false;
51 // All the problem cases are member functions named "swap" within class
52 // templates declared directly within namespace std or std::__debug or
53 // std::__profile.
54 if (!RD || !RD->getIdentifier() || !RD->getDescribedClassTemplate() ||
55 !D.getIdentifier() || !D.getIdentifier()->isStr(Str: "swap"))
56 return false;
57
58 auto *ND = dyn_cast<NamespaceDecl>(Val: RD->getDeclContext());
59 if (!ND)
60 return false;
61
62 bool IsInStd = ND->isStdNamespace();
63 if (!IsInStd) {
64 // This isn't a direct member of namespace std, but it might still be
65 // libstdc++'s std::__debug::array or std::__profile::array.
66 IdentifierInfo *II = ND->getIdentifier();
67 if (!II || !(II->isStr(Str: "__debug") || II->isStr(Str: "__profile")) ||
68 !ND->isInStdNamespace())
69 return false;
70 }
71
72 // Only apply this hack within a system header.
73 if (!Context.getSourceManager().isInSystemHeader(Loc: D.getBeginLoc()))
74 return false;
75
76 return llvm::StringSwitch<bool>(RD->getIdentifier()->getName())
77 .Case(S: "array", Value: true)
78 .Case(S: "pair", Value: IsInStd)
79 .Case(S: "priority_queue", Value: IsInStd)
80 .Case(S: "stack", Value: IsInStd)
81 .Case(S: "queue", Value: IsInStd)
82 .Default(Value: false);
83}
84
85ExprResult Sema::ActOnNoexceptSpec(Expr *NoexceptExpr,
86 ExceptionSpecificationType &EST) {
87
88 if (NoexceptExpr->isTypeDependent() ||
89 NoexceptExpr->containsUnexpandedParameterPack()) {
90 EST = EST_DependentNoexcept;
91 return NoexceptExpr;
92 }
93
94 llvm::APSInt Result;
95 ExprResult Converted = CheckConvertedConstantExpression(
96 From: NoexceptExpr, T: Context.BoolTy, Value&: Result, CCE: CCEKind::Noexcept);
97
98 if (Converted.isInvalid()) {
99 EST = EST_NoexceptFalse;
100 // Fill in an expression of 'false' as a fixup.
101 auto *BoolExpr = new (Context)
102 CXXBoolLiteralExpr(false, Context.BoolTy, NoexceptExpr->getBeginLoc());
103 llvm::APSInt Value{1};
104 Value = 0;
105 return ConstantExpr::Create(Context, E: BoolExpr, Result: APValue{Value});
106 }
107
108 if (Converted.get()->isValueDependent()) {
109 EST = EST_DependentNoexcept;
110 return Converted;
111 }
112
113 if (!Converted.isInvalid())
114 EST = !Result ? EST_NoexceptFalse : EST_NoexceptTrue;
115 return Converted;
116}
117
118bool Sema::CheckSpecifiedExceptionType(QualType &T, SourceRange Range) {
119 // C++11 [except.spec]p2:
120 // A type cv T, "array of T", or "function returning T" denoted
121 // in an exception-specification is adjusted to type T, "pointer to T", or
122 // "pointer to function returning T", respectively.
123 //
124 // We also apply this rule in C++98.
125 if (T->isArrayType())
126 T = Context.getArrayDecayedType(T);
127 else if (T->isFunctionType())
128 T = Context.getPointerType(T);
129
130 int Kind = 0;
131 QualType PointeeT = T;
132 if (const PointerType *PT = T->getAs<PointerType>()) {
133 PointeeT = PT->getPointeeType();
134 Kind = 1;
135
136 // cv void* is explicitly permitted, despite being a pointer to an
137 // incomplete type.
138 if (PointeeT->isVoidType())
139 return false;
140 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
141 PointeeT = RT->getPointeeType();
142 Kind = 2;
143
144 if (RT->isRValueReferenceType()) {
145 // C++11 [except.spec]p2:
146 // A type denoted in an exception-specification shall not denote [...]
147 // an rvalue reference type.
148 Diag(Loc: Range.getBegin(), DiagID: diag::err_rref_in_exception_spec)
149 << T << Range;
150 return true;
151 }
152 }
153
154 // C++11 [except.spec]p2:
155 // A type denoted in an exception-specification shall not denote an
156 // incomplete type other than a class currently being defined [...].
157 // A type denoted in an exception-specification shall not denote a
158 // pointer or reference to an incomplete type, other than (cv) void* or a
159 // pointer or reference to a class currently being defined.
160 // In Microsoft mode, downgrade this to a warning.
161 unsigned DiagID = diag::err_incomplete_in_exception_spec;
162 bool ReturnValueOnError = true;
163 if (getLangOpts().MSVCCompat) {
164 DiagID = diag::ext_incomplete_in_exception_spec;
165 ReturnValueOnError = false;
166 }
167 if (auto *RD = PointeeT->getAsRecordDecl();
168 !(RD && RD->isBeingDefined()) &&
169 RequireCompleteType(Loc: Range.getBegin(), T: PointeeT, DiagID, Args: Kind, Args: Range))
170 return ReturnValueOnError;
171
172 // WebAssembly reference types can't be used in exception specifications.
173 if (PointeeT.isWebAssemblyReferenceType()) {
174 Diag(Loc: Range.getBegin(), DiagID: diag::err_wasm_reftype_exception_spec);
175 return true;
176 }
177
178 // The MSVC compatibility mode doesn't extend to sizeless types,
179 // so diagnose them separately.
180 if (PointeeT->isSizelessType() && Kind != 1) {
181 Diag(Loc: Range.getBegin(), DiagID: diag::err_sizeless_in_exception_spec)
182 << (Kind == 2 ? 1 : 0) << PointeeT << Range;
183 return true;
184 }
185
186 return false;
187}
188
189bool Sema::CheckDistantExceptionSpec(QualType T) {
190 // C++17 removes this rule in favor of putting exception specifications into
191 // the type system.
192 if (getLangOpts().CPlusPlus17)
193 return false;
194
195 if (const PointerType *PT = T->getAs<PointerType>())
196 T = PT->getPointeeType();
197 else if (const MemberPointerType *PT = T->getAs<MemberPointerType>())
198 T = PT->getPointeeType();
199 else
200 return false;
201
202 const FunctionProtoType *FnT = T->getAs<FunctionProtoType>();
203 if (!FnT)
204 return false;
205
206 return FnT->hasExceptionSpec();
207}
208
209const FunctionProtoType *
210Sema::ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT) {
211 if (FPT->getExceptionSpecType() == EST_Unparsed) {
212 Diag(Loc, DiagID: diag::err_exception_spec_not_parsed);
213 return nullptr;
214 }
215
216 if (!isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType()))
217 return FPT;
218
219 FunctionDecl *SourceDecl = FPT->getExceptionSpecDecl();
220 const FunctionProtoType *SourceFPT =
221 SourceDecl->getType()->castAs<FunctionProtoType>();
222
223 // If the exception specification has already been resolved, just return it.
224 if (!isUnresolvedExceptionSpec(ESpecType: SourceFPT->getExceptionSpecType()))
225 return SourceFPT;
226
227 // Compute or instantiate the exception specification now.
228 if (SourceFPT->getExceptionSpecType() == EST_Unevaluated)
229 EvaluateImplicitExceptionSpec(Loc, FD: SourceDecl);
230 else
231 InstantiateExceptionSpec(PointOfInstantiation: Loc, Function: SourceDecl);
232
233 const FunctionProtoType *Proto =
234 SourceDecl->getType()->castAs<FunctionProtoType>();
235 if (Proto->getExceptionSpecType() == clang::EST_Unparsed) {
236 Diag(Loc, DiagID: diag::err_exception_spec_not_parsed);
237 Proto = nullptr;
238 }
239 return Proto;
240}
241
242void
243Sema::UpdateExceptionSpec(FunctionDecl *FD,
244 const FunctionProtoType::ExceptionSpecInfo &ESI) {
245 // If we've fully resolved the exception specification, notify listeners.
246 if (!isUnresolvedExceptionSpec(ESpecType: ESI.Type))
247 if (auto *Listener = getASTMutationListener())
248 Listener->ResolvedExceptionSpec(FD);
249
250 for (FunctionDecl *Redecl : FD->redecls())
251 Context.adjustExceptionSpec(FD: Redecl, ESI);
252}
253
254static bool exceptionSpecNotKnownYet(const FunctionDecl *FD) {
255 ExceptionSpecificationType EST =
256 FD->getType()->castAs<FunctionProtoType>()->getExceptionSpecType();
257 if (EST == EST_Unparsed)
258 return true;
259 else if (EST != EST_Unevaluated)
260 return false;
261 const DeclContext *DC = FD->getLexicalDeclContext();
262 return DC->isRecord() && cast<RecordDecl>(Val: DC)->isBeingDefined();
263}
264
265static bool CheckEquivalentExceptionSpecImpl(
266 Sema &S, const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID,
267 const FunctionProtoType *Old, SourceLocation OldLoc,
268 const FunctionProtoType *New, SourceLocation NewLoc,
269 bool *MissingExceptionSpecification = nullptr,
270 bool *MissingEmptyExceptionSpecification = nullptr,
271 bool AllowNoexceptAllMatchWithNoSpec = false, bool IsOperatorNew = false);
272
273/// Determine whether a function has an implicitly-generated exception
274/// specification.
275static bool hasImplicitExceptionSpec(FunctionDecl *Decl) {
276 if (!isa<CXXDestructorDecl>(Val: Decl) &&
277 Decl->getDeclName().getCXXOverloadedOperator() != OO_Delete &&
278 Decl->getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
279 return false;
280
281 // For a function that the user didn't declare:
282 // - if this is a destructor, its exception specification is implicit.
283 // - if this is 'operator delete' or 'operator delete[]', the exception
284 // specification is as-if an explicit exception specification was given
285 // (per [basic.stc.dynamic]p2).
286 if (!Decl->getTypeSourceInfo())
287 return isa<CXXDestructorDecl>(Val: Decl);
288
289 auto *Ty = Decl->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
290 return !Ty->hasExceptionSpec();
291}
292
293bool Sema::CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New) {
294 // Just completely ignore this under -fno-exceptions prior to C++17.
295 // In C++17 onwards, the exception specification is part of the type and
296 // we will diagnose mismatches anyway, so it's better to check for them here.
297 if (!getLangOpts().CXXExceptions && !getLangOpts().CPlusPlus17)
298 return false;
299
300 OverloadedOperatorKind OO = New->getDeclName().getCXXOverloadedOperator();
301 bool IsOperatorNew = OO == OO_New || OO == OO_Array_New;
302 bool MissingExceptionSpecification = false;
303 bool MissingEmptyExceptionSpecification = false;
304
305 unsigned DiagID = diag::err_mismatched_exception_spec;
306 bool ReturnValueOnError = true;
307 if (getLangOpts().MSVCCompat) {
308 DiagID = diag::ext_mismatched_exception_spec;
309 ReturnValueOnError = false;
310 }
311
312 // If we're befriending a member function of a class that's currently being
313 // defined, we might not be able to work out its exception specification yet.
314 // If not, defer the check until later.
315 if (exceptionSpecNotKnownYet(FD: Old) || exceptionSpecNotKnownYet(FD: New)) {
316 DelayedEquivalentExceptionSpecChecks.push_back(Elt: {New, Old});
317 return false;
318 }
319
320 // Check the types as written: they must match before any exception
321 // specification adjustment is applied.
322 if (!CheckEquivalentExceptionSpecImpl(
323 S&: *this, DiagID: PDiag(DiagID), NoteID: PDiag(DiagID: diag::note_previous_declaration),
324 Old: Old->getType()->getAs<FunctionProtoType>(), OldLoc: Old->getLocation(),
325 New: New->getType()->getAs<FunctionProtoType>(), NewLoc: New->getLocation(),
326 MissingExceptionSpecification: &MissingExceptionSpecification, MissingEmptyExceptionSpecification: &MissingEmptyExceptionSpecification,
327 /*AllowNoexceptAllMatchWithNoSpec=*/true, IsOperatorNew)) {
328 // C++11 [except.spec]p4 [DR1492]:
329 // If a declaration of a function has an implicit
330 // exception-specification, other declarations of the function shall
331 // not specify an exception-specification.
332 if (getLangOpts().CPlusPlus11 && getLangOpts().CXXExceptions &&
333 hasImplicitExceptionSpec(Decl: Old) != hasImplicitExceptionSpec(Decl: New)) {
334 Diag(Loc: New->getLocation(), DiagID: diag::ext_implicit_exception_spec_mismatch)
335 << hasImplicitExceptionSpec(Decl: Old);
336 if (Old->getLocation().isValid())
337 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
338 }
339 return false;
340 }
341
342 // The failure was something other than an missing exception
343 // specification; return an error, except in MS mode where this is a warning.
344 if (!MissingExceptionSpecification)
345 return ReturnValueOnError;
346
347 const auto *NewProto = New->getType()->castAs<FunctionProtoType>();
348
349 // The new function declaration is only missing an empty exception
350 // specification "throw()". If the throw() specification came from a
351 // function in a system header that has C linkage, just add an empty
352 // exception specification to the "new" declaration. Note that C library
353 // implementations are permitted to add these nothrow exception
354 // specifications.
355 //
356 // Likewise if the old function is a builtin.
357 if (MissingEmptyExceptionSpecification &&
358 (Old->getLocation().isInvalid() ||
359 Context.getSourceManager().isInSystemHeader(Loc: Old->getLocation()) ||
360 Old->getBuiltinID()) &&
361 Old->isExternC()) {
362 New->setType(Context.getFunctionType(
363 ResultTy: NewProto->getReturnType(), Args: NewProto->getParamTypes(),
364 EPI: NewProto->getExtProtoInfo().withExceptionSpec(ESI: EST_DynamicNone)));
365 return false;
366 }
367
368 const auto *OldProto = Old->getType()->castAs<FunctionProtoType>();
369
370 FunctionProtoType::ExceptionSpecInfo ESI = OldProto->getExceptionSpecType();
371 if (ESI.Type == EST_Dynamic) {
372 // FIXME: What if the exceptions are described in terms of the old
373 // prototype's parameters?
374 ESI.Exceptions = OldProto->exceptions();
375 }
376
377 if (ESI.Type == EST_NoexceptFalse)
378 ESI.Type = EST_None;
379 if (ESI.Type == EST_NoexceptTrue)
380 ESI.Type = EST_BasicNoexcept;
381
382 // For dependent noexcept, we can't just take the expression from the old
383 // prototype. It likely contains references to the old prototype's parameters.
384 if (ESI.Type == EST_DependentNoexcept) {
385 New->setInvalidDecl();
386 } else {
387 // Update the type of the function with the appropriate exception
388 // specification.
389 New->setType(Context.getFunctionType(
390 ResultTy: NewProto->getReturnType(), Args: NewProto->getParamTypes(),
391 EPI: NewProto->getExtProtoInfo().withExceptionSpec(ESI)));
392 }
393
394 if (getLangOpts().MSVCCompat && isDynamicExceptionSpec(ESpecType: ESI.Type)) {
395 DiagID = diag::ext_missing_exception_specification;
396 ReturnValueOnError = false;
397 } else if (New->isReplaceableGlobalAllocationFunction() &&
398 ESI.Type != EST_DependentNoexcept) {
399 // Allow missing exception specifications in redeclarations as an extension,
400 // when declaring a replaceable global allocation function.
401 DiagID = diag::ext_missing_exception_specification;
402 ReturnValueOnError = false;
403 } else if (ESI.Type == EST_NoThrow) {
404 // Don't emit any warning for missing 'nothrow' in MSVC.
405 if (getLangOpts().MSVCCompat) {
406 return false;
407 }
408 // Allow missing attribute 'nothrow' in redeclarations, since this is a very
409 // common omission.
410 DiagID = diag::ext_missing_exception_specification;
411 ReturnValueOnError = false;
412 } else {
413 DiagID = diag::err_missing_exception_specification;
414 ReturnValueOnError = true;
415 }
416
417 // Warn about the lack of exception specification.
418 SmallString<128> ExceptionSpecString;
419 llvm::raw_svector_ostream OS(ExceptionSpecString);
420 switch (OldProto->getExceptionSpecType()) {
421 case EST_DynamicNone:
422 OS << "throw()";
423 break;
424
425 case EST_Dynamic: {
426 OS << "throw(";
427 bool OnFirstException = true;
428 for (const auto &E : OldProto->exceptions()) {
429 if (OnFirstException)
430 OnFirstException = false;
431 else
432 OS << ", ";
433
434 OS << E.getAsString(Policy: getPrintingPolicy());
435 }
436 OS << ")";
437 break;
438 }
439
440 case EST_BasicNoexcept:
441 OS << "noexcept";
442 break;
443
444 case EST_DependentNoexcept:
445 case EST_NoexceptFalse:
446 case EST_NoexceptTrue:
447 OS << "noexcept(";
448 assert(OldProto->getNoexceptExpr() != nullptr && "Expected non-null Expr");
449 OldProto->getNoexceptExpr()->printPretty(OS, Helper: nullptr, Policy: getPrintingPolicy());
450 OS << ")";
451 break;
452 case EST_NoThrow:
453 OS <<"__attribute__((nothrow))";
454 break;
455 case EST_None:
456 case EST_MSAny:
457 case EST_Unevaluated:
458 case EST_Uninstantiated:
459 case EST_Unparsed:
460 llvm_unreachable("This spec type is compatible with none.");
461 }
462
463 SourceLocation FixItLoc;
464 if (TypeSourceInfo *TSInfo = New->getTypeSourceInfo()) {
465 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
466 // FIXME: Preserve enough information so that we can produce a correct fixit
467 // location when there is a trailing return type.
468 if (auto FTLoc = TL.getAs<FunctionProtoTypeLoc>())
469 if (!FTLoc.getTypePtr()->hasTrailingReturn())
470 FixItLoc = getLocForEndOfToken(Loc: FTLoc.getLocalRangeEnd());
471 }
472
473 if (FixItLoc.isInvalid())
474 Diag(Loc: New->getLocation(), DiagID)
475 << New << OS.str();
476 else {
477 Diag(Loc: New->getLocation(), DiagID)
478 << New << OS.str()
479 << FixItHint::CreateInsertion(InsertionLoc: FixItLoc, Code: " " + OS.str().str());
480 }
481
482 if (Old->getLocation().isValid())
483 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
484
485 return ReturnValueOnError;
486}
487
488bool Sema::CheckEquivalentExceptionSpec(
489 const FunctionProtoType *Old, SourceLocation OldLoc,
490 const FunctionProtoType *New, SourceLocation NewLoc) {
491 if (!getLangOpts().CXXExceptions)
492 return false;
493
494 unsigned DiagID = diag::err_mismatched_exception_spec;
495 if (getLangOpts().MSVCCompat)
496 DiagID = diag::ext_mismatched_exception_spec;
497 bool Result = CheckEquivalentExceptionSpecImpl(
498 S&: *this, DiagID: PDiag(DiagID), NoteID: PDiag(DiagID: diag::note_previous_declaration),
499 Old, OldLoc, New, NewLoc);
500
501 // In Microsoft mode, mismatching exception specifications just cause a warning.
502 if (getLangOpts().MSVCCompat)
503 return false;
504 return Result;
505}
506
507/// CheckEquivalentExceptionSpec - Check if the two types have compatible
508/// exception specifications. See C++ [except.spec]p3.
509///
510/// \return \c false if the exception specifications match, \c true if there is
511/// a problem. If \c true is returned, either a diagnostic has already been
512/// produced or \c *MissingExceptionSpecification is set to \c true.
513static bool CheckEquivalentExceptionSpecImpl(
514 Sema &S, const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID,
515 const FunctionProtoType *Old, SourceLocation OldLoc,
516 const FunctionProtoType *New, SourceLocation NewLoc,
517 bool *MissingExceptionSpecification,
518 bool *MissingEmptyExceptionSpecification,
519 bool AllowNoexceptAllMatchWithNoSpec, bool IsOperatorNew) {
520 if (MissingExceptionSpecification)
521 *MissingExceptionSpecification = false;
522
523 if (MissingEmptyExceptionSpecification)
524 *MissingEmptyExceptionSpecification = false;
525
526 Old = S.ResolveExceptionSpec(Loc: NewLoc, FPT: Old);
527 if (!Old)
528 return false;
529 New = S.ResolveExceptionSpec(Loc: NewLoc, FPT: New);
530 if (!New)
531 return false;
532
533 // C++0x [except.spec]p3: Two exception-specifications are compatible if:
534 // - both are non-throwing, regardless of their form,
535 // - both have the form noexcept(constant-expression) and the constant-
536 // expressions are equivalent,
537 // - both are dynamic-exception-specifications that have the same set of
538 // adjusted types.
539 //
540 // C++0x [except.spec]p12: An exception-specification is non-throwing if it is
541 // of the form throw(), noexcept, or noexcept(constant-expression) where the
542 // constant-expression yields true.
543 //
544 // C++0x [except.spec]p4: If any declaration of a function has an exception-
545 // specifier that is not a noexcept-specification allowing all exceptions,
546 // all declarations [...] of that function shall have a compatible
547 // exception-specification.
548 //
549 // That last point basically means that noexcept(false) matches no spec.
550 // It's considered when AllowNoexceptAllMatchWithNoSpec is true.
551
552 ExceptionSpecificationType OldEST = Old->getExceptionSpecType();
553 ExceptionSpecificationType NewEST = New->getExceptionSpecType();
554
555 assert(!isUnresolvedExceptionSpec(OldEST) &&
556 !isUnresolvedExceptionSpec(NewEST) &&
557 "Shouldn't see unknown exception specifications here");
558
559 CanThrowResult OldCanThrow = Old->canThrow();
560 CanThrowResult NewCanThrow = New->canThrow();
561
562 // Any non-throwing specifications are compatible.
563 if (OldCanThrow == CT_Cannot && NewCanThrow == CT_Cannot)
564 return false;
565
566 // Any throws-anything specifications are usually compatible.
567 if (OldCanThrow == CT_Can && OldEST != EST_Dynamic &&
568 NewCanThrow == CT_Can && NewEST != EST_Dynamic) {
569 // The exception is that the absence of an exception specification only
570 // matches noexcept(false) for functions, as described above.
571 if (!AllowNoexceptAllMatchWithNoSpec &&
572 ((OldEST == EST_None && NewEST == EST_NoexceptFalse) ||
573 (OldEST == EST_NoexceptFalse && NewEST == EST_None))) {
574 // This is the disallowed case.
575 } else {
576 return false;
577 }
578 }
579
580 // C++14 [except.spec]p3:
581 // Two exception-specifications are compatible if [...] both have the form
582 // noexcept(constant-expression) and the constant-expressions are equivalent
583 if (OldEST == EST_DependentNoexcept && NewEST == EST_DependentNoexcept) {
584 llvm::FoldingSetNodeID OldFSN, NewFSN;
585 Old->getNoexceptExpr()->Profile(ID&: OldFSN, Context: S.Context, Canonical: true);
586 New->getNoexceptExpr()->Profile(ID&: NewFSN, Context: S.Context, Canonical: true);
587 if (OldFSN == NewFSN)
588 return false;
589 }
590
591 // Dynamic exception specifications with the same set of adjusted types
592 // are compatible.
593 if (OldEST == EST_Dynamic && NewEST == EST_Dynamic) {
594 bool Success = true;
595 // Both have a dynamic exception spec. Collect the first set, then compare
596 // to the second.
597 llvm::SmallPtrSet<CanQualType, 8> OldTypes, NewTypes;
598 for (const auto &I : Old->exceptions())
599 OldTypes.insert(Ptr: S.Context.getCanonicalType(T: I).getUnqualifiedType());
600
601 for (const auto &I : New->exceptions()) {
602 CanQualType TypePtr = S.Context.getCanonicalType(T: I).getUnqualifiedType();
603 if (OldTypes.count(Ptr: TypePtr))
604 NewTypes.insert(Ptr: TypePtr);
605 else {
606 Success = false;
607 break;
608 }
609 }
610
611 if (Success && OldTypes.size() == NewTypes.size())
612 return false;
613 }
614
615 // As a special compatibility feature, under C++0x we accept no spec and
616 // throw(std::bad_alloc) as equivalent for operator new and operator new[].
617 // This is because the implicit declaration changed, but old code would break.
618 if (S.getLangOpts().CPlusPlus11 && IsOperatorNew) {
619 const FunctionProtoType *WithExceptions = nullptr;
620 if (OldEST == EST_None && NewEST == EST_Dynamic)
621 WithExceptions = New;
622 else if (OldEST == EST_Dynamic && NewEST == EST_None)
623 WithExceptions = Old;
624 if (WithExceptions && WithExceptions->getNumExceptions() == 1) {
625 // One has no spec, the other throw(something). If that something is
626 // std::bad_alloc, all conditions are met.
627 QualType Exception = *WithExceptions->exception_begin();
628 if (CXXRecordDecl *ExRecord = Exception->getAsCXXRecordDecl()) {
629 IdentifierInfo* Name = ExRecord->getIdentifier();
630 if (Name && Name->getName() == "bad_alloc") {
631 // It's called bad_alloc, but is it in std?
632 if (ExRecord->isInStdNamespace()) {
633 return false;
634 }
635 }
636 }
637 }
638 }
639
640 // If the caller wants to handle the case that the new function is
641 // incompatible due to a missing exception specification, let it.
642 if (MissingExceptionSpecification && OldEST != EST_None &&
643 NewEST == EST_None) {
644 // The old type has an exception specification of some sort, but
645 // the new type does not.
646 *MissingExceptionSpecification = true;
647
648 if (MissingEmptyExceptionSpecification && OldCanThrow == CT_Cannot) {
649 // The old type has a throw() or noexcept(true) exception specification
650 // and the new type has no exception specification, and the caller asked
651 // to handle this itself.
652 *MissingEmptyExceptionSpecification = true;
653 }
654
655 return true;
656 }
657
658 S.Diag(Loc: NewLoc, PD: DiagID);
659 if (NoteID.getDiagID() != 0 && OldLoc.isValid())
660 S.Diag(Loc: OldLoc, PD: NoteID);
661 return true;
662}
663
664bool Sema::CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
665 const PartialDiagnostic &NoteID,
666 const FunctionProtoType *Old,
667 SourceLocation OldLoc,
668 const FunctionProtoType *New,
669 SourceLocation NewLoc) {
670 if (!getLangOpts().CXXExceptions)
671 return false;
672 return CheckEquivalentExceptionSpecImpl(S&: *this, DiagID, NoteID, Old, OldLoc,
673 New, NewLoc);
674}
675
676bool Sema::handlerCanCatch(QualType HandlerType, QualType ExceptionType) {
677 // [except.handle]p3:
678 // A handler is a match for an exception object of type E if:
679
680 // HandlerType must be ExceptionType or derived from it, or pointer or
681 // reference to such types.
682 const ReferenceType *RefTy = HandlerType->getAs<ReferenceType>();
683 if (RefTy)
684 HandlerType = RefTy->getPointeeType();
685
686 // -- the handler is of type cv T or cv T& and E and T are the same type
687 if (Context.hasSameUnqualifiedType(T1: ExceptionType, T2: HandlerType))
688 return true;
689
690 // FIXME: ObjC pointer types?
691 if (HandlerType->isPointerType() || HandlerType->isMemberPointerType()) {
692 if (RefTy && (!HandlerType.isConstQualified() ||
693 HandlerType.isVolatileQualified()))
694 return false;
695
696 // -- the handler is of type cv T or const T& where T is a pointer or
697 // pointer to member type and E is std::nullptr_t
698 if (ExceptionType->isNullPtrType())
699 return true;
700
701 // -- the handler is of type cv T or const T& where T is a pointer or
702 // pointer to member type and E is a pointer or pointer to member type
703 // that can be converted to T by one or more of
704 // -- a qualification conversion
705 // -- a function pointer conversion
706 bool LifetimeConv;
707 // FIXME: Should we treat the exception as catchable if a lifetime
708 // conversion is required?
709 if (IsQualificationConversion(FromType: ExceptionType, ToType: HandlerType, CStyle: false,
710 ObjCLifetimeConversion&: LifetimeConv) ||
711 IsFunctionConversion(FromType: ExceptionType, ToType: HandlerType))
712 return true;
713
714 // -- a standard pointer conversion [...]
715 if (!ExceptionType->isPointerType() || !HandlerType->isPointerType())
716 return false;
717
718 // Handle the "qualification conversion" portion.
719 Qualifiers EQuals, HQuals;
720 ExceptionType = Context.getUnqualifiedArrayType(
721 T: ExceptionType->getPointeeType(), Quals&: EQuals);
722 HandlerType =
723 Context.getUnqualifiedArrayType(T: HandlerType->getPointeeType(), Quals&: HQuals);
724 if (!HQuals.compatiblyIncludes(other: EQuals, Ctx: getASTContext()))
725 return false;
726
727 if (HandlerType->isVoidType() && ExceptionType->isObjectType())
728 return true;
729
730 // The only remaining case is a derived-to-base conversion.
731 }
732
733 // -- the handler is of type cg T or cv T& and T is an unambiguous public
734 // base class of E
735 if (!ExceptionType->isRecordType() || !HandlerType->isRecordType())
736 return false;
737 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
738 /*DetectVirtual=*/false);
739 if (!IsDerivedFrom(Loc: SourceLocation(), Derived: ExceptionType, Base: HandlerType, Paths) ||
740 Paths.isAmbiguous(BaseType: Context.getCanonicalType(T: HandlerType)))
741 return false;
742
743 // Do this check from a context without privileges.
744 switch (CheckBaseClassAccess(AccessLoc: SourceLocation(), Base: HandlerType, Derived: ExceptionType,
745 Path: Paths.front(),
746 /*Diagnostic*/ DiagID: 0,
747 /*ForceCheck*/ true,
748 /*ForceUnprivileged*/ true)) {
749 case AR_accessible: return true;
750 case AR_inaccessible: return false;
751 case AR_dependent:
752 llvm_unreachable("access check dependent for unprivileged context");
753 case AR_delayed:
754 llvm_unreachable("access check delayed in non-declaration");
755 }
756 llvm_unreachable("unexpected access check result");
757}
758
759bool Sema::CheckExceptionSpecSubset(
760 const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID,
761 const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID,
762 const FunctionProtoType *Superset, bool SkipSupersetFirstParameter,
763 SourceLocation SuperLoc, const FunctionProtoType *Subset,
764 bool SkipSubsetFirstParameter, SourceLocation SubLoc) {
765
766 // Just auto-succeed under -fno-exceptions.
767 if (!getLangOpts().CXXExceptions)
768 return false;
769
770 // FIXME: As usual, we could be more specific in our error messages, but
771 // that better waits until we've got types with source locations.
772
773 if (!SubLoc.isValid())
774 SubLoc = SuperLoc;
775
776 // Resolve the exception specifications, if needed.
777 Superset = ResolveExceptionSpec(Loc: SuperLoc, FPT: Superset);
778 if (!Superset)
779 return false;
780 Subset = ResolveExceptionSpec(Loc: SubLoc, FPT: Subset);
781 if (!Subset)
782 return false;
783
784 ExceptionSpecificationType SuperEST = Superset->getExceptionSpecType();
785 ExceptionSpecificationType SubEST = Subset->getExceptionSpecType();
786 assert(!isUnresolvedExceptionSpec(SuperEST) &&
787 !isUnresolvedExceptionSpec(SubEST) &&
788 "Shouldn't see unknown exception specifications here");
789
790 // If there are dependent noexcept specs, assume everything is fine. Unlike
791 // with the equivalency check, this is safe in this case, because we don't
792 // want to merge declarations. Checks after instantiation will catch any
793 // omissions we make here.
794 if (SuperEST == EST_DependentNoexcept || SubEST == EST_DependentNoexcept)
795 return false;
796
797 CanThrowResult SuperCanThrow = Superset->canThrow();
798 CanThrowResult SubCanThrow = Subset->canThrow();
799
800 // If the superset contains everything or the subset contains nothing, we're
801 // done.
802 if ((SuperCanThrow == CT_Can && SuperEST != EST_Dynamic) ||
803 SubCanThrow == CT_Cannot)
804 return CheckParamExceptionSpec(NestedDiagID, NoteID, Target: Superset,
805 SkipTargetFirstParameter: SkipSupersetFirstParameter, TargetLoc: SuperLoc, Source: Subset,
806 SkipSourceFirstParameter: SkipSubsetFirstParameter, SourceLoc: SubLoc);
807
808 // Allow __declspec(nothrow) to be missing on redeclaration as an extension in
809 // some cases.
810 if (NoThrowDiagID.getDiagID() != 0 && SubCanThrow == CT_Can &&
811 SuperCanThrow == CT_Cannot && SuperEST == EST_NoThrow) {
812 Diag(Loc: SubLoc, PD: NoThrowDiagID);
813 if (NoteID.getDiagID() != 0)
814 Diag(Loc: SuperLoc, PD: NoteID);
815 return true;
816 }
817
818 // If the subset contains everything or the superset contains nothing, we've
819 // failed.
820 if ((SubCanThrow == CT_Can && SubEST != EST_Dynamic) ||
821 SuperCanThrow == CT_Cannot) {
822 Diag(Loc: SubLoc, PD: DiagID);
823 if (NoteID.getDiagID() != 0)
824 Diag(Loc: SuperLoc, PD: NoteID);
825 return true;
826 }
827
828 assert(SuperEST == EST_Dynamic && SubEST == EST_Dynamic &&
829 "Exception spec subset: non-dynamic case slipped through.");
830
831 // Neither contains everything or nothing. Do a proper comparison.
832 for (QualType SubI : Subset->exceptions()) {
833 if (const ReferenceType *RefTy = SubI->getAs<ReferenceType>())
834 SubI = RefTy->getPointeeType();
835
836 // Make sure it's in the superset.
837 bool Contained = false;
838 for (QualType SuperI : Superset->exceptions()) {
839 // [except.spec]p5:
840 // the target entity shall allow at least the exceptions allowed by the
841 // source
842 //
843 // We interpret this as meaning that a handler for some target type would
844 // catch an exception of each source type.
845 if (handlerCanCatch(HandlerType: SuperI, ExceptionType: SubI)) {
846 Contained = true;
847 break;
848 }
849 }
850 if (!Contained) {
851 Diag(Loc: SubLoc, PD: DiagID);
852 if (NoteID.getDiagID() != 0)
853 Diag(Loc: SuperLoc, PD: NoteID);
854 return true;
855 }
856 }
857 // We've run half the gauntlet.
858 return CheckParamExceptionSpec(NestedDiagID, NoteID, Target: Superset,
859 SkipTargetFirstParameter: SkipSupersetFirstParameter, TargetLoc: SuperLoc, Source: Subset,
860 SkipSourceFirstParameter: SkipSupersetFirstParameter, SourceLoc: SubLoc);
861}
862
863static bool
864CheckSpecForTypesEquivalent(Sema &S, const PartialDiagnostic &DiagID,
865 const PartialDiagnostic &NoteID, QualType Target,
866 SourceLocation TargetLoc, QualType Source,
867 SourceLocation SourceLoc) {
868 const FunctionProtoType *TFunc = GetUnderlyingFunction(T: Target);
869 if (!TFunc)
870 return false;
871 const FunctionProtoType *SFunc = GetUnderlyingFunction(T: Source);
872 if (!SFunc)
873 return false;
874
875 return S.CheckEquivalentExceptionSpec(DiagID, NoteID, Old: TFunc, OldLoc: TargetLoc,
876 New: SFunc, NewLoc: SourceLoc);
877}
878
879bool Sema::CheckParamExceptionSpec(
880 const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID,
881 const FunctionProtoType *Target, bool SkipTargetFirstParameter,
882 SourceLocation TargetLoc, const FunctionProtoType *Source,
883 bool SkipSourceFirstParameter, SourceLocation SourceLoc) {
884 auto RetDiag = DiagID;
885 RetDiag << 0;
886 if (CheckSpecForTypesEquivalent(
887 S&: *this, DiagID: RetDiag, NoteID: PDiag(),
888 Target: Target->getReturnType(), TargetLoc, Source: Source->getReturnType(),
889 SourceLoc))
890 return true;
891
892 // We shouldn't even be testing this unless the arguments are otherwise
893 // compatible.
894 assert((Target->getNumParams() - (unsigned)SkipTargetFirstParameter) ==
895 (Source->getNumParams() - (unsigned)SkipSourceFirstParameter) &&
896 "Functions have different argument counts.");
897 for (unsigned i = 0, E = Target->getNumParams(); i != E; ++i) {
898 auto ParamDiag = DiagID;
899 ParamDiag << 1;
900 if (CheckSpecForTypesEquivalent(
901 S&: *this, DiagID: ParamDiag, NoteID: PDiag(),
902 Target: Target->getParamType(i: i + (SkipTargetFirstParameter ? 1 : 0)),
903 TargetLoc, Source: Source->getParamType(i: SkipSourceFirstParameter ? 1 : 0),
904 SourceLoc))
905 return true;
906 }
907 return false;
908}
909
910bool Sema::CheckExceptionSpecCompatibility(Expr *From, QualType ToType) {
911 // First we check for applicability.
912 // Target type must be a function, function pointer or function reference.
913 const FunctionProtoType *ToFunc = GetUnderlyingFunction(T: ToType);
914 if (!ToFunc || ToFunc->hasDependentExceptionSpec())
915 return false;
916
917 // SourceType must be a function or function pointer.
918 const FunctionProtoType *FromFunc = GetUnderlyingFunction(T: From->getType());
919 if (!FromFunc || FromFunc->hasDependentExceptionSpec())
920 return false;
921
922 unsigned DiagID = diag::err_incompatible_exception_specs;
923 unsigned NestedDiagID = diag::err_deep_exception_specs_differ;
924 // This is not an error in C++17 onwards, unless the noexceptness doesn't
925 // match, but in that case we have a full-on type mismatch, not just a
926 // type sugar mismatch.
927 if (getLangOpts().CPlusPlus17) {
928 DiagID = diag::warn_incompatible_exception_specs;
929 NestedDiagID = diag::warn_deep_exception_specs_differ;
930 }
931
932 // Now we've got the correct types on both sides, check their compatibility.
933 // This means that the source of the conversion can only throw a subset of
934 // the exceptions of the target, and any exception specs on arguments or
935 // return types must be equivalent.
936 //
937 // FIXME: If there is a nested dependent exception specification, we should
938 // not be checking it here. This is fine:
939 // template<typename T> void f() {
940 // void (*p)(void (*) throw(T));
941 // void (*q)(void (*) throw(int)) = p;
942 // }
943 // ... because it might be instantiated with T=int.
944 return CheckExceptionSpecSubset(DiagID: PDiag(DiagID), NestedDiagID: PDiag(DiagID: NestedDiagID), NoteID: PDiag(),
945 NoThrowDiagID: PDiag(), Superset: ToFunc, SkipSupersetFirstParameter: 0,
946 SuperLoc: From->getSourceRange().getBegin(), Subset: FromFunc,
947 SkipSubsetFirstParameter: 0, SubLoc: SourceLocation()) &&
948 !getLangOpts().CPlusPlus17;
949}
950
951bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
952 const CXXMethodDecl *Old) {
953 // If the new exception specification hasn't been parsed yet, skip the check.
954 // We'll get called again once it's been parsed.
955 if (New->getType()->castAs<FunctionProtoType>()->getExceptionSpecType() ==
956 EST_Unparsed)
957 return false;
958
959 // Don't check uninstantiated template destructors at all. We can only
960 // synthesize correct specs after the template is instantiated.
961 if (isa<CXXDestructorDecl>(Val: New) && New->getParent()->isDependentType())
962 return false;
963
964 // If the old exception specification hasn't been parsed yet, or the new
965 // exception specification can't be computed yet, remember that we need to
966 // perform this check when we get to the end of the outermost
967 // lexically-surrounding class.
968 if (exceptionSpecNotKnownYet(FD: Old) || exceptionSpecNotKnownYet(FD: New)) {
969 DelayedOverridingExceptionSpecChecks.push_back(Elt: {New, Old});
970 return false;
971 }
972
973 unsigned DiagID = diag::err_override_exception_spec;
974 if (getLangOpts().MSVCCompat)
975 DiagID = diag::ext_override_exception_spec;
976 return CheckExceptionSpecSubset(
977 DiagID: PDiag(DiagID), NestedDiagID: PDiag(DiagID: diag::err_deep_exception_specs_differ),
978 NoteID: PDiag(DiagID: diag::note_overridden_virtual_function),
979 NoThrowDiagID: PDiag(DiagID: diag::ext_override_exception_spec),
980 Superset: Old->getType()->castAs<FunctionProtoType>(),
981 SkipSupersetFirstParameter: Old->hasCXXExplicitFunctionObjectParameter(), SuperLoc: Old->getLocation(),
982 Subset: New->getType()->castAs<FunctionProtoType>(),
983 SkipSubsetFirstParameter: New->hasCXXExplicitFunctionObjectParameter(), SubLoc: New->getLocation());
984}
985
986static CanThrowResult canSubStmtsThrow(Sema &Self, const Stmt *S) {
987 CanThrowResult R = CT_Cannot;
988 for (const Stmt *SubStmt : S->children()) {
989 if (!SubStmt)
990 continue;
991 R = mergeCanThrow(CT1: R, CT2: Self.canThrow(E: SubStmt));
992 if (R == CT_Can)
993 break;
994 }
995 return R;
996}
997
998CanThrowResult Sema::canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
999 SourceLocation Loc) {
1000 // As an extension, we assume that __attribute__((nothrow)) functions don't
1001 // throw.
1002 if (isa_and_nonnull<FunctionDecl>(Val: D) && D->hasAttr<NoThrowAttr>())
1003 return CT_Cannot;
1004
1005 QualType T;
1006
1007 // In C++1z, just look at the function type of the callee.
1008 if (S.getLangOpts().CPlusPlus17 && isa_and_nonnull<CallExpr>(Val: E)) {
1009 E = cast<CallExpr>(Val: E)->getCallee();
1010 T = E->getType();
1011 if (T->isSpecificPlaceholderType(K: BuiltinType::BoundMember)) {
1012 // Sadly we don't preserve the actual type as part of the "bound member"
1013 // placeholder, so we need to reconstruct it.
1014 E = E->IgnoreParenImpCasts();
1015
1016 // Could be a call to a pointer-to-member or a plain member access.
1017 if (auto *Op = dyn_cast<BinaryOperator>(Val: E)) {
1018 assert(Op->getOpcode() == BO_PtrMemD || Op->getOpcode() == BO_PtrMemI);
1019 T = Op->getRHS()->getType()
1020 ->castAs<MemberPointerType>()->getPointeeType();
1021 } else {
1022 T = cast<MemberExpr>(Val: E)->getMemberDecl()->getType();
1023 }
1024 }
1025 } else if (const ValueDecl *VD = dyn_cast_or_null<ValueDecl>(Val: D))
1026 T = VD->getType();
1027 else
1028 // If we have no clue what we're calling, assume the worst.
1029 return CT_Can;
1030
1031 const FunctionProtoType *FT;
1032 if ((FT = T->getAs<FunctionProtoType>())) {
1033 } else if (const PointerType *PT = T->getAs<PointerType>())
1034 FT = PT->getPointeeType()->getAs<FunctionProtoType>();
1035 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
1036 FT = RT->getPointeeType()->getAs<FunctionProtoType>();
1037 else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
1038 FT = MT->getPointeeType()->getAs<FunctionProtoType>();
1039 else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
1040 FT = BT->getPointeeType()->getAs<FunctionProtoType>();
1041
1042 if (!FT)
1043 return CT_Can;
1044
1045 if (Loc.isValid() || (Loc.isInvalid() && E))
1046 FT = S.ResolveExceptionSpec(Loc: Loc.isInvalid() ? E->getBeginLoc() : Loc, FPT: FT);
1047 if (!FT)
1048 return CT_Can;
1049
1050 return FT->canThrow();
1051}
1052
1053static CanThrowResult canVarDeclThrow(Sema &Self, const VarDecl *VD) {
1054 CanThrowResult CT = CT_Cannot;
1055
1056 // Initialization might throw.
1057 if (!VD->isUsableInConstantExpressions(C: Self.Context))
1058 if (const Expr *Init = VD->getInit())
1059 CT = mergeCanThrow(CT1: CT, CT2: Self.canThrow(E: Init));
1060
1061 // Destructor might throw.
1062 if (VD->needsDestruction(Ctx: Self.Context) == QualType::DK_cxx_destructor) {
1063 if (auto *RD =
1064 VD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
1065 if (auto *Dtor = RD->getDestructor()) {
1066 CT = mergeCanThrow(
1067 CT1: CT, CT2: Sema::canCalleeThrow(S&: Self, E: nullptr, D: Dtor, Loc: VD->getLocation()));
1068 }
1069 }
1070 }
1071
1072 // If this is a decomposition declaration, bindings might throw.
1073 if (auto *DD = dyn_cast<DecompositionDecl>(Val: VD))
1074 for (auto *B : DD->flat_bindings())
1075 if (auto *HD = B->getHoldingVar())
1076 CT = mergeCanThrow(CT1: CT, CT2: canVarDeclThrow(Self, VD: HD));
1077
1078 return CT;
1079}
1080
1081static CanThrowResult canDynamicCastThrow(const CXXDynamicCastExpr *DC) {
1082 if (DC->isTypeDependent())
1083 return CT_Dependent;
1084
1085 if (!DC->getTypeAsWritten()->isReferenceType())
1086 return CT_Cannot;
1087
1088 if (DC->getSubExpr()->isTypeDependent())
1089 return CT_Dependent;
1090
1091 return DC->getCastKind() == clang::CK_Dynamic? CT_Can : CT_Cannot;
1092}
1093
1094static CanThrowResult canTypeidThrow(Sema &S, const CXXTypeidExpr *DC) {
1095 // A typeid of a type is a constant and does not throw.
1096 if (DC->isTypeOperand())
1097 return CT_Cannot;
1098
1099 if (DC->isValueDependent())
1100 return CT_Dependent;
1101
1102 // If this operand is not evaluated it cannot possibly throw.
1103 if (!DC->isPotentiallyEvaluated())
1104 return CT_Cannot;
1105
1106 // Can throw std::bad_typeid if a nullptr is dereferenced.
1107 if (DC->hasNullCheck())
1108 return CT_Can;
1109
1110 return S.canThrow(E: DC->getExprOperand());
1111}
1112
1113CanThrowResult Sema::canThrow(const Stmt *S) {
1114 // C++ [expr.unary.noexcept]p3:
1115 // [Can throw] if in a potentially-evaluated context the expression would
1116 // contain:
1117 switch (S->getStmtClass()) {
1118 case Expr::ConstantExprClass:
1119 return canThrow(S: cast<ConstantExpr>(Val: S)->getSubExpr());
1120
1121 case Expr::CXXThrowExprClass:
1122 // - a potentially evaluated throw-expression
1123 return CT_Can;
1124
1125 case Expr::CXXDynamicCastExprClass: {
1126 // - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
1127 // where T is a reference type, that requires a run-time check
1128 auto *CE = cast<CXXDynamicCastExpr>(Val: S);
1129 // FIXME: Properly determine whether a variably-modified type can throw.
1130 if (CE->getType()->isVariablyModifiedType())
1131 return CT_Can;
1132 CanThrowResult CT = canDynamicCastThrow(DC: CE);
1133 if (CT == CT_Can)
1134 return CT;
1135 return mergeCanThrow(CT1: CT, CT2: canSubStmtsThrow(Self&: *this, S: CE));
1136 }
1137
1138 case Expr::CXXTypeidExprClass:
1139 // - a potentially evaluated typeid expression applied to a (possibly
1140 // parenthesized) built-in unary * operator applied to a pointer to a
1141 // polymorphic class type
1142 return canTypeidThrow(S&: *this, DC: cast<CXXTypeidExpr>(Val: S));
1143
1144 // - a potentially evaluated call to a function, member function, function
1145 // pointer, or member function pointer that does not have a non-throwing
1146 // exception-specification
1147 case Expr::CallExprClass:
1148 case Expr::CXXMemberCallExprClass:
1149 case Expr::CXXOperatorCallExprClass:
1150 case Expr::UserDefinedLiteralClass: {
1151 const CallExpr *CE = cast<CallExpr>(Val: S);
1152 CanThrowResult CT;
1153 if (CE->isTypeDependent())
1154 CT = CT_Dependent;
1155 else if (isa<CXXPseudoDestructorExpr>(Val: CE->getCallee()->IgnoreParens()))
1156 CT = CT_Cannot;
1157 else
1158 CT = canCalleeThrow(S&: *this, E: CE, D: CE->getCalleeDecl());
1159 if (CT == CT_Can)
1160 return CT;
1161 return mergeCanThrow(CT1: CT, CT2: canSubStmtsThrow(Self&: *this, S: CE));
1162 }
1163
1164 case Expr::CXXConstructExprClass:
1165 case Expr::CXXTemporaryObjectExprClass: {
1166 auto *CE = cast<CXXConstructExpr>(Val: S);
1167 // FIXME: Properly determine whether a variably-modified type can throw.
1168 if (CE->getType()->isVariablyModifiedType())
1169 return CT_Can;
1170 CanThrowResult CT = canCalleeThrow(S&: *this, E: CE, D: CE->getConstructor());
1171 if (CT == CT_Can)
1172 return CT;
1173 return mergeCanThrow(CT1: CT, CT2: canSubStmtsThrow(Self&: *this, S: CE));
1174 }
1175
1176 case Expr::CXXInheritedCtorInitExprClass: {
1177 auto *ICIE = cast<CXXInheritedCtorInitExpr>(Val: S);
1178 return canCalleeThrow(S&: *this, E: ICIE, D: ICIE->getConstructor());
1179 }
1180
1181 case Expr::LambdaExprClass: {
1182 const LambdaExpr *Lambda = cast<LambdaExpr>(Val: S);
1183 CanThrowResult CT = CT_Cannot;
1184 for (LambdaExpr::const_capture_init_iterator
1185 Cap = Lambda->capture_init_begin(),
1186 CapEnd = Lambda->capture_init_end();
1187 Cap != CapEnd; ++Cap)
1188 CT = mergeCanThrow(CT1: CT, CT2: canThrow(S: *Cap));
1189 return CT;
1190 }
1191
1192 case Expr::CXXNewExprClass: {
1193 auto *NE = cast<CXXNewExpr>(Val: S);
1194 CanThrowResult CT;
1195 if (NE->isTypeDependent())
1196 CT = CT_Dependent;
1197 else
1198 CT = canCalleeThrow(S&: *this, E: NE, D: NE->getOperatorNew());
1199 if (CT == CT_Can)
1200 return CT;
1201 return mergeCanThrow(CT1: CT, CT2: canSubStmtsThrow(Self&: *this, S: NE));
1202 }
1203
1204 case Expr::CXXDeleteExprClass: {
1205 auto *DE = cast<CXXDeleteExpr>(Val: S);
1206 CanThrowResult CT = CT_Cannot;
1207 QualType DTy = DE->getDestroyedType();
1208 if (DTy.isNull() || DTy->isDependentType()) {
1209 CT = CT_Dependent;
1210 } else {
1211 // C++20 [expr.delete]p6: If the value of the operand of the delete-
1212 // expression is not a null pointer value and the selected deallocation
1213 // function (see below) is not a destroying operator delete, the delete-
1214 // expression will invoke the destructor (if any) for the object or the
1215 // elements of the array being deleted.
1216 const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
1217 if (const auto *RD = DTy->getAsCXXRecordDecl()) {
1218 if (const CXXDestructorDecl *DD = RD->getDestructor();
1219 DD && DD->isCalledByDelete(OpDel: OperatorDelete))
1220 CT = canCalleeThrow(S&: *this, E: DE, D: DD);
1221 }
1222
1223 // We always look at the exception specification of the operator delete.
1224 CT = mergeCanThrow(CT1: CT, CT2: canCalleeThrow(S&: *this, E: DE, D: OperatorDelete));
1225
1226 // If we know we can throw, we're done.
1227 if (CT == CT_Can)
1228 return CT;
1229 }
1230 return mergeCanThrow(CT1: CT, CT2: canSubStmtsThrow(Self&: *this, S: DE));
1231 }
1232
1233 case Expr::CXXBindTemporaryExprClass: {
1234 auto *BTE = cast<CXXBindTemporaryExpr>(Val: S);
1235 // The bound temporary has to be destroyed again, which might throw.
1236 CanThrowResult CT =
1237 canCalleeThrow(S&: *this, E: BTE, D: BTE->getTemporary()->getDestructor());
1238 if (CT == CT_Can)
1239 return CT;
1240 return mergeCanThrow(CT1: CT, CT2: canSubStmtsThrow(Self&: *this, S: BTE));
1241 }
1242
1243 case Expr::PseudoObjectExprClass: {
1244 auto *POE = cast<PseudoObjectExpr>(Val: S);
1245 CanThrowResult CT = CT_Cannot;
1246 for (const Expr *E : POE->semantics()) {
1247 CT = mergeCanThrow(CT1: CT, CT2: canThrow(S: E));
1248 if (CT == CT_Can)
1249 break;
1250 }
1251 return CT;
1252 }
1253
1254 case Stmt::SYCLKernelCallStmtClass: {
1255 auto *SKCS = cast<SYCLKernelCallStmt>(Val: S);
1256 if (getLangOpts().SYCLIsDevice)
1257 return canSubStmtsThrow(Self&: *this,
1258 S: SKCS->getOutlinedFunctionDecl()->getBody());
1259 assert(getLangOpts().SYCLIsHost);
1260 return canSubStmtsThrow(Self&: *this, S: SKCS->getKernelLaunchStmt());
1261 }
1262
1263 case Stmt::UnresolvedSYCLKernelCallStmtClass:
1264 return CT_Dependent;
1265
1266 // ObjC message sends are like function calls, but never have exception
1267 // specs.
1268 case Expr::ObjCMessageExprClass:
1269 case Expr::ObjCPropertyRefExprClass:
1270 case Expr::ObjCSubscriptRefExprClass:
1271 return CT_Can;
1272
1273 // All the ObjC literals that are implemented as calls are
1274 // potentially throwing unless we decide to close off that
1275 // possibility.
1276 case Expr::ObjCArrayLiteralClass:
1277 case Expr::ObjCDictionaryLiteralClass:
1278 case Expr::ObjCBoxedExprClass:
1279 return CT_Can;
1280
1281 // Many other things have subexpressions, so we have to test those.
1282 // Some are simple:
1283 case Expr::CoawaitExprClass:
1284 case Expr::ConditionalOperatorClass:
1285 case Expr::CoyieldExprClass:
1286 case Expr::CXXRewrittenBinaryOperatorClass:
1287 case Expr::CXXStdInitializerListExprClass:
1288 case Expr::DesignatedInitExprClass:
1289 case Expr::DesignatedInitUpdateExprClass:
1290 case Expr::ExprWithCleanupsClass:
1291 case Expr::ExtVectorElementExprClass:
1292 case Expr::MatrixElementExprClass:
1293 case Expr::InitListExprClass:
1294 case Expr::ArrayInitLoopExprClass:
1295 case Expr::MemberExprClass:
1296 case Expr::ObjCIsaExprClass:
1297 case Expr::ObjCIvarRefExprClass:
1298 case Expr::ParenExprClass:
1299 case Expr::ParenListExprClass:
1300 case Expr::ShuffleVectorExprClass:
1301 case Expr::StmtExprClass:
1302 case Expr::ConvertVectorExprClass:
1303 case Expr::VAArgExprClass:
1304 case Expr::CXXParenListInitExprClass:
1305 return canSubStmtsThrow(Self&: *this, S);
1306
1307 case Expr::CompoundLiteralExprClass:
1308 case Expr::CXXConstCastExprClass:
1309 case Expr::CXXAddrspaceCastExprClass:
1310 case Expr::CXXReinterpretCastExprClass:
1311 case Expr::BuiltinBitCastExprClass:
1312 // FIXME: Properly determine whether a variably-modified type can throw.
1313 if (cast<Expr>(Val: S)->getType()->isVariablyModifiedType())
1314 return CT_Can;
1315 return canSubStmtsThrow(Self&: *this, S);
1316
1317 // Some might be dependent for other reasons.
1318 case Expr::ArraySubscriptExprClass:
1319 case Expr::MatrixSubscriptExprClass:
1320 case Expr::MatrixSingleSubscriptExprClass:
1321 case Expr::ArraySectionExprClass:
1322 case Expr::OMPArrayShapingExprClass:
1323 case Expr::OMPIteratorExprClass:
1324 case Expr::BinaryOperatorClass:
1325 case Expr::DependentCoawaitExprClass:
1326 case Expr::CompoundAssignOperatorClass:
1327 case Expr::CStyleCastExprClass:
1328 case Expr::CXXStaticCastExprClass:
1329 case Expr::CXXFunctionalCastExprClass:
1330 case Expr::ImplicitCastExprClass:
1331 case Expr::MaterializeTemporaryExprClass:
1332 case Expr::UnaryOperatorClass: {
1333 // FIXME: Properly determine whether a variably-modified type can throw.
1334 if (auto *CE = dyn_cast<CastExpr>(Val: S))
1335 if (CE->getType()->isVariablyModifiedType())
1336 return CT_Can;
1337 CanThrowResult CT =
1338 cast<Expr>(Val: S)->isTypeDependent() ? CT_Dependent : CT_Cannot;
1339 return mergeCanThrow(CT1: CT, CT2: canSubStmtsThrow(Self&: *this, S));
1340 }
1341
1342 case Expr::CXXDefaultArgExprClass:
1343 return canThrow(S: cast<CXXDefaultArgExpr>(Val: S)->getExpr());
1344
1345 case Expr::CXXDefaultInitExprClass:
1346 return canThrow(S: cast<CXXDefaultInitExpr>(Val: S)->getExpr());
1347
1348 case Expr::ChooseExprClass: {
1349 auto *CE = cast<ChooseExpr>(Val: S);
1350 if (CE->isTypeDependent() || CE->isValueDependent())
1351 return CT_Dependent;
1352 return canThrow(S: CE->getChosenSubExpr());
1353 }
1354
1355 case Expr::GenericSelectionExprClass:
1356 if (cast<GenericSelectionExpr>(Val: S)->isResultDependent())
1357 return CT_Dependent;
1358 return canThrow(S: cast<GenericSelectionExpr>(Val: S)->getResultExpr());
1359
1360 // Some expressions are always dependent.
1361 case Expr::CXXDependentScopeMemberExprClass:
1362 case Expr::CXXUnresolvedConstructExprClass:
1363 case Expr::DependentScopeDeclRefExprClass:
1364 case Expr::CXXFoldExprClass:
1365 case Expr::RecoveryExprClass:
1366 return CT_Dependent;
1367
1368 case Expr::AsTypeExprClass:
1369 case Expr::BinaryConditionalOperatorClass:
1370 case Expr::BlockExprClass:
1371 case Expr::CUDAKernelCallExprClass:
1372 case Expr::DeclRefExprClass:
1373 case Expr::ObjCBridgedCastExprClass:
1374 case Expr::ObjCIndirectCopyRestoreExprClass:
1375 case Expr::ObjCProtocolExprClass:
1376 case Expr::ObjCSelectorExprClass:
1377 case Expr::ObjCAvailabilityCheckExprClass:
1378 case Expr::OffsetOfExprClass:
1379 case Expr::PackExpansionExprClass:
1380 case Expr::SubstNonTypeTemplateParmExprClass:
1381 case Expr::SubstNonTypeTemplateParmPackExprClass:
1382 case Expr::FunctionParmPackExprClass:
1383 case Expr::UnaryExprOrTypeTraitExprClass:
1384 case Expr::UnresolvedLookupExprClass:
1385 case Expr::UnresolvedMemberExprClass:
1386 // FIXME: Many of the above can throw.
1387 return CT_Cannot;
1388
1389 case Expr::AddrLabelExprClass:
1390 case Expr::ArrayTypeTraitExprClass:
1391 case Expr::AtomicExprClass:
1392 case Expr::TypeTraitExprClass:
1393 case Expr::CXXBoolLiteralExprClass:
1394 case Expr::CXXNoexceptExprClass:
1395 case Expr::CXXNullPtrLiteralExprClass:
1396 case Expr::CXXPseudoDestructorExprClass:
1397 case Expr::CXXReflectExprClass:
1398 case Expr::CXXScalarValueInitExprClass:
1399 case Expr::CXXThisExprClass:
1400 case Expr::CXXUuidofExprClass:
1401 case Expr::CharacterLiteralClass:
1402 case Expr::ExpressionTraitExprClass:
1403 case Expr::FloatingLiteralClass:
1404 case Expr::GNUNullExprClass:
1405 case Expr::ImaginaryLiteralClass:
1406 case Expr::ImplicitValueInitExprClass:
1407 case Expr::IntegerLiteralClass:
1408 case Expr::FixedPointLiteralClass:
1409 case Expr::ArrayInitIndexExprClass:
1410 case Expr::NoInitExprClass:
1411 case Expr::ObjCEncodeExprClass:
1412 case Expr::ObjCStringLiteralClass:
1413 case Expr::ObjCBoolLiteralExprClass:
1414 case Expr::OpaqueValueExprClass:
1415 case Expr::PredefinedExprClass:
1416 case Expr::SizeOfPackExprClass:
1417 case Expr::PackIndexingExprClass:
1418 case Expr::StringLiteralClass:
1419 case Expr::SourceLocExprClass:
1420 case Expr::EmbedExprClass:
1421 case Expr::ConceptSpecializationExprClass:
1422 case Expr::RequiresExprClass:
1423 case Expr::HLSLOutArgExprClass:
1424 case Stmt::OpenACCEnterDataConstructClass:
1425 case Stmt::OpenACCExitDataConstructClass:
1426 case Stmt::OpenACCWaitConstructClass:
1427 case Stmt::OpenACCCacheConstructClass:
1428 case Stmt::OpenACCInitConstructClass:
1429 case Stmt::OpenACCShutdownConstructClass:
1430 case Stmt::OpenACCSetConstructClass:
1431 case Stmt::OpenACCUpdateConstructClass:
1432 // These expressions can never throw.
1433 return CT_Cannot;
1434
1435 case Expr::MSPropertyRefExprClass:
1436 case Expr::MSPropertySubscriptExprClass:
1437 llvm_unreachable("Invalid class for expression");
1438
1439 // Most statements can throw if any substatement can throw.
1440 case Stmt::OpenACCComputeConstructClass:
1441 case Stmt::OpenACCLoopConstructClass:
1442 case Stmt::OpenACCCombinedConstructClass:
1443 case Stmt::OpenACCDataConstructClass:
1444 case Stmt::OpenACCHostDataConstructClass:
1445 case Stmt::OpenACCAtomicConstructClass:
1446 case Stmt::AttributedStmtClass:
1447 case Stmt::BreakStmtClass:
1448 case Stmt::CapturedStmtClass:
1449 case Stmt::CaseStmtClass:
1450 case Stmt::CompoundStmtClass:
1451 case Stmt::ContinueStmtClass:
1452 case Stmt::CoreturnStmtClass:
1453 case Stmt::CoroutineBodyStmtClass:
1454 case Stmt::CXXCatchStmtClass:
1455 case Stmt::CXXForRangeStmtClass:
1456 case Stmt::DefaultStmtClass:
1457 case Stmt::DoStmtClass:
1458 case Stmt::ForStmtClass:
1459 case Stmt::GCCAsmStmtClass:
1460 case Stmt::GotoStmtClass:
1461 case Stmt::IndirectGotoStmtClass:
1462 case Stmt::LabelStmtClass:
1463 case Stmt::MSAsmStmtClass:
1464 case Stmt::MSDependentExistsStmtClass:
1465 case Stmt::NullStmtClass:
1466 case Stmt::ObjCAtCatchStmtClass:
1467 case Stmt::ObjCAtFinallyStmtClass:
1468 case Stmt::ObjCAtSynchronizedStmtClass:
1469 case Stmt::ObjCAutoreleasePoolStmtClass:
1470 case Stmt::ObjCForCollectionStmtClass:
1471 case Stmt::OMPAtomicDirectiveClass:
1472 case Stmt::OMPAssumeDirectiveClass:
1473 case Stmt::OMPBarrierDirectiveClass:
1474 case Stmt::OMPCancelDirectiveClass:
1475 case Stmt::OMPCancellationPointDirectiveClass:
1476 case Stmt::OMPCriticalDirectiveClass:
1477 case Stmt::OMPDistributeDirectiveClass:
1478 case Stmt::OMPDistributeParallelForDirectiveClass:
1479 case Stmt::OMPDistributeParallelForSimdDirectiveClass:
1480 case Stmt::OMPDistributeSimdDirectiveClass:
1481 case Stmt::OMPFlushDirectiveClass:
1482 case Stmt::OMPDepobjDirectiveClass:
1483 case Stmt::OMPScanDirectiveClass:
1484 case Stmt::OMPForDirectiveClass:
1485 case Stmt::OMPForSimdDirectiveClass:
1486 case Stmt::OMPMasterDirectiveClass:
1487 case Stmt::OMPMasterTaskLoopDirectiveClass:
1488 case Stmt::OMPMaskedTaskLoopDirectiveClass:
1489 case Stmt::OMPMasterTaskLoopSimdDirectiveClass:
1490 case Stmt::OMPMaskedTaskLoopSimdDirectiveClass:
1491 case Stmt::OMPOrderedDirectiveClass:
1492 case Stmt::OMPCanonicalLoopClass:
1493 case Stmt::OMPParallelDirectiveClass:
1494 case Stmt::OMPParallelForDirectiveClass:
1495 case Stmt::OMPParallelForSimdDirectiveClass:
1496 case Stmt::OMPParallelMasterDirectiveClass:
1497 case Stmt::OMPParallelMaskedDirectiveClass:
1498 case Stmt::OMPParallelMasterTaskLoopDirectiveClass:
1499 case Stmt::OMPParallelMaskedTaskLoopDirectiveClass:
1500 case Stmt::OMPParallelMasterTaskLoopSimdDirectiveClass:
1501 case Stmt::OMPParallelMaskedTaskLoopSimdDirectiveClass:
1502 case Stmt::OMPParallelSectionsDirectiveClass:
1503 case Stmt::OMPSectionDirectiveClass:
1504 case Stmt::OMPSectionsDirectiveClass:
1505 case Stmt::OMPSimdDirectiveClass:
1506 case Stmt::OMPTileDirectiveClass:
1507 case Stmt::OMPStripeDirectiveClass:
1508 case Stmt::OMPUnrollDirectiveClass:
1509 case Stmt::OMPReverseDirectiveClass:
1510 case Stmt::OMPInterchangeDirectiveClass:
1511 case Stmt::OMPFuseDirectiveClass:
1512 case Stmt::OMPSingleDirectiveClass:
1513 case Stmt::OMPTargetDataDirectiveClass:
1514 case Stmt::OMPTargetDirectiveClass:
1515 case Stmt::OMPTargetEnterDataDirectiveClass:
1516 case Stmt::OMPTargetExitDataDirectiveClass:
1517 case Stmt::OMPTargetParallelDirectiveClass:
1518 case Stmt::OMPTargetParallelForDirectiveClass:
1519 case Stmt::OMPTargetParallelForSimdDirectiveClass:
1520 case Stmt::OMPTargetSimdDirectiveClass:
1521 case Stmt::OMPTargetTeamsDirectiveClass:
1522 case Stmt::OMPTargetTeamsDistributeDirectiveClass:
1523 case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
1524 case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
1525 case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
1526 case Stmt::OMPTargetUpdateDirectiveClass:
1527 case Stmt::OMPScopeDirectiveClass:
1528 case Stmt::OMPTaskDirectiveClass:
1529 case Stmt::OMPTaskgroupDirectiveClass:
1530 case Stmt::OMPTaskLoopDirectiveClass:
1531 case Stmt::OMPTaskLoopSimdDirectiveClass:
1532 case Stmt::OMPTaskwaitDirectiveClass:
1533 case Stmt::OMPTaskyieldDirectiveClass:
1534 case Stmt::OMPErrorDirectiveClass:
1535 case Stmt::OMPTeamsDirectiveClass:
1536 case Stmt::OMPTeamsDistributeDirectiveClass:
1537 case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
1538 case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
1539 case Stmt::OMPTeamsDistributeSimdDirectiveClass:
1540 case Stmt::OMPInteropDirectiveClass:
1541 case Stmt::OMPDispatchDirectiveClass:
1542 case Stmt::OMPMaskedDirectiveClass:
1543 case Stmt::OMPMetaDirectiveClass:
1544 case Stmt::OMPGenericLoopDirectiveClass:
1545 case Stmt::OMPTeamsGenericLoopDirectiveClass:
1546 case Stmt::OMPTargetTeamsGenericLoopDirectiveClass:
1547 case Stmt::OMPParallelGenericLoopDirectiveClass:
1548 case Stmt::OMPTargetParallelGenericLoopDirectiveClass:
1549 case Stmt::ReturnStmtClass:
1550 case Stmt::SEHExceptStmtClass:
1551 case Stmt::SEHFinallyStmtClass:
1552 case Stmt::SEHLeaveStmtClass:
1553 case Stmt::SEHTryStmtClass:
1554 case Stmt::SwitchStmtClass:
1555 case Stmt::WhileStmtClass:
1556 case Stmt::DeferStmtClass:
1557 return canSubStmtsThrow(Self&: *this, S);
1558
1559 case Stmt::DeclStmtClass: {
1560 CanThrowResult CT = CT_Cannot;
1561 for (const Decl *D : cast<DeclStmt>(Val: S)->decls()) {
1562 if (auto *VD = dyn_cast<VarDecl>(Val: D))
1563 CT = mergeCanThrow(CT1: CT, CT2: canVarDeclThrow(Self&: *this, VD));
1564
1565 // FIXME: Properly determine whether a variably-modified type can throw.
1566 if (auto *TND = dyn_cast<TypedefNameDecl>(Val: D))
1567 if (TND->getUnderlyingType()->isVariablyModifiedType())
1568 return CT_Can;
1569 if (auto *VD = dyn_cast<ValueDecl>(Val: D))
1570 if (VD->getType()->isVariablyModifiedType())
1571 return CT_Can;
1572 }
1573 return CT;
1574 }
1575
1576 case Stmt::IfStmtClass: {
1577 auto *IS = cast<IfStmt>(Val: S);
1578 CanThrowResult CT = CT_Cannot;
1579 if (const Stmt *Init = IS->getInit())
1580 CT = mergeCanThrow(CT1: CT, CT2: canThrow(S: Init));
1581 if (const Stmt *CondDS = IS->getConditionVariableDeclStmt())
1582 CT = mergeCanThrow(CT1: CT, CT2: canThrow(S: CondDS));
1583 CT = mergeCanThrow(CT1: CT, CT2: canThrow(S: IS->getCond()));
1584
1585 // For 'if constexpr', consider only the non-discarded case.
1586 // FIXME: We should add a DiscardedStmt marker to the AST.
1587 if (std::optional<const Stmt *> Case = IS->getNondiscardedCase(Ctx: Context))
1588 return *Case ? mergeCanThrow(CT1: CT, CT2: canThrow(S: *Case)) : CT;
1589
1590 CanThrowResult Then = canThrow(S: IS->getThen());
1591 CanThrowResult Else = IS->getElse() ? canThrow(S: IS->getElse()) : CT_Cannot;
1592 if (Then == Else)
1593 return mergeCanThrow(CT1: CT, CT2: Then);
1594
1595 // For a dependent 'if constexpr', the result is dependent if it depends on
1596 // the value of the condition.
1597 return mergeCanThrow(CT1: CT, CT2: IS->isConstexpr() ? CT_Dependent
1598 : mergeCanThrow(CT1: Then, CT2: Else));
1599 }
1600
1601 case Stmt::CXXTryStmtClass: {
1602 auto *TS = cast<CXXTryStmt>(Val: S);
1603 // try /*...*/ catch (...) { H } can throw only if H can throw.
1604 // Any other try-catch can throw if any substatement can throw.
1605 const CXXCatchStmt *FinalHandler = TS->getHandler(i: TS->getNumHandlers() - 1);
1606 if (!FinalHandler->getExceptionDecl())
1607 return canThrow(S: FinalHandler->getHandlerBlock());
1608 return canSubStmtsThrow(Self&: *this, S);
1609 }
1610
1611 case Stmt::ObjCAtThrowStmtClass:
1612 return CT_Can;
1613
1614 case Stmt::ObjCAtTryStmtClass: {
1615 auto *TS = cast<ObjCAtTryStmt>(Val: S);
1616
1617 // @catch(...) need not be last in Objective-C. Walk backwards until we
1618 // see one or hit the @try.
1619 CanThrowResult CT = CT_Cannot;
1620 if (const Stmt *Finally = TS->getFinallyStmt())
1621 CT = mergeCanThrow(CT1: CT, CT2: canThrow(S: Finally));
1622 for (unsigned I = TS->getNumCatchStmts(); I != 0; --I) {
1623 const ObjCAtCatchStmt *Catch = TS->getCatchStmt(I: I - 1);
1624 CT = mergeCanThrow(CT1: CT, CT2: canThrow(S: Catch));
1625 // If we reach a @catch(...), no earlier exceptions can escape.
1626 if (Catch->hasEllipsis())
1627 return CT;
1628 }
1629
1630 // Didn't find an @catch(...). Exceptions from the @try body can escape.
1631 return mergeCanThrow(CT1: CT, CT2: canThrow(S: TS->getTryBody()));
1632 }
1633
1634 case Stmt::SYCLUniqueStableNameExprClass:
1635 return CT_Cannot;
1636 case Stmt::OpenACCAsteriskSizeExprClass:
1637 return CT_Cannot;
1638 case Stmt::NoStmtClass:
1639 llvm_unreachable("Invalid class for statement");
1640 }
1641 llvm_unreachable("Bogus StmtClass");
1642}
1643
1644} // end namespace clang
1645