blob: 2eee07c0afdf1f4d20ef9932832004b472c1bee4 [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 Smith66f3ac92012-10-20 08:26:51 +0000143 // If the user didn't declare the function, its exception specification must
144 // be implicit.
145 if (!Decl->getTypeSourceInfo())
146 return true;
147
148 const FunctionProtoType *Ty =
149 Decl->getTypeSourceInfo()->getType()->getAs<FunctionProtoType>();
150 return !Ty->hasExceptionSpec();
Richard Smith1ee63522012-10-16 23:30:16 +0000151}
152
Douglas Gregorf40863c2010-02-12 07:32:17 +0000153bool Sema::CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New) {
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000154 OverloadedOperatorKind OO = New->getDeclName().getCXXOverloadedOperator();
155 bool IsOperatorNew = OO == OO_New || OO == OO_Array_New;
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000156 bool MissingExceptionSpecification = false;
Douglas Gregorf40863c2010-02-12 07:32:17 +0000157 bool MissingEmptyExceptionSpecification = false;
Hans Wennborg39a509a2014-02-05 02:37:58 +0000158
Francois Pichet13b4e682011-03-19 23:05:18 +0000159 unsigned DiagID = diag::err_mismatched_exception_spec;
Hans Wennborg39a509a2014-02-05 02:37:58 +0000160 bool ReturnValueOnError = true;
161 if (getLangOpts().MicrosoftExt) {
Francois Pichet93921652011-04-22 08:25:24 +0000162 DiagID = diag::warn_mismatched_exception_spec;
Hans Wennborg39a509a2014-02-05 02:37:58 +0000163 ReturnValueOnError = false;
164 }
Richard Smithf623c962012-04-17 00:58:00 +0000165
Richard Smith1ee63522012-10-16 23:30:16 +0000166 // Check the types as written: they must match before any exception
167 // specification adjustment is applied.
168 if (!CheckEquivalentExceptionSpec(
169 PDiag(DiagID), PDiag(diag::note_previous_declaration),
Richard Smith66f3ac92012-10-20 08:26:51 +0000170 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
171 New->getType()->getAs<FunctionProtoType>(), New->getLocation(),
Richard Smith1ee63522012-10-16 23:30:16 +0000172 &MissingExceptionSpecification, &MissingEmptyExceptionSpecification,
Richard Smith66f3ac92012-10-20 08:26:51 +0000173 /*AllowNoexceptAllMatchWithNoSpec=*/true, IsOperatorNew)) {
174 // C++11 [except.spec]p4 [DR1492]:
175 // If a declaration of a function has an implicit
176 // exception-specification, other declarations of the function shall
177 // not specify an exception-specification.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000178 if (getLangOpts().CPlusPlus11 &&
Richard Smith66f3ac92012-10-20 08:26:51 +0000179 hasImplicitExceptionSpec(Old) != hasImplicitExceptionSpec(New)) {
180 Diag(New->getLocation(), diag::ext_implicit_exception_spec_mismatch)
181 << hasImplicitExceptionSpec(Old);
182 if (!Old->getLocation().isInvalid())
183 Diag(Old->getLocation(), diag::note_previous_declaration);
184 }
Douglas Gregorf40863c2010-02-12 07:32:17 +0000185 return false;
Richard Smith66f3ac92012-10-20 08:26:51 +0000186 }
Douglas Gregorf40863c2010-02-12 07:32:17 +0000187
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000188 // The failure was something other than an missing exception
Hans Wennborg39a509a2014-02-05 02:37:58 +0000189 // specification; return an error, except in MS mode where this is a warning.
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000190 if (!MissingExceptionSpecification)
Hans Wennborg39a509a2014-02-05 02:37:58 +0000191 return ReturnValueOnError;
Douglas Gregorf40863c2010-02-12 07:32:17 +0000192
Richard Smith66f3ac92012-10-20 08:26:51 +0000193 const FunctionProtoType *NewProto =
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000194 New->getType()->castAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +0000195
Douglas Gregorf40863c2010-02-12 07:32:17 +0000196 // The new function declaration is only missing an empty exception
197 // specification "throw()". If the throw() specification came from a
198 // function in a system header that has C linkage, just add an empty
199 // exception specification to the "new" declaration. This is an
200 // egregious workaround for glibc, which adds throw() specifications
201 // to many libc functions as an optimization. Unfortunately, that
202 // optimization isn't permitted by the C++ standard, so we're forced
203 // to work around it here.
John McCalldb40c7f2010-12-14 08:05:40 +0000204 if (MissingEmptyExceptionSpecification && NewProto &&
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000205 (Old->getLocation().isInvalid() ||
206 Context.getSourceManager().isInSystemHeader(Old->getLocation())) &&
Douglas Gregorf40863c2010-02-12 07:32:17 +0000207 Old->isExternC()) {
John McCalldb40c7f2010-12-14 08:05:40 +0000208 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000209 EPI.ExceptionSpecType = EST_DynamicNone;
Alp Toker314cc812014-01-25 16:55:45 +0000210 QualType NewType = Context.getFunctionType(NewProto->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +0000211 NewProto->getParamTypes(), EPI);
Douglas Gregorf40863c2010-02-12 07:32:17 +0000212 New->setType(NewType);
213 return false;
214 }
215
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000216 const FunctionProtoType *OldProto =
217 Old->getType()->castAs<FunctionProtoType>();
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000218
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000219 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
220 EPI.ExceptionSpecType = OldProto->getExceptionSpecType();
221 if (EPI.ExceptionSpecType == EST_Dynamic) {
222 EPI.NumExceptions = OldProto->getNumExceptions();
223 EPI.Exceptions = OldProto->exception_begin();
224 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
225 // FIXME: We can't just take the expression from the old prototype. It
226 // likely contains references to the old prototype's parameters.
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000227 }
228
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000229 // Update the type of the function with the appropriate exception
230 // specification.
Alp Toker314cc812014-01-25 16:55:45 +0000231 QualType NewType = Context.getFunctionType(NewProto->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +0000232 NewProto->getParamTypes(), EPI);
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000233 New->setType(NewType);
234
235 // Warn about the lack of exception specification.
236 SmallString<128> ExceptionSpecString;
237 llvm::raw_svector_ostream OS(ExceptionSpecString);
238 switch (OldProto->getExceptionSpecType()) {
239 case EST_DynamicNone:
240 OS << "throw()";
241 break;
242
243 case EST_Dynamic: {
244 OS << "throw(";
245 bool OnFirstException = true;
246 for (FunctionProtoType::exception_iterator E = OldProto->exception_begin(),
247 EEnd = OldProto->exception_end();
248 E != EEnd;
249 ++E) {
250 if (OnFirstException)
251 OnFirstException = false;
252 else
253 OS << ", ";
254
255 OS << E->getAsString(getPrintingPolicy());
256 }
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;
Sebastian Redl4915e632009-10-11 09:03:14 +0000499 for (FunctionProtoType::exception_iterator I = Old->exception_begin(),
500 E = Old->exception_end(); I != E; ++I)
Sebastian Redl184edca2009-10-14 15:06:25 +0000501 OldTypes.insert(Context.getCanonicalType(*I).getUnqualifiedType());
Sebastian Redl4915e632009-10-11 09:03:14 +0000502
503 for (FunctionProtoType::exception_iterator I = New->exception_begin(),
Sebastian Redl6e4c8712009-10-11 09:11:23 +0000504 E = New->exception_end(); I != E && Success; ++I) {
Sebastian Redl184edca2009-10-14 15:06:25 +0000505 CanQualType TypePtr = Context.getCanonicalType(*I).getUnqualifiedType();
Sebastian Redl6e4c8712009-10-11 09:11:23 +0000506 if(OldTypes.count(TypePtr))
507 NewTypes.insert(TypePtr);
508 else
509 Success = false;
510 }
Sebastian Redl4915e632009-10-11 09:03:14 +0000511
Sebastian Redl6e4c8712009-10-11 09:11:23 +0000512 Success = Success && OldTypes.size() == NewTypes.size();
Sebastian Redl4915e632009-10-11 09:03:14 +0000513
514 if (Success) {
515 return false;
516 }
517 Diag(NewLoc, DiagID);
Sebastian Redla44822f2009-10-14 16:09:29 +0000518 if (NoteID.getDiagID() != 0)
Sebastian Redl4915e632009-10-11 09:03:14 +0000519 Diag(OldLoc, NoteID);
520 return true;
521}
522
523/// CheckExceptionSpecSubset - Check whether the second function type's
524/// exception specification is a subset (or equivalent) of the first function
525/// type. This is used by override and pointer assignment checks.
Sebastian Redla44822f2009-10-14 16:09:29 +0000526bool Sema::CheckExceptionSpecSubset(
527 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
Sebastian Redl4915e632009-10-11 09:03:14 +0000528 const FunctionProtoType *Superset, SourceLocation SuperLoc,
529 const FunctionProtoType *Subset, SourceLocation SubLoc) {
John McCallf9c94092010-05-28 08:37:35 +0000530
531 // Just auto-succeed under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000532 if (!getLangOpts().CXXExceptions)
John McCallf9c94092010-05-28 08:37:35 +0000533 return false;
534
Sebastian Redl4915e632009-10-11 09:03:14 +0000535 // FIXME: As usual, we could be more specific in our error messages, but
536 // that better waits until we've got types with source locations.
537
538 if (!SubLoc.isValid())
539 SubLoc = SuperLoc;
540
Richard Smithf623c962012-04-17 00:58:00 +0000541 // Resolve the exception specifications, if needed.
542 Superset = ResolveExceptionSpec(SuperLoc, Superset);
543 if (!Superset)
544 return false;
545 Subset = ResolveExceptionSpec(SubLoc, Subset);
546 if (!Subset)
547 return false;
548
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000549 ExceptionSpecificationType SuperEST = Superset->getExceptionSpecType();
550
Sebastian Redl4915e632009-10-11 09:03:14 +0000551 // If superset contains everything, we're done.
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000552 if (SuperEST == EST_None || SuperEST == EST_MSAny)
Sebastian Redl4915e632009-10-11 09:03:14 +0000553 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
554
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000555 // If there are dependent noexcept specs, assume everything is fine. Unlike
556 // with the equivalency check, this is safe in this case, because we don't
557 // want to merge declarations. Checks after instantiation will catch any
558 // omissions we make here.
559 // We also shortcut checking if a noexcept expression was bad.
560
Sebastian Redl31ad7542011-03-13 17:09:40 +0000561 FunctionProtoType::NoexceptResult SuperNR =Superset->getNoexceptSpec(Context);
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000562 if (SuperNR == FunctionProtoType::NR_BadNoexcept ||
563 SuperNR == FunctionProtoType::NR_Dependent)
564 return false;
565
566 // Another case of the superset containing everything.
567 if (SuperNR == FunctionProtoType::NR_Throw)
568 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
569
570 ExceptionSpecificationType SubEST = Subset->getExceptionSpecType();
571
Richard Smithd3b5c9082012-07-27 04:22:15 +0000572 assert(!isUnresolvedExceptionSpec(SuperEST) &&
573 !isUnresolvedExceptionSpec(SubEST) &&
Richard Smith938f40b2011-06-11 17:19:42 +0000574 "Shouldn't see unknown exception specifications here");
575
Sebastian Redl4915e632009-10-11 09:03:14 +0000576 // It does not. If the subset contains everything, we've failed.
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000577 if (SubEST == EST_None || SubEST == EST_MSAny) {
Sebastian Redl4915e632009-10-11 09:03:14 +0000578 Diag(SubLoc, DiagID);
Sebastian Redla44822f2009-10-14 16:09:29 +0000579 if (NoteID.getDiagID() != 0)
Sebastian Redl4915e632009-10-11 09:03:14 +0000580 Diag(SuperLoc, NoteID);
581 return true;
582 }
583
Sebastian Redl31ad7542011-03-13 17:09:40 +0000584 FunctionProtoType::NoexceptResult SubNR = Subset->getNoexceptSpec(Context);
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000585 if (SubNR == FunctionProtoType::NR_BadNoexcept ||
586 SubNR == FunctionProtoType::NR_Dependent)
587 return false;
588
589 // Another case of the subset containing everything.
590 if (SubNR == FunctionProtoType::NR_Throw) {
591 Diag(SubLoc, DiagID);
592 if (NoteID.getDiagID() != 0)
593 Diag(SuperLoc, NoteID);
594 return true;
595 }
596
597 // If the subset contains nothing, we're done.
598 if (SubEST == EST_DynamicNone || SubNR == FunctionProtoType::NR_Nothrow)
599 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
600
601 // Otherwise, if the superset contains nothing, we've failed.
602 if (SuperEST == EST_DynamicNone || SuperNR == FunctionProtoType::NR_Nothrow) {
603 Diag(SubLoc, DiagID);
604 if (NoteID.getDiagID() != 0)
605 Diag(SuperLoc, NoteID);
606 return true;
607 }
608
609 assert(SuperEST == EST_Dynamic && SubEST == EST_Dynamic &&
610 "Exception spec subset: non-dynamic case slipped through.");
611
612 // Neither contains everything or nothing. Do a proper comparison.
Sebastian Redl4915e632009-10-11 09:03:14 +0000613 for (FunctionProtoType::exception_iterator SubI = Subset->exception_begin(),
614 SubE = Subset->exception_end(); SubI != SubE; ++SubI) {
615 // Take one type from the subset.
616 QualType CanonicalSubT = Context.getCanonicalType(*SubI);
Sebastian Redl075b21d2009-10-14 14:38:54 +0000617 // Unwrap pointers and references so that we can do checks within a class
618 // hierarchy. Don't unwrap member pointers; they don't have hierarchy
619 // conversions on the pointee.
Sebastian Redl4915e632009-10-11 09:03:14 +0000620 bool SubIsPointer = false;
621 if (const ReferenceType *RefTy = CanonicalSubT->getAs<ReferenceType>())
622 CanonicalSubT = RefTy->getPointeeType();
623 if (const PointerType *PtrTy = CanonicalSubT->getAs<PointerType>()) {
624 CanonicalSubT = PtrTy->getPointeeType();
625 SubIsPointer = true;
626 }
627 bool SubIsClass = CanonicalSubT->isRecordType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000628 CanonicalSubT = CanonicalSubT.getLocalUnqualifiedType();
Sebastian Redl4915e632009-10-11 09:03:14 +0000629
630 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
631 /*DetectVirtual=*/false);
632
633 bool Contained = false;
634 // Make sure it's in the superset.
635 for (FunctionProtoType::exception_iterator SuperI =
636 Superset->exception_begin(), SuperE = Superset->exception_end();
637 SuperI != SuperE; ++SuperI) {
638 QualType CanonicalSuperT = Context.getCanonicalType(*SuperI);
639 // SubT must be SuperT or derived from it, or pointer or reference to
640 // such types.
641 if (const ReferenceType *RefTy = CanonicalSuperT->getAs<ReferenceType>())
642 CanonicalSuperT = RefTy->getPointeeType();
643 if (SubIsPointer) {
644 if (const PointerType *PtrTy = CanonicalSuperT->getAs<PointerType>())
645 CanonicalSuperT = PtrTy->getPointeeType();
646 else {
647 continue;
648 }
649 }
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000650 CanonicalSuperT = CanonicalSuperT.getLocalUnqualifiedType();
Sebastian Redl4915e632009-10-11 09:03:14 +0000651 // If the types are the same, move on to the next type in the subset.
652 if (CanonicalSubT == CanonicalSuperT) {
653 Contained = true;
654 break;
655 }
656
657 // Otherwise we need to check the inheritance.
658 if (!SubIsClass || !CanonicalSuperT->isRecordType())
659 continue;
660
661 Paths.clear();
662 if (!IsDerivedFrom(CanonicalSubT, CanonicalSuperT, Paths))
663 continue;
664
Douglas Gregor27ac4292010-05-21 20:29:55 +0000665 if (Paths.isAmbiguous(Context.getCanonicalType(CanonicalSuperT)))
Sebastian Redl4915e632009-10-11 09:03:14 +0000666 continue;
667
John McCall5b0829a2010-02-10 09:31:12 +0000668 // Do this check from a context without privileges.
John McCall1064d7e2010-03-16 05:22:47 +0000669 switch (CheckBaseClassAccess(SourceLocation(),
John McCall5b0829a2010-02-10 09:31:12 +0000670 CanonicalSuperT, CanonicalSubT,
671 Paths.front(),
John McCall1064d7e2010-03-16 05:22:47 +0000672 /*Diagnostic*/ 0,
John McCall5b0829a2010-02-10 09:31:12 +0000673 /*ForceCheck*/ true,
John McCall1064d7e2010-03-16 05:22:47 +0000674 /*ForceUnprivileged*/ true)) {
John McCall5b0829a2010-02-10 09:31:12 +0000675 case AR_accessible: break;
676 case AR_inaccessible: continue;
677 case AR_dependent:
678 llvm_unreachable("access check dependent for unprivileged context");
John McCall5b0829a2010-02-10 09:31:12 +0000679 case AR_delayed:
680 llvm_unreachable("access check delayed in non-declaration");
John McCall5b0829a2010-02-10 09:31:12 +0000681 }
Sebastian Redl4915e632009-10-11 09:03:14 +0000682
683 Contained = true;
684 break;
685 }
686 if (!Contained) {
687 Diag(SubLoc, DiagID);
Sebastian Redla44822f2009-10-14 16:09:29 +0000688 if (NoteID.getDiagID() != 0)
Sebastian Redl4915e632009-10-11 09:03:14 +0000689 Diag(SuperLoc, NoteID);
690 return true;
691 }
692 }
693 // We've run half the gauntlet.
694 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
695}
696
697static bool CheckSpecForTypesEquivalent(Sema &S,
Sebastian Redla44822f2009-10-14 16:09:29 +0000698 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
Sebastian Redl4915e632009-10-11 09:03:14 +0000699 QualType Target, SourceLocation TargetLoc,
700 QualType Source, SourceLocation SourceLoc)
701{
702 const FunctionProtoType *TFunc = GetUnderlyingFunction(Target);
703 if (!TFunc)
704 return false;
705 const FunctionProtoType *SFunc = GetUnderlyingFunction(Source);
706 if (!SFunc)
707 return false;
708
709 return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc,
710 SFunc, SourceLoc);
711}
712
713/// CheckParamExceptionSpec - Check if the parameter and return types of the
714/// two functions have equivalent exception specs. This is part of the
715/// assignment and override compatibility check. We do not check the parameters
716/// of parameter function pointers recursively, as no sane programmer would
717/// even be able to write such a function type.
Sebastian Redla44822f2009-10-14 16:09:29 +0000718bool Sema::CheckParamExceptionSpec(const PartialDiagnostic & NoteID,
Sebastian Redl4915e632009-10-11 09:03:14 +0000719 const FunctionProtoType *Target, SourceLocation TargetLoc,
720 const FunctionProtoType *Source, SourceLocation SourceLoc)
721{
Alp Toker314cc812014-01-25 16:55:45 +0000722 if (CheckSpecForTypesEquivalent(
723 *this, PDiag(diag::err_deep_exception_specs_differ) << 0, PDiag(),
724 Target->getReturnType(), TargetLoc, Source->getReturnType(),
725 SourceLoc))
Sebastian Redl4915e632009-10-11 09:03:14 +0000726 return true;
727
Sebastian Redla44822f2009-10-14 16:09:29 +0000728 // We shouldn't even be testing this unless the arguments are otherwise
Sebastian Redl4915e632009-10-11 09:03:14 +0000729 // compatible.
Alp Toker9cacbab2014-01-20 20:26:09 +0000730 assert(Target->getNumParams() == Source->getNumParams() &&
Sebastian Redl4915e632009-10-11 09:03:14 +0000731 "Functions have different argument counts.");
Alp Toker9cacbab2014-01-20 20:26:09 +0000732 for (unsigned i = 0, E = Target->getNumParams(); i != E; ++i) {
733 if (CheckSpecForTypesEquivalent(
734 *this, PDiag(diag::err_deep_exception_specs_differ) << 1, PDiag(),
735 Target->getParamType(i), TargetLoc, Source->getParamType(i),
736 SourceLoc))
Sebastian Redl4915e632009-10-11 09:03:14 +0000737 return true;
738 }
739 return false;
740}
741
742bool Sema::CheckExceptionSpecCompatibility(Expr *From, QualType ToType)
743{
744 // First we check for applicability.
745 // Target type must be a function, function pointer or function reference.
746 const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType);
747 if (!ToFunc)
748 return false;
749
750 // SourceType must be a function or function pointer.
751 const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType());
752 if (!FromFunc)
753 return false;
754
755 // Now we've got the correct types on both sides, check their compatibility.
756 // This means that the source of the conversion can only throw a subset of
757 // the exceptions of the target, and any exception specs on arguments or
758 // return types must be equivalent.
Douglas Gregor89336232010-03-29 23:34:08 +0000759 return CheckExceptionSpecSubset(PDiag(diag::err_incompatible_exception_specs),
760 PDiag(), ToFunc,
761 From->getSourceRange().getBegin(),
Sebastian Redl4915e632009-10-11 09:03:14 +0000762 FromFunc, SourceLocation());
763}
764
765bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
766 const CXXMethodDecl *Old) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000767 if (getLangOpts().CPlusPlus11 && isa<CXXDestructorDecl>(New)) {
Sebastian Redl645d9582011-05-20 05:57:18 +0000768 // Don't check uninstantiated template destructors at all. We can only
769 // synthesize correct specs after the template is instantiated.
770 if (New->getParent()->isDependentType())
771 return false;
772 if (New->getParent()->isBeingDefined()) {
773 // The destructor might be updated once the definition is finished. So
774 // remember it and check later.
775 DelayedDestructorExceptionSpecChecks.push_back(std::make_pair(
776 cast<CXXDestructorDecl>(New), cast<CXXDestructorDecl>(Old)));
777 return false;
778 }
Sebastian Redl623ea822011-05-19 05:13:44 +0000779 }
Francois Picheta8032e92011-05-24 02:11:43 +0000780 unsigned DiagID = diag::err_override_exception_spec;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000781 if (getLangOpts().MicrosoftExt)
Francois Picheta8032e92011-05-24 02:11:43 +0000782 DiagID = diag::warn_override_exception_spec;
783 return CheckExceptionSpecSubset(PDiag(DiagID),
Douglas Gregor89336232010-03-29 23:34:08 +0000784 PDiag(diag::note_overridden_virtual_function),
Sebastian Redl4915e632009-10-11 09:03:14 +0000785 Old->getType()->getAs<FunctionProtoType>(),
786 Old->getLocation(),
787 New->getType()->getAs<FunctionProtoType>(),
788 New->getLocation());
789}
790
Richard Smithf623c962012-04-17 00:58:00 +0000791static CanThrowResult canSubExprsThrow(Sema &S, const Expr *CE) {
792 Expr *E = const_cast<Expr*>(CE);
793 CanThrowResult R = CT_Cannot;
794 for (Expr::child_range I = E->children(); I && R != CT_Can; ++I)
795 R = mergeCanThrow(R, S.canThrow(cast<Expr>(*I)));
796 return R;
797}
798
Eli Friedman0423b762013-06-25 01:24:22 +0000799static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D) {
800 assert(D && "Expected decl");
Richard Smithf623c962012-04-17 00:58:00 +0000801
802 // See if we can get a function type from the decl somehow.
803 const ValueDecl *VD = dyn_cast<ValueDecl>(D);
804 if (!VD) // If we have no clue what we're calling, assume the worst.
805 return CT_Can;
806
807 // As an extension, we assume that __attribute__((nothrow)) functions don't
808 // throw.
809 if (isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())
810 return CT_Cannot;
811
812 QualType T = VD->getType();
813 const FunctionProtoType *FT;
814 if ((FT = T->getAs<FunctionProtoType>())) {
815 } else if (const PointerType *PT = T->getAs<PointerType>())
816 FT = PT->getPointeeType()->getAs<FunctionProtoType>();
817 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
818 FT = RT->getPointeeType()->getAs<FunctionProtoType>();
819 else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
820 FT = MT->getPointeeType()->getAs<FunctionProtoType>();
821 else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
822 FT = BT->getPointeeType()->getAs<FunctionProtoType>();
823
824 if (!FT)
825 return CT_Can;
826
827 FT = S.ResolveExceptionSpec(E->getLocStart(), FT);
828 if (!FT)
829 return CT_Can;
830
Richard Smithf623c962012-04-17 00:58:00 +0000831 return FT->isNothrow(S.Context) ? CT_Cannot : CT_Can;
832}
833
834static CanThrowResult canDynamicCastThrow(const CXXDynamicCastExpr *DC) {
835 if (DC->isTypeDependent())
836 return CT_Dependent;
837
838 if (!DC->getTypeAsWritten()->isReferenceType())
839 return CT_Cannot;
840
841 if (DC->getSubExpr()->isTypeDependent())
842 return CT_Dependent;
843
844 return DC->getCastKind() == clang::CK_Dynamic? CT_Can : CT_Cannot;
845}
846
847static CanThrowResult canTypeidThrow(Sema &S, const CXXTypeidExpr *DC) {
848 if (DC->isTypeOperand())
849 return CT_Cannot;
850
851 Expr *Op = DC->getExprOperand();
852 if (Op->isTypeDependent())
853 return CT_Dependent;
854
855 const RecordType *RT = Op->getType()->getAs<RecordType>();
856 if (!RT)
857 return CT_Cannot;
858
859 if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
860 return CT_Cannot;
861
862 if (Op->Classify(S.Context).isPRValue())
863 return CT_Cannot;
864
865 return CT_Can;
866}
867
868CanThrowResult Sema::canThrow(const Expr *E) {
869 // C++ [expr.unary.noexcept]p3:
870 // [Can throw] if in a potentially-evaluated context the expression would
871 // contain:
872 switch (E->getStmtClass()) {
873 case Expr::CXXThrowExprClass:
874 // - a potentially evaluated throw-expression
875 return CT_Can;
876
877 case Expr::CXXDynamicCastExprClass: {
878 // - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
879 // where T is a reference type, that requires a run-time check
880 CanThrowResult CT = canDynamicCastThrow(cast<CXXDynamicCastExpr>(E));
881 if (CT == CT_Can)
882 return CT;
883 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
884 }
885
886 case Expr::CXXTypeidExprClass:
887 // - a potentially evaluated typeid expression applied to a glvalue
888 // expression whose type is a polymorphic class type
889 return canTypeidThrow(*this, cast<CXXTypeidExpr>(E));
890
891 // - a potentially evaluated call to a function, member function, function
892 // pointer, or member function pointer that does not have a non-throwing
893 // exception-specification
894 case Expr::CallExprClass:
895 case Expr::CXXMemberCallExprClass:
896 case Expr::CXXOperatorCallExprClass:
897 case Expr::UserDefinedLiteralClass: {
898 const CallExpr *CE = cast<CallExpr>(E);
899 CanThrowResult CT;
900 if (E->isTypeDependent())
901 CT = CT_Dependent;
902 else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens()))
903 CT = CT_Cannot;
Eli Friedman5a8738f2013-06-25 01:55:41 +0000904 else if (CE->getCalleeDecl())
Richard Smithf623c962012-04-17 00:58:00 +0000905 CT = canCalleeThrow(*this, E, CE->getCalleeDecl());
Eli Friedman5a8738f2013-06-25 01:55:41 +0000906 else
907 CT = CT_Can;
Richard Smithf623c962012-04-17 00:58:00 +0000908 if (CT == CT_Can)
909 return CT;
910 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
911 }
912
913 case Expr::CXXConstructExprClass:
914 case Expr::CXXTemporaryObjectExprClass: {
915 CanThrowResult CT = canCalleeThrow(*this, E,
916 cast<CXXConstructExpr>(E)->getConstructor());
917 if (CT == CT_Can)
918 return CT;
919 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
920 }
921
922 case Expr::LambdaExprClass: {
923 const LambdaExpr *Lambda = cast<LambdaExpr>(E);
924 CanThrowResult CT = CT_Cannot;
925 for (LambdaExpr::capture_init_iterator Cap = Lambda->capture_init_begin(),
926 CapEnd = Lambda->capture_init_end();
927 Cap != CapEnd; ++Cap)
928 CT = mergeCanThrow(CT, canThrow(*Cap));
929 return CT;
930 }
931
932 case Expr::CXXNewExprClass: {
933 CanThrowResult CT;
934 if (E->isTypeDependent())
935 CT = CT_Dependent;
936 else
937 CT = canCalleeThrow(*this, E, cast<CXXNewExpr>(E)->getOperatorNew());
938 if (CT == CT_Can)
939 return CT;
940 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
941 }
942
943 case Expr::CXXDeleteExprClass: {
944 CanThrowResult CT;
945 QualType DTy = cast<CXXDeleteExpr>(E)->getDestroyedType();
946 if (DTy.isNull() || DTy->isDependentType()) {
947 CT = CT_Dependent;
948 } else {
949 CT = canCalleeThrow(*this, E,
950 cast<CXXDeleteExpr>(E)->getOperatorDelete());
951 if (const RecordType *RT = DTy->getAs<RecordType>()) {
952 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedman0423b762013-06-25 01:24:22 +0000953 const CXXDestructorDecl *DD = RD->getDestructor();
954 if (DD)
955 CT = mergeCanThrow(CT, canCalleeThrow(*this, E, DD));
Richard Smithf623c962012-04-17 00:58:00 +0000956 }
957 if (CT == CT_Can)
958 return CT;
959 }
960 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
961 }
962
963 case Expr::CXXBindTemporaryExprClass: {
964 // The bound temporary has to be destroyed again, which might throw.
965 CanThrowResult CT = canCalleeThrow(*this, E,
966 cast<CXXBindTemporaryExpr>(E)->getTemporary()->getDestructor());
967 if (CT == CT_Can)
968 return CT;
969 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
970 }
971
972 // ObjC message sends are like function calls, but never have exception
973 // specs.
974 case Expr::ObjCMessageExprClass:
975 case Expr::ObjCPropertyRefExprClass:
976 case Expr::ObjCSubscriptRefExprClass:
977 return CT_Can;
978
979 // All the ObjC literals that are implemented as calls are
980 // potentially throwing unless we decide to close off that
981 // possibility.
982 case Expr::ObjCArrayLiteralClass:
983 case Expr::ObjCDictionaryLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +0000984 case Expr::ObjCBoxedExprClass:
Richard Smithf623c962012-04-17 00:58:00 +0000985 return CT_Can;
986
987 // Many other things have subexpressions, so we have to test those.
988 // Some are simple:
989 case Expr::ConditionalOperatorClass:
990 case Expr::CompoundLiteralExprClass:
991 case Expr::CXXConstCastExprClass:
Richard Smithf623c962012-04-17 00:58:00 +0000992 case Expr::CXXReinterpretCastExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +0000993 case Expr::CXXStdInitializerListExprClass:
Richard Smithf623c962012-04-17 00:58:00 +0000994 case Expr::DesignatedInitExprClass:
995 case Expr::ExprWithCleanupsClass:
996 case Expr::ExtVectorElementExprClass:
997 case Expr::InitListExprClass:
998 case Expr::MemberExprClass:
999 case Expr::ObjCIsaExprClass:
1000 case Expr::ObjCIvarRefExprClass:
1001 case Expr::ParenExprClass:
1002 case Expr::ParenListExprClass:
1003 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00001004 case Expr::ConvertVectorExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001005 case Expr::VAArgExprClass:
1006 return canSubExprsThrow(*this, E);
1007
1008 // Some might be dependent for other reasons.
1009 case Expr::ArraySubscriptExprClass:
1010 case Expr::BinaryOperatorClass:
1011 case Expr::CompoundAssignOperatorClass:
1012 case Expr::CStyleCastExprClass:
1013 case Expr::CXXStaticCastExprClass:
1014 case Expr::CXXFunctionalCastExprClass:
1015 case Expr::ImplicitCastExprClass:
1016 case Expr::MaterializeTemporaryExprClass:
1017 case Expr::UnaryOperatorClass: {
1018 CanThrowResult CT = E->isTypeDependent() ? CT_Dependent : CT_Cannot;
1019 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1020 }
1021
1022 // FIXME: We should handle StmtExpr, but that opens a MASSIVE can of worms.
1023 case Expr::StmtExprClass:
1024 return CT_Can;
1025
Richard Smith852c9db2013-04-20 22:23:05 +00001026 case Expr::CXXDefaultArgExprClass:
1027 return canThrow(cast<CXXDefaultArgExpr>(E)->getExpr());
1028
1029 case Expr::CXXDefaultInitExprClass:
1030 return canThrow(cast<CXXDefaultInitExpr>(E)->getExpr());
1031
Richard Smithf623c962012-04-17 00:58:00 +00001032 case Expr::ChooseExprClass:
1033 if (E->isTypeDependent() || E->isValueDependent())
1034 return CT_Dependent;
Eli Friedman75807f22013-07-20 00:40:58 +00001035 return canThrow(cast<ChooseExpr>(E)->getChosenSubExpr());
Richard Smithf623c962012-04-17 00:58:00 +00001036
1037 case Expr::GenericSelectionExprClass:
1038 if (cast<GenericSelectionExpr>(E)->isResultDependent())
1039 return CT_Dependent;
1040 return canThrow(cast<GenericSelectionExpr>(E)->getResultExpr());
1041
1042 // Some expressions are always dependent.
1043 case Expr::CXXDependentScopeMemberExprClass:
1044 case Expr::CXXUnresolvedConstructExprClass:
1045 case Expr::DependentScopeDeclRefExprClass:
1046 return CT_Dependent;
1047
1048 case Expr::AsTypeExprClass:
1049 case Expr::BinaryConditionalOperatorClass:
1050 case Expr::BlockExprClass:
1051 case Expr::CUDAKernelCallExprClass:
1052 case Expr::DeclRefExprClass:
1053 case Expr::ObjCBridgedCastExprClass:
1054 case Expr::ObjCIndirectCopyRestoreExprClass:
1055 case Expr::ObjCProtocolExprClass:
1056 case Expr::ObjCSelectorExprClass:
1057 case Expr::OffsetOfExprClass:
1058 case Expr::PackExpansionExprClass:
1059 case Expr::PseudoObjectExprClass:
1060 case Expr::SubstNonTypeTemplateParmExprClass:
1061 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00001062 case Expr::FunctionParmPackExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001063 case Expr::UnaryExprOrTypeTraitExprClass:
1064 case Expr::UnresolvedLookupExprClass:
1065 case Expr::UnresolvedMemberExprClass:
1066 // FIXME: Can any of the above throw? If so, when?
1067 return CT_Cannot;
1068
1069 case Expr::AddrLabelExprClass:
1070 case Expr::ArrayTypeTraitExprClass:
1071 case Expr::AtomicExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001072 case Expr::TypeTraitExprClass:
1073 case Expr::CXXBoolLiteralExprClass:
1074 case Expr::CXXNoexceptExprClass:
1075 case Expr::CXXNullPtrLiteralExprClass:
1076 case Expr::CXXPseudoDestructorExprClass:
1077 case Expr::CXXScalarValueInitExprClass:
1078 case Expr::CXXThisExprClass:
1079 case Expr::CXXUuidofExprClass:
1080 case Expr::CharacterLiteralClass:
1081 case Expr::ExpressionTraitExprClass:
1082 case Expr::FloatingLiteralClass:
1083 case Expr::GNUNullExprClass:
1084 case Expr::ImaginaryLiteralClass:
1085 case Expr::ImplicitValueInitExprClass:
1086 case Expr::IntegerLiteralClass:
1087 case Expr::ObjCEncodeExprClass:
1088 case Expr::ObjCStringLiteralClass:
1089 case Expr::ObjCBoolLiteralExprClass:
1090 case Expr::OpaqueValueExprClass:
1091 case Expr::PredefinedExprClass:
1092 case Expr::SizeOfPackExprClass:
1093 case Expr::StringLiteralClass:
Richard Smithf623c962012-04-17 00:58:00 +00001094 // These expressions can never throw.
1095 return CT_Cannot;
1096
John McCall5e77d762013-04-16 07:28:30 +00001097 case Expr::MSPropertyRefExprClass:
1098 llvm_unreachable("Invalid class for expression");
1099
Richard Smithf623c962012-04-17 00:58:00 +00001100#define STMT(CLASS, PARENT) case Expr::CLASS##Class:
1101#define STMT_RANGE(Base, First, Last)
1102#define LAST_STMT_RANGE(BASE, FIRST, LAST)
1103#define EXPR(CLASS, PARENT)
1104#define ABSTRACT_STMT(STMT)
1105#include "clang/AST/StmtNodes.inc"
1106 case Expr::NoStmtClass:
1107 llvm_unreachable("Invalid class for expression");
1108 }
1109 llvm_unreachable("Bogus StmtClass");
1110}
1111
Sebastian Redl4915e632009-10-11 09:03:14 +00001112} // end namespace clang