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