blob: e35badc9f3e6a06f87c4cd44f9fed31d0ba6ec6e [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"
19#include "clang/Lex/Preprocessor.h"
Douglas Gregore13ad832010-02-12 07:32:17 +000020#include "clang/Basic/Diagnostic.h"
21#include "clang/Basic/SourceManager.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.
41bool Sema::CheckSpecifiedExceptionType(QualType T, const SourceRange &Range) {
Sebastian Redldced2262009-10-11 09:03:14 +000042
Douglas Gregor0966f352009-12-10 18:13:52 +000043 // This check (and the similar one below) deals with issue 437, that changes
44 // C++ 9.2p2 this way:
45 // Within the class member-specification, the class is regarded as complete
46 // within function bodies, default arguments, exception-specifications, and
47 // constructor ctor-initializers (including such things in nested classes).
48 if (T->isRecordType() && T->getAs<RecordType>()->isBeingDefined())
49 return false;
50
Sebastian Redldced2262009-10-11 09:03:14 +000051 // C++ 15.4p2: A type denoted in an exception-specification shall not denote
52 // an incomplete type.
Sebastian Redl491b84c2009-10-14 14:59:48 +000053 if (RequireCompleteType(Range.getBegin(), T,
Douglas Gregord10099e2012-05-04 16:32:21 +000054 diag::err_incomplete_in_exception_spec,
55 /*direct*/0, Range))
Sebastian Redl491b84c2009-10-14 14:59:48 +000056 return true;
Sebastian Redldced2262009-10-11 09:03:14 +000057
58 // C++ 15.4p2: A type denoted in an exception-specification shall not denote
59 // an incomplete type a pointer or reference to an incomplete type, other
60 // than (cv) void*.
61 int kind;
62 if (const PointerType* IT = T->getAs<PointerType>()) {
63 T = IT->getPointeeType();
64 kind = 1;
65 } else if (const ReferenceType* IT = T->getAs<ReferenceType>()) {
66 T = IT->getPointeeType();
67 kind = 2;
68 } else
69 return false;
70
Douglas Gregor0966f352009-12-10 18:13:52 +000071 // Again as before
72 if (T->isRecordType() && T->getAs<RecordType>()->isBeingDefined())
73 return false;
74
Douglas Gregord10099e2012-05-04 16:32:21 +000075 if (!T->isVoidType() &&
76 RequireCompleteType(Range.getBegin(), T,
77 diag::err_incomplete_in_exception_spec, kind, Range))
Sebastian Redl491b84c2009-10-14 14:59:48 +000078 return true;
Sebastian Redldced2262009-10-11 09:03:14 +000079
80 return false;
81}
82
83/// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer
84/// to member to a function with an exception specification. This means that
85/// it is invalid to add another level of indirection.
86bool Sema::CheckDistantExceptionSpec(QualType T) {
87 if (const PointerType *PT = T->getAs<PointerType>())
88 T = PT->getPointeeType();
89 else if (const MemberPointerType *PT = T->getAs<MemberPointerType>())
90 T = PT->getPointeeType();
91 else
92 return false;
93
94 const FunctionProtoType *FnT = T->getAs<FunctionProtoType>();
95 if (!FnT)
96 return false;
97
98 return FnT->hasExceptionSpec();
99}
100
Richard Smithe6975e92012-04-17 00:58:00 +0000101const FunctionProtoType *
102Sema::ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000103 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
Richard Smithe6975e92012-04-17 00:58:00 +0000104 return FPT;
105
106 FunctionDecl *SourceDecl = FPT->getExceptionSpecDecl();
107 const FunctionProtoType *SourceFPT =
108 SourceDecl->getType()->castAs<FunctionProtoType>();
109
Richard Smithb9d0b762012-07-27 04:22:15 +0000110 // If the exception specification has already been resolved, just return it.
111 if (!isUnresolvedExceptionSpec(SourceFPT->getExceptionSpecType()))
Richard Smithe6975e92012-04-17 00:58:00 +0000112 return SourceFPT;
113
Richard Smithb9d0b762012-07-27 04:22:15 +0000114 // Compute or instantiate the exception specification now.
115 if (FPT->getExceptionSpecType() == EST_Unevaluated)
116 EvaluateImplicitExceptionSpec(Loc, cast<CXXMethodDecl>(SourceDecl));
117 else
118 InstantiateExceptionSpec(Loc, SourceDecl);
Richard Smithe6975e92012-04-17 00:58:00 +0000119
120 return SourceDecl->getType()->castAs<FunctionProtoType>();
121}
122
Richard Smith708f69b2012-10-16 23:30:16 +0000123/// Get the type that a function had prior to adjustment of the exception
124/// specification.
125static const FunctionProtoType *getUnadjustedFunctionType(FunctionDecl *Decl) {
126 if (isa<CXXDestructorDecl>(Decl) && Decl->getTypeSourceInfo()) {
127 const FunctionProtoType *Ty =
128 Decl->getTypeSourceInfo()->getType()->getAs<FunctionProtoType>();
129 if (!Ty->hasExceptionSpec())
130 // The type will be adjusted. Use the EST_None exception specification
131 // from the type as written.
132 return Ty;
133 }
134
135 // Use whatever type the function now has. The TypeSourceInfo does not contain
136 // an instantiated exception specification for a function template,
137 return Decl->getType()->getAs<FunctionProtoType>();
138}
139
Douglas Gregore13ad832010-02-12 07:32:17 +0000140bool Sema::CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New) {
Sebastian Redl99439d42011-03-15 19:52:30 +0000141 OverloadedOperatorKind OO = New->getDeclName().getCXXOverloadedOperator();
142 bool IsOperatorNew = OO == OO_New || OO == OO_Array_New;
Douglas Gregor2eef8292010-03-24 07:14:45 +0000143 bool MissingExceptionSpecification = false;
Douglas Gregore13ad832010-02-12 07:32:17 +0000144 bool MissingEmptyExceptionSpecification = false;
Francois Picheteedd4672011-03-19 23:05:18 +0000145 unsigned DiagID = diag::err_mismatched_exception_spec;
David Blaikie4e4d0842012-03-11 07:00:24 +0000146 if (getLangOpts().MicrosoftExt)
Francois Pichetcf320c62011-04-22 08:25:24 +0000147 DiagID = diag::warn_mismatched_exception_spec;
Richard Smithe6975e92012-04-17 00:58:00 +0000148
Richard Smith708f69b2012-10-16 23:30:16 +0000149 // Check the types as written: they must match before any exception
150 // specification adjustment is applied.
151 if (!CheckEquivalentExceptionSpec(
152 PDiag(DiagID), PDiag(diag::note_previous_declaration),
153 getUnadjustedFunctionType(Old), Old->getLocation(),
154 getUnadjustedFunctionType(New), New->getLocation(),
155 &MissingExceptionSpecification, &MissingEmptyExceptionSpecification,
156 /*AllowNoexceptAllMatchWithNoSpec=*/true, IsOperatorNew))
Douglas Gregore13ad832010-02-12 07:32:17 +0000157 return false;
158
159 // The failure was something other than an empty exception
160 // specification; return an error.
Douglas Gregor2eef8292010-03-24 07:14:45 +0000161 if (!MissingExceptionSpecification && !MissingEmptyExceptionSpecification)
Douglas Gregore13ad832010-02-12 07:32:17 +0000162 return true;
163
Richard Smith708f69b2012-10-16 23:30:16 +0000164 const FunctionProtoType *NewProto = getUnadjustedFunctionType(New);
John McCalle23cf432010-12-14 08:05:40 +0000165
Douglas Gregore13ad832010-02-12 07:32:17 +0000166 // The new function declaration is only missing an empty exception
167 // specification "throw()". If the throw() specification came from a
168 // function in a system header that has C linkage, just add an empty
169 // exception specification to the "new" declaration. This is an
170 // egregious workaround for glibc, which adds throw() specifications
171 // to many libc functions as an optimization. Unfortunately, that
172 // optimization isn't permitted by the C++ standard, so we're forced
173 // to work around it here.
John McCalle23cf432010-12-14 08:05:40 +0000174 if (MissingEmptyExceptionSpecification && NewProto &&
Douglas Gregor2eef8292010-03-24 07:14:45 +0000175 (Old->getLocation().isInvalid() ||
176 Context.getSourceManager().isInSystemHeader(Old->getLocation())) &&
Douglas Gregore13ad832010-02-12 07:32:17 +0000177 Old->isExternC()) {
John McCalle23cf432010-12-14 08:05:40 +0000178 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
Sebastian Redl60618fa2011-03-12 11:50:43 +0000179 EPI.ExceptionSpecType = EST_DynamicNone;
Douglas Gregore13ad832010-02-12 07:32:17 +0000180 QualType NewType = Context.getFunctionType(NewProto->getResultType(),
181 NewProto->arg_type_begin(),
182 NewProto->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +0000183 EPI);
Douglas Gregore13ad832010-02-12 07:32:17 +0000184 New->setType(NewType);
185 return false;
186 }
187
John McCalle23cf432010-12-14 08:05:40 +0000188 if (MissingExceptionSpecification && NewProto) {
Richard Smith708f69b2012-10-16 23:30:16 +0000189 const FunctionProtoType *OldProto = getUnadjustedFunctionType(Old);
Douglas Gregor2eef8292010-03-24 07:14:45 +0000190
John McCalle23cf432010-12-14 08:05:40 +0000191 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
Sebastian Redl60618fa2011-03-12 11:50:43 +0000192 EPI.ExceptionSpecType = OldProto->getExceptionSpecType();
193 if (EPI.ExceptionSpecType == EST_Dynamic) {
194 EPI.NumExceptions = OldProto->getNumExceptions();
195 EPI.Exceptions = OldProto->exception_begin();
196 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
197 // FIXME: We can't just take the expression from the old prototype. It
198 // likely contains references to the old prototype's parameters.
199 }
John McCalle23cf432010-12-14 08:05:40 +0000200
Douglas Gregor2eef8292010-03-24 07:14:45 +0000201 // Update the type of the function with the appropriate exception
202 // specification.
203 QualType NewType = Context.getFunctionType(NewProto->getResultType(),
204 NewProto->arg_type_begin(),
205 NewProto->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +0000206 EPI);
Douglas Gregor2eef8292010-03-24 07:14:45 +0000207 New->setType(NewType);
208
209 // If exceptions are disabled, suppress the warning about missing
210 // exception specifications for new and delete operators.
David Blaikie4e4d0842012-03-11 07:00:24 +0000211 if (!getLangOpts().CXXExceptions) {
Douglas Gregor2eef8292010-03-24 07:14:45 +0000212 switch (New->getDeclName().getCXXOverloadedOperator()) {
213 case OO_New:
214 case OO_Array_New:
215 case OO_Delete:
216 case OO_Array_Delete:
217 if (New->getDeclContext()->isTranslationUnit())
218 return false;
219 break;
220
221 default:
222 break;
223 }
224 }
225
226 // Warn about the lack of exception specification.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000227 SmallString<128> ExceptionSpecString;
Douglas Gregor2eef8292010-03-24 07:14:45 +0000228 llvm::raw_svector_ostream OS(ExceptionSpecString);
Sebastian Redl60618fa2011-03-12 11:50:43 +0000229 switch (OldProto->getExceptionSpecType()) {
230 case EST_DynamicNone:
231 OS << "throw()";
232 break;
233
234 case EST_Dynamic: {
235 OS << "throw(";
236 bool OnFirstException = true;
237 for (FunctionProtoType::exception_iterator E = OldProto->exception_begin(),
238 EEnd = OldProto->exception_end();
239 E != EEnd;
240 ++E) {
241 if (OnFirstException)
242 OnFirstException = false;
243 else
244 OS << ", ";
245
Douglas Gregor8987b232011-09-27 23:30:47 +0000246 OS << E->getAsString(getPrintingPolicy());
Sebastian Redl60618fa2011-03-12 11:50:43 +0000247 }
248 OS << ")";
249 break;
Douglas Gregor2eef8292010-03-24 07:14:45 +0000250 }
Sebastian Redl60618fa2011-03-12 11:50:43 +0000251
252 case EST_BasicNoexcept:
253 OS << "noexcept";
254 break;
255
256 case EST_ComputedNoexcept:
257 OS << "noexcept(";
Richard Smithd1420c62012-08-16 03:56:14 +0000258 OldProto->getNoexceptExpr()->printPretty(OS, 0, getPrintingPolicy());
Sebastian Redl60618fa2011-03-12 11:50:43 +0000259 OS << ")";
260 break;
261
262 default:
David Blaikieb219cfc2011-09-23 05:06:16 +0000263 llvm_unreachable("This spec type is compatible with none.");
Sebastian Redl60618fa2011-03-12 11:50:43 +0000264 }
Douglas Gregor2eef8292010-03-24 07:14:45 +0000265 OS.flush();
266
Abramo Bagnara796aa442011-03-12 11:17:06 +0000267 SourceLocation FixItLoc;
Douglas Gregor2eef8292010-03-24 07:14:45 +0000268 if (TypeSourceInfo *TSInfo = New->getTypeSourceInfo()) {
Abramo Bagnara723df242010-12-14 22:11:44 +0000269 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor2eef8292010-03-24 07:14:45 +0000270 if (const FunctionTypeLoc *FTLoc = dyn_cast<FunctionTypeLoc>(&TL))
Abramo Bagnara796aa442011-03-12 11:17:06 +0000271 FixItLoc = PP.getLocForEndOfToken(FTLoc->getLocalRangeEnd());
Douglas Gregor2eef8292010-03-24 07:14:45 +0000272 }
273
Abramo Bagnara796aa442011-03-12 11:17:06 +0000274 if (FixItLoc.isInvalid())
Douglas Gregor2eef8292010-03-24 07:14:45 +0000275 Diag(New->getLocation(), diag::warn_missing_exception_specification)
276 << New << OS.str();
277 else {
278 // FIXME: This will get more complicated with C++0x
279 // late-specified return types.
280 Diag(New->getLocation(), diag::warn_missing_exception_specification)
281 << New << OS.str()
Abramo Bagnara796aa442011-03-12 11:17:06 +0000282 << FixItHint::CreateInsertion(FixItLoc, " " + OS.str().str());
Douglas Gregor2eef8292010-03-24 07:14:45 +0000283 }
284
285 if (!Old->getLocation().isInvalid())
286 Diag(Old->getLocation(), diag::note_previous_declaration);
287
288 return false;
289 }
290
Francois Picheteedd4672011-03-19 23:05:18 +0000291 Diag(New->getLocation(), DiagID);
Douglas Gregore13ad832010-02-12 07:32:17 +0000292 Diag(Old->getLocation(), diag::note_previous_declaration);
293 return true;
294}
295
Sebastian Redldced2262009-10-11 09:03:14 +0000296/// CheckEquivalentExceptionSpec - Check if the two types have equivalent
297/// exception specifications. Exception specifications are equivalent if
298/// they allow exactly the same set of exception types. It does not matter how
299/// that is achieved. See C++ [except.spec]p2.
300bool Sema::CheckEquivalentExceptionSpec(
301 const FunctionProtoType *Old, SourceLocation OldLoc,
302 const FunctionProtoType *New, SourceLocation NewLoc) {
Francois Picheteedd4672011-03-19 23:05:18 +0000303 unsigned DiagID = diag::err_mismatched_exception_spec;
David Blaikie4e4d0842012-03-11 07:00:24 +0000304 if (getLangOpts().MicrosoftExt)
Francois Pichetcf320c62011-04-22 08:25:24 +0000305 DiagID = diag::warn_mismatched_exception_spec;
Richard Smith708f69b2012-10-16 23:30:16 +0000306 return CheckEquivalentExceptionSpec(PDiag(DiagID),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000307 PDiag(diag::note_previous_declaration),
Sebastian Redldced2262009-10-11 09:03:14 +0000308 Old, OldLoc, New, NewLoc);
309}
310
Sebastian Redl60618fa2011-03-12 11:50:43 +0000311/// CheckEquivalentExceptionSpec - Check if the two types have compatible
312/// exception specifications. See C++ [except.spec]p3.
313bool Sema::CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
Douglas Gregor2eef8292010-03-24 07:14:45 +0000314 const PartialDiagnostic & NoteID,
Sebastian Redl60618fa2011-03-12 11:50:43 +0000315 const FunctionProtoType *Old,
Douglas Gregor2eef8292010-03-24 07:14:45 +0000316 SourceLocation OldLoc,
Sebastian Redl60618fa2011-03-12 11:50:43 +0000317 const FunctionProtoType *New,
Douglas Gregor2eef8292010-03-24 07:14:45 +0000318 SourceLocation NewLoc,
319 bool *MissingExceptionSpecification,
Sebastian Redl60618fa2011-03-12 11:50:43 +0000320 bool*MissingEmptyExceptionSpecification,
Sebastian Redl99439d42011-03-15 19:52:30 +0000321 bool AllowNoexceptAllMatchWithNoSpec,
322 bool IsOperatorNew) {
John McCall811d0be2010-05-28 08:37:35 +0000323 // Just completely ignore this under -fno-exceptions.
David Blaikie4e4d0842012-03-11 07:00:24 +0000324 if (!getLangOpts().CXXExceptions)
John McCall811d0be2010-05-28 08:37:35 +0000325 return false;
326
Douglas Gregor2eef8292010-03-24 07:14:45 +0000327 if (MissingExceptionSpecification)
328 *MissingExceptionSpecification = false;
329
Douglas Gregore13ad832010-02-12 07:32:17 +0000330 if (MissingEmptyExceptionSpecification)
331 *MissingEmptyExceptionSpecification = false;
332
Richard Smithe6975e92012-04-17 00:58:00 +0000333 Old = ResolveExceptionSpec(NewLoc, Old);
334 if (!Old)
335 return false;
336 New = ResolveExceptionSpec(NewLoc, New);
337 if (!New)
338 return false;
339
Sebastian Redl60618fa2011-03-12 11:50:43 +0000340 // C++0x [except.spec]p3: Two exception-specifications are compatible if:
341 // - both are non-throwing, regardless of their form,
342 // - both have the form noexcept(constant-expression) and the constant-
343 // expressions are equivalent,
Sebastian Redl60618fa2011-03-12 11:50:43 +0000344 // - both are dynamic-exception-specifications that have the same set of
345 // adjusted types.
346 //
347 // C++0x [except.spec]p12: An exception-specifcation is non-throwing if it is
348 // of the form throw(), noexcept, or noexcept(constant-expression) where the
349 // constant-expression yields true.
350 //
Sebastian Redl60618fa2011-03-12 11:50:43 +0000351 // C++0x [except.spec]p4: If any declaration of a function has an exception-
352 // specifier that is not a noexcept-specification allowing all exceptions,
353 // all declarations [...] of that function shall have a compatible
354 // exception-specification.
355 //
356 // That last point basically means that noexcept(false) matches no spec.
357 // It's considered when AllowNoexceptAllMatchWithNoSpec is true.
358
359 ExceptionSpecificationType OldEST = Old->getExceptionSpecType();
360 ExceptionSpecificationType NewEST = New->getExceptionSpecType();
361
Richard Smithb9d0b762012-07-27 04:22:15 +0000362 assert(!isUnresolvedExceptionSpec(OldEST) &&
363 !isUnresolvedExceptionSpec(NewEST) &&
Richard Smith7a614d82011-06-11 17:19:42 +0000364 "Shouldn't see unknown exception specifications here");
365
Sebastian Redl60618fa2011-03-12 11:50:43 +0000366 // Shortcut the case where both have no spec.
367 if (OldEST == EST_None && NewEST == EST_None)
368 return false;
369
Sebastian Redl8026f6d2011-03-13 17:09:40 +0000370 FunctionProtoType::NoexceptResult OldNR = Old->getNoexceptSpec(Context);
371 FunctionProtoType::NoexceptResult NewNR = New->getNoexceptSpec(Context);
Sebastian Redl60618fa2011-03-12 11:50:43 +0000372 if (OldNR == FunctionProtoType::NR_BadNoexcept ||
373 NewNR == FunctionProtoType::NR_BadNoexcept)
374 return false;
375
376 // Dependent noexcept specifiers are compatible with each other, but nothing
377 // else.
378 // One noexcept is compatible with another if the argument is the same
379 if (OldNR == NewNR &&
380 OldNR != FunctionProtoType::NR_NoNoexcept &&
381 NewNR != FunctionProtoType::NR_NoNoexcept)
382 return false;
383 if (OldNR != NewNR &&
384 OldNR != FunctionProtoType::NR_NoNoexcept &&
385 NewNR != FunctionProtoType::NR_NoNoexcept) {
386 Diag(NewLoc, DiagID);
387 if (NoteID.getDiagID() != 0)
388 Diag(OldLoc, NoteID);
389 return true;
Douglas Gregor5b6f7692010-08-30 15:04:51 +0000390 }
391
Sebastian Redl60618fa2011-03-12 11:50:43 +0000392 // The MS extension throw(...) is compatible with itself.
393 if (OldEST == EST_MSAny && NewEST == EST_MSAny)
Sebastian Redldced2262009-10-11 09:03:14 +0000394 return false;
Sebastian Redl60618fa2011-03-12 11:50:43 +0000395
396 // It's also compatible with no spec.
397 if ((OldEST == EST_None && NewEST == EST_MSAny) ||
398 (OldEST == EST_MSAny && NewEST == EST_None))
399 return false;
400
401 // It's also compatible with noexcept(false).
402 if (OldEST == EST_MSAny && NewNR == FunctionProtoType::NR_Throw)
403 return false;
404 if (NewEST == EST_MSAny && OldNR == FunctionProtoType::NR_Throw)
405 return false;
406
407 // As described above, noexcept(false) matches no spec only for functions.
408 if (AllowNoexceptAllMatchWithNoSpec) {
409 if (OldEST == EST_None && NewNR == FunctionProtoType::NR_Throw)
410 return false;
411 if (NewEST == EST_None && OldNR == FunctionProtoType::NR_Throw)
412 return false;
413 }
414
415 // Any non-throwing specifications are compatible.
416 bool OldNonThrowing = OldNR == FunctionProtoType::NR_Nothrow ||
417 OldEST == EST_DynamicNone;
418 bool NewNonThrowing = NewNR == FunctionProtoType::NR_Nothrow ||
419 NewEST == EST_DynamicNone;
420 if (OldNonThrowing && NewNonThrowing)
421 return false;
422
Sebastian Redl99439d42011-03-15 19:52:30 +0000423 // As a special compatibility feature, under C++0x we accept no spec and
424 // throw(std::bad_alloc) as equivalent for operator new and operator new[].
425 // This is because the implicit declaration changed, but old code would break.
David Blaikie4e4d0842012-03-11 07:00:24 +0000426 if (getLangOpts().CPlusPlus0x && IsOperatorNew) {
Sebastian Redl99439d42011-03-15 19:52:30 +0000427 const FunctionProtoType *WithExceptions = 0;
428 if (OldEST == EST_None && NewEST == EST_Dynamic)
429 WithExceptions = New;
430 else if (OldEST == EST_Dynamic && NewEST == EST_None)
431 WithExceptions = Old;
432 if (WithExceptions && WithExceptions->getNumExceptions() == 1) {
433 // One has no spec, the other throw(something). If that something is
434 // std::bad_alloc, all conditions are met.
435 QualType Exception = *WithExceptions->exception_begin();
436 if (CXXRecordDecl *ExRecord = Exception->getAsCXXRecordDecl()) {
437 IdentifierInfo* Name = ExRecord->getIdentifier();
438 if (Name && Name->getName() == "bad_alloc") {
439 // It's called bad_alloc, but is it in std?
440 DeclContext* DC = ExRecord->getDeclContext();
Sebastian Redld8f2e8e2011-03-15 20:41:09 +0000441 DC = DC->getEnclosingNamespaceContext();
442 if (NamespaceDecl* NS = dyn_cast<NamespaceDecl>(DC)) {
Sebastian Redl99439d42011-03-15 19:52:30 +0000443 IdentifierInfo* NSName = NS->getIdentifier();
Sebastian Redld8f2e8e2011-03-15 20:41:09 +0000444 DC = DC->getParent();
Sebastian Redl99439d42011-03-15 19:52:30 +0000445 if (NSName && NSName->getName() == "std" &&
Sebastian Redld8f2e8e2011-03-15 20:41:09 +0000446 DC->getEnclosingNamespaceContext()->isTranslationUnit()) {
Sebastian Redl99439d42011-03-15 19:52:30 +0000447 return false;
Sebastian Redld8f2e8e2011-03-15 20:41:09 +0000448 }
Sebastian Redl99439d42011-03-15 19:52:30 +0000449 }
450 }
451 }
452 }
453 }
454
Sebastian Redl60618fa2011-03-12 11:50:43 +0000455 // At this point, the only remaining valid case is two matching dynamic
456 // specifications. We return here unless both specifications are dynamic.
457 if (OldEST != EST_Dynamic || NewEST != EST_Dynamic) {
Douglas Gregor2eef8292010-03-24 07:14:45 +0000458 if (MissingExceptionSpecification && Old->hasExceptionSpec() &&
Douglas Gregore13ad832010-02-12 07:32:17 +0000459 !New->hasExceptionSpec()) {
Douglas Gregor2eef8292010-03-24 07:14:45 +0000460 // The old type has an exception specification of some sort, but
461 // the new type does not.
462 *MissingExceptionSpecification = true;
463
Sebastian Redl60618fa2011-03-12 11:50:43 +0000464 if (MissingEmptyExceptionSpecification && OldNonThrowing) {
465 // The old type has a throw() or noexcept(true) exception specification
466 // and the new type has no exception specification, and the caller asked
Douglas Gregor2eef8292010-03-24 07:14:45 +0000467 // to handle this itself.
468 *MissingEmptyExceptionSpecification = true;
469 }
470
Douglas Gregore13ad832010-02-12 07:32:17 +0000471 return true;
472 }
473
Sebastian Redldced2262009-10-11 09:03:14 +0000474 Diag(NewLoc, DiagID);
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000475 if (NoteID.getDiagID() != 0)
Sebastian Redldced2262009-10-11 09:03:14 +0000476 Diag(OldLoc, NoteID);
477 return true;
478 }
479
Sebastian Redl60618fa2011-03-12 11:50:43 +0000480 assert(OldEST == EST_Dynamic && NewEST == EST_Dynamic &&
481 "Exception compatibility logic error: non-dynamic spec slipped through.");
482
Sebastian Redldced2262009-10-11 09:03:14 +0000483 bool Success = true;
Sebastian Redl60618fa2011-03-12 11:50:43 +0000484 // Both have a dynamic exception spec. Collect the first set, then compare
Sebastian Redldced2262009-10-11 09:03:14 +0000485 // to the second.
Sebastian Redl1219d152009-10-14 15:06:25 +0000486 llvm::SmallPtrSet<CanQualType, 8> OldTypes, NewTypes;
Sebastian Redldced2262009-10-11 09:03:14 +0000487 for (FunctionProtoType::exception_iterator I = Old->exception_begin(),
488 E = Old->exception_end(); I != E; ++I)
Sebastian Redl1219d152009-10-14 15:06:25 +0000489 OldTypes.insert(Context.getCanonicalType(*I).getUnqualifiedType());
Sebastian Redldced2262009-10-11 09:03:14 +0000490
491 for (FunctionProtoType::exception_iterator I = New->exception_begin(),
Sebastian Redl5db4d902009-10-11 09:11:23 +0000492 E = New->exception_end(); I != E && Success; ++I) {
Sebastian Redl1219d152009-10-14 15:06:25 +0000493 CanQualType TypePtr = Context.getCanonicalType(*I).getUnqualifiedType();
Sebastian Redl5db4d902009-10-11 09:11:23 +0000494 if(OldTypes.count(TypePtr))
495 NewTypes.insert(TypePtr);
496 else
497 Success = false;
498 }
Sebastian Redldced2262009-10-11 09:03:14 +0000499
Sebastian Redl5db4d902009-10-11 09:11:23 +0000500 Success = Success && OldTypes.size() == NewTypes.size();
Sebastian Redldced2262009-10-11 09:03:14 +0000501
502 if (Success) {
503 return false;
504 }
505 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
511/// CheckExceptionSpecSubset - Check whether the second function type's
512/// exception specification is a subset (or equivalent) of the first function
513/// type. This is used by override and pointer assignment checks.
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000514bool Sema::CheckExceptionSpecSubset(
515 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
Sebastian Redldced2262009-10-11 09:03:14 +0000516 const FunctionProtoType *Superset, SourceLocation SuperLoc,
517 const FunctionProtoType *Subset, SourceLocation SubLoc) {
John McCall811d0be2010-05-28 08:37:35 +0000518
519 // Just auto-succeed under -fno-exceptions.
David Blaikie4e4d0842012-03-11 07:00:24 +0000520 if (!getLangOpts().CXXExceptions)
John McCall811d0be2010-05-28 08:37:35 +0000521 return false;
522
Sebastian Redldced2262009-10-11 09:03:14 +0000523 // FIXME: As usual, we could be more specific in our error messages, but
524 // that better waits until we've got types with source locations.
525
526 if (!SubLoc.isValid())
527 SubLoc = SuperLoc;
528
Richard Smithe6975e92012-04-17 00:58:00 +0000529 // Resolve the exception specifications, if needed.
530 Superset = ResolveExceptionSpec(SuperLoc, Superset);
531 if (!Superset)
532 return false;
533 Subset = ResolveExceptionSpec(SubLoc, Subset);
534 if (!Subset)
535 return false;
536
Sebastian Redl60618fa2011-03-12 11:50:43 +0000537 ExceptionSpecificationType SuperEST = Superset->getExceptionSpecType();
538
Sebastian Redldced2262009-10-11 09:03:14 +0000539 // If superset contains everything, we're done.
Sebastian Redl60618fa2011-03-12 11:50:43 +0000540 if (SuperEST == EST_None || SuperEST == EST_MSAny)
Sebastian Redldced2262009-10-11 09:03:14 +0000541 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
542
Sebastian Redl60618fa2011-03-12 11:50:43 +0000543 // If there are dependent noexcept specs, assume everything is fine. Unlike
544 // with the equivalency check, this is safe in this case, because we don't
545 // want to merge declarations. Checks after instantiation will catch any
546 // omissions we make here.
547 // We also shortcut checking if a noexcept expression was bad.
548
Sebastian Redl8026f6d2011-03-13 17:09:40 +0000549 FunctionProtoType::NoexceptResult SuperNR =Superset->getNoexceptSpec(Context);
Sebastian Redl60618fa2011-03-12 11:50:43 +0000550 if (SuperNR == FunctionProtoType::NR_BadNoexcept ||
551 SuperNR == FunctionProtoType::NR_Dependent)
552 return false;
553
554 // Another case of the superset containing everything.
555 if (SuperNR == FunctionProtoType::NR_Throw)
556 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
557
558 ExceptionSpecificationType SubEST = Subset->getExceptionSpecType();
559
Richard Smithb9d0b762012-07-27 04:22:15 +0000560 assert(!isUnresolvedExceptionSpec(SuperEST) &&
561 !isUnresolvedExceptionSpec(SubEST) &&
Richard Smith7a614d82011-06-11 17:19:42 +0000562 "Shouldn't see unknown exception specifications here");
563
Sebastian Redldced2262009-10-11 09:03:14 +0000564 // It does not. If the subset contains everything, we've failed.
Sebastian Redl60618fa2011-03-12 11:50:43 +0000565 if (SubEST == EST_None || SubEST == EST_MSAny) {
Sebastian Redldced2262009-10-11 09:03:14 +0000566 Diag(SubLoc, DiagID);
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000567 if (NoteID.getDiagID() != 0)
Sebastian Redldced2262009-10-11 09:03:14 +0000568 Diag(SuperLoc, NoteID);
569 return true;
570 }
571
Sebastian Redl8026f6d2011-03-13 17:09:40 +0000572 FunctionProtoType::NoexceptResult SubNR = Subset->getNoexceptSpec(Context);
Sebastian Redl60618fa2011-03-12 11:50:43 +0000573 if (SubNR == FunctionProtoType::NR_BadNoexcept ||
574 SubNR == FunctionProtoType::NR_Dependent)
575 return false;
576
577 // Another case of the subset containing everything.
578 if (SubNR == FunctionProtoType::NR_Throw) {
579 Diag(SubLoc, DiagID);
580 if (NoteID.getDiagID() != 0)
581 Diag(SuperLoc, NoteID);
582 return true;
583 }
584
585 // If the subset contains nothing, we're done.
586 if (SubEST == EST_DynamicNone || SubNR == FunctionProtoType::NR_Nothrow)
587 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
588
589 // Otherwise, if the superset contains nothing, we've failed.
590 if (SuperEST == EST_DynamicNone || SuperNR == FunctionProtoType::NR_Nothrow) {
591 Diag(SubLoc, DiagID);
592 if (NoteID.getDiagID() != 0)
593 Diag(SuperLoc, NoteID);
594 return true;
595 }
596
597 assert(SuperEST == EST_Dynamic && SubEST == EST_Dynamic &&
598 "Exception spec subset: non-dynamic case slipped through.");
599
600 // Neither contains everything or nothing. Do a proper comparison.
Sebastian Redldced2262009-10-11 09:03:14 +0000601 for (FunctionProtoType::exception_iterator SubI = Subset->exception_begin(),
602 SubE = Subset->exception_end(); SubI != SubE; ++SubI) {
603 // Take one type from the subset.
604 QualType CanonicalSubT = Context.getCanonicalType(*SubI);
Sebastian Redlc3a3b7b2009-10-14 14:38:54 +0000605 // Unwrap pointers and references so that we can do checks within a class
606 // hierarchy. Don't unwrap member pointers; they don't have hierarchy
607 // conversions on the pointee.
Sebastian Redldced2262009-10-11 09:03:14 +0000608 bool SubIsPointer = false;
609 if (const ReferenceType *RefTy = CanonicalSubT->getAs<ReferenceType>())
610 CanonicalSubT = RefTy->getPointeeType();
611 if (const PointerType *PtrTy = CanonicalSubT->getAs<PointerType>()) {
612 CanonicalSubT = PtrTy->getPointeeType();
613 SubIsPointer = true;
614 }
615 bool SubIsClass = CanonicalSubT->isRecordType();
Douglas Gregora4923eb2009-11-16 21:35:15 +0000616 CanonicalSubT = CanonicalSubT.getLocalUnqualifiedType();
Sebastian Redldced2262009-10-11 09:03:14 +0000617
618 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
619 /*DetectVirtual=*/false);
620
621 bool Contained = false;
622 // Make sure it's in the superset.
623 for (FunctionProtoType::exception_iterator SuperI =
624 Superset->exception_begin(), SuperE = Superset->exception_end();
625 SuperI != SuperE; ++SuperI) {
626 QualType CanonicalSuperT = Context.getCanonicalType(*SuperI);
627 // SubT must be SuperT or derived from it, or pointer or reference to
628 // such types.
629 if (const ReferenceType *RefTy = CanonicalSuperT->getAs<ReferenceType>())
630 CanonicalSuperT = RefTy->getPointeeType();
631 if (SubIsPointer) {
632 if (const PointerType *PtrTy = CanonicalSuperT->getAs<PointerType>())
633 CanonicalSuperT = PtrTy->getPointeeType();
634 else {
635 continue;
636 }
637 }
Douglas Gregora4923eb2009-11-16 21:35:15 +0000638 CanonicalSuperT = CanonicalSuperT.getLocalUnqualifiedType();
Sebastian Redldced2262009-10-11 09:03:14 +0000639 // If the types are the same, move on to the next type in the subset.
640 if (CanonicalSubT == CanonicalSuperT) {
641 Contained = true;
642 break;
643 }
644
645 // Otherwise we need to check the inheritance.
646 if (!SubIsClass || !CanonicalSuperT->isRecordType())
647 continue;
648
649 Paths.clear();
650 if (!IsDerivedFrom(CanonicalSubT, CanonicalSuperT, Paths))
651 continue;
652
Douglas Gregore0d5fe22010-05-21 20:29:55 +0000653 if (Paths.isAmbiguous(Context.getCanonicalType(CanonicalSuperT)))
Sebastian Redldced2262009-10-11 09:03:14 +0000654 continue;
655
John McCall6b2accb2010-02-10 09:31:12 +0000656 // Do this check from a context without privileges.
John McCall58e6f342010-03-16 05:22:47 +0000657 switch (CheckBaseClassAccess(SourceLocation(),
John McCall6b2accb2010-02-10 09:31:12 +0000658 CanonicalSuperT, CanonicalSubT,
659 Paths.front(),
John McCall58e6f342010-03-16 05:22:47 +0000660 /*Diagnostic*/ 0,
John McCall6b2accb2010-02-10 09:31:12 +0000661 /*ForceCheck*/ true,
John McCall58e6f342010-03-16 05:22:47 +0000662 /*ForceUnprivileged*/ true)) {
John McCall6b2accb2010-02-10 09:31:12 +0000663 case AR_accessible: break;
664 case AR_inaccessible: continue;
665 case AR_dependent:
666 llvm_unreachable("access check dependent for unprivileged context");
John McCall6b2accb2010-02-10 09:31:12 +0000667 case AR_delayed:
668 llvm_unreachable("access check delayed in non-declaration");
John McCall6b2accb2010-02-10 09:31:12 +0000669 }
Sebastian Redldced2262009-10-11 09:03:14 +0000670
671 Contained = true;
672 break;
673 }
674 if (!Contained) {
675 Diag(SubLoc, DiagID);
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000676 if (NoteID.getDiagID() != 0)
Sebastian Redldced2262009-10-11 09:03:14 +0000677 Diag(SuperLoc, NoteID);
678 return true;
679 }
680 }
681 // We've run half the gauntlet.
682 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
683}
684
685static bool CheckSpecForTypesEquivalent(Sema &S,
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000686 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
Sebastian Redldced2262009-10-11 09:03:14 +0000687 QualType Target, SourceLocation TargetLoc,
688 QualType Source, SourceLocation SourceLoc)
689{
690 const FunctionProtoType *TFunc = GetUnderlyingFunction(Target);
691 if (!TFunc)
692 return false;
693 const FunctionProtoType *SFunc = GetUnderlyingFunction(Source);
694 if (!SFunc)
695 return false;
696
697 return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc,
698 SFunc, SourceLoc);
699}
700
701/// CheckParamExceptionSpec - Check if the parameter and return types of the
702/// two functions have equivalent exception specs. This is part of the
703/// assignment and override compatibility check. We do not check the parameters
704/// of parameter function pointers recursively, as no sane programmer would
705/// even be able to write such a function type.
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000706bool Sema::CheckParamExceptionSpec(const PartialDiagnostic & NoteID,
Sebastian Redldced2262009-10-11 09:03:14 +0000707 const FunctionProtoType *Target, SourceLocation TargetLoc,
708 const FunctionProtoType *Source, SourceLocation SourceLoc)
709{
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000710 if (CheckSpecForTypesEquivalent(*this,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000711 PDiag(diag::err_deep_exception_specs_differ) << 0,
712 PDiag(),
Sebastian Redldced2262009-10-11 09:03:14 +0000713 Target->getResultType(), TargetLoc,
714 Source->getResultType(), SourceLoc))
715 return true;
716
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000717 // We shouldn't even be testing this unless the arguments are otherwise
Sebastian Redldced2262009-10-11 09:03:14 +0000718 // compatible.
719 assert(Target->getNumArgs() == Source->getNumArgs() &&
720 "Functions have different argument counts.");
721 for (unsigned i = 0, E = Target->getNumArgs(); i != E; ++i) {
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000722 if (CheckSpecForTypesEquivalent(*this,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000723 PDiag(diag::err_deep_exception_specs_differ) << 1,
724 PDiag(),
Sebastian Redldced2262009-10-11 09:03:14 +0000725 Target->getArgType(i), TargetLoc,
726 Source->getArgType(i), SourceLoc))
727 return true;
728 }
729 return false;
730}
731
732bool Sema::CheckExceptionSpecCompatibility(Expr *From, QualType ToType)
733{
734 // First we check for applicability.
735 // Target type must be a function, function pointer or function reference.
736 const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType);
737 if (!ToFunc)
738 return false;
739
740 // SourceType must be a function or function pointer.
741 const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType());
742 if (!FromFunc)
743 return false;
744
745 // Now we've got the correct types on both sides, check their compatibility.
746 // This means that the source of the conversion can only throw a subset of
747 // the exceptions of the target, and any exception specs on arguments or
748 // return types must be equivalent.
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000749 return CheckExceptionSpecSubset(PDiag(diag::err_incompatible_exception_specs),
750 PDiag(), ToFunc,
751 From->getSourceRange().getBegin(),
Sebastian Redldced2262009-10-11 09:03:14 +0000752 FromFunc, SourceLocation());
753}
754
755bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
756 const CXXMethodDecl *Old) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000757 if (getLangOpts().CPlusPlus0x && isa<CXXDestructorDecl>(New)) {
Sebastian Redla0448262011-05-20 05:57:18 +0000758 // Don't check uninstantiated template destructors at all. We can only
759 // synthesize correct specs after the template is instantiated.
760 if (New->getParent()->isDependentType())
761 return false;
762 if (New->getParent()->isBeingDefined()) {
763 // The destructor might be updated once the definition is finished. So
764 // remember it and check later.
765 DelayedDestructorExceptionSpecChecks.push_back(std::make_pair(
766 cast<CXXDestructorDecl>(New), cast<CXXDestructorDecl>(Old)));
767 return false;
768 }
Sebastian Redl0ee33912011-05-19 05:13:44 +0000769 }
Francois Pichet0f161592011-05-24 02:11:43 +0000770 unsigned DiagID = diag::err_override_exception_spec;
David Blaikie4e4d0842012-03-11 07:00:24 +0000771 if (getLangOpts().MicrosoftExt)
Francois Pichet0f161592011-05-24 02:11:43 +0000772 DiagID = diag::warn_override_exception_spec;
773 return CheckExceptionSpecSubset(PDiag(DiagID),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000774 PDiag(diag::note_overridden_virtual_function),
Sebastian Redldced2262009-10-11 09:03:14 +0000775 Old->getType()->getAs<FunctionProtoType>(),
776 Old->getLocation(),
777 New->getType()->getAs<FunctionProtoType>(),
778 New->getLocation());
779}
780
Richard Smithe6975e92012-04-17 00:58:00 +0000781static CanThrowResult canSubExprsThrow(Sema &S, const Expr *CE) {
782 Expr *E = const_cast<Expr*>(CE);
783 CanThrowResult R = CT_Cannot;
784 for (Expr::child_range I = E->children(); I && R != CT_Can; ++I)
785 R = mergeCanThrow(R, S.canThrow(cast<Expr>(*I)));
786 return R;
787}
788
789static CanThrowResult canCalleeThrow(Sema &S, const Expr *E,
790 const Decl *D,
791 bool NullThrows = true) {
792 if (!D)
793 return NullThrows ? CT_Can : CT_Cannot;
794
795 // See if we can get a function type from the decl somehow.
796 const ValueDecl *VD = dyn_cast<ValueDecl>(D);
797 if (!VD) // If we have no clue what we're calling, assume the worst.
798 return CT_Can;
799
800 // As an extension, we assume that __attribute__((nothrow)) functions don't
801 // throw.
802 if (isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())
803 return CT_Cannot;
804
805 QualType T = VD->getType();
806 const FunctionProtoType *FT;
807 if ((FT = T->getAs<FunctionProtoType>())) {
808 } else if (const PointerType *PT = T->getAs<PointerType>())
809 FT = PT->getPointeeType()->getAs<FunctionProtoType>();
810 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
811 FT = RT->getPointeeType()->getAs<FunctionProtoType>();
812 else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
813 FT = MT->getPointeeType()->getAs<FunctionProtoType>();
814 else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
815 FT = BT->getPointeeType()->getAs<FunctionProtoType>();
816
817 if (!FT)
818 return CT_Can;
819
820 FT = S.ResolveExceptionSpec(E->getLocStart(), FT);
821 if (!FT)
822 return CT_Can;
823
Richard Smithe6975e92012-04-17 00:58:00 +0000824 return FT->isNothrow(S.Context) ? CT_Cannot : CT_Can;
825}
826
827static CanThrowResult canDynamicCastThrow(const CXXDynamicCastExpr *DC) {
828 if (DC->isTypeDependent())
829 return CT_Dependent;
830
831 if (!DC->getTypeAsWritten()->isReferenceType())
832 return CT_Cannot;
833
834 if (DC->getSubExpr()->isTypeDependent())
835 return CT_Dependent;
836
837 return DC->getCastKind() == clang::CK_Dynamic? CT_Can : CT_Cannot;
838}
839
840static CanThrowResult canTypeidThrow(Sema &S, const CXXTypeidExpr *DC) {
841 if (DC->isTypeOperand())
842 return CT_Cannot;
843
844 Expr *Op = DC->getExprOperand();
845 if (Op->isTypeDependent())
846 return CT_Dependent;
847
848 const RecordType *RT = Op->getType()->getAs<RecordType>();
849 if (!RT)
850 return CT_Cannot;
851
852 if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
853 return CT_Cannot;
854
855 if (Op->Classify(S.Context).isPRValue())
856 return CT_Cannot;
857
858 return CT_Can;
859}
860
861CanThrowResult Sema::canThrow(const Expr *E) {
862 // C++ [expr.unary.noexcept]p3:
863 // [Can throw] if in a potentially-evaluated context the expression would
864 // contain:
865 switch (E->getStmtClass()) {
866 case Expr::CXXThrowExprClass:
867 // - a potentially evaluated throw-expression
868 return CT_Can;
869
870 case Expr::CXXDynamicCastExprClass: {
871 // - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
872 // where T is a reference type, that requires a run-time check
873 CanThrowResult CT = canDynamicCastThrow(cast<CXXDynamicCastExpr>(E));
874 if (CT == CT_Can)
875 return CT;
876 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
877 }
878
879 case Expr::CXXTypeidExprClass:
880 // - a potentially evaluated typeid expression applied to a glvalue
881 // expression whose type is a polymorphic class type
882 return canTypeidThrow(*this, cast<CXXTypeidExpr>(E));
883
884 // - a potentially evaluated call to a function, member function, function
885 // pointer, or member function pointer that does not have a non-throwing
886 // exception-specification
887 case Expr::CallExprClass:
888 case Expr::CXXMemberCallExprClass:
889 case Expr::CXXOperatorCallExprClass:
890 case Expr::UserDefinedLiteralClass: {
891 const CallExpr *CE = cast<CallExpr>(E);
892 CanThrowResult CT;
893 if (E->isTypeDependent())
894 CT = CT_Dependent;
895 else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens()))
896 CT = CT_Cannot;
897 else
898 CT = canCalleeThrow(*this, E, CE->getCalleeDecl());
899 if (CT == CT_Can)
900 return CT;
901 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
902 }
903
904 case Expr::CXXConstructExprClass:
905 case Expr::CXXTemporaryObjectExprClass: {
906 CanThrowResult CT = canCalleeThrow(*this, E,
907 cast<CXXConstructExpr>(E)->getConstructor());
908 if (CT == CT_Can)
909 return CT;
910 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
911 }
912
913 case Expr::LambdaExprClass: {
914 const LambdaExpr *Lambda = cast<LambdaExpr>(E);
915 CanThrowResult CT = CT_Cannot;
916 for (LambdaExpr::capture_init_iterator Cap = Lambda->capture_init_begin(),
917 CapEnd = Lambda->capture_init_end();
918 Cap != CapEnd; ++Cap)
919 CT = mergeCanThrow(CT, canThrow(*Cap));
920 return CT;
921 }
922
923 case Expr::CXXNewExprClass: {
924 CanThrowResult CT;
925 if (E->isTypeDependent())
926 CT = CT_Dependent;
927 else
928 CT = canCalleeThrow(*this, E, cast<CXXNewExpr>(E)->getOperatorNew());
929 if (CT == CT_Can)
930 return CT;
931 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
932 }
933
934 case Expr::CXXDeleteExprClass: {
935 CanThrowResult CT;
936 QualType DTy = cast<CXXDeleteExpr>(E)->getDestroyedType();
937 if (DTy.isNull() || DTy->isDependentType()) {
938 CT = CT_Dependent;
939 } else {
940 CT = canCalleeThrow(*this, E,
941 cast<CXXDeleteExpr>(E)->getOperatorDelete());
942 if (const RecordType *RT = DTy->getAs<RecordType>()) {
943 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
944 CT = mergeCanThrow(CT, canCalleeThrow(*this, E, RD->getDestructor()));
945 }
946 if (CT == CT_Can)
947 return CT;
948 }
949 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
950 }
951
952 case Expr::CXXBindTemporaryExprClass: {
953 // The bound temporary has to be destroyed again, which might throw.
954 CanThrowResult CT = canCalleeThrow(*this, E,
955 cast<CXXBindTemporaryExpr>(E)->getTemporary()->getDestructor());
956 if (CT == CT_Can)
957 return CT;
958 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
959 }
960
961 // ObjC message sends are like function calls, but never have exception
962 // specs.
963 case Expr::ObjCMessageExprClass:
964 case Expr::ObjCPropertyRefExprClass:
965 case Expr::ObjCSubscriptRefExprClass:
966 return CT_Can;
967
968 // All the ObjC literals that are implemented as calls are
969 // potentially throwing unless we decide to close off that
970 // possibility.
971 case Expr::ObjCArrayLiteralClass:
972 case Expr::ObjCDictionaryLiteralClass:
Patrick Beardeb382ec2012-04-19 00:25:12 +0000973 case Expr::ObjCBoxedExprClass:
Richard Smithe6975e92012-04-17 00:58:00 +0000974 return CT_Can;
975
976 // Many other things have subexpressions, so we have to test those.
977 // Some are simple:
978 case Expr::ConditionalOperatorClass:
979 case Expr::CompoundLiteralExprClass:
980 case Expr::CXXConstCastExprClass:
981 case Expr::CXXDefaultArgExprClass:
982 case Expr::CXXReinterpretCastExprClass:
983 case Expr::DesignatedInitExprClass:
984 case Expr::ExprWithCleanupsClass:
985 case Expr::ExtVectorElementExprClass:
986 case Expr::InitListExprClass:
987 case Expr::MemberExprClass:
988 case Expr::ObjCIsaExprClass:
989 case Expr::ObjCIvarRefExprClass:
990 case Expr::ParenExprClass:
991 case Expr::ParenListExprClass:
992 case Expr::ShuffleVectorExprClass:
993 case Expr::VAArgExprClass:
994 return canSubExprsThrow(*this, E);
995
996 // Some might be dependent for other reasons.
997 case Expr::ArraySubscriptExprClass:
998 case Expr::BinaryOperatorClass:
999 case Expr::CompoundAssignOperatorClass:
1000 case Expr::CStyleCastExprClass:
1001 case Expr::CXXStaticCastExprClass:
1002 case Expr::CXXFunctionalCastExprClass:
1003 case Expr::ImplicitCastExprClass:
1004 case Expr::MaterializeTemporaryExprClass:
1005 case Expr::UnaryOperatorClass: {
1006 CanThrowResult CT = E->isTypeDependent() ? CT_Dependent : CT_Cannot;
1007 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1008 }
1009
1010 // FIXME: We should handle StmtExpr, but that opens a MASSIVE can of worms.
1011 case Expr::StmtExprClass:
1012 return CT_Can;
1013
1014 case Expr::ChooseExprClass:
1015 if (E->isTypeDependent() || E->isValueDependent())
1016 return CT_Dependent;
1017 return canThrow(cast<ChooseExpr>(E)->getChosenSubExpr(Context));
1018
1019 case Expr::GenericSelectionExprClass:
1020 if (cast<GenericSelectionExpr>(E)->isResultDependent())
1021 return CT_Dependent;
1022 return canThrow(cast<GenericSelectionExpr>(E)->getResultExpr());
1023
1024 // Some expressions are always dependent.
1025 case Expr::CXXDependentScopeMemberExprClass:
1026 case Expr::CXXUnresolvedConstructExprClass:
1027 case Expr::DependentScopeDeclRefExprClass:
1028 return CT_Dependent;
1029
1030 case Expr::AsTypeExprClass:
1031 case Expr::BinaryConditionalOperatorClass:
1032 case Expr::BlockExprClass:
1033 case Expr::CUDAKernelCallExprClass:
1034 case Expr::DeclRefExprClass:
1035 case Expr::ObjCBridgedCastExprClass:
1036 case Expr::ObjCIndirectCopyRestoreExprClass:
1037 case Expr::ObjCProtocolExprClass:
1038 case Expr::ObjCSelectorExprClass:
1039 case Expr::OffsetOfExprClass:
1040 case Expr::PackExpansionExprClass:
1041 case Expr::PseudoObjectExprClass:
1042 case Expr::SubstNonTypeTemplateParmExprClass:
1043 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smith9a4db032012-09-12 00:56:43 +00001044 case Expr::FunctionParmPackExprClass:
Richard Smithe6975e92012-04-17 00:58:00 +00001045 case Expr::UnaryExprOrTypeTraitExprClass:
1046 case Expr::UnresolvedLookupExprClass:
1047 case Expr::UnresolvedMemberExprClass:
1048 // FIXME: Can any of the above throw? If so, when?
1049 return CT_Cannot;
1050
1051 case Expr::AddrLabelExprClass:
1052 case Expr::ArrayTypeTraitExprClass:
1053 case Expr::AtomicExprClass:
1054 case Expr::BinaryTypeTraitExprClass:
1055 case Expr::TypeTraitExprClass:
1056 case Expr::CXXBoolLiteralExprClass:
1057 case Expr::CXXNoexceptExprClass:
1058 case Expr::CXXNullPtrLiteralExprClass:
1059 case Expr::CXXPseudoDestructorExprClass:
1060 case Expr::CXXScalarValueInitExprClass:
1061 case Expr::CXXThisExprClass:
1062 case Expr::CXXUuidofExprClass:
1063 case Expr::CharacterLiteralClass:
1064 case Expr::ExpressionTraitExprClass:
1065 case Expr::FloatingLiteralClass:
1066 case Expr::GNUNullExprClass:
1067 case Expr::ImaginaryLiteralClass:
1068 case Expr::ImplicitValueInitExprClass:
1069 case Expr::IntegerLiteralClass:
1070 case Expr::ObjCEncodeExprClass:
1071 case Expr::ObjCStringLiteralClass:
1072 case Expr::ObjCBoolLiteralExprClass:
1073 case Expr::OpaqueValueExprClass:
1074 case Expr::PredefinedExprClass:
1075 case Expr::SizeOfPackExprClass:
1076 case Expr::StringLiteralClass:
1077 case Expr::UnaryTypeTraitExprClass:
1078 // These expressions can never throw.
1079 return CT_Cannot;
1080
1081#define STMT(CLASS, PARENT) case Expr::CLASS##Class:
1082#define STMT_RANGE(Base, First, Last)
1083#define LAST_STMT_RANGE(BASE, FIRST, LAST)
1084#define EXPR(CLASS, PARENT)
1085#define ABSTRACT_STMT(STMT)
1086#include "clang/AST/StmtNodes.inc"
1087 case Expr::NoStmtClass:
1088 llvm_unreachable("Invalid class for expression");
1089 }
1090 llvm_unreachable("Bogus StmtClass");
1091}
1092
Sebastian Redldced2262009-10-11 09:03:14 +00001093} // end namespace clang