blob: f8e75b2fe7926af4a319fa91c8a1fe116ad01600 [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.
Vassil Vassilev86436392016-08-20 14:50:22 +000047 if (!RD || !getStdNamespace() ||
48 !RD->getEnclosingNamespaceContext()->Equals(getStdNamespace()) ||
Richard Smith6403e932014-11-14 00:37:55 +000049 !RD->getIdentifier() || !RD->getDescribedClassTemplate() ||
50 !D.getIdentifier() || !D.getIdentifier()->isStr("swap"))
51 return false;
52
53 // Only apply this hack within a system header.
54 if (!Context.getSourceManager().isInSystemHeader(D.getLocStart()))
55 return false;
56
57 return llvm::StringSwitch<bool>(RD->getIdentifier()->getName())
58 .Case("array", true)
59 .Case("pair", true)
60 .Case("priority_queue", true)
61 .Case("stack", true)
62 .Case("queue", true)
63 .Default(false);
64}
65
Sebastian Redl4915e632009-10-11 09:03:14 +000066/// CheckSpecifiedExceptionType - Check if the given type is valid in an
67/// exception specification. Incomplete types, or pointers to incomplete types
68/// other than void are not allowed.
Richard Smith8606d752012-11-28 22:33:28 +000069///
70/// \param[in,out] T The exception type. This will be decayed to a pointer type
71/// when the input is an array or a function type.
Craig Toppere335f252015-10-04 04:53:55 +000072bool Sema::CheckSpecifiedExceptionType(QualType &T, SourceRange Range) {
Richard Smitha118c6a2012-11-28 22:52:42 +000073 // C++11 [except.spec]p2:
74 // A type cv T, "array of T", or "function returning T" denoted
Richard Smith8606d752012-11-28 22:33:28 +000075 // in an exception-specification is adjusted to type T, "pointer to T", or
76 // "pointer to function returning T", respectively.
Richard Smitha118c6a2012-11-28 22:52:42 +000077 //
78 // We also apply this rule in C++98.
Richard Smith8606d752012-11-28 22:33:28 +000079 if (T->isArrayType())
80 T = Context.getArrayDecayedType(T);
81 else if (T->isFunctionType())
82 T = Context.getPointerType(T);
Sebastian Redl4915e632009-10-11 09:03:14 +000083
Richard Smitha118c6a2012-11-28 22:52:42 +000084 int Kind = 0;
Richard Smith8606d752012-11-28 22:33:28 +000085 QualType PointeeT = T;
Richard Smitha118c6a2012-11-28 22:52:42 +000086 if (const PointerType *PT = T->getAs<PointerType>()) {
87 PointeeT = PT->getPointeeType();
88 Kind = 1;
Sebastian Redl4915e632009-10-11 09:03:14 +000089
Richard Smitha118c6a2012-11-28 22:52:42 +000090 // cv void* is explicitly permitted, despite being a pointer to an
91 // incomplete type.
92 if (PointeeT->isVoidType())
93 return false;
94 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
95 PointeeT = RT->getPointeeType();
96 Kind = 2;
Richard Smith8606d752012-11-28 22:33:28 +000097
Richard Smitha118c6a2012-11-28 22:52:42 +000098 if (RT->isRValueReferenceType()) {
99 // C++11 [except.spec]p2:
100 // A type denoted in an exception-specification shall not denote [...]
101 // an rvalue reference type.
102 Diag(Range.getBegin(), diag::err_rref_in_exception_spec)
103 << T << Range;
104 return true;
105 }
106 }
107
108 // C++11 [except.spec]p2:
109 // A type denoted in an exception-specification shall not denote an
110 // incomplete type other than a class currently being defined [...].
111 // A type denoted in an exception-specification shall not denote a
112 // pointer or reference to an incomplete type, other than (cv) void* or a
113 // pointer or reference to a class currently being defined.
David Majnemerb2b0da42016-06-10 18:24:41 +0000114 // In Microsoft mode, downgrade this to a warning.
115 unsigned DiagID = diag::err_incomplete_in_exception_spec;
David Majnemer5d321e62016-06-11 01:25:04 +0000116 bool ReturnValueOnError = true;
117 if (getLangOpts().MicrosoftExt) {
David Majnemerb2b0da42016-06-10 18:24:41 +0000118 DiagID = diag::ext_incomplete_in_exception_spec;
David Majnemer5d321e62016-06-11 01:25:04 +0000119 ReturnValueOnError = false;
120 }
Richard Smitha118c6a2012-11-28 22:52:42 +0000121 if (!(PointeeT->isRecordType() &&
122 PointeeT->getAs<RecordType>()->isBeingDefined()) &&
David Majnemerb2b0da42016-06-10 18:24:41 +0000123 RequireCompleteType(Range.getBegin(), PointeeT, DiagID, Kind, Range))
David Majnemer5d321e62016-06-11 01:25:04 +0000124 return ReturnValueOnError;
Sebastian Redl4915e632009-10-11 09:03:14 +0000125
126 return false;
127}
128
129/// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer
130/// to member to a function with an exception specification. This means that
131/// it is invalid to add another level of indirection.
132bool Sema::CheckDistantExceptionSpec(QualType T) {
133 if (const PointerType *PT = T->getAs<PointerType>())
134 T = PT->getPointeeType();
135 else if (const MemberPointerType *PT = T->getAs<MemberPointerType>())
136 T = PT->getPointeeType();
137 else
138 return false;
139
140 const FunctionProtoType *FnT = T->getAs<FunctionProtoType>();
141 if (!FnT)
142 return false;
143
144 return FnT->hasExceptionSpec();
145}
146
Richard Smithf623c962012-04-17 00:58:00 +0000147const FunctionProtoType *
148Sema::ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT) {
Richard Smith0b3a4622014-11-13 20:01:57 +0000149 if (FPT->getExceptionSpecType() == EST_Unparsed) {
150 Diag(Loc, diag::err_exception_spec_not_parsed);
151 return nullptr;
152 }
153
Richard Smithd3b5c9082012-07-27 04:22:15 +0000154 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
Richard Smithf623c962012-04-17 00:58:00 +0000155 return FPT;
156
157 FunctionDecl *SourceDecl = FPT->getExceptionSpecDecl();
158 const FunctionProtoType *SourceFPT =
159 SourceDecl->getType()->castAs<FunctionProtoType>();
160
Richard Smithd3b5c9082012-07-27 04:22:15 +0000161 // If the exception specification has already been resolved, just return it.
162 if (!isUnresolvedExceptionSpec(SourceFPT->getExceptionSpecType()))
Richard Smithf623c962012-04-17 00:58:00 +0000163 return SourceFPT;
164
Richard Smithd3b5c9082012-07-27 04:22:15 +0000165 // Compute or instantiate the exception specification now.
Richard Smith3901dfe2013-03-27 00:22:47 +0000166 if (SourceFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smithd3b5c9082012-07-27 04:22:15 +0000167 EvaluateImplicitExceptionSpec(Loc, cast<CXXMethodDecl>(SourceDecl));
168 else
169 InstantiateExceptionSpec(Loc, SourceDecl);
Richard Smithf623c962012-04-17 00:58:00 +0000170
Davide Italiano922b7022015-07-25 01:19:32 +0000171 const FunctionProtoType *Proto =
172 SourceDecl->getType()->castAs<FunctionProtoType>();
173 if (Proto->getExceptionSpecType() == clang::EST_Unparsed) {
174 Diag(Loc, diag::err_exception_spec_not_parsed);
175 Proto = nullptr;
176 }
177 return Proto;
Richard Smithf623c962012-04-17 00:58:00 +0000178}
179
Richard Smith8acb4282014-07-31 21:57:55 +0000180void
181Sema::UpdateExceptionSpec(FunctionDecl *FD,
182 const FunctionProtoType::ExceptionSpecInfo &ESI) {
Richard Smith564417a2014-03-20 21:47:22 +0000183 // If we've fully resolved the exception specification, notify listeners.
Richard Smith8acb4282014-07-31 21:57:55 +0000184 if (!isUnresolvedExceptionSpec(ESI.Type))
Richard Smith564417a2014-03-20 21:47:22 +0000185 if (auto *Listener = getASTMutationListener())
186 Listener->ResolvedExceptionSpec(FD);
Richard Smith9e2341d2015-03-23 03:25:59 +0000187
188 for (auto *Redecl : FD->redecls())
189 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith564417a2014-03-20 21:47:22 +0000190}
191
Richard Smith66f3ac92012-10-20 08:26:51 +0000192/// Determine whether a function has an implicitly-generated exception
Richard Smith1ee63522012-10-16 23:30:16 +0000193/// specification.
Richard Smith66f3ac92012-10-20 08:26:51 +0000194static bool hasImplicitExceptionSpec(FunctionDecl *Decl) {
195 if (!isa<CXXDestructorDecl>(Decl) &&
196 Decl->getDeclName().getCXXOverloadedOperator() != OO_Delete &&
197 Decl->getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
198 return false;
Richard Smith1ee63522012-10-16 23:30:16 +0000199
Richard Smithc7fb2252014-02-07 22:51:16 +0000200 // For a function that the user didn't declare:
201 // - if this is a destructor, its exception specification is implicit.
202 // - if this is 'operator delete' or 'operator delete[]', the exception
203 // specification is as-if an explicit exception specification was given
204 // (per [basic.stc.dynamic]p2).
Richard Smith66f3ac92012-10-20 08:26:51 +0000205 if (!Decl->getTypeSourceInfo())
Richard Smithc7fb2252014-02-07 22:51:16 +0000206 return isa<CXXDestructorDecl>(Decl);
Richard Smith66f3ac92012-10-20 08:26:51 +0000207
208 const FunctionProtoType *Ty =
209 Decl->getTypeSourceInfo()->getType()->getAs<FunctionProtoType>();
210 return !Ty->hasExceptionSpec();
Richard Smith1ee63522012-10-16 23:30:16 +0000211}
212
Douglas Gregorf40863c2010-02-12 07:32:17 +0000213bool Sema::CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New) {
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000214 OverloadedOperatorKind OO = New->getDeclName().getCXXOverloadedOperator();
215 bool IsOperatorNew = OO == OO_New || OO == OO_Array_New;
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000216 bool MissingExceptionSpecification = false;
Douglas Gregorf40863c2010-02-12 07:32:17 +0000217 bool MissingEmptyExceptionSpecification = false;
Hans Wennborg39a509a2014-02-05 02:37:58 +0000218
Francois Pichet13b4e682011-03-19 23:05:18 +0000219 unsigned DiagID = diag::err_mismatched_exception_spec;
Hans Wennborg39a509a2014-02-05 02:37:58 +0000220 bool ReturnValueOnError = true;
221 if (getLangOpts().MicrosoftExt) {
Richard Smith1b98ccc2014-07-19 01:39:17 +0000222 DiagID = diag::ext_mismatched_exception_spec;
Hans Wennborg39a509a2014-02-05 02:37:58 +0000223 ReturnValueOnError = false;
224 }
Richard Smithf623c962012-04-17 00:58:00 +0000225
Richard Smith1ee63522012-10-16 23:30:16 +0000226 // Check the types as written: they must match before any exception
227 // specification adjustment is applied.
228 if (!CheckEquivalentExceptionSpec(
229 PDiag(DiagID), PDiag(diag::note_previous_declaration),
Richard Smith66f3ac92012-10-20 08:26:51 +0000230 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
231 New->getType()->getAs<FunctionProtoType>(), New->getLocation(),
Richard Smith1ee63522012-10-16 23:30:16 +0000232 &MissingExceptionSpecification, &MissingEmptyExceptionSpecification,
Richard Smith66f3ac92012-10-20 08:26:51 +0000233 /*AllowNoexceptAllMatchWithNoSpec=*/true, IsOperatorNew)) {
234 // C++11 [except.spec]p4 [DR1492]:
235 // If a declaration of a function has an implicit
236 // exception-specification, other declarations of the function shall
237 // not specify an exception-specification.
Richard Smithe3ea0012016-08-31 20:38:32 +0000238 if (getLangOpts().CPlusPlus11 && getLangOpts().CXXExceptions &&
Richard Smith66f3ac92012-10-20 08:26:51 +0000239 hasImplicitExceptionSpec(Old) != hasImplicitExceptionSpec(New)) {
240 Diag(New->getLocation(), diag::ext_implicit_exception_spec_mismatch)
241 << hasImplicitExceptionSpec(Old);
Yaron Keren8b563662015-10-03 10:46:20 +0000242 if (Old->getLocation().isValid())
Richard Smith66f3ac92012-10-20 08:26:51 +0000243 Diag(Old->getLocation(), diag::note_previous_declaration);
244 }
Douglas Gregorf40863c2010-02-12 07:32:17 +0000245 return false;
Richard Smith66f3ac92012-10-20 08:26:51 +0000246 }
Douglas Gregorf40863c2010-02-12 07:32:17 +0000247
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000248 // The failure was something other than an missing exception
Hans Wennborg39a509a2014-02-05 02:37:58 +0000249 // specification; return an error, except in MS mode where this is a warning.
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000250 if (!MissingExceptionSpecification)
Hans Wennborg39a509a2014-02-05 02:37:58 +0000251 return ReturnValueOnError;
Douglas Gregorf40863c2010-02-12 07:32:17 +0000252
Richard Smith66f3ac92012-10-20 08:26:51 +0000253 const FunctionProtoType *NewProto =
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000254 New->getType()->castAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +0000255
Douglas Gregorf40863c2010-02-12 07:32:17 +0000256 // The new function declaration is only missing an empty exception
257 // specification "throw()". If the throw() specification came from a
258 // function in a system header that has C linkage, just add an empty
259 // exception specification to the "new" declaration. This is an
260 // egregious workaround for glibc, which adds throw() specifications
261 // to many libc functions as an optimization. Unfortunately, that
262 // optimization isn't permitted by the C++ standard, so we're forced
263 // to work around it here.
John McCalldb40c7f2010-12-14 08:05:40 +0000264 if (MissingEmptyExceptionSpecification && NewProto &&
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000265 (Old->getLocation().isInvalid() ||
266 Context.getSourceManager().isInSystemHeader(Old->getLocation())) &&
Douglas Gregorf40863c2010-02-12 07:32:17 +0000267 Old->isExternC()) {
Richard Smith8acb4282014-07-31 21:57:55 +0000268 New->setType(Context.getFunctionType(
269 NewProto->getReturnType(), NewProto->getParamTypes(),
270 NewProto->getExtProtoInfo().withExceptionSpec(EST_DynamicNone)));
Douglas Gregorf40863c2010-02-12 07:32:17 +0000271 return false;
272 }
273
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000274 const FunctionProtoType *OldProto =
275 Old->getType()->castAs<FunctionProtoType>();
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000276
Richard Smith8acb4282014-07-31 21:57:55 +0000277 FunctionProtoType::ExceptionSpecInfo ESI = OldProto->getExceptionSpecType();
278 if (ESI.Type == EST_Dynamic) {
279 ESI.Exceptions = OldProto->exceptions();
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000280 }
281
Richard Smitha91de372015-09-30 00:48:50 +0000282 if (ESI.Type == EST_ComputedNoexcept) {
283 // For computed noexcept, we can't just take the expression from the old
284 // prototype. It likely contains references to the old prototype's
285 // parameters.
286 New->setInvalidDecl();
287 } else {
288 // Update the type of the function with the appropriate exception
289 // specification.
290 New->setType(Context.getFunctionType(
291 NewProto->getReturnType(), NewProto->getParamTypes(),
292 NewProto->getExtProtoInfo().withExceptionSpec(ESI)));
293 }
294
David Majnemer06ce8a42015-10-20 20:49:21 +0000295 if (getLangOpts().MicrosoftExt && ESI.Type != EST_ComputedNoexcept) {
296 // Allow missing exception specifications in redeclarations as an extension.
297 DiagID = diag::ext_ms_missing_exception_specification;
298 ReturnValueOnError = false;
299 } else if (New->isReplaceableGlobalAllocationFunction() &&
300 ESI.Type != EST_ComputedNoexcept) {
301 // Allow missing exception specifications in redeclarations as an extension,
302 // when declaring a replaceable global allocation function.
Richard Smitha91de372015-09-30 00:48:50 +0000303 DiagID = diag::ext_missing_exception_specification;
304 ReturnValueOnError = false;
305 } else {
306 DiagID = diag::err_missing_exception_specification;
307 ReturnValueOnError = true;
308 }
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000309
310 // Warn about the lack of exception specification.
311 SmallString<128> ExceptionSpecString;
312 llvm::raw_svector_ostream OS(ExceptionSpecString);
313 switch (OldProto->getExceptionSpecType()) {
314 case EST_DynamicNone:
315 OS << "throw()";
316 break;
317
318 case EST_Dynamic: {
319 OS << "throw(";
320 bool OnFirstException = true;
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000321 for (const auto &E : OldProto->exceptions()) {
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000322 if (OnFirstException)
323 OnFirstException = false;
324 else
325 OS << ", ";
326
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000327 OS << E.getAsString(getPrintingPolicy());
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000328 }
329 OS << ")";
330 break;
331 }
332
333 case EST_BasicNoexcept:
334 OS << "noexcept";
335 break;
336
337 case EST_ComputedNoexcept:
338 OS << "noexcept(";
Richard Trieuddd01ce2014-06-09 22:53:25 +0000339 assert(OldProto->getNoexceptExpr() != nullptr && "Expected non-null Expr");
Craig Topperc3ec1492014-05-26 06:22:03 +0000340 OldProto->getNoexceptExpr()->printPretty(OS, nullptr, getPrintingPolicy());
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000341 OS << ")";
342 break;
343
344 default:
345 llvm_unreachable("This spec type is compatible with none.");
346 }
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000347
348 SourceLocation FixItLoc;
349 if (TypeSourceInfo *TSInfo = New->getTypeSourceInfo()) {
350 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Richard Smitha91de372015-09-30 00:48:50 +0000351 // FIXME: Preserve enough information so that we can produce a correct fixit
352 // location when there is a trailing return type.
353 if (auto FTLoc = TL.getAs<FunctionProtoTypeLoc>())
354 if (!FTLoc.getTypePtr()->hasTrailingReturn())
355 FixItLoc = getLocForEndOfToken(FTLoc.getLocalRangeEnd());
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000356 }
357
358 if (FixItLoc.isInvalid())
Richard Smitha91de372015-09-30 00:48:50 +0000359 Diag(New->getLocation(), DiagID)
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000360 << New << OS.str();
361 else {
Richard Smitha91de372015-09-30 00:48:50 +0000362 Diag(New->getLocation(), DiagID)
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000363 << New << OS.str()
364 << FixItHint::CreateInsertion(FixItLoc, " " + OS.str().str());
365 }
366
Yaron Keren8b563662015-10-03 10:46:20 +0000367 if (Old->getLocation().isValid())
Eli Friedman96dbf6f2013-06-25 00:46:32 +0000368 Diag(Old->getLocation(), diag::note_previous_declaration);
369
Richard Smitha91de372015-09-30 00:48:50 +0000370 return ReturnValueOnError;
Douglas Gregorf40863c2010-02-12 07:32:17 +0000371}
372
Sebastian Redl4915e632009-10-11 09:03:14 +0000373/// CheckEquivalentExceptionSpec - Check if the two types have equivalent
374/// exception specifications. Exception specifications are equivalent if
375/// they allow exactly the same set of exception types. It does not matter how
376/// that is achieved. See C++ [except.spec]p2.
377bool Sema::CheckEquivalentExceptionSpec(
378 const FunctionProtoType *Old, SourceLocation OldLoc,
379 const FunctionProtoType *New, SourceLocation NewLoc) {
Francois Pichet13b4e682011-03-19 23:05:18 +0000380 unsigned DiagID = diag::err_mismatched_exception_spec;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000381 if (getLangOpts().MicrosoftExt)
Richard Smith1b98ccc2014-07-19 01:39:17 +0000382 DiagID = diag::ext_mismatched_exception_spec;
Hans Wennborg39a509a2014-02-05 02:37:58 +0000383 bool Result = CheckEquivalentExceptionSpec(PDiag(DiagID),
384 PDiag(diag::note_previous_declaration), Old, OldLoc, New, NewLoc);
385
386 // In Microsoft mode, mismatching exception specifications just cause a warning.
387 if (getLangOpts().MicrosoftExt)
388 return false;
389 return Result;
Sebastian Redl4915e632009-10-11 09:03:14 +0000390}
391
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000392/// CheckEquivalentExceptionSpec - Check if the two types have compatible
393/// exception specifications. See C++ [except.spec]p3.
Richard Smith66f3ac92012-10-20 08:26:51 +0000394///
395/// \return \c false if the exception specifications match, \c true if there is
396/// a problem. If \c true is returned, either a diagnostic has already been
397/// produced or \c *MissingExceptionSpecification is set to \c true.
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000398bool Sema::CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000399 const PartialDiagnostic & NoteID,
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000400 const FunctionProtoType *Old,
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000401 SourceLocation OldLoc,
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000402 const FunctionProtoType *New,
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000403 SourceLocation NewLoc,
404 bool *MissingExceptionSpecification,
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000405 bool*MissingEmptyExceptionSpecification,
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000406 bool AllowNoexceptAllMatchWithNoSpec,
407 bool IsOperatorNew) {
John McCallf9c94092010-05-28 08:37:35 +0000408 // Just completely ignore this under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000409 if (!getLangOpts().CXXExceptions)
John McCallf9c94092010-05-28 08:37:35 +0000410 return false;
411
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000412 if (MissingExceptionSpecification)
413 *MissingExceptionSpecification = false;
414
Douglas Gregorf40863c2010-02-12 07:32:17 +0000415 if (MissingEmptyExceptionSpecification)
416 *MissingEmptyExceptionSpecification = false;
417
Richard Smithf623c962012-04-17 00:58:00 +0000418 Old = ResolveExceptionSpec(NewLoc, Old);
419 if (!Old)
420 return false;
421 New = ResolveExceptionSpec(NewLoc, New);
422 if (!New)
423 return false;
424
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000425 // C++0x [except.spec]p3: Two exception-specifications are compatible if:
426 // - both are non-throwing, regardless of their form,
427 // - both have the form noexcept(constant-expression) and the constant-
428 // expressions are equivalent,
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000429 // - both are dynamic-exception-specifications that have the same set of
430 // adjusted types.
431 //
Eric Christophere6b7cf42015-07-10 18:25:52 +0000432 // C++0x [except.spec]p12: An exception-specification is non-throwing if it is
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000433 // of the form throw(), noexcept, or noexcept(constant-expression) where the
434 // constant-expression yields true.
435 //
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000436 // C++0x [except.spec]p4: If any declaration of a function has an exception-
437 // specifier that is not a noexcept-specification allowing all exceptions,
438 // all declarations [...] of that function shall have a compatible
439 // exception-specification.
440 //
441 // That last point basically means that noexcept(false) matches no spec.
442 // It's considered when AllowNoexceptAllMatchWithNoSpec is true.
443
444 ExceptionSpecificationType OldEST = Old->getExceptionSpecType();
445 ExceptionSpecificationType NewEST = New->getExceptionSpecType();
446
Richard Smithd3b5c9082012-07-27 04:22:15 +0000447 assert(!isUnresolvedExceptionSpec(OldEST) &&
448 !isUnresolvedExceptionSpec(NewEST) &&
Richard Smith938f40b2011-06-11 17:19:42 +0000449 "Shouldn't see unknown exception specifications here");
450
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000451 // Shortcut the case where both have no spec.
452 if (OldEST == EST_None && NewEST == EST_None)
453 return false;
454
Sebastian Redl31ad7542011-03-13 17:09:40 +0000455 FunctionProtoType::NoexceptResult OldNR = Old->getNoexceptSpec(Context);
456 FunctionProtoType::NoexceptResult NewNR = New->getNoexceptSpec(Context);
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000457 if (OldNR == FunctionProtoType::NR_BadNoexcept ||
458 NewNR == FunctionProtoType::NR_BadNoexcept)
459 return false;
460
461 // Dependent noexcept specifiers are compatible with each other, but nothing
462 // else.
463 // One noexcept is compatible with another if the argument is the same
464 if (OldNR == NewNR &&
465 OldNR != FunctionProtoType::NR_NoNoexcept &&
466 NewNR != FunctionProtoType::NR_NoNoexcept)
467 return false;
468 if (OldNR != NewNR &&
469 OldNR != FunctionProtoType::NR_NoNoexcept &&
470 NewNR != FunctionProtoType::NR_NoNoexcept) {
471 Diag(NewLoc, DiagID);
David Majnemer7da23022015-02-19 07:28:55 +0000472 if (NoteID.getDiagID() != 0 && OldLoc.isValid())
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000473 Diag(OldLoc, NoteID);
474 return true;
Douglas Gregorf62c5292010-08-30 15:04:51 +0000475 }
476
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000477 // The MS extension throw(...) is compatible with itself.
478 if (OldEST == EST_MSAny && NewEST == EST_MSAny)
Sebastian Redl4915e632009-10-11 09:03:14 +0000479 return false;
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000480
481 // It's also compatible with no spec.
482 if ((OldEST == EST_None && NewEST == EST_MSAny) ||
483 (OldEST == EST_MSAny && NewEST == EST_None))
484 return false;
485
486 // It's also compatible with noexcept(false).
487 if (OldEST == EST_MSAny && NewNR == FunctionProtoType::NR_Throw)
488 return false;
489 if (NewEST == EST_MSAny && OldNR == FunctionProtoType::NR_Throw)
490 return false;
491
492 // As described above, noexcept(false) matches no spec only for functions.
493 if (AllowNoexceptAllMatchWithNoSpec) {
494 if (OldEST == EST_None && NewNR == FunctionProtoType::NR_Throw)
495 return false;
496 if (NewEST == EST_None && OldNR == FunctionProtoType::NR_Throw)
497 return false;
498 }
499
500 // Any non-throwing specifications are compatible.
501 bool OldNonThrowing = OldNR == FunctionProtoType::NR_Nothrow ||
502 OldEST == EST_DynamicNone;
503 bool NewNonThrowing = NewNR == FunctionProtoType::NR_Nothrow ||
504 NewEST == EST_DynamicNone;
505 if (OldNonThrowing && NewNonThrowing)
506 return false;
507
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000508 // As a special compatibility feature, under C++0x we accept no spec and
509 // throw(std::bad_alloc) as equivalent for operator new and operator new[].
510 // This is because the implicit declaration changed, but old code would break.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000511 if (getLangOpts().CPlusPlus11 && IsOperatorNew) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000512 const FunctionProtoType *WithExceptions = nullptr;
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000513 if (OldEST == EST_None && NewEST == EST_Dynamic)
514 WithExceptions = New;
515 else if (OldEST == EST_Dynamic && NewEST == EST_None)
516 WithExceptions = Old;
517 if (WithExceptions && WithExceptions->getNumExceptions() == 1) {
518 // One has no spec, the other throw(something). If that something is
519 // std::bad_alloc, all conditions are met.
520 QualType Exception = *WithExceptions->exception_begin();
521 if (CXXRecordDecl *ExRecord = Exception->getAsCXXRecordDecl()) {
522 IdentifierInfo* Name = ExRecord->getIdentifier();
523 if (Name && Name->getName() == "bad_alloc") {
524 // It's called bad_alloc, but is it in std?
Richard Trieuc771d5d2014-05-28 02:16:01 +0000525 if (ExRecord->isInStdNamespace()) {
526 return false;
Sebastian Redlcb5dd002011-03-15 19:52:30 +0000527 }
528 }
529 }
530 }
531 }
532
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000533 // At this point, the only remaining valid case is two matching dynamic
534 // specifications. We return here unless both specifications are dynamic.
535 if (OldEST != EST_Dynamic || NewEST != EST_Dynamic) {
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000536 if (MissingExceptionSpecification && Old->hasExceptionSpec() &&
Douglas Gregorf40863c2010-02-12 07:32:17 +0000537 !New->hasExceptionSpec()) {
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000538 // The old type has an exception specification of some sort, but
539 // the new type does not.
540 *MissingExceptionSpecification = true;
541
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000542 if (MissingEmptyExceptionSpecification && OldNonThrowing) {
543 // The old type has a throw() or noexcept(true) exception specification
544 // and the new type has no exception specification, and the caller asked
Douglas Gregord6bc5e62010-03-24 07:14:45 +0000545 // to handle this itself.
546 *MissingEmptyExceptionSpecification = true;
547 }
548
Douglas Gregorf40863c2010-02-12 07:32:17 +0000549 return true;
550 }
551
Sebastian Redl4915e632009-10-11 09:03:14 +0000552 Diag(NewLoc, DiagID);
David Majnemer7da23022015-02-19 07:28:55 +0000553 if (NoteID.getDiagID() != 0 && OldLoc.isValid())
Sebastian Redl4915e632009-10-11 09:03:14 +0000554 Diag(OldLoc, NoteID);
555 return true;
556 }
557
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000558 assert(OldEST == EST_Dynamic && NewEST == EST_Dynamic &&
559 "Exception compatibility logic error: non-dynamic spec slipped through.");
560
Sebastian Redl4915e632009-10-11 09:03:14 +0000561 bool Success = true;
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000562 // Both have a dynamic exception spec. Collect the first set, then compare
Sebastian Redl4915e632009-10-11 09:03:14 +0000563 // to the second.
Sebastian Redl184edca2009-10-14 15:06:25 +0000564 llvm::SmallPtrSet<CanQualType, 8> OldTypes, NewTypes;
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000565 for (const auto &I : Old->exceptions())
566 OldTypes.insert(Context.getCanonicalType(I).getUnqualifiedType());
Sebastian Redl4915e632009-10-11 09:03:14 +0000567
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000568 for (const auto &I : New->exceptions()) {
569 CanQualType TypePtr = Context.getCanonicalType(I).getUnqualifiedType();
Sebastian Redl6e4c8712009-10-11 09:11:23 +0000570 if(OldTypes.count(TypePtr))
571 NewTypes.insert(TypePtr);
572 else
573 Success = false;
574 }
Sebastian Redl4915e632009-10-11 09:03:14 +0000575
Sebastian Redl6e4c8712009-10-11 09:11:23 +0000576 Success = Success && OldTypes.size() == NewTypes.size();
Sebastian Redl4915e632009-10-11 09:03:14 +0000577
578 if (Success) {
579 return false;
580 }
581 Diag(NewLoc, DiagID);
David Majnemer7da23022015-02-19 07:28:55 +0000582 if (NoteID.getDiagID() != 0 && OldLoc.isValid())
Sebastian Redl4915e632009-10-11 09:03:14 +0000583 Diag(OldLoc, NoteID);
584 return true;
585}
586
587/// CheckExceptionSpecSubset - Check whether the second function type's
588/// exception specification is a subset (or equivalent) of the first function
589/// type. This is used by override and pointer assignment checks.
Sebastian Redla44822f2009-10-14 16:09:29 +0000590bool Sema::CheckExceptionSpecSubset(
591 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
Sebastian Redl4915e632009-10-11 09:03:14 +0000592 const FunctionProtoType *Superset, SourceLocation SuperLoc,
593 const FunctionProtoType *Subset, SourceLocation SubLoc) {
John McCallf9c94092010-05-28 08:37:35 +0000594
595 // Just auto-succeed under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000596 if (!getLangOpts().CXXExceptions)
John McCallf9c94092010-05-28 08:37:35 +0000597 return false;
598
Sebastian Redl4915e632009-10-11 09:03:14 +0000599 // FIXME: As usual, we could be more specific in our error messages, but
600 // that better waits until we've got types with source locations.
601
602 if (!SubLoc.isValid())
603 SubLoc = SuperLoc;
604
Richard Smithf623c962012-04-17 00:58:00 +0000605 // Resolve the exception specifications, if needed.
606 Superset = ResolveExceptionSpec(SuperLoc, Superset);
607 if (!Superset)
608 return false;
609 Subset = ResolveExceptionSpec(SubLoc, Subset);
610 if (!Subset)
611 return false;
612
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000613 ExceptionSpecificationType SuperEST = Superset->getExceptionSpecType();
614
Sebastian Redl4915e632009-10-11 09:03:14 +0000615 // If superset contains everything, we're done.
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000616 if (SuperEST == EST_None || SuperEST == EST_MSAny)
Sebastian Redl4915e632009-10-11 09:03:14 +0000617 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
618
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000619 // If there are dependent noexcept specs, assume everything is fine. Unlike
620 // with the equivalency check, this is safe in this case, because we don't
621 // want to merge declarations. Checks after instantiation will catch any
622 // omissions we make here.
623 // We also shortcut checking if a noexcept expression was bad.
624
Sebastian Redl31ad7542011-03-13 17:09:40 +0000625 FunctionProtoType::NoexceptResult SuperNR =Superset->getNoexceptSpec(Context);
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000626 if (SuperNR == FunctionProtoType::NR_BadNoexcept ||
627 SuperNR == FunctionProtoType::NR_Dependent)
628 return false;
629
630 // Another case of the superset containing everything.
631 if (SuperNR == FunctionProtoType::NR_Throw)
632 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
633
634 ExceptionSpecificationType SubEST = Subset->getExceptionSpecType();
635
Richard Smithd3b5c9082012-07-27 04:22:15 +0000636 assert(!isUnresolvedExceptionSpec(SuperEST) &&
637 !isUnresolvedExceptionSpec(SubEST) &&
Richard Smith938f40b2011-06-11 17:19:42 +0000638 "Shouldn't see unknown exception specifications here");
639
Sebastian Redl4915e632009-10-11 09:03:14 +0000640 // It does not. If the subset contains everything, we've failed.
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000641 if (SubEST == EST_None || SubEST == EST_MSAny) {
Sebastian Redl4915e632009-10-11 09:03:14 +0000642 Diag(SubLoc, DiagID);
Sebastian Redla44822f2009-10-14 16:09:29 +0000643 if (NoteID.getDiagID() != 0)
Sebastian Redl4915e632009-10-11 09:03:14 +0000644 Diag(SuperLoc, NoteID);
645 return true;
646 }
647
Sebastian Redl31ad7542011-03-13 17:09:40 +0000648 FunctionProtoType::NoexceptResult SubNR = Subset->getNoexceptSpec(Context);
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000649 if (SubNR == FunctionProtoType::NR_BadNoexcept ||
650 SubNR == FunctionProtoType::NR_Dependent)
651 return false;
652
653 // Another case of the subset containing everything.
654 if (SubNR == FunctionProtoType::NR_Throw) {
655 Diag(SubLoc, DiagID);
656 if (NoteID.getDiagID() != 0)
657 Diag(SuperLoc, NoteID);
658 return true;
659 }
660
661 // If the subset contains nothing, we're done.
662 if (SubEST == EST_DynamicNone || SubNR == FunctionProtoType::NR_Nothrow)
663 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
664
665 // Otherwise, if the superset contains nothing, we've failed.
666 if (SuperEST == EST_DynamicNone || SuperNR == FunctionProtoType::NR_Nothrow) {
667 Diag(SubLoc, DiagID);
668 if (NoteID.getDiagID() != 0)
669 Diag(SuperLoc, NoteID);
670 return true;
671 }
672
673 assert(SuperEST == EST_Dynamic && SubEST == EST_Dynamic &&
674 "Exception spec subset: non-dynamic case slipped through.");
675
676 // Neither contains everything or nothing. Do a proper comparison.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000677 for (const auto &SubI : Subset->exceptions()) {
Sebastian Redl4915e632009-10-11 09:03:14 +0000678 // Take one type from the subset.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000679 QualType CanonicalSubT = Context.getCanonicalType(SubI);
Sebastian Redl075b21d2009-10-14 14:38:54 +0000680 // Unwrap pointers and references so that we can do checks within a class
681 // hierarchy. Don't unwrap member pointers; they don't have hierarchy
682 // conversions on the pointee.
Sebastian Redl4915e632009-10-11 09:03:14 +0000683 bool SubIsPointer = false;
684 if (const ReferenceType *RefTy = CanonicalSubT->getAs<ReferenceType>())
685 CanonicalSubT = RefTy->getPointeeType();
686 if (const PointerType *PtrTy = CanonicalSubT->getAs<PointerType>()) {
687 CanonicalSubT = PtrTy->getPointeeType();
688 SubIsPointer = true;
689 }
690 bool SubIsClass = CanonicalSubT->isRecordType();
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000691 CanonicalSubT = CanonicalSubT.getLocalUnqualifiedType();
Sebastian Redl4915e632009-10-11 09:03:14 +0000692
693 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
694 /*DetectVirtual=*/false);
695
696 bool Contained = false;
697 // Make sure it's in the superset.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000698 for (const auto &SuperI : Superset->exceptions()) {
699 QualType CanonicalSuperT = Context.getCanonicalType(SuperI);
Sebastian Redl4915e632009-10-11 09:03:14 +0000700 // SubT must be SuperT or derived from it, or pointer or reference to
701 // such types.
702 if (const ReferenceType *RefTy = CanonicalSuperT->getAs<ReferenceType>())
703 CanonicalSuperT = RefTy->getPointeeType();
704 if (SubIsPointer) {
705 if (const PointerType *PtrTy = CanonicalSuperT->getAs<PointerType>())
706 CanonicalSuperT = PtrTy->getPointeeType();
707 else {
708 continue;
709 }
710 }
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000711 CanonicalSuperT = CanonicalSuperT.getLocalUnqualifiedType();
Sebastian Redl4915e632009-10-11 09:03:14 +0000712 // If the types are the same, move on to the next type in the subset.
713 if (CanonicalSubT == CanonicalSuperT) {
714 Contained = true;
715 break;
716 }
717
718 // Otherwise we need to check the inheritance.
719 if (!SubIsClass || !CanonicalSuperT->isRecordType())
720 continue;
721
722 Paths.clear();
Richard Smith0f59cb32015-12-18 21:45:41 +0000723 if (!IsDerivedFrom(SubLoc, CanonicalSubT, CanonicalSuperT, Paths))
Sebastian Redl4915e632009-10-11 09:03:14 +0000724 continue;
725
Douglas Gregor27ac4292010-05-21 20:29:55 +0000726 if (Paths.isAmbiguous(Context.getCanonicalType(CanonicalSuperT)))
Sebastian Redl4915e632009-10-11 09:03:14 +0000727 continue;
728
John McCall5b0829a2010-02-10 09:31:12 +0000729 // Do this check from a context without privileges.
John McCall1064d7e2010-03-16 05:22:47 +0000730 switch (CheckBaseClassAccess(SourceLocation(),
John McCall5b0829a2010-02-10 09:31:12 +0000731 CanonicalSuperT, CanonicalSubT,
732 Paths.front(),
John McCall1064d7e2010-03-16 05:22:47 +0000733 /*Diagnostic*/ 0,
John McCall5b0829a2010-02-10 09:31:12 +0000734 /*ForceCheck*/ true,
John McCall1064d7e2010-03-16 05:22:47 +0000735 /*ForceUnprivileged*/ true)) {
John McCall5b0829a2010-02-10 09:31:12 +0000736 case AR_accessible: break;
737 case AR_inaccessible: continue;
738 case AR_dependent:
739 llvm_unreachable("access check dependent for unprivileged context");
John McCall5b0829a2010-02-10 09:31:12 +0000740 case AR_delayed:
741 llvm_unreachable("access check delayed in non-declaration");
John McCall5b0829a2010-02-10 09:31:12 +0000742 }
Sebastian Redl4915e632009-10-11 09:03:14 +0000743
744 Contained = true;
745 break;
746 }
747 if (!Contained) {
748 Diag(SubLoc, DiagID);
Sebastian Redla44822f2009-10-14 16:09:29 +0000749 if (NoteID.getDiagID() != 0)
Sebastian Redl4915e632009-10-11 09:03:14 +0000750 Diag(SuperLoc, NoteID);
751 return true;
752 }
753 }
754 // We've run half the gauntlet.
755 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
756}
757
758static bool CheckSpecForTypesEquivalent(Sema &S,
Sebastian Redla44822f2009-10-14 16:09:29 +0000759 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
Sebastian Redl4915e632009-10-11 09:03:14 +0000760 QualType Target, SourceLocation TargetLoc,
761 QualType Source, SourceLocation SourceLoc)
762{
763 const FunctionProtoType *TFunc = GetUnderlyingFunction(Target);
764 if (!TFunc)
765 return false;
766 const FunctionProtoType *SFunc = GetUnderlyingFunction(Source);
767 if (!SFunc)
768 return false;
769
770 return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc,
771 SFunc, SourceLoc);
772}
773
774/// CheckParamExceptionSpec - Check if the parameter and return types of the
775/// two functions have equivalent exception specs. This is part of the
776/// assignment and override compatibility check. We do not check the parameters
777/// of parameter function pointers recursively, as no sane programmer would
778/// even be able to write such a function type.
Richard Smith2e321552014-11-12 02:00:47 +0000779bool Sema::CheckParamExceptionSpec(const PartialDiagnostic &NoteID,
780 const FunctionProtoType *Target,
781 SourceLocation TargetLoc,
782 const FunctionProtoType *Source,
783 SourceLocation SourceLoc) {
Alp Toker314cc812014-01-25 16:55:45 +0000784 if (CheckSpecForTypesEquivalent(
785 *this, PDiag(diag::err_deep_exception_specs_differ) << 0, PDiag(),
786 Target->getReturnType(), TargetLoc, Source->getReturnType(),
787 SourceLoc))
Sebastian Redl4915e632009-10-11 09:03:14 +0000788 return true;
789
Sebastian Redla44822f2009-10-14 16:09:29 +0000790 // We shouldn't even be testing this unless the arguments are otherwise
Sebastian Redl4915e632009-10-11 09:03:14 +0000791 // compatible.
Alp Toker9cacbab2014-01-20 20:26:09 +0000792 assert(Target->getNumParams() == Source->getNumParams() &&
Sebastian Redl4915e632009-10-11 09:03:14 +0000793 "Functions have different argument counts.");
Alp Toker9cacbab2014-01-20 20:26:09 +0000794 for (unsigned i = 0, E = Target->getNumParams(); i != E; ++i) {
795 if (CheckSpecForTypesEquivalent(
796 *this, PDiag(diag::err_deep_exception_specs_differ) << 1, PDiag(),
797 Target->getParamType(i), TargetLoc, Source->getParamType(i),
798 SourceLoc))
Sebastian Redl4915e632009-10-11 09:03:14 +0000799 return true;
800 }
801 return false;
802}
803
Richard Smith2e321552014-11-12 02:00:47 +0000804bool Sema::CheckExceptionSpecCompatibility(Expr *From, QualType ToType) {
Sebastian Redl4915e632009-10-11 09:03:14 +0000805 // First we check for applicability.
806 // Target type must be a function, function pointer or function reference.
807 const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType);
Richard Smith2e321552014-11-12 02:00:47 +0000808 if (!ToFunc || ToFunc->hasDependentExceptionSpec())
Sebastian Redl4915e632009-10-11 09:03:14 +0000809 return false;
810
811 // SourceType must be a function or function pointer.
812 const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType());
Richard Smith2e321552014-11-12 02:00:47 +0000813 if (!FromFunc || FromFunc->hasDependentExceptionSpec())
Sebastian Redl4915e632009-10-11 09:03:14 +0000814 return false;
815
816 // Now we've got the correct types on both sides, check their compatibility.
817 // This means that the source of the conversion can only throw a subset of
818 // the exceptions of the target, and any exception specs on arguments or
819 // return types must be equivalent.
Richard Smith2e321552014-11-12 02:00:47 +0000820 //
821 // FIXME: If there is a nested dependent exception specification, we should
822 // not be checking it here. This is fine:
823 // template<typename T> void f() {
824 // void (*p)(void (*) throw(T));
825 // void (*q)(void (*) throw(int)) = p;
826 // }
827 // ... because it might be instantiated with T=int.
Douglas Gregor89336232010-03-29 23:34:08 +0000828 return CheckExceptionSpecSubset(PDiag(diag::err_incompatible_exception_specs),
829 PDiag(), ToFunc,
830 From->getSourceRange().getBegin(),
Sebastian Redl4915e632009-10-11 09:03:14 +0000831 FromFunc, SourceLocation());
832}
833
834bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
835 const CXXMethodDecl *Old) {
Richard Smith88f45492014-11-22 03:09:05 +0000836 // If the new exception specification hasn't been parsed yet, skip the check.
837 // We'll get called again once it's been parsed.
838 if (New->getType()->castAs<FunctionProtoType>()->getExceptionSpecType() ==
839 EST_Unparsed)
840 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000841 if (getLangOpts().CPlusPlus11 && isa<CXXDestructorDecl>(New)) {
Sebastian Redl645d9582011-05-20 05:57:18 +0000842 // Don't check uninstantiated template destructors at all. We can only
843 // synthesize correct specs after the template is instantiated.
844 if (New->getParent()->isDependentType())
845 return false;
846 if (New->getParent()->isBeingDefined()) {
847 // The destructor might be updated once the definition is finished. So
848 // remember it and check later.
Richard Smith88f45492014-11-22 03:09:05 +0000849 DelayedExceptionSpecChecks.push_back(std::make_pair(New, Old));
Sebastian Redl645d9582011-05-20 05:57:18 +0000850 return false;
851 }
Sebastian Redl623ea822011-05-19 05:13:44 +0000852 }
Richard Smith88f45492014-11-22 03:09:05 +0000853 // If the old exception specification hasn't been parsed yet, remember that
854 // we need to perform this check when we get to the end of the outermost
855 // lexically-surrounding class.
856 if (Old->getType()->castAs<FunctionProtoType>()->getExceptionSpecType() ==
857 EST_Unparsed) {
858 DelayedExceptionSpecChecks.push_back(std::make_pair(New, Old));
Richard Smith0b3a4622014-11-13 20:01:57 +0000859 return false;
Richard Smith88f45492014-11-22 03:09:05 +0000860 }
Francois Picheta8032e92011-05-24 02:11:43 +0000861 unsigned DiagID = diag::err_override_exception_spec;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000862 if (getLangOpts().MicrosoftExt)
Richard Smith1b98ccc2014-07-19 01:39:17 +0000863 DiagID = diag::ext_override_exception_spec;
Francois Picheta8032e92011-05-24 02:11:43 +0000864 return CheckExceptionSpecSubset(PDiag(DiagID),
Douglas Gregor89336232010-03-29 23:34:08 +0000865 PDiag(diag::note_overridden_virtual_function),
Sebastian Redl4915e632009-10-11 09:03:14 +0000866 Old->getType()->getAs<FunctionProtoType>(),
867 Old->getLocation(),
868 New->getType()->getAs<FunctionProtoType>(),
869 New->getLocation());
870}
871
Benjamin Kramer642f1732015-07-02 21:03:14 +0000872static CanThrowResult canSubExprsThrow(Sema &S, const Expr *E) {
Richard Smithf623c962012-04-17 00:58:00 +0000873 CanThrowResult R = CT_Cannot;
Benjamin Kramer642f1732015-07-02 21:03:14 +0000874 for (const Stmt *SubStmt : E->children()) {
875 R = mergeCanThrow(R, S.canThrow(cast<Expr>(SubStmt)));
876 if (R == CT_Can)
877 break;
878 }
Richard Smithf623c962012-04-17 00:58:00 +0000879 return R;
880}
881
Eli Friedman0423b762013-06-25 01:24:22 +0000882static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D) {
883 assert(D && "Expected decl");
Richard Smithf623c962012-04-17 00:58:00 +0000884
885 // See if we can get a function type from the decl somehow.
886 const ValueDecl *VD = dyn_cast<ValueDecl>(D);
887 if (!VD) // If we have no clue what we're calling, assume the worst.
888 return CT_Can;
889
890 // As an extension, we assume that __attribute__((nothrow)) functions don't
891 // throw.
892 if (isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())
893 return CT_Cannot;
894
895 QualType T = VD->getType();
896 const FunctionProtoType *FT;
897 if ((FT = T->getAs<FunctionProtoType>())) {
898 } else if (const PointerType *PT = T->getAs<PointerType>())
899 FT = PT->getPointeeType()->getAs<FunctionProtoType>();
900 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
901 FT = RT->getPointeeType()->getAs<FunctionProtoType>();
902 else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
903 FT = MT->getPointeeType()->getAs<FunctionProtoType>();
904 else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
905 FT = BT->getPointeeType()->getAs<FunctionProtoType>();
906
907 if (!FT)
908 return CT_Can;
909
910 FT = S.ResolveExceptionSpec(E->getLocStart(), FT);
911 if (!FT)
912 return CT_Can;
913
Richard Smithf623c962012-04-17 00:58:00 +0000914 return FT->isNothrow(S.Context) ? CT_Cannot : CT_Can;
915}
916
917static CanThrowResult canDynamicCastThrow(const CXXDynamicCastExpr *DC) {
918 if (DC->isTypeDependent())
919 return CT_Dependent;
920
921 if (!DC->getTypeAsWritten()->isReferenceType())
922 return CT_Cannot;
923
924 if (DC->getSubExpr()->isTypeDependent())
925 return CT_Dependent;
926
927 return DC->getCastKind() == clang::CK_Dynamic? CT_Can : CT_Cannot;
928}
929
930static CanThrowResult canTypeidThrow(Sema &S, const CXXTypeidExpr *DC) {
931 if (DC->isTypeOperand())
932 return CT_Cannot;
933
934 Expr *Op = DC->getExprOperand();
935 if (Op->isTypeDependent())
936 return CT_Dependent;
937
938 const RecordType *RT = Op->getType()->getAs<RecordType>();
939 if (!RT)
940 return CT_Cannot;
941
942 if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
943 return CT_Cannot;
944
945 if (Op->Classify(S.Context).isPRValue())
946 return CT_Cannot;
947
948 return CT_Can;
949}
950
951CanThrowResult Sema::canThrow(const Expr *E) {
952 // C++ [expr.unary.noexcept]p3:
953 // [Can throw] if in a potentially-evaluated context the expression would
954 // contain:
955 switch (E->getStmtClass()) {
956 case Expr::CXXThrowExprClass:
957 // - a potentially evaluated throw-expression
958 return CT_Can;
959
960 case Expr::CXXDynamicCastExprClass: {
961 // - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
962 // where T is a reference type, that requires a run-time check
963 CanThrowResult CT = canDynamicCastThrow(cast<CXXDynamicCastExpr>(E));
964 if (CT == CT_Can)
965 return CT;
966 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
967 }
968
969 case Expr::CXXTypeidExprClass:
970 // - a potentially evaluated typeid expression applied to a glvalue
971 // expression whose type is a polymorphic class type
972 return canTypeidThrow(*this, cast<CXXTypeidExpr>(E));
973
974 // - a potentially evaluated call to a function, member function, function
975 // pointer, or member function pointer that does not have a non-throwing
976 // exception-specification
977 case Expr::CallExprClass:
978 case Expr::CXXMemberCallExprClass:
979 case Expr::CXXOperatorCallExprClass:
980 case Expr::UserDefinedLiteralClass: {
981 const CallExpr *CE = cast<CallExpr>(E);
982 CanThrowResult CT;
983 if (E->isTypeDependent())
984 CT = CT_Dependent;
985 else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens()))
986 CT = CT_Cannot;
Eli Friedman5a8738f2013-06-25 01:55:41 +0000987 else if (CE->getCalleeDecl())
Richard Smithf623c962012-04-17 00:58:00 +0000988 CT = canCalleeThrow(*this, E, CE->getCalleeDecl());
Eli Friedman5a8738f2013-06-25 01:55:41 +0000989 else
990 CT = CT_Can;
Richard Smithf623c962012-04-17 00:58:00 +0000991 if (CT == CT_Can)
992 return CT;
993 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
994 }
995
996 case Expr::CXXConstructExprClass:
997 case Expr::CXXTemporaryObjectExprClass: {
998 CanThrowResult CT = canCalleeThrow(*this, E,
999 cast<CXXConstructExpr>(E)->getConstructor());
1000 if (CT == CT_Can)
1001 return CT;
1002 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1003 }
1004
Richard Smith5179eb72016-06-28 19:03:57 +00001005 case Expr::CXXInheritedCtorInitExprClass:
1006 return canCalleeThrow(*this, E,
1007 cast<CXXInheritedCtorInitExpr>(E)->getConstructor());
1008
Richard Smithf623c962012-04-17 00:58:00 +00001009 case Expr::LambdaExprClass: {
1010 const LambdaExpr *Lambda = cast<LambdaExpr>(E);
1011 CanThrowResult CT = CT_Cannot;
James Y Knight53c76162015-07-17 18:21:37 +00001012 for (LambdaExpr::const_capture_init_iterator
1013 Cap = Lambda->capture_init_begin(),
1014 CapEnd = Lambda->capture_init_end();
Richard Smithf623c962012-04-17 00:58:00 +00001015 Cap != CapEnd; ++Cap)
1016 CT = mergeCanThrow(CT, canThrow(*Cap));
1017 return CT;
1018 }
1019
1020 case Expr::CXXNewExprClass: {
1021 CanThrowResult CT;
1022 if (E->isTypeDependent())
1023 CT = CT_Dependent;
1024 else
1025 CT = canCalleeThrow(*this, E, cast<CXXNewExpr>(E)->getOperatorNew());
1026 if (CT == CT_Can)
1027 return CT;
1028 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1029 }
1030
1031 case Expr::CXXDeleteExprClass: {
1032 CanThrowResult CT;
1033 QualType DTy = cast<CXXDeleteExpr>(E)->getDestroyedType();
1034 if (DTy.isNull() || DTy->isDependentType()) {
1035 CT = CT_Dependent;
1036 } else {
1037 CT = canCalleeThrow(*this, E,
1038 cast<CXXDeleteExpr>(E)->getOperatorDelete());
1039 if (const RecordType *RT = DTy->getAs<RecordType>()) {
1040 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedman0423b762013-06-25 01:24:22 +00001041 const CXXDestructorDecl *DD = RD->getDestructor();
1042 if (DD)
1043 CT = mergeCanThrow(CT, canCalleeThrow(*this, E, DD));
Richard Smithf623c962012-04-17 00:58:00 +00001044 }
1045 if (CT == CT_Can)
1046 return CT;
1047 }
1048 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1049 }
1050
1051 case Expr::CXXBindTemporaryExprClass: {
1052 // The bound temporary has to be destroyed again, which might throw.
1053 CanThrowResult CT = canCalleeThrow(*this, E,
1054 cast<CXXBindTemporaryExpr>(E)->getTemporary()->getDestructor());
1055 if (CT == CT_Can)
1056 return CT;
1057 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1058 }
1059
1060 // ObjC message sends are like function calls, but never have exception
1061 // specs.
1062 case Expr::ObjCMessageExprClass:
1063 case Expr::ObjCPropertyRefExprClass:
1064 case Expr::ObjCSubscriptRefExprClass:
1065 return CT_Can;
1066
1067 // All the ObjC literals that are implemented as calls are
1068 // potentially throwing unless we decide to close off that
1069 // possibility.
1070 case Expr::ObjCArrayLiteralClass:
1071 case Expr::ObjCDictionaryLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00001072 case Expr::ObjCBoxedExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001073 return CT_Can;
1074
1075 // Many other things have subexpressions, so we have to test those.
1076 // Some are simple:
Richard Smith9f690bd2015-10-27 06:02:45 +00001077 case Expr::CoawaitExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001078 case Expr::ConditionalOperatorClass:
1079 case Expr::CompoundLiteralExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00001080 case Expr::CoyieldExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001081 case Expr::CXXConstCastExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001082 case Expr::CXXReinterpretCastExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00001083 case Expr::CXXStdInitializerListExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001084 case Expr::DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00001085 case Expr::DesignatedInitUpdateExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001086 case Expr::ExprWithCleanupsClass:
1087 case Expr::ExtVectorElementExprClass:
1088 case Expr::InitListExprClass:
1089 case Expr::MemberExprClass:
1090 case Expr::ObjCIsaExprClass:
1091 case Expr::ObjCIvarRefExprClass:
1092 case Expr::ParenExprClass:
1093 case Expr::ParenListExprClass:
1094 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00001095 case Expr::ConvertVectorExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001096 case Expr::VAArgExprClass:
1097 return canSubExprsThrow(*this, E);
1098
1099 // Some might be dependent for other reasons.
1100 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001101 case Expr::OMPArraySectionExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001102 case Expr::BinaryOperatorClass:
1103 case Expr::CompoundAssignOperatorClass:
1104 case Expr::CStyleCastExprClass:
1105 case Expr::CXXStaticCastExprClass:
1106 case Expr::CXXFunctionalCastExprClass:
1107 case Expr::ImplicitCastExprClass:
1108 case Expr::MaterializeTemporaryExprClass:
1109 case Expr::UnaryOperatorClass: {
1110 CanThrowResult CT = E->isTypeDependent() ? CT_Dependent : CT_Cannot;
1111 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1112 }
1113
1114 // FIXME: We should handle StmtExpr, but that opens a MASSIVE can of worms.
1115 case Expr::StmtExprClass:
1116 return CT_Can;
1117
Richard Smith852c9db2013-04-20 22:23:05 +00001118 case Expr::CXXDefaultArgExprClass:
1119 return canThrow(cast<CXXDefaultArgExpr>(E)->getExpr());
1120
1121 case Expr::CXXDefaultInitExprClass:
1122 return canThrow(cast<CXXDefaultInitExpr>(E)->getExpr());
1123
Richard Smithf623c962012-04-17 00:58:00 +00001124 case Expr::ChooseExprClass:
1125 if (E->isTypeDependent() || E->isValueDependent())
1126 return CT_Dependent;
Eli Friedman75807f22013-07-20 00:40:58 +00001127 return canThrow(cast<ChooseExpr>(E)->getChosenSubExpr());
Richard Smithf623c962012-04-17 00:58:00 +00001128
1129 case Expr::GenericSelectionExprClass:
1130 if (cast<GenericSelectionExpr>(E)->isResultDependent())
1131 return CT_Dependent;
1132 return canThrow(cast<GenericSelectionExpr>(E)->getResultExpr());
1133
1134 // Some expressions are always dependent.
1135 case Expr::CXXDependentScopeMemberExprClass:
1136 case Expr::CXXUnresolvedConstructExprClass:
1137 case Expr::DependentScopeDeclRefExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00001138 case Expr::CXXFoldExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001139 return CT_Dependent;
1140
1141 case Expr::AsTypeExprClass:
1142 case Expr::BinaryConditionalOperatorClass:
1143 case Expr::BlockExprClass:
1144 case Expr::CUDAKernelCallExprClass:
1145 case Expr::DeclRefExprClass:
1146 case Expr::ObjCBridgedCastExprClass:
1147 case Expr::ObjCIndirectCopyRestoreExprClass:
1148 case Expr::ObjCProtocolExprClass:
1149 case Expr::ObjCSelectorExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00001150 case Expr::ObjCAvailabilityCheckExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001151 case Expr::OffsetOfExprClass:
1152 case Expr::PackExpansionExprClass:
1153 case Expr::PseudoObjectExprClass:
1154 case Expr::SubstNonTypeTemplateParmExprClass:
1155 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00001156 case Expr::FunctionParmPackExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001157 case Expr::UnaryExprOrTypeTraitExprClass:
1158 case Expr::UnresolvedLookupExprClass:
1159 case Expr::UnresolvedMemberExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00001160 case Expr::TypoExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001161 // FIXME: Can any of the above throw? If so, when?
1162 return CT_Cannot;
1163
1164 case Expr::AddrLabelExprClass:
1165 case Expr::ArrayTypeTraitExprClass:
1166 case Expr::AtomicExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001167 case Expr::TypeTraitExprClass:
1168 case Expr::CXXBoolLiteralExprClass:
1169 case Expr::CXXNoexceptExprClass:
1170 case Expr::CXXNullPtrLiteralExprClass:
1171 case Expr::CXXPseudoDestructorExprClass:
1172 case Expr::CXXScalarValueInitExprClass:
1173 case Expr::CXXThisExprClass:
1174 case Expr::CXXUuidofExprClass:
1175 case Expr::CharacterLiteralClass:
1176 case Expr::ExpressionTraitExprClass:
1177 case Expr::FloatingLiteralClass:
1178 case Expr::GNUNullExprClass:
1179 case Expr::ImaginaryLiteralClass:
1180 case Expr::ImplicitValueInitExprClass:
1181 case Expr::IntegerLiteralClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00001182 case Expr::NoInitExprClass:
Richard Smithf623c962012-04-17 00:58:00 +00001183 case Expr::ObjCEncodeExprClass:
1184 case Expr::ObjCStringLiteralClass:
1185 case Expr::ObjCBoolLiteralExprClass:
1186 case Expr::OpaqueValueExprClass:
1187 case Expr::PredefinedExprClass:
1188 case Expr::SizeOfPackExprClass:
1189 case Expr::StringLiteralClass:
Richard Smithf623c962012-04-17 00:58:00 +00001190 // These expressions can never throw.
1191 return CT_Cannot;
1192
John McCall5e77d762013-04-16 07:28:30 +00001193 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00001194 case Expr::MSPropertySubscriptExprClass:
John McCall5e77d762013-04-16 07:28:30 +00001195 llvm_unreachable("Invalid class for expression");
1196
Richard Smithf623c962012-04-17 00:58:00 +00001197#define STMT(CLASS, PARENT) case Expr::CLASS##Class:
1198#define STMT_RANGE(Base, First, Last)
1199#define LAST_STMT_RANGE(BASE, FIRST, LAST)
1200#define EXPR(CLASS, PARENT)
1201#define ABSTRACT_STMT(STMT)
1202#include "clang/AST/StmtNodes.inc"
1203 case Expr::NoStmtClass:
1204 llvm_unreachable("Invalid class for expression");
1205 }
1206 llvm_unreachable("Bogus StmtClass");
1207}
1208
Sebastian Redl4915e632009-10-11 09:03:14 +00001209} // end namespace clang