blob: f2ae6bfe2ff31dd73a1df4ed1e4ee0e3ecb7c5da [file] [log] [blame]
Sebastian Redl4915e632009-10-11 09:03:14 +00001//===--- SemaExceptionSpec.cpp - C++ Exception Specifications ---*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ exception specification testing.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Richard Smith564417a2014-03-20 21:47:22 +000015#include "clang/AST/ASTMutationListener.h"
Sebastian Redl4915e632009-10-11 09:03:14 +000016#include "clang/AST/CXXInheritance.h"
17#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
Douglas Gregord6bc5e62010-03-24 07:14:45 +000019#include "clang/AST/TypeLoc.h"
Douglas Gregorf40863c2010-02-12 07:32:17 +000020#include "clang/Basic/Diagnostic.h"
21#include "clang/Basic/SourceManager.h"
Sebastian Redl4915e632009-10-11 09:03:14 +000022#include "llvm/ADT/SmallPtrSet.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000023#include "llvm/ADT/SmallString.h"
Sebastian Redl4915e632009-10-11 09:03:14 +000024
25namespace clang {
26
27static const FunctionProtoType *GetUnderlyingFunction(QualType T)
28{
29 if (const PointerType *PtrTy = T->getAs<PointerType>())
30 T = PtrTy->getPointeeType();
31 else if (const ReferenceType *RefTy = T->getAs<ReferenceType>())
32 T = RefTy->getPointeeType();
Sebastian Redl075b21d2009-10-14 14:38:54 +000033 else if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
34 T = MPTy->getPointeeType();
Sebastian Redl4915e632009-10-11 09:03:14 +000035 return T->getAs<FunctionProtoType>();
36}
37
Richard Smith6403e932014-11-14 00:37:55 +000038/// HACK: libstdc++ has a bug where it shadows std::swap with a member
39/// swap function then tries to call std::swap unqualified from the exception
40/// specification of that function. This function detects whether we're in
41/// such a case and turns off delay-parsing of exception specifications.
42bool Sema::isLibstdcxxEagerExceptionSpecHack(const Declarator &D) {
43 auto *RD = dyn_cast<CXXRecordDecl>(CurContext);
44
45 // All the problem cases are member functions named "swap" within class
46 // templates declared directly within namespace std.
47 if (!RD || RD->getEnclosingNamespaceContext() != getStdNamespace() ||
48 !RD->getIdentifier() || !RD->getDescribedClassTemplate() ||
49 !D.getIdentifier() || !D.getIdentifier()->isStr("swap"))
50 return false;
51
52 // Only apply this hack within a system header.
53 if (!Context.getSourceManager().isInSystemHeader(D.getLocStart()))
54 return false;
55
56 return llvm::StringSwitch<bool>(RD->getIdentifier()->getName())
57 .Case("array", true)
58 .Case("pair", true)
59 .Case("priority_queue", true)
60 .Case("stack", true)
61 .Case("queue", true)
62 .Default(false);
63}
64
Sebastian Redl4915e632009-10-11 09:03:14 +000065/// CheckSpecifiedExceptionType - Check if the given type is valid in an
66/// exception specification. Incomplete types, or pointers to incomplete types
67/// other than void are not allowed.
Richard Smith8606d752012-11-28 22:33:28 +000068///
69/// \param[in,out] T The exception type. This will be decayed to a pointer type
70/// when the input is an array or a function type.
Craig Toppere335f252015-10-04 04:53:55 +000071bool Sema::CheckSpecifiedExceptionType(QualType &T, SourceRange Range) {
Richard Smitha118c6a2012-11-28 22:52:42 +000072 // C++11 [except.spec]p2:
73 // A type cv T, "array of T", or "function returning T" denoted
Richard Smith8606d752012-11-28 22:33:28 +000074 // in an exception-specification is adjusted to type T, "pointer to T", or
75 // "pointer to function returning T", respectively.
Richard Smitha118c6a2012-11-28 22:52:42 +000076 //
77 // We also apply this rule in C++98.
Richard Smith8606d752012-11-28 22:33:28 +000078 if (T->isArrayType())
79 T = Context.getArrayDecayedType(T);
80 else if (T->isFunctionType())
81 T = Context.getPointerType(T);
Sebastian Redl4915e632009-10-11 09:03:14 +000082
Richard Smitha118c6a2012-11-28 22:52:42 +000083 int Kind = 0;
Richard Smith8606d752012-11-28 22:33:28 +000084 QualType PointeeT = T;
Richard Smitha118c6a2012-11-28 22:52:42 +000085 if (const PointerType *PT = T->getAs<PointerType>()) {
86 PointeeT = PT->getPointeeType();
87 Kind = 1;
Sebastian Redl4915e632009-10-11 09:03:14 +000088
Richard Smitha118c6a2012-11-28 22:52:42 +000089 // cv void* is explicitly permitted, despite being a pointer to an
90 // incomplete type.
91 if (PointeeT->isVoidType())
92 return false;
93 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
94 PointeeT = RT->getPointeeType();
95 Kind = 2;
Richard Smith8606d752012-11-28 22:33:28 +000096
Richard Smitha118c6a2012-11-28 22:52:42 +000097 if (RT->isRValueReferenceType()) {
98 // C++11 [except.spec]p2:
99 // A type denoted in an exception-specification shall not denote [...]
100 // an rvalue reference type.
101 Diag(Range.getBegin(), diag::err_rref_in_exception_spec)
102 << T << Range;
103 return true;
104 }
105 }
106
107 // C++11 [except.spec]p2:
108 // A type denoted in an exception-specification shall not denote an
109 // incomplete type other than a class currently being defined [...].
110 // A type denoted in an exception-specification shall not denote a
111 // pointer or reference to an incomplete type, other than (cv) void* or a
112 // pointer or reference to a class currently being defined.
David Majnemerb2b0da42016-06-10 18:24:41 +0000113 // In Microsoft mode, downgrade this to a warning.
114 unsigned DiagID = diag::err_incomplete_in_exception_spec;
115 if (getLangOpts().MicrosoftExt)
116 DiagID = diag::ext_incomplete_in_exception_spec;
Richard Smitha118c6a2012-11-28 22:52:42 +0000117 if (!(PointeeT->isRecordType() &&
118 PointeeT->getAs<RecordType>()->isBeingDefined()) &&
David Majnemerb2b0da42016-06-10 18:24:41 +0000119 RequireCompleteType(Range.getBegin(), PointeeT, DiagID, Kind, Range))
Sebastian Redl7eb5d372009-10-14 14:59:48 +0000120 return true;
Sebastian Redl4915e632009-10-11 09:03:14 +0000121
122 return false;
123}
124
125/// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer
126/// to member to a function with an exception specification. This means that
127/// it is invalid to add another level of indirection.
128bool Sema::CheckDistantExceptionSpec(QualType T) {
129 if (const PointerType *PT = T->getAs<PointerType>())
130 T = PT->getPointeeType();
131 else if (const MemberPointerType *PT = T->getAs<MemberPointerType>())
132 T = PT->getPointeeType();
133 else
134 return false;
135
136 const FunctionProtoType *FnT = T->getAs<FunctionProtoType>();
137 if (!FnT)
138 return false;
139
140 return FnT->hasExceptionSpec();
141}
142
Richard Smithf623c962012-04-17 00:58:00 +0000143const FunctionProtoType *
144Sema::ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT) {
Richard Smith0b3a4622014-11-13 20:01:57 +0000145 if (FPT->getExceptionSpecType() == EST_Unparsed) {
146 Diag(Loc, diag::err_exception_spec_not_parsed);
147 return nullptr;
148 }
149
Richard Smithd3b5c9082012-07-27 04:22:15 +0000150 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
Richard Smithf623c962012-04-17 00:58:00 +0000151 return FPT;
152
153 FunctionDecl *SourceDecl = FPT->getExceptionSpecDecl();
154 const FunctionProtoType *SourceFPT =
155 SourceDecl->getType()->castAs<FunctionProtoType>();
156
Richard Smithd3b5c9082012-07-27 04:22:15 +0000157 // If the exception specification has already been resolved, just return it.
158 if (!isUnresolvedExceptionSpec(SourceFPT->getExceptionSpecType()))
Richard Smithf623c962012-04-17 00:58:00 +0000159 return SourceFPT;
160
Richard Smithd3b5c9082012-07-27 04:22:15 +0000161 // Compute or instantiate the exception specification now.
Richard Smith3901dfe2013-03-27 00:22:47 +0000162 if (SourceFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smithd3b5c9082012-07-27 04:22:15 +0000163 EvaluateImplicitExceptionSpec(Loc, cast<CXXMethodDecl>(SourceDecl));
164 else
165 InstantiateExceptionSpec(Loc, SourceDecl);
Richard Smithf623c962012-04-17 00:58:00 +0000166
Davide Italiano922b7022015-07-25 01:19:32 +0000167 const FunctionProtoType *Proto =
168 SourceDecl->getType()->castAs<FunctionProtoType>();
169 if (Proto->getExceptionSpecType() == clang::EST_Unparsed) {
170 Diag(Loc, diag::err_exception_spec_not_parsed);
171 Proto = nullptr;
172 }
173 return Proto;
Richard Smithf623c962012-04-17 00:58:00 +0000174}
175
Richard Smith8acb4282014-07-31 21:57:55 +0000176void
177Sema::UpdateExceptionSpec(FunctionDecl *FD,
178 const FunctionProtoType::ExceptionSpecInfo &ESI) {
Richard Smith564417a2014-03-20 21:47:22 +0000179 // If we've fully resolved the exception specification, notify listeners.
Richard Smith8acb4282014-07-31 21:57:55 +0000180 if (!isUnresolvedExceptionSpec(ESI.Type))
Richard Smith564417a2014-03-20 21:47:22 +0000181 if (auto *Listener = getASTMutationListener())
182 Listener->ResolvedExceptionSpec(FD);
Richard Smith9e2341d2015-03-23 03:25:59 +0000183
184 for (auto *Redecl : FD->redecls())
185 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith564417a2014-03-20 21:47:22 +0000186}
187
Richard Smith66f3ac92012-10-20 08:26:51 +0000188/// Determine whether a function has an implicitly-generated exception
Richard Smith1ee63522012-10-16 23:30:16 +0000189/// specification.
Richard Smith66f3ac92012-10-20 08:26:51 +0000190static bool hasImplicitExceptionSpec(FunctionDecl *Decl) {
191 if (!isa<CXXDestructorDecl>(Decl) &&
192 Decl->getDeclName().getCXXOverloadedOperator() != OO_Delete &&
193 Decl->getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
194 return false;
Richard Smith1ee63522012-10-16 23:30:16 +0000195
Richard Smithc7fb2252014-02-07 22:51:16 +0000196 // For a function that the user didn't declare:
197 // - if this is a destructor, its exception specification is implicit.
198 // - if this is 'operator delete' or 'operator delete[]', the exception
199 // specification is as-if an explicit exception specification was given
200 // (per [basic.stc.dynamic]p2).
Richard Smith66f3ac92012-10-20 08:26:51 +0000201 if (!Decl->getTypeSourceInfo())
Richard Smithc7fb2252014-02-07 22:51:16 +0000202 return isa<CXXDestructorDecl>(Decl);
Richard Smith66f3ac92012-10-20 08:26:51 +0000203
204 const FunctionProtoType *Ty =
205 Decl->getTypeSourceInfo()->getType()->getAs<FunctionProtoType>();
206 return !Ty->hasExceptionSpec();
Richard Smith1ee63522012-10-16 23:30:16 +0000207}
208
Douglas Gregorf40863c2010-02-12 07:32:17 +0000209bool Sema::CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New) {
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000210 OverloadedOperatorKind OO = New->getDeclName().getCXXOverloadedOperator();
211 bool IsOperatorNew = OO == OO_New || OO == OO_Array_New;
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000212 bool MissingExceptionSpecification = false;
Douglas Gregorf40863c2010-02-12 07:32:17 +0000213 bool MissingEmptyExceptionSpecification = false;
Hans Wennborg39a509a2014-02-05 02:37:58 +0000214
Francois Pichet13b4e682011-03-19 23:05:18 +0000215 unsigned DiagID = diag::err_mismatched_exception_spec;
Hans Wennborg39a509a2014-02-05 02:37:58 +0000216 bool ReturnValueOnError = true;
217 if (getLangOpts().MicrosoftExt) {
Richard Smith1b98ccc2014-07-19 01:39:17 +0000218 DiagID = diag::ext_mismatched_exception_spec;
Hans Wennborg39a509a2014-02-05 02:37:58 +0000219 ReturnValueOnError = false;
220 }
Richard Smithf623c962012-04-17 00:58:00 +0000221
Richard Smith1ee63522012-10-16 23:30:16 +0000222 // Check the types as written: they must match before any exception
223 // specification adjustment is applied.
224 if (!CheckEquivalentExceptionSpec(
225 PDiag(DiagID), PDiag(diag::note_previous_declaration),
Richard Smith66f3ac92012-10-20 08:26:51 +0000226 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
227 New->getType()->getAs<FunctionProtoType>(), New->getLocation(),
Richard Smith1ee63522012-10-16 23:30:16 +0000228 &MissingExceptionSpecification, &MissingEmptyExceptionSpecification,
Richard Smith66f3ac92012-10-20 08:26:51 +0000229 /*AllowNoexceptAllMatchWithNoSpec=*/true, IsOperatorNew)) {
230 // C++11 [except.spec]p4 [DR1492]:
231 // If a declaration of a function has an implicit
232 // exception-specification, other declarations of the function shall
233 // not specify an exception-specification.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000234 if (getLangOpts().CPlusPlus11 &&
Richard Smith66f3ac92012-10-20 08:26:51 +0000235 hasImplicitExceptionSpec(Old) != hasImplicitExceptionSpec(New)) {
236 Diag(New->getLocation(), diag::ext_implicit_exception_spec_mismatch)
237 << hasImplicitExceptionSpec(Old);
Yaron Keren8b563662015-10-03 10:46:20 +0000238 if (Old->getLocation().isValid())
Richard Smith66f3ac92012-10-20 08:26:51 +0000239 Diag(Old->getLocation(), diag::note_previous_declaration);
240 }
Douglas Gregorf40863c2010-02-12 07:32:17 +0000241 return false;
Richard Smith66f3ac92012-10-20 08:26:51 +0000242 }
Douglas Gregorf40863c2010-02-12 07:32:17 +0000243
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000244 // The failure was something other than an missing exception
Hans Wennborg39a509a2014-02-05 02:37:58 +0000245 // specification; return an error, except in MS mode where this is a warning.
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000246 if (!MissingExceptionSpecification)
Hans Wennborg39a509a2014-02-05 02:37:58 +0000247 return ReturnValueOnError;
Douglas Gregorf40863c2010-02-12 07:32:17 +0000248
Richard Smith66f3ac92012-10-20 08:26:51 +0000249 const FunctionProtoType *NewProto =
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000250 New->getType()->castAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +0000251
Douglas Gregorf40863c2010-02-12 07:32:17 +0000252 // The new function declaration is only missing an empty exception
253 // specification "throw()". If the throw() specification came from a
254 // function in a system header that has C linkage, just add an empty
255 // exception specification to the "new" declaration. This is an
256 // egregious workaround for glibc, which adds throw() specifications
257 // to many libc functions as an optimization. Unfortunately, that
258 // optimization isn't permitted by the C++ standard, so we're forced
259 // to work around it here.
John McCalldb40c7f2010-12-14 08:05:40 +0000260 if (MissingEmptyExceptionSpecification && NewProto &&
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000261 (Old->getLocation().isInvalid() ||
262 Context.getSourceManager().isInSystemHeader(Old->getLocation())) &&
Douglas Gregorf40863c2010-02-12 07:32:17 +0000263 Old->isExternC()) {
Richard Smith8acb4282014-07-31 21:57:55 +0000264 New->setType(Context.getFunctionType(
265 NewProto->getReturnType(), NewProto->getParamTypes(),
266 NewProto->getExtProtoInfo().withExceptionSpec(EST_DynamicNone)));
Douglas Gregorf40863c2010-02-12 07:32:17 +0000267 return false;
268 }
269
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000270 const FunctionProtoType *OldProto =
271 Old->getType()->castAs<FunctionProtoType>();
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000272
Richard Smith8acb4282014-07-31 21:57:55 +0000273 FunctionProtoType::ExceptionSpecInfo ESI = OldProto->getExceptionSpecType();
274 if (ESI.Type == EST_Dynamic) {
275 ESI.Exceptions = OldProto->exceptions();
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000276 }
277
Richard Smitha91de372015-09-30 00:48:50 +0000278 if (ESI.Type == EST_ComputedNoexcept) {
279 // For computed noexcept, we can't just take the expression from the old
280 // prototype. It likely contains references to the old prototype's
281 // parameters.
282 New->setInvalidDecl();
283 } else {
284 // Update the type of the function with the appropriate exception
285 // specification.
286 New->setType(Context.getFunctionType(
287 NewProto->getReturnType(), NewProto->getParamTypes(),
288 NewProto->getExtProtoInfo().withExceptionSpec(ESI)));
289 }
290
David Majnemer06ce8a42015-10-20 20:49:21 +0000291 if (getLangOpts().MicrosoftExt && ESI.Type != EST_ComputedNoexcept) {
292 // Allow missing exception specifications in redeclarations as an extension.
293 DiagID = diag::ext_ms_missing_exception_specification;
294 ReturnValueOnError = false;
295 } else if (New->isReplaceableGlobalAllocationFunction() &&
296 ESI.Type != EST_ComputedNoexcept) {
297 // Allow missing exception specifications in redeclarations as an extension,
298 // when declaring a replaceable global allocation function.
Richard Smitha91de372015-09-30 00:48:50 +0000299 DiagID = diag::ext_missing_exception_specification;
300 ReturnValueOnError = false;
301 } else {
302 DiagID = diag::err_missing_exception_specification;
303 ReturnValueOnError = true;
304 }
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000305
306 // Warn about the lack of exception specification.
307 SmallString<128> ExceptionSpecString;
308 llvm::raw_svector_ostream OS(ExceptionSpecString);
309 switch (OldProto->getExceptionSpecType()) {
310 case EST_DynamicNone:
311 OS << "throw()";
312 break;
313
314 case EST_Dynamic: {
315 OS << "throw(";
316 bool OnFirstException = true;
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000317 for (const auto &E : OldProto->exceptions()) {
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000318 if (OnFirstException)
319 OnFirstException = false;
320 else
321 OS << ", ";
322
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000323 OS << E.getAsString(getPrintingPolicy());
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000324 }
325 OS << ")";
326 break;
327 }
328
329 case EST_BasicNoexcept:
330 OS << "noexcept";
331 break;
332
333 case EST_ComputedNoexcept:
334 OS << "noexcept(";
Richard Trieuddd01ce2014-06-09 22:53:25 +0000335 assert(OldProto->getNoexceptExpr() != nullptr && "Expected non-null Expr");
Craig Topperc3ec1492014-05-26 06:22:03 +0000336 OldProto->getNoexceptExpr()->printPretty(OS, nullptr, getPrintingPolicy());
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000337 OS << ")";
338 break;
339
340 default:
341 llvm_unreachable("This spec type is compatible with none.");
342 }
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000343
344 SourceLocation FixItLoc;
345 if (TypeSourceInfo *TSInfo = New->getTypeSourceInfo()) {
346 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Richard Smitha91de372015-09-30 00:48:50 +0000347 // FIXME: Preserve enough information so that we can produce a correct fixit
348 // location when there is a trailing return type.
349 if (auto FTLoc = TL.getAs<FunctionProtoTypeLoc>())
350 if (!FTLoc.getTypePtr()->hasTrailingReturn())
351 FixItLoc = getLocForEndOfToken(FTLoc.getLocalRangeEnd());
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000352 }
353
354 if (FixItLoc.isInvalid())
Richard Smitha91de372015-09-30 00:48:50 +0000355 Diag(New->getLocation(), DiagID)
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000356 << New << OS.str();
357 else {
Richard Smitha91de372015-09-30 00:48:50 +0000358 Diag(New->getLocation(), DiagID)
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000359 << New << OS.str()
360 << FixItHint::CreateInsertion(FixItLoc, " " + OS.str().str());
361 }
362
Yaron Keren8b563662015-10-03 10:46:20 +0000363 if (Old->getLocation().isValid())
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000364 Diag(Old->getLocation(), diag::note_previous_declaration);
365
Richard Smitha91de372015-09-30 00:48:50 +0000366 return ReturnValueOnError;
Douglas Gregorf40863c2010-02-12 07:32:17 +0000367}
368
Sebastian Redl4915e632009-10-11 09:03:14 +0000369/// CheckEquivalentExceptionSpec - Check if the two types have equivalent
370/// exception specifications. Exception specifications are equivalent if
371/// they allow exactly the same set of exception types. It does not matter how
372/// that is achieved. See C++ [except.spec]p2.
373bool Sema::CheckEquivalentExceptionSpec(
374 const FunctionProtoType *Old, SourceLocation OldLoc,
375 const FunctionProtoType *New, SourceLocation NewLoc) {
Francois Pichet13b4e682011-03-19 23:05:18 +0000376 unsigned DiagID = diag::err_mismatched_exception_spec;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000377 if (getLangOpts().MicrosoftExt)
Richard Smith1b98ccc2014-07-19 01:39:17 +0000378 DiagID = diag::ext_mismatched_exception_spec;
Hans Wennborg39a509a2014-02-05 02:37:58 +0000379 bool Result = CheckEquivalentExceptionSpec(PDiag(DiagID),
380 PDiag(diag::note_previous_declaration), Old, OldLoc, New, NewLoc);
381
382 // In Microsoft mode, mismatching exception specifications just cause a warning.
383 if (getLangOpts().MicrosoftExt)
384 return false;
385 return Result;
Sebastian Redl4915e632009-10-11 09:03:14 +0000386}
387
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000388/// CheckEquivalentExceptionSpec - Check if the two types have compatible
389/// exception specifications. See C++ [except.spec]p3.
Richard Smith66f3ac92012-10-20 08:26:51 +0000390///
391/// \return \c false if the exception specifications match, \c true if there is
392/// a problem. If \c true is returned, either a diagnostic has already been
393/// produced or \c *MissingExceptionSpecification is set to \c true.
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000394bool Sema::CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000395 const PartialDiagnostic & NoteID,
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000396 const FunctionProtoType *Old,
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000397 SourceLocation OldLoc,
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000398 const FunctionProtoType *New,
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000399 SourceLocation NewLoc,
400 bool *MissingExceptionSpecification,
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000401 bool*MissingEmptyExceptionSpecification,
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000402 bool AllowNoexceptAllMatchWithNoSpec,
403 bool IsOperatorNew) {
John McCallf9c94092010-05-28 08:37:35 +0000404 // Just completely ignore this under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000405 if (!getLangOpts().CXXExceptions)
John McCallf9c94092010-05-28 08:37:35 +0000406 return false;
407
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000408 if (MissingExceptionSpecification)
409 *MissingExceptionSpecification = false;
410
Douglas Gregorf40863c2010-02-12 07:32:17 +0000411 if (MissingEmptyExceptionSpecification)
412 *MissingEmptyExceptionSpecification = false;
413
Richard Smithf623c962012-04-17 00:58:00 +0000414 Old = ResolveExceptionSpec(NewLoc, Old);
415 if (!Old)
416 return false;
417 New = ResolveExceptionSpec(NewLoc, New);
418 if (!New)
419 return false;
420
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000421 // C++0x [except.spec]p3: Two exception-specifications are compatible if:
422 // - both are non-throwing, regardless of their form,
423 // - both have the form noexcept(constant-expression) and the constant-
424 // expressions are equivalent,
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000425 // - both are dynamic-exception-specifications that have the same set of
426 // adjusted types.
427 //
Eric Christophere6b7cf42015-07-10 18:25:52 +0000428 // C++0x [except.spec]p12: An exception-specification is non-throwing if it is
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000429 // of the form throw(), noexcept, or noexcept(constant-expression) where the
430 // constant-expression yields true.
431 //
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000432 // C++0x [except.spec]p4: If any declaration of a function has an exception-
433 // specifier that is not a noexcept-specification allowing all exceptions,
434 // all declarations [...] of that function shall have a compatible
435 // exception-specification.
436 //
437 // That last point basically means that noexcept(false) matches no spec.
438 // It's considered when AllowNoexceptAllMatchWithNoSpec is true.
439
440 ExceptionSpecificationType OldEST = Old->getExceptionSpecType();
441 ExceptionSpecificationType NewEST = New->getExceptionSpecType();
442
Richard Smithd3b5c9082012-07-27 04:22:15 +0000443 assert(!isUnresolvedExceptionSpec(OldEST) &&
444 !isUnresolvedExceptionSpec(NewEST) &&
Richard Smith938f40b2011-06-11 17:19:42 +0000445 "Shouldn't see unknown exception specifications here");
446
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000447 // Shortcut the case where both have no spec.
448 if (OldEST == EST_None && NewEST == EST_None)
449 return false;
450
Sebastian Redl31ad7542011-03-13 17:09:40 +0000451 FunctionProtoType::NoexceptResult OldNR = Old->getNoexceptSpec(Context);
452 FunctionProtoType::NoexceptResult NewNR = New->getNoexceptSpec(Context);
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000453 if (OldNR == FunctionProtoType::NR_BadNoexcept ||
454 NewNR == FunctionProtoType::NR_BadNoexcept)
455 return false;
456
457 // Dependent noexcept specifiers are compatible with each other, but nothing
458 // else.
459 // One noexcept is compatible with another if the argument is the same
460 if (OldNR == NewNR &&
461 OldNR != FunctionProtoType::NR_NoNoexcept &&
462 NewNR != FunctionProtoType::NR_NoNoexcept)
463 return false;
464 if (OldNR != NewNR &&
465 OldNR != FunctionProtoType::NR_NoNoexcept &&
466 NewNR != FunctionProtoType::NR_NoNoexcept) {
467 Diag(NewLoc, DiagID);
David Majnemer7da23022015-02-19 07:28:55 +0000468 if (NoteID.getDiagID() != 0 && OldLoc.isValid())
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000469 Diag(OldLoc, NoteID);
470 return true;
Douglas Gregorf62c5292010-08-30 15:04:51 +0000471 }
472
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000473 // The MS extension throw(...) is compatible with itself.
474 if (OldEST == EST_MSAny && NewEST == EST_MSAny)
Sebastian Redl4915e632009-10-11 09:03:14 +0000475 return false;
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000476
477 // It's also compatible with no spec.
478 if ((OldEST == EST_None && NewEST == EST_MSAny) ||
479 (OldEST == EST_MSAny && NewEST == EST_None))
480 return false;
481
482 // It's also compatible with noexcept(false).
483 if (OldEST == EST_MSAny && NewNR == FunctionProtoType::NR_Throw)
484 return false;
485 if (NewEST == EST_MSAny && OldNR == FunctionProtoType::NR_Throw)
486 return false;
487
488 // As described above, noexcept(false) matches no spec only for functions.
489 if (AllowNoexceptAllMatchWithNoSpec) {
490 if (OldEST == EST_None && NewNR == FunctionProtoType::NR_Throw)
491 return false;
492 if (NewEST == EST_None && OldNR == FunctionProtoType::NR_Throw)
493 return false;
494 }
495
496 // Any non-throwing specifications are compatible.
497 bool OldNonThrowing = OldNR == FunctionProtoType::NR_Nothrow ||
498 OldEST == EST_DynamicNone;
499 bool NewNonThrowing = NewNR == FunctionProtoType::NR_Nothrow ||
500 NewEST == EST_DynamicNone;
501 if (OldNonThrowing && NewNonThrowing)
502 return false;
503
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000504 // As a special compatibility feature, under C++0x we accept no spec and
505 // throw(std::bad_alloc) as equivalent for operator new and operator new[].
506 // This is because the implicit declaration changed, but old code would break.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000507 if (getLangOpts().CPlusPlus11 && IsOperatorNew) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000508 const FunctionProtoType *WithExceptions = nullptr;
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000509 if (OldEST == EST_None && NewEST == EST_Dynamic)
510 WithExceptions = New;
511 else if (OldEST == EST_Dynamic && NewEST == EST_None)
512 WithExceptions = Old;
513 if (WithExceptions && WithExceptions->getNumExceptions() == 1) {
514 // One has no spec, the other throw(something). If that something is
515 // std::bad_alloc, all conditions are met.
516 QualType Exception = *WithExceptions->exception_begin();
517 if (CXXRecordDecl *ExRecord = Exception->getAsCXXRecordDecl()) {
518 IdentifierInfo* Name = ExRecord->getIdentifier();
519 if (Name && Name->getName() == "bad_alloc") {
520 // It's called bad_alloc, but is it in std?
Richard Trieuc771d5d2014-05-28 02:16:01 +0000521 if (ExRecord->isInStdNamespace()) {
522 return false;
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000523 }
524 }
525 }
526 }
527 }
528
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000529 // At this point, the only remaining valid case is two matching dynamic
530 // specifications. We return here unless both specifications are dynamic.
531 if (OldEST != EST_Dynamic || NewEST != EST_Dynamic) {
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000532 if (MissingExceptionSpecification && Old->hasExceptionSpec() &&
Douglas Gregorf40863c2010-02-12 07:32:17 +0000533 !New->hasExceptionSpec()) {
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000534 // The old type has an exception specification of some sort, but
535 // the new type does not.
536 *MissingExceptionSpecification = true;
537
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000538 if (MissingEmptyExceptionSpecification && OldNonThrowing) {
539 // The old type has a throw() or noexcept(true) exception specification
540 // and the new type has no exception specification, and the caller asked
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000541 // to handle this itself.
542 *MissingEmptyExceptionSpecification = true;
543 }
544
Douglas Gregorf40863c2010-02-12 07:32:17 +0000545 return true;
546 }
547
Sebastian Redl4915e632009-10-11 09:03:14 +0000548 Diag(NewLoc, DiagID);
David Majnemer7da23022015-02-19 07:28:55 +0000549 if (NoteID.getDiagID() != 0 && OldLoc.isValid())
Sebastian Redl4915e632009-10-11 09:03:14 +0000550 Diag(OldLoc, NoteID);
551 return true;
552 }
553
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000554 assert(OldEST == EST_Dynamic && NewEST == EST_Dynamic &&
555 "Exception compatibility logic error: non-dynamic spec slipped through.");
556
Sebastian Redl4915e632009-10-11 09:03:14 +0000557 bool Success = true;
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000558 // Both have a dynamic exception spec. Collect the first set, then compare
Sebastian Redl4915e632009-10-11 09:03:14 +0000559 // to the second.
Sebastian Redl184edca2009-10-14 15:06:25 +0000560 llvm::SmallPtrSet<CanQualType, 8> OldTypes, NewTypes;
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000561 for (const auto &I : Old->exceptions())
562 OldTypes.insert(Context.getCanonicalType(I).getUnqualifiedType());
Sebastian Redl4915e632009-10-11 09:03:14 +0000563
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000564 for (const auto &I : New->exceptions()) {
565 CanQualType TypePtr = Context.getCanonicalType(I).getUnqualifiedType();
Sebastian Redl6e4c8712009-10-11 09:11:23 +0000566 if(OldTypes.count(TypePtr))
567 NewTypes.insert(TypePtr);
568 else
569 Success = false;
570 }
Sebastian Redl4915e632009-10-11 09:03:14 +0000571
Sebastian Redl6e4c8712009-10-11 09:11:23 +0000572 Success = Success && OldTypes.size() == NewTypes.size();
Sebastian Redl4915e632009-10-11 09:03:14 +0000573
574 if (Success) {
575 return false;
576 }
577 Diag(NewLoc, DiagID);
David Majnemer7da23022015-02-19 07:28:55 +0000578 if (NoteID.getDiagID() != 0 && OldLoc.isValid())
Sebastian Redl4915e632009-10-11 09:03:14 +0000579 Diag(OldLoc, NoteID);
580 return true;
581}
582
583/// CheckExceptionSpecSubset - Check whether the second function type's
584/// exception specification is a subset (or equivalent) of the first function
585/// type. This is used by override and pointer assignment checks.
Sebastian Redla44822f2009-10-14 16:09:29 +0000586bool Sema::CheckExceptionSpecSubset(
587 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
Sebastian Redl4915e632009-10-11 09:03:14 +0000588 const FunctionProtoType *Superset, SourceLocation SuperLoc,
589 const FunctionProtoType *Subset, SourceLocation SubLoc) {
John McCallf9c94092010-05-28 08:37:35 +0000590
591 // Just auto-succeed under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000592 if (!getLangOpts().CXXExceptions)
John McCallf9c94092010-05-28 08:37:35 +0000593 return false;
594
Sebastian Redl4915e632009-10-11 09:03:14 +0000595 // FIXME: As usual, we could be more specific in our error messages, but
596 // that better waits until we've got types with source locations.
597
598 if (!SubLoc.isValid())
599 SubLoc = SuperLoc;
600
Richard Smithf623c962012-04-17 00:58:00 +0000601 // Resolve the exception specifications, if needed.
602 Superset = ResolveExceptionSpec(SuperLoc, Superset);
603 if (!Superset)
604 return false;
605 Subset = ResolveExceptionSpec(SubLoc, Subset);
606 if (!Subset)
607 return false;
608
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000609 ExceptionSpecificationType SuperEST = Superset->getExceptionSpecType();
610
Sebastian Redl4915e632009-10-11 09:03:14 +0000611 // If superset contains everything, we're done.
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000612 if (SuperEST == EST_None || SuperEST == EST_MSAny)
Sebastian Redl4915e632009-10-11 09:03:14 +0000613 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
614
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000615 // If there are dependent noexcept specs, assume everything is fine. Unlike
616 // with the equivalency check, this is safe in this case, because we don't
617 // want to merge declarations. Checks after instantiation will catch any
618 // omissions we make here.
619 // We also shortcut checking if a noexcept expression was bad.
620
Sebastian Redl31ad7542011-03-13 17:09:40 +0000621 FunctionProtoType::NoexceptResult SuperNR =Superset->getNoexceptSpec(Context);
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000622 if (SuperNR == FunctionProtoType::NR_BadNoexcept ||
623 SuperNR == FunctionProtoType::NR_Dependent)
624 return false;
625
626 // Another case of the superset containing everything.
627 if (SuperNR == FunctionProtoType::NR_Throw)
628 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
629
630 ExceptionSpecificationType SubEST = Subset->getExceptionSpecType();
631
Richard Smithd3b5c9082012-07-27 04:22:15 +0000632 assert(!isUnresolvedExceptionSpec(SuperEST) &&
633 !isUnresolvedExceptionSpec(SubEST) &&
Richard Smith938f40b2011-06-11 17:19:42 +0000634 "Shouldn't see unknown exception specifications here");
635
Sebastian Redl4915e632009-10-11 09:03:14 +0000636 // It does not. If the subset contains everything, we've failed.
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000637 if (SubEST == EST_None || SubEST == EST_MSAny) {
Sebastian Redl4915e632009-10-11 09:03:14 +0000638 Diag(SubLoc, DiagID);
Sebastian Redla44822f2009-10-14 16:09:29 +0000639 if (NoteID.getDiagID() != 0)
Sebastian Redl4915e632009-10-11 09:03:14 +0000640 Diag(SuperLoc, NoteID);
641 return true;
642 }
643
Sebastian Redl31ad7542011-03-13 17:09:40 +0000644 FunctionProtoType::NoexceptResult SubNR = Subset->getNoexceptSpec(Context);
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000645 if (SubNR == FunctionProtoType::NR_BadNoexcept ||
646 SubNR == FunctionProtoType::NR_Dependent)
647 return false;
648
649 // Another case of the subset containing everything.
650 if (SubNR == FunctionProtoType::NR_Throw) {
651 Diag(SubLoc, DiagID);
652 if (NoteID.getDiagID() != 0)
653 Diag(SuperLoc, NoteID);
654 return true;
655 }
656
657 // If the subset contains nothing, we're done.
658 if (SubEST == EST_DynamicNone || SubNR == FunctionProtoType::NR_Nothrow)
659 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
660
661 // Otherwise, if the superset contains nothing, we've failed.
662 if (SuperEST == EST_DynamicNone || SuperNR == FunctionProtoType::NR_Nothrow) {
663 Diag(SubLoc, DiagID);
664 if (NoteID.getDiagID() != 0)
665 Diag(SuperLoc, NoteID);
666 return true;
667 }
668
669 assert(SuperEST == EST_Dynamic && SubEST == EST_Dynamic &&
670 "Exception spec subset: non-dynamic case slipped through.");
671
672 // Neither contains everything or nothing. Do a proper comparison.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000673 for (const auto &SubI : Subset->exceptions()) {
Sebastian Redl4915e632009-10-11 09:03:14 +0000674 // Take one type from the subset.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000675 QualType CanonicalSubT = Context.getCanonicalType(SubI);
Sebastian Redl075b21d2009-10-14 14:38:54 +0000676 // Unwrap pointers and references so that we can do checks within a class
677 // hierarchy. Don't unwrap member pointers; they don't have hierarchy
678 // conversions on the pointee.
Sebastian Redl4915e632009-10-11 09:03:14 +0000679 bool SubIsPointer = false;
680 if (const ReferenceType *RefTy = CanonicalSubT->getAs<ReferenceType>())
681 CanonicalSubT = RefTy->getPointeeType();
682 if (const PointerType *PtrTy = CanonicalSubT->getAs<PointerType>()) {
683 CanonicalSubT = PtrTy->getPointeeType();
684 SubIsPointer = true;
685 }
686 bool SubIsClass = CanonicalSubT->isRecordType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000687 CanonicalSubT = CanonicalSubT.getLocalUnqualifiedType();
Sebastian Redl4915e632009-10-11 09:03:14 +0000688
689 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
690 /*DetectVirtual=*/false);
691
692 bool Contained = false;
693 // Make sure it's in the superset.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000694 for (const auto &SuperI : Superset->exceptions()) {
695 QualType CanonicalSuperT = Context.getCanonicalType(SuperI);
Sebastian Redl4915e632009-10-11 09:03:14 +0000696 // SubT must be SuperT or derived from it, or pointer or reference to
697 // such types.
698 if (const ReferenceType *RefTy = CanonicalSuperT->getAs<ReferenceType>())
699 CanonicalSuperT = RefTy->getPointeeType();
700 if (SubIsPointer) {
701 if (const PointerType *PtrTy = CanonicalSuperT->getAs<PointerType>())
702 CanonicalSuperT = PtrTy->getPointeeType();
703 else {
704 continue;
705 }
706 }
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000707 CanonicalSuperT = CanonicalSuperT.getLocalUnqualifiedType();
Sebastian Redl4915e632009-10-11 09:03:14 +0000708 // If the types are the same, move on to the next type in the subset.
709 if (CanonicalSubT == CanonicalSuperT) {
710 Contained = true;
711 break;
712 }
713
714 // Otherwise we need to check the inheritance.
715 if (!SubIsClass || !CanonicalSuperT->isRecordType())
716 continue;
717
718 Paths.clear();
Richard Smith0f59cb32015-12-18 21:45:41 +0000719 if (!IsDerivedFrom(SubLoc, CanonicalSubT, CanonicalSuperT, Paths))
Sebastian Redl4915e632009-10-11 09:03:14 +0000720 continue;
721
Douglas Gregor27ac4292010-05-21 20:29:55 +0000722 if (Paths.isAmbiguous(Context.getCanonicalType(CanonicalSuperT)))
Sebastian Redl4915e632009-10-11 09:03:14 +0000723 continue;
724
John McCall5b0829a2010-02-10 09:31:12 +0000725 // Do this check from a context without privileges.
John McCall1064d7e2010-03-16 05:22:47 +0000726 switch (CheckBaseClassAccess(SourceLocation(),
John McCall5b0829a2010-02-10 09:31:12 +0000727 CanonicalSuperT, CanonicalSubT,
728 Paths.front(),
John McCall1064d7e2010-03-16 05:22:47 +0000729 /*Diagnostic*/ 0,
John McCall5b0829a2010-02-10 09:31:12 +0000730 /*ForceCheck*/ true,
John McCall1064d7e2010-03-16 05:22:47 +0000731 /*ForceUnprivileged*/ true)) {
John McCall5b0829a2010-02-10 09:31:12 +0000732 case AR_accessible: break;
733 case AR_inaccessible: continue;
734 case AR_dependent:
735 llvm_unreachable("access check dependent for unprivileged context");
John McCall5b0829a2010-02-10 09:31:12 +0000736 case AR_delayed:
737 llvm_unreachable("access check delayed in non-declaration");
John McCall5b0829a2010-02-10 09:31:12 +0000738 }
Sebastian Redl4915e632009-10-11 09:03:14 +0000739
740 Contained = true;
741 break;
742 }
743 if (!Contained) {
744 Diag(SubLoc, DiagID);
Sebastian Redla44822f2009-10-14 16:09:29 +0000745 if (NoteID.getDiagID() != 0)
Sebastian Redl4915e632009-10-11 09:03:14 +0000746 Diag(SuperLoc, NoteID);
747 return true;
748 }
749 }
750 // We've run half the gauntlet.
751 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
752}
753
754static bool CheckSpecForTypesEquivalent(Sema &S,
Sebastian Redla44822f2009-10-14 16:09:29 +0000755 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
Sebastian Redl4915e632009-10-11 09:03:14 +0000756 QualType Target, SourceLocation TargetLoc,
757 QualType Source, SourceLocation SourceLoc)
758{
759 const FunctionProtoType *TFunc = GetUnderlyingFunction(Target);
760 if (!TFunc)
761 return false;
762 const FunctionProtoType *SFunc = GetUnderlyingFunction(Source);
763 if (!SFunc)
764 return false;
765
766 return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc,
767 SFunc, SourceLoc);
768}
769
770/// CheckParamExceptionSpec - Check if the parameter and return types of the
771/// two functions have equivalent exception specs. This is part of the
772/// assignment and override compatibility check. We do not check the parameters
773/// of parameter function pointers recursively, as no sane programmer would
774/// even be able to write such a function type.
Richard Smith2e321552014-11-12 02:00:47 +0000775bool Sema::CheckParamExceptionSpec(const PartialDiagnostic &NoteID,
776 const FunctionProtoType *Target,
777 SourceLocation TargetLoc,
778 const FunctionProtoType *Source,
779 SourceLocation SourceLoc) {
Alp Toker314cc812014-01-25 16:55:45 +0000780 if (CheckSpecForTypesEquivalent(
781 *this, PDiag(diag::err_deep_exception_specs_differ) << 0, PDiag(),
782 Target->getReturnType(), TargetLoc, Source->getReturnType(),
783 SourceLoc))
Sebastian Redl4915e632009-10-11 09:03:14 +0000784 return true;
785
Sebastian Redla44822f2009-10-14 16:09:29 +0000786 // We shouldn't even be testing this unless the arguments are otherwise
Sebastian Redl4915e632009-10-11 09:03:14 +0000787 // compatible.
Alp Toker9cacbab2014-01-20 20:26:09 +0000788 assert(Target->getNumParams() == Source->getNumParams() &&
Sebastian Redl4915e632009-10-11 09:03:14 +0000789 "Functions have different argument counts.");
Alp Toker9cacbab2014-01-20 20:26:09 +0000790 for (unsigned i = 0, E = Target->getNumParams(); i != E; ++i) {
791 if (CheckSpecForTypesEquivalent(
792 *this, PDiag(diag::err_deep_exception_specs_differ) << 1, PDiag(),
793 Target->getParamType(i), TargetLoc, Source->getParamType(i),
794 SourceLoc))
Sebastian Redl4915e632009-10-11 09:03:14 +0000795 return true;
796 }
797 return false;
798}
799
Richard Smith2e321552014-11-12 02:00:47 +0000800bool Sema::CheckExceptionSpecCompatibility(Expr *From, QualType ToType) {
Sebastian Redl4915e632009-10-11 09:03:14 +0000801 // First we check for applicability.
802 // Target type must be a function, function pointer or function reference.
803 const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType);
Richard Smith2e321552014-11-12 02:00:47 +0000804 if (!ToFunc || ToFunc->hasDependentExceptionSpec())
Sebastian Redl4915e632009-10-11 09:03:14 +0000805 return false;
806
807 // SourceType must be a function or function pointer.
808 const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType());
Richard Smith2e321552014-11-12 02:00:47 +0000809 if (!FromFunc || FromFunc->hasDependentExceptionSpec())
Sebastian Redl4915e632009-10-11 09:03:14 +0000810 return false;
811
812 // Now we've got the correct types on both sides, check their compatibility.
813 // This means that the source of the conversion can only throw a subset of
814 // the exceptions of the target, and any exception specs on arguments or
815 // return types must be equivalent.
Richard Smith2e321552014-11-12 02:00:47 +0000816 //
817 // FIXME: If there is a nested dependent exception specification, we should
818 // not be checking it here. This is fine:
819 // template<typename T> void f() {
820 // void (*p)(void (*) throw(T));
821 // void (*q)(void (*) throw(int)) = p;
822 // }
823 // ... because it might be instantiated with T=int.
Douglas Gregor89336232010-03-29 23:34:08 +0000824 return CheckExceptionSpecSubset(PDiag(diag::err_incompatible_exception_specs),
825 PDiag(), ToFunc,
826 From->getSourceRange().getBegin(),
Sebastian Redl4915e632009-10-11 09:03:14 +0000827 FromFunc, SourceLocation());
828}
829
830bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
831 const CXXMethodDecl *Old) {
Richard Smith88f45492014-11-22 03:09:05 +0000832 // If the new exception specification hasn't been parsed yet, skip the check.
833 // We'll get called again once it's been parsed.
834 if (New->getType()->castAs<FunctionProtoType>()->getExceptionSpecType() ==
835 EST_Unparsed)
836 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000837 if (getLangOpts().CPlusPlus11 && isa<CXXDestructorDecl>(New)) {
Sebastian Redl645d9582011-05-20 05:57:18 +0000838 // Don't check uninstantiated template destructors at all. We can only
839 // synthesize correct specs after the template is instantiated.
840 if (New->getParent()->isDependentType())
841 return false;
842 if (New->getParent()->isBeingDefined()) {
843 // The destructor might be updated once the definition is finished. So
844 // remember it and check later.
Richard Smith88f45492014-11-22 03:09:05 +0000845 DelayedExceptionSpecChecks.push_back(std::make_pair(New, Old));
Sebastian Redl645d9582011-05-20 05:57:18 +0000846 return false;
847 }
Sebastian Redl623ea822011-05-19 05:13:44 +0000848 }
Richard Smith88f45492014-11-22 03:09:05 +0000849 // If the old exception specification hasn't been parsed yet, remember that
850 // we need to perform this check when we get to the end of the outermost
851 // lexically-surrounding class.
852 if (Old->getType()->castAs<FunctionProtoType>()->getExceptionSpecType() ==
853 EST_Unparsed) {
854 DelayedExceptionSpecChecks.push_back(std::make_pair(New, Old));
Richard Smith0b3a4622014-11-13 20:01:57 +0000855 return false;
Richard Smith88f45492014-11-22 03:09:05 +0000856 }
Francois Picheta8032e92011-05-24 02:11:43 +0000857 unsigned DiagID = diag::err_override_exception_spec;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000858 if (getLangOpts().MicrosoftExt)
Richard Smith1b98ccc2014-07-19 01:39:17 +0000859 DiagID = diag::ext_override_exception_spec;
Francois Picheta8032e92011-05-24 02:11:43 +0000860 return CheckExceptionSpecSubset(PDiag(DiagID),
Douglas Gregor89336232010-03-29 23:34:08 +0000861 PDiag(diag::note_overridden_virtual_function),
Sebastian Redl4915e632009-10-11 09:03:14 +0000862 Old->getType()->getAs<FunctionProtoType>(),
863 Old->getLocation(),
864 New->getType()->getAs<FunctionProtoType>(),
865 New->getLocation());
866}
867
Benjamin Kramer642f1732015-07-02 21:03:14 +0000868static CanThrowResult canSubExprsThrow(Sema &S, const Expr *E) {
Richard Smithf623c962012-04-17 00:58:00 +0000869 CanThrowResult R = CT_Cannot;
Benjamin Kramer642f1732015-07-02 21:03:14 +0000870 for (const Stmt *SubStmt : E->children()) {
871 R = mergeCanThrow(R, S.canThrow(cast<Expr>(SubStmt)));
872 if (R == CT_Can)
873 break;
874 }
Richard Smithf623c962012-04-17 00:58:00 +0000875 return R;
876}
877
Eli Friedman0423b762013-06-25 01:24:22 +0000878static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D) {
879 assert(D && "Expected decl");
Richard Smithf623c962012-04-17 00:58:00 +0000880
881 // See if we can get a function type from the decl somehow.
882 const ValueDecl *VD = dyn_cast<ValueDecl>(D);
883 if (!VD) // If we have no clue what we're calling, assume the worst.
884 return CT_Can;
885
886 // As an extension, we assume that __attribute__((nothrow)) functions don't
887 // throw.
888 if (isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())
889 return CT_Cannot;
890
891 QualType T = VD->getType();
892 const FunctionProtoType *FT;
893 if ((FT = T->getAs<FunctionProtoType>())) {
894 } else if (const PointerType *PT = T->getAs<PointerType>())
895 FT = PT->getPointeeType()->getAs<FunctionProtoType>();
896 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
897 FT = RT->getPointeeType()->getAs<FunctionProtoType>();
898 else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
899 FT = MT->getPointeeType()->getAs<FunctionProtoType>();
900 else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
901 FT = BT->getPointeeType()->getAs<FunctionProtoType>();
902
903 if (!FT)
904 return CT_Can;
905
906 FT = S.ResolveExceptionSpec(E->getLocStart(), FT);
907 if (!FT)
908 return CT_Can;
909
Richard Smithf623c962012-04-17 00:58:00 +0000910 return FT->isNothrow(S.Context) ? CT_Cannot : CT_Can;
911}
912
913static CanThrowResult canDynamicCastThrow(const CXXDynamicCastExpr *DC) {
914 if (DC->isTypeDependent())
915 return CT_Dependent;
916
917 if (!DC->getTypeAsWritten()->isReferenceType())
918 return CT_Cannot;
919
920 if (DC->getSubExpr()->isTypeDependent())
921 return CT_Dependent;
922
923 return DC->getCastKind() == clang::CK_Dynamic? CT_Can : CT_Cannot;
924}
925
926static CanThrowResult canTypeidThrow(Sema &S, const CXXTypeidExpr *DC) {
927 if (DC->isTypeOperand())
928 return CT_Cannot;
929
930 Expr *Op = DC->getExprOperand();
931 if (Op->isTypeDependent())
932 return CT_Dependent;
933
934 const RecordType *RT = Op->getType()->getAs<RecordType>();
935 if (!RT)
936 return CT_Cannot;
937
938 if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
939 return CT_Cannot;
940
941 if (Op->Classify(S.Context).isPRValue())
942 return CT_Cannot;
943
944 return CT_Can;
945}
946
947CanThrowResult Sema::canThrow(const Expr *E) {
948 // C++ [expr.unary.noexcept]p3:
949 // [Can throw] if in a potentially-evaluated context the expression would
950 // contain:
951 switch (E->getStmtClass()) {
952 case Expr::CXXThrowExprClass:
953 // - a potentially evaluated throw-expression
954 return CT_Can;
955
956 case Expr::CXXDynamicCastExprClass: {
957 // - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
958 // where T is a reference type, that requires a run-time check
959 CanThrowResult CT = canDynamicCastThrow(cast<CXXDynamicCastExpr>(E));
960 if (CT == CT_Can)
961 return CT;
962 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
963 }
964
965 case Expr::CXXTypeidExprClass:
966 // - a potentially evaluated typeid expression applied to a glvalue
967 // expression whose type is a polymorphic class type
968 return canTypeidThrow(*this, cast<CXXTypeidExpr>(E));
969
970 // - a potentially evaluated call to a function, member function, function
971 // pointer, or member function pointer that does not have a non-throwing
972 // exception-specification
973 case Expr::CallExprClass:
974 case Expr::CXXMemberCallExprClass:
975 case Expr::CXXOperatorCallExprClass:
976 case Expr::UserDefinedLiteralClass: {
977 const CallExpr *CE = cast<CallExpr>(E);
978 CanThrowResult CT;
979 if (E->isTypeDependent())
980 CT = CT_Dependent;
981 else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens()))
982 CT = CT_Cannot;
Eli Friedman5a8738f2013-06-25 01:55:41 +0000983 else if (CE->getCalleeDecl())
Richard Smithf623c962012-04-17 00:58:00 +0000984 CT = canCalleeThrow(*this, E, CE->getCalleeDecl());
Eli Friedman5a8738f2013-06-25 01:55:41 +0000985 else
986 CT = CT_Can;
Richard Smithf623c962012-04-17 00:58:00 +0000987 if (CT == CT_Can)
988 return CT;
989 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
990 }
991
992 case Expr::CXXConstructExprClass:
993 case Expr::CXXTemporaryObjectExprClass: {
994 CanThrowResult CT = canCalleeThrow(*this, E,
995 cast<CXXConstructExpr>(E)->getConstructor());
996 if (CT == CT_Can)
997 return CT;
998 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
999 }
1000
1001 case Expr::LambdaExprClass: {
1002 const LambdaExpr *Lambda = cast<LambdaExpr>(E);
1003 CanThrowResult CT = CT_Cannot;
James Y Knight53c76162015-07-17 18:21:37 +00001004 for (LambdaExpr::const_capture_init_iterator
1005 Cap = Lambda->capture_init_begin(),
1006 CapEnd = Lambda->capture_init_end();
Richard Smithf623c962012-04-17 00:58:00 +00001007 Cap != CapEnd; ++Cap)
1008 CT = mergeCanThrow(CT, canThrow(*Cap));
1009 return CT;
1010 }
1011
1012 case Expr::CXXNewExprClass: {
1013 CanThrowResult CT;
1014 if (E->isTypeDependent())
1015 CT = CT_Dependent;
1016 else
1017 CT = canCalleeThrow(*this, E, cast<CXXNewExpr>(E)->getOperatorNew());
1018 if (CT == CT_Can)
1019 return CT;
1020 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1021 }
1022
1023 case Expr::CXXDeleteExprClass: {
1024 CanThrowResult CT;
1025 QualType DTy = cast<CXXDeleteExpr>(E)->getDestroyedType();
1026 if (DTy.isNull() || DTy->isDependentType()) {
1027 CT = CT_Dependent;
1028 } else {
1029 CT = canCalleeThrow(*this, E,
1030 cast<CXXDeleteExpr>(E)->getOperatorDelete());
1031 if (const RecordType *RT = DTy->getAs<RecordType>()) {
1032 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedman0423b762013-06-25 01:24:22 +00001033 const CXXDestructorDecl *DD = RD->getDestructor();
1034 if (DD)
1035 CT = mergeCanThrow(CT, canCalleeThrow(*this, E, DD));
Richard Smithf623c962012-04-17 00:58:00 +00001036 }
1037 if (CT == CT_Can)
1038 return CT;
1039 }
1040 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1041 }
1042
1043 case Expr::CXXBindTemporaryExprClass: {
1044 // The bound temporary has to be destroyed again, which might throw.
1045 CanThrowResult CT = canCalleeThrow(*this, E,
1046 cast<CXXBindTemporaryExpr>(E)->getTemporary()->getDestructor());
1047 if (CT == CT_Can)
1048 return CT;
1049 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1050 }
1051
1052 // ObjC message sends are like function calls, but never have exception
1053 // specs.
1054 case Expr::ObjCMessageExprClass:
1055 case Expr::ObjCPropertyRefExprClass:
1056 case Expr::ObjCSubscriptRefExprClass:
1057 return CT_Can;
1058
1059 // All the ObjC literals that are implemented as calls are
1060 // potentially throwing unless we decide to close off that
1061 // possibility.
1062 case Expr::ObjCArrayLiteralClass:
1063 case Expr::ObjCDictionaryLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00001064 case Expr::ObjCBoxedExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001065 return CT_Can;
1066
1067 // Many other things have subexpressions, so we have to test those.
1068 // Some are simple:
Richard Smith9f690bd2015-10-27 06:02:45 +00001069 case Expr::CoawaitExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001070 case Expr::ConditionalOperatorClass:
1071 case Expr::CompoundLiteralExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00001072 case Expr::CoyieldExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001073 case Expr::CXXConstCastExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001074 case Expr::CXXReinterpretCastExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00001075 case Expr::CXXStdInitializerListExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001076 case Expr::DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00001077 case Expr::DesignatedInitUpdateExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001078 case Expr::ExprWithCleanupsClass:
1079 case Expr::ExtVectorElementExprClass:
1080 case Expr::InitListExprClass:
1081 case Expr::MemberExprClass:
1082 case Expr::ObjCIsaExprClass:
1083 case Expr::ObjCIvarRefExprClass:
1084 case Expr::ParenExprClass:
1085 case Expr::ParenListExprClass:
1086 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00001087 case Expr::ConvertVectorExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001088 case Expr::VAArgExprClass:
1089 return canSubExprsThrow(*this, E);
1090
1091 // Some might be dependent for other reasons.
1092 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001093 case Expr::OMPArraySectionExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001094 case Expr::BinaryOperatorClass:
1095 case Expr::CompoundAssignOperatorClass:
1096 case Expr::CStyleCastExprClass:
1097 case Expr::CXXStaticCastExprClass:
1098 case Expr::CXXFunctionalCastExprClass:
1099 case Expr::ImplicitCastExprClass:
1100 case Expr::MaterializeTemporaryExprClass:
1101 case Expr::UnaryOperatorClass: {
1102 CanThrowResult CT = E->isTypeDependent() ? CT_Dependent : CT_Cannot;
1103 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1104 }
1105
1106 // FIXME: We should handle StmtExpr, but that opens a MASSIVE can of worms.
1107 case Expr::StmtExprClass:
1108 return CT_Can;
1109
Richard Smith852c9db2013-04-20 22:23:05 +00001110 case Expr::CXXDefaultArgExprClass:
1111 return canThrow(cast<CXXDefaultArgExpr>(E)->getExpr());
1112
1113 case Expr::CXXDefaultInitExprClass:
1114 return canThrow(cast<CXXDefaultInitExpr>(E)->getExpr());
1115
Richard Smithf623c962012-04-17 00:58:00 +00001116 case Expr::ChooseExprClass:
1117 if (E->isTypeDependent() || E->isValueDependent())
1118 return CT_Dependent;
Eli Friedman75807f22013-07-20 00:40:58 +00001119 return canThrow(cast<ChooseExpr>(E)->getChosenSubExpr());
Richard Smithf623c962012-04-17 00:58:00 +00001120
1121 case Expr::GenericSelectionExprClass:
1122 if (cast<GenericSelectionExpr>(E)->isResultDependent())
1123 return CT_Dependent;
1124 return canThrow(cast<GenericSelectionExpr>(E)->getResultExpr());
1125
1126 // Some expressions are always dependent.
1127 case Expr::CXXDependentScopeMemberExprClass:
1128 case Expr::CXXUnresolvedConstructExprClass:
1129 case Expr::DependentScopeDeclRefExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00001130 case Expr::CXXFoldExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001131 return CT_Dependent;
1132
1133 case Expr::AsTypeExprClass:
1134 case Expr::BinaryConditionalOperatorClass:
1135 case Expr::BlockExprClass:
1136 case Expr::CUDAKernelCallExprClass:
1137 case Expr::DeclRefExprClass:
1138 case Expr::ObjCBridgedCastExprClass:
1139 case Expr::ObjCIndirectCopyRestoreExprClass:
1140 case Expr::ObjCProtocolExprClass:
1141 case Expr::ObjCSelectorExprClass:
1142 case Expr::OffsetOfExprClass:
1143 case Expr::PackExpansionExprClass:
1144 case Expr::PseudoObjectExprClass:
1145 case Expr::SubstNonTypeTemplateParmExprClass:
1146 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00001147 case Expr::FunctionParmPackExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001148 case Expr::UnaryExprOrTypeTraitExprClass:
1149 case Expr::UnresolvedLookupExprClass:
1150 case Expr::UnresolvedMemberExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00001151 case Expr::TypoExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001152 // FIXME: Can any of the above throw? If so, when?
1153 return CT_Cannot;
1154
1155 case Expr::AddrLabelExprClass:
1156 case Expr::ArrayTypeTraitExprClass:
1157 case Expr::AtomicExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001158 case Expr::TypeTraitExprClass:
1159 case Expr::CXXBoolLiteralExprClass:
1160 case Expr::CXXNoexceptExprClass:
1161 case Expr::CXXNullPtrLiteralExprClass:
1162 case Expr::CXXPseudoDestructorExprClass:
1163 case Expr::CXXScalarValueInitExprClass:
1164 case Expr::CXXThisExprClass:
1165 case Expr::CXXUuidofExprClass:
1166 case Expr::CharacterLiteralClass:
1167 case Expr::ExpressionTraitExprClass:
1168 case Expr::FloatingLiteralClass:
1169 case Expr::GNUNullExprClass:
1170 case Expr::ImaginaryLiteralClass:
1171 case Expr::ImplicitValueInitExprClass:
1172 case Expr::IntegerLiteralClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00001173 case Expr::NoInitExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001174 case Expr::ObjCEncodeExprClass:
1175 case Expr::ObjCStringLiteralClass:
1176 case Expr::ObjCBoolLiteralExprClass:
1177 case Expr::OpaqueValueExprClass:
1178 case Expr::PredefinedExprClass:
1179 case Expr::SizeOfPackExprClass:
1180 case Expr::StringLiteralClass:
Richard Smithf623c962012-04-17 00:58:00 +00001181 // These expressions can never throw.
1182 return CT_Cannot;
1183
John McCall5e77d762013-04-16 07:28:30 +00001184 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00001185 case Expr::MSPropertySubscriptExprClass:
John McCall5e77d762013-04-16 07:28:30 +00001186 llvm_unreachable("Invalid class for expression");
1187
Richard Smithf623c962012-04-17 00:58:00 +00001188#define STMT(CLASS, PARENT) case Expr::CLASS##Class:
1189#define STMT_RANGE(Base, First, Last)
1190#define LAST_STMT_RANGE(BASE, FIRST, LAST)
1191#define EXPR(CLASS, PARENT)
1192#define ABSTRACT_STMT(STMT)
1193#include "clang/AST/StmtNodes.inc"
1194 case Expr::NoStmtClass:
1195 llvm_unreachable("Invalid class for expression");
1196 }
1197 llvm_unreachable("Bogus StmtClass");
1198}
1199
Sebastian Redl4915e632009-10-11 09:03:14 +00001200} // end namespace clang