blob: f9a8a5db466a15694d7c72d5052aec9cf78f15e8 [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"
Sebastian Redl4915e632009-10-11 09:03:14 +000015#include "clang/AST/CXXInheritance.h"
16#include "clang/AST/Expr.h"
17#include "clang/AST/ExprCXX.h"
Douglas Gregord6bc5e62010-03-24 07:14:45 +000018#include "clang/AST/TypeLoc.h"
Douglas Gregorf40863c2010-02-12 07:32:17 +000019#include "clang/Basic/Diagnostic.h"
20#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Lex/Preprocessor.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 Smith66f3ac92012-10-20 08:26:51 +0000135/// Determine whether a function has an implicitly-generated exception
Richard Smith1ee63522012-10-16 23:30:16 +0000136/// specification.
Richard Smith66f3ac92012-10-20 08:26:51 +0000137static bool hasImplicitExceptionSpec(FunctionDecl *Decl) {
138 if (!isa<CXXDestructorDecl>(Decl) &&
139 Decl->getDeclName().getCXXOverloadedOperator() != OO_Delete &&
140 Decl->getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
141 return false;
Richard Smith1ee63522012-10-16 23:30:16 +0000142
Richard Smithc7fb2252014-02-07 22:51:16 +0000143 // For a function that the user didn't declare:
144 // - if this is a destructor, its exception specification is implicit.
145 // - if this is 'operator delete' or 'operator delete[]', the exception
146 // specification is as-if an explicit exception specification was given
147 // (per [basic.stc.dynamic]p2).
Richard Smith66f3ac92012-10-20 08:26:51 +0000148 if (!Decl->getTypeSourceInfo())
Richard Smithc7fb2252014-02-07 22:51:16 +0000149 return isa<CXXDestructorDecl>(Decl);
Richard Smith66f3ac92012-10-20 08:26:51 +0000150
151 const FunctionProtoType *Ty =
152 Decl->getTypeSourceInfo()->getType()->getAs<FunctionProtoType>();
153 return !Ty->hasExceptionSpec();
Richard Smith1ee63522012-10-16 23:30:16 +0000154}
155
Douglas Gregorf40863c2010-02-12 07:32:17 +0000156bool Sema::CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New) {
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000157 OverloadedOperatorKind OO = New->getDeclName().getCXXOverloadedOperator();
158 bool IsOperatorNew = OO == OO_New || OO == OO_Array_New;
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000159 bool MissingExceptionSpecification = false;
Douglas Gregorf40863c2010-02-12 07:32:17 +0000160 bool MissingEmptyExceptionSpecification = false;
Hans Wennborg39a509a2014-02-05 02:37:58 +0000161
Francois Pichet13b4e682011-03-19 23:05:18 +0000162 unsigned DiagID = diag::err_mismatched_exception_spec;
Hans Wennborg39a509a2014-02-05 02:37:58 +0000163 bool ReturnValueOnError = true;
164 if (getLangOpts().MicrosoftExt) {
Francois Pichet93921652011-04-22 08:25:24 +0000165 DiagID = diag::warn_mismatched_exception_spec;
Hans Wennborg39a509a2014-02-05 02:37:58 +0000166 ReturnValueOnError = false;
167 }
Richard Smithf623c962012-04-17 00:58:00 +0000168
Richard Smith1ee63522012-10-16 23:30:16 +0000169 // Check the types as written: they must match before any exception
170 // specification adjustment is applied.
171 if (!CheckEquivalentExceptionSpec(
172 PDiag(DiagID), PDiag(diag::note_previous_declaration),
Richard Smith66f3ac92012-10-20 08:26:51 +0000173 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
174 New->getType()->getAs<FunctionProtoType>(), New->getLocation(),
Richard Smith1ee63522012-10-16 23:30:16 +0000175 &MissingExceptionSpecification, &MissingEmptyExceptionSpecification,
Richard Smith66f3ac92012-10-20 08:26:51 +0000176 /*AllowNoexceptAllMatchWithNoSpec=*/true, IsOperatorNew)) {
177 // C++11 [except.spec]p4 [DR1492]:
178 // If a declaration of a function has an implicit
179 // exception-specification, other declarations of the function shall
180 // not specify an exception-specification.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000181 if (getLangOpts().CPlusPlus11 &&
Richard Smith66f3ac92012-10-20 08:26:51 +0000182 hasImplicitExceptionSpec(Old) != hasImplicitExceptionSpec(New)) {
183 Diag(New->getLocation(), diag::ext_implicit_exception_spec_mismatch)
184 << hasImplicitExceptionSpec(Old);
185 if (!Old->getLocation().isInvalid())
186 Diag(Old->getLocation(), diag::note_previous_declaration);
187 }
Douglas Gregorf40863c2010-02-12 07:32:17 +0000188 return false;
Richard Smith66f3ac92012-10-20 08:26:51 +0000189 }
Douglas Gregorf40863c2010-02-12 07:32:17 +0000190
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000191 // The failure was something other than an missing exception
Hans Wennborg39a509a2014-02-05 02:37:58 +0000192 // specification; return an error, except in MS mode where this is a warning.
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000193 if (!MissingExceptionSpecification)
Hans Wennborg39a509a2014-02-05 02:37:58 +0000194 return ReturnValueOnError;
Douglas Gregorf40863c2010-02-12 07:32:17 +0000195
Richard Smith66f3ac92012-10-20 08:26:51 +0000196 const FunctionProtoType *NewProto =
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000197 New->getType()->castAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +0000198
Douglas Gregorf40863c2010-02-12 07:32:17 +0000199 // The new function declaration is only missing an empty exception
200 // specification "throw()". If the throw() specification came from a
201 // function in a system header that has C linkage, just add an empty
202 // exception specification to the "new" declaration. This is an
203 // egregious workaround for glibc, which adds throw() specifications
204 // to many libc functions as an optimization. Unfortunately, that
205 // optimization isn't permitted by the C++ standard, so we're forced
206 // to work around it here.
John McCalldb40c7f2010-12-14 08:05:40 +0000207 if (MissingEmptyExceptionSpecification && NewProto &&
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000208 (Old->getLocation().isInvalid() ||
209 Context.getSourceManager().isInSystemHeader(Old->getLocation())) &&
Douglas Gregorf40863c2010-02-12 07:32:17 +0000210 Old->isExternC()) {
John McCalldb40c7f2010-12-14 08:05:40 +0000211 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000212 EPI.ExceptionSpecType = EST_DynamicNone;
Alp Toker314cc812014-01-25 16:55:45 +0000213 QualType NewType = Context.getFunctionType(NewProto->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +0000214 NewProto->getParamTypes(), EPI);
Douglas Gregorf40863c2010-02-12 07:32:17 +0000215 New->setType(NewType);
216 return false;
217 }
218
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000219 const FunctionProtoType *OldProto =
220 Old->getType()->castAs<FunctionProtoType>();
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000221
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000222 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
223 EPI.ExceptionSpecType = OldProto->getExceptionSpecType();
224 if (EPI.ExceptionSpecType == EST_Dynamic) {
225 EPI.NumExceptions = OldProto->getNumExceptions();
226 EPI.Exceptions = OldProto->exception_begin();
227 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
228 // FIXME: We can't just take the expression from the old prototype. It
229 // likely contains references to the old prototype's parameters.
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000230 }
231
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000232 // Update the type of the function with the appropriate exception
233 // specification.
Alp Toker314cc812014-01-25 16:55:45 +0000234 QualType NewType = Context.getFunctionType(NewProto->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +0000235 NewProto->getParamTypes(), EPI);
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000236 New->setType(NewType);
237
238 // Warn about the lack of exception specification.
239 SmallString<128> ExceptionSpecString;
240 llvm::raw_svector_ostream OS(ExceptionSpecString);
241 switch (OldProto->getExceptionSpecType()) {
242 case EST_DynamicNone:
243 OS << "throw()";
244 break;
245
246 case EST_Dynamic: {
247 OS << "throw(";
248 bool OnFirstException = true;
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000249 for (const auto &E : OldProto->exceptions()) {
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000250 if (OnFirstException)
251 OnFirstException = false;
252 else
253 OS << ", ";
254
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000255 OS << E.getAsString(getPrintingPolicy());
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000256 }
257 OS << ")";
258 break;
259 }
260
261 case EST_BasicNoexcept:
262 OS << "noexcept";
263 break;
264
265 case EST_ComputedNoexcept:
266 OS << "noexcept(";
267 OldProto->getNoexceptExpr()->printPretty(OS, 0, getPrintingPolicy());
268 OS << ")";
269 break;
270
271 default:
272 llvm_unreachable("This spec type is compatible with none.");
273 }
274 OS.flush();
275
276 SourceLocation FixItLoc;
277 if (TypeSourceInfo *TSInfo = New->getTypeSourceInfo()) {
278 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
279 if (FunctionTypeLoc FTLoc = TL.getAs<FunctionTypeLoc>())
280 FixItLoc = PP.getLocForEndOfToken(FTLoc.getLocalRangeEnd());
281 }
282
283 if (FixItLoc.isInvalid())
284 Diag(New->getLocation(), diag::warn_missing_exception_specification)
285 << New << OS.str();
286 else {
287 // FIXME: This will get more complicated with C++0x
288 // late-specified return types.
289 Diag(New->getLocation(), diag::warn_missing_exception_specification)
290 << New << OS.str()
291 << FixItHint::CreateInsertion(FixItLoc, " " + OS.str().str());
292 }
293
294 if (!Old->getLocation().isInvalid())
295 Diag(Old->getLocation(), diag::note_previous_declaration);
296
297 return false;
Douglas Gregorf40863c2010-02-12 07:32:17 +0000298}
299
Sebastian Redl4915e632009-10-11 09:03:14 +0000300/// CheckEquivalentExceptionSpec - Check if the two types have equivalent
301/// exception specifications. Exception specifications are equivalent if
302/// they allow exactly the same set of exception types. It does not matter how
303/// that is achieved. See C++ [except.spec]p2.
304bool Sema::CheckEquivalentExceptionSpec(
305 const FunctionProtoType *Old, SourceLocation OldLoc,
306 const FunctionProtoType *New, SourceLocation NewLoc) {
Francois Pichet13b4e682011-03-19 23:05:18 +0000307 unsigned DiagID = diag::err_mismatched_exception_spec;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000308 if (getLangOpts().MicrosoftExt)
Hans Wennborg39a509a2014-02-05 02:37:58 +0000309 DiagID = diag::warn_mismatched_exception_spec;
310 bool Result = CheckEquivalentExceptionSpec(PDiag(DiagID),
311 PDiag(diag::note_previous_declaration), Old, OldLoc, New, NewLoc);
312
313 // In Microsoft mode, mismatching exception specifications just cause a warning.
314 if (getLangOpts().MicrosoftExt)
315 return false;
316 return Result;
Sebastian Redl4915e632009-10-11 09:03:14 +0000317}
318
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000319/// CheckEquivalentExceptionSpec - Check if the two types have compatible
320/// exception specifications. See C++ [except.spec]p3.
Richard Smith66f3ac92012-10-20 08:26:51 +0000321///
322/// \return \c false if the exception specifications match, \c true if there is
323/// a problem. If \c true is returned, either a diagnostic has already been
324/// produced or \c *MissingExceptionSpecification is set to \c true.
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000325bool Sema::CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000326 const PartialDiagnostic & NoteID,
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000327 const FunctionProtoType *Old,
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000328 SourceLocation OldLoc,
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000329 const FunctionProtoType *New,
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000330 SourceLocation NewLoc,
331 bool *MissingExceptionSpecification,
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000332 bool*MissingEmptyExceptionSpecification,
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000333 bool AllowNoexceptAllMatchWithNoSpec,
334 bool IsOperatorNew) {
John McCallf9c94092010-05-28 08:37:35 +0000335 // Just completely ignore this under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000336 if (!getLangOpts().CXXExceptions)
John McCallf9c94092010-05-28 08:37:35 +0000337 return false;
338
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000339 if (MissingExceptionSpecification)
340 *MissingExceptionSpecification = false;
341
Douglas Gregorf40863c2010-02-12 07:32:17 +0000342 if (MissingEmptyExceptionSpecification)
343 *MissingEmptyExceptionSpecification = false;
344
Richard Smithf623c962012-04-17 00:58:00 +0000345 Old = ResolveExceptionSpec(NewLoc, Old);
346 if (!Old)
347 return false;
348 New = ResolveExceptionSpec(NewLoc, New);
349 if (!New)
350 return false;
351
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000352 // C++0x [except.spec]p3: Two exception-specifications are compatible if:
353 // - both are non-throwing, regardless of their form,
354 // - both have the form noexcept(constant-expression) and the constant-
355 // expressions are equivalent,
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000356 // - both are dynamic-exception-specifications that have the same set of
357 // adjusted types.
358 //
359 // C++0x [except.spec]p12: An exception-specifcation is non-throwing if it is
360 // of the form throw(), noexcept, or noexcept(constant-expression) where the
361 // constant-expression yields true.
362 //
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000363 // C++0x [except.spec]p4: If any declaration of a function has an exception-
364 // specifier that is not a noexcept-specification allowing all exceptions,
365 // all declarations [...] of that function shall have a compatible
366 // exception-specification.
367 //
368 // That last point basically means that noexcept(false) matches no spec.
369 // It's considered when AllowNoexceptAllMatchWithNoSpec is true.
370
371 ExceptionSpecificationType OldEST = Old->getExceptionSpecType();
372 ExceptionSpecificationType NewEST = New->getExceptionSpecType();
373
Richard Smithd3b5c9082012-07-27 04:22:15 +0000374 assert(!isUnresolvedExceptionSpec(OldEST) &&
375 !isUnresolvedExceptionSpec(NewEST) &&
Richard Smith938f40b2011-06-11 17:19:42 +0000376 "Shouldn't see unknown exception specifications here");
377
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000378 // Shortcut the case where both have no spec.
379 if (OldEST == EST_None && NewEST == EST_None)
380 return false;
381
Sebastian Redl31ad7542011-03-13 17:09:40 +0000382 FunctionProtoType::NoexceptResult OldNR = Old->getNoexceptSpec(Context);
383 FunctionProtoType::NoexceptResult NewNR = New->getNoexceptSpec(Context);
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000384 if (OldNR == FunctionProtoType::NR_BadNoexcept ||
385 NewNR == FunctionProtoType::NR_BadNoexcept)
386 return false;
387
388 // Dependent noexcept specifiers are compatible with each other, but nothing
389 // else.
390 // One noexcept is compatible with another if the argument is the same
391 if (OldNR == NewNR &&
392 OldNR != FunctionProtoType::NR_NoNoexcept &&
393 NewNR != FunctionProtoType::NR_NoNoexcept)
394 return false;
395 if (OldNR != NewNR &&
396 OldNR != FunctionProtoType::NR_NoNoexcept &&
397 NewNR != FunctionProtoType::NR_NoNoexcept) {
398 Diag(NewLoc, DiagID);
399 if (NoteID.getDiagID() != 0)
400 Diag(OldLoc, NoteID);
401 return true;
Douglas Gregorf62c5292010-08-30 15:04:51 +0000402 }
403
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000404 // The MS extension throw(...) is compatible with itself.
405 if (OldEST == EST_MSAny && NewEST == EST_MSAny)
Sebastian Redl4915e632009-10-11 09:03:14 +0000406 return false;
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000407
408 // It's also compatible with no spec.
409 if ((OldEST == EST_None && NewEST == EST_MSAny) ||
410 (OldEST == EST_MSAny && NewEST == EST_None))
411 return false;
412
413 // It's also compatible with noexcept(false).
414 if (OldEST == EST_MSAny && NewNR == FunctionProtoType::NR_Throw)
415 return false;
416 if (NewEST == EST_MSAny && OldNR == FunctionProtoType::NR_Throw)
417 return false;
418
419 // As described above, noexcept(false) matches no spec only for functions.
420 if (AllowNoexceptAllMatchWithNoSpec) {
421 if (OldEST == EST_None && NewNR == FunctionProtoType::NR_Throw)
422 return false;
423 if (NewEST == EST_None && OldNR == FunctionProtoType::NR_Throw)
424 return false;
425 }
426
427 // Any non-throwing specifications are compatible.
428 bool OldNonThrowing = OldNR == FunctionProtoType::NR_Nothrow ||
429 OldEST == EST_DynamicNone;
430 bool NewNonThrowing = NewNR == FunctionProtoType::NR_Nothrow ||
431 NewEST == EST_DynamicNone;
432 if (OldNonThrowing && NewNonThrowing)
433 return false;
434
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000435 // As a special compatibility feature, under C++0x we accept no spec and
436 // throw(std::bad_alloc) as equivalent for operator new and operator new[].
437 // This is because the implicit declaration changed, but old code would break.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000438 if (getLangOpts().CPlusPlus11 && IsOperatorNew) {
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000439 const FunctionProtoType *WithExceptions = 0;
440 if (OldEST == EST_None && NewEST == EST_Dynamic)
441 WithExceptions = New;
442 else if (OldEST == EST_Dynamic && NewEST == EST_None)
443 WithExceptions = Old;
444 if (WithExceptions && WithExceptions->getNumExceptions() == 1) {
445 // One has no spec, the other throw(something). If that something is
446 // std::bad_alloc, all conditions are met.
447 QualType Exception = *WithExceptions->exception_begin();
448 if (CXXRecordDecl *ExRecord = Exception->getAsCXXRecordDecl()) {
449 IdentifierInfo* Name = ExRecord->getIdentifier();
450 if (Name && Name->getName() == "bad_alloc") {
451 // It's called bad_alloc, but is it in std?
452 DeclContext* DC = ExRecord->getDeclContext();
Sebastian Redlc34c29f2011-03-15 20:41:09 +0000453 DC = DC->getEnclosingNamespaceContext();
454 if (NamespaceDecl* NS = dyn_cast<NamespaceDecl>(DC)) {
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000455 IdentifierInfo* NSName = NS->getIdentifier();
Sebastian Redlc34c29f2011-03-15 20:41:09 +0000456 DC = DC->getParent();
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000457 if (NSName && NSName->getName() == "std" &&
Sebastian Redlc34c29f2011-03-15 20:41:09 +0000458 DC->getEnclosingNamespaceContext()->isTranslationUnit()) {
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000459 return false;
Sebastian Redlc34c29f2011-03-15 20:41:09 +0000460 }
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000461 }
462 }
463 }
464 }
465 }
466
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000467 // At this point, the only remaining valid case is two matching dynamic
468 // specifications. We return here unless both specifications are dynamic.
469 if (OldEST != EST_Dynamic || NewEST != EST_Dynamic) {
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000470 if (MissingExceptionSpecification && Old->hasExceptionSpec() &&
Douglas Gregorf40863c2010-02-12 07:32:17 +0000471 !New->hasExceptionSpec()) {
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000472 // The old type has an exception specification of some sort, but
473 // the new type does not.
474 *MissingExceptionSpecification = true;
475
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000476 if (MissingEmptyExceptionSpecification && OldNonThrowing) {
477 // The old type has a throw() or noexcept(true) exception specification
478 // and the new type has no exception specification, and the caller asked
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000479 // to handle this itself.
480 *MissingEmptyExceptionSpecification = true;
481 }
482
Douglas Gregorf40863c2010-02-12 07:32:17 +0000483 return true;
484 }
485
Sebastian Redl4915e632009-10-11 09:03:14 +0000486 Diag(NewLoc, DiagID);
Sebastian Redla44822f2009-10-14 16:09:29 +0000487 if (NoteID.getDiagID() != 0)
Sebastian Redl4915e632009-10-11 09:03:14 +0000488 Diag(OldLoc, NoteID);
489 return true;
490 }
491
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000492 assert(OldEST == EST_Dynamic && NewEST == EST_Dynamic &&
493 "Exception compatibility logic error: non-dynamic spec slipped through.");
494
Sebastian Redl4915e632009-10-11 09:03:14 +0000495 bool Success = true;
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000496 // Both have a dynamic exception spec. Collect the first set, then compare
Sebastian Redl4915e632009-10-11 09:03:14 +0000497 // to the second.
Sebastian Redl184edca2009-10-14 15:06:25 +0000498 llvm::SmallPtrSet<CanQualType, 8> OldTypes, NewTypes;
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000499 for (const auto &I : Old->exceptions())
500 OldTypes.insert(Context.getCanonicalType(I).getUnqualifiedType());
Sebastian Redl4915e632009-10-11 09:03:14 +0000501
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000502 for (const auto &I : New->exceptions()) {
503 CanQualType TypePtr = Context.getCanonicalType(I).getUnqualifiedType();
Sebastian Redl6e4c8712009-10-11 09:11:23 +0000504 if(OldTypes.count(TypePtr))
505 NewTypes.insert(TypePtr);
506 else
507 Success = false;
508 }
Sebastian Redl4915e632009-10-11 09:03:14 +0000509
Sebastian Redl6e4c8712009-10-11 09:11:23 +0000510 Success = Success && OldTypes.size() == NewTypes.size();
Sebastian Redl4915e632009-10-11 09:03:14 +0000511
512 if (Success) {
513 return false;
514 }
515 Diag(NewLoc, DiagID);
Sebastian Redla44822f2009-10-14 16:09:29 +0000516 if (NoteID.getDiagID() != 0)
Sebastian Redl4915e632009-10-11 09:03:14 +0000517 Diag(OldLoc, NoteID);
518 return true;
519}
520
521/// CheckExceptionSpecSubset - Check whether the second function type's
522/// exception specification is a subset (or equivalent) of the first function
523/// type. This is used by override and pointer assignment checks.
Sebastian Redla44822f2009-10-14 16:09:29 +0000524bool Sema::CheckExceptionSpecSubset(
525 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
Sebastian Redl4915e632009-10-11 09:03:14 +0000526 const FunctionProtoType *Superset, SourceLocation SuperLoc,
527 const FunctionProtoType *Subset, SourceLocation SubLoc) {
John McCallf9c94092010-05-28 08:37:35 +0000528
529 // Just auto-succeed under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000530 if (!getLangOpts().CXXExceptions)
John McCallf9c94092010-05-28 08:37:35 +0000531 return false;
532
Sebastian Redl4915e632009-10-11 09:03:14 +0000533 // FIXME: As usual, we could be more specific in our error messages, but
534 // that better waits until we've got types with source locations.
535
536 if (!SubLoc.isValid())
537 SubLoc = SuperLoc;
538
Richard Smithf623c962012-04-17 00:58:00 +0000539 // Resolve the exception specifications, if needed.
540 Superset = ResolveExceptionSpec(SuperLoc, Superset);
541 if (!Superset)
542 return false;
543 Subset = ResolveExceptionSpec(SubLoc, Subset);
544 if (!Subset)
545 return false;
546
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000547 ExceptionSpecificationType SuperEST = Superset->getExceptionSpecType();
548
Sebastian Redl4915e632009-10-11 09:03:14 +0000549 // If superset contains everything, we're done.
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000550 if (SuperEST == EST_None || SuperEST == EST_MSAny)
Sebastian Redl4915e632009-10-11 09:03:14 +0000551 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
552
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000553 // If there are dependent noexcept specs, assume everything is fine. Unlike
554 // with the equivalency check, this is safe in this case, because we don't
555 // want to merge declarations. Checks after instantiation will catch any
556 // omissions we make here.
557 // We also shortcut checking if a noexcept expression was bad.
558
Sebastian Redl31ad7542011-03-13 17:09:40 +0000559 FunctionProtoType::NoexceptResult SuperNR =Superset->getNoexceptSpec(Context);
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000560 if (SuperNR == FunctionProtoType::NR_BadNoexcept ||
561 SuperNR == FunctionProtoType::NR_Dependent)
562 return false;
563
564 // Another case of the superset containing everything.
565 if (SuperNR == FunctionProtoType::NR_Throw)
566 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
567
568 ExceptionSpecificationType SubEST = Subset->getExceptionSpecType();
569
Richard Smithd3b5c9082012-07-27 04:22:15 +0000570 assert(!isUnresolvedExceptionSpec(SuperEST) &&
571 !isUnresolvedExceptionSpec(SubEST) &&
Richard Smith938f40b2011-06-11 17:19:42 +0000572 "Shouldn't see unknown exception specifications here");
573
Sebastian Redl4915e632009-10-11 09:03:14 +0000574 // It does not. If the subset contains everything, we've failed.
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000575 if (SubEST == EST_None || SubEST == EST_MSAny) {
Sebastian Redl4915e632009-10-11 09:03:14 +0000576 Diag(SubLoc, DiagID);
Sebastian Redla44822f2009-10-14 16:09:29 +0000577 if (NoteID.getDiagID() != 0)
Sebastian Redl4915e632009-10-11 09:03:14 +0000578 Diag(SuperLoc, NoteID);
579 return true;
580 }
581
Sebastian Redl31ad7542011-03-13 17:09:40 +0000582 FunctionProtoType::NoexceptResult SubNR = Subset->getNoexceptSpec(Context);
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000583 if (SubNR == FunctionProtoType::NR_BadNoexcept ||
584 SubNR == FunctionProtoType::NR_Dependent)
585 return false;
586
587 // Another case of the subset containing everything.
588 if (SubNR == FunctionProtoType::NR_Throw) {
589 Diag(SubLoc, DiagID);
590 if (NoteID.getDiagID() != 0)
591 Diag(SuperLoc, NoteID);
592 return true;
593 }
594
595 // If the subset contains nothing, we're done.
596 if (SubEST == EST_DynamicNone || SubNR == FunctionProtoType::NR_Nothrow)
597 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
598
599 // Otherwise, if the superset contains nothing, we've failed.
600 if (SuperEST == EST_DynamicNone || SuperNR == FunctionProtoType::NR_Nothrow) {
601 Diag(SubLoc, DiagID);
602 if (NoteID.getDiagID() != 0)
603 Diag(SuperLoc, NoteID);
604 return true;
605 }
606
607 assert(SuperEST == EST_Dynamic && SubEST == EST_Dynamic &&
608 "Exception spec subset: non-dynamic case slipped through.");
609
610 // Neither contains everything or nothing. Do a proper comparison.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000611 for (const auto &SubI : Subset->exceptions()) {
Sebastian Redl4915e632009-10-11 09:03:14 +0000612 // Take one type from the subset.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000613 QualType CanonicalSubT = Context.getCanonicalType(SubI);
Sebastian Redl075b21d2009-10-14 14:38:54 +0000614 // Unwrap pointers and references so that we can do checks within a class
615 // hierarchy. Don't unwrap member pointers; they don't have hierarchy
616 // conversions on the pointee.
Sebastian Redl4915e632009-10-11 09:03:14 +0000617 bool SubIsPointer = false;
618 if (const ReferenceType *RefTy = CanonicalSubT->getAs<ReferenceType>())
619 CanonicalSubT = RefTy->getPointeeType();
620 if (const PointerType *PtrTy = CanonicalSubT->getAs<PointerType>()) {
621 CanonicalSubT = PtrTy->getPointeeType();
622 SubIsPointer = true;
623 }
624 bool SubIsClass = CanonicalSubT->isRecordType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000625 CanonicalSubT = CanonicalSubT.getLocalUnqualifiedType();
Sebastian Redl4915e632009-10-11 09:03:14 +0000626
627 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
628 /*DetectVirtual=*/false);
629
630 bool Contained = false;
631 // Make sure it's in the superset.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000632 for (const auto &SuperI : Superset->exceptions()) {
633 QualType CanonicalSuperT = Context.getCanonicalType(SuperI);
Sebastian Redl4915e632009-10-11 09:03:14 +0000634 // SubT must be SuperT or derived from it, or pointer or reference to
635 // such types.
636 if (const ReferenceType *RefTy = CanonicalSuperT->getAs<ReferenceType>())
637 CanonicalSuperT = RefTy->getPointeeType();
638 if (SubIsPointer) {
639 if (const PointerType *PtrTy = CanonicalSuperT->getAs<PointerType>())
640 CanonicalSuperT = PtrTy->getPointeeType();
641 else {
642 continue;
643 }
644 }
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000645 CanonicalSuperT = CanonicalSuperT.getLocalUnqualifiedType();
Sebastian Redl4915e632009-10-11 09:03:14 +0000646 // If the types are the same, move on to the next type in the subset.
647 if (CanonicalSubT == CanonicalSuperT) {
648 Contained = true;
649 break;
650 }
651
652 // Otherwise we need to check the inheritance.
653 if (!SubIsClass || !CanonicalSuperT->isRecordType())
654 continue;
655
656 Paths.clear();
657 if (!IsDerivedFrom(CanonicalSubT, CanonicalSuperT, Paths))
658 continue;
659
Douglas Gregor27ac4292010-05-21 20:29:55 +0000660 if (Paths.isAmbiguous(Context.getCanonicalType(CanonicalSuperT)))
Sebastian Redl4915e632009-10-11 09:03:14 +0000661 continue;
662
John McCall5b0829a2010-02-10 09:31:12 +0000663 // Do this check from a context without privileges.
John McCall1064d7e2010-03-16 05:22:47 +0000664 switch (CheckBaseClassAccess(SourceLocation(),
John McCall5b0829a2010-02-10 09:31:12 +0000665 CanonicalSuperT, CanonicalSubT,
666 Paths.front(),
John McCall1064d7e2010-03-16 05:22:47 +0000667 /*Diagnostic*/ 0,
John McCall5b0829a2010-02-10 09:31:12 +0000668 /*ForceCheck*/ true,
John McCall1064d7e2010-03-16 05:22:47 +0000669 /*ForceUnprivileged*/ true)) {
John McCall5b0829a2010-02-10 09:31:12 +0000670 case AR_accessible: break;
671 case AR_inaccessible: continue;
672 case AR_dependent:
673 llvm_unreachable("access check dependent for unprivileged context");
John McCall5b0829a2010-02-10 09:31:12 +0000674 case AR_delayed:
675 llvm_unreachable("access check delayed in non-declaration");
John McCall5b0829a2010-02-10 09:31:12 +0000676 }
Sebastian Redl4915e632009-10-11 09:03:14 +0000677
678 Contained = true;
679 break;
680 }
681 if (!Contained) {
682 Diag(SubLoc, DiagID);
Sebastian Redla44822f2009-10-14 16:09:29 +0000683 if (NoteID.getDiagID() != 0)
Sebastian Redl4915e632009-10-11 09:03:14 +0000684 Diag(SuperLoc, NoteID);
685 return true;
686 }
687 }
688 // We've run half the gauntlet.
689 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
690}
691
692static bool CheckSpecForTypesEquivalent(Sema &S,
Sebastian Redla44822f2009-10-14 16:09:29 +0000693 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
Sebastian Redl4915e632009-10-11 09:03:14 +0000694 QualType Target, SourceLocation TargetLoc,
695 QualType Source, SourceLocation SourceLoc)
696{
697 const FunctionProtoType *TFunc = GetUnderlyingFunction(Target);
698 if (!TFunc)
699 return false;
700 const FunctionProtoType *SFunc = GetUnderlyingFunction(Source);
701 if (!SFunc)
702 return false;
703
704 return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc,
705 SFunc, SourceLoc);
706}
707
708/// CheckParamExceptionSpec - Check if the parameter and return types of the
709/// two functions have equivalent exception specs. This is part of the
710/// assignment and override compatibility check. We do not check the parameters
711/// of parameter function pointers recursively, as no sane programmer would
712/// even be able to write such a function type.
Sebastian Redla44822f2009-10-14 16:09:29 +0000713bool Sema::CheckParamExceptionSpec(const PartialDiagnostic & NoteID,
Sebastian Redl4915e632009-10-11 09:03:14 +0000714 const FunctionProtoType *Target, SourceLocation TargetLoc,
715 const FunctionProtoType *Source, SourceLocation SourceLoc)
716{
Alp Toker314cc812014-01-25 16:55:45 +0000717 if (CheckSpecForTypesEquivalent(
718 *this, PDiag(diag::err_deep_exception_specs_differ) << 0, PDiag(),
719 Target->getReturnType(), TargetLoc, Source->getReturnType(),
720 SourceLoc))
Sebastian Redl4915e632009-10-11 09:03:14 +0000721 return true;
722
Sebastian Redla44822f2009-10-14 16:09:29 +0000723 // We shouldn't even be testing this unless the arguments are otherwise
Sebastian Redl4915e632009-10-11 09:03:14 +0000724 // compatible.
Alp Toker9cacbab2014-01-20 20:26:09 +0000725 assert(Target->getNumParams() == Source->getNumParams() &&
Sebastian Redl4915e632009-10-11 09:03:14 +0000726 "Functions have different argument counts.");
Alp Toker9cacbab2014-01-20 20:26:09 +0000727 for (unsigned i = 0, E = Target->getNumParams(); i != E; ++i) {
728 if (CheckSpecForTypesEquivalent(
729 *this, PDiag(diag::err_deep_exception_specs_differ) << 1, PDiag(),
730 Target->getParamType(i), TargetLoc, Source->getParamType(i),
731 SourceLoc))
Sebastian Redl4915e632009-10-11 09:03:14 +0000732 return true;
733 }
734 return false;
735}
736
737bool Sema::CheckExceptionSpecCompatibility(Expr *From, QualType ToType)
738{
739 // First we check for applicability.
740 // Target type must be a function, function pointer or function reference.
741 const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType);
742 if (!ToFunc)
743 return false;
744
745 // SourceType must be a function or function pointer.
746 const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType());
747 if (!FromFunc)
748 return false;
749
750 // Now we've got the correct types on both sides, check their compatibility.
751 // This means that the source of the conversion can only throw a subset of
752 // the exceptions of the target, and any exception specs on arguments or
753 // return types must be equivalent.
Douglas Gregor89336232010-03-29 23:34:08 +0000754 return CheckExceptionSpecSubset(PDiag(diag::err_incompatible_exception_specs),
755 PDiag(), ToFunc,
756 From->getSourceRange().getBegin(),
Sebastian Redl4915e632009-10-11 09:03:14 +0000757 FromFunc, SourceLocation());
758}
759
760bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
761 const CXXMethodDecl *Old) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000762 if (getLangOpts().CPlusPlus11 && isa<CXXDestructorDecl>(New)) {
Sebastian Redl645d9582011-05-20 05:57:18 +0000763 // Don't check uninstantiated template destructors at all. We can only
764 // synthesize correct specs after the template is instantiated.
765 if (New->getParent()->isDependentType())
766 return false;
767 if (New->getParent()->isBeingDefined()) {
768 // The destructor might be updated once the definition is finished. So
769 // remember it and check later.
770 DelayedDestructorExceptionSpecChecks.push_back(std::make_pair(
771 cast<CXXDestructorDecl>(New), cast<CXXDestructorDecl>(Old)));
772 return false;
773 }
Sebastian Redl623ea822011-05-19 05:13:44 +0000774 }
Francois Picheta8032e92011-05-24 02:11:43 +0000775 unsigned DiagID = diag::err_override_exception_spec;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000776 if (getLangOpts().MicrosoftExt)
Francois Picheta8032e92011-05-24 02:11:43 +0000777 DiagID = diag::warn_override_exception_spec;
778 return CheckExceptionSpecSubset(PDiag(DiagID),
Douglas Gregor89336232010-03-29 23:34:08 +0000779 PDiag(diag::note_overridden_virtual_function),
Sebastian Redl4915e632009-10-11 09:03:14 +0000780 Old->getType()->getAs<FunctionProtoType>(),
781 Old->getLocation(),
782 New->getType()->getAs<FunctionProtoType>(),
783 New->getLocation());
784}
785
Richard Smithf623c962012-04-17 00:58:00 +0000786static CanThrowResult canSubExprsThrow(Sema &S, const Expr *CE) {
787 Expr *E = const_cast<Expr*>(CE);
788 CanThrowResult R = CT_Cannot;
789 for (Expr::child_range I = E->children(); I && R != CT_Can; ++I)
790 R = mergeCanThrow(R, S.canThrow(cast<Expr>(*I)));
791 return R;
792}
793
Eli Friedman0423b762013-06-25 01:24:22 +0000794static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D) {
795 assert(D && "Expected decl");
Richard Smithf623c962012-04-17 00:58:00 +0000796
797 // See if we can get a function type from the decl somehow.
798 const ValueDecl *VD = dyn_cast<ValueDecl>(D);
799 if (!VD) // If we have no clue what we're calling, assume the worst.
800 return CT_Can;
801
802 // As an extension, we assume that __attribute__((nothrow)) functions don't
803 // throw.
804 if (isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())
805 return CT_Cannot;
806
807 QualType T = VD->getType();
808 const FunctionProtoType *FT;
809 if ((FT = T->getAs<FunctionProtoType>())) {
810 } else if (const PointerType *PT = T->getAs<PointerType>())
811 FT = PT->getPointeeType()->getAs<FunctionProtoType>();
812 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
813 FT = RT->getPointeeType()->getAs<FunctionProtoType>();
814 else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
815 FT = MT->getPointeeType()->getAs<FunctionProtoType>();
816 else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
817 FT = BT->getPointeeType()->getAs<FunctionProtoType>();
818
819 if (!FT)
820 return CT_Can;
821
822 FT = S.ResolveExceptionSpec(E->getLocStart(), FT);
823 if (!FT)
824 return CT_Can;
825
Richard Smithf623c962012-04-17 00:58:00 +0000826 return FT->isNothrow(S.Context) ? CT_Cannot : CT_Can;
827}
828
829static CanThrowResult canDynamicCastThrow(const CXXDynamicCastExpr *DC) {
830 if (DC->isTypeDependent())
831 return CT_Dependent;
832
833 if (!DC->getTypeAsWritten()->isReferenceType())
834 return CT_Cannot;
835
836 if (DC->getSubExpr()->isTypeDependent())
837 return CT_Dependent;
838
839 return DC->getCastKind() == clang::CK_Dynamic? CT_Can : CT_Cannot;
840}
841
842static CanThrowResult canTypeidThrow(Sema &S, const CXXTypeidExpr *DC) {
843 if (DC->isTypeOperand())
844 return CT_Cannot;
845
846 Expr *Op = DC->getExprOperand();
847 if (Op->isTypeDependent())
848 return CT_Dependent;
849
850 const RecordType *RT = Op->getType()->getAs<RecordType>();
851 if (!RT)
852 return CT_Cannot;
853
854 if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
855 return CT_Cannot;
856
857 if (Op->Classify(S.Context).isPRValue())
858 return CT_Cannot;
859
860 return CT_Can;
861}
862
863CanThrowResult Sema::canThrow(const Expr *E) {
864 // C++ [expr.unary.noexcept]p3:
865 // [Can throw] if in a potentially-evaluated context the expression would
866 // contain:
867 switch (E->getStmtClass()) {
868 case Expr::CXXThrowExprClass:
869 // - a potentially evaluated throw-expression
870 return CT_Can;
871
872 case Expr::CXXDynamicCastExprClass: {
873 // - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
874 // where T is a reference type, that requires a run-time check
875 CanThrowResult CT = canDynamicCastThrow(cast<CXXDynamicCastExpr>(E));
876 if (CT == CT_Can)
877 return CT;
878 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
879 }
880
881 case Expr::CXXTypeidExprClass:
882 // - a potentially evaluated typeid expression applied to a glvalue
883 // expression whose type is a polymorphic class type
884 return canTypeidThrow(*this, cast<CXXTypeidExpr>(E));
885
886 // - a potentially evaluated call to a function, member function, function
887 // pointer, or member function pointer that does not have a non-throwing
888 // exception-specification
889 case Expr::CallExprClass:
890 case Expr::CXXMemberCallExprClass:
891 case Expr::CXXOperatorCallExprClass:
892 case Expr::UserDefinedLiteralClass: {
893 const CallExpr *CE = cast<CallExpr>(E);
894 CanThrowResult CT;
895 if (E->isTypeDependent())
896 CT = CT_Dependent;
897 else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens()))
898 CT = CT_Cannot;
Eli Friedman5a8738f2013-06-25 01:55:41 +0000899 else if (CE->getCalleeDecl())
Richard Smithf623c962012-04-17 00:58:00 +0000900 CT = canCalleeThrow(*this, E, CE->getCalleeDecl());
Eli Friedman5a8738f2013-06-25 01:55:41 +0000901 else
902 CT = CT_Can;
Richard Smithf623c962012-04-17 00:58:00 +0000903 if (CT == CT_Can)
904 return CT;
905 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
906 }
907
908 case Expr::CXXConstructExprClass:
909 case Expr::CXXTemporaryObjectExprClass: {
910 CanThrowResult CT = canCalleeThrow(*this, E,
911 cast<CXXConstructExpr>(E)->getConstructor());
912 if (CT == CT_Can)
913 return CT;
914 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
915 }
916
917 case Expr::LambdaExprClass: {
918 const LambdaExpr *Lambda = cast<LambdaExpr>(E);
919 CanThrowResult CT = CT_Cannot;
920 for (LambdaExpr::capture_init_iterator Cap = Lambda->capture_init_begin(),
921 CapEnd = Lambda->capture_init_end();
922 Cap != CapEnd; ++Cap)
923 CT = mergeCanThrow(CT, canThrow(*Cap));
924 return CT;
925 }
926
927 case Expr::CXXNewExprClass: {
928 CanThrowResult CT;
929 if (E->isTypeDependent())
930 CT = CT_Dependent;
931 else
932 CT = canCalleeThrow(*this, E, cast<CXXNewExpr>(E)->getOperatorNew());
933 if (CT == CT_Can)
934 return CT;
935 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
936 }
937
938 case Expr::CXXDeleteExprClass: {
939 CanThrowResult CT;
940 QualType DTy = cast<CXXDeleteExpr>(E)->getDestroyedType();
941 if (DTy.isNull() || DTy->isDependentType()) {
942 CT = CT_Dependent;
943 } else {
944 CT = canCalleeThrow(*this, E,
945 cast<CXXDeleteExpr>(E)->getOperatorDelete());
946 if (const RecordType *RT = DTy->getAs<RecordType>()) {
947 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedman0423b762013-06-25 01:24:22 +0000948 const CXXDestructorDecl *DD = RD->getDestructor();
949 if (DD)
950 CT = mergeCanThrow(CT, canCalleeThrow(*this, E, DD));
Richard Smithf623c962012-04-17 00:58:00 +0000951 }
952 if (CT == CT_Can)
953 return CT;
954 }
955 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
956 }
957
958 case Expr::CXXBindTemporaryExprClass: {
959 // The bound temporary has to be destroyed again, which might throw.
960 CanThrowResult CT = canCalleeThrow(*this, E,
961 cast<CXXBindTemporaryExpr>(E)->getTemporary()->getDestructor());
962 if (CT == CT_Can)
963 return CT;
964 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
965 }
966
967 // ObjC message sends are like function calls, but never have exception
968 // specs.
969 case Expr::ObjCMessageExprClass:
970 case Expr::ObjCPropertyRefExprClass:
971 case Expr::ObjCSubscriptRefExprClass:
972 return CT_Can;
973
974 // All the ObjC literals that are implemented as calls are
975 // potentially throwing unless we decide to close off that
976 // possibility.
977 case Expr::ObjCArrayLiteralClass:
978 case Expr::ObjCDictionaryLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +0000979 case Expr::ObjCBoxedExprClass:
Richard Smithf623c962012-04-17 00:58:00 +0000980 return CT_Can;
981
982 // Many other things have subexpressions, so we have to test those.
983 // Some are simple:
984 case Expr::ConditionalOperatorClass:
985 case Expr::CompoundLiteralExprClass:
986 case Expr::CXXConstCastExprClass:
Richard Smithf623c962012-04-17 00:58:00 +0000987 case Expr::CXXReinterpretCastExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +0000988 case Expr::CXXStdInitializerListExprClass:
Richard Smithf623c962012-04-17 00:58:00 +0000989 case Expr::DesignatedInitExprClass:
990 case Expr::ExprWithCleanupsClass:
991 case Expr::ExtVectorElementExprClass:
992 case Expr::InitListExprClass:
993 case Expr::MemberExprClass:
994 case Expr::ObjCIsaExprClass:
995 case Expr::ObjCIvarRefExprClass:
996 case Expr::ParenExprClass:
997 case Expr::ParenListExprClass:
998 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +0000999 case Expr::ConvertVectorExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001000 case Expr::VAArgExprClass:
1001 return canSubExprsThrow(*this, E);
1002
1003 // Some might be dependent for other reasons.
1004 case Expr::ArraySubscriptExprClass:
1005 case Expr::BinaryOperatorClass:
1006 case Expr::CompoundAssignOperatorClass:
1007 case Expr::CStyleCastExprClass:
1008 case Expr::CXXStaticCastExprClass:
1009 case Expr::CXXFunctionalCastExprClass:
1010 case Expr::ImplicitCastExprClass:
1011 case Expr::MaterializeTemporaryExprClass:
1012 case Expr::UnaryOperatorClass: {
1013 CanThrowResult CT = E->isTypeDependent() ? CT_Dependent : CT_Cannot;
1014 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1015 }
1016
1017 // FIXME: We should handle StmtExpr, but that opens a MASSIVE can of worms.
1018 case Expr::StmtExprClass:
1019 return CT_Can;
1020
Richard Smith852c9db2013-04-20 22:23:05 +00001021 case Expr::CXXDefaultArgExprClass:
1022 return canThrow(cast<CXXDefaultArgExpr>(E)->getExpr());
1023
1024 case Expr::CXXDefaultInitExprClass:
1025 return canThrow(cast<CXXDefaultInitExpr>(E)->getExpr());
1026
Richard Smithf623c962012-04-17 00:58:00 +00001027 case Expr::ChooseExprClass:
1028 if (E->isTypeDependent() || E->isValueDependent())
1029 return CT_Dependent;
Eli Friedman75807f22013-07-20 00:40:58 +00001030 return canThrow(cast<ChooseExpr>(E)->getChosenSubExpr());
Richard Smithf623c962012-04-17 00:58:00 +00001031
1032 case Expr::GenericSelectionExprClass:
1033 if (cast<GenericSelectionExpr>(E)->isResultDependent())
1034 return CT_Dependent;
1035 return canThrow(cast<GenericSelectionExpr>(E)->getResultExpr());
1036
1037 // Some expressions are always dependent.
1038 case Expr::CXXDependentScopeMemberExprClass:
1039 case Expr::CXXUnresolvedConstructExprClass:
1040 case Expr::DependentScopeDeclRefExprClass:
1041 return CT_Dependent;
1042
1043 case Expr::AsTypeExprClass:
1044 case Expr::BinaryConditionalOperatorClass:
1045 case Expr::BlockExprClass:
1046 case Expr::CUDAKernelCallExprClass:
1047 case Expr::DeclRefExprClass:
1048 case Expr::ObjCBridgedCastExprClass:
1049 case Expr::ObjCIndirectCopyRestoreExprClass:
1050 case Expr::ObjCProtocolExprClass:
1051 case Expr::ObjCSelectorExprClass:
1052 case Expr::OffsetOfExprClass:
1053 case Expr::PackExpansionExprClass:
1054 case Expr::PseudoObjectExprClass:
1055 case Expr::SubstNonTypeTemplateParmExprClass:
1056 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00001057 case Expr::FunctionParmPackExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001058 case Expr::UnaryExprOrTypeTraitExprClass:
1059 case Expr::UnresolvedLookupExprClass:
1060 case Expr::UnresolvedMemberExprClass:
1061 // FIXME: Can any of the above throw? If so, when?
1062 return CT_Cannot;
1063
1064 case Expr::AddrLabelExprClass:
1065 case Expr::ArrayTypeTraitExprClass:
1066 case Expr::AtomicExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001067 case Expr::TypeTraitExprClass:
1068 case Expr::CXXBoolLiteralExprClass:
1069 case Expr::CXXNoexceptExprClass:
1070 case Expr::CXXNullPtrLiteralExprClass:
1071 case Expr::CXXPseudoDestructorExprClass:
1072 case Expr::CXXScalarValueInitExprClass:
1073 case Expr::CXXThisExprClass:
1074 case Expr::CXXUuidofExprClass:
1075 case Expr::CharacterLiteralClass:
1076 case Expr::ExpressionTraitExprClass:
1077 case Expr::FloatingLiteralClass:
1078 case Expr::GNUNullExprClass:
1079 case Expr::ImaginaryLiteralClass:
1080 case Expr::ImplicitValueInitExprClass:
1081 case Expr::IntegerLiteralClass:
1082 case Expr::ObjCEncodeExprClass:
1083 case Expr::ObjCStringLiteralClass:
1084 case Expr::ObjCBoolLiteralExprClass:
1085 case Expr::OpaqueValueExprClass:
1086 case Expr::PredefinedExprClass:
1087 case Expr::SizeOfPackExprClass:
1088 case Expr::StringLiteralClass:
Richard Smithf623c962012-04-17 00:58:00 +00001089 // These expressions can never throw.
1090 return CT_Cannot;
1091
John McCall5e77d762013-04-16 07:28:30 +00001092 case Expr::MSPropertyRefExprClass:
1093 llvm_unreachable("Invalid class for expression");
1094
Richard Smithf623c962012-04-17 00:58:00 +00001095#define STMT(CLASS, PARENT) case Expr::CLASS##Class:
1096#define STMT_RANGE(Base, First, Last)
1097#define LAST_STMT_RANGE(BASE, FIRST, LAST)
1098#define EXPR(CLASS, PARENT)
1099#define ABSTRACT_STMT(STMT)
1100#include "clang/AST/StmtNodes.inc"
1101 case Expr::NoStmtClass:
1102 llvm_unreachable("Invalid class for expression");
1103 }
1104 llvm_unreachable("Bogus StmtClass");
1105}
1106
Sebastian Redl4915e632009-10-11 09:03:14 +00001107} // end namespace clang