1 //===--- SemaExceptionSpec.cpp - C++ Exception Specifications ---*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file provides Sema routines for C++ exception specification testing.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/AST/ASTMutationListener.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/ExprCXX.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 
25 namespace clang {
26 
27 static const FunctionProtoType *GetUnderlyingFunction(QualType T)
28 {
29   if (const PointerType *PtrTy = T->getAs<PointerType>())
30     T = PtrTy->getPointeeType();
31   else if (const ReferenceType *RefTy = T->getAs<ReferenceType>())
32     T = RefTy->getPointeeType();
33   else if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
34     T = MPTy->getPointeeType();
35   return T->getAs<FunctionProtoType>();
36 }
37 
38 /// HACK: libstdc++ has a bug where it shadows std::swap with a member
39 /// swap function then tries to call std::swap unqualified from the exception
40 /// specification of that function. This function detects whether we're in
41 /// such a case and turns off delay-parsing of exception specifications.
42 bool Sema::isLibstdcxxEagerExceptionSpecHack(const Declarator &D) {
43   auto *RD = dyn_cast<CXXRecordDecl>(CurContext);
44 
45   // All the problem cases are member functions named "swap" within class
46   // templates declared directly within namespace std.
47   if (!RD || RD->getEnclosingNamespaceContext() != getStdNamespace() ||
48       !RD->getIdentifier() || !RD->getDescribedClassTemplate() ||
49       !D.getIdentifier() || !D.getIdentifier()->isStr("swap"))
50     return false;
51 
52   // Only apply this hack within a system header.
53   if (!Context.getSourceManager().isInSystemHeader(D.getLocStart()))
54     return false;
55 
56   return llvm::StringSwitch<bool>(RD->getIdentifier()->getName())
57       .Case("array", true)
58       .Case("pair", true)
59       .Case("priority_queue", true)
60       .Case("stack", true)
61       .Case("queue", true)
62       .Default(false);
63 }
64 
65 /// CheckSpecifiedExceptionType - Check if the given type is valid in an
66 /// exception specification. Incomplete types, or pointers to incomplete types
67 /// other than void are not allowed.
68 ///
69 /// \param[in,out] T  The exception type. This will be decayed to a pointer type
70 ///                   when the input is an array or a function type.
71 bool Sema::CheckSpecifiedExceptionType(QualType &T, const SourceRange &Range) {
72   // C++11 [except.spec]p2:
73   //   A type cv T, "array of T", or "function returning T" denoted
74   //   in an exception-specification is adjusted to type T, "pointer to T", or
75   //   "pointer to function returning T", respectively.
76   //
77   // We also apply this rule in C++98.
78   if (T->isArrayType())
79     T = Context.getArrayDecayedType(T);
80   else if (T->isFunctionType())
81     T = Context.getPointerType(T);
82 
83   int Kind = 0;
84   QualType PointeeT = T;
85   if (const PointerType *PT = T->getAs<PointerType>()) {
86     PointeeT = PT->getPointeeType();
87     Kind = 1;
88 
89     // cv void* is explicitly permitted, despite being a pointer to an
90     // incomplete type.
91     if (PointeeT->isVoidType())
92       return false;
93   } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
94     PointeeT = RT->getPointeeType();
95     Kind = 2;
96 
97     if (RT->isRValueReferenceType()) {
98       // C++11 [except.spec]p2:
99       //   A type denoted in an exception-specification shall not denote [...]
100       //   an rvalue reference type.
101       Diag(Range.getBegin(), diag::err_rref_in_exception_spec)
102         << T << Range;
103       return true;
104     }
105   }
106 
107   // C++11 [except.spec]p2:
108   //   A type denoted in an exception-specification shall not denote an
109   //   incomplete type other than a class currently being defined [...].
110   //   A type denoted in an exception-specification shall not denote a
111   //   pointer or reference to an incomplete type, other than (cv) void* or a
112   //   pointer or reference to a class currently being defined.
113   if (!(PointeeT->isRecordType() &&
114         PointeeT->getAs<RecordType>()->isBeingDefined()) &&
115       RequireCompleteType(Range.getBegin(), PointeeT,
116                           diag::err_incomplete_in_exception_spec, Kind, Range))
117     return true;
118 
119   return false;
120 }
121 
122 /// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer
123 /// to member to a function with an exception specification. This means that
124 /// it is invalid to add another level of indirection.
125 bool Sema::CheckDistantExceptionSpec(QualType T) {
126   if (const PointerType *PT = T->getAs<PointerType>())
127     T = PT->getPointeeType();
128   else if (const MemberPointerType *PT = T->getAs<MemberPointerType>())
129     T = PT->getPointeeType();
130   else
131     return false;
132 
133   const FunctionProtoType *FnT = T->getAs<FunctionProtoType>();
134   if (!FnT)
135     return false;
136 
137   return FnT->hasExceptionSpec();
138 }
139 
140 const FunctionProtoType *
141 Sema::ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT) {
142   if (FPT->getExceptionSpecType() == EST_Unparsed) {
143     Diag(Loc, diag::err_exception_spec_not_parsed);
144     return nullptr;
145   }
146 
147   if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
148     return FPT;
149 
150   FunctionDecl *SourceDecl = FPT->getExceptionSpecDecl();
151   const FunctionProtoType *SourceFPT =
152       SourceDecl->getType()->castAs<FunctionProtoType>();
153 
154   // If the exception specification has already been resolved, just return it.
155   if (!isUnresolvedExceptionSpec(SourceFPT->getExceptionSpecType()))
156     return SourceFPT;
157 
158   // Compute or instantiate the exception specification now.
159   if (SourceFPT->getExceptionSpecType() == EST_Unevaluated)
160     EvaluateImplicitExceptionSpec(Loc, cast<CXXMethodDecl>(SourceDecl));
161   else
162     InstantiateExceptionSpec(Loc, SourceDecl);
163 
164   const FunctionProtoType *Proto =
165     SourceDecl->getType()->castAs<FunctionProtoType>();
166   if (Proto->getExceptionSpecType() == clang::EST_Unparsed) {
167     Diag(Loc, diag::err_exception_spec_not_parsed);
168     Proto = nullptr;
169   }
170   return Proto;
171 }
172 
173 void
174 Sema::UpdateExceptionSpec(FunctionDecl *FD,
175                           const FunctionProtoType::ExceptionSpecInfo &ESI) {
176   // If we've fully resolved the exception specification, notify listeners.
177   if (!isUnresolvedExceptionSpec(ESI.Type))
178     if (auto *Listener = getASTMutationListener())
179       Listener->ResolvedExceptionSpec(FD);
180 
181   for (auto *Redecl : FD->redecls())
182     Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
183 }
184 
185 /// Determine whether a function has an implicitly-generated exception
186 /// specification.
187 static bool hasImplicitExceptionSpec(FunctionDecl *Decl) {
188   if (!isa<CXXDestructorDecl>(Decl) &&
189       Decl->getDeclName().getCXXOverloadedOperator() != OO_Delete &&
190       Decl->getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
191     return false;
192 
193   // For a function that the user didn't declare:
194   //  - if this is a destructor, its exception specification is implicit.
195   //  - if this is 'operator delete' or 'operator delete[]', the exception
196   //    specification is as-if an explicit exception specification was given
197   //    (per [basic.stc.dynamic]p2).
198   if (!Decl->getTypeSourceInfo())
199     return isa<CXXDestructorDecl>(Decl);
200 
201   const FunctionProtoType *Ty =
202     Decl->getTypeSourceInfo()->getType()->getAs<FunctionProtoType>();
203   return !Ty->hasExceptionSpec();
204 }
205 
206 bool Sema::CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New) {
207   OverloadedOperatorKind OO = New->getDeclName().getCXXOverloadedOperator();
208   bool IsOperatorNew = OO == OO_New || OO == OO_Array_New;
209   bool MissingExceptionSpecification = false;
210   bool MissingEmptyExceptionSpecification = false;
211 
212   unsigned DiagID = diag::err_mismatched_exception_spec;
213   bool ReturnValueOnError = true;
214   if (getLangOpts().MicrosoftExt) {
215     DiagID = diag::ext_mismatched_exception_spec;
216     ReturnValueOnError = false;
217   }
218 
219   // Check the types as written: they must match before any exception
220   // specification adjustment is applied.
221   if (!CheckEquivalentExceptionSpec(
222         PDiag(DiagID), PDiag(diag::note_previous_declaration),
223         Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
224         New->getType()->getAs<FunctionProtoType>(), New->getLocation(),
225         &MissingExceptionSpecification, &MissingEmptyExceptionSpecification,
226         /*AllowNoexceptAllMatchWithNoSpec=*/true, IsOperatorNew)) {
227     // C++11 [except.spec]p4 [DR1492]:
228     //   If a declaration of a function has an implicit
229     //   exception-specification, other declarations of the function shall
230     //   not specify an exception-specification.
231     if (getLangOpts().CPlusPlus11 &&
232         hasImplicitExceptionSpec(Old) != hasImplicitExceptionSpec(New)) {
233       Diag(New->getLocation(), diag::ext_implicit_exception_spec_mismatch)
234         << hasImplicitExceptionSpec(Old);
235       if (!Old->getLocation().isInvalid())
236         Diag(Old->getLocation(), diag::note_previous_declaration);
237     }
238     return false;
239   }
240 
241   // The failure was something other than an missing exception
242   // specification; return an error, except in MS mode where this is a warning.
243   if (!MissingExceptionSpecification)
244     return ReturnValueOnError;
245 
246   const FunctionProtoType *NewProto =
247     New->getType()->castAs<FunctionProtoType>();
248 
249   // The new function declaration is only missing an empty exception
250   // specification "throw()". If the throw() specification came from a
251   // function in a system header that has C linkage, just add an empty
252   // exception specification to the "new" declaration. This is an
253   // egregious workaround for glibc, which adds throw() specifications
254   // to many libc functions as an optimization. Unfortunately, that
255   // optimization isn't permitted by the C++ standard, so we're forced
256   // to work around it here.
257   if (MissingEmptyExceptionSpecification && NewProto &&
258       (Old->getLocation().isInvalid() ||
259        Context.getSourceManager().isInSystemHeader(Old->getLocation())) &&
260       Old->isExternC()) {
261     New->setType(Context.getFunctionType(
262         NewProto->getReturnType(), NewProto->getParamTypes(),
263         NewProto->getExtProtoInfo().withExceptionSpec(EST_DynamicNone)));
264     return false;
265   }
266 
267   const FunctionProtoType *OldProto =
268     Old->getType()->castAs<FunctionProtoType>();
269 
270   FunctionProtoType::ExceptionSpecInfo ESI = OldProto->getExceptionSpecType();
271   if (ESI.Type == EST_Dynamic) {
272     ESI.Exceptions = OldProto->exceptions();
273   }
274 
275   if (ESI.Type == EST_ComputedNoexcept) {
276     // For computed noexcept, we can't just take the expression from the old
277     // prototype. It likely contains references to the old prototype's
278     // parameters.
279     New->setInvalidDecl();
280   } else {
281     // Update the type of the function with the appropriate exception
282     // specification.
283     New->setType(Context.getFunctionType(
284         NewProto->getReturnType(), NewProto->getParamTypes(),
285         NewProto->getExtProtoInfo().withExceptionSpec(ESI)));
286   }
287 
288   // Allow missing exception specifications in redeclarations as an extension,
289   // when declaring a replaceable global allocation function.
290   if (New->isReplaceableGlobalAllocationFunction() &&
291       ESI.Type != EST_ComputedNoexcept) {
292     DiagID = diag::ext_missing_exception_specification;
293     ReturnValueOnError = false;
294   } else {
295     DiagID = diag::err_missing_exception_specification;
296     ReturnValueOnError = true;
297   }
298 
299   // Warn about the lack of exception specification.
300   SmallString<128> ExceptionSpecString;
301   llvm::raw_svector_ostream OS(ExceptionSpecString);
302   switch (OldProto->getExceptionSpecType()) {
303   case EST_DynamicNone:
304     OS << "throw()";
305     break;
306 
307   case EST_Dynamic: {
308     OS << "throw(";
309     bool OnFirstException = true;
310     for (const auto &E : OldProto->exceptions()) {
311       if (OnFirstException)
312         OnFirstException = false;
313       else
314         OS << ", ";
315 
316       OS << E.getAsString(getPrintingPolicy());
317     }
318     OS << ")";
319     break;
320   }
321 
322   case EST_BasicNoexcept:
323     OS << "noexcept";
324     break;
325 
326   case EST_ComputedNoexcept:
327     OS << "noexcept(";
328     assert(OldProto->getNoexceptExpr() != nullptr && "Expected non-null Expr");
329     OldProto->getNoexceptExpr()->printPretty(OS, nullptr, getPrintingPolicy());
330     OS << ")";
331     break;
332 
333   default:
334     llvm_unreachable("This spec type is compatible with none.");
335   }
336 
337   SourceLocation FixItLoc;
338   if (TypeSourceInfo *TSInfo = New->getTypeSourceInfo()) {
339     TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
340     // FIXME: Preserve enough information so that we can produce a correct fixit
341     // location when there is a trailing return type.
342     if (auto FTLoc = TL.getAs<FunctionProtoTypeLoc>())
343       if (!FTLoc.getTypePtr()->hasTrailingReturn())
344         FixItLoc = getLocForEndOfToken(FTLoc.getLocalRangeEnd());
345   }
346 
347   if (FixItLoc.isInvalid())
348     Diag(New->getLocation(), DiagID)
349       << New << OS.str();
350   else {
351     Diag(New->getLocation(), DiagID)
352       << New << OS.str()
353       << FixItHint::CreateInsertion(FixItLoc, " " + OS.str().str());
354   }
355 
356   if (!Old->getLocation().isInvalid())
357     Diag(Old->getLocation(), diag::note_previous_declaration);
358 
359   return ReturnValueOnError;
360 }
361 
362 /// CheckEquivalentExceptionSpec - Check if the two types have equivalent
363 /// exception specifications. Exception specifications are equivalent if
364 /// they allow exactly the same set of exception types. It does not matter how
365 /// that is achieved. See C++ [except.spec]p2.
366 bool Sema::CheckEquivalentExceptionSpec(
367     const FunctionProtoType *Old, SourceLocation OldLoc,
368     const FunctionProtoType *New, SourceLocation NewLoc) {
369   unsigned DiagID = diag::err_mismatched_exception_spec;
370   if (getLangOpts().MicrosoftExt)
371     DiagID = diag::ext_mismatched_exception_spec;
372   bool Result = CheckEquivalentExceptionSpec(PDiag(DiagID),
373       PDiag(diag::note_previous_declaration), Old, OldLoc, New, NewLoc);
374 
375   // In Microsoft mode, mismatching exception specifications just cause a warning.
376   if (getLangOpts().MicrosoftExt)
377     return false;
378   return Result;
379 }
380 
381 /// CheckEquivalentExceptionSpec - Check if the two types have compatible
382 /// exception specifications. See C++ [except.spec]p3.
383 ///
384 /// \return \c false if the exception specifications match, \c true if there is
385 /// a problem. If \c true is returned, either a diagnostic has already been
386 /// produced or \c *MissingExceptionSpecification is set to \c true.
387 bool Sema::CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
388                                         const PartialDiagnostic & NoteID,
389                                         const FunctionProtoType *Old,
390                                         SourceLocation OldLoc,
391                                         const FunctionProtoType *New,
392                                         SourceLocation NewLoc,
393                                         bool *MissingExceptionSpecification,
394                                         bool*MissingEmptyExceptionSpecification,
395                                         bool AllowNoexceptAllMatchWithNoSpec,
396                                         bool IsOperatorNew) {
397   // Just completely ignore this under -fno-exceptions.
398   if (!getLangOpts().CXXExceptions)
399     return false;
400 
401   if (MissingExceptionSpecification)
402     *MissingExceptionSpecification = false;
403 
404   if (MissingEmptyExceptionSpecification)
405     *MissingEmptyExceptionSpecification = false;
406 
407   Old = ResolveExceptionSpec(NewLoc, Old);
408   if (!Old)
409     return false;
410   New = ResolveExceptionSpec(NewLoc, New);
411   if (!New)
412     return false;
413 
414   // C++0x [except.spec]p3: Two exception-specifications are compatible if:
415   //   - both are non-throwing, regardless of their form,
416   //   - both have the form noexcept(constant-expression) and the constant-
417   //     expressions are equivalent,
418   //   - both are dynamic-exception-specifications that have the same set of
419   //     adjusted types.
420   //
421   // C++0x [except.spec]p12: An exception-specification is non-throwing if it is
422   //   of the form throw(), noexcept, or noexcept(constant-expression) where the
423   //   constant-expression yields true.
424   //
425   // C++0x [except.spec]p4: If any declaration of a function has an exception-
426   //   specifier that is not a noexcept-specification allowing all exceptions,
427   //   all declarations [...] of that function shall have a compatible
428   //   exception-specification.
429   //
430   // That last point basically means that noexcept(false) matches no spec.
431   // It's considered when AllowNoexceptAllMatchWithNoSpec is true.
432 
433   ExceptionSpecificationType OldEST = Old->getExceptionSpecType();
434   ExceptionSpecificationType NewEST = New->getExceptionSpecType();
435 
436   assert(!isUnresolvedExceptionSpec(OldEST) &&
437          !isUnresolvedExceptionSpec(NewEST) &&
438          "Shouldn't see unknown exception specifications here");
439 
440   // Shortcut the case where both have no spec.
441   if (OldEST == EST_None && NewEST == EST_None)
442     return false;
443 
444   FunctionProtoType::NoexceptResult OldNR = Old->getNoexceptSpec(Context);
445   FunctionProtoType::NoexceptResult NewNR = New->getNoexceptSpec(Context);
446   if (OldNR == FunctionProtoType::NR_BadNoexcept ||
447       NewNR == FunctionProtoType::NR_BadNoexcept)
448     return false;
449 
450   // Dependent noexcept specifiers are compatible with each other, but nothing
451   // else.
452   // One noexcept is compatible with another if the argument is the same
453   if (OldNR == NewNR &&
454       OldNR != FunctionProtoType::NR_NoNoexcept &&
455       NewNR != FunctionProtoType::NR_NoNoexcept)
456     return false;
457   if (OldNR != NewNR &&
458       OldNR != FunctionProtoType::NR_NoNoexcept &&
459       NewNR != FunctionProtoType::NR_NoNoexcept) {
460     Diag(NewLoc, DiagID);
461     if (NoteID.getDiagID() != 0 && OldLoc.isValid())
462       Diag(OldLoc, NoteID);
463     return true;
464   }
465 
466   // The MS extension throw(...) is compatible with itself.
467   if (OldEST == EST_MSAny && NewEST == EST_MSAny)
468     return false;
469 
470   // It's also compatible with no spec.
471   if ((OldEST == EST_None && NewEST == EST_MSAny) ||
472       (OldEST == EST_MSAny && NewEST == EST_None))
473     return false;
474 
475   // It's also compatible with noexcept(false).
476   if (OldEST == EST_MSAny && NewNR == FunctionProtoType::NR_Throw)
477     return false;
478   if (NewEST == EST_MSAny && OldNR == FunctionProtoType::NR_Throw)
479     return false;
480 
481   // As described above, noexcept(false) matches no spec only for functions.
482   if (AllowNoexceptAllMatchWithNoSpec) {
483     if (OldEST == EST_None && NewNR == FunctionProtoType::NR_Throw)
484       return false;
485     if (NewEST == EST_None && OldNR == FunctionProtoType::NR_Throw)
486       return false;
487   }
488 
489   // Any non-throwing specifications are compatible.
490   bool OldNonThrowing = OldNR == FunctionProtoType::NR_Nothrow ||
491                         OldEST == EST_DynamicNone;
492   bool NewNonThrowing = NewNR == FunctionProtoType::NR_Nothrow ||
493                         NewEST == EST_DynamicNone;
494   if (OldNonThrowing && NewNonThrowing)
495     return false;
496 
497   // As a special compatibility feature, under C++0x we accept no spec and
498   // throw(std::bad_alloc) as equivalent for operator new and operator new[].
499   // This is because the implicit declaration changed, but old code would break.
500   if (getLangOpts().CPlusPlus11 && IsOperatorNew) {
501     const FunctionProtoType *WithExceptions = nullptr;
502     if (OldEST == EST_None && NewEST == EST_Dynamic)
503       WithExceptions = New;
504     else if (OldEST == EST_Dynamic && NewEST == EST_None)
505       WithExceptions = Old;
506     if (WithExceptions && WithExceptions->getNumExceptions() == 1) {
507       // One has no spec, the other throw(something). If that something is
508       // std::bad_alloc, all conditions are met.
509       QualType Exception = *WithExceptions->exception_begin();
510       if (CXXRecordDecl *ExRecord = Exception->getAsCXXRecordDecl()) {
511         IdentifierInfo* Name = ExRecord->getIdentifier();
512         if (Name && Name->getName() == "bad_alloc") {
513           // It's called bad_alloc, but is it in std?
514           if (ExRecord->isInStdNamespace()) {
515             return false;
516           }
517         }
518       }
519     }
520   }
521 
522   // At this point, the only remaining valid case is two matching dynamic
523   // specifications. We return here unless both specifications are dynamic.
524   if (OldEST != EST_Dynamic || NewEST != EST_Dynamic) {
525     if (MissingExceptionSpecification && Old->hasExceptionSpec() &&
526         !New->hasExceptionSpec()) {
527       // The old type has an exception specification of some sort, but
528       // the new type does not.
529       *MissingExceptionSpecification = true;
530 
531       if (MissingEmptyExceptionSpecification && OldNonThrowing) {
532         // The old type has a throw() or noexcept(true) exception specification
533         // and the new type has no exception specification, and the caller asked
534         // to handle this itself.
535         *MissingEmptyExceptionSpecification = true;
536       }
537 
538       return true;
539     }
540 
541     Diag(NewLoc, DiagID);
542     if (NoteID.getDiagID() != 0 && OldLoc.isValid())
543       Diag(OldLoc, NoteID);
544     return true;
545   }
546 
547   assert(OldEST == EST_Dynamic && NewEST == EST_Dynamic &&
548       "Exception compatibility logic error: non-dynamic spec slipped through.");
549 
550   bool Success = true;
551   // Both have a dynamic exception spec. Collect the first set, then compare
552   // to the second.
553   llvm::SmallPtrSet<CanQualType, 8> OldTypes, NewTypes;
554   for (const auto &I : Old->exceptions())
555     OldTypes.insert(Context.getCanonicalType(I).getUnqualifiedType());
556 
557   for (const auto &I : New->exceptions()) {
558     CanQualType TypePtr = Context.getCanonicalType(I).getUnqualifiedType();
559     if(OldTypes.count(TypePtr))
560       NewTypes.insert(TypePtr);
561     else
562       Success = false;
563   }
564 
565   Success = Success && OldTypes.size() == NewTypes.size();
566 
567   if (Success) {
568     return false;
569   }
570   Diag(NewLoc, DiagID);
571   if (NoteID.getDiagID() != 0 && OldLoc.isValid())
572     Diag(OldLoc, NoteID);
573   return true;
574 }
575 
576 /// CheckExceptionSpecSubset - Check whether the second function type's
577 /// exception specification is a subset (or equivalent) of the first function
578 /// type. This is used by override and pointer assignment checks.
579 bool Sema::CheckExceptionSpecSubset(
580     const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
581     const FunctionProtoType *Superset, SourceLocation SuperLoc,
582     const FunctionProtoType *Subset, SourceLocation SubLoc) {
583 
584   // Just auto-succeed under -fno-exceptions.
585   if (!getLangOpts().CXXExceptions)
586     return false;
587 
588   // FIXME: As usual, we could be more specific in our error messages, but
589   // that better waits until we've got types with source locations.
590 
591   if (!SubLoc.isValid())
592     SubLoc = SuperLoc;
593 
594   // Resolve the exception specifications, if needed.
595   Superset = ResolveExceptionSpec(SuperLoc, Superset);
596   if (!Superset)
597     return false;
598   Subset = ResolveExceptionSpec(SubLoc, Subset);
599   if (!Subset)
600     return false;
601 
602   ExceptionSpecificationType SuperEST = Superset->getExceptionSpecType();
603 
604   // If superset contains everything, we're done.
605   if (SuperEST == EST_None || SuperEST == EST_MSAny)
606     return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
607 
608   // If there are dependent noexcept specs, assume everything is fine. Unlike
609   // with the equivalency check, this is safe in this case, because we don't
610   // want to merge declarations. Checks after instantiation will catch any
611   // omissions we make here.
612   // We also shortcut checking if a noexcept expression was bad.
613 
614   FunctionProtoType::NoexceptResult SuperNR =Superset->getNoexceptSpec(Context);
615   if (SuperNR == FunctionProtoType::NR_BadNoexcept ||
616       SuperNR == FunctionProtoType::NR_Dependent)
617     return false;
618 
619   // Another case of the superset containing everything.
620   if (SuperNR == FunctionProtoType::NR_Throw)
621     return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
622 
623   ExceptionSpecificationType SubEST = Subset->getExceptionSpecType();
624 
625   assert(!isUnresolvedExceptionSpec(SuperEST) &&
626          !isUnresolvedExceptionSpec(SubEST) &&
627          "Shouldn't see unknown exception specifications here");
628 
629   // It does not. If the subset contains everything, we've failed.
630   if (SubEST == EST_None || SubEST == EST_MSAny) {
631     Diag(SubLoc, DiagID);
632     if (NoteID.getDiagID() != 0)
633       Diag(SuperLoc, NoteID);
634     return true;
635   }
636 
637   FunctionProtoType::NoexceptResult SubNR = Subset->getNoexceptSpec(Context);
638   if (SubNR == FunctionProtoType::NR_BadNoexcept ||
639       SubNR == FunctionProtoType::NR_Dependent)
640     return false;
641 
642   // Another case of the subset containing everything.
643   if (SubNR == FunctionProtoType::NR_Throw) {
644     Diag(SubLoc, DiagID);
645     if (NoteID.getDiagID() != 0)
646       Diag(SuperLoc, NoteID);
647     return true;
648   }
649 
650   // If the subset contains nothing, we're done.
651   if (SubEST == EST_DynamicNone || SubNR == FunctionProtoType::NR_Nothrow)
652     return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
653 
654   // Otherwise, if the superset contains nothing, we've failed.
655   if (SuperEST == EST_DynamicNone || SuperNR == FunctionProtoType::NR_Nothrow) {
656     Diag(SubLoc, DiagID);
657     if (NoteID.getDiagID() != 0)
658       Diag(SuperLoc, NoteID);
659     return true;
660   }
661 
662   assert(SuperEST == EST_Dynamic && SubEST == EST_Dynamic &&
663          "Exception spec subset: non-dynamic case slipped through.");
664 
665   // Neither contains everything or nothing. Do a proper comparison.
666   for (const auto &SubI : Subset->exceptions()) {
667     // Take one type from the subset.
668     QualType CanonicalSubT = Context.getCanonicalType(SubI);
669     // Unwrap pointers and references so that we can do checks within a class
670     // hierarchy. Don't unwrap member pointers; they don't have hierarchy
671     // conversions on the pointee.
672     bool SubIsPointer = false;
673     if (const ReferenceType *RefTy = CanonicalSubT->getAs<ReferenceType>())
674       CanonicalSubT = RefTy->getPointeeType();
675     if (const PointerType *PtrTy = CanonicalSubT->getAs<PointerType>()) {
676       CanonicalSubT = PtrTy->getPointeeType();
677       SubIsPointer = true;
678     }
679     bool SubIsClass = CanonicalSubT->isRecordType();
680     CanonicalSubT = CanonicalSubT.getLocalUnqualifiedType();
681 
682     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
683                        /*DetectVirtual=*/false);
684 
685     bool Contained = false;
686     // Make sure it's in the superset.
687     for (const auto &SuperI : Superset->exceptions()) {
688       QualType CanonicalSuperT = Context.getCanonicalType(SuperI);
689       // SubT must be SuperT or derived from it, or pointer or reference to
690       // such types.
691       if (const ReferenceType *RefTy = CanonicalSuperT->getAs<ReferenceType>())
692         CanonicalSuperT = RefTy->getPointeeType();
693       if (SubIsPointer) {
694         if (const PointerType *PtrTy = CanonicalSuperT->getAs<PointerType>())
695           CanonicalSuperT = PtrTy->getPointeeType();
696         else {
697           continue;
698         }
699       }
700       CanonicalSuperT = CanonicalSuperT.getLocalUnqualifiedType();
701       // If the types are the same, move on to the next type in the subset.
702       if (CanonicalSubT == CanonicalSuperT) {
703         Contained = true;
704         break;
705       }
706 
707       // Otherwise we need to check the inheritance.
708       if (!SubIsClass || !CanonicalSuperT->isRecordType())
709         continue;
710 
711       Paths.clear();
712       if (!IsDerivedFrom(CanonicalSubT, CanonicalSuperT, Paths))
713         continue;
714 
715       if (Paths.isAmbiguous(Context.getCanonicalType(CanonicalSuperT)))
716         continue;
717 
718       // Do this check from a context without privileges.
719       switch (CheckBaseClassAccess(SourceLocation(),
720                                    CanonicalSuperT, CanonicalSubT,
721                                    Paths.front(),
722                                    /*Diagnostic*/ 0,
723                                    /*ForceCheck*/ true,
724                                    /*ForceUnprivileged*/ true)) {
725       case AR_accessible: break;
726       case AR_inaccessible: continue;
727       case AR_dependent:
728         llvm_unreachable("access check dependent for unprivileged context");
729       case AR_delayed:
730         llvm_unreachable("access check delayed in non-declaration");
731       }
732 
733       Contained = true;
734       break;
735     }
736     if (!Contained) {
737       Diag(SubLoc, DiagID);
738       if (NoteID.getDiagID() != 0)
739         Diag(SuperLoc, NoteID);
740       return true;
741     }
742   }
743   // We've run half the gauntlet.
744   return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
745 }
746 
747 static bool CheckSpecForTypesEquivalent(Sema &S,
748     const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
749     QualType Target, SourceLocation TargetLoc,
750     QualType Source, SourceLocation SourceLoc)
751 {
752   const FunctionProtoType *TFunc = GetUnderlyingFunction(Target);
753   if (!TFunc)
754     return false;
755   const FunctionProtoType *SFunc = GetUnderlyingFunction(Source);
756   if (!SFunc)
757     return false;
758 
759   return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc,
760                                         SFunc, SourceLoc);
761 }
762 
763 /// CheckParamExceptionSpec - Check if the parameter and return types of the
764 /// two functions have equivalent exception specs. This is part of the
765 /// assignment and override compatibility check. We do not check the parameters
766 /// of parameter function pointers recursively, as no sane programmer would
767 /// even be able to write such a function type.
768 bool Sema::CheckParamExceptionSpec(const PartialDiagnostic &NoteID,
769                                    const FunctionProtoType *Target,
770                                    SourceLocation TargetLoc,
771                                    const FunctionProtoType *Source,
772                                    SourceLocation SourceLoc) {
773   if (CheckSpecForTypesEquivalent(
774           *this, PDiag(diag::err_deep_exception_specs_differ) << 0, PDiag(),
775           Target->getReturnType(), TargetLoc, Source->getReturnType(),
776           SourceLoc))
777     return true;
778 
779   // We shouldn't even be testing this unless the arguments are otherwise
780   // compatible.
781   assert(Target->getNumParams() == Source->getNumParams() &&
782          "Functions have different argument counts.");
783   for (unsigned i = 0, E = Target->getNumParams(); i != E; ++i) {
784     if (CheckSpecForTypesEquivalent(
785             *this, PDiag(diag::err_deep_exception_specs_differ) << 1, PDiag(),
786             Target->getParamType(i), TargetLoc, Source->getParamType(i),
787             SourceLoc))
788       return true;
789   }
790   return false;
791 }
792 
793 bool Sema::CheckExceptionSpecCompatibility(Expr *From, QualType ToType) {
794   // First we check for applicability.
795   // Target type must be a function, function pointer or function reference.
796   const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType);
797   if (!ToFunc || ToFunc->hasDependentExceptionSpec())
798     return false;
799 
800   // SourceType must be a function or function pointer.
801   const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType());
802   if (!FromFunc || FromFunc->hasDependentExceptionSpec())
803     return false;
804 
805   // Now we've got the correct types on both sides, check their compatibility.
806   // This means that the source of the conversion can only throw a subset of
807   // the exceptions of the target, and any exception specs on arguments or
808   // return types must be equivalent.
809   //
810   // FIXME: If there is a nested dependent exception specification, we should
811   // not be checking it here. This is fine:
812   //   template<typename T> void f() {
813   //     void (*p)(void (*) throw(T));
814   //     void (*q)(void (*) throw(int)) = p;
815   //   }
816   // ... because it might be instantiated with T=int.
817   return CheckExceptionSpecSubset(PDiag(diag::err_incompatible_exception_specs),
818                                   PDiag(), ToFunc,
819                                   From->getSourceRange().getBegin(),
820                                   FromFunc, SourceLocation());
821 }
822 
823 bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
824                                                 const CXXMethodDecl *Old) {
825   // If the new exception specification hasn't been parsed yet, skip the check.
826   // We'll get called again once it's been parsed.
827   if (New->getType()->castAs<FunctionProtoType>()->getExceptionSpecType() ==
828       EST_Unparsed)
829     return false;
830   if (getLangOpts().CPlusPlus11 && isa<CXXDestructorDecl>(New)) {
831     // Don't check uninstantiated template destructors at all. We can only
832     // synthesize correct specs after the template is instantiated.
833     if (New->getParent()->isDependentType())
834       return false;
835     if (New->getParent()->isBeingDefined()) {
836       // The destructor might be updated once the definition is finished. So
837       // remember it and check later.
838       DelayedExceptionSpecChecks.push_back(std::make_pair(New, Old));
839       return false;
840     }
841   }
842   // If the old exception specification hasn't been parsed yet, remember that
843   // we need to perform this check when we get to the end of the outermost
844   // lexically-surrounding class.
845   if (Old->getType()->castAs<FunctionProtoType>()->getExceptionSpecType() ==
846       EST_Unparsed) {
847     DelayedExceptionSpecChecks.push_back(std::make_pair(New, Old));
848     return false;
849   }
850   unsigned DiagID = diag::err_override_exception_spec;
851   if (getLangOpts().MicrosoftExt)
852     DiagID = diag::ext_override_exception_spec;
853   return CheckExceptionSpecSubset(PDiag(DiagID),
854                                   PDiag(diag::note_overridden_virtual_function),
855                                   Old->getType()->getAs<FunctionProtoType>(),
856                                   Old->getLocation(),
857                                   New->getType()->getAs<FunctionProtoType>(),
858                                   New->getLocation());
859 }
860 
861 static CanThrowResult canSubExprsThrow(Sema &S, const Expr *E) {
862   CanThrowResult R = CT_Cannot;
863   for (const Stmt *SubStmt : E->children()) {
864     R = mergeCanThrow(R, S.canThrow(cast<Expr>(SubStmt)));
865     if (R == CT_Can)
866       break;
867   }
868   return R;
869 }
870 
871 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D) {
872   assert(D && "Expected decl");
873 
874   // See if we can get a function type from the decl somehow.
875   const ValueDecl *VD = dyn_cast<ValueDecl>(D);
876   if (!VD) // If we have no clue what we're calling, assume the worst.
877     return CT_Can;
878 
879   // As an extension, we assume that __attribute__((nothrow)) functions don't
880   // throw.
881   if (isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())
882     return CT_Cannot;
883 
884   QualType T = VD->getType();
885   const FunctionProtoType *FT;
886   if ((FT = T->getAs<FunctionProtoType>())) {
887   } else if (const PointerType *PT = T->getAs<PointerType>())
888     FT = PT->getPointeeType()->getAs<FunctionProtoType>();
889   else if (const ReferenceType *RT = T->getAs<ReferenceType>())
890     FT = RT->getPointeeType()->getAs<FunctionProtoType>();
891   else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
892     FT = MT->getPointeeType()->getAs<FunctionProtoType>();
893   else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
894     FT = BT->getPointeeType()->getAs<FunctionProtoType>();
895 
896   if (!FT)
897     return CT_Can;
898 
899   FT = S.ResolveExceptionSpec(E->getLocStart(), FT);
900   if (!FT)
901     return CT_Can;
902 
903   return FT->isNothrow(S.Context) ? CT_Cannot : CT_Can;
904 }
905 
906 static CanThrowResult canDynamicCastThrow(const CXXDynamicCastExpr *DC) {
907   if (DC->isTypeDependent())
908     return CT_Dependent;
909 
910   if (!DC->getTypeAsWritten()->isReferenceType())
911     return CT_Cannot;
912 
913   if (DC->getSubExpr()->isTypeDependent())
914     return CT_Dependent;
915 
916   return DC->getCastKind() == clang::CK_Dynamic? CT_Can : CT_Cannot;
917 }
918 
919 static CanThrowResult canTypeidThrow(Sema &S, const CXXTypeidExpr *DC) {
920   if (DC->isTypeOperand())
921     return CT_Cannot;
922 
923   Expr *Op = DC->getExprOperand();
924   if (Op->isTypeDependent())
925     return CT_Dependent;
926 
927   const RecordType *RT = Op->getType()->getAs<RecordType>();
928   if (!RT)
929     return CT_Cannot;
930 
931   if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
932     return CT_Cannot;
933 
934   if (Op->Classify(S.Context).isPRValue())
935     return CT_Cannot;
936 
937   return CT_Can;
938 }
939 
940 CanThrowResult Sema::canThrow(const Expr *E) {
941   // C++ [expr.unary.noexcept]p3:
942   //   [Can throw] if in a potentially-evaluated context the expression would
943   //   contain:
944   switch (E->getStmtClass()) {
945   case Expr::CXXThrowExprClass:
946     //   - a potentially evaluated throw-expression
947     return CT_Can;
948 
949   case Expr::CXXDynamicCastExprClass: {
950     //   - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
951     //     where T is a reference type, that requires a run-time check
952     CanThrowResult CT = canDynamicCastThrow(cast<CXXDynamicCastExpr>(E));
953     if (CT == CT_Can)
954       return CT;
955     return mergeCanThrow(CT, canSubExprsThrow(*this, E));
956   }
957 
958   case Expr::CXXTypeidExprClass:
959     //   - a potentially evaluated typeid expression applied to a glvalue
960     //     expression whose type is a polymorphic class type
961     return canTypeidThrow(*this, cast<CXXTypeidExpr>(E));
962 
963     //   - a potentially evaluated call to a function, member function, function
964     //     pointer, or member function pointer that does not have a non-throwing
965     //     exception-specification
966   case Expr::CallExprClass:
967   case Expr::CXXMemberCallExprClass:
968   case Expr::CXXOperatorCallExprClass:
969   case Expr::UserDefinedLiteralClass: {
970     const CallExpr *CE = cast<CallExpr>(E);
971     CanThrowResult CT;
972     if (E->isTypeDependent())
973       CT = CT_Dependent;
974     else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens()))
975       CT = CT_Cannot;
976     else if (CE->getCalleeDecl())
977       CT = canCalleeThrow(*this, E, CE->getCalleeDecl());
978     else
979       CT = CT_Can;
980     if (CT == CT_Can)
981       return CT;
982     return mergeCanThrow(CT, canSubExprsThrow(*this, E));
983   }
984 
985   case Expr::CXXConstructExprClass:
986   case Expr::CXXTemporaryObjectExprClass: {
987     CanThrowResult CT = canCalleeThrow(*this, E,
988         cast<CXXConstructExpr>(E)->getConstructor());
989     if (CT == CT_Can)
990       return CT;
991     return mergeCanThrow(CT, canSubExprsThrow(*this, E));
992   }
993 
994   case Expr::LambdaExprClass: {
995     const LambdaExpr *Lambda = cast<LambdaExpr>(E);
996     CanThrowResult CT = CT_Cannot;
997     for (LambdaExpr::const_capture_init_iterator
998              Cap = Lambda->capture_init_begin(),
999              CapEnd = Lambda->capture_init_end();
1000          Cap != CapEnd; ++Cap)
1001       CT = mergeCanThrow(CT, canThrow(*Cap));
1002     return CT;
1003   }
1004 
1005   case Expr::CXXNewExprClass: {
1006     CanThrowResult CT;
1007     if (E->isTypeDependent())
1008       CT = CT_Dependent;
1009     else
1010       CT = canCalleeThrow(*this, E, cast<CXXNewExpr>(E)->getOperatorNew());
1011     if (CT == CT_Can)
1012       return CT;
1013     return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1014   }
1015 
1016   case Expr::CXXDeleteExprClass: {
1017     CanThrowResult CT;
1018     QualType DTy = cast<CXXDeleteExpr>(E)->getDestroyedType();
1019     if (DTy.isNull() || DTy->isDependentType()) {
1020       CT = CT_Dependent;
1021     } else {
1022       CT = canCalleeThrow(*this, E,
1023                           cast<CXXDeleteExpr>(E)->getOperatorDelete());
1024       if (const RecordType *RT = DTy->getAs<RecordType>()) {
1025         const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1026         const CXXDestructorDecl *DD = RD->getDestructor();
1027         if (DD)
1028           CT = mergeCanThrow(CT, canCalleeThrow(*this, E, DD));
1029       }
1030       if (CT == CT_Can)
1031         return CT;
1032     }
1033     return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1034   }
1035 
1036   case Expr::CXXBindTemporaryExprClass: {
1037     // The bound temporary has to be destroyed again, which might throw.
1038     CanThrowResult CT = canCalleeThrow(*this, E,
1039       cast<CXXBindTemporaryExpr>(E)->getTemporary()->getDestructor());
1040     if (CT == CT_Can)
1041       return CT;
1042     return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1043   }
1044 
1045     // ObjC message sends are like function calls, but never have exception
1046     // specs.
1047   case Expr::ObjCMessageExprClass:
1048   case Expr::ObjCPropertyRefExprClass:
1049   case Expr::ObjCSubscriptRefExprClass:
1050     return CT_Can;
1051 
1052     // All the ObjC literals that are implemented as calls are
1053     // potentially throwing unless we decide to close off that
1054     // possibility.
1055   case Expr::ObjCArrayLiteralClass:
1056   case Expr::ObjCDictionaryLiteralClass:
1057   case Expr::ObjCBoxedExprClass:
1058     return CT_Can;
1059 
1060     // Many other things have subexpressions, so we have to test those.
1061     // Some are simple:
1062   case Expr::ConditionalOperatorClass:
1063   case Expr::CompoundLiteralExprClass:
1064   case Expr::CXXConstCastExprClass:
1065   case Expr::CXXReinterpretCastExprClass:
1066   case Expr::CXXStdInitializerListExprClass:
1067   case Expr::DesignatedInitExprClass:
1068   case Expr::DesignatedInitUpdateExprClass:
1069   case Expr::ExprWithCleanupsClass:
1070   case Expr::ExtVectorElementExprClass:
1071   case Expr::InitListExprClass:
1072   case Expr::MemberExprClass:
1073   case Expr::ObjCIsaExprClass:
1074   case Expr::ObjCIvarRefExprClass:
1075   case Expr::ParenExprClass:
1076   case Expr::ParenListExprClass:
1077   case Expr::ShuffleVectorExprClass:
1078   case Expr::ConvertVectorExprClass:
1079   case Expr::VAArgExprClass:
1080     return canSubExprsThrow(*this, E);
1081 
1082     // Some might be dependent for other reasons.
1083   case Expr::ArraySubscriptExprClass:
1084   case Expr::OMPArraySectionExprClass:
1085   case Expr::BinaryOperatorClass:
1086   case Expr::CompoundAssignOperatorClass:
1087   case Expr::CStyleCastExprClass:
1088   case Expr::CXXStaticCastExprClass:
1089   case Expr::CXXFunctionalCastExprClass:
1090   case Expr::ImplicitCastExprClass:
1091   case Expr::MaterializeTemporaryExprClass:
1092   case Expr::UnaryOperatorClass: {
1093     CanThrowResult CT = E->isTypeDependent() ? CT_Dependent : CT_Cannot;
1094     return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1095   }
1096 
1097     // FIXME: We should handle StmtExpr, but that opens a MASSIVE can of worms.
1098   case Expr::StmtExprClass:
1099     return CT_Can;
1100 
1101   case Expr::CXXDefaultArgExprClass:
1102     return canThrow(cast<CXXDefaultArgExpr>(E)->getExpr());
1103 
1104   case Expr::CXXDefaultInitExprClass:
1105     return canThrow(cast<CXXDefaultInitExpr>(E)->getExpr());
1106 
1107   case Expr::ChooseExprClass:
1108     if (E->isTypeDependent() || E->isValueDependent())
1109       return CT_Dependent;
1110     return canThrow(cast<ChooseExpr>(E)->getChosenSubExpr());
1111 
1112   case Expr::GenericSelectionExprClass:
1113     if (cast<GenericSelectionExpr>(E)->isResultDependent())
1114       return CT_Dependent;
1115     return canThrow(cast<GenericSelectionExpr>(E)->getResultExpr());
1116 
1117     // Some expressions are always dependent.
1118   case Expr::CXXDependentScopeMemberExprClass:
1119   case Expr::CXXUnresolvedConstructExprClass:
1120   case Expr::DependentScopeDeclRefExprClass:
1121   case Expr::CXXFoldExprClass:
1122     return CT_Dependent;
1123 
1124   case Expr::AsTypeExprClass:
1125   case Expr::BinaryConditionalOperatorClass:
1126   case Expr::BlockExprClass:
1127   case Expr::CUDAKernelCallExprClass:
1128   case Expr::DeclRefExprClass:
1129   case Expr::ObjCBridgedCastExprClass:
1130   case Expr::ObjCIndirectCopyRestoreExprClass:
1131   case Expr::ObjCProtocolExprClass:
1132   case Expr::ObjCSelectorExprClass:
1133   case Expr::OffsetOfExprClass:
1134   case Expr::PackExpansionExprClass:
1135   case Expr::PseudoObjectExprClass:
1136   case Expr::SubstNonTypeTemplateParmExprClass:
1137   case Expr::SubstNonTypeTemplateParmPackExprClass:
1138   case Expr::FunctionParmPackExprClass:
1139   case Expr::UnaryExprOrTypeTraitExprClass:
1140   case Expr::UnresolvedLookupExprClass:
1141   case Expr::UnresolvedMemberExprClass:
1142   case Expr::TypoExprClass:
1143     // FIXME: Can any of the above throw?  If so, when?
1144     return CT_Cannot;
1145 
1146   case Expr::AddrLabelExprClass:
1147   case Expr::ArrayTypeTraitExprClass:
1148   case Expr::AtomicExprClass:
1149   case Expr::TypeTraitExprClass:
1150   case Expr::CXXBoolLiteralExprClass:
1151   case Expr::CXXNoexceptExprClass:
1152   case Expr::CXXNullPtrLiteralExprClass:
1153   case Expr::CXXPseudoDestructorExprClass:
1154   case Expr::CXXScalarValueInitExprClass:
1155   case Expr::CXXThisExprClass:
1156   case Expr::CXXUuidofExprClass:
1157   case Expr::CharacterLiteralClass:
1158   case Expr::ExpressionTraitExprClass:
1159   case Expr::FloatingLiteralClass:
1160   case Expr::GNUNullExprClass:
1161   case Expr::ImaginaryLiteralClass:
1162   case Expr::ImplicitValueInitExprClass:
1163   case Expr::IntegerLiteralClass:
1164   case Expr::NoInitExprClass:
1165   case Expr::ObjCEncodeExprClass:
1166   case Expr::ObjCStringLiteralClass:
1167   case Expr::ObjCBoolLiteralExprClass:
1168   case Expr::OpaqueValueExprClass:
1169   case Expr::PredefinedExprClass:
1170   case Expr::SizeOfPackExprClass:
1171   case Expr::StringLiteralClass:
1172     // These expressions can never throw.
1173     return CT_Cannot;
1174 
1175   case Expr::MSPropertyRefExprClass:
1176     llvm_unreachable("Invalid class for expression");
1177 
1178 #define STMT(CLASS, PARENT) case Expr::CLASS##Class:
1179 #define STMT_RANGE(Base, First, Last)
1180 #define LAST_STMT_RANGE(BASE, FIRST, LAST)
1181 #define EXPR(CLASS, PARENT)
1182 #define ABSTRACT_STMT(STMT)
1183 #include "clang/AST/StmtNodes.inc"
1184   case Expr::NoStmtClass:
1185     llvm_unreachable("Invalid class for expression");
1186   }
1187   llvm_unreachable("Bogus StmtClass");
1188 }
1189 
1190 } // end namespace clang
1191