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