blob: b7bed6de2d71e8d79a82403bb8fa3f8917eb45d0 [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;
David Majnemer5d321e62016-06-11 01:25:04 +0000115 bool ReturnValueOnError = true;
116 if (getLangOpts().MicrosoftExt) {
David Majnemerb2b0da42016-06-10 18:24:41 +0000117 DiagID = diag::ext_incomplete_in_exception_spec;
David Majnemer5d321e62016-06-11 01:25:04 +0000118 ReturnValueOnError = false;
119 }
Richard Smitha118c6a2012-11-28 22:52:42 +0000120 if (!(PointeeT->isRecordType() &&
121 PointeeT->getAs<RecordType>()->isBeingDefined()) &&
David Majnemerb2b0da42016-06-10 18:24:41 +0000122 RequireCompleteType(Range.getBegin(), PointeeT, DiagID, Kind, Range))
David Majnemer5d321e62016-06-11 01:25:04 +0000123 return ReturnValueOnError;
Sebastian Redl4915e632009-10-11 09:03:14 +0000124
125 return false;
126}
127
128/// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer
129/// to member to a function with an exception specification. This means that
130/// it is invalid to add another level of indirection.
131bool Sema::CheckDistantExceptionSpec(QualType T) {
132 if (const PointerType *PT = T->getAs<PointerType>())
133 T = PT->getPointeeType();
134 else if (const MemberPointerType *PT = T->getAs<MemberPointerType>())
135 T = PT->getPointeeType();
136 else
137 return false;
138
139 const FunctionProtoType *FnT = T->getAs<FunctionProtoType>();
140 if (!FnT)
141 return false;
142
143 return FnT->hasExceptionSpec();
144}
145
Richard Smithf623c962012-04-17 00:58:00 +0000146const FunctionProtoType *
147Sema::ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT) {
Richard Smith0b3a4622014-11-13 20:01:57 +0000148 if (FPT->getExceptionSpecType() == EST_Unparsed) {
149 Diag(Loc, diag::err_exception_spec_not_parsed);
150 return nullptr;
151 }
152
Richard Smithd3b5c9082012-07-27 04:22:15 +0000153 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
Richard Smithf623c962012-04-17 00:58:00 +0000154 return FPT;
155
156 FunctionDecl *SourceDecl = FPT->getExceptionSpecDecl();
157 const FunctionProtoType *SourceFPT =
158 SourceDecl->getType()->castAs<FunctionProtoType>();
159
Richard Smithd3b5c9082012-07-27 04:22:15 +0000160 // If the exception specification has already been resolved, just return it.
161 if (!isUnresolvedExceptionSpec(SourceFPT->getExceptionSpecType()))
Richard Smithf623c962012-04-17 00:58:00 +0000162 return SourceFPT;
163
Richard Smithd3b5c9082012-07-27 04:22:15 +0000164 // Compute or instantiate the exception specification now.
Richard Smith3901dfe2013-03-27 00:22:47 +0000165 if (SourceFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smithd3b5c9082012-07-27 04:22:15 +0000166 EvaluateImplicitExceptionSpec(Loc, cast<CXXMethodDecl>(SourceDecl));
167 else
168 InstantiateExceptionSpec(Loc, SourceDecl);
Richard Smithf623c962012-04-17 00:58:00 +0000169
Davide Italiano922b7022015-07-25 01:19:32 +0000170 const FunctionProtoType *Proto =
171 SourceDecl->getType()->castAs<FunctionProtoType>();
172 if (Proto->getExceptionSpecType() == clang::EST_Unparsed) {
173 Diag(Loc, diag::err_exception_spec_not_parsed);
174 Proto = nullptr;
175 }
176 return Proto;
Richard Smithf623c962012-04-17 00:58:00 +0000177}
178
Richard Smith8acb4282014-07-31 21:57:55 +0000179void
180Sema::UpdateExceptionSpec(FunctionDecl *FD,
181 const FunctionProtoType::ExceptionSpecInfo &ESI) {
Richard Smith564417a2014-03-20 21:47:22 +0000182 // If we've fully resolved the exception specification, notify listeners.
Richard Smith8acb4282014-07-31 21:57:55 +0000183 if (!isUnresolvedExceptionSpec(ESI.Type))
Richard Smith564417a2014-03-20 21:47:22 +0000184 if (auto *Listener = getASTMutationListener())
185 Listener->ResolvedExceptionSpec(FD);
Richard Smith9e2341d2015-03-23 03:25:59 +0000186
187 for (auto *Redecl : FD->redecls())
188 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith564417a2014-03-20 21:47:22 +0000189}
190
Richard Smith66f3ac92012-10-20 08:26:51 +0000191/// Determine whether a function has an implicitly-generated exception
Richard Smith1ee63522012-10-16 23:30:16 +0000192/// specification.
Richard Smith66f3ac92012-10-20 08:26:51 +0000193static bool hasImplicitExceptionSpec(FunctionDecl *Decl) {
194 if (!isa<CXXDestructorDecl>(Decl) &&
195 Decl->getDeclName().getCXXOverloadedOperator() != OO_Delete &&
196 Decl->getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
197 return false;
Richard Smith1ee63522012-10-16 23:30:16 +0000198
Richard Smithc7fb2252014-02-07 22:51:16 +0000199 // For a function that the user didn't declare:
200 // - if this is a destructor, its exception specification is implicit.
201 // - if this is 'operator delete' or 'operator delete[]', the exception
202 // specification is as-if an explicit exception specification was given
203 // (per [basic.stc.dynamic]p2).
Richard Smith66f3ac92012-10-20 08:26:51 +0000204 if (!Decl->getTypeSourceInfo())
Richard Smithc7fb2252014-02-07 22:51:16 +0000205 return isa<CXXDestructorDecl>(Decl);
Richard Smith66f3ac92012-10-20 08:26:51 +0000206
207 const FunctionProtoType *Ty =
208 Decl->getTypeSourceInfo()->getType()->getAs<FunctionProtoType>();
209 return !Ty->hasExceptionSpec();
Richard Smith1ee63522012-10-16 23:30:16 +0000210}
211
Douglas Gregorf40863c2010-02-12 07:32:17 +0000212bool Sema::CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New) {
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000213 OverloadedOperatorKind OO = New->getDeclName().getCXXOverloadedOperator();
214 bool IsOperatorNew = OO == OO_New || OO == OO_Array_New;
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000215 bool MissingExceptionSpecification = false;
Douglas Gregorf40863c2010-02-12 07:32:17 +0000216 bool MissingEmptyExceptionSpecification = false;
Hans Wennborg39a509a2014-02-05 02:37:58 +0000217
Francois Pichet13b4e682011-03-19 23:05:18 +0000218 unsigned DiagID = diag::err_mismatched_exception_spec;
Hans Wennborg39a509a2014-02-05 02:37:58 +0000219 bool ReturnValueOnError = true;
220 if (getLangOpts().MicrosoftExt) {
Richard Smith1b98ccc2014-07-19 01:39:17 +0000221 DiagID = diag::ext_mismatched_exception_spec;
Hans Wennborg39a509a2014-02-05 02:37:58 +0000222 ReturnValueOnError = false;
223 }
Richard Smithf623c962012-04-17 00:58:00 +0000224
Richard Smith1ee63522012-10-16 23:30:16 +0000225 // Check the types as written: they must match before any exception
226 // specification adjustment is applied.
227 if (!CheckEquivalentExceptionSpec(
228 PDiag(DiagID), PDiag(diag::note_previous_declaration),
Richard Smith66f3ac92012-10-20 08:26:51 +0000229 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
230 New->getType()->getAs<FunctionProtoType>(), New->getLocation(),
Richard Smith1ee63522012-10-16 23:30:16 +0000231 &MissingExceptionSpecification, &MissingEmptyExceptionSpecification,
Richard Smith66f3ac92012-10-20 08:26:51 +0000232 /*AllowNoexceptAllMatchWithNoSpec=*/true, IsOperatorNew)) {
233 // C++11 [except.spec]p4 [DR1492]:
234 // If a declaration of a function has an implicit
235 // exception-specification, other declarations of the function shall
236 // not specify an exception-specification.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000237 if (getLangOpts().CPlusPlus11 &&
Richard Smith66f3ac92012-10-20 08:26:51 +0000238 hasImplicitExceptionSpec(Old) != hasImplicitExceptionSpec(New)) {
239 Diag(New->getLocation(), diag::ext_implicit_exception_spec_mismatch)
240 << hasImplicitExceptionSpec(Old);
Yaron Keren8b563662015-10-03 10:46:20 +0000241 if (Old->getLocation().isValid())
Richard Smith66f3ac92012-10-20 08:26:51 +0000242 Diag(Old->getLocation(), diag::note_previous_declaration);
243 }
Douglas Gregorf40863c2010-02-12 07:32:17 +0000244 return false;
Richard Smith66f3ac92012-10-20 08:26:51 +0000245 }
Douglas Gregorf40863c2010-02-12 07:32:17 +0000246
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000247 // The failure was something other than an missing exception
Hans Wennborg39a509a2014-02-05 02:37:58 +0000248 // specification; return an error, except in MS mode where this is a warning.
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000249 if (!MissingExceptionSpecification)
Hans Wennborg39a509a2014-02-05 02:37:58 +0000250 return ReturnValueOnError;
Douglas Gregorf40863c2010-02-12 07:32:17 +0000251
Richard Smith66f3ac92012-10-20 08:26:51 +0000252 const FunctionProtoType *NewProto =
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000253 New->getType()->castAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +0000254
Douglas Gregorf40863c2010-02-12 07:32:17 +0000255 // The new function declaration is only missing an empty exception
256 // specification "throw()". If the throw() specification came from a
257 // function in a system header that has C linkage, just add an empty
258 // exception specification to the "new" declaration. This is an
259 // egregious workaround for glibc, which adds throw() specifications
260 // to many libc functions as an optimization. Unfortunately, that
261 // optimization isn't permitted by the C++ standard, so we're forced
262 // to work around it here.
John McCalldb40c7f2010-12-14 08:05:40 +0000263 if (MissingEmptyExceptionSpecification && NewProto &&
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000264 (Old->getLocation().isInvalid() ||
265 Context.getSourceManager().isInSystemHeader(Old->getLocation())) &&
Douglas Gregorf40863c2010-02-12 07:32:17 +0000266 Old->isExternC()) {
Richard Smith8acb4282014-07-31 21:57:55 +0000267 New->setType(Context.getFunctionType(
268 NewProto->getReturnType(), NewProto->getParamTypes(),
269 NewProto->getExtProtoInfo().withExceptionSpec(EST_DynamicNone)));
Douglas Gregorf40863c2010-02-12 07:32:17 +0000270 return false;
271 }
272
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000273 const FunctionProtoType *OldProto =
274 Old->getType()->castAs<FunctionProtoType>();
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000275
Richard Smith8acb4282014-07-31 21:57:55 +0000276 FunctionProtoType::ExceptionSpecInfo ESI = OldProto->getExceptionSpecType();
277 if (ESI.Type == EST_Dynamic) {
278 ESI.Exceptions = OldProto->exceptions();
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000279 }
280
Richard Smitha91de372015-09-30 00:48:50 +0000281 if (ESI.Type == EST_ComputedNoexcept) {
282 // For computed noexcept, we can't just take the expression from the old
283 // prototype. It likely contains references to the old prototype's
284 // parameters.
285 New->setInvalidDecl();
286 } else {
287 // Update the type of the function with the appropriate exception
288 // specification.
289 New->setType(Context.getFunctionType(
290 NewProto->getReturnType(), NewProto->getParamTypes(),
291 NewProto->getExtProtoInfo().withExceptionSpec(ESI)));
292 }
293
David Majnemer06ce8a42015-10-20 20:49:21 +0000294 if (getLangOpts().MicrosoftExt && ESI.Type != EST_ComputedNoexcept) {
295 // Allow missing exception specifications in redeclarations as an extension.
296 DiagID = diag::ext_ms_missing_exception_specification;
297 ReturnValueOnError = false;
298 } else if (New->isReplaceableGlobalAllocationFunction() &&
299 ESI.Type != EST_ComputedNoexcept) {
300 // Allow missing exception specifications in redeclarations as an extension,
301 // when declaring a replaceable global allocation function.
Richard Smitha91de372015-09-30 00:48:50 +0000302 DiagID = diag::ext_missing_exception_specification;
303 ReturnValueOnError = false;
304 } else {
305 DiagID = diag::err_missing_exception_specification;
306 ReturnValueOnError = true;
307 }
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000308
309 // Warn about the lack of exception specification.
310 SmallString<128> ExceptionSpecString;
311 llvm::raw_svector_ostream OS(ExceptionSpecString);
312 switch (OldProto->getExceptionSpecType()) {
313 case EST_DynamicNone:
314 OS << "throw()";
315 break;
316
317 case EST_Dynamic: {
318 OS << "throw(";
319 bool OnFirstException = true;
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000320 for (const auto &E : OldProto->exceptions()) {
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000321 if (OnFirstException)
322 OnFirstException = false;
323 else
324 OS << ", ";
325
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000326 OS << E.getAsString(getPrintingPolicy());
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000327 }
328 OS << ")";
329 break;
330 }
331
332 case EST_BasicNoexcept:
333 OS << "noexcept";
334 break;
335
336 case EST_ComputedNoexcept:
337 OS << "noexcept(";
Richard Trieuddd01ce2014-06-09 22:53:25 +0000338 assert(OldProto->getNoexceptExpr() != nullptr && "Expected non-null Expr");
Craig Topperc3ec1492014-05-26 06:22:03 +0000339 OldProto->getNoexceptExpr()->printPretty(OS, nullptr, getPrintingPolicy());
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000340 OS << ")";
341 break;
342
343 default:
344 llvm_unreachable("This spec type is compatible with none.");
345 }
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000346
347 SourceLocation FixItLoc;
348 if (TypeSourceInfo *TSInfo = New->getTypeSourceInfo()) {
349 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Richard Smitha91de372015-09-30 00:48:50 +0000350 // FIXME: Preserve enough information so that we can produce a correct fixit
351 // location when there is a trailing return type.
352 if (auto FTLoc = TL.getAs<FunctionProtoTypeLoc>())
353 if (!FTLoc.getTypePtr()->hasTrailingReturn())
354 FixItLoc = getLocForEndOfToken(FTLoc.getLocalRangeEnd());
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000355 }
356
357 if (FixItLoc.isInvalid())
Richard Smitha91de372015-09-30 00:48:50 +0000358 Diag(New->getLocation(), DiagID)
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000359 << New << OS.str();
360 else {
Richard Smitha91de372015-09-30 00:48:50 +0000361 Diag(New->getLocation(), DiagID)
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000362 << New << OS.str()
363 << FixItHint::CreateInsertion(FixItLoc, " " + OS.str().str());
364 }
365
Yaron Keren8b563662015-10-03 10:46:20 +0000366 if (Old->getLocation().isValid())
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000367 Diag(Old->getLocation(), diag::note_previous_declaration);
368
Richard Smitha91de372015-09-30 00:48:50 +0000369 return ReturnValueOnError;
Douglas Gregorf40863c2010-02-12 07:32:17 +0000370}
371
Sebastian Redl4915e632009-10-11 09:03:14 +0000372/// CheckEquivalentExceptionSpec - Check if the two types have equivalent
373/// exception specifications. Exception specifications are equivalent if
374/// they allow exactly the same set of exception types. It does not matter how
375/// that is achieved. See C++ [except.spec]p2.
376bool Sema::CheckEquivalentExceptionSpec(
377 const FunctionProtoType *Old, SourceLocation OldLoc,
378 const FunctionProtoType *New, SourceLocation NewLoc) {
Francois Pichet13b4e682011-03-19 23:05:18 +0000379 unsigned DiagID = diag::err_mismatched_exception_spec;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000380 if (getLangOpts().MicrosoftExt)
Richard Smith1b98ccc2014-07-19 01:39:17 +0000381 DiagID = diag::ext_mismatched_exception_spec;
Hans Wennborg39a509a2014-02-05 02:37:58 +0000382 bool Result = CheckEquivalentExceptionSpec(PDiag(DiagID),
383 PDiag(diag::note_previous_declaration), Old, OldLoc, New, NewLoc);
384
385 // In Microsoft mode, mismatching exception specifications just cause a warning.
386 if (getLangOpts().MicrosoftExt)
387 return false;
388 return Result;
Sebastian Redl4915e632009-10-11 09:03:14 +0000389}
390
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000391/// CheckEquivalentExceptionSpec - Check if the two types have compatible
392/// exception specifications. See C++ [except.spec]p3.
Richard Smith66f3ac92012-10-20 08:26:51 +0000393///
394/// \return \c false if the exception specifications match, \c true if there is
395/// a problem. If \c true is returned, either a diagnostic has already been
396/// produced or \c *MissingExceptionSpecification is set to \c true.
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000397bool Sema::CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000398 const PartialDiagnostic & NoteID,
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000399 const FunctionProtoType *Old,
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000400 SourceLocation OldLoc,
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000401 const FunctionProtoType *New,
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000402 SourceLocation NewLoc,
403 bool *MissingExceptionSpecification,
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000404 bool*MissingEmptyExceptionSpecification,
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000405 bool AllowNoexceptAllMatchWithNoSpec,
406 bool IsOperatorNew) {
John McCallf9c94092010-05-28 08:37:35 +0000407 // Just completely ignore this under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000408 if (!getLangOpts().CXXExceptions)
John McCallf9c94092010-05-28 08:37:35 +0000409 return false;
410
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000411 if (MissingExceptionSpecification)
412 *MissingExceptionSpecification = false;
413
Douglas Gregorf40863c2010-02-12 07:32:17 +0000414 if (MissingEmptyExceptionSpecification)
415 *MissingEmptyExceptionSpecification = false;
416
Richard Smithf623c962012-04-17 00:58:00 +0000417 Old = ResolveExceptionSpec(NewLoc, Old);
418 if (!Old)
419 return false;
420 New = ResolveExceptionSpec(NewLoc, New);
421 if (!New)
422 return false;
423
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000424 // C++0x [except.spec]p3: Two exception-specifications are compatible if:
425 // - both are non-throwing, regardless of their form,
426 // - both have the form noexcept(constant-expression) and the constant-
427 // expressions are equivalent,
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000428 // - both are dynamic-exception-specifications that have the same set of
429 // adjusted types.
430 //
Eric Christophere6b7cf42015-07-10 18:25:52 +0000431 // C++0x [except.spec]p12: An exception-specification is non-throwing if it is
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000432 // of the form throw(), noexcept, or noexcept(constant-expression) where the
433 // constant-expression yields true.
434 //
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000435 // C++0x [except.spec]p4: If any declaration of a function has an exception-
436 // specifier that is not a noexcept-specification allowing all exceptions,
437 // all declarations [...] of that function shall have a compatible
438 // exception-specification.
439 //
440 // That last point basically means that noexcept(false) matches no spec.
441 // It's considered when AllowNoexceptAllMatchWithNoSpec is true.
442
443 ExceptionSpecificationType OldEST = Old->getExceptionSpecType();
444 ExceptionSpecificationType NewEST = New->getExceptionSpecType();
445
Richard Smithd3b5c9082012-07-27 04:22:15 +0000446 assert(!isUnresolvedExceptionSpec(OldEST) &&
447 !isUnresolvedExceptionSpec(NewEST) &&
Richard Smith938f40b2011-06-11 17:19:42 +0000448 "Shouldn't see unknown exception specifications here");
449
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000450 // Shortcut the case where both have no spec.
451 if (OldEST == EST_None && NewEST == EST_None)
452 return false;
453
Sebastian Redl31ad7542011-03-13 17:09:40 +0000454 FunctionProtoType::NoexceptResult OldNR = Old->getNoexceptSpec(Context);
455 FunctionProtoType::NoexceptResult NewNR = New->getNoexceptSpec(Context);
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000456 if (OldNR == FunctionProtoType::NR_BadNoexcept ||
457 NewNR == FunctionProtoType::NR_BadNoexcept)
458 return false;
459
460 // Dependent noexcept specifiers are compatible with each other, but nothing
461 // else.
462 // One noexcept is compatible with another if the argument is the same
463 if (OldNR == NewNR &&
464 OldNR != FunctionProtoType::NR_NoNoexcept &&
465 NewNR != FunctionProtoType::NR_NoNoexcept)
466 return false;
467 if (OldNR != NewNR &&
468 OldNR != FunctionProtoType::NR_NoNoexcept &&
469 NewNR != FunctionProtoType::NR_NoNoexcept) {
470 Diag(NewLoc, DiagID);
David Majnemer7da23022015-02-19 07:28:55 +0000471 if (NoteID.getDiagID() != 0 && OldLoc.isValid())
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000472 Diag(OldLoc, NoteID);
473 return true;
Douglas Gregorf62c5292010-08-30 15:04:51 +0000474 }
475
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000476 // The MS extension throw(...) is compatible with itself.
477 if (OldEST == EST_MSAny && NewEST == EST_MSAny)
Sebastian Redl4915e632009-10-11 09:03:14 +0000478 return false;
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000479
480 // It's also compatible with no spec.
481 if ((OldEST == EST_None && NewEST == EST_MSAny) ||
482 (OldEST == EST_MSAny && NewEST == EST_None))
483 return false;
484
485 // It's also compatible with noexcept(false).
486 if (OldEST == EST_MSAny && NewNR == FunctionProtoType::NR_Throw)
487 return false;
488 if (NewEST == EST_MSAny && OldNR == FunctionProtoType::NR_Throw)
489 return false;
490
491 // As described above, noexcept(false) matches no spec only for functions.
492 if (AllowNoexceptAllMatchWithNoSpec) {
493 if (OldEST == EST_None && NewNR == FunctionProtoType::NR_Throw)
494 return false;
495 if (NewEST == EST_None && OldNR == FunctionProtoType::NR_Throw)
496 return false;
497 }
498
499 // Any non-throwing specifications are compatible.
500 bool OldNonThrowing = OldNR == FunctionProtoType::NR_Nothrow ||
501 OldEST == EST_DynamicNone;
502 bool NewNonThrowing = NewNR == FunctionProtoType::NR_Nothrow ||
503 NewEST == EST_DynamicNone;
504 if (OldNonThrowing && NewNonThrowing)
505 return false;
506
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000507 // As a special compatibility feature, under C++0x we accept no spec and
508 // throw(std::bad_alloc) as equivalent for operator new and operator new[].
509 // This is because the implicit declaration changed, but old code would break.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000510 if (getLangOpts().CPlusPlus11 && IsOperatorNew) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000511 const FunctionProtoType *WithExceptions = nullptr;
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000512 if (OldEST == EST_None && NewEST == EST_Dynamic)
513 WithExceptions = New;
514 else if (OldEST == EST_Dynamic && NewEST == EST_None)
515 WithExceptions = Old;
516 if (WithExceptions && WithExceptions->getNumExceptions() == 1) {
517 // One has no spec, the other throw(something). If that something is
518 // std::bad_alloc, all conditions are met.
519 QualType Exception = *WithExceptions->exception_begin();
520 if (CXXRecordDecl *ExRecord = Exception->getAsCXXRecordDecl()) {
521 IdentifierInfo* Name = ExRecord->getIdentifier();
522 if (Name && Name->getName() == "bad_alloc") {
523 // It's called bad_alloc, but is it in std?
Richard Trieuc771d5d2014-05-28 02:16:01 +0000524 if (ExRecord->isInStdNamespace()) {
525 return false;
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000526 }
527 }
528 }
529 }
530 }
531
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000532 // At this point, the only remaining valid case is two matching dynamic
533 // specifications. We return here unless both specifications are dynamic.
534 if (OldEST != EST_Dynamic || NewEST != EST_Dynamic) {
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000535 if (MissingExceptionSpecification && Old->hasExceptionSpec() &&
Douglas Gregorf40863c2010-02-12 07:32:17 +0000536 !New->hasExceptionSpec()) {
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000537 // The old type has an exception specification of some sort, but
538 // the new type does not.
539 *MissingExceptionSpecification = true;
540
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000541 if (MissingEmptyExceptionSpecification && OldNonThrowing) {
542 // The old type has a throw() or noexcept(true) exception specification
543 // and the new type has no exception specification, and the caller asked
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000544 // to handle this itself.
545 *MissingEmptyExceptionSpecification = true;
546 }
547
Douglas Gregorf40863c2010-02-12 07:32:17 +0000548 return true;
549 }
550
Sebastian Redl4915e632009-10-11 09:03:14 +0000551 Diag(NewLoc, DiagID);
David Majnemer7da23022015-02-19 07:28:55 +0000552 if (NoteID.getDiagID() != 0 && OldLoc.isValid())
Sebastian Redl4915e632009-10-11 09:03:14 +0000553 Diag(OldLoc, NoteID);
554 return true;
555 }
556
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000557 assert(OldEST == EST_Dynamic && NewEST == EST_Dynamic &&
558 "Exception compatibility logic error: non-dynamic spec slipped through.");
559
Sebastian Redl4915e632009-10-11 09:03:14 +0000560 bool Success = true;
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000561 // Both have a dynamic exception spec. Collect the first set, then compare
Sebastian Redl4915e632009-10-11 09:03:14 +0000562 // to the second.
Sebastian Redl184edca2009-10-14 15:06:25 +0000563 llvm::SmallPtrSet<CanQualType, 8> OldTypes, NewTypes;
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000564 for (const auto &I : Old->exceptions())
565 OldTypes.insert(Context.getCanonicalType(I).getUnqualifiedType());
Sebastian Redl4915e632009-10-11 09:03:14 +0000566
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000567 for (const auto &I : New->exceptions()) {
568 CanQualType TypePtr = Context.getCanonicalType(I).getUnqualifiedType();
Sebastian Redl6e4c8712009-10-11 09:11:23 +0000569 if(OldTypes.count(TypePtr))
570 NewTypes.insert(TypePtr);
571 else
572 Success = false;
573 }
Sebastian Redl4915e632009-10-11 09:03:14 +0000574
Sebastian Redl6e4c8712009-10-11 09:11:23 +0000575 Success = Success && OldTypes.size() == NewTypes.size();
Sebastian Redl4915e632009-10-11 09:03:14 +0000576
577 if (Success) {
578 return false;
579 }
580 Diag(NewLoc, DiagID);
David Majnemer7da23022015-02-19 07:28:55 +0000581 if (NoteID.getDiagID() != 0 && OldLoc.isValid())
Sebastian Redl4915e632009-10-11 09:03:14 +0000582 Diag(OldLoc, NoteID);
583 return true;
584}
585
586/// CheckExceptionSpecSubset - Check whether the second function type's
587/// exception specification is a subset (or equivalent) of the first function
588/// type. This is used by override and pointer assignment checks.
Sebastian Redla44822f2009-10-14 16:09:29 +0000589bool Sema::CheckExceptionSpecSubset(
590 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
Sebastian Redl4915e632009-10-11 09:03:14 +0000591 const FunctionProtoType *Superset, SourceLocation SuperLoc,
592 const FunctionProtoType *Subset, SourceLocation SubLoc) {
John McCallf9c94092010-05-28 08:37:35 +0000593
594 // Just auto-succeed under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000595 if (!getLangOpts().CXXExceptions)
John McCallf9c94092010-05-28 08:37:35 +0000596 return false;
597
Sebastian Redl4915e632009-10-11 09:03:14 +0000598 // FIXME: As usual, we could be more specific in our error messages, but
599 // that better waits until we've got types with source locations.
600
601 if (!SubLoc.isValid())
602 SubLoc = SuperLoc;
603
Richard Smithf623c962012-04-17 00:58:00 +0000604 // Resolve the exception specifications, if needed.
605 Superset = ResolveExceptionSpec(SuperLoc, Superset);
606 if (!Superset)
607 return false;
608 Subset = ResolveExceptionSpec(SubLoc, Subset);
609 if (!Subset)
610 return false;
611
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000612 ExceptionSpecificationType SuperEST = Superset->getExceptionSpecType();
613
Sebastian Redl4915e632009-10-11 09:03:14 +0000614 // If superset contains everything, we're done.
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000615 if (SuperEST == EST_None || SuperEST == EST_MSAny)
Sebastian Redl4915e632009-10-11 09:03:14 +0000616 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
617
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000618 // If there are dependent noexcept specs, assume everything is fine. Unlike
619 // with the equivalency check, this is safe in this case, because we don't
620 // want to merge declarations. Checks after instantiation will catch any
621 // omissions we make here.
622 // We also shortcut checking if a noexcept expression was bad.
623
Sebastian Redl31ad7542011-03-13 17:09:40 +0000624 FunctionProtoType::NoexceptResult SuperNR =Superset->getNoexceptSpec(Context);
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000625 if (SuperNR == FunctionProtoType::NR_BadNoexcept ||
626 SuperNR == FunctionProtoType::NR_Dependent)
627 return false;
628
629 // Another case of the superset containing everything.
630 if (SuperNR == FunctionProtoType::NR_Throw)
631 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
632
633 ExceptionSpecificationType SubEST = Subset->getExceptionSpecType();
634
Richard Smithd3b5c9082012-07-27 04:22:15 +0000635 assert(!isUnresolvedExceptionSpec(SuperEST) &&
636 !isUnresolvedExceptionSpec(SubEST) &&
Richard Smith938f40b2011-06-11 17:19:42 +0000637 "Shouldn't see unknown exception specifications here");
638
Sebastian Redl4915e632009-10-11 09:03:14 +0000639 // It does not. If the subset contains everything, we've failed.
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000640 if (SubEST == EST_None || SubEST == EST_MSAny) {
Sebastian Redl4915e632009-10-11 09:03:14 +0000641 Diag(SubLoc, DiagID);
Sebastian Redla44822f2009-10-14 16:09:29 +0000642 if (NoteID.getDiagID() != 0)
Sebastian Redl4915e632009-10-11 09:03:14 +0000643 Diag(SuperLoc, NoteID);
644 return true;
645 }
646
Sebastian Redl31ad7542011-03-13 17:09:40 +0000647 FunctionProtoType::NoexceptResult SubNR = Subset->getNoexceptSpec(Context);
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000648 if (SubNR == FunctionProtoType::NR_BadNoexcept ||
649 SubNR == FunctionProtoType::NR_Dependent)
650 return false;
651
652 // Another case of the subset containing everything.
653 if (SubNR == FunctionProtoType::NR_Throw) {
654 Diag(SubLoc, DiagID);
655 if (NoteID.getDiagID() != 0)
656 Diag(SuperLoc, NoteID);
657 return true;
658 }
659
660 // If the subset contains nothing, we're done.
661 if (SubEST == EST_DynamicNone || SubNR == FunctionProtoType::NR_Nothrow)
662 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
663
664 // Otherwise, if the superset contains nothing, we've failed.
665 if (SuperEST == EST_DynamicNone || SuperNR == FunctionProtoType::NR_Nothrow) {
666 Diag(SubLoc, DiagID);
667 if (NoteID.getDiagID() != 0)
668 Diag(SuperLoc, NoteID);
669 return true;
670 }
671
672 assert(SuperEST == EST_Dynamic && SubEST == EST_Dynamic &&
673 "Exception spec subset: non-dynamic case slipped through.");
674
675 // Neither contains everything or nothing. Do a proper comparison.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000676 for (const auto &SubI : Subset->exceptions()) {
Sebastian Redl4915e632009-10-11 09:03:14 +0000677 // Take one type from the subset.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000678 QualType CanonicalSubT = Context.getCanonicalType(SubI);
Sebastian Redl075b21d2009-10-14 14:38:54 +0000679 // Unwrap pointers and references so that we can do checks within a class
680 // hierarchy. Don't unwrap member pointers; they don't have hierarchy
681 // conversions on the pointee.
Sebastian Redl4915e632009-10-11 09:03:14 +0000682 bool SubIsPointer = false;
683 if (const ReferenceType *RefTy = CanonicalSubT->getAs<ReferenceType>())
684 CanonicalSubT = RefTy->getPointeeType();
685 if (const PointerType *PtrTy = CanonicalSubT->getAs<PointerType>()) {
686 CanonicalSubT = PtrTy->getPointeeType();
687 SubIsPointer = true;
688 }
689 bool SubIsClass = CanonicalSubT->isRecordType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000690 CanonicalSubT = CanonicalSubT.getLocalUnqualifiedType();
Sebastian Redl4915e632009-10-11 09:03:14 +0000691
692 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
693 /*DetectVirtual=*/false);
694
695 bool Contained = false;
696 // Make sure it's in the superset.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000697 for (const auto &SuperI : Superset->exceptions()) {
698 QualType CanonicalSuperT = Context.getCanonicalType(SuperI);
Sebastian Redl4915e632009-10-11 09:03:14 +0000699 // SubT must be SuperT or derived from it, or pointer or reference to
700 // such types.
701 if (const ReferenceType *RefTy = CanonicalSuperT->getAs<ReferenceType>())
702 CanonicalSuperT = RefTy->getPointeeType();
703 if (SubIsPointer) {
704 if (const PointerType *PtrTy = CanonicalSuperT->getAs<PointerType>())
705 CanonicalSuperT = PtrTy->getPointeeType();
706 else {
707 continue;
708 }
709 }
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000710 CanonicalSuperT = CanonicalSuperT.getLocalUnqualifiedType();
Sebastian Redl4915e632009-10-11 09:03:14 +0000711 // If the types are the same, move on to the next type in the subset.
712 if (CanonicalSubT == CanonicalSuperT) {
713 Contained = true;
714 break;
715 }
716
717 // Otherwise we need to check the inheritance.
718 if (!SubIsClass || !CanonicalSuperT->isRecordType())
719 continue;
720
721 Paths.clear();
Richard Smith0f59cb32015-12-18 21:45:41 +0000722 if (!IsDerivedFrom(SubLoc, CanonicalSubT, CanonicalSuperT, Paths))
Sebastian Redl4915e632009-10-11 09:03:14 +0000723 continue;
724
Douglas Gregor27ac4292010-05-21 20:29:55 +0000725 if (Paths.isAmbiguous(Context.getCanonicalType(CanonicalSuperT)))
Sebastian Redl4915e632009-10-11 09:03:14 +0000726 continue;
727
John McCall5b0829a2010-02-10 09:31:12 +0000728 // Do this check from a context without privileges.
John McCall1064d7e2010-03-16 05:22:47 +0000729 switch (CheckBaseClassAccess(SourceLocation(),
John McCall5b0829a2010-02-10 09:31:12 +0000730 CanonicalSuperT, CanonicalSubT,
731 Paths.front(),
John McCall1064d7e2010-03-16 05:22:47 +0000732 /*Diagnostic*/ 0,
John McCall5b0829a2010-02-10 09:31:12 +0000733 /*ForceCheck*/ true,
John McCall1064d7e2010-03-16 05:22:47 +0000734 /*ForceUnprivileged*/ true)) {
John McCall5b0829a2010-02-10 09:31:12 +0000735 case AR_accessible: break;
736 case AR_inaccessible: continue;
737 case AR_dependent:
738 llvm_unreachable("access check dependent for unprivileged context");
John McCall5b0829a2010-02-10 09:31:12 +0000739 case AR_delayed:
740 llvm_unreachable("access check delayed in non-declaration");
John McCall5b0829a2010-02-10 09:31:12 +0000741 }
Sebastian Redl4915e632009-10-11 09:03:14 +0000742
743 Contained = true;
744 break;
745 }
746 if (!Contained) {
747 Diag(SubLoc, DiagID);
Sebastian Redla44822f2009-10-14 16:09:29 +0000748 if (NoteID.getDiagID() != 0)
Sebastian Redl4915e632009-10-11 09:03:14 +0000749 Diag(SuperLoc, NoteID);
750 return true;
751 }
752 }
753 // We've run half the gauntlet.
754 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
755}
756
757static bool CheckSpecForTypesEquivalent(Sema &S,
Sebastian Redla44822f2009-10-14 16:09:29 +0000758 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
Sebastian Redl4915e632009-10-11 09:03:14 +0000759 QualType Target, SourceLocation TargetLoc,
760 QualType Source, SourceLocation SourceLoc)
761{
762 const FunctionProtoType *TFunc = GetUnderlyingFunction(Target);
763 if (!TFunc)
764 return false;
765 const FunctionProtoType *SFunc = GetUnderlyingFunction(Source);
766 if (!SFunc)
767 return false;
768
769 return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc,
770 SFunc, SourceLoc);
771}
772
773/// CheckParamExceptionSpec - Check if the parameter and return types of the
774/// two functions have equivalent exception specs. This is part of the
775/// assignment and override compatibility check. We do not check the parameters
776/// of parameter function pointers recursively, as no sane programmer would
777/// even be able to write such a function type.
Richard Smith2e321552014-11-12 02:00:47 +0000778bool Sema::CheckParamExceptionSpec(const PartialDiagnostic &NoteID,
779 const FunctionProtoType *Target,
780 SourceLocation TargetLoc,
781 const FunctionProtoType *Source,
782 SourceLocation SourceLoc) {
Alp Toker314cc812014-01-25 16:55:45 +0000783 if (CheckSpecForTypesEquivalent(
784 *this, PDiag(diag::err_deep_exception_specs_differ) << 0, PDiag(),
785 Target->getReturnType(), TargetLoc, Source->getReturnType(),
786 SourceLoc))
Sebastian Redl4915e632009-10-11 09:03:14 +0000787 return true;
788
Sebastian Redla44822f2009-10-14 16:09:29 +0000789 // We shouldn't even be testing this unless the arguments are otherwise
Sebastian Redl4915e632009-10-11 09:03:14 +0000790 // compatible.
Alp Toker9cacbab2014-01-20 20:26:09 +0000791 assert(Target->getNumParams() == Source->getNumParams() &&
Sebastian Redl4915e632009-10-11 09:03:14 +0000792 "Functions have different argument counts.");
Alp Toker9cacbab2014-01-20 20:26:09 +0000793 for (unsigned i = 0, E = Target->getNumParams(); i != E; ++i) {
794 if (CheckSpecForTypesEquivalent(
795 *this, PDiag(diag::err_deep_exception_specs_differ) << 1, PDiag(),
796 Target->getParamType(i), TargetLoc, Source->getParamType(i),
797 SourceLoc))
Sebastian Redl4915e632009-10-11 09:03:14 +0000798 return true;
799 }
800 return false;
801}
802
Richard Smith2e321552014-11-12 02:00:47 +0000803bool Sema::CheckExceptionSpecCompatibility(Expr *From, QualType ToType) {
Sebastian Redl4915e632009-10-11 09:03:14 +0000804 // First we check for applicability.
805 // Target type must be a function, function pointer or function reference.
806 const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType);
Richard Smith2e321552014-11-12 02:00:47 +0000807 if (!ToFunc || ToFunc->hasDependentExceptionSpec())
Sebastian Redl4915e632009-10-11 09:03:14 +0000808 return false;
809
810 // SourceType must be a function or function pointer.
811 const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType());
Richard Smith2e321552014-11-12 02:00:47 +0000812 if (!FromFunc || FromFunc->hasDependentExceptionSpec())
Sebastian Redl4915e632009-10-11 09:03:14 +0000813 return false;
814
815 // Now we've got the correct types on both sides, check their compatibility.
816 // This means that the source of the conversion can only throw a subset of
817 // the exceptions of the target, and any exception specs on arguments or
818 // return types must be equivalent.
Richard Smith2e321552014-11-12 02:00:47 +0000819 //
820 // FIXME: If there is a nested dependent exception specification, we should
821 // not be checking it here. This is fine:
822 // template<typename T> void f() {
823 // void (*p)(void (*) throw(T));
824 // void (*q)(void (*) throw(int)) = p;
825 // }
826 // ... because it might be instantiated with T=int.
Douglas Gregor89336232010-03-29 23:34:08 +0000827 return CheckExceptionSpecSubset(PDiag(diag::err_incompatible_exception_specs),
828 PDiag(), ToFunc,
829 From->getSourceRange().getBegin(),
Sebastian Redl4915e632009-10-11 09:03:14 +0000830 FromFunc, SourceLocation());
831}
832
833bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
834 const CXXMethodDecl *Old) {
Richard Smith88f45492014-11-22 03:09:05 +0000835 // If the new exception specification hasn't been parsed yet, skip the check.
836 // We'll get called again once it's been parsed.
837 if (New->getType()->castAs<FunctionProtoType>()->getExceptionSpecType() ==
838 EST_Unparsed)
839 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000840 if (getLangOpts().CPlusPlus11 && isa<CXXDestructorDecl>(New)) {
Sebastian Redl645d9582011-05-20 05:57:18 +0000841 // Don't check uninstantiated template destructors at all. We can only
842 // synthesize correct specs after the template is instantiated.
843 if (New->getParent()->isDependentType())
844 return false;
845 if (New->getParent()->isBeingDefined()) {
846 // The destructor might be updated once the definition is finished. So
847 // remember it and check later.
Richard Smith88f45492014-11-22 03:09:05 +0000848 DelayedExceptionSpecChecks.push_back(std::make_pair(New, Old));
Sebastian Redl645d9582011-05-20 05:57:18 +0000849 return false;
850 }
Sebastian Redl623ea822011-05-19 05:13:44 +0000851 }
Richard Smith88f45492014-11-22 03:09:05 +0000852 // If the old exception specification hasn't been parsed yet, remember that
853 // we need to perform this check when we get to the end of the outermost
854 // lexically-surrounding class.
855 if (Old->getType()->castAs<FunctionProtoType>()->getExceptionSpecType() ==
856 EST_Unparsed) {
857 DelayedExceptionSpecChecks.push_back(std::make_pair(New, Old));
Richard Smith0b3a4622014-11-13 20:01:57 +0000858 return false;
Richard Smith88f45492014-11-22 03:09:05 +0000859 }
Francois Picheta8032e92011-05-24 02:11:43 +0000860 unsigned DiagID = diag::err_override_exception_spec;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000861 if (getLangOpts().MicrosoftExt)
Richard Smith1b98ccc2014-07-19 01:39:17 +0000862 DiagID = diag::ext_override_exception_spec;
Francois Picheta8032e92011-05-24 02:11:43 +0000863 return CheckExceptionSpecSubset(PDiag(DiagID),
Douglas Gregor89336232010-03-29 23:34:08 +0000864 PDiag(diag::note_overridden_virtual_function),
Sebastian Redl4915e632009-10-11 09:03:14 +0000865 Old->getType()->getAs<FunctionProtoType>(),
866 Old->getLocation(),
867 New->getType()->getAs<FunctionProtoType>(),
868 New->getLocation());
869}
870
Benjamin Kramer642f1732015-07-02 21:03:14 +0000871static CanThrowResult canSubExprsThrow(Sema &S, const Expr *E) {
Richard Smithf623c962012-04-17 00:58:00 +0000872 CanThrowResult R = CT_Cannot;
Benjamin Kramer642f1732015-07-02 21:03:14 +0000873 for (const Stmt *SubStmt : E->children()) {
874 R = mergeCanThrow(R, S.canThrow(cast<Expr>(SubStmt)));
875 if (R == CT_Can)
876 break;
877 }
Richard Smithf623c962012-04-17 00:58:00 +0000878 return R;
879}
880
Eli Friedman0423b762013-06-25 01:24:22 +0000881static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D) {
882 assert(D && "Expected decl");
Richard Smithf623c962012-04-17 00:58:00 +0000883
884 // See if we can get a function type from the decl somehow.
885 const ValueDecl *VD = dyn_cast<ValueDecl>(D);
886 if (!VD) // If we have no clue what we're calling, assume the worst.
887 return CT_Can;
888
889 // As an extension, we assume that __attribute__((nothrow)) functions don't
890 // throw.
891 if (isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())
892 return CT_Cannot;
893
894 QualType T = VD->getType();
895 const FunctionProtoType *FT;
896 if ((FT = T->getAs<FunctionProtoType>())) {
897 } else if (const PointerType *PT = T->getAs<PointerType>())
898 FT = PT->getPointeeType()->getAs<FunctionProtoType>();
899 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
900 FT = RT->getPointeeType()->getAs<FunctionProtoType>();
901 else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
902 FT = MT->getPointeeType()->getAs<FunctionProtoType>();
903 else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
904 FT = BT->getPointeeType()->getAs<FunctionProtoType>();
905
906 if (!FT)
907 return CT_Can;
908
909 FT = S.ResolveExceptionSpec(E->getLocStart(), FT);
910 if (!FT)
911 return CT_Can;
912
Richard Smithf623c962012-04-17 00:58:00 +0000913 return FT->isNothrow(S.Context) ? CT_Cannot : CT_Can;
914}
915
916static CanThrowResult canDynamicCastThrow(const CXXDynamicCastExpr *DC) {
917 if (DC->isTypeDependent())
918 return CT_Dependent;
919
920 if (!DC->getTypeAsWritten()->isReferenceType())
921 return CT_Cannot;
922
923 if (DC->getSubExpr()->isTypeDependent())
924 return CT_Dependent;
925
926 return DC->getCastKind() == clang::CK_Dynamic? CT_Can : CT_Cannot;
927}
928
929static CanThrowResult canTypeidThrow(Sema &S, const CXXTypeidExpr *DC) {
930 if (DC->isTypeOperand())
931 return CT_Cannot;
932
933 Expr *Op = DC->getExprOperand();
934 if (Op->isTypeDependent())
935 return CT_Dependent;
936
937 const RecordType *RT = Op->getType()->getAs<RecordType>();
938 if (!RT)
939 return CT_Cannot;
940
941 if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
942 return CT_Cannot;
943
944 if (Op->Classify(S.Context).isPRValue())
945 return CT_Cannot;
946
947 return CT_Can;
948}
949
950CanThrowResult Sema::canThrow(const Expr *E) {
951 // C++ [expr.unary.noexcept]p3:
952 // [Can throw] if in a potentially-evaluated context the expression would
953 // contain:
954 switch (E->getStmtClass()) {
955 case Expr::CXXThrowExprClass:
956 // - a potentially evaluated throw-expression
957 return CT_Can;
958
959 case Expr::CXXDynamicCastExprClass: {
960 // - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
961 // where T is a reference type, that requires a run-time check
962 CanThrowResult CT = canDynamicCastThrow(cast<CXXDynamicCastExpr>(E));
963 if (CT == CT_Can)
964 return CT;
965 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
966 }
967
968 case Expr::CXXTypeidExprClass:
969 // - a potentially evaluated typeid expression applied to a glvalue
970 // expression whose type is a polymorphic class type
971 return canTypeidThrow(*this, cast<CXXTypeidExpr>(E));
972
973 // - a potentially evaluated call to a function, member function, function
974 // pointer, or member function pointer that does not have a non-throwing
975 // exception-specification
976 case Expr::CallExprClass:
977 case Expr::CXXMemberCallExprClass:
978 case Expr::CXXOperatorCallExprClass:
979 case Expr::UserDefinedLiteralClass: {
980 const CallExpr *CE = cast<CallExpr>(E);
981 CanThrowResult CT;
982 if (E->isTypeDependent())
983 CT = CT_Dependent;
984 else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens()))
985 CT = CT_Cannot;
Eli Friedman5a8738f2013-06-25 01:55:41 +0000986 else if (CE->getCalleeDecl())
Richard Smithf623c962012-04-17 00:58:00 +0000987 CT = canCalleeThrow(*this, E, CE->getCalleeDecl());
Eli Friedman5a8738f2013-06-25 01:55:41 +0000988 else
989 CT = CT_Can;
Richard Smithf623c962012-04-17 00:58:00 +0000990 if (CT == CT_Can)
991 return CT;
992 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
993 }
994
995 case Expr::CXXConstructExprClass:
996 case Expr::CXXTemporaryObjectExprClass: {
997 CanThrowResult CT = canCalleeThrow(*this, E,
998 cast<CXXConstructExpr>(E)->getConstructor());
999 if (CT == CT_Can)
1000 return CT;
1001 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1002 }
1003
1004 case Expr::LambdaExprClass: {
1005 const LambdaExpr *Lambda = cast<LambdaExpr>(E);
1006 CanThrowResult CT = CT_Cannot;
James Y Knight53c76162015-07-17 18:21:37 +00001007 for (LambdaExpr::const_capture_init_iterator
1008 Cap = Lambda->capture_init_begin(),
1009 CapEnd = Lambda->capture_init_end();
Richard Smithf623c962012-04-17 00:58:00 +00001010 Cap != CapEnd; ++Cap)
1011 CT = mergeCanThrow(CT, canThrow(*Cap));
1012 return CT;
1013 }
1014
1015 case Expr::CXXNewExprClass: {
1016 CanThrowResult CT;
1017 if (E->isTypeDependent())
1018 CT = CT_Dependent;
1019 else
1020 CT = canCalleeThrow(*this, E, cast<CXXNewExpr>(E)->getOperatorNew());
1021 if (CT == CT_Can)
1022 return CT;
1023 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1024 }
1025
1026 case Expr::CXXDeleteExprClass: {
1027 CanThrowResult CT;
1028 QualType DTy = cast<CXXDeleteExpr>(E)->getDestroyedType();
1029 if (DTy.isNull() || DTy->isDependentType()) {
1030 CT = CT_Dependent;
1031 } else {
1032 CT = canCalleeThrow(*this, E,
1033 cast<CXXDeleteExpr>(E)->getOperatorDelete());
1034 if (const RecordType *RT = DTy->getAs<RecordType>()) {
1035 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedman0423b762013-06-25 01:24:22 +00001036 const CXXDestructorDecl *DD = RD->getDestructor();
1037 if (DD)
1038 CT = mergeCanThrow(CT, canCalleeThrow(*this, E, DD));
Richard Smithf623c962012-04-17 00:58:00 +00001039 }
1040 if (CT == CT_Can)
1041 return CT;
1042 }
1043 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1044 }
1045
1046 case Expr::CXXBindTemporaryExprClass: {
1047 // The bound temporary has to be destroyed again, which might throw.
1048 CanThrowResult CT = canCalleeThrow(*this, E,
1049 cast<CXXBindTemporaryExpr>(E)->getTemporary()->getDestructor());
1050 if (CT == CT_Can)
1051 return CT;
1052 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1053 }
1054
1055 // ObjC message sends are like function calls, but never have exception
1056 // specs.
1057 case Expr::ObjCMessageExprClass:
1058 case Expr::ObjCPropertyRefExprClass:
1059 case Expr::ObjCSubscriptRefExprClass:
1060 return CT_Can;
1061
1062 // All the ObjC literals that are implemented as calls are
1063 // potentially throwing unless we decide to close off that
1064 // possibility.
1065 case Expr::ObjCArrayLiteralClass:
1066 case Expr::ObjCDictionaryLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00001067 case Expr::ObjCBoxedExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001068 return CT_Can;
1069
1070 // Many other things have subexpressions, so we have to test those.
1071 // Some are simple:
Richard Smith9f690bd2015-10-27 06:02:45 +00001072 case Expr::CoawaitExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001073 case Expr::ConditionalOperatorClass:
1074 case Expr::CompoundLiteralExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00001075 case Expr::CoyieldExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001076 case Expr::CXXConstCastExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001077 case Expr::CXXReinterpretCastExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00001078 case Expr::CXXStdInitializerListExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001079 case Expr::DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00001080 case Expr::DesignatedInitUpdateExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001081 case Expr::ExprWithCleanupsClass:
1082 case Expr::ExtVectorElementExprClass:
1083 case Expr::InitListExprClass:
1084 case Expr::MemberExprClass:
1085 case Expr::ObjCIsaExprClass:
1086 case Expr::ObjCIvarRefExprClass:
1087 case Expr::ParenExprClass:
1088 case Expr::ParenListExprClass:
1089 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00001090 case Expr::ConvertVectorExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001091 case Expr::VAArgExprClass:
1092 return canSubExprsThrow(*this, E);
1093
1094 // Some might be dependent for other reasons.
1095 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001096 case Expr::OMPArraySectionExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001097 case Expr::BinaryOperatorClass:
1098 case Expr::CompoundAssignOperatorClass:
1099 case Expr::CStyleCastExprClass:
1100 case Expr::CXXStaticCastExprClass:
1101 case Expr::CXXFunctionalCastExprClass:
1102 case Expr::ImplicitCastExprClass:
1103 case Expr::MaterializeTemporaryExprClass:
1104 case Expr::UnaryOperatorClass: {
1105 CanThrowResult CT = E->isTypeDependent() ? CT_Dependent : CT_Cannot;
1106 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1107 }
1108
1109 // FIXME: We should handle StmtExpr, but that opens a MASSIVE can of worms.
1110 case Expr::StmtExprClass:
1111 return CT_Can;
1112
Richard Smith852c9db2013-04-20 22:23:05 +00001113 case Expr::CXXDefaultArgExprClass:
1114 return canThrow(cast<CXXDefaultArgExpr>(E)->getExpr());
1115
1116 case Expr::CXXDefaultInitExprClass:
1117 return canThrow(cast<CXXDefaultInitExpr>(E)->getExpr());
1118
Richard Smithf623c962012-04-17 00:58:00 +00001119 case Expr::ChooseExprClass:
1120 if (E->isTypeDependent() || E->isValueDependent())
1121 return CT_Dependent;
Eli Friedman75807f22013-07-20 00:40:58 +00001122 return canThrow(cast<ChooseExpr>(E)->getChosenSubExpr());
Richard Smithf623c962012-04-17 00:58:00 +00001123
1124 case Expr::GenericSelectionExprClass:
1125 if (cast<GenericSelectionExpr>(E)->isResultDependent())
1126 return CT_Dependent;
1127 return canThrow(cast<GenericSelectionExpr>(E)->getResultExpr());
1128
1129 // Some expressions are always dependent.
1130 case Expr::CXXDependentScopeMemberExprClass:
1131 case Expr::CXXUnresolvedConstructExprClass:
1132 case Expr::DependentScopeDeclRefExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00001133 case Expr::CXXFoldExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001134 return CT_Dependent;
1135
1136 case Expr::AsTypeExprClass:
1137 case Expr::BinaryConditionalOperatorClass:
1138 case Expr::BlockExprClass:
1139 case Expr::CUDAKernelCallExprClass:
1140 case Expr::DeclRefExprClass:
1141 case Expr::ObjCBridgedCastExprClass:
1142 case Expr::ObjCIndirectCopyRestoreExprClass:
1143 case Expr::ObjCProtocolExprClass:
1144 case Expr::ObjCSelectorExprClass:
1145 case Expr::OffsetOfExprClass:
1146 case Expr::PackExpansionExprClass:
1147 case Expr::PseudoObjectExprClass:
1148 case Expr::SubstNonTypeTemplateParmExprClass:
1149 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00001150 case Expr::FunctionParmPackExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001151 case Expr::UnaryExprOrTypeTraitExprClass:
1152 case Expr::UnresolvedLookupExprClass:
1153 case Expr::UnresolvedMemberExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00001154 case Expr::TypoExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001155 // FIXME: Can any of the above throw? If so, when?
1156 return CT_Cannot;
1157
1158 case Expr::AddrLabelExprClass:
1159 case Expr::ArrayTypeTraitExprClass:
1160 case Expr::AtomicExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001161 case Expr::TypeTraitExprClass:
1162 case Expr::CXXBoolLiteralExprClass:
1163 case Expr::CXXNoexceptExprClass:
1164 case Expr::CXXNullPtrLiteralExprClass:
1165 case Expr::CXXPseudoDestructorExprClass:
1166 case Expr::CXXScalarValueInitExprClass:
1167 case Expr::CXXThisExprClass:
1168 case Expr::CXXUuidofExprClass:
1169 case Expr::CharacterLiteralClass:
1170 case Expr::ExpressionTraitExprClass:
1171 case Expr::FloatingLiteralClass:
1172 case Expr::GNUNullExprClass:
1173 case Expr::ImaginaryLiteralClass:
1174 case Expr::ImplicitValueInitExprClass:
1175 case Expr::IntegerLiteralClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00001176 case Expr::NoInitExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001177 case Expr::ObjCEncodeExprClass:
1178 case Expr::ObjCStringLiteralClass:
1179 case Expr::ObjCBoolLiteralExprClass:
1180 case Expr::OpaqueValueExprClass:
1181 case Expr::PredefinedExprClass:
1182 case Expr::SizeOfPackExprClass:
1183 case Expr::StringLiteralClass:
Richard Smithf623c962012-04-17 00:58:00 +00001184 // These expressions can never throw.
1185 return CT_Cannot;
1186
John McCall5e77d762013-04-16 07:28:30 +00001187 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00001188 case Expr::MSPropertySubscriptExprClass:
John McCall5e77d762013-04-16 07:28:30 +00001189 llvm_unreachable("Invalid class for expression");
1190
Richard Smithf623c962012-04-17 00:58:00 +00001191#define STMT(CLASS, PARENT) case Expr::CLASS##Class:
1192#define STMT_RANGE(Base, First, Last)
1193#define LAST_STMT_RANGE(BASE, FIRST, LAST)
1194#define EXPR(CLASS, PARENT)
1195#define ABSTRACT_STMT(STMT)
1196#include "clang/AST/StmtNodes.inc"
1197 case Expr::NoStmtClass:
1198 llvm_unreachable("Invalid class for expression");
1199 }
1200 llvm_unreachable("Bogus StmtClass");
1201}
1202
Sebastian Redl4915e632009-10-11 09:03:14 +00001203} // end namespace clang