blob: 937b5771efa827933330149a7d471ba4740b31ec [file] [log] [blame]
Sebastian Redldced2262009-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 McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Sebastian Redldced2262009-10-11 09:03:14 +000015#include "clang/AST/CXXInheritance.h"
16#include "clang/AST/Expr.h"
17#include "clang/AST/ExprCXX.h"
Douglas Gregor2eef8292010-03-24 07:14:45 +000018#include "clang/AST/TypeLoc.h"
Douglas Gregore13ad832010-02-12 07:32:17 +000019#include "clang/Basic/Diagnostic.h"
20#include "clang/Basic/SourceManager.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000021#include "clang/Lex/Preprocessor.h"
Sebastian Redldced2262009-10-11 09:03:14 +000022#include "llvm/ADT/SmallPtrSet.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000023#include "llvm/ADT/SmallString.h"
Sebastian Redldced2262009-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 Redlc3a3b7b2009-10-14 14:38:54 +000033 else if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
34 T = MPTy->getPointeeType();
Sebastian Redldced2262009-10-11 09:03:14 +000035 return T->getAs<FunctionProtoType>();
36}
37
38/// CheckSpecifiedExceptionType - Check if the given type is valid in an
39/// exception specification. Incomplete types, or pointers to incomplete types
40/// other than void are not allowed.
Richard Smith21173b12012-11-28 22:33:28 +000041///
42/// \param[in,out] T The exception type. This will be decayed to a pointer type
43/// when the input is an array or a function type.
44bool Sema::CheckSpecifiedExceptionType(QualType &T, const SourceRange &Range) {
Richard Smitha70c3f82012-11-28 22:52:42 +000045 // C++11 [except.spec]p2:
46 // A type cv T, "array of T", or "function returning T" denoted
Richard Smith21173b12012-11-28 22:33:28 +000047 // in an exception-specification is adjusted to type T, "pointer to T", or
48 // "pointer to function returning T", respectively.
Richard Smitha70c3f82012-11-28 22:52:42 +000049 //
50 // We also apply this rule in C++98.
Richard Smith21173b12012-11-28 22:33:28 +000051 if (T->isArrayType())
52 T = Context.getArrayDecayedType(T);
53 else if (T->isFunctionType())
54 T = Context.getPointerType(T);
Sebastian Redldced2262009-10-11 09:03:14 +000055
Richard Smitha70c3f82012-11-28 22:52:42 +000056 int Kind = 0;
Richard Smith21173b12012-11-28 22:33:28 +000057 QualType PointeeT = T;
Richard Smitha70c3f82012-11-28 22:52:42 +000058 if (const PointerType *PT = T->getAs<PointerType>()) {
59 PointeeT = PT->getPointeeType();
60 Kind = 1;
Sebastian Redldced2262009-10-11 09:03:14 +000061
Richard Smitha70c3f82012-11-28 22:52:42 +000062 // cv void* is explicitly permitted, despite being a pointer to an
63 // incomplete type.
64 if (PointeeT->isVoidType())
65 return false;
66 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
67 PointeeT = RT->getPointeeType();
68 Kind = 2;
Richard Smith21173b12012-11-28 22:33:28 +000069
Richard Smitha70c3f82012-11-28 22:52:42 +000070 if (RT->isRValueReferenceType()) {
71 // C++11 [except.spec]p2:
72 // A type denoted in an exception-specification shall not denote [...]
73 // an rvalue reference type.
74 Diag(Range.getBegin(), diag::err_rref_in_exception_spec)
75 << T << Range;
76 return true;
77 }
78 }
79
80 // C++11 [except.spec]p2:
81 // A type denoted in an exception-specification shall not denote an
82 // incomplete type other than a class currently being defined [...].
83 // A type denoted in an exception-specification shall not denote a
84 // pointer or reference to an incomplete type, other than (cv) void* or a
85 // pointer or reference to a class currently being defined.
86 if (!(PointeeT->isRecordType() &&
87 PointeeT->getAs<RecordType>()->isBeingDefined()) &&
Richard Smith21173b12012-11-28 22:33:28 +000088 RequireCompleteType(Range.getBegin(), PointeeT,
Richard Smitha70c3f82012-11-28 22:52:42 +000089 diag::err_incomplete_in_exception_spec, Kind, Range))
Sebastian Redl491b84c2009-10-14 14:59:48 +000090 return true;
Sebastian Redldced2262009-10-11 09:03:14 +000091
92 return false;
93}
94
95/// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer
96/// to member to a function with an exception specification. This means that
97/// it is invalid to add another level of indirection.
98bool Sema::CheckDistantExceptionSpec(QualType T) {
99 if (const PointerType *PT = T->getAs<PointerType>())
100 T = PT->getPointeeType();
101 else if (const MemberPointerType *PT = T->getAs<MemberPointerType>())
102 T = PT->getPointeeType();
103 else
104 return false;
105
106 const FunctionProtoType *FnT = T->getAs<FunctionProtoType>();
107 if (!FnT)
108 return false;
109
110 return FnT->hasExceptionSpec();
111}
112
Richard Smithe6975e92012-04-17 00:58:00 +0000113const FunctionProtoType *
114Sema::ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000115 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
Richard Smithe6975e92012-04-17 00:58:00 +0000116 return FPT;
117
118 FunctionDecl *SourceDecl = FPT->getExceptionSpecDecl();
119 const FunctionProtoType *SourceFPT =
120 SourceDecl->getType()->castAs<FunctionProtoType>();
121
Richard Smithb9d0b762012-07-27 04:22:15 +0000122 // If the exception specification has already been resolved, just return it.
123 if (!isUnresolvedExceptionSpec(SourceFPT->getExceptionSpecType()))
Richard Smithe6975e92012-04-17 00:58:00 +0000124 return SourceFPT;
125
Richard Smithb9d0b762012-07-27 04:22:15 +0000126 // Compute or instantiate the exception specification now.
127 if (FPT->getExceptionSpecType() == EST_Unevaluated)
128 EvaluateImplicitExceptionSpec(Loc, cast<CXXMethodDecl>(SourceDecl));
129 else
130 InstantiateExceptionSpec(Loc, SourceDecl);
Richard Smithe6975e92012-04-17 00:58:00 +0000131
132 return SourceDecl->getType()->castAs<FunctionProtoType>();
133}
134
Richard Smith444d3842012-10-20 08:26:51 +0000135/// Determine whether a function has an implicitly-generated exception
Richard Smith708f69b2012-10-16 23:30:16 +0000136/// specification.
Richard Smith444d3842012-10-20 08:26:51 +0000137static bool hasImplicitExceptionSpec(FunctionDecl *Decl) {
138 if (!isa<CXXDestructorDecl>(Decl) &&
139 Decl->getDeclName().getCXXOverloadedOperator() != OO_Delete &&
140 Decl->getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
141 return false;
Richard Smith708f69b2012-10-16 23:30:16 +0000142
Richard Smith444d3842012-10-20 08:26:51 +0000143 // If the user didn't declare the function, its exception specification must
144 // be implicit.
145 if (!Decl->getTypeSourceInfo())
146 return true;
147
148 const FunctionProtoType *Ty =
149 Decl->getTypeSourceInfo()->getType()->getAs<FunctionProtoType>();
150 return !Ty->hasExceptionSpec();
Richard Smith708f69b2012-10-16 23:30:16 +0000151}
152
Douglas Gregore13ad832010-02-12 07:32:17 +0000153bool Sema::CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New) {
Sebastian Redl99439d42011-03-15 19:52:30 +0000154 OverloadedOperatorKind OO = New->getDeclName().getCXXOverloadedOperator();
155 bool IsOperatorNew = OO == OO_New || OO == OO_Array_New;
Douglas Gregor2eef8292010-03-24 07:14:45 +0000156 bool MissingExceptionSpecification = false;
Douglas Gregore13ad832010-02-12 07:32:17 +0000157 bool MissingEmptyExceptionSpecification = false;
Francois Picheteedd4672011-03-19 23:05:18 +0000158 unsigned DiagID = diag::err_mismatched_exception_spec;
David Blaikie4e4d0842012-03-11 07:00:24 +0000159 if (getLangOpts().MicrosoftExt)
Francois Pichetcf320c62011-04-22 08:25:24 +0000160 DiagID = diag::warn_mismatched_exception_spec;
Richard Smithe6975e92012-04-17 00:58:00 +0000161
Richard Smith708f69b2012-10-16 23:30:16 +0000162 // Check the types as written: they must match before any exception
163 // specification adjustment is applied.
164 if (!CheckEquivalentExceptionSpec(
165 PDiag(DiagID), PDiag(diag::note_previous_declaration),
Richard Smith444d3842012-10-20 08:26:51 +0000166 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
167 New->getType()->getAs<FunctionProtoType>(), New->getLocation(),
Richard Smith708f69b2012-10-16 23:30:16 +0000168 &MissingExceptionSpecification, &MissingEmptyExceptionSpecification,
Richard Smith444d3842012-10-20 08:26:51 +0000169 /*AllowNoexceptAllMatchWithNoSpec=*/true, IsOperatorNew)) {
170 // C++11 [except.spec]p4 [DR1492]:
171 // If a declaration of a function has an implicit
172 // exception-specification, other declarations of the function shall
173 // not specify an exception-specification.
Richard Smith80ad52f2013-01-02 11:42:31 +0000174 if (getLangOpts().CPlusPlus11 &&
Richard Smith444d3842012-10-20 08:26:51 +0000175 hasImplicitExceptionSpec(Old) != hasImplicitExceptionSpec(New)) {
176 Diag(New->getLocation(), diag::ext_implicit_exception_spec_mismatch)
177 << hasImplicitExceptionSpec(Old);
178 if (!Old->getLocation().isInvalid())
179 Diag(Old->getLocation(), diag::note_previous_declaration);
180 }
Douglas Gregore13ad832010-02-12 07:32:17 +0000181 return false;
Richard Smith444d3842012-10-20 08:26:51 +0000182 }
Douglas Gregore13ad832010-02-12 07:32:17 +0000183
184 // The failure was something other than an empty exception
185 // specification; return an error.
Douglas Gregor2eef8292010-03-24 07:14:45 +0000186 if (!MissingExceptionSpecification && !MissingEmptyExceptionSpecification)
Douglas Gregore13ad832010-02-12 07:32:17 +0000187 return true;
188
Richard Smith444d3842012-10-20 08:26:51 +0000189 const FunctionProtoType *NewProto =
190 New->getType()->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +0000191
Douglas Gregore13ad832010-02-12 07:32:17 +0000192 // The new function declaration is only missing an empty exception
193 // specification "throw()". If the throw() specification came from a
194 // function in a system header that has C linkage, just add an empty
195 // exception specification to the "new" declaration. This is an
196 // egregious workaround for glibc, which adds throw() specifications
197 // to many libc functions as an optimization. Unfortunately, that
198 // optimization isn't permitted by the C++ standard, so we're forced
199 // to work around it here.
John McCalle23cf432010-12-14 08:05:40 +0000200 if (MissingEmptyExceptionSpecification && NewProto &&
Douglas Gregor2eef8292010-03-24 07:14:45 +0000201 (Old->getLocation().isInvalid() ||
202 Context.getSourceManager().isInSystemHeader(Old->getLocation())) &&
Douglas Gregore13ad832010-02-12 07:32:17 +0000203 Old->isExternC()) {
John McCalle23cf432010-12-14 08:05:40 +0000204 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
Sebastian Redl60618fa2011-03-12 11:50:43 +0000205 EPI.ExceptionSpecType = EST_DynamicNone;
Douglas Gregore13ad832010-02-12 07:32:17 +0000206 QualType NewType = Context.getFunctionType(NewProto->getResultType(),
207 NewProto->arg_type_begin(),
208 NewProto->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +0000209 EPI);
Douglas Gregore13ad832010-02-12 07:32:17 +0000210 New->setType(NewType);
211 return false;
212 }
213
John McCalle23cf432010-12-14 08:05:40 +0000214 if (MissingExceptionSpecification && NewProto) {
Richard Smith444d3842012-10-20 08:26:51 +0000215 const FunctionProtoType *OldProto =
216 Old->getType()->getAs<FunctionProtoType>();
Douglas Gregor2eef8292010-03-24 07:14:45 +0000217
John McCalle23cf432010-12-14 08:05:40 +0000218 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
Sebastian Redl60618fa2011-03-12 11:50:43 +0000219 EPI.ExceptionSpecType = OldProto->getExceptionSpecType();
220 if (EPI.ExceptionSpecType == EST_Dynamic) {
221 EPI.NumExceptions = OldProto->getNumExceptions();
222 EPI.Exceptions = OldProto->exception_begin();
223 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
224 // FIXME: We can't just take the expression from the old prototype. It
225 // likely contains references to the old prototype's parameters.
226 }
John McCalle23cf432010-12-14 08:05:40 +0000227
Douglas Gregor2eef8292010-03-24 07:14:45 +0000228 // Update the type of the function with the appropriate exception
229 // specification.
230 QualType NewType = Context.getFunctionType(NewProto->getResultType(),
231 NewProto->arg_type_begin(),
232 NewProto->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +0000233 EPI);
Douglas Gregor2eef8292010-03-24 07:14:45 +0000234 New->setType(NewType);
235
236 // If exceptions are disabled, suppress the warning about missing
237 // exception specifications for new and delete operators.
David Blaikie4e4d0842012-03-11 07:00:24 +0000238 if (!getLangOpts().CXXExceptions) {
Douglas Gregor2eef8292010-03-24 07:14:45 +0000239 switch (New->getDeclName().getCXXOverloadedOperator()) {
240 case OO_New:
241 case OO_Array_New:
242 case OO_Delete:
243 case OO_Array_Delete:
244 if (New->getDeclContext()->isTranslationUnit())
245 return false;
246 break;
247
248 default:
249 break;
250 }
251 }
252
253 // Warn about the lack of exception specification.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000254 SmallString<128> ExceptionSpecString;
Douglas Gregor2eef8292010-03-24 07:14:45 +0000255 llvm::raw_svector_ostream OS(ExceptionSpecString);
Sebastian Redl60618fa2011-03-12 11:50:43 +0000256 switch (OldProto->getExceptionSpecType()) {
257 case EST_DynamicNone:
258 OS << "throw()";
259 break;
260
261 case EST_Dynamic: {
262 OS << "throw(";
263 bool OnFirstException = true;
264 for (FunctionProtoType::exception_iterator E = OldProto->exception_begin(),
265 EEnd = OldProto->exception_end();
266 E != EEnd;
267 ++E) {
268 if (OnFirstException)
269 OnFirstException = false;
270 else
271 OS << ", ";
272
Douglas Gregor8987b232011-09-27 23:30:47 +0000273 OS << E->getAsString(getPrintingPolicy());
Sebastian Redl60618fa2011-03-12 11:50:43 +0000274 }
275 OS << ")";
276 break;
Douglas Gregor2eef8292010-03-24 07:14:45 +0000277 }
Sebastian Redl60618fa2011-03-12 11:50:43 +0000278
279 case EST_BasicNoexcept:
280 OS << "noexcept";
281 break;
282
283 case EST_ComputedNoexcept:
284 OS << "noexcept(";
Richard Smithd1420c62012-08-16 03:56:14 +0000285 OldProto->getNoexceptExpr()->printPretty(OS, 0, getPrintingPolicy());
Sebastian Redl60618fa2011-03-12 11:50:43 +0000286 OS << ")";
287 break;
288
289 default:
David Blaikieb219cfc2011-09-23 05:06:16 +0000290 llvm_unreachable("This spec type is compatible with none.");
Sebastian Redl60618fa2011-03-12 11:50:43 +0000291 }
Douglas Gregor2eef8292010-03-24 07:14:45 +0000292 OS.flush();
293
Abramo Bagnara796aa442011-03-12 11:17:06 +0000294 SourceLocation FixItLoc;
Douglas Gregor2eef8292010-03-24 07:14:45 +0000295 if (TypeSourceInfo *TSInfo = New->getTypeSourceInfo()) {
Abramo Bagnara723df242010-12-14 22:11:44 +0000296 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor2eef8292010-03-24 07:14:45 +0000297 if (const FunctionTypeLoc *FTLoc = dyn_cast<FunctionTypeLoc>(&TL))
Abramo Bagnara796aa442011-03-12 11:17:06 +0000298 FixItLoc = PP.getLocForEndOfToken(FTLoc->getLocalRangeEnd());
Douglas Gregor2eef8292010-03-24 07:14:45 +0000299 }
300
Abramo Bagnara796aa442011-03-12 11:17:06 +0000301 if (FixItLoc.isInvalid())
Douglas Gregor2eef8292010-03-24 07:14:45 +0000302 Diag(New->getLocation(), diag::warn_missing_exception_specification)
303 << New << OS.str();
304 else {
305 // FIXME: This will get more complicated with C++0x
306 // late-specified return types.
307 Diag(New->getLocation(), diag::warn_missing_exception_specification)
308 << New << OS.str()
Abramo Bagnara796aa442011-03-12 11:17:06 +0000309 << FixItHint::CreateInsertion(FixItLoc, " " + OS.str().str());
Douglas Gregor2eef8292010-03-24 07:14:45 +0000310 }
311
312 if (!Old->getLocation().isInvalid())
313 Diag(Old->getLocation(), diag::note_previous_declaration);
314
315 return false;
316 }
317
Francois Picheteedd4672011-03-19 23:05:18 +0000318 Diag(New->getLocation(), DiagID);
Douglas Gregore13ad832010-02-12 07:32:17 +0000319 Diag(Old->getLocation(), diag::note_previous_declaration);
320 return true;
321}
322
Sebastian Redldced2262009-10-11 09:03:14 +0000323/// CheckEquivalentExceptionSpec - Check if the two types have equivalent
324/// exception specifications. Exception specifications are equivalent if
325/// they allow exactly the same set of exception types. It does not matter how
326/// that is achieved. See C++ [except.spec]p2.
327bool Sema::CheckEquivalentExceptionSpec(
328 const FunctionProtoType *Old, SourceLocation OldLoc,
329 const FunctionProtoType *New, SourceLocation NewLoc) {
Francois Picheteedd4672011-03-19 23:05:18 +0000330 unsigned DiagID = diag::err_mismatched_exception_spec;
David Blaikie4e4d0842012-03-11 07:00:24 +0000331 if (getLangOpts().MicrosoftExt)
Francois Pichetcf320c62011-04-22 08:25:24 +0000332 DiagID = diag::warn_mismatched_exception_spec;
Richard Smith708f69b2012-10-16 23:30:16 +0000333 return CheckEquivalentExceptionSpec(PDiag(DiagID),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000334 PDiag(diag::note_previous_declaration),
Sebastian Redldced2262009-10-11 09:03:14 +0000335 Old, OldLoc, New, NewLoc);
336}
337
Sebastian Redl60618fa2011-03-12 11:50:43 +0000338/// CheckEquivalentExceptionSpec - Check if the two types have compatible
339/// exception specifications. See C++ [except.spec]p3.
Richard Smith444d3842012-10-20 08:26:51 +0000340///
341/// \return \c false if the exception specifications match, \c true if there is
342/// a problem. If \c true is returned, either a diagnostic has already been
343/// produced or \c *MissingExceptionSpecification is set to \c true.
Sebastian Redl60618fa2011-03-12 11:50:43 +0000344bool Sema::CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
Douglas Gregor2eef8292010-03-24 07:14:45 +0000345 const PartialDiagnostic & NoteID,
Sebastian Redl60618fa2011-03-12 11:50:43 +0000346 const FunctionProtoType *Old,
Douglas Gregor2eef8292010-03-24 07:14:45 +0000347 SourceLocation OldLoc,
Sebastian Redl60618fa2011-03-12 11:50:43 +0000348 const FunctionProtoType *New,
Douglas Gregor2eef8292010-03-24 07:14:45 +0000349 SourceLocation NewLoc,
350 bool *MissingExceptionSpecification,
Sebastian Redl60618fa2011-03-12 11:50:43 +0000351 bool*MissingEmptyExceptionSpecification,
Sebastian Redl99439d42011-03-15 19:52:30 +0000352 bool AllowNoexceptAllMatchWithNoSpec,
353 bool IsOperatorNew) {
John McCall811d0be2010-05-28 08:37:35 +0000354 // Just completely ignore this under -fno-exceptions.
David Blaikie4e4d0842012-03-11 07:00:24 +0000355 if (!getLangOpts().CXXExceptions)
John McCall811d0be2010-05-28 08:37:35 +0000356 return false;
357
Douglas Gregor2eef8292010-03-24 07:14:45 +0000358 if (MissingExceptionSpecification)
359 *MissingExceptionSpecification = false;
360
Douglas Gregore13ad832010-02-12 07:32:17 +0000361 if (MissingEmptyExceptionSpecification)
362 *MissingEmptyExceptionSpecification = false;
363
Richard Smithe6975e92012-04-17 00:58:00 +0000364 Old = ResolveExceptionSpec(NewLoc, Old);
365 if (!Old)
366 return false;
367 New = ResolveExceptionSpec(NewLoc, New);
368 if (!New)
369 return false;
370
Sebastian Redl60618fa2011-03-12 11:50:43 +0000371 // C++0x [except.spec]p3: Two exception-specifications are compatible if:
372 // - both are non-throwing, regardless of their form,
373 // - both have the form noexcept(constant-expression) and the constant-
374 // expressions are equivalent,
Sebastian Redl60618fa2011-03-12 11:50:43 +0000375 // - both are dynamic-exception-specifications that have the same set of
376 // adjusted types.
377 //
378 // C++0x [except.spec]p12: An exception-specifcation is non-throwing if it is
379 // of the form throw(), noexcept, or noexcept(constant-expression) where the
380 // constant-expression yields true.
381 //
Sebastian Redl60618fa2011-03-12 11:50:43 +0000382 // C++0x [except.spec]p4: If any declaration of a function has an exception-
383 // specifier that is not a noexcept-specification allowing all exceptions,
384 // all declarations [...] of that function shall have a compatible
385 // exception-specification.
386 //
387 // That last point basically means that noexcept(false) matches no spec.
388 // It's considered when AllowNoexceptAllMatchWithNoSpec is true.
389
390 ExceptionSpecificationType OldEST = Old->getExceptionSpecType();
391 ExceptionSpecificationType NewEST = New->getExceptionSpecType();
392
Richard Smithb9d0b762012-07-27 04:22:15 +0000393 assert(!isUnresolvedExceptionSpec(OldEST) &&
394 !isUnresolvedExceptionSpec(NewEST) &&
Richard Smith7a614d82011-06-11 17:19:42 +0000395 "Shouldn't see unknown exception specifications here");
396
Sebastian Redl60618fa2011-03-12 11:50:43 +0000397 // Shortcut the case where both have no spec.
398 if (OldEST == EST_None && NewEST == EST_None)
399 return false;
400
Sebastian Redl8026f6d2011-03-13 17:09:40 +0000401 FunctionProtoType::NoexceptResult OldNR = Old->getNoexceptSpec(Context);
402 FunctionProtoType::NoexceptResult NewNR = New->getNoexceptSpec(Context);
Sebastian Redl60618fa2011-03-12 11:50:43 +0000403 if (OldNR == FunctionProtoType::NR_BadNoexcept ||
404 NewNR == FunctionProtoType::NR_BadNoexcept)
405 return false;
406
407 // Dependent noexcept specifiers are compatible with each other, but nothing
408 // else.
409 // One noexcept is compatible with another if the argument is the same
410 if (OldNR == NewNR &&
411 OldNR != FunctionProtoType::NR_NoNoexcept &&
412 NewNR != FunctionProtoType::NR_NoNoexcept)
413 return false;
414 if (OldNR != NewNR &&
415 OldNR != FunctionProtoType::NR_NoNoexcept &&
416 NewNR != FunctionProtoType::NR_NoNoexcept) {
417 Diag(NewLoc, DiagID);
418 if (NoteID.getDiagID() != 0)
419 Diag(OldLoc, NoteID);
420 return true;
Douglas Gregor5b6f7692010-08-30 15:04:51 +0000421 }
422
Sebastian Redl60618fa2011-03-12 11:50:43 +0000423 // The MS extension throw(...) is compatible with itself.
424 if (OldEST == EST_MSAny && NewEST == EST_MSAny)
Sebastian Redldced2262009-10-11 09:03:14 +0000425 return false;
Sebastian Redl60618fa2011-03-12 11:50:43 +0000426
427 // It's also compatible with no spec.
428 if ((OldEST == EST_None && NewEST == EST_MSAny) ||
429 (OldEST == EST_MSAny && NewEST == EST_None))
430 return false;
431
432 // It's also compatible with noexcept(false).
433 if (OldEST == EST_MSAny && NewNR == FunctionProtoType::NR_Throw)
434 return false;
435 if (NewEST == EST_MSAny && OldNR == FunctionProtoType::NR_Throw)
436 return false;
437
438 // As described above, noexcept(false) matches no spec only for functions.
439 if (AllowNoexceptAllMatchWithNoSpec) {
440 if (OldEST == EST_None && NewNR == FunctionProtoType::NR_Throw)
441 return false;
442 if (NewEST == EST_None && OldNR == FunctionProtoType::NR_Throw)
443 return false;
444 }
445
446 // Any non-throwing specifications are compatible.
447 bool OldNonThrowing = OldNR == FunctionProtoType::NR_Nothrow ||
448 OldEST == EST_DynamicNone;
449 bool NewNonThrowing = NewNR == FunctionProtoType::NR_Nothrow ||
450 NewEST == EST_DynamicNone;
451 if (OldNonThrowing && NewNonThrowing)
452 return false;
453
Sebastian Redl99439d42011-03-15 19:52:30 +0000454 // As a special compatibility feature, under C++0x we accept no spec and
455 // throw(std::bad_alloc) as equivalent for operator new and operator new[].
456 // This is because the implicit declaration changed, but old code would break.
Richard Smith80ad52f2013-01-02 11:42:31 +0000457 if (getLangOpts().CPlusPlus11 && IsOperatorNew) {
Sebastian Redl99439d42011-03-15 19:52:30 +0000458 const FunctionProtoType *WithExceptions = 0;
459 if (OldEST == EST_None && NewEST == EST_Dynamic)
460 WithExceptions = New;
461 else if (OldEST == EST_Dynamic && NewEST == EST_None)
462 WithExceptions = Old;
463 if (WithExceptions && WithExceptions->getNumExceptions() == 1) {
464 // One has no spec, the other throw(something). If that something is
465 // std::bad_alloc, all conditions are met.
466 QualType Exception = *WithExceptions->exception_begin();
467 if (CXXRecordDecl *ExRecord = Exception->getAsCXXRecordDecl()) {
468 IdentifierInfo* Name = ExRecord->getIdentifier();
469 if (Name && Name->getName() == "bad_alloc") {
470 // It's called bad_alloc, but is it in std?
471 DeclContext* DC = ExRecord->getDeclContext();
Sebastian Redld8f2e8e2011-03-15 20:41:09 +0000472 DC = DC->getEnclosingNamespaceContext();
473 if (NamespaceDecl* NS = dyn_cast<NamespaceDecl>(DC)) {
Sebastian Redl99439d42011-03-15 19:52:30 +0000474 IdentifierInfo* NSName = NS->getIdentifier();
Sebastian Redld8f2e8e2011-03-15 20:41:09 +0000475 DC = DC->getParent();
Sebastian Redl99439d42011-03-15 19:52:30 +0000476 if (NSName && NSName->getName() == "std" &&
Sebastian Redld8f2e8e2011-03-15 20:41:09 +0000477 DC->getEnclosingNamespaceContext()->isTranslationUnit()) {
Sebastian Redl99439d42011-03-15 19:52:30 +0000478 return false;
Sebastian Redld8f2e8e2011-03-15 20:41:09 +0000479 }
Sebastian Redl99439d42011-03-15 19:52:30 +0000480 }
481 }
482 }
483 }
484 }
485
Sebastian Redl60618fa2011-03-12 11:50:43 +0000486 // At this point, the only remaining valid case is two matching dynamic
487 // specifications. We return here unless both specifications are dynamic.
488 if (OldEST != EST_Dynamic || NewEST != EST_Dynamic) {
Douglas Gregor2eef8292010-03-24 07:14:45 +0000489 if (MissingExceptionSpecification && Old->hasExceptionSpec() &&
Douglas Gregore13ad832010-02-12 07:32:17 +0000490 !New->hasExceptionSpec()) {
Douglas Gregor2eef8292010-03-24 07:14:45 +0000491 // The old type has an exception specification of some sort, but
492 // the new type does not.
493 *MissingExceptionSpecification = true;
494
Sebastian Redl60618fa2011-03-12 11:50:43 +0000495 if (MissingEmptyExceptionSpecification && OldNonThrowing) {
496 // The old type has a throw() or noexcept(true) exception specification
497 // and the new type has no exception specification, and the caller asked
Douglas Gregor2eef8292010-03-24 07:14:45 +0000498 // to handle this itself.
499 *MissingEmptyExceptionSpecification = true;
500 }
501
Douglas Gregore13ad832010-02-12 07:32:17 +0000502 return true;
503 }
504
Sebastian Redldced2262009-10-11 09:03:14 +0000505 Diag(NewLoc, DiagID);
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000506 if (NoteID.getDiagID() != 0)
Sebastian Redldced2262009-10-11 09:03:14 +0000507 Diag(OldLoc, NoteID);
508 return true;
509 }
510
Sebastian Redl60618fa2011-03-12 11:50:43 +0000511 assert(OldEST == EST_Dynamic && NewEST == EST_Dynamic &&
512 "Exception compatibility logic error: non-dynamic spec slipped through.");
513
Sebastian Redldced2262009-10-11 09:03:14 +0000514 bool Success = true;
Sebastian Redl60618fa2011-03-12 11:50:43 +0000515 // Both have a dynamic exception spec. Collect the first set, then compare
Sebastian Redldced2262009-10-11 09:03:14 +0000516 // to the second.
Sebastian Redl1219d152009-10-14 15:06:25 +0000517 llvm::SmallPtrSet<CanQualType, 8> OldTypes, NewTypes;
Sebastian Redldced2262009-10-11 09:03:14 +0000518 for (FunctionProtoType::exception_iterator I = Old->exception_begin(),
519 E = Old->exception_end(); I != E; ++I)
Sebastian Redl1219d152009-10-14 15:06:25 +0000520 OldTypes.insert(Context.getCanonicalType(*I).getUnqualifiedType());
Sebastian Redldced2262009-10-11 09:03:14 +0000521
522 for (FunctionProtoType::exception_iterator I = New->exception_begin(),
Sebastian Redl5db4d902009-10-11 09:11:23 +0000523 E = New->exception_end(); I != E && Success; ++I) {
Sebastian Redl1219d152009-10-14 15:06:25 +0000524 CanQualType TypePtr = Context.getCanonicalType(*I).getUnqualifiedType();
Sebastian Redl5db4d902009-10-11 09:11:23 +0000525 if(OldTypes.count(TypePtr))
526 NewTypes.insert(TypePtr);
527 else
528 Success = false;
529 }
Sebastian Redldced2262009-10-11 09:03:14 +0000530
Sebastian Redl5db4d902009-10-11 09:11:23 +0000531 Success = Success && OldTypes.size() == NewTypes.size();
Sebastian Redldced2262009-10-11 09:03:14 +0000532
533 if (Success) {
534 return false;
535 }
536 Diag(NewLoc, DiagID);
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000537 if (NoteID.getDiagID() != 0)
Sebastian Redldced2262009-10-11 09:03:14 +0000538 Diag(OldLoc, NoteID);
539 return true;
540}
541
542/// CheckExceptionSpecSubset - Check whether the second function type's
543/// exception specification is a subset (or equivalent) of the first function
544/// type. This is used by override and pointer assignment checks.
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000545bool Sema::CheckExceptionSpecSubset(
546 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
Sebastian Redldced2262009-10-11 09:03:14 +0000547 const FunctionProtoType *Superset, SourceLocation SuperLoc,
548 const FunctionProtoType *Subset, SourceLocation SubLoc) {
John McCall811d0be2010-05-28 08:37:35 +0000549
550 // Just auto-succeed under -fno-exceptions.
David Blaikie4e4d0842012-03-11 07:00:24 +0000551 if (!getLangOpts().CXXExceptions)
John McCall811d0be2010-05-28 08:37:35 +0000552 return false;
553
Sebastian Redldced2262009-10-11 09:03:14 +0000554 // FIXME: As usual, we could be more specific in our error messages, but
555 // that better waits until we've got types with source locations.
556
557 if (!SubLoc.isValid())
558 SubLoc = SuperLoc;
559
Richard Smithe6975e92012-04-17 00:58:00 +0000560 // Resolve the exception specifications, if needed.
561 Superset = ResolveExceptionSpec(SuperLoc, Superset);
562 if (!Superset)
563 return false;
564 Subset = ResolveExceptionSpec(SubLoc, Subset);
565 if (!Subset)
566 return false;
567
Sebastian Redl60618fa2011-03-12 11:50:43 +0000568 ExceptionSpecificationType SuperEST = Superset->getExceptionSpecType();
569
Sebastian Redldced2262009-10-11 09:03:14 +0000570 // If superset contains everything, we're done.
Sebastian Redl60618fa2011-03-12 11:50:43 +0000571 if (SuperEST == EST_None || SuperEST == EST_MSAny)
Sebastian Redldced2262009-10-11 09:03:14 +0000572 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
573
Sebastian Redl60618fa2011-03-12 11:50:43 +0000574 // If there are dependent noexcept specs, assume everything is fine. Unlike
575 // with the equivalency check, this is safe in this case, because we don't
576 // want to merge declarations. Checks after instantiation will catch any
577 // omissions we make here.
578 // We also shortcut checking if a noexcept expression was bad.
579
Sebastian Redl8026f6d2011-03-13 17:09:40 +0000580 FunctionProtoType::NoexceptResult SuperNR =Superset->getNoexceptSpec(Context);
Sebastian Redl60618fa2011-03-12 11:50:43 +0000581 if (SuperNR == FunctionProtoType::NR_BadNoexcept ||
582 SuperNR == FunctionProtoType::NR_Dependent)
583 return false;
584
585 // Another case of the superset containing everything.
586 if (SuperNR == FunctionProtoType::NR_Throw)
587 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
588
589 ExceptionSpecificationType SubEST = Subset->getExceptionSpecType();
590
Richard Smithb9d0b762012-07-27 04:22:15 +0000591 assert(!isUnresolvedExceptionSpec(SuperEST) &&
592 !isUnresolvedExceptionSpec(SubEST) &&
Richard Smith7a614d82011-06-11 17:19:42 +0000593 "Shouldn't see unknown exception specifications here");
594
Sebastian Redldced2262009-10-11 09:03:14 +0000595 // It does not. If the subset contains everything, we've failed.
Sebastian Redl60618fa2011-03-12 11:50:43 +0000596 if (SubEST == EST_None || SubEST == EST_MSAny) {
Sebastian Redldced2262009-10-11 09:03:14 +0000597 Diag(SubLoc, DiagID);
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000598 if (NoteID.getDiagID() != 0)
Sebastian Redldced2262009-10-11 09:03:14 +0000599 Diag(SuperLoc, NoteID);
600 return true;
601 }
602
Sebastian Redl8026f6d2011-03-13 17:09:40 +0000603 FunctionProtoType::NoexceptResult SubNR = Subset->getNoexceptSpec(Context);
Sebastian Redl60618fa2011-03-12 11:50:43 +0000604 if (SubNR == FunctionProtoType::NR_BadNoexcept ||
605 SubNR == FunctionProtoType::NR_Dependent)
606 return false;
607
608 // Another case of the subset containing everything.
609 if (SubNR == FunctionProtoType::NR_Throw) {
610 Diag(SubLoc, DiagID);
611 if (NoteID.getDiagID() != 0)
612 Diag(SuperLoc, NoteID);
613 return true;
614 }
615
616 // If the subset contains nothing, we're done.
617 if (SubEST == EST_DynamicNone || SubNR == FunctionProtoType::NR_Nothrow)
618 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
619
620 // Otherwise, if the superset contains nothing, we've failed.
621 if (SuperEST == EST_DynamicNone || SuperNR == FunctionProtoType::NR_Nothrow) {
622 Diag(SubLoc, DiagID);
623 if (NoteID.getDiagID() != 0)
624 Diag(SuperLoc, NoteID);
625 return true;
626 }
627
628 assert(SuperEST == EST_Dynamic && SubEST == EST_Dynamic &&
629 "Exception spec subset: non-dynamic case slipped through.");
630
631 // Neither contains everything or nothing. Do a proper comparison.
Sebastian Redldced2262009-10-11 09:03:14 +0000632 for (FunctionProtoType::exception_iterator SubI = Subset->exception_begin(),
633 SubE = Subset->exception_end(); SubI != SubE; ++SubI) {
634 // Take one type from the subset.
635 QualType CanonicalSubT = Context.getCanonicalType(*SubI);
Sebastian Redlc3a3b7b2009-10-14 14:38:54 +0000636 // Unwrap pointers and references so that we can do checks within a class
637 // hierarchy. Don't unwrap member pointers; they don't have hierarchy
638 // conversions on the pointee.
Sebastian Redldced2262009-10-11 09:03:14 +0000639 bool SubIsPointer = false;
640 if (const ReferenceType *RefTy = CanonicalSubT->getAs<ReferenceType>())
641 CanonicalSubT = RefTy->getPointeeType();
642 if (const PointerType *PtrTy = CanonicalSubT->getAs<PointerType>()) {
643 CanonicalSubT = PtrTy->getPointeeType();
644 SubIsPointer = true;
645 }
646 bool SubIsClass = CanonicalSubT->isRecordType();
Douglas Gregora4923eb2009-11-16 21:35:15 +0000647 CanonicalSubT = CanonicalSubT.getLocalUnqualifiedType();
Sebastian Redldced2262009-10-11 09:03:14 +0000648
649 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
650 /*DetectVirtual=*/false);
651
652 bool Contained = false;
653 // Make sure it's in the superset.
654 for (FunctionProtoType::exception_iterator SuperI =
655 Superset->exception_begin(), SuperE = Superset->exception_end();
656 SuperI != SuperE; ++SuperI) {
657 QualType CanonicalSuperT = Context.getCanonicalType(*SuperI);
658 // SubT must be SuperT or derived from it, or pointer or reference to
659 // such types.
660 if (const ReferenceType *RefTy = CanonicalSuperT->getAs<ReferenceType>())
661 CanonicalSuperT = RefTy->getPointeeType();
662 if (SubIsPointer) {
663 if (const PointerType *PtrTy = CanonicalSuperT->getAs<PointerType>())
664 CanonicalSuperT = PtrTy->getPointeeType();
665 else {
666 continue;
667 }
668 }
Douglas Gregora4923eb2009-11-16 21:35:15 +0000669 CanonicalSuperT = CanonicalSuperT.getLocalUnqualifiedType();
Sebastian Redldced2262009-10-11 09:03:14 +0000670 // If the types are the same, move on to the next type in the subset.
671 if (CanonicalSubT == CanonicalSuperT) {
672 Contained = true;
673 break;
674 }
675
676 // Otherwise we need to check the inheritance.
677 if (!SubIsClass || !CanonicalSuperT->isRecordType())
678 continue;
679
680 Paths.clear();
681 if (!IsDerivedFrom(CanonicalSubT, CanonicalSuperT, Paths))
682 continue;
683
Douglas Gregore0d5fe22010-05-21 20:29:55 +0000684 if (Paths.isAmbiguous(Context.getCanonicalType(CanonicalSuperT)))
Sebastian Redldced2262009-10-11 09:03:14 +0000685 continue;
686
John McCall6b2accb2010-02-10 09:31:12 +0000687 // Do this check from a context without privileges.
John McCall58e6f342010-03-16 05:22:47 +0000688 switch (CheckBaseClassAccess(SourceLocation(),
John McCall6b2accb2010-02-10 09:31:12 +0000689 CanonicalSuperT, CanonicalSubT,
690 Paths.front(),
John McCall58e6f342010-03-16 05:22:47 +0000691 /*Diagnostic*/ 0,
John McCall6b2accb2010-02-10 09:31:12 +0000692 /*ForceCheck*/ true,
John McCall58e6f342010-03-16 05:22:47 +0000693 /*ForceUnprivileged*/ true)) {
John McCall6b2accb2010-02-10 09:31:12 +0000694 case AR_accessible: break;
695 case AR_inaccessible: continue;
696 case AR_dependent:
697 llvm_unreachable("access check dependent for unprivileged context");
John McCall6b2accb2010-02-10 09:31:12 +0000698 case AR_delayed:
699 llvm_unreachable("access check delayed in non-declaration");
John McCall6b2accb2010-02-10 09:31:12 +0000700 }
Sebastian Redldced2262009-10-11 09:03:14 +0000701
702 Contained = true;
703 break;
704 }
705 if (!Contained) {
706 Diag(SubLoc, DiagID);
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000707 if (NoteID.getDiagID() != 0)
Sebastian Redldced2262009-10-11 09:03:14 +0000708 Diag(SuperLoc, NoteID);
709 return true;
710 }
711 }
712 // We've run half the gauntlet.
713 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
714}
715
716static bool CheckSpecForTypesEquivalent(Sema &S,
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000717 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
Sebastian Redldced2262009-10-11 09:03:14 +0000718 QualType Target, SourceLocation TargetLoc,
719 QualType Source, SourceLocation SourceLoc)
720{
721 const FunctionProtoType *TFunc = GetUnderlyingFunction(Target);
722 if (!TFunc)
723 return false;
724 const FunctionProtoType *SFunc = GetUnderlyingFunction(Source);
725 if (!SFunc)
726 return false;
727
728 return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc,
729 SFunc, SourceLoc);
730}
731
732/// CheckParamExceptionSpec - Check if the parameter and return types of the
733/// two functions have equivalent exception specs. This is part of the
734/// assignment and override compatibility check. We do not check the parameters
735/// of parameter function pointers recursively, as no sane programmer would
736/// even be able to write such a function type.
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000737bool Sema::CheckParamExceptionSpec(const PartialDiagnostic & NoteID,
Sebastian Redldced2262009-10-11 09:03:14 +0000738 const FunctionProtoType *Target, SourceLocation TargetLoc,
739 const FunctionProtoType *Source, SourceLocation SourceLoc)
740{
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000741 if (CheckSpecForTypesEquivalent(*this,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000742 PDiag(diag::err_deep_exception_specs_differ) << 0,
743 PDiag(),
Sebastian Redldced2262009-10-11 09:03:14 +0000744 Target->getResultType(), TargetLoc,
745 Source->getResultType(), SourceLoc))
746 return true;
747
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000748 // We shouldn't even be testing this unless the arguments are otherwise
Sebastian Redldced2262009-10-11 09:03:14 +0000749 // compatible.
750 assert(Target->getNumArgs() == Source->getNumArgs() &&
751 "Functions have different argument counts.");
752 for (unsigned i = 0, E = Target->getNumArgs(); i != E; ++i) {
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000753 if (CheckSpecForTypesEquivalent(*this,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000754 PDiag(diag::err_deep_exception_specs_differ) << 1,
755 PDiag(),
Sebastian Redldced2262009-10-11 09:03:14 +0000756 Target->getArgType(i), TargetLoc,
757 Source->getArgType(i), SourceLoc))
758 return true;
759 }
760 return false;
761}
762
763bool Sema::CheckExceptionSpecCompatibility(Expr *From, QualType ToType)
764{
765 // First we check for applicability.
766 // Target type must be a function, function pointer or function reference.
767 const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType);
768 if (!ToFunc)
769 return false;
770
771 // SourceType must be a function or function pointer.
772 const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType());
773 if (!FromFunc)
774 return false;
775
776 // Now we've got the correct types on both sides, check their compatibility.
777 // This means that the source of the conversion can only throw a subset of
778 // the exceptions of the target, and any exception specs on arguments or
779 // return types must be equivalent.
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000780 return CheckExceptionSpecSubset(PDiag(diag::err_incompatible_exception_specs),
781 PDiag(), ToFunc,
782 From->getSourceRange().getBegin(),
Sebastian Redldced2262009-10-11 09:03:14 +0000783 FromFunc, SourceLocation());
784}
785
786bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
787 const CXXMethodDecl *Old) {
Richard Smith80ad52f2013-01-02 11:42:31 +0000788 if (getLangOpts().CPlusPlus11 && isa<CXXDestructorDecl>(New)) {
Sebastian Redla0448262011-05-20 05:57:18 +0000789 // Don't check uninstantiated template destructors at all. We can only
790 // synthesize correct specs after the template is instantiated.
791 if (New->getParent()->isDependentType())
792 return false;
793 if (New->getParent()->isBeingDefined()) {
794 // The destructor might be updated once the definition is finished. So
795 // remember it and check later.
796 DelayedDestructorExceptionSpecChecks.push_back(std::make_pair(
797 cast<CXXDestructorDecl>(New), cast<CXXDestructorDecl>(Old)));
798 return false;
799 }
Sebastian Redl0ee33912011-05-19 05:13:44 +0000800 }
Francois Pichet0f161592011-05-24 02:11:43 +0000801 unsigned DiagID = diag::err_override_exception_spec;
David Blaikie4e4d0842012-03-11 07:00:24 +0000802 if (getLangOpts().MicrosoftExt)
Francois Pichet0f161592011-05-24 02:11:43 +0000803 DiagID = diag::warn_override_exception_spec;
804 return CheckExceptionSpecSubset(PDiag(DiagID),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000805 PDiag(diag::note_overridden_virtual_function),
Sebastian Redldced2262009-10-11 09:03:14 +0000806 Old->getType()->getAs<FunctionProtoType>(),
807 Old->getLocation(),
808 New->getType()->getAs<FunctionProtoType>(),
809 New->getLocation());
810}
811
Richard Smithe6975e92012-04-17 00:58:00 +0000812static CanThrowResult canSubExprsThrow(Sema &S, const Expr *CE) {
813 Expr *E = const_cast<Expr*>(CE);
814 CanThrowResult R = CT_Cannot;
815 for (Expr::child_range I = E->children(); I && R != CT_Can; ++I)
816 R = mergeCanThrow(R, S.canThrow(cast<Expr>(*I)));
817 return R;
818}
819
820static CanThrowResult canCalleeThrow(Sema &S, const Expr *E,
821 const Decl *D,
822 bool NullThrows = true) {
823 if (!D)
824 return NullThrows ? CT_Can : CT_Cannot;
825
826 // See if we can get a function type from the decl somehow.
827 const ValueDecl *VD = dyn_cast<ValueDecl>(D);
828 if (!VD) // If we have no clue what we're calling, assume the worst.
829 return CT_Can;
830
831 // As an extension, we assume that __attribute__((nothrow)) functions don't
832 // throw.
833 if (isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())
834 return CT_Cannot;
835
836 QualType T = VD->getType();
837 const FunctionProtoType *FT;
838 if ((FT = T->getAs<FunctionProtoType>())) {
839 } else if (const PointerType *PT = T->getAs<PointerType>())
840 FT = PT->getPointeeType()->getAs<FunctionProtoType>();
841 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
842 FT = RT->getPointeeType()->getAs<FunctionProtoType>();
843 else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
844 FT = MT->getPointeeType()->getAs<FunctionProtoType>();
845 else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
846 FT = BT->getPointeeType()->getAs<FunctionProtoType>();
847
848 if (!FT)
849 return CT_Can;
850
851 FT = S.ResolveExceptionSpec(E->getLocStart(), FT);
852 if (!FT)
853 return CT_Can;
854
Richard Smithe6975e92012-04-17 00:58:00 +0000855 return FT->isNothrow(S.Context) ? CT_Cannot : CT_Can;
856}
857
858static CanThrowResult canDynamicCastThrow(const CXXDynamicCastExpr *DC) {
859 if (DC->isTypeDependent())
860 return CT_Dependent;
861
862 if (!DC->getTypeAsWritten()->isReferenceType())
863 return CT_Cannot;
864
865 if (DC->getSubExpr()->isTypeDependent())
866 return CT_Dependent;
867
868 return DC->getCastKind() == clang::CK_Dynamic? CT_Can : CT_Cannot;
869}
870
871static CanThrowResult canTypeidThrow(Sema &S, const CXXTypeidExpr *DC) {
872 if (DC->isTypeOperand())
873 return CT_Cannot;
874
875 Expr *Op = DC->getExprOperand();
876 if (Op->isTypeDependent())
877 return CT_Dependent;
878
879 const RecordType *RT = Op->getType()->getAs<RecordType>();
880 if (!RT)
881 return CT_Cannot;
882
883 if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
884 return CT_Cannot;
885
886 if (Op->Classify(S.Context).isPRValue())
887 return CT_Cannot;
888
889 return CT_Can;
890}
891
892CanThrowResult Sema::canThrow(const Expr *E) {
893 // C++ [expr.unary.noexcept]p3:
894 // [Can throw] if in a potentially-evaluated context the expression would
895 // contain:
896 switch (E->getStmtClass()) {
897 case Expr::CXXThrowExprClass:
898 // - a potentially evaluated throw-expression
899 return CT_Can;
900
901 case Expr::CXXDynamicCastExprClass: {
902 // - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
903 // where T is a reference type, that requires a run-time check
904 CanThrowResult CT = canDynamicCastThrow(cast<CXXDynamicCastExpr>(E));
905 if (CT == CT_Can)
906 return CT;
907 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
908 }
909
910 case Expr::CXXTypeidExprClass:
911 // - a potentially evaluated typeid expression applied to a glvalue
912 // expression whose type is a polymorphic class type
913 return canTypeidThrow(*this, cast<CXXTypeidExpr>(E));
914
915 // - a potentially evaluated call to a function, member function, function
916 // pointer, or member function pointer that does not have a non-throwing
917 // exception-specification
918 case Expr::CallExprClass:
919 case Expr::CXXMemberCallExprClass:
920 case Expr::CXXOperatorCallExprClass:
921 case Expr::UserDefinedLiteralClass: {
922 const CallExpr *CE = cast<CallExpr>(E);
923 CanThrowResult CT;
924 if (E->isTypeDependent())
925 CT = CT_Dependent;
926 else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens()))
927 CT = CT_Cannot;
928 else
929 CT = canCalleeThrow(*this, E, CE->getCalleeDecl());
930 if (CT == CT_Can)
931 return CT;
932 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
933 }
934
935 case Expr::CXXConstructExprClass:
936 case Expr::CXXTemporaryObjectExprClass: {
937 CanThrowResult CT = canCalleeThrow(*this, E,
938 cast<CXXConstructExpr>(E)->getConstructor());
939 if (CT == CT_Can)
940 return CT;
941 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
942 }
943
944 case Expr::LambdaExprClass: {
945 const LambdaExpr *Lambda = cast<LambdaExpr>(E);
946 CanThrowResult CT = CT_Cannot;
947 for (LambdaExpr::capture_init_iterator Cap = Lambda->capture_init_begin(),
948 CapEnd = Lambda->capture_init_end();
949 Cap != CapEnd; ++Cap)
950 CT = mergeCanThrow(CT, canThrow(*Cap));
951 return CT;
952 }
953
954 case Expr::CXXNewExprClass: {
955 CanThrowResult CT;
956 if (E->isTypeDependent())
957 CT = CT_Dependent;
958 else
959 CT = canCalleeThrow(*this, E, cast<CXXNewExpr>(E)->getOperatorNew());
960 if (CT == CT_Can)
961 return CT;
962 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
963 }
964
965 case Expr::CXXDeleteExprClass: {
966 CanThrowResult CT;
967 QualType DTy = cast<CXXDeleteExpr>(E)->getDestroyedType();
968 if (DTy.isNull() || DTy->isDependentType()) {
969 CT = CT_Dependent;
970 } else {
971 CT = canCalleeThrow(*this, E,
972 cast<CXXDeleteExpr>(E)->getOperatorDelete());
973 if (const RecordType *RT = DTy->getAs<RecordType>()) {
974 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
975 CT = mergeCanThrow(CT, canCalleeThrow(*this, E, RD->getDestructor()));
976 }
977 if (CT == CT_Can)
978 return CT;
979 }
980 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
981 }
982
983 case Expr::CXXBindTemporaryExprClass: {
984 // The bound temporary has to be destroyed again, which might throw.
985 CanThrowResult CT = canCalleeThrow(*this, E,
986 cast<CXXBindTemporaryExpr>(E)->getTemporary()->getDestructor());
987 if (CT == CT_Can)
988 return CT;
989 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
990 }
991
992 // ObjC message sends are like function calls, but never have exception
993 // specs.
994 case Expr::ObjCMessageExprClass:
995 case Expr::ObjCPropertyRefExprClass:
996 case Expr::ObjCSubscriptRefExprClass:
997 return CT_Can;
998
999 // All the ObjC literals that are implemented as calls are
1000 // potentially throwing unless we decide to close off that
1001 // possibility.
1002 case Expr::ObjCArrayLiteralClass:
1003 case Expr::ObjCDictionaryLiteralClass:
Patrick Beardeb382ec2012-04-19 00:25:12 +00001004 case Expr::ObjCBoxedExprClass:
Richard Smithe6975e92012-04-17 00:58:00 +00001005 return CT_Can;
1006
1007 // Many other things have subexpressions, so we have to test those.
1008 // Some are simple:
1009 case Expr::ConditionalOperatorClass:
1010 case Expr::CompoundLiteralExprClass:
1011 case Expr::CXXConstCastExprClass:
1012 case Expr::CXXDefaultArgExprClass:
1013 case Expr::CXXReinterpretCastExprClass:
1014 case Expr::DesignatedInitExprClass:
1015 case Expr::ExprWithCleanupsClass:
1016 case Expr::ExtVectorElementExprClass:
1017 case Expr::InitListExprClass:
1018 case Expr::MemberExprClass:
1019 case Expr::ObjCIsaExprClass:
1020 case Expr::ObjCIvarRefExprClass:
1021 case Expr::ParenExprClass:
1022 case Expr::ParenListExprClass:
1023 case Expr::ShuffleVectorExprClass:
1024 case Expr::VAArgExprClass:
1025 return canSubExprsThrow(*this, E);
1026
1027 // Some might be dependent for other reasons.
1028 case Expr::ArraySubscriptExprClass:
1029 case Expr::BinaryOperatorClass:
1030 case Expr::CompoundAssignOperatorClass:
1031 case Expr::CStyleCastExprClass:
1032 case Expr::CXXStaticCastExprClass:
1033 case Expr::CXXFunctionalCastExprClass:
1034 case Expr::ImplicitCastExprClass:
1035 case Expr::MaterializeTemporaryExprClass:
1036 case Expr::UnaryOperatorClass: {
1037 CanThrowResult CT = E->isTypeDependent() ? CT_Dependent : CT_Cannot;
1038 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1039 }
1040
1041 // FIXME: We should handle StmtExpr, but that opens a MASSIVE can of worms.
1042 case Expr::StmtExprClass:
1043 return CT_Can;
1044
1045 case Expr::ChooseExprClass:
1046 if (E->isTypeDependent() || E->isValueDependent())
1047 return CT_Dependent;
1048 return canThrow(cast<ChooseExpr>(E)->getChosenSubExpr(Context));
1049
1050 case Expr::GenericSelectionExprClass:
1051 if (cast<GenericSelectionExpr>(E)->isResultDependent())
1052 return CT_Dependent;
1053 return canThrow(cast<GenericSelectionExpr>(E)->getResultExpr());
1054
1055 // Some expressions are always dependent.
1056 case Expr::CXXDependentScopeMemberExprClass:
1057 case Expr::CXXUnresolvedConstructExprClass:
1058 case Expr::DependentScopeDeclRefExprClass:
1059 return CT_Dependent;
1060
1061 case Expr::AsTypeExprClass:
1062 case Expr::BinaryConditionalOperatorClass:
1063 case Expr::BlockExprClass:
1064 case Expr::CUDAKernelCallExprClass:
1065 case Expr::DeclRefExprClass:
1066 case Expr::ObjCBridgedCastExprClass:
1067 case Expr::ObjCIndirectCopyRestoreExprClass:
1068 case Expr::ObjCProtocolExprClass:
1069 case Expr::ObjCSelectorExprClass:
1070 case Expr::OffsetOfExprClass:
1071 case Expr::PackExpansionExprClass:
1072 case Expr::PseudoObjectExprClass:
1073 case Expr::SubstNonTypeTemplateParmExprClass:
1074 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smith9a4db032012-09-12 00:56:43 +00001075 case Expr::FunctionParmPackExprClass:
Richard Smithe6975e92012-04-17 00:58:00 +00001076 case Expr::UnaryExprOrTypeTraitExprClass:
1077 case Expr::UnresolvedLookupExprClass:
1078 case Expr::UnresolvedMemberExprClass:
1079 // FIXME: Can any of the above throw? If so, when?
1080 return CT_Cannot;
1081
1082 case Expr::AddrLabelExprClass:
1083 case Expr::ArrayTypeTraitExprClass:
1084 case Expr::AtomicExprClass:
1085 case Expr::BinaryTypeTraitExprClass:
1086 case Expr::TypeTraitExprClass:
1087 case Expr::CXXBoolLiteralExprClass:
1088 case Expr::CXXNoexceptExprClass:
1089 case Expr::CXXNullPtrLiteralExprClass:
1090 case Expr::CXXPseudoDestructorExprClass:
1091 case Expr::CXXScalarValueInitExprClass:
1092 case Expr::CXXThisExprClass:
1093 case Expr::CXXUuidofExprClass:
1094 case Expr::CharacterLiteralClass:
1095 case Expr::ExpressionTraitExprClass:
1096 case Expr::FloatingLiteralClass:
1097 case Expr::GNUNullExprClass:
1098 case Expr::ImaginaryLiteralClass:
1099 case Expr::ImplicitValueInitExprClass:
1100 case Expr::IntegerLiteralClass:
1101 case Expr::ObjCEncodeExprClass:
1102 case Expr::ObjCStringLiteralClass:
1103 case Expr::ObjCBoolLiteralExprClass:
1104 case Expr::OpaqueValueExprClass:
1105 case Expr::PredefinedExprClass:
1106 case Expr::SizeOfPackExprClass:
1107 case Expr::StringLiteralClass:
1108 case Expr::UnaryTypeTraitExprClass:
1109 // These expressions can never throw.
1110 return CT_Cannot;
1111
1112#define STMT(CLASS, PARENT) case Expr::CLASS##Class:
1113#define STMT_RANGE(Base, First, Last)
1114#define LAST_STMT_RANGE(BASE, FIRST, LAST)
1115#define EXPR(CLASS, PARENT)
1116#define ABSTRACT_STMT(STMT)
1117#include "clang/AST/StmtNodes.inc"
1118 case Expr::NoStmtClass:
1119 llvm_unreachable("Invalid class for expression");
1120 }
1121 llvm_unreachable("Bogus StmtClass");
1122}
1123
Sebastian Redldced2262009-10-11 09:03:14 +00001124} // end namespace clang