blob: 07671b2f1d73e05bcf9fa57a0c8f4f100b5d5ee6 [file] [log] [blame]
Sebastian Redl4915e632009-10-11 09:03:14 +00001//===--- 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
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Richard Smith564417a2014-03-20 21:47:22 +000015#include "clang/AST/ASTMutationListener.h"
Sebastian Redl4915e632009-10-11 09:03:14 +000016#include "clang/AST/CXXInheritance.h"
17#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
Douglas Gregord6bc5e62010-03-24 07:14:45 +000019#include "clang/AST/TypeLoc.h"
Douglas Gregorf40863c2010-02-12 07:32:17 +000020#include "clang/Basic/Diagnostic.h"
21#include "clang/Basic/SourceManager.h"
Sebastian Redl4915e632009-10-11 09:03:14 +000022#include "llvm/ADT/SmallPtrSet.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000023#include "llvm/ADT/SmallString.h"
Sebastian Redl4915e632009-10-11 09:03:14 +000024
25namespace clang {
26
27static 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();
Sebastian Redl075b21d2009-10-14 14:38:54 +000033 else if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
34 T = MPTy->getPointeeType();
Sebastian Redl4915e632009-10-11 09:03:14 +000035 return T->getAs<FunctionProtoType>();
36}
37
38/// CheckSpecifiedExceptionType - Check if the given type is valid in an
39/// exception specification. Incomplete types, or pointers to incomplete types
40/// other than void are not allowed.
Richard Smith8606d752012-11-28 22:33:28 +000041///
42/// \param[in,out] T The exception type. This will be decayed to a pointer type
43/// when the input is an array or a function type.
44bool Sema::CheckSpecifiedExceptionType(QualType &T, const SourceRange &Range) {
Richard Smitha118c6a2012-11-28 22:52:42 +000045 // C++11 [except.spec]p2:
46 // A type cv T, "array of T", or "function returning T" denoted
Richard Smith8606d752012-11-28 22:33:28 +000047 // in an exception-specification is adjusted to type T, "pointer to T", or
48 // "pointer to function returning T", respectively.
Richard Smitha118c6a2012-11-28 22:52:42 +000049 //
50 // We also apply this rule in C++98.
Richard Smith8606d752012-11-28 22:33:28 +000051 if (T->isArrayType())
52 T = Context.getArrayDecayedType(T);
53 else if (T->isFunctionType())
54 T = Context.getPointerType(T);
Sebastian Redl4915e632009-10-11 09:03:14 +000055
Richard Smitha118c6a2012-11-28 22:52:42 +000056 int Kind = 0;
Richard Smith8606d752012-11-28 22:33:28 +000057 QualType PointeeT = T;
Richard Smitha118c6a2012-11-28 22:52:42 +000058 if (const PointerType *PT = T->getAs<PointerType>()) {
59 PointeeT = PT->getPointeeType();
60 Kind = 1;
Sebastian Redl4915e632009-10-11 09:03:14 +000061
Richard Smitha118c6a2012-11-28 22:52:42 +000062 // cv void* is explicitly permitted, despite being a pointer to an
63 // incomplete type.
64 if (PointeeT->isVoidType())
65 return false;
66 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
67 PointeeT = RT->getPointeeType();
68 Kind = 2;
Richard Smith8606d752012-11-28 22:33:28 +000069
Richard Smitha118c6a2012-11-28 22:52:42 +000070 if (RT->isRValueReferenceType()) {
71 // C++11 [except.spec]p2:
72 // A type denoted in an exception-specification shall not denote [...]
73 // an rvalue reference type.
74 Diag(Range.getBegin(), diag::err_rref_in_exception_spec)
75 << T << Range;
76 return true;
77 }
78 }
79
80 // C++11 [except.spec]p2:
81 // A type denoted in an exception-specification shall not denote an
82 // incomplete type other than a class currently being defined [...].
83 // A type denoted in an exception-specification shall not denote a
84 // pointer or reference to an incomplete type, other than (cv) void* or a
85 // pointer or reference to a class currently being defined.
86 if (!(PointeeT->isRecordType() &&
87 PointeeT->getAs<RecordType>()->isBeingDefined()) &&
Richard Smith8606d752012-11-28 22:33:28 +000088 RequireCompleteType(Range.getBegin(), PointeeT,
Richard Smitha118c6a2012-11-28 22:52:42 +000089 diag::err_incomplete_in_exception_spec, Kind, Range))
Sebastian Redl7eb5d372009-10-14 14:59:48 +000090 return true;
Sebastian Redl4915e632009-10-11 09:03:14 +000091
92 return false;
93}
94
95/// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer
96/// to member to a function with an exception specification. This means that
97/// it is invalid to add another level of indirection.
98bool Sema::CheckDistantExceptionSpec(QualType T) {
99 if (const PointerType *PT = T->getAs<PointerType>())
100 T = PT->getPointeeType();
101 else if (const MemberPointerType *PT = T->getAs<MemberPointerType>())
102 T = PT->getPointeeType();
103 else
104 return false;
105
106 const FunctionProtoType *FnT = T->getAs<FunctionProtoType>();
107 if (!FnT)
108 return false;
109
110 return FnT->hasExceptionSpec();
111}
112
Richard Smithf623c962012-04-17 00:58:00 +0000113const FunctionProtoType *
114Sema::ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000115 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
Richard Smithf623c962012-04-17 00:58:00 +0000116 return FPT;
117
118 FunctionDecl *SourceDecl = FPT->getExceptionSpecDecl();
119 const FunctionProtoType *SourceFPT =
120 SourceDecl->getType()->castAs<FunctionProtoType>();
121
Richard Smithd3b5c9082012-07-27 04:22:15 +0000122 // If the exception specification has already been resolved, just return it.
123 if (!isUnresolvedExceptionSpec(SourceFPT->getExceptionSpecType()))
Richard Smithf623c962012-04-17 00:58:00 +0000124 return SourceFPT;
125
Richard Smithd3b5c9082012-07-27 04:22:15 +0000126 // Compute or instantiate the exception specification now.
Richard Smith3901dfe2013-03-27 00:22:47 +0000127 if (SourceFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smithd3b5c9082012-07-27 04:22:15 +0000128 EvaluateImplicitExceptionSpec(Loc, cast<CXXMethodDecl>(SourceDecl));
129 else
130 InstantiateExceptionSpec(Loc, SourceDecl);
Richard Smithf623c962012-04-17 00:58:00 +0000131
132 return SourceDecl->getType()->castAs<FunctionProtoType>();
133}
134
Richard Smith8acb4282014-07-31 21:57:55 +0000135void
136Sema::UpdateExceptionSpec(FunctionDecl *FD,
137 const FunctionProtoType::ExceptionSpecInfo &ESI) {
Richard Smith6de7a242014-07-31 23:46:44 +0000138 for (auto *Redecl : FD->redecls()) {
139 auto *RedeclFD = dyn_cast<FunctionDecl>(Redecl);
140 const FunctionProtoType *Proto =
141 RedeclFD->getType()->castAs<FunctionProtoType>();
Richard Smith564417a2014-03-20 21:47:22 +0000142
Richard Smith6de7a242014-07-31 23:46:44 +0000143 // Overwrite the exception spec and rebuild the function type.
144 RedeclFD->setType(Context.getFunctionType(
145 Proto->getReturnType(), Proto->getParamTypes(),
146 Proto->getExtProtoInfo().withExceptionSpec(ESI)));
147 }
Richard Smith564417a2014-03-20 21:47:22 +0000148
149 // If we've fully resolved the exception specification, notify listeners.
Richard Smith8acb4282014-07-31 21:57:55 +0000150 if (!isUnresolvedExceptionSpec(ESI.Type))
Richard Smith564417a2014-03-20 21:47:22 +0000151 if (auto *Listener = getASTMutationListener())
152 Listener->ResolvedExceptionSpec(FD);
153}
154
Richard Smith66f3ac92012-10-20 08:26:51 +0000155/// Determine whether a function has an implicitly-generated exception
Richard Smith1ee63522012-10-16 23:30:16 +0000156/// specification.
Richard Smith66f3ac92012-10-20 08:26:51 +0000157static bool hasImplicitExceptionSpec(FunctionDecl *Decl) {
158 if (!isa<CXXDestructorDecl>(Decl) &&
159 Decl->getDeclName().getCXXOverloadedOperator() != OO_Delete &&
160 Decl->getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
161 return false;
Richard Smith1ee63522012-10-16 23:30:16 +0000162
Richard Smithc7fb2252014-02-07 22:51:16 +0000163 // For a function that the user didn't declare:
164 // - if this is a destructor, its exception specification is implicit.
165 // - if this is 'operator delete' or 'operator delete[]', the exception
166 // specification is as-if an explicit exception specification was given
167 // (per [basic.stc.dynamic]p2).
Richard Smith66f3ac92012-10-20 08:26:51 +0000168 if (!Decl->getTypeSourceInfo())
Richard Smithc7fb2252014-02-07 22:51:16 +0000169 return isa<CXXDestructorDecl>(Decl);
Richard Smith66f3ac92012-10-20 08:26:51 +0000170
171 const FunctionProtoType *Ty =
172 Decl->getTypeSourceInfo()->getType()->getAs<FunctionProtoType>();
173 return !Ty->hasExceptionSpec();
Richard Smith1ee63522012-10-16 23:30:16 +0000174}
175
Douglas Gregorf40863c2010-02-12 07:32:17 +0000176bool Sema::CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New) {
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000177 OverloadedOperatorKind OO = New->getDeclName().getCXXOverloadedOperator();
178 bool IsOperatorNew = OO == OO_New || OO == OO_Array_New;
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000179 bool MissingExceptionSpecification = false;
Douglas Gregorf40863c2010-02-12 07:32:17 +0000180 bool MissingEmptyExceptionSpecification = false;
Hans Wennborg39a509a2014-02-05 02:37:58 +0000181
Francois Pichet13b4e682011-03-19 23:05:18 +0000182 unsigned DiagID = diag::err_mismatched_exception_spec;
Hans Wennborg39a509a2014-02-05 02:37:58 +0000183 bool ReturnValueOnError = true;
184 if (getLangOpts().MicrosoftExt) {
Richard Smith1b98ccc2014-07-19 01:39:17 +0000185 DiagID = diag::ext_mismatched_exception_spec;
Hans Wennborg39a509a2014-02-05 02:37:58 +0000186 ReturnValueOnError = false;
187 }
Richard Smithf623c962012-04-17 00:58:00 +0000188
Richard Smith1ee63522012-10-16 23:30:16 +0000189 // Check the types as written: they must match before any exception
190 // specification adjustment is applied.
191 if (!CheckEquivalentExceptionSpec(
192 PDiag(DiagID), PDiag(diag::note_previous_declaration),
Richard Smith66f3ac92012-10-20 08:26:51 +0000193 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
194 New->getType()->getAs<FunctionProtoType>(), New->getLocation(),
Richard Smith1ee63522012-10-16 23:30:16 +0000195 &MissingExceptionSpecification, &MissingEmptyExceptionSpecification,
Richard Smith66f3ac92012-10-20 08:26:51 +0000196 /*AllowNoexceptAllMatchWithNoSpec=*/true, IsOperatorNew)) {
197 // C++11 [except.spec]p4 [DR1492]:
198 // If a declaration of a function has an implicit
199 // exception-specification, other declarations of the function shall
200 // not specify an exception-specification.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000201 if (getLangOpts().CPlusPlus11 &&
Richard Smith66f3ac92012-10-20 08:26:51 +0000202 hasImplicitExceptionSpec(Old) != hasImplicitExceptionSpec(New)) {
203 Diag(New->getLocation(), diag::ext_implicit_exception_spec_mismatch)
204 << hasImplicitExceptionSpec(Old);
205 if (!Old->getLocation().isInvalid())
206 Diag(Old->getLocation(), diag::note_previous_declaration);
207 }
Douglas Gregorf40863c2010-02-12 07:32:17 +0000208 return false;
Richard Smith66f3ac92012-10-20 08:26:51 +0000209 }
Douglas Gregorf40863c2010-02-12 07:32:17 +0000210
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000211 // The failure was something other than an missing exception
Hans Wennborg39a509a2014-02-05 02:37:58 +0000212 // specification; return an error, except in MS mode where this is a warning.
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000213 if (!MissingExceptionSpecification)
Hans Wennborg39a509a2014-02-05 02:37:58 +0000214 return ReturnValueOnError;
Douglas Gregorf40863c2010-02-12 07:32:17 +0000215
Richard Smith66f3ac92012-10-20 08:26:51 +0000216 const FunctionProtoType *NewProto =
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000217 New->getType()->castAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +0000218
Douglas Gregorf40863c2010-02-12 07:32:17 +0000219 // The new function declaration is only missing an empty exception
220 // specification "throw()". If the throw() specification came from a
221 // function in a system header that has C linkage, just add an empty
222 // exception specification to the "new" declaration. This is an
223 // egregious workaround for glibc, which adds throw() specifications
224 // to many libc functions as an optimization. Unfortunately, that
225 // optimization isn't permitted by the C++ standard, so we're forced
226 // to work around it here.
John McCalldb40c7f2010-12-14 08:05:40 +0000227 if (MissingEmptyExceptionSpecification && NewProto &&
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000228 (Old->getLocation().isInvalid() ||
229 Context.getSourceManager().isInSystemHeader(Old->getLocation())) &&
Douglas Gregorf40863c2010-02-12 07:32:17 +0000230 Old->isExternC()) {
Richard Smith8acb4282014-07-31 21:57:55 +0000231 New->setType(Context.getFunctionType(
232 NewProto->getReturnType(), NewProto->getParamTypes(),
233 NewProto->getExtProtoInfo().withExceptionSpec(EST_DynamicNone)));
Douglas Gregorf40863c2010-02-12 07:32:17 +0000234 return false;
235 }
236
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000237 const FunctionProtoType *OldProto =
238 Old->getType()->castAs<FunctionProtoType>();
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000239
Richard Smith8acb4282014-07-31 21:57:55 +0000240 FunctionProtoType::ExceptionSpecInfo ESI = OldProto->getExceptionSpecType();
241 if (ESI.Type == EST_Dynamic) {
242 ESI.Exceptions = OldProto->exceptions();
243 } else if (ESI.Type == EST_ComputedNoexcept) {
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000244 // FIXME: We can't just take the expression from the old prototype. It
245 // likely contains references to the old prototype's parameters.
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000246 }
247
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000248 // Update the type of the function with the appropriate exception
249 // specification.
Richard Smith8acb4282014-07-31 21:57:55 +0000250 New->setType(Context.getFunctionType(
251 NewProto->getReturnType(), NewProto->getParamTypes(),
252 NewProto->getExtProtoInfo().withExceptionSpec(ESI)));
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000253
254 // Warn about the lack of exception specification.
255 SmallString<128> ExceptionSpecString;
256 llvm::raw_svector_ostream OS(ExceptionSpecString);
257 switch (OldProto->getExceptionSpecType()) {
258 case EST_DynamicNone:
259 OS << "throw()";
260 break;
261
262 case EST_Dynamic: {
263 OS << "throw(";
264 bool OnFirstException = true;
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000265 for (const auto &E : OldProto->exceptions()) {
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000266 if (OnFirstException)
267 OnFirstException = false;
268 else
269 OS << ", ";
270
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000271 OS << E.getAsString(getPrintingPolicy());
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000272 }
273 OS << ")";
274 break;
275 }
276
277 case EST_BasicNoexcept:
278 OS << "noexcept";
279 break;
280
281 case EST_ComputedNoexcept:
282 OS << "noexcept(";
Richard Trieuddd01ce2014-06-09 22:53:25 +0000283 assert(OldProto->getNoexceptExpr() != nullptr && "Expected non-null Expr");
Craig Topperc3ec1492014-05-26 06:22:03 +0000284 OldProto->getNoexceptExpr()->printPretty(OS, nullptr, getPrintingPolicy());
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000285 OS << ")";
286 break;
287
288 default:
289 llvm_unreachable("This spec type is compatible with none.");
290 }
291 OS.flush();
292
293 SourceLocation FixItLoc;
294 if (TypeSourceInfo *TSInfo = New->getTypeSourceInfo()) {
295 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
296 if (FunctionTypeLoc FTLoc = TL.getAs<FunctionTypeLoc>())
Alp Tokerb6cc5922014-05-03 03:45:55 +0000297 FixItLoc = getLocForEndOfToken(FTLoc.getLocalRangeEnd());
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000298 }
299
300 if (FixItLoc.isInvalid())
301 Diag(New->getLocation(), diag::warn_missing_exception_specification)
302 << New << OS.str();
303 else {
304 // FIXME: This will get more complicated with C++0x
305 // late-specified return types.
306 Diag(New->getLocation(), diag::warn_missing_exception_specification)
307 << New << OS.str()
308 << FixItHint::CreateInsertion(FixItLoc, " " + OS.str().str());
309 }
310
311 if (!Old->getLocation().isInvalid())
312 Diag(Old->getLocation(), diag::note_previous_declaration);
313
314 return false;
Douglas Gregorf40863c2010-02-12 07:32:17 +0000315}
316
Sebastian Redl4915e632009-10-11 09:03:14 +0000317/// CheckEquivalentExceptionSpec - Check if the two types have equivalent
318/// exception specifications. Exception specifications are equivalent if
319/// they allow exactly the same set of exception types. It does not matter how
320/// that is achieved. See C++ [except.spec]p2.
321bool Sema::CheckEquivalentExceptionSpec(
322 const FunctionProtoType *Old, SourceLocation OldLoc,
323 const FunctionProtoType *New, SourceLocation NewLoc) {
Francois Pichet13b4e682011-03-19 23:05:18 +0000324 unsigned DiagID = diag::err_mismatched_exception_spec;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000325 if (getLangOpts().MicrosoftExt)
Richard Smith1b98ccc2014-07-19 01:39:17 +0000326 DiagID = diag::ext_mismatched_exception_spec;
Hans Wennborg39a509a2014-02-05 02:37:58 +0000327 bool Result = CheckEquivalentExceptionSpec(PDiag(DiagID),
328 PDiag(diag::note_previous_declaration), Old, OldLoc, New, NewLoc);
329
330 // In Microsoft mode, mismatching exception specifications just cause a warning.
331 if (getLangOpts().MicrosoftExt)
332 return false;
333 return Result;
Sebastian Redl4915e632009-10-11 09:03:14 +0000334}
335
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000336/// CheckEquivalentExceptionSpec - Check if the two types have compatible
337/// exception specifications. See C++ [except.spec]p3.
Richard Smith66f3ac92012-10-20 08:26:51 +0000338///
339/// \return \c false if the exception specifications match, \c true if there is
340/// a problem. If \c true is returned, either a diagnostic has already been
341/// produced or \c *MissingExceptionSpecification is set to \c true.
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000342bool Sema::CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000343 const PartialDiagnostic & NoteID,
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000344 const FunctionProtoType *Old,
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000345 SourceLocation OldLoc,
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000346 const FunctionProtoType *New,
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000347 SourceLocation NewLoc,
348 bool *MissingExceptionSpecification,
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000349 bool*MissingEmptyExceptionSpecification,
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000350 bool AllowNoexceptAllMatchWithNoSpec,
351 bool IsOperatorNew) {
John McCallf9c94092010-05-28 08:37:35 +0000352 // Just completely ignore this under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000353 if (!getLangOpts().CXXExceptions)
John McCallf9c94092010-05-28 08:37:35 +0000354 return false;
355
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000356 if (MissingExceptionSpecification)
357 *MissingExceptionSpecification = false;
358
Douglas Gregorf40863c2010-02-12 07:32:17 +0000359 if (MissingEmptyExceptionSpecification)
360 *MissingEmptyExceptionSpecification = false;
361
Richard Smithf623c962012-04-17 00:58:00 +0000362 Old = ResolveExceptionSpec(NewLoc, Old);
363 if (!Old)
364 return false;
365 New = ResolveExceptionSpec(NewLoc, New);
366 if (!New)
367 return false;
368
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000369 // C++0x [except.spec]p3: Two exception-specifications are compatible if:
370 // - both are non-throwing, regardless of their form,
371 // - both have the form noexcept(constant-expression) and the constant-
372 // expressions are equivalent,
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000373 // - both are dynamic-exception-specifications that have the same set of
374 // adjusted types.
375 //
376 // C++0x [except.spec]p12: An exception-specifcation is non-throwing if it is
377 // of the form throw(), noexcept, or noexcept(constant-expression) where the
378 // constant-expression yields true.
379 //
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000380 // C++0x [except.spec]p4: If any declaration of a function has an exception-
381 // specifier that is not a noexcept-specification allowing all exceptions,
382 // all declarations [...] of that function shall have a compatible
383 // exception-specification.
384 //
385 // That last point basically means that noexcept(false) matches no spec.
386 // It's considered when AllowNoexceptAllMatchWithNoSpec is true.
387
388 ExceptionSpecificationType OldEST = Old->getExceptionSpecType();
389 ExceptionSpecificationType NewEST = New->getExceptionSpecType();
390
Richard Smithd3b5c9082012-07-27 04:22:15 +0000391 assert(!isUnresolvedExceptionSpec(OldEST) &&
392 !isUnresolvedExceptionSpec(NewEST) &&
Richard Smith938f40b2011-06-11 17:19:42 +0000393 "Shouldn't see unknown exception specifications here");
394
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000395 // Shortcut the case where both have no spec.
396 if (OldEST == EST_None && NewEST == EST_None)
397 return false;
398
Sebastian Redl31ad7542011-03-13 17:09:40 +0000399 FunctionProtoType::NoexceptResult OldNR = Old->getNoexceptSpec(Context);
400 FunctionProtoType::NoexceptResult NewNR = New->getNoexceptSpec(Context);
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000401 if (OldNR == FunctionProtoType::NR_BadNoexcept ||
402 NewNR == FunctionProtoType::NR_BadNoexcept)
403 return false;
404
405 // Dependent noexcept specifiers are compatible with each other, but nothing
406 // else.
407 // One noexcept is compatible with another if the argument is the same
408 if (OldNR == NewNR &&
409 OldNR != FunctionProtoType::NR_NoNoexcept &&
410 NewNR != FunctionProtoType::NR_NoNoexcept)
411 return false;
412 if (OldNR != NewNR &&
413 OldNR != FunctionProtoType::NR_NoNoexcept &&
414 NewNR != FunctionProtoType::NR_NoNoexcept) {
415 Diag(NewLoc, DiagID);
416 if (NoteID.getDiagID() != 0)
417 Diag(OldLoc, NoteID);
418 return true;
Douglas Gregorf62c5292010-08-30 15:04:51 +0000419 }
420
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000421 // The MS extension throw(...) is compatible with itself.
422 if (OldEST == EST_MSAny && NewEST == EST_MSAny)
Sebastian Redl4915e632009-10-11 09:03:14 +0000423 return false;
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000424
425 // It's also compatible with no spec.
426 if ((OldEST == EST_None && NewEST == EST_MSAny) ||
427 (OldEST == EST_MSAny && NewEST == EST_None))
428 return false;
429
430 // It's also compatible with noexcept(false).
431 if (OldEST == EST_MSAny && NewNR == FunctionProtoType::NR_Throw)
432 return false;
433 if (NewEST == EST_MSAny && OldNR == FunctionProtoType::NR_Throw)
434 return false;
435
436 // As described above, noexcept(false) matches no spec only for functions.
437 if (AllowNoexceptAllMatchWithNoSpec) {
438 if (OldEST == EST_None && NewNR == FunctionProtoType::NR_Throw)
439 return false;
440 if (NewEST == EST_None && OldNR == FunctionProtoType::NR_Throw)
441 return false;
442 }
443
444 // Any non-throwing specifications are compatible.
445 bool OldNonThrowing = OldNR == FunctionProtoType::NR_Nothrow ||
446 OldEST == EST_DynamicNone;
447 bool NewNonThrowing = NewNR == FunctionProtoType::NR_Nothrow ||
448 NewEST == EST_DynamicNone;
449 if (OldNonThrowing && NewNonThrowing)
450 return false;
451
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000452 // As a special compatibility feature, under C++0x we accept no spec and
453 // throw(std::bad_alloc) as equivalent for operator new and operator new[].
454 // This is because the implicit declaration changed, but old code would break.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000455 if (getLangOpts().CPlusPlus11 && IsOperatorNew) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000456 const FunctionProtoType *WithExceptions = nullptr;
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000457 if (OldEST == EST_None && NewEST == EST_Dynamic)
458 WithExceptions = New;
459 else if (OldEST == EST_Dynamic && NewEST == EST_None)
460 WithExceptions = Old;
461 if (WithExceptions && WithExceptions->getNumExceptions() == 1) {
462 // One has no spec, the other throw(something). If that something is
463 // std::bad_alloc, all conditions are met.
464 QualType Exception = *WithExceptions->exception_begin();
465 if (CXXRecordDecl *ExRecord = Exception->getAsCXXRecordDecl()) {
466 IdentifierInfo* Name = ExRecord->getIdentifier();
467 if (Name && Name->getName() == "bad_alloc") {
468 // It's called bad_alloc, but is it in std?
Richard Trieuc771d5d2014-05-28 02:16:01 +0000469 if (ExRecord->isInStdNamespace()) {
470 return false;
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000471 }
472 }
473 }
474 }
475 }
476
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000477 // At this point, the only remaining valid case is two matching dynamic
478 // specifications. We return here unless both specifications are dynamic.
479 if (OldEST != EST_Dynamic || NewEST != EST_Dynamic) {
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000480 if (MissingExceptionSpecification && Old->hasExceptionSpec() &&
Douglas Gregorf40863c2010-02-12 07:32:17 +0000481 !New->hasExceptionSpec()) {
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000482 // The old type has an exception specification of some sort, but
483 // the new type does not.
484 *MissingExceptionSpecification = true;
485
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000486 if (MissingEmptyExceptionSpecification && OldNonThrowing) {
487 // The old type has a throw() or noexcept(true) exception specification
488 // and the new type has no exception specification, and the caller asked
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000489 // to handle this itself.
490 *MissingEmptyExceptionSpecification = true;
491 }
492
Douglas Gregorf40863c2010-02-12 07:32:17 +0000493 return true;
494 }
495
Sebastian Redl4915e632009-10-11 09:03:14 +0000496 Diag(NewLoc, DiagID);
Sebastian Redla44822f2009-10-14 16:09:29 +0000497 if (NoteID.getDiagID() != 0)
Sebastian Redl4915e632009-10-11 09:03:14 +0000498 Diag(OldLoc, NoteID);
499 return true;
500 }
501
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000502 assert(OldEST == EST_Dynamic && NewEST == EST_Dynamic &&
503 "Exception compatibility logic error: non-dynamic spec slipped through.");
504
Sebastian Redl4915e632009-10-11 09:03:14 +0000505 bool Success = true;
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000506 // Both have a dynamic exception spec. Collect the first set, then compare
Sebastian Redl4915e632009-10-11 09:03:14 +0000507 // to the second.
Sebastian Redl184edca2009-10-14 15:06:25 +0000508 llvm::SmallPtrSet<CanQualType, 8> OldTypes, NewTypes;
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000509 for (const auto &I : Old->exceptions())
510 OldTypes.insert(Context.getCanonicalType(I).getUnqualifiedType());
Sebastian Redl4915e632009-10-11 09:03:14 +0000511
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000512 for (const auto &I : New->exceptions()) {
513 CanQualType TypePtr = Context.getCanonicalType(I).getUnqualifiedType();
Sebastian Redl6e4c8712009-10-11 09:11:23 +0000514 if(OldTypes.count(TypePtr))
515 NewTypes.insert(TypePtr);
516 else
517 Success = false;
518 }
Sebastian Redl4915e632009-10-11 09:03:14 +0000519
Sebastian Redl6e4c8712009-10-11 09:11:23 +0000520 Success = Success && OldTypes.size() == NewTypes.size();
Sebastian Redl4915e632009-10-11 09:03:14 +0000521
522 if (Success) {
523 return false;
524 }
525 Diag(NewLoc, DiagID);
Sebastian Redla44822f2009-10-14 16:09:29 +0000526 if (NoteID.getDiagID() != 0)
Sebastian Redl4915e632009-10-11 09:03:14 +0000527 Diag(OldLoc, NoteID);
528 return true;
529}
530
531/// CheckExceptionSpecSubset - Check whether the second function type's
532/// exception specification is a subset (or equivalent) of the first function
533/// type. This is used by override and pointer assignment checks.
Sebastian Redla44822f2009-10-14 16:09:29 +0000534bool Sema::CheckExceptionSpecSubset(
535 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
Sebastian Redl4915e632009-10-11 09:03:14 +0000536 const FunctionProtoType *Superset, SourceLocation SuperLoc,
537 const FunctionProtoType *Subset, SourceLocation SubLoc) {
John McCallf9c94092010-05-28 08:37:35 +0000538
539 // Just auto-succeed under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000540 if (!getLangOpts().CXXExceptions)
John McCallf9c94092010-05-28 08:37:35 +0000541 return false;
542
Sebastian Redl4915e632009-10-11 09:03:14 +0000543 // FIXME: As usual, we could be more specific in our error messages, but
544 // that better waits until we've got types with source locations.
545
546 if (!SubLoc.isValid())
547 SubLoc = SuperLoc;
548
Richard Smithf623c962012-04-17 00:58:00 +0000549 // Resolve the exception specifications, if needed.
550 Superset = ResolveExceptionSpec(SuperLoc, Superset);
551 if (!Superset)
552 return false;
553 Subset = ResolveExceptionSpec(SubLoc, Subset);
554 if (!Subset)
555 return false;
556
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000557 ExceptionSpecificationType SuperEST = Superset->getExceptionSpecType();
558
Sebastian Redl4915e632009-10-11 09:03:14 +0000559 // If superset contains everything, we're done.
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000560 if (SuperEST == EST_None || SuperEST == EST_MSAny)
Sebastian Redl4915e632009-10-11 09:03:14 +0000561 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
562
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000563 // If there are dependent noexcept specs, assume everything is fine. Unlike
564 // with the equivalency check, this is safe in this case, because we don't
565 // want to merge declarations. Checks after instantiation will catch any
566 // omissions we make here.
567 // We also shortcut checking if a noexcept expression was bad.
568
Sebastian Redl31ad7542011-03-13 17:09:40 +0000569 FunctionProtoType::NoexceptResult SuperNR =Superset->getNoexceptSpec(Context);
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000570 if (SuperNR == FunctionProtoType::NR_BadNoexcept ||
571 SuperNR == FunctionProtoType::NR_Dependent)
572 return false;
573
574 // Another case of the superset containing everything.
575 if (SuperNR == FunctionProtoType::NR_Throw)
576 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
577
578 ExceptionSpecificationType SubEST = Subset->getExceptionSpecType();
579
Richard Smithd3b5c9082012-07-27 04:22:15 +0000580 assert(!isUnresolvedExceptionSpec(SuperEST) &&
581 !isUnresolvedExceptionSpec(SubEST) &&
Richard Smith938f40b2011-06-11 17:19:42 +0000582 "Shouldn't see unknown exception specifications here");
583
Sebastian Redl4915e632009-10-11 09:03:14 +0000584 // It does not. If the subset contains everything, we've failed.
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000585 if (SubEST == EST_None || SubEST == EST_MSAny) {
Sebastian Redl4915e632009-10-11 09:03:14 +0000586 Diag(SubLoc, DiagID);
Sebastian Redla44822f2009-10-14 16:09:29 +0000587 if (NoteID.getDiagID() != 0)
Sebastian Redl4915e632009-10-11 09:03:14 +0000588 Diag(SuperLoc, NoteID);
589 return true;
590 }
591
Sebastian Redl31ad7542011-03-13 17:09:40 +0000592 FunctionProtoType::NoexceptResult SubNR = Subset->getNoexceptSpec(Context);
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000593 if (SubNR == FunctionProtoType::NR_BadNoexcept ||
594 SubNR == FunctionProtoType::NR_Dependent)
595 return false;
596
597 // Another case of the subset containing everything.
598 if (SubNR == FunctionProtoType::NR_Throw) {
599 Diag(SubLoc, DiagID);
600 if (NoteID.getDiagID() != 0)
601 Diag(SuperLoc, NoteID);
602 return true;
603 }
604
605 // If the subset contains nothing, we're done.
606 if (SubEST == EST_DynamicNone || SubNR == FunctionProtoType::NR_Nothrow)
607 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
608
609 // Otherwise, if the superset contains nothing, we've failed.
610 if (SuperEST == EST_DynamicNone || SuperNR == FunctionProtoType::NR_Nothrow) {
611 Diag(SubLoc, DiagID);
612 if (NoteID.getDiagID() != 0)
613 Diag(SuperLoc, NoteID);
614 return true;
615 }
616
617 assert(SuperEST == EST_Dynamic && SubEST == EST_Dynamic &&
618 "Exception spec subset: non-dynamic case slipped through.");
619
620 // Neither contains everything or nothing. Do a proper comparison.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000621 for (const auto &SubI : Subset->exceptions()) {
Sebastian Redl4915e632009-10-11 09:03:14 +0000622 // Take one type from the subset.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000623 QualType CanonicalSubT = Context.getCanonicalType(SubI);
Sebastian Redl075b21d2009-10-14 14:38:54 +0000624 // Unwrap pointers and references so that we can do checks within a class
625 // hierarchy. Don't unwrap member pointers; they don't have hierarchy
626 // conversions on the pointee.
Sebastian Redl4915e632009-10-11 09:03:14 +0000627 bool SubIsPointer = false;
628 if (const ReferenceType *RefTy = CanonicalSubT->getAs<ReferenceType>())
629 CanonicalSubT = RefTy->getPointeeType();
630 if (const PointerType *PtrTy = CanonicalSubT->getAs<PointerType>()) {
631 CanonicalSubT = PtrTy->getPointeeType();
632 SubIsPointer = true;
633 }
634 bool SubIsClass = CanonicalSubT->isRecordType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000635 CanonicalSubT = CanonicalSubT.getLocalUnqualifiedType();
Sebastian Redl4915e632009-10-11 09:03:14 +0000636
637 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
638 /*DetectVirtual=*/false);
639
640 bool Contained = false;
641 // Make sure it's in the superset.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000642 for (const auto &SuperI : Superset->exceptions()) {
643 QualType CanonicalSuperT = Context.getCanonicalType(SuperI);
Sebastian Redl4915e632009-10-11 09:03:14 +0000644 // SubT must be SuperT or derived from it, or pointer or reference to
645 // such types.
646 if (const ReferenceType *RefTy = CanonicalSuperT->getAs<ReferenceType>())
647 CanonicalSuperT = RefTy->getPointeeType();
648 if (SubIsPointer) {
649 if (const PointerType *PtrTy = CanonicalSuperT->getAs<PointerType>())
650 CanonicalSuperT = PtrTy->getPointeeType();
651 else {
652 continue;
653 }
654 }
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000655 CanonicalSuperT = CanonicalSuperT.getLocalUnqualifiedType();
Sebastian Redl4915e632009-10-11 09:03:14 +0000656 // If the types are the same, move on to the next type in the subset.
657 if (CanonicalSubT == CanonicalSuperT) {
658 Contained = true;
659 break;
660 }
661
662 // Otherwise we need to check the inheritance.
663 if (!SubIsClass || !CanonicalSuperT->isRecordType())
664 continue;
665
666 Paths.clear();
667 if (!IsDerivedFrom(CanonicalSubT, CanonicalSuperT, Paths))
668 continue;
669
Douglas Gregor27ac4292010-05-21 20:29:55 +0000670 if (Paths.isAmbiguous(Context.getCanonicalType(CanonicalSuperT)))
Sebastian Redl4915e632009-10-11 09:03:14 +0000671 continue;
672
John McCall5b0829a2010-02-10 09:31:12 +0000673 // Do this check from a context without privileges.
John McCall1064d7e2010-03-16 05:22:47 +0000674 switch (CheckBaseClassAccess(SourceLocation(),
John McCall5b0829a2010-02-10 09:31:12 +0000675 CanonicalSuperT, CanonicalSubT,
676 Paths.front(),
John McCall1064d7e2010-03-16 05:22:47 +0000677 /*Diagnostic*/ 0,
John McCall5b0829a2010-02-10 09:31:12 +0000678 /*ForceCheck*/ true,
John McCall1064d7e2010-03-16 05:22:47 +0000679 /*ForceUnprivileged*/ true)) {
John McCall5b0829a2010-02-10 09:31:12 +0000680 case AR_accessible: break;
681 case AR_inaccessible: continue;
682 case AR_dependent:
683 llvm_unreachable("access check dependent for unprivileged context");
John McCall5b0829a2010-02-10 09:31:12 +0000684 case AR_delayed:
685 llvm_unreachable("access check delayed in non-declaration");
John McCall5b0829a2010-02-10 09:31:12 +0000686 }
Sebastian Redl4915e632009-10-11 09:03:14 +0000687
688 Contained = true;
689 break;
690 }
691 if (!Contained) {
692 Diag(SubLoc, DiagID);
Sebastian Redla44822f2009-10-14 16:09:29 +0000693 if (NoteID.getDiagID() != 0)
Sebastian Redl4915e632009-10-11 09:03:14 +0000694 Diag(SuperLoc, NoteID);
695 return true;
696 }
697 }
698 // We've run half the gauntlet.
699 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
700}
701
702static bool CheckSpecForTypesEquivalent(Sema &S,
Sebastian Redla44822f2009-10-14 16:09:29 +0000703 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
Sebastian Redl4915e632009-10-11 09:03:14 +0000704 QualType Target, SourceLocation TargetLoc,
705 QualType Source, SourceLocation SourceLoc)
706{
707 const FunctionProtoType *TFunc = GetUnderlyingFunction(Target);
708 if (!TFunc)
709 return false;
710 const FunctionProtoType *SFunc = GetUnderlyingFunction(Source);
711 if (!SFunc)
712 return false;
713
714 return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc,
715 SFunc, SourceLoc);
716}
717
718/// CheckParamExceptionSpec - Check if the parameter and return types of the
719/// two functions have equivalent exception specs. This is part of the
720/// assignment and override compatibility check. We do not check the parameters
721/// of parameter function pointers recursively, as no sane programmer would
722/// even be able to write such a function type.
NAKAMURA Takumi23224152014-10-17 12:48:37 +0000723bool Sema::CheckParamExceptionSpec(const PartialDiagnostic & NoteID,
724 const FunctionProtoType *Target, SourceLocation TargetLoc,
725 const FunctionProtoType *Source, SourceLocation SourceLoc)
726{
Alp Toker314cc812014-01-25 16:55:45 +0000727 if (CheckSpecForTypesEquivalent(
728 *this, PDiag(diag::err_deep_exception_specs_differ) << 0, PDiag(),
729 Target->getReturnType(), TargetLoc, Source->getReturnType(),
730 SourceLoc))
Sebastian Redl4915e632009-10-11 09:03:14 +0000731 return true;
732
Sebastian Redla44822f2009-10-14 16:09:29 +0000733 // We shouldn't even be testing this unless the arguments are otherwise
Sebastian Redl4915e632009-10-11 09:03:14 +0000734 // compatible.
Alp Toker9cacbab2014-01-20 20:26:09 +0000735 assert(Target->getNumParams() == Source->getNumParams() &&
Sebastian Redl4915e632009-10-11 09:03:14 +0000736 "Functions have different argument counts.");
Alp Toker9cacbab2014-01-20 20:26:09 +0000737 for (unsigned i = 0, E = Target->getNumParams(); i != E; ++i) {
738 if (CheckSpecForTypesEquivalent(
739 *this, PDiag(diag::err_deep_exception_specs_differ) << 1, PDiag(),
740 Target->getParamType(i), TargetLoc, Source->getParamType(i),
741 SourceLoc))
Sebastian Redl4915e632009-10-11 09:03:14 +0000742 return true;
743 }
744 return false;
745}
746
NAKAMURA Takumi23224152014-10-17 12:48:37 +0000747bool Sema::CheckExceptionSpecCompatibility(Expr *From, QualType ToType)
748{
Sebastian Redl4915e632009-10-11 09:03:14 +0000749 // First we check for applicability.
750 // Target type must be a function, function pointer or function reference.
751 const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType);
NAKAMURA Takumi23224152014-10-17 12:48:37 +0000752 if (!ToFunc)
Sebastian Redl4915e632009-10-11 09:03:14 +0000753 return false;
754
755 // SourceType must be a function or function pointer.
756 const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType());
NAKAMURA Takumi23224152014-10-17 12:48:37 +0000757 if (!FromFunc)
Sebastian Redl4915e632009-10-11 09:03:14 +0000758 return false;
759
760 // Now we've got the correct types on both sides, check their compatibility.
761 // This means that the source of the conversion can only throw a subset of
762 // the exceptions of the target, and any exception specs on arguments or
763 // return types must be equivalent.
Douglas Gregor89336232010-03-29 23:34:08 +0000764 return CheckExceptionSpecSubset(PDiag(diag::err_incompatible_exception_specs),
765 PDiag(), ToFunc,
766 From->getSourceRange().getBegin(),
Sebastian Redl4915e632009-10-11 09:03:14 +0000767 FromFunc, SourceLocation());
768}
769
770bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
771 const CXXMethodDecl *Old) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000772 if (getLangOpts().CPlusPlus11 && isa<CXXDestructorDecl>(New)) {
Sebastian Redl645d9582011-05-20 05:57:18 +0000773 // Don't check uninstantiated template destructors at all. We can only
774 // synthesize correct specs after the template is instantiated.
775 if (New->getParent()->isDependentType())
776 return false;
777 if (New->getParent()->isBeingDefined()) {
778 // The destructor might be updated once the definition is finished. So
779 // remember it and check later.
780 DelayedDestructorExceptionSpecChecks.push_back(std::make_pair(
781 cast<CXXDestructorDecl>(New), cast<CXXDestructorDecl>(Old)));
782 return false;
783 }
Sebastian Redl623ea822011-05-19 05:13:44 +0000784 }
Francois Picheta8032e92011-05-24 02:11:43 +0000785 unsigned DiagID = diag::err_override_exception_spec;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000786 if (getLangOpts().MicrosoftExt)
Richard Smith1b98ccc2014-07-19 01:39:17 +0000787 DiagID = diag::ext_override_exception_spec;
Francois Picheta8032e92011-05-24 02:11:43 +0000788 return CheckExceptionSpecSubset(PDiag(DiagID),
Douglas Gregor89336232010-03-29 23:34:08 +0000789 PDiag(diag::note_overridden_virtual_function),
Sebastian Redl4915e632009-10-11 09:03:14 +0000790 Old->getType()->getAs<FunctionProtoType>(),
791 Old->getLocation(),
792 New->getType()->getAs<FunctionProtoType>(),
793 New->getLocation());
794}
795
Richard Smithf623c962012-04-17 00:58:00 +0000796static CanThrowResult canSubExprsThrow(Sema &S, const Expr *CE) {
797 Expr *E = const_cast<Expr*>(CE);
798 CanThrowResult R = CT_Cannot;
799 for (Expr::child_range I = E->children(); I && R != CT_Can; ++I)
800 R = mergeCanThrow(R, S.canThrow(cast<Expr>(*I)));
801 return R;
802}
803
Eli Friedman0423b762013-06-25 01:24:22 +0000804static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D) {
805 assert(D && "Expected decl");
Richard Smithf623c962012-04-17 00:58:00 +0000806
807 // See if we can get a function type from the decl somehow.
808 const ValueDecl *VD = dyn_cast<ValueDecl>(D);
809 if (!VD) // If we have no clue what we're calling, assume the worst.
810 return CT_Can;
811
812 // As an extension, we assume that __attribute__((nothrow)) functions don't
813 // throw.
814 if (isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())
815 return CT_Cannot;
816
817 QualType T = VD->getType();
818 const FunctionProtoType *FT;
819 if ((FT = T->getAs<FunctionProtoType>())) {
820 } else if (const PointerType *PT = T->getAs<PointerType>())
821 FT = PT->getPointeeType()->getAs<FunctionProtoType>();
822 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
823 FT = RT->getPointeeType()->getAs<FunctionProtoType>();
824 else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
825 FT = MT->getPointeeType()->getAs<FunctionProtoType>();
826 else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
827 FT = BT->getPointeeType()->getAs<FunctionProtoType>();
828
829 if (!FT)
830 return CT_Can;
831
832 FT = S.ResolveExceptionSpec(E->getLocStart(), FT);
833 if (!FT)
834 return CT_Can;
835
Richard Smithf623c962012-04-17 00:58:00 +0000836 return FT->isNothrow(S.Context) ? CT_Cannot : CT_Can;
837}
838
839static CanThrowResult canDynamicCastThrow(const CXXDynamicCastExpr *DC) {
840 if (DC->isTypeDependent())
841 return CT_Dependent;
842
843 if (!DC->getTypeAsWritten()->isReferenceType())
844 return CT_Cannot;
845
846 if (DC->getSubExpr()->isTypeDependent())
847 return CT_Dependent;
848
849 return DC->getCastKind() == clang::CK_Dynamic? CT_Can : CT_Cannot;
850}
851
852static CanThrowResult canTypeidThrow(Sema &S, const CXXTypeidExpr *DC) {
853 if (DC->isTypeOperand())
854 return CT_Cannot;
855
856 Expr *Op = DC->getExprOperand();
857 if (Op->isTypeDependent())
858 return CT_Dependent;
859
860 const RecordType *RT = Op->getType()->getAs<RecordType>();
861 if (!RT)
862 return CT_Cannot;
863
864 if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
865 return CT_Cannot;
866
867 if (Op->Classify(S.Context).isPRValue())
868 return CT_Cannot;
869
870 return CT_Can;
871}
872
873CanThrowResult Sema::canThrow(const Expr *E) {
874 // C++ [expr.unary.noexcept]p3:
875 // [Can throw] if in a potentially-evaluated context the expression would
876 // contain:
877 switch (E->getStmtClass()) {
878 case Expr::CXXThrowExprClass:
879 // - a potentially evaluated throw-expression
880 return CT_Can;
881
882 case Expr::CXXDynamicCastExprClass: {
883 // - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
884 // where T is a reference type, that requires a run-time check
885 CanThrowResult CT = canDynamicCastThrow(cast<CXXDynamicCastExpr>(E));
886 if (CT == CT_Can)
887 return CT;
888 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
889 }
890
891 case Expr::CXXTypeidExprClass:
892 // - a potentially evaluated typeid expression applied to a glvalue
893 // expression whose type is a polymorphic class type
894 return canTypeidThrow(*this, cast<CXXTypeidExpr>(E));
895
896 // - a potentially evaluated call to a function, member function, function
897 // pointer, or member function pointer that does not have a non-throwing
898 // exception-specification
899 case Expr::CallExprClass:
900 case Expr::CXXMemberCallExprClass:
901 case Expr::CXXOperatorCallExprClass:
902 case Expr::UserDefinedLiteralClass: {
903 const CallExpr *CE = cast<CallExpr>(E);
904 CanThrowResult CT;
905 if (E->isTypeDependent())
906 CT = CT_Dependent;
907 else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens()))
908 CT = CT_Cannot;
Eli Friedman5a8738f2013-06-25 01:55:41 +0000909 else if (CE->getCalleeDecl())
Richard Smithf623c962012-04-17 00:58:00 +0000910 CT = canCalleeThrow(*this, E, CE->getCalleeDecl());
Eli Friedman5a8738f2013-06-25 01:55:41 +0000911 else
912 CT = CT_Can;
Richard Smithf623c962012-04-17 00:58:00 +0000913 if (CT == CT_Can)
914 return CT;
915 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
916 }
917
918 case Expr::CXXConstructExprClass:
919 case Expr::CXXTemporaryObjectExprClass: {
920 CanThrowResult CT = canCalleeThrow(*this, E,
921 cast<CXXConstructExpr>(E)->getConstructor());
922 if (CT == CT_Can)
923 return CT;
924 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
925 }
926
927 case Expr::LambdaExprClass: {
928 const LambdaExpr *Lambda = cast<LambdaExpr>(E);
929 CanThrowResult CT = CT_Cannot;
930 for (LambdaExpr::capture_init_iterator Cap = Lambda->capture_init_begin(),
931 CapEnd = Lambda->capture_init_end();
932 Cap != CapEnd; ++Cap)
933 CT = mergeCanThrow(CT, canThrow(*Cap));
934 return CT;
935 }
936
937 case Expr::CXXNewExprClass: {
938 CanThrowResult CT;
939 if (E->isTypeDependent())
940 CT = CT_Dependent;
941 else
942 CT = canCalleeThrow(*this, E, cast<CXXNewExpr>(E)->getOperatorNew());
943 if (CT == CT_Can)
944 return CT;
945 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
946 }
947
948 case Expr::CXXDeleteExprClass: {
949 CanThrowResult CT;
950 QualType DTy = cast<CXXDeleteExpr>(E)->getDestroyedType();
951 if (DTy.isNull() || DTy->isDependentType()) {
952 CT = CT_Dependent;
953 } else {
954 CT = canCalleeThrow(*this, E,
955 cast<CXXDeleteExpr>(E)->getOperatorDelete());
956 if (const RecordType *RT = DTy->getAs<RecordType>()) {
957 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedman0423b762013-06-25 01:24:22 +0000958 const CXXDestructorDecl *DD = RD->getDestructor();
959 if (DD)
960 CT = mergeCanThrow(CT, canCalleeThrow(*this, E, DD));
Richard Smithf623c962012-04-17 00:58:00 +0000961 }
962 if (CT == CT_Can)
963 return CT;
964 }
965 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
966 }
967
968 case Expr::CXXBindTemporaryExprClass: {
969 // The bound temporary has to be destroyed again, which might throw.
970 CanThrowResult CT = canCalleeThrow(*this, E,
971 cast<CXXBindTemporaryExpr>(E)->getTemporary()->getDestructor());
972 if (CT == CT_Can)
973 return CT;
974 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
975 }
976
977 // ObjC message sends are like function calls, but never have exception
978 // specs.
979 case Expr::ObjCMessageExprClass:
980 case Expr::ObjCPropertyRefExprClass:
981 case Expr::ObjCSubscriptRefExprClass:
982 return CT_Can;
983
984 // All the ObjC literals that are implemented as calls are
985 // potentially throwing unless we decide to close off that
986 // possibility.
987 case Expr::ObjCArrayLiteralClass:
988 case Expr::ObjCDictionaryLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +0000989 case Expr::ObjCBoxedExprClass:
Richard Smithf623c962012-04-17 00:58:00 +0000990 return CT_Can;
991
992 // Many other things have subexpressions, so we have to test those.
993 // Some are simple:
994 case Expr::ConditionalOperatorClass:
995 case Expr::CompoundLiteralExprClass:
996 case Expr::CXXConstCastExprClass:
Richard Smithf623c962012-04-17 00:58:00 +0000997 case Expr::CXXReinterpretCastExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +0000998 case Expr::CXXStdInitializerListExprClass:
Richard Smithf623c962012-04-17 00:58:00 +0000999 case Expr::DesignatedInitExprClass:
1000 case Expr::ExprWithCleanupsClass:
1001 case Expr::ExtVectorElementExprClass:
1002 case Expr::InitListExprClass:
1003 case Expr::MemberExprClass:
1004 case Expr::ObjCIsaExprClass:
1005 case Expr::ObjCIvarRefExprClass:
1006 case Expr::ParenExprClass:
1007 case Expr::ParenListExprClass:
1008 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00001009 case Expr::ConvertVectorExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001010 case Expr::VAArgExprClass:
1011 return canSubExprsThrow(*this, E);
1012
1013 // Some might be dependent for other reasons.
1014 case Expr::ArraySubscriptExprClass:
1015 case Expr::BinaryOperatorClass:
1016 case Expr::CompoundAssignOperatorClass:
1017 case Expr::CStyleCastExprClass:
1018 case Expr::CXXStaticCastExprClass:
1019 case Expr::CXXFunctionalCastExprClass:
1020 case Expr::ImplicitCastExprClass:
1021 case Expr::MaterializeTemporaryExprClass:
1022 case Expr::UnaryOperatorClass: {
1023 CanThrowResult CT = E->isTypeDependent() ? CT_Dependent : CT_Cannot;
1024 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1025 }
1026
1027 // FIXME: We should handle StmtExpr, but that opens a MASSIVE can of worms.
1028 case Expr::StmtExprClass:
1029 return CT_Can;
1030
Richard Smith852c9db2013-04-20 22:23:05 +00001031 case Expr::CXXDefaultArgExprClass:
1032 return canThrow(cast<CXXDefaultArgExpr>(E)->getExpr());
1033
1034 case Expr::CXXDefaultInitExprClass:
1035 return canThrow(cast<CXXDefaultInitExpr>(E)->getExpr());
1036
Richard Smithf623c962012-04-17 00:58:00 +00001037 case Expr::ChooseExprClass:
1038 if (E->isTypeDependent() || E->isValueDependent())
1039 return CT_Dependent;
Eli Friedman75807f22013-07-20 00:40:58 +00001040 return canThrow(cast<ChooseExpr>(E)->getChosenSubExpr());
Richard Smithf623c962012-04-17 00:58:00 +00001041
1042 case Expr::GenericSelectionExprClass:
1043 if (cast<GenericSelectionExpr>(E)->isResultDependent())
1044 return CT_Dependent;
1045 return canThrow(cast<GenericSelectionExpr>(E)->getResultExpr());
1046
1047 // Some expressions are always dependent.
1048 case Expr::CXXDependentScopeMemberExprClass:
1049 case Expr::CXXUnresolvedConstructExprClass:
1050 case Expr::DependentScopeDeclRefExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00001051 case Expr::CXXFoldExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001052 return CT_Dependent;
1053
1054 case Expr::AsTypeExprClass:
1055 case Expr::BinaryConditionalOperatorClass:
1056 case Expr::BlockExprClass:
1057 case Expr::CUDAKernelCallExprClass:
1058 case Expr::DeclRefExprClass:
1059 case Expr::ObjCBridgedCastExprClass:
1060 case Expr::ObjCIndirectCopyRestoreExprClass:
1061 case Expr::ObjCProtocolExprClass:
1062 case Expr::ObjCSelectorExprClass:
1063 case Expr::OffsetOfExprClass:
1064 case Expr::PackExpansionExprClass:
1065 case Expr::PseudoObjectExprClass:
1066 case Expr::SubstNonTypeTemplateParmExprClass:
1067 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00001068 case Expr::FunctionParmPackExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001069 case Expr::UnaryExprOrTypeTraitExprClass:
1070 case Expr::UnresolvedLookupExprClass:
1071 case Expr::UnresolvedMemberExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00001072 case Expr::TypoExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001073 // FIXME: Can any of the above throw? If so, when?
1074 return CT_Cannot;
1075
1076 case Expr::AddrLabelExprClass:
1077 case Expr::ArrayTypeTraitExprClass:
1078 case Expr::AtomicExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001079 case Expr::TypeTraitExprClass:
1080 case Expr::CXXBoolLiteralExprClass:
1081 case Expr::CXXNoexceptExprClass:
1082 case Expr::CXXNullPtrLiteralExprClass:
1083 case Expr::CXXPseudoDestructorExprClass:
1084 case Expr::CXXScalarValueInitExprClass:
1085 case Expr::CXXThisExprClass:
1086 case Expr::CXXUuidofExprClass:
1087 case Expr::CharacterLiteralClass:
1088 case Expr::ExpressionTraitExprClass:
1089 case Expr::FloatingLiteralClass:
1090 case Expr::GNUNullExprClass:
1091 case Expr::ImaginaryLiteralClass:
1092 case Expr::ImplicitValueInitExprClass:
1093 case Expr::IntegerLiteralClass:
1094 case Expr::ObjCEncodeExprClass:
1095 case Expr::ObjCStringLiteralClass:
1096 case Expr::ObjCBoolLiteralExprClass:
1097 case Expr::OpaqueValueExprClass:
1098 case Expr::PredefinedExprClass:
1099 case Expr::SizeOfPackExprClass:
1100 case Expr::StringLiteralClass:
Richard Smithf623c962012-04-17 00:58:00 +00001101 // These expressions can never throw.
1102 return CT_Cannot;
1103
John McCall5e77d762013-04-16 07:28:30 +00001104 case Expr::MSPropertyRefExprClass:
1105 llvm_unreachable("Invalid class for expression");
1106
Richard Smithf623c962012-04-17 00:58:00 +00001107#define STMT(CLASS, PARENT) case Expr::CLASS##Class:
1108#define STMT_RANGE(Base, First, Last)
1109#define LAST_STMT_RANGE(BASE, FIRST, LAST)
1110#define EXPR(CLASS, PARENT)
1111#define ABSTRACT_STMT(STMT)
1112#include "clang/AST/StmtNodes.inc"
1113 case Expr::NoStmtClass:
1114 llvm_unreachable("Invalid class for expression");
1115 }
1116 llvm_unreachable("Bogus StmtClass");
1117}
1118
Sebastian Redl4915e632009-10-11 09:03:14 +00001119} // end namespace clang