blob: 1c2a8dbc3012750d4d7db2d37cbac01a095d8987 [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;
249 for (FunctionProtoType::exception_iterator E = OldProto->exception_begin(),
250 EEnd = OldProto->exception_end();
251 E != EEnd;
252 ++E) {
253 if (OnFirstException)
254 OnFirstException = false;
255 else
256 OS << ", ";
257
258 OS << E->getAsString(getPrintingPolicy());
259 }
260 OS << ")";
261 break;
262 }
263
264 case EST_BasicNoexcept:
265 OS << "noexcept";
266 break;
267
268 case EST_ComputedNoexcept:
269 OS << "noexcept(";
270 OldProto->getNoexceptExpr()->printPretty(OS, 0, getPrintingPolicy());
271 OS << ")";
272 break;
273
274 default:
275 llvm_unreachable("This spec type is compatible with none.");
276 }
277 OS.flush();
278
279 SourceLocation FixItLoc;
280 if (TypeSourceInfo *TSInfo = New->getTypeSourceInfo()) {
281 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
282 if (FunctionTypeLoc FTLoc = TL.getAs<FunctionTypeLoc>())
283 FixItLoc = PP.getLocForEndOfToken(FTLoc.getLocalRangeEnd());
284 }
285
286 if (FixItLoc.isInvalid())
287 Diag(New->getLocation(), diag::warn_missing_exception_specification)
288 << New << OS.str();
289 else {
290 // FIXME: This will get more complicated with C++0x
291 // late-specified return types.
292 Diag(New->getLocation(), diag::warn_missing_exception_specification)
293 << New << OS.str()
294 << FixItHint::CreateInsertion(FixItLoc, " " + OS.str().str());
295 }
296
297 if (!Old->getLocation().isInvalid())
298 Diag(Old->getLocation(), diag::note_previous_declaration);
299
300 return false;
Douglas Gregorf40863c2010-02-12 07:32:17 +0000301}
302
Sebastian Redl4915e632009-10-11 09:03:14 +0000303/// CheckEquivalentExceptionSpec - Check if the two types have equivalent
304/// exception specifications. Exception specifications are equivalent if
305/// they allow exactly the same set of exception types. It does not matter how
306/// that is achieved. See C++ [except.spec]p2.
307bool Sema::CheckEquivalentExceptionSpec(
308 const FunctionProtoType *Old, SourceLocation OldLoc,
309 const FunctionProtoType *New, SourceLocation NewLoc) {
Francois Pichet13b4e682011-03-19 23:05:18 +0000310 unsigned DiagID = diag::err_mismatched_exception_spec;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000311 if (getLangOpts().MicrosoftExt)
Hans Wennborg39a509a2014-02-05 02:37:58 +0000312 DiagID = diag::warn_mismatched_exception_spec;
313 bool Result = CheckEquivalentExceptionSpec(PDiag(DiagID),
314 PDiag(diag::note_previous_declaration), Old, OldLoc, New, NewLoc);
315
316 // In Microsoft mode, mismatching exception specifications just cause a warning.
317 if (getLangOpts().MicrosoftExt)
318 return false;
319 return Result;
Sebastian Redl4915e632009-10-11 09:03:14 +0000320}
321
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000322/// CheckEquivalentExceptionSpec - Check if the two types have compatible
323/// exception specifications. See C++ [except.spec]p3.
Richard Smith66f3ac92012-10-20 08:26:51 +0000324///
325/// \return \c false if the exception specifications match, \c true if there is
326/// a problem. If \c true is returned, either a diagnostic has already been
327/// produced or \c *MissingExceptionSpecification is set to \c true.
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000328bool Sema::CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000329 const PartialDiagnostic & NoteID,
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000330 const FunctionProtoType *Old,
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000331 SourceLocation OldLoc,
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000332 const FunctionProtoType *New,
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000333 SourceLocation NewLoc,
334 bool *MissingExceptionSpecification,
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000335 bool*MissingEmptyExceptionSpecification,
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000336 bool AllowNoexceptAllMatchWithNoSpec,
337 bool IsOperatorNew) {
John McCallf9c94092010-05-28 08:37:35 +0000338 // Just completely ignore this under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000339 if (!getLangOpts().CXXExceptions)
John McCallf9c94092010-05-28 08:37:35 +0000340 return false;
341
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000342 if (MissingExceptionSpecification)
343 *MissingExceptionSpecification = false;
344
Douglas Gregorf40863c2010-02-12 07:32:17 +0000345 if (MissingEmptyExceptionSpecification)
346 *MissingEmptyExceptionSpecification = false;
347
Richard Smithf623c962012-04-17 00:58:00 +0000348 Old = ResolveExceptionSpec(NewLoc, Old);
349 if (!Old)
350 return false;
351 New = ResolveExceptionSpec(NewLoc, New);
352 if (!New)
353 return false;
354
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000355 // C++0x [except.spec]p3: Two exception-specifications are compatible if:
356 // - both are non-throwing, regardless of their form,
357 // - both have the form noexcept(constant-expression) and the constant-
358 // expressions are equivalent,
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000359 // - both are dynamic-exception-specifications that have the same set of
360 // adjusted types.
361 //
362 // C++0x [except.spec]p12: An exception-specifcation is non-throwing if it is
363 // of the form throw(), noexcept, or noexcept(constant-expression) where the
364 // constant-expression yields true.
365 //
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000366 // C++0x [except.spec]p4: If any declaration of a function has an exception-
367 // specifier that is not a noexcept-specification allowing all exceptions,
368 // all declarations [...] of that function shall have a compatible
369 // exception-specification.
370 //
371 // That last point basically means that noexcept(false) matches no spec.
372 // It's considered when AllowNoexceptAllMatchWithNoSpec is true.
373
374 ExceptionSpecificationType OldEST = Old->getExceptionSpecType();
375 ExceptionSpecificationType NewEST = New->getExceptionSpecType();
376
Richard Smithd3b5c9082012-07-27 04:22:15 +0000377 assert(!isUnresolvedExceptionSpec(OldEST) &&
378 !isUnresolvedExceptionSpec(NewEST) &&
Richard Smith938f40b2011-06-11 17:19:42 +0000379 "Shouldn't see unknown exception specifications here");
380
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000381 // Shortcut the case where both have no spec.
382 if (OldEST == EST_None && NewEST == EST_None)
383 return false;
384
Sebastian Redl31ad7542011-03-13 17:09:40 +0000385 FunctionProtoType::NoexceptResult OldNR = Old->getNoexceptSpec(Context);
386 FunctionProtoType::NoexceptResult NewNR = New->getNoexceptSpec(Context);
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000387 if (OldNR == FunctionProtoType::NR_BadNoexcept ||
388 NewNR == FunctionProtoType::NR_BadNoexcept)
389 return false;
390
391 // Dependent noexcept specifiers are compatible with each other, but nothing
392 // else.
393 // One noexcept is compatible with another if the argument is the same
394 if (OldNR == NewNR &&
395 OldNR != FunctionProtoType::NR_NoNoexcept &&
396 NewNR != FunctionProtoType::NR_NoNoexcept)
397 return false;
398 if (OldNR != NewNR &&
399 OldNR != FunctionProtoType::NR_NoNoexcept &&
400 NewNR != FunctionProtoType::NR_NoNoexcept) {
401 Diag(NewLoc, DiagID);
402 if (NoteID.getDiagID() != 0)
403 Diag(OldLoc, NoteID);
404 return true;
Douglas Gregorf62c5292010-08-30 15:04:51 +0000405 }
406
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000407 // The MS extension throw(...) is compatible with itself.
408 if (OldEST == EST_MSAny && NewEST == EST_MSAny)
Sebastian Redl4915e632009-10-11 09:03:14 +0000409 return false;
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000410
411 // It's also compatible with no spec.
412 if ((OldEST == EST_None && NewEST == EST_MSAny) ||
413 (OldEST == EST_MSAny && NewEST == EST_None))
414 return false;
415
416 // It's also compatible with noexcept(false).
417 if (OldEST == EST_MSAny && NewNR == FunctionProtoType::NR_Throw)
418 return false;
419 if (NewEST == EST_MSAny && OldNR == FunctionProtoType::NR_Throw)
420 return false;
421
422 // As described above, noexcept(false) matches no spec only for functions.
423 if (AllowNoexceptAllMatchWithNoSpec) {
424 if (OldEST == EST_None && NewNR == FunctionProtoType::NR_Throw)
425 return false;
426 if (NewEST == EST_None && OldNR == FunctionProtoType::NR_Throw)
427 return false;
428 }
429
430 // Any non-throwing specifications are compatible.
431 bool OldNonThrowing = OldNR == FunctionProtoType::NR_Nothrow ||
432 OldEST == EST_DynamicNone;
433 bool NewNonThrowing = NewNR == FunctionProtoType::NR_Nothrow ||
434 NewEST == EST_DynamicNone;
435 if (OldNonThrowing && NewNonThrowing)
436 return false;
437
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000438 // As a special compatibility feature, under C++0x we accept no spec and
439 // throw(std::bad_alloc) as equivalent for operator new and operator new[].
440 // This is because the implicit declaration changed, but old code would break.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000441 if (getLangOpts().CPlusPlus11 && IsOperatorNew) {
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000442 const FunctionProtoType *WithExceptions = 0;
443 if (OldEST == EST_None && NewEST == EST_Dynamic)
444 WithExceptions = New;
445 else if (OldEST == EST_Dynamic && NewEST == EST_None)
446 WithExceptions = Old;
447 if (WithExceptions && WithExceptions->getNumExceptions() == 1) {
448 // One has no spec, the other throw(something). If that something is
449 // std::bad_alloc, all conditions are met.
450 QualType Exception = *WithExceptions->exception_begin();
451 if (CXXRecordDecl *ExRecord = Exception->getAsCXXRecordDecl()) {
452 IdentifierInfo* Name = ExRecord->getIdentifier();
453 if (Name && Name->getName() == "bad_alloc") {
454 // It's called bad_alloc, but is it in std?
455 DeclContext* DC = ExRecord->getDeclContext();
Sebastian Redlc34c29f2011-03-15 20:41:09 +0000456 DC = DC->getEnclosingNamespaceContext();
457 if (NamespaceDecl* NS = dyn_cast<NamespaceDecl>(DC)) {
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000458 IdentifierInfo* NSName = NS->getIdentifier();
Sebastian Redlc34c29f2011-03-15 20:41:09 +0000459 DC = DC->getParent();
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000460 if (NSName && NSName->getName() == "std" &&
Sebastian Redlc34c29f2011-03-15 20:41:09 +0000461 DC->getEnclosingNamespaceContext()->isTranslationUnit()) {
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000462 return false;
Sebastian Redlc34c29f2011-03-15 20:41:09 +0000463 }
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000464 }
465 }
466 }
467 }
468 }
469
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000470 // At this point, the only remaining valid case is two matching dynamic
471 // specifications. We return here unless both specifications are dynamic.
472 if (OldEST != EST_Dynamic || NewEST != EST_Dynamic) {
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000473 if (MissingExceptionSpecification && Old->hasExceptionSpec() &&
Douglas Gregorf40863c2010-02-12 07:32:17 +0000474 !New->hasExceptionSpec()) {
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000475 // The old type has an exception specification of some sort, but
476 // the new type does not.
477 *MissingExceptionSpecification = true;
478
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000479 if (MissingEmptyExceptionSpecification && OldNonThrowing) {
480 // The old type has a throw() or noexcept(true) exception specification
481 // and the new type has no exception specification, and the caller asked
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000482 // to handle this itself.
483 *MissingEmptyExceptionSpecification = true;
484 }
485
Douglas Gregorf40863c2010-02-12 07:32:17 +0000486 return true;
487 }
488
Sebastian Redl4915e632009-10-11 09:03:14 +0000489 Diag(NewLoc, DiagID);
Sebastian Redla44822f2009-10-14 16:09:29 +0000490 if (NoteID.getDiagID() != 0)
Sebastian Redl4915e632009-10-11 09:03:14 +0000491 Diag(OldLoc, NoteID);
492 return true;
493 }
494
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000495 assert(OldEST == EST_Dynamic && NewEST == EST_Dynamic &&
496 "Exception compatibility logic error: non-dynamic spec slipped through.");
497
Sebastian Redl4915e632009-10-11 09:03:14 +0000498 bool Success = true;
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000499 // Both have a dynamic exception spec. Collect the first set, then compare
Sebastian Redl4915e632009-10-11 09:03:14 +0000500 // to the second.
Sebastian Redl184edca2009-10-14 15:06:25 +0000501 llvm::SmallPtrSet<CanQualType, 8> OldTypes, NewTypes;
Sebastian Redl4915e632009-10-11 09:03:14 +0000502 for (FunctionProtoType::exception_iterator I = Old->exception_begin(),
503 E = Old->exception_end(); I != E; ++I)
Sebastian Redl184edca2009-10-14 15:06:25 +0000504 OldTypes.insert(Context.getCanonicalType(*I).getUnqualifiedType());
Sebastian Redl4915e632009-10-11 09:03:14 +0000505
506 for (FunctionProtoType::exception_iterator I = New->exception_begin(),
Sebastian Redl6e4c8712009-10-11 09:11:23 +0000507 E = New->exception_end(); I != E && Success; ++I) {
Sebastian Redl184edca2009-10-14 15:06:25 +0000508 CanQualType TypePtr = Context.getCanonicalType(*I).getUnqualifiedType();
Sebastian Redl6e4c8712009-10-11 09:11:23 +0000509 if(OldTypes.count(TypePtr))
510 NewTypes.insert(TypePtr);
511 else
512 Success = false;
513 }
Sebastian Redl4915e632009-10-11 09:03:14 +0000514
Sebastian Redl6e4c8712009-10-11 09:11:23 +0000515 Success = Success && OldTypes.size() == NewTypes.size();
Sebastian Redl4915e632009-10-11 09:03:14 +0000516
517 if (Success) {
518 return false;
519 }
520 Diag(NewLoc, DiagID);
Sebastian Redla44822f2009-10-14 16:09:29 +0000521 if (NoteID.getDiagID() != 0)
Sebastian Redl4915e632009-10-11 09:03:14 +0000522 Diag(OldLoc, NoteID);
523 return true;
524}
525
526/// CheckExceptionSpecSubset - Check whether the second function type's
527/// exception specification is a subset (or equivalent) of the first function
528/// type. This is used by override and pointer assignment checks.
Sebastian Redla44822f2009-10-14 16:09:29 +0000529bool Sema::CheckExceptionSpecSubset(
530 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
Sebastian Redl4915e632009-10-11 09:03:14 +0000531 const FunctionProtoType *Superset, SourceLocation SuperLoc,
532 const FunctionProtoType *Subset, SourceLocation SubLoc) {
John McCallf9c94092010-05-28 08:37:35 +0000533
534 // Just auto-succeed under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000535 if (!getLangOpts().CXXExceptions)
John McCallf9c94092010-05-28 08:37:35 +0000536 return false;
537
Sebastian Redl4915e632009-10-11 09:03:14 +0000538 // FIXME: As usual, we could be more specific in our error messages, but
539 // that better waits until we've got types with source locations.
540
541 if (!SubLoc.isValid())
542 SubLoc = SuperLoc;
543
Richard Smithf623c962012-04-17 00:58:00 +0000544 // Resolve the exception specifications, if needed.
545 Superset = ResolveExceptionSpec(SuperLoc, Superset);
546 if (!Superset)
547 return false;
548 Subset = ResolveExceptionSpec(SubLoc, Subset);
549 if (!Subset)
550 return false;
551
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000552 ExceptionSpecificationType SuperEST = Superset->getExceptionSpecType();
553
Sebastian Redl4915e632009-10-11 09:03:14 +0000554 // If superset contains everything, we're done.
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000555 if (SuperEST == EST_None || SuperEST == EST_MSAny)
Sebastian Redl4915e632009-10-11 09:03:14 +0000556 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
557
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000558 // If there are dependent noexcept specs, assume everything is fine. Unlike
559 // with the equivalency check, this is safe in this case, because we don't
560 // want to merge declarations. Checks after instantiation will catch any
561 // omissions we make here.
562 // We also shortcut checking if a noexcept expression was bad.
563
Sebastian Redl31ad7542011-03-13 17:09:40 +0000564 FunctionProtoType::NoexceptResult SuperNR =Superset->getNoexceptSpec(Context);
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000565 if (SuperNR == FunctionProtoType::NR_BadNoexcept ||
566 SuperNR == FunctionProtoType::NR_Dependent)
567 return false;
568
569 // Another case of the superset containing everything.
570 if (SuperNR == FunctionProtoType::NR_Throw)
571 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
572
573 ExceptionSpecificationType SubEST = Subset->getExceptionSpecType();
574
Richard Smithd3b5c9082012-07-27 04:22:15 +0000575 assert(!isUnresolvedExceptionSpec(SuperEST) &&
576 !isUnresolvedExceptionSpec(SubEST) &&
Richard Smith938f40b2011-06-11 17:19:42 +0000577 "Shouldn't see unknown exception specifications here");
578
Sebastian Redl4915e632009-10-11 09:03:14 +0000579 // It does not. If the subset contains everything, we've failed.
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000580 if (SubEST == EST_None || SubEST == EST_MSAny) {
Sebastian Redl4915e632009-10-11 09:03:14 +0000581 Diag(SubLoc, DiagID);
Sebastian Redla44822f2009-10-14 16:09:29 +0000582 if (NoteID.getDiagID() != 0)
Sebastian Redl4915e632009-10-11 09:03:14 +0000583 Diag(SuperLoc, NoteID);
584 return true;
585 }
586
Sebastian Redl31ad7542011-03-13 17:09:40 +0000587 FunctionProtoType::NoexceptResult SubNR = Subset->getNoexceptSpec(Context);
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000588 if (SubNR == FunctionProtoType::NR_BadNoexcept ||
589 SubNR == FunctionProtoType::NR_Dependent)
590 return false;
591
592 // Another case of the subset containing everything.
593 if (SubNR == FunctionProtoType::NR_Throw) {
594 Diag(SubLoc, DiagID);
595 if (NoteID.getDiagID() != 0)
596 Diag(SuperLoc, NoteID);
597 return true;
598 }
599
600 // If the subset contains nothing, we're done.
601 if (SubEST == EST_DynamicNone || SubNR == FunctionProtoType::NR_Nothrow)
602 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
603
604 // Otherwise, if the superset contains nothing, we've failed.
605 if (SuperEST == EST_DynamicNone || SuperNR == FunctionProtoType::NR_Nothrow) {
606 Diag(SubLoc, DiagID);
607 if (NoteID.getDiagID() != 0)
608 Diag(SuperLoc, NoteID);
609 return true;
610 }
611
612 assert(SuperEST == EST_Dynamic && SubEST == EST_Dynamic &&
613 "Exception spec subset: non-dynamic case slipped through.");
614
615 // Neither contains everything or nothing. Do a proper comparison.
Sebastian Redl4915e632009-10-11 09:03:14 +0000616 for (FunctionProtoType::exception_iterator SubI = Subset->exception_begin(),
617 SubE = Subset->exception_end(); SubI != SubE; ++SubI) {
618 // Take one type from the subset.
619 QualType CanonicalSubT = Context.getCanonicalType(*SubI);
Sebastian Redl075b21d2009-10-14 14:38:54 +0000620 // Unwrap pointers and references so that we can do checks within a class
621 // hierarchy. Don't unwrap member pointers; they don't have hierarchy
622 // conversions on the pointee.
Sebastian Redl4915e632009-10-11 09:03:14 +0000623 bool SubIsPointer = false;
624 if (const ReferenceType *RefTy = CanonicalSubT->getAs<ReferenceType>())
625 CanonicalSubT = RefTy->getPointeeType();
626 if (const PointerType *PtrTy = CanonicalSubT->getAs<PointerType>()) {
627 CanonicalSubT = PtrTy->getPointeeType();
628 SubIsPointer = true;
629 }
630 bool SubIsClass = CanonicalSubT->isRecordType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000631 CanonicalSubT = CanonicalSubT.getLocalUnqualifiedType();
Sebastian Redl4915e632009-10-11 09:03:14 +0000632
633 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
634 /*DetectVirtual=*/false);
635
636 bool Contained = false;
637 // Make sure it's in the superset.
638 for (FunctionProtoType::exception_iterator SuperI =
639 Superset->exception_begin(), SuperE = Superset->exception_end();
640 SuperI != SuperE; ++SuperI) {
641 QualType CanonicalSuperT = Context.getCanonicalType(*SuperI);
642 // SubT must be SuperT or derived from it, or pointer or reference to
643 // such types.
644 if (const ReferenceType *RefTy = CanonicalSuperT->getAs<ReferenceType>())
645 CanonicalSuperT = RefTy->getPointeeType();
646 if (SubIsPointer) {
647 if (const PointerType *PtrTy = CanonicalSuperT->getAs<PointerType>())
648 CanonicalSuperT = PtrTy->getPointeeType();
649 else {
650 continue;
651 }
652 }
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000653 CanonicalSuperT = CanonicalSuperT.getLocalUnqualifiedType();
Sebastian Redl4915e632009-10-11 09:03:14 +0000654 // If the types are the same, move on to the next type in the subset.
655 if (CanonicalSubT == CanonicalSuperT) {
656 Contained = true;
657 break;
658 }
659
660 // Otherwise we need to check the inheritance.
661 if (!SubIsClass || !CanonicalSuperT->isRecordType())
662 continue;
663
664 Paths.clear();
665 if (!IsDerivedFrom(CanonicalSubT, CanonicalSuperT, Paths))
666 continue;
667
Douglas Gregor27ac4292010-05-21 20:29:55 +0000668 if (Paths.isAmbiguous(Context.getCanonicalType(CanonicalSuperT)))
Sebastian Redl4915e632009-10-11 09:03:14 +0000669 continue;
670
John McCall5b0829a2010-02-10 09:31:12 +0000671 // Do this check from a context without privileges.
John McCall1064d7e2010-03-16 05:22:47 +0000672 switch (CheckBaseClassAccess(SourceLocation(),
John McCall5b0829a2010-02-10 09:31:12 +0000673 CanonicalSuperT, CanonicalSubT,
674 Paths.front(),
John McCall1064d7e2010-03-16 05:22:47 +0000675 /*Diagnostic*/ 0,
John McCall5b0829a2010-02-10 09:31:12 +0000676 /*ForceCheck*/ true,
John McCall1064d7e2010-03-16 05:22:47 +0000677 /*ForceUnprivileged*/ true)) {
John McCall5b0829a2010-02-10 09:31:12 +0000678 case AR_accessible: break;
679 case AR_inaccessible: continue;
680 case AR_dependent:
681 llvm_unreachable("access check dependent for unprivileged context");
John McCall5b0829a2010-02-10 09:31:12 +0000682 case AR_delayed:
683 llvm_unreachable("access check delayed in non-declaration");
John McCall5b0829a2010-02-10 09:31:12 +0000684 }
Sebastian Redl4915e632009-10-11 09:03:14 +0000685
686 Contained = true;
687 break;
688 }
689 if (!Contained) {
690 Diag(SubLoc, DiagID);
Sebastian Redla44822f2009-10-14 16:09:29 +0000691 if (NoteID.getDiagID() != 0)
Sebastian Redl4915e632009-10-11 09:03:14 +0000692 Diag(SuperLoc, NoteID);
693 return true;
694 }
695 }
696 // We've run half the gauntlet.
697 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
698}
699
700static bool CheckSpecForTypesEquivalent(Sema &S,
Sebastian Redla44822f2009-10-14 16:09:29 +0000701 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
Sebastian Redl4915e632009-10-11 09:03:14 +0000702 QualType Target, SourceLocation TargetLoc,
703 QualType Source, SourceLocation SourceLoc)
704{
705 const FunctionProtoType *TFunc = GetUnderlyingFunction(Target);
706 if (!TFunc)
707 return false;
708 const FunctionProtoType *SFunc = GetUnderlyingFunction(Source);
709 if (!SFunc)
710 return false;
711
712 return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc,
713 SFunc, SourceLoc);
714}
715
716/// CheckParamExceptionSpec - Check if the parameter and return types of the
717/// two functions have equivalent exception specs. This is part of the
718/// assignment and override compatibility check. We do not check the parameters
719/// of parameter function pointers recursively, as no sane programmer would
720/// even be able to write such a function type.
Sebastian Redla44822f2009-10-14 16:09:29 +0000721bool Sema::CheckParamExceptionSpec(const PartialDiagnostic & NoteID,
Sebastian Redl4915e632009-10-11 09:03:14 +0000722 const FunctionProtoType *Target, SourceLocation TargetLoc,
723 const FunctionProtoType *Source, SourceLocation SourceLoc)
724{
Alp Toker314cc812014-01-25 16:55:45 +0000725 if (CheckSpecForTypesEquivalent(
726 *this, PDiag(diag::err_deep_exception_specs_differ) << 0, PDiag(),
727 Target->getReturnType(), TargetLoc, Source->getReturnType(),
728 SourceLoc))
Sebastian Redl4915e632009-10-11 09:03:14 +0000729 return true;
730
Sebastian Redla44822f2009-10-14 16:09:29 +0000731 // We shouldn't even be testing this unless the arguments are otherwise
Sebastian Redl4915e632009-10-11 09:03:14 +0000732 // compatible.
Alp Toker9cacbab2014-01-20 20:26:09 +0000733 assert(Target->getNumParams() == Source->getNumParams() &&
Sebastian Redl4915e632009-10-11 09:03:14 +0000734 "Functions have different argument counts.");
Alp Toker9cacbab2014-01-20 20:26:09 +0000735 for (unsigned i = 0, E = Target->getNumParams(); i != E; ++i) {
736 if (CheckSpecForTypesEquivalent(
737 *this, PDiag(diag::err_deep_exception_specs_differ) << 1, PDiag(),
738 Target->getParamType(i), TargetLoc, Source->getParamType(i),
739 SourceLoc))
Sebastian Redl4915e632009-10-11 09:03:14 +0000740 return true;
741 }
742 return false;
743}
744
745bool Sema::CheckExceptionSpecCompatibility(Expr *From, QualType ToType)
746{
747 // First we check for applicability.
748 // Target type must be a function, function pointer or function reference.
749 const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType);
750 if (!ToFunc)
751 return false;
752
753 // SourceType must be a function or function pointer.
754 const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType());
755 if (!FromFunc)
756 return false;
757
758 // Now we've got the correct types on both sides, check their compatibility.
759 // This means that the source of the conversion can only throw a subset of
760 // the exceptions of the target, and any exception specs on arguments or
761 // return types must be equivalent.
Douglas Gregor89336232010-03-29 23:34:08 +0000762 return CheckExceptionSpecSubset(PDiag(diag::err_incompatible_exception_specs),
763 PDiag(), ToFunc,
764 From->getSourceRange().getBegin(),
Sebastian Redl4915e632009-10-11 09:03:14 +0000765 FromFunc, SourceLocation());
766}
767
768bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
769 const CXXMethodDecl *Old) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000770 if (getLangOpts().CPlusPlus11 && isa<CXXDestructorDecl>(New)) {
Sebastian Redl645d9582011-05-20 05:57:18 +0000771 // Don't check uninstantiated template destructors at all. We can only
772 // synthesize correct specs after the template is instantiated.
773 if (New->getParent()->isDependentType())
774 return false;
775 if (New->getParent()->isBeingDefined()) {
776 // The destructor might be updated once the definition is finished. So
777 // remember it and check later.
778 DelayedDestructorExceptionSpecChecks.push_back(std::make_pair(
779 cast<CXXDestructorDecl>(New), cast<CXXDestructorDecl>(Old)));
780 return false;
781 }
Sebastian Redl623ea822011-05-19 05:13:44 +0000782 }
Francois Picheta8032e92011-05-24 02:11:43 +0000783 unsigned DiagID = diag::err_override_exception_spec;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000784 if (getLangOpts().MicrosoftExt)
Francois Picheta8032e92011-05-24 02:11:43 +0000785 DiagID = diag::warn_override_exception_spec;
786 return CheckExceptionSpecSubset(PDiag(DiagID),
Douglas Gregor89336232010-03-29 23:34:08 +0000787 PDiag(diag::note_overridden_virtual_function),
Sebastian Redl4915e632009-10-11 09:03:14 +0000788 Old->getType()->getAs<FunctionProtoType>(),
789 Old->getLocation(),
790 New->getType()->getAs<FunctionProtoType>(),
791 New->getLocation());
792}
793
Richard Smithf623c962012-04-17 00:58:00 +0000794static CanThrowResult canSubExprsThrow(Sema &S, const Expr *CE) {
795 Expr *E = const_cast<Expr*>(CE);
796 CanThrowResult R = CT_Cannot;
797 for (Expr::child_range I = E->children(); I && R != CT_Can; ++I)
798 R = mergeCanThrow(R, S.canThrow(cast<Expr>(*I)));
799 return R;
800}
801
Eli Friedman0423b762013-06-25 01:24:22 +0000802static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D) {
803 assert(D && "Expected decl");
Richard Smithf623c962012-04-17 00:58:00 +0000804
805 // See if we can get a function type from the decl somehow.
806 const ValueDecl *VD = dyn_cast<ValueDecl>(D);
807 if (!VD) // If we have no clue what we're calling, assume the worst.
808 return CT_Can;
809
810 // As an extension, we assume that __attribute__((nothrow)) functions don't
811 // throw.
812 if (isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())
813 return CT_Cannot;
814
815 QualType T = VD->getType();
816 const FunctionProtoType *FT;
817 if ((FT = T->getAs<FunctionProtoType>())) {
818 } else if (const PointerType *PT = T->getAs<PointerType>())
819 FT = PT->getPointeeType()->getAs<FunctionProtoType>();
820 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
821 FT = RT->getPointeeType()->getAs<FunctionProtoType>();
822 else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
823 FT = MT->getPointeeType()->getAs<FunctionProtoType>();
824 else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
825 FT = BT->getPointeeType()->getAs<FunctionProtoType>();
826
827 if (!FT)
828 return CT_Can;
829
830 FT = S.ResolveExceptionSpec(E->getLocStart(), FT);
831 if (!FT)
832 return CT_Can;
833
Richard Smithf623c962012-04-17 00:58:00 +0000834 return FT->isNothrow(S.Context) ? CT_Cannot : CT_Can;
835}
836
837static CanThrowResult canDynamicCastThrow(const CXXDynamicCastExpr *DC) {
838 if (DC->isTypeDependent())
839 return CT_Dependent;
840
841 if (!DC->getTypeAsWritten()->isReferenceType())
842 return CT_Cannot;
843
844 if (DC->getSubExpr()->isTypeDependent())
845 return CT_Dependent;
846
847 return DC->getCastKind() == clang::CK_Dynamic? CT_Can : CT_Cannot;
848}
849
850static CanThrowResult canTypeidThrow(Sema &S, const CXXTypeidExpr *DC) {
851 if (DC->isTypeOperand())
852 return CT_Cannot;
853
854 Expr *Op = DC->getExprOperand();
855 if (Op->isTypeDependent())
856 return CT_Dependent;
857
858 const RecordType *RT = Op->getType()->getAs<RecordType>();
859 if (!RT)
860 return CT_Cannot;
861
862 if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
863 return CT_Cannot;
864
865 if (Op->Classify(S.Context).isPRValue())
866 return CT_Cannot;
867
868 return CT_Can;
869}
870
871CanThrowResult Sema::canThrow(const Expr *E) {
872 // C++ [expr.unary.noexcept]p3:
873 // [Can throw] if in a potentially-evaluated context the expression would
874 // contain:
875 switch (E->getStmtClass()) {
876 case Expr::CXXThrowExprClass:
877 // - a potentially evaluated throw-expression
878 return CT_Can;
879
880 case Expr::CXXDynamicCastExprClass: {
881 // - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
882 // where T is a reference type, that requires a run-time check
883 CanThrowResult CT = canDynamicCastThrow(cast<CXXDynamicCastExpr>(E));
884 if (CT == CT_Can)
885 return CT;
886 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
887 }
888
889 case Expr::CXXTypeidExprClass:
890 // - a potentially evaluated typeid expression applied to a glvalue
891 // expression whose type is a polymorphic class type
892 return canTypeidThrow(*this, cast<CXXTypeidExpr>(E));
893
894 // - a potentially evaluated call to a function, member function, function
895 // pointer, or member function pointer that does not have a non-throwing
896 // exception-specification
897 case Expr::CallExprClass:
898 case Expr::CXXMemberCallExprClass:
899 case Expr::CXXOperatorCallExprClass:
900 case Expr::UserDefinedLiteralClass: {
901 const CallExpr *CE = cast<CallExpr>(E);
902 CanThrowResult CT;
903 if (E->isTypeDependent())
904 CT = CT_Dependent;
905 else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens()))
906 CT = CT_Cannot;
Eli Friedman5a8738f2013-06-25 01:55:41 +0000907 else if (CE->getCalleeDecl())
Richard Smithf623c962012-04-17 00:58:00 +0000908 CT = canCalleeThrow(*this, E, CE->getCalleeDecl());
Eli Friedman5a8738f2013-06-25 01:55:41 +0000909 else
910 CT = CT_Can;
Richard Smithf623c962012-04-17 00:58:00 +0000911 if (CT == CT_Can)
912 return CT;
913 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
914 }
915
916 case Expr::CXXConstructExprClass:
917 case Expr::CXXTemporaryObjectExprClass: {
918 CanThrowResult CT = canCalleeThrow(*this, E,
919 cast<CXXConstructExpr>(E)->getConstructor());
920 if (CT == CT_Can)
921 return CT;
922 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
923 }
924
925 case Expr::LambdaExprClass: {
926 const LambdaExpr *Lambda = cast<LambdaExpr>(E);
927 CanThrowResult CT = CT_Cannot;
928 for (LambdaExpr::capture_init_iterator Cap = Lambda->capture_init_begin(),
929 CapEnd = Lambda->capture_init_end();
930 Cap != CapEnd; ++Cap)
931 CT = mergeCanThrow(CT, canThrow(*Cap));
932 return CT;
933 }
934
935 case Expr::CXXNewExprClass: {
936 CanThrowResult CT;
937 if (E->isTypeDependent())
938 CT = CT_Dependent;
939 else
940 CT = canCalleeThrow(*this, E, cast<CXXNewExpr>(E)->getOperatorNew());
941 if (CT == CT_Can)
942 return CT;
943 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
944 }
945
946 case Expr::CXXDeleteExprClass: {
947 CanThrowResult CT;
948 QualType DTy = cast<CXXDeleteExpr>(E)->getDestroyedType();
949 if (DTy.isNull() || DTy->isDependentType()) {
950 CT = CT_Dependent;
951 } else {
952 CT = canCalleeThrow(*this, E,
953 cast<CXXDeleteExpr>(E)->getOperatorDelete());
954 if (const RecordType *RT = DTy->getAs<RecordType>()) {
955 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedman0423b762013-06-25 01:24:22 +0000956 const CXXDestructorDecl *DD = RD->getDestructor();
957 if (DD)
958 CT = mergeCanThrow(CT, canCalleeThrow(*this, E, DD));
Richard Smithf623c962012-04-17 00:58:00 +0000959 }
960 if (CT == CT_Can)
961 return CT;
962 }
963 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
964 }
965
966 case Expr::CXXBindTemporaryExprClass: {
967 // The bound temporary has to be destroyed again, which might throw.
968 CanThrowResult CT = canCalleeThrow(*this, E,
969 cast<CXXBindTemporaryExpr>(E)->getTemporary()->getDestructor());
970 if (CT == CT_Can)
971 return CT;
972 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
973 }
974
975 // ObjC message sends are like function calls, but never have exception
976 // specs.
977 case Expr::ObjCMessageExprClass:
978 case Expr::ObjCPropertyRefExprClass:
979 case Expr::ObjCSubscriptRefExprClass:
980 return CT_Can;
981
982 // All the ObjC literals that are implemented as calls are
983 // potentially throwing unless we decide to close off that
984 // possibility.
985 case Expr::ObjCArrayLiteralClass:
986 case Expr::ObjCDictionaryLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +0000987 case Expr::ObjCBoxedExprClass:
Richard Smithf623c962012-04-17 00:58:00 +0000988 return CT_Can;
989
990 // Many other things have subexpressions, so we have to test those.
991 // Some are simple:
992 case Expr::ConditionalOperatorClass:
993 case Expr::CompoundLiteralExprClass:
994 case Expr::CXXConstCastExprClass:
Richard Smithf623c962012-04-17 00:58:00 +0000995 case Expr::CXXReinterpretCastExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +0000996 case Expr::CXXStdInitializerListExprClass:
Richard Smithf623c962012-04-17 00:58:00 +0000997 case Expr::DesignatedInitExprClass:
998 case Expr::ExprWithCleanupsClass:
999 case Expr::ExtVectorElementExprClass:
1000 case Expr::InitListExprClass:
1001 case Expr::MemberExprClass:
1002 case Expr::ObjCIsaExprClass:
1003 case Expr::ObjCIvarRefExprClass:
1004 case Expr::ParenExprClass:
1005 case Expr::ParenListExprClass:
1006 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00001007 case Expr::ConvertVectorExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001008 case Expr::VAArgExprClass:
1009 return canSubExprsThrow(*this, E);
1010
1011 // Some might be dependent for other reasons.
1012 case Expr::ArraySubscriptExprClass:
1013 case Expr::BinaryOperatorClass:
1014 case Expr::CompoundAssignOperatorClass:
1015 case Expr::CStyleCastExprClass:
1016 case Expr::CXXStaticCastExprClass:
1017 case Expr::CXXFunctionalCastExprClass:
1018 case Expr::ImplicitCastExprClass:
1019 case Expr::MaterializeTemporaryExprClass:
1020 case Expr::UnaryOperatorClass: {
1021 CanThrowResult CT = E->isTypeDependent() ? CT_Dependent : CT_Cannot;
1022 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1023 }
1024
1025 // FIXME: We should handle StmtExpr, but that opens a MASSIVE can of worms.
1026 case Expr::StmtExprClass:
1027 return CT_Can;
1028
Richard Smith852c9db2013-04-20 22:23:05 +00001029 case Expr::CXXDefaultArgExprClass:
1030 return canThrow(cast<CXXDefaultArgExpr>(E)->getExpr());
1031
1032 case Expr::CXXDefaultInitExprClass:
1033 return canThrow(cast<CXXDefaultInitExpr>(E)->getExpr());
1034
Richard Smithf623c962012-04-17 00:58:00 +00001035 case Expr::ChooseExprClass:
1036 if (E->isTypeDependent() || E->isValueDependent())
1037 return CT_Dependent;
Eli Friedman75807f22013-07-20 00:40:58 +00001038 return canThrow(cast<ChooseExpr>(E)->getChosenSubExpr());
Richard Smithf623c962012-04-17 00:58:00 +00001039
1040 case Expr::GenericSelectionExprClass:
1041 if (cast<GenericSelectionExpr>(E)->isResultDependent())
1042 return CT_Dependent;
1043 return canThrow(cast<GenericSelectionExpr>(E)->getResultExpr());
1044
1045 // Some expressions are always dependent.
1046 case Expr::CXXDependentScopeMemberExprClass:
1047 case Expr::CXXUnresolvedConstructExprClass:
1048 case Expr::DependentScopeDeclRefExprClass:
1049 return CT_Dependent;
1050
1051 case Expr::AsTypeExprClass:
1052 case Expr::BinaryConditionalOperatorClass:
1053 case Expr::BlockExprClass:
1054 case Expr::CUDAKernelCallExprClass:
1055 case Expr::DeclRefExprClass:
1056 case Expr::ObjCBridgedCastExprClass:
1057 case Expr::ObjCIndirectCopyRestoreExprClass:
1058 case Expr::ObjCProtocolExprClass:
1059 case Expr::ObjCSelectorExprClass:
1060 case Expr::OffsetOfExprClass:
1061 case Expr::PackExpansionExprClass:
1062 case Expr::PseudoObjectExprClass:
1063 case Expr::SubstNonTypeTemplateParmExprClass:
1064 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00001065 case Expr::FunctionParmPackExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001066 case Expr::UnaryExprOrTypeTraitExprClass:
1067 case Expr::UnresolvedLookupExprClass:
1068 case Expr::UnresolvedMemberExprClass:
1069 // FIXME: Can any of the above throw? If so, when?
1070 return CT_Cannot;
1071
1072 case Expr::AddrLabelExprClass:
1073 case Expr::ArrayTypeTraitExprClass:
1074 case Expr::AtomicExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001075 case Expr::TypeTraitExprClass:
1076 case Expr::CXXBoolLiteralExprClass:
1077 case Expr::CXXNoexceptExprClass:
1078 case Expr::CXXNullPtrLiteralExprClass:
1079 case Expr::CXXPseudoDestructorExprClass:
1080 case Expr::CXXScalarValueInitExprClass:
1081 case Expr::CXXThisExprClass:
1082 case Expr::CXXUuidofExprClass:
1083 case Expr::CharacterLiteralClass:
1084 case Expr::ExpressionTraitExprClass:
1085 case Expr::FloatingLiteralClass:
1086 case Expr::GNUNullExprClass:
1087 case Expr::ImaginaryLiteralClass:
1088 case Expr::ImplicitValueInitExprClass:
1089 case Expr::IntegerLiteralClass:
1090 case Expr::ObjCEncodeExprClass:
1091 case Expr::ObjCStringLiteralClass:
1092 case Expr::ObjCBoolLiteralExprClass:
1093 case Expr::OpaqueValueExprClass:
1094 case Expr::PredefinedExprClass:
1095 case Expr::SizeOfPackExprClass:
1096 case Expr::StringLiteralClass:
Richard Smithf623c962012-04-17 00:58:00 +00001097 // These expressions can never throw.
1098 return CT_Cannot;
1099
John McCall5e77d762013-04-16 07:28:30 +00001100 case Expr::MSPropertyRefExprClass:
1101 llvm_unreachable("Invalid class for expression");
1102
Richard Smithf623c962012-04-17 00:58:00 +00001103#define STMT(CLASS, PARENT) case Expr::CLASS##Class:
1104#define STMT_RANGE(Base, First, Last)
1105#define LAST_STMT_RANGE(BASE, FIRST, LAST)
1106#define EXPR(CLASS, PARENT)
1107#define ABSTRACT_STMT(STMT)
1108#include "clang/AST/StmtNodes.inc"
1109 case Expr::NoStmtClass:
1110 llvm_unreachable("Invalid class for expression");
1111 }
1112 llvm_unreachable("Bogus StmtClass");
1113}
1114
Sebastian Redl4915e632009-10-11 09:03:14 +00001115} // end namespace clang