blob: 8cb2cb4290e7252eb2606b9b961c0ee01f691350 [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.
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) {
Douglas Gregor0966f352009-12-10 18:13:52 +000045 // This check (and the similar one below) deals with issue 437, that changes
46 // C++ 9.2p2 this way:
47 // Within the class member-specification, the class is regarded as complete
48 // within function bodies, default arguments, exception-specifications, and
49 // constructor ctor-initializers (including such things in nested classes).
50 if (T->isRecordType() && T->getAs<RecordType>()->isBeingDefined())
51 return false;
Richard Smith21173b12012-11-28 22:33:28 +000052
53 // C++ 15.4p2: A type cv T, "array of T", or "function returning T" denoted
54 // in an exception-specification is adjusted to type T, "pointer to T", or
55 // "pointer to function returning T", respectively.
Sebastian Redldced2262009-10-11 09:03:14 +000056 // C++ 15.4p2: A type denoted in an exception-specification shall not denote
57 // an incomplete type.
Richard Smith21173b12012-11-28 22:33:28 +000058 if (T->isArrayType())
59 T = Context.getArrayDecayedType(T);
60 else if (T->isFunctionType())
61 T = Context.getPointerType(T);
62 else if (RequireCompleteType(Range.getBegin(), T,
63 diag::err_incomplete_in_exception_spec,
64 /*direct*/0, Range))
Sebastian Redl491b84c2009-10-14 14:59:48 +000065 return true;
Sebastian Redldced2262009-10-11 09:03:14 +000066
Richard Smith21173b12012-11-28 22:33:28 +000067
Sebastian Redldced2262009-10-11 09:03:14 +000068 // C++ 15.4p2: A type denoted in an exception-specification shall not denote
69 // an incomplete type a pointer or reference to an incomplete type, other
70 // than (cv) void*.
71 int kind;
Richard Smith21173b12012-11-28 22:33:28 +000072 QualType PointeeT = T;
Sebastian Redldced2262009-10-11 09:03:14 +000073 if (const PointerType* IT = T->getAs<PointerType>()) {
Richard Smith21173b12012-11-28 22:33:28 +000074 PointeeT = IT->getPointeeType();
Sebastian Redldced2262009-10-11 09:03:14 +000075 kind = 1;
76 } else if (const ReferenceType* IT = T->getAs<ReferenceType>()) {
Richard Smith21173b12012-11-28 22:33:28 +000077 PointeeT = IT->getPointeeType();
Sebastian Redldced2262009-10-11 09:03:14 +000078 kind = 2;
79 } else
80 return false;
81
Douglas Gregor0966f352009-12-10 18:13:52 +000082 // Again as before
Richard Smith21173b12012-11-28 22:33:28 +000083 if (PointeeT->isRecordType() && PointeeT->getAs<RecordType>()->isBeingDefined())
Douglas Gregor0966f352009-12-10 18:13:52 +000084 return false;
Richard Smith21173b12012-11-28 22:33:28 +000085
86 if (!PointeeT->isVoidType() &&
87 RequireCompleteType(Range.getBegin(), PointeeT,
Douglas Gregord10099e2012-05-04 16:32:21 +000088 diag::err_incomplete_in_exception_spec, kind, Range))
Sebastian Redl491b84c2009-10-14 14:59:48 +000089 return true;
Sebastian Redldced2262009-10-11 09:03:14 +000090
91 return false;
92}
93
94/// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer
95/// to member to a function with an exception specification. This means that
96/// it is invalid to add another level of indirection.
97bool Sema::CheckDistantExceptionSpec(QualType T) {
98 if (const PointerType *PT = T->getAs<PointerType>())
99 T = PT->getPointeeType();
100 else if (const MemberPointerType *PT = T->getAs<MemberPointerType>())
101 T = PT->getPointeeType();
102 else
103 return false;
104
105 const FunctionProtoType *FnT = T->getAs<FunctionProtoType>();
106 if (!FnT)
107 return false;
108
109 return FnT->hasExceptionSpec();
110}
111
Richard Smithe6975e92012-04-17 00:58:00 +0000112const FunctionProtoType *
113Sema::ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000114 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
Richard Smithe6975e92012-04-17 00:58:00 +0000115 return FPT;
116
117 FunctionDecl *SourceDecl = FPT->getExceptionSpecDecl();
118 const FunctionProtoType *SourceFPT =
119 SourceDecl->getType()->castAs<FunctionProtoType>();
120
Richard Smithb9d0b762012-07-27 04:22:15 +0000121 // If the exception specification has already been resolved, just return it.
122 if (!isUnresolvedExceptionSpec(SourceFPT->getExceptionSpecType()))
Richard Smithe6975e92012-04-17 00:58:00 +0000123 return SourceFPT;
124
Richard Smithb9d0b762012-07-27 04:22:15 +0000125 // Compute or instantiate the exception specification now.
126 if (FPT->getExceptionSpecType() == EST_Unevaluated)
127 EvaluateImplicitExceptionSpec(Loc, cast<CXXMethodDecl>(SourceDecl));
128 else
129 InstantiateExceptionSpec(Loc, SourceDecl);
Richard Smithe6975e92012-04-17 00:58:00 +0000130
131 return SourceDecl->getType()->castAs<FunctionProtoType>();
132}
133
Richard Smith444d3842012-10-20 08:26:51 +0000134/// Determine whether a function has an implicitly-generated exception
Richard Smith708f69b2012-10-16 23:30:16 +0000135/// specification.
Richard Smith444d3842012-10-20 08:26:51 +0000136static bool hasImplicitExceptionSpec(FunctionDecl *Decl) {
137 if (!isa<CXXDestructorDecl>(Decl) &&
138 Decl->getDeclName().getCXXOverloadedOperator() != OO_Delete &&
139 Decl->getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
140 return false;
Richard Smith708f69b2012-10-16 23:30:16 +0000141
Richard Smith444d3842012-10-20 08:26:51 +0000142 // If the user didn't declare the function, its exception specification must
143 // be implicit.
144 if (!Decl->getTypeSourceInfo())
145 return true;
146
147 const FunctionProtoType *Ty =
148 Decl->getTypeSourceInfo()->getType()->getAs<FunctionProtoType>();
149 return !Ty->hasExceptionSpec();
Richard Smith708f69b2012-10-16 23:30:16 +0000150}
151
Douglas Gregore13ad832010-02-12 07:32:17 +0000152bool Sema::CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New) {
Sebastian Redl99439d42011-03-15 19:52:30 +0000153 OverloadedOperatorKind OO = New->getDeclName().getCXXOverloadedOperator();
154 bool IsOperatorNew = OO == OO_New || OO == OO_Array_New;
Douglas Gregor2eef8292010-03-24 07:14:45 +0000155 bool MissingExceptionSpecification = false;
Douglas Gregore13ad832010-02-12 07:32:17 +0000156 bool MissingEmptyExceptionSpecification = false;
Francois Picheteedd4672011-03-19 23:05:18 +0000157 unsigned DiagID = diag::err_mismatched_exception_spec;
David Blaikie4e4d0842012-03-11 07:00:24 +0000158 if (getLangOpts().MicrosoftExt)
Francois Pichetcf320c62011-04-22 08:25:24 +0000159 DiagID = diag::warn_mismatched_exception_spec;
Richard Smithe6975e92012-04-17 00:58:00 +0000160
Richard Smith708f69b2012-10-16 23:30:16 +0000161 // Check the types as written: they must match before any exception
162 // specification adjustment is applied.
163 if (!CheckEquivalentExceptionSpec(
164 PDiag(DiagID), PDiag(diag::note_previous_declaration),
Richard Smith444d3842012-10-20 08:26:51 +0000165 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
166 New->getType()->getAs<FunctionProtoType>(), New->getLocation(),
Richard Smith708f69b2012-10-16 23:30:16 +0000167 &MissingExceptionSpecification, &MissingEmptyExceptionSpecification,
Richard Smith444d3842012-10-20 08:26:51 +0000168 /*AllowNoexceptAllMatchWithNoSpec=*/true, IsOperatorNew)) {
169 // C++11 [except.spec]p4 [DR1492]:
170 // If a declaration of a function has an implicit
171 // exception-specification, other declarations of the function shall
172 // not specify an exception-specification.
173 if (getLangOpts().CPlusPlus0x &&
174 hasImplicitExceptionSpec(Old) != hasImplicitExceptionSpec(New)) {
175 Diag(New->getLocation(), diag::ext_implicit_exception_spec_mismatch)
176 << hasImplicitExceptionSpec(Old);
177 if (!Old->getLocation().isInvalid())
178 Diag(Old->getLocation(), diag::note_previous_declaration);
179 }
Douglas Gregore13ad832010-02-12 07:32:17 +0000180 return false;
Richard Smith444d3842012-10-20 08:26:51 +0000181 }
Douglas Gregore13ad832010-02-12 07:32:17 +0000182
183 // The failure was something other than an empty exception
184 // specification; return an error.
Douglas Gregor2eef8292010-03-24 07:14:45 +0000185 if (!MissingExceptionSpecification && !MissingEmptyExceptionSpecification)
Douglas Gregore13ad832010-02-12 07:32:17 +0000186 return true;
187
Richard Smith444d3842012-10-20 08:26:51 +0000188 const FunctionProtoType *NewProto =
189 New->getType()->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +0000190
Douglas Gregore13ad832010-02-12 07:32:17 +0000191 // The new function declaration is only missing an empty exception
192 // specification "throw()". If the throw() specification came from a
193 // function in a system header that has C linkage, just add an empty
194 // exception specification to the "new" declaration. This is an
195 // egregious workaround for glibc, which adds throw() specifications
196 // to many libc functions as an optimization. Unfortunately, that
197 // optimization isn't permitted by the C++ standard, so we're forced
198 // to work around it here.
John McCalle23cf432010-12-14 08:05:40 +0000199 if (MissingEmptyExceptionSpecification && NewProto &&
Douglas Gregor2eef8292010-03-24 07:14:45 +0000200 (Old->getLocation().isInvalid() ||
201 Context.getSourceManager().isInSystemHeader(Old->getLocation())) &&
Douglas Gregore13ad832010-02-12 07:32:17 +0000202 Old->isExternC()) {
John McCalle23cf432010-12-14 08:05:40 +0000203 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
Sebastian Redl60618fa2011-03-12 11:50:43 +0000204 EPI.ExceptionSpecType = EST_DynamicNone;
Douglas Gregore13ad832010-02-12 07:32:17 +0000205 QualType NewType = Context.getFunctionType(NewProto->getResultType(),
206 NewProto->arg_type_begin(),
207 NewProto->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +0000208 EPI);
Douglas Gregore13ad832010-02-12 07:32:17 +0000209 New->setType(NewType);
210 return false;
211 }
212
John McCalle23cf432010-12-14 08:05:40 +0000213 if (MissingExceptionSpecification && NewProto) {
Richard Smith444d3842012-10-20 08:26:51 +0000214 const FunctionProtoType *OldProto =
215 Old->getType()->getAs<FunctionProtoType>();
Douglas Gregor2eef8292010-03-24 07:14:45 +0000216
John McCalle23cf432010-12-14 08:05:40 +0000217 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
Sebastian Redl60618fa2011-03-12 11:50:43 +0000218 EPI.ExceptionSpecType = OldProto->getExceptionSpecType();
219 if (EPI.ExceptionSpecType == EST_Dynamic) {
220 EPI.NumExceptions = OldProto->getNumExceptions();
221 EPI.Exceptions = OldProto->exception_begin();
222 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
223 // FIXME: We can't just take the expression from the old prototype. It
224 // likely contains references to the old prototype's parameters.
225 }
John McCalle23cf432010-12-14 08:05:40 +0000226
Douglas Gregor2eef8292010-03-24 07:14:45 +0000227 // Update the type of the function with the appropriate exception
228 // specification.
229 QualType NewType = Context.getFunctionType(NewProto->getResultType(),
230 NewProto->arg_type_begin(),
231 NewProto->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +0000232 EPI);
Douglas Gregor2eef8292010-03-24 07:14:45 +0000233 New->setType(NewType);
234
235 // If exceptions are disabled, suppress the warning about missing
236 // exception specifications for new and delete operators.
David Blaikie4e4d0842012-03-11 07:00:24 +0000237 if (!getLangOpts().CXXExceptions) {
Douglas Gregor2eef8292010-03-24 07:14:45 +0000238 switch (New->getDeclName().getCXXOverloadedOperator()) {
239 case OO_New:
240 case OO_Array_New:
241 case OO_Delete:
242 case OO_Array_Delete:
243 if (New->getDeclContext()->isTranslationUnit())
244 return false;
245 break;
246
247 default:
248 break;
249 }
250 }
251
252 // Warn about the lack of exception specification.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000253 SmallString<128> ExceptionSpecString;
Douglas Gregor2eef8292010-03-24 07:14:45 +0000254 llvm::raw_svector_ostream OS(ExceptionSpecString);
Sebastian Redl60618fa2011-03-12 11:50:43 +0000255 switch (OldProto->getExceptionSpecType()) {
256 case EST_DynamicNone:
257 OS << "throw()";
258 break;
259
260 case EST_Dynamic: {
261 OS << "throw(";
262 bool OnFirstException = true;
263 for (FunctionProtoType::exception_iterator E = OldProto->exception_begin(),
264 EEnd = OldProto->exception_end();
265 E != EEnd;
266 ++E) {
267 if (OnFirstException)
268 OnFirstException = false;
269 else
270 OS << ", ";
271
Douglas Gregor8987b232011-09-27 23:30:47 +0000272 OS << E->getAsString(getPrintingPolicy());
Sebastian Redl60618fa2011-03-12 11:50:43 +0000273 }
274 OS << ")";
275 break;
Douglas Gregor2eef8292010-03-24 07:14:45 +0000276 }
Sebastian Redl60618fa2011-03-12 11:50:43 +0000277
278 case EST_BasicNoexcept:
279 OS << "noexcept";
280 break;
281
282 case EST_ComputedNoexcept:
283 OS << "noexcept(";
Richard Smithd1420c62012-08-16 03:56:14 +0000284 OldProto->getNoexceptExpr()->printPretty(OS, 0, getPrintingPolicy());
Sebastian Redl60618fa2011-03-12 11:50:43 +0000285 OS << ")";
286 break;
287
288 default:
David Blaikieb219cfc2011-09-23 05:06:16 +0000289 llvm_unreachable("This spec type is compatible with none.");
Sebastian Redl60618fa2011-03-12 11:50:43 +0000290 }
Douglas Gregor2eef8292010-03-24 07:14:45 +0000291 OS.flush();
292
Abramo Bagnara796aa442011-03-12 11:17:06 +0000293 SourceLocation FixItLoc;
Douglas Gregor2eef8292010-03-24 07:14:45 +0000294 if (TypeSourceInfo *TSInfo = New->getTypeSourceInfo()) {
Abramo Bagnara723df242010-12-14 22:11:44 +0000295 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor2eef8292010-03-24 07:14:45 +0000296 if (const FunctionTypeLoc *FTLoc = dyn_cast<FunctionTypeLoc>(&TL))
Abramo Bagnara796aa442011-03-12 11:17:06 +0000297 FixItLoc = PP.getLocForEndOfToken(FTLoc->getLocalRangeEnd());
Douglas Gregor2eef8292010-03-24 07:14:45 +0000298 }
299
Abramo Bagnara796aa442011-03-12 11:17:06 +0000300 if (FixItLoc.isInvalid())
Douglas Gregor2eef8292010-03-24 07:14:45 +0000301 Diag(New->getLocation(), diag::warn_missing_exception_specification)
302 << New << OS.str();
303 else {
304 // FIXME: This will get more complicated with C++0x
305 // late-specified return types.
306 Diag(New->getLocation(), diag::warn_missing_exception_specification)
307 << New << OS.str()
Abramo Bagnara796aa442011-03-12 11:17:06 +0000308 << FixItHint::CreateInsertion(FixItLoc, " " + OS.str().str());
Douglas Gregor2eef8292010-03-24 07:14:45 +0000309 }
310
311 if (!Old->getLocation().isInvalid())
312 Diag(Old->getLocation(), diag::note_previous_declaration);
313
314 return false;
315 }
316
Francois Picheteedd4672011-03-19 23:05:18 +0000317 Diag(New->getLocation(), DiagID);
Douglas Gregore13ad832010-02-12 07:32:17 +0000318 Diag(Old->getLocation(), diag::note_previous_declaration);
319 return true;
320}
321
Sebastian Redldced2262009-10-11 09:03:14 +0000322/// CheckEquivalentExceptionSpec - Check if the two types have equivalent
323/// exception specifications. Exception specifications are equivalent if
324/// they allow exactly the same set of exception types. It does not matter how
325/// that is achieved. See C++ [except.spec]p2.
326bool Sema::CheckEquivalentExceptionSpec(
327 const FunctionProtoType *Old, SourceLocation OldLoc,
328 const FunctionProtoType *New, SourceLocation NewLoc) {
Francois Picheteedd4672011-03-19 23:05:18 +0000329 unsigned DiagID = diag::err_mismatched_exception_spec;
David Blaikie4e4d0842012-03-11 07:00:24 +0000330 if (getLangOpts().MicrosoftExt)
Francois Pichetcf320c62011-04-22 08:25:24 +0000331 DiagID = diag::warn_mismatched_exception_spec;
Richard Smith708f69b2012-10-16 23:30:16 +0000332 return CheckEquivalentExceptionSpec(PDiag(DiagID),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000333 PDiag(diag::note_previous_declaration),
Sebastian Redldced2262009-10-11 09:03:14 +0000334 Old, OldLoc, New, NewLoc);
335}
336
Sebastian Redl60618fa2011-03-12 11:50:43 +0000337/// CheckEquivalentExceptionSpec - Check if the two types have compatible
338/// exception specifications. See C++ [except.spec]p3.
Richard Smith444d3842012-10-20 08:26:51 +0000339///
340/// \return \c false if the exception specifications match, \c true if there is
341/// a problem. If \c true is returned, either a diagnostic has already been
342/// produced or \c *MissingExceptionSpecification is set to \c true.
Sebastian Redl60618fa2011-03-12 11:50:43 +0000343bool Sema::CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
Douglas Gregor2eef8292010-03-24 07:14:45 +0000344 const PartialDiagnostic & NoteID,
Sebastian Redl60618fa2011-03-12 11:50:43 +0000345 const FunctionProtoType *Old,
Douglas Gregor2eef8292010-03-24 07:14:45 +0000346 SourceLocation OldLoc,
Sebastian Redl60618fa2011-03-12 11:50:43 +0000347 const FunctionProtoType *New,
Douglas Gregor2eef8292010-03-24 07:14:45 +0000348 SourceLocation NewLoc,
349 bool *MissingExceptionSpecification,
Sebastian Redl60618fa2011-03-12 11:50:43 +0000350 bool*MissingEmptyExceptionSpecification,
Sebastian Redl99439d42011-03-15 19:52:30 +0000351 bool AllowNoexceptAllMatchWithNoSpec,
352 bool IsOperatorNew) {
John McCall811d0be2010-05-28 08:37:35 +0000353 // Just completely ignore this under -fno-exceptions.
David Blaikie4e4d0842012-03-11 07:00:24 +0000354 if (!getLangOpts().CXXExceptions)
John McCall811d0be2010-05-28 08:37:35 +0000355 return false;
356
Douglas Gregor2eef8292010-03-24 07:14:45 +0000357 if (MissingExceptionSpecification)
358 *MissingExceptionSpecification = false;
359
Douglas Gregore13ad832010-02-12 07:32:17 +0000360 if (MissingEmptyExceptionSpecification)
361 *MissingEmptyExceptionSpecification = false;
362
Richard Smithe6975e92012-04-17 00:58:00 +0000363 Old = ResolveExceptionSpec(NewLoc, Old);
364 if (!Old)
365 return false;
366 New = ResolveExceptionSpec(NewLoc, New);
367 if (!New)
368 return false;
369
Sebastian Redl60618fa2011-03-12 11:50:43 +0000370 // C++0x [except.spec]p3: Two exception-specifications are compatible if:
371 // - both are non-throwing, regardless of their form,
372 // - both have the form noexcept(constant-expression) and the constant-
373 // expressions are equivalent,
Sebastian Redl60618fa2011-03-12 11:50:43 +0000374 // - both are dynamic-exception-specifications that have the same set of
375 // adjusted types.
376 //
377 // C++0x [except.spec]p12: An exception-specifcation is non-throwing if it is
378 // of the form throw(), noexcept, or noexcept(constant-expression) where the
379 // constant-expression yields true.
380 //
Sebastian Redl60618fa2011-03-12 11:50:43 +0000381 // C++0x [except.spec]p4: If any declaration of a function has an exception-
382 // specifier that is not a noexcept-specification allowing all exceptions,
383 // all declarations [...] of that function shall have a compatible
384 // exception-specification.
385 //
386 // That last point basically means that noexcept(false) matches no spec.
387 // It's considered when AllowNoexceptAllMatchWithNoSpec is true.
388
389 ExceptionSpecificationType OldEST = Old->getExceptionSpecType();
390 ExceptionSpecificationType NewEST = New->getExceptionSpecType();
391
Richard Smithb9d0b762012-07-27 04:22:15 +0000392 assert(!isUnresolvedExceptionSpec(OldEST) &&
393 !isUnresolvedExceptionSpec(NewEST) &&
Richard Smith7a614d82011-06-11 17:19:42 +0000394 "Shouldn't see unknown exception specifications here");
395
Sebastian Redl60618fa2011-03-12 11:50:43 +0000396 // Shortcut the case where both have no spec.
397 if (OldEST == EST_None && NewEST == EST_None)
398 return false;
399
Sebastian Redl8026f6d2011-03-13 17:09:40 +0000400 FunctionProtoType::NoexceptResult OldNR = Old->getNoexceptSpec(Context);
401 FunctionProtoType::NoexceptResult NewNR = New->getNoexceptSpec(Context);
Sebastian Redl60618fa2011-03-12 11:50:43 +0000402 if (OldNR == FunctionProtoType::NR_BadNoexcept ||
403 NewNR == FunctionProtoType::NR_BadNoexcept)
404 return false;
405
406 // Dependent noexcept specifiers are compatible with each other, but nothing
407 // else.
408 // One noexcept is compatible with another if the argument is the same
409 if (OldNR == NewNR &&
410 OldNR != FunctionProtoType::NR_NoNoexcept &&
411 NewNR != FunctionProtoType::NR_NoNoexcept)
412 return false;
413 if (OldNR != NewNR &&
414 OldNR != FunctionProtoType::NR_NoNoexcept &&
415 NewNR != FunctionProtoType::NR_NoNoexcept) {
416 Diag(NewLoc, DiagID);
417 if (NoteID.getDiagID() != 0)
418 Diag(OldLoc, NoteID);
419 return true;
Douglas Gregor5b6f7692010-08-30 15:04:51 +0000420 }
421
Sebastian Redl60618fa2011-03-12 11:50:43 +0000422 // The MS extension throw(...) is compatible with itself.
423 if (OldEST == EST_MSAny && NewEST == EST_MSAny)
Sebastian Redldced2262009-10-11 09:03:14 +0000424 return false;
Sebastian Redl60618fa2011-03-12 11:50:43 +0000425
426 // It's also compatible with no spec.
427 if ((OldEST == EST_None && NewEST == EST_MSAny) ||
428 (OldEST == EST_MSAny && NewEST == EST_None))
429 return false;
430
431 // It's also compatible with noexcept(false).
432 if (OldEST == EST_MSAny && NewNR == FunctionProtoType::NR_Throw)
433 return false;
434 if (NewEST == EST_MSAny && OldNR == FunctionProtoType::NR_Throw)
435 return false;
436
437 // As described above, noexcept(false) matches no spec only for functions.
438 if (AllowNoexceptAllMatchWithNoSpec) {
439 if (OldEST == EST_None && NewNR == FunctionProtoType::NR_Throw)
440 return false;
441 if (NewEST == EST_None && OldNR == FunctionProtoType::NR_Throw)
442 return false;
443 }
444
445 // Any non-throwing specifications are compatible.
446 bool OldNonThrowing = OldNR == FunctionProtoType::NR_Nothrow ||
447 OldEST == EST_DynamicNone;
448 bool NewNonThrowing = NewNR == FunctionProtoType::NR_Nothrow ||
449 NewEST == EST_DynamicNone;
450 if (OldNonThrowing && NewNonThrowing)
451 return false;
452
Sebastian Redl99439d42011-03-15 19:52:30 +0000453 // As a special compatibility feature, under C++0x we accept no spec and
454 // throw(std::bad_alloc) as equivalent for operator new and operator new[].
455 // This is because the implicit declaration changed, but old code would break.
David Blaikie4e4d0842012-03-11 07:00:24 +0000456 if (getLangOpts().CPlusPlus0x && IsOperatorNew) {
Sebastian Redl99439d42011-03-15 19:52:30 +0000457 const FunctionProtoType *WithExceptions = 0;
458 if (OldEST == EST_None && NewEST == EST_Dynamic)
459 WithExceptions = New;
460 else if (OldEST == EST_Dynamic && NewEST == EST_None)
461 WithExceptions = Old;
462 if (WithExceptions && WithExceptions->getNumExceptions() == 1) {
463 // One has no spec, the other throw(something). If that something is
464 // std::bad_alloc, all conditions are met.
465 QualType Exception = *WithExceptions->exception_begin();
466 if (CXXRecordDecl *ExRecord = Exception->getAsCXXRecordDecl()) {
467 IdentifierInfo* Name = ExRecord->getIdentifier();
468 if (Name && Name->getName() == "bad_alloc") {
469 // It's called bad_alloc, but is it in std?
470 DeclContext* DC = ExRecord->getDeclContext();
Sebastian Redld8f2e8e2011-03-15 20:41:09 +0000471 DC = DC->getEnclosingNamespaceContext();
472 if (NamespaceDecl* NS = dyn_cast<NamespaceDecl>(DC)) {
Sebastian Redl99439d42011-03-15 19:52:30 +0000473 IdentifierInfo* NSName = NS->getIdentifier();
Sebastian Redld8f2e8e2011-03-15 20:41:09 +0000474 DC = DC->getParent();
Sebastian Redl99439d42011-03-15 19:52:30 +0000475 if (NSName && NSName->getName() == "std" &&
Sebastian Redld8f2e8e2011-03-15 20:41:09 +0000476 DC->getEnclosingNamespaceContext()->isTranslationUnit()) {
Sebastian Redl99439d42011-03-15 19:52:30 +0000477 return false;
Sebastian Redld8f2e8e2011-03-15 20:41:09 +0000478 }
Sebastian Redl99439d42011-03-15 19:52:30 +0000479 }
480 }
481 }
482 }
483 }
484
Sebastian Redl60618fa2011-03-12 11:50:43 +0000485 // At this point, the only remaining valid case is two matching dynamic
486 // specifications. We return here unless both specifications are dynamic.
487 if (OldEST != EST_Dynamic || NewEST != EST_Dynamic) {
Douglas Gregor2eef8292010-03-24 07:14:45 +0000488 if (MissingExceptionSpecification && Old->hasExceptionSpec() &&
Douglas Gregore13ad832010-02-12 07:32:17 +0000489 !New->hasExceptionSpec()) {
Douglas Gregor2eef8292010-03-24 07:14:45 +0000490 // The old type has an exception specification of some sort, but
491 // the new type does not.
492 *MissingExceptionSpecification = true;
493
Sebastian Redl60618fa2011-03-12 11:50:43 +0000494 if (MissingEmptyExceptionSpecification && OldNonThrowing) {
495 // The old type has a throw() or noexcept(true) exception specification
496 // and the new type has no exception specification, and the caller asked
Douglas Gregor2eef8292010-03-24 07:14:45 +0000497 // to handle this itself.
498 *MissingEmptyExceptionSpecification = true;
499 }
500
Douglas Gregore13ad832010-02-12 07:32:17 +0000501 return true;
502 }
503
Sebastian Redldced2262009-10-11 09:03:14 +0000504 Diag(NewLoc, DiagID);
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000505 if (NoteID.getDiagID() != 0)
Sebastian Redldced2262009-10-11 09:03:14 +0000506 Diag(OldLoc, NoteID);
507 return true;
508 }
509
Sebastian Redl60618fa2011-03-12 11:50:43 +0000510 assert(OldEST == EST_Dynamic && NewEST == EST_Dynamic &&
511 "Exception compatibility logic error: non-dynamic spec slipped through.");
512
Sebastian Redldced2262009-10-11 09:03:14 +0000513 bool Success = true;
Sebastian Redl60618fa2011-03-12 11:50:43 +0000514 // Both have a dynamic exception spec. Collect the first set, then compare
Sebastian Redldced2262009-10-11 09:03:14 +0000515 // to the second.
Sebastian Redl1219d152009-10-14 15:06:25 +0000516 llvm::SmallPtrSet<CanQualType, 8> OldTypes, NewTypes;
Sebastian Redldced2262009-10-11 09:03:14 +0000517 for (FunctionProtoType::exception_iterator I = Old->exception_begin(),
518 E = Old->exception_end(); I != E; ++I)
Sebastian Redl1219d152009-10-14 15:06:25 +0000519 OldTypes.insert(Context.getCanonicalType(*I).getUnqualifiedType());
Sebastian Redldced2262009-10-11 09:03:14 +0000520
521 for (FunctionProtoType::exception_iterator I = New->exception_begin(),
Sebastian Redl5db4d902009-10-11 09:11:23 +0000522 E = New->exception_end(); I != E && Success; ++I) {
Sebastian Redl1219d152009-10-14 15:06:25 +0000523 CanQualType TypePtr = Context.getCanonicalType(*I).getUnqualifiedType();
Sebastian Redl5db4d902009-10-11 09:11:23 +0000524 if(OldTypes.count(TypePtr))
525 NewTypes.insert(TypePtr);
526 else
527 Success = false;
528 }
Sebastian Redldced2262009-10-11 09:03:14 +0000529
Sebastian Redl5db4d902009-10-11 09:11:23 +0000530 Success = Success && OldTypes.size() == NewTypes.size();
Sebastian Redldced2262009-10-11 09:03:14 +0000531
532 if (Success) {
533 return false;
534 }
535 Diag(NewLoc, DiagID);
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000536 if (NoteID.getDiagID() != 0)
Sebastian Redldced2262009-10-11 09:03:14 +0000537 Diag(OldLoc, NoteID);
538 return true;
539}
540
541/// CheckExceptionSpecSubset - Check whether the second function type's
542/// exception specification is a subset (or equivalent) of the first function
543/// type. This is used by override and pointer assignment checks.
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000544bool Sema::CheckExceptionSpecSubset(
545 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
Sebastian Redldced2262009-10-11 09:03:14 +0000546 const FunctionProtoType *Superset, SourceLocation SuperLoc,
547 const FunctionProtoType *Subset, SourceLocation SubLoc) {
John McCall811d0be2010-05-28 08:37:35 +0000548
549 // Just auto-succeed under -fno-exceptions.
David Blaikie4e4d0842012-03-11 07:00:24 +0000550 if (!getLangOpts().CXXExceptions)
John McCall811d0be2010-05-28 08:37:35 +0000551 return false;
552
Sebastian Redldced2262009-10-11 09:03:14 +0000553 // FIXME: As usual, we could be more specific in our error messages, but
554 // that better waits until we've got types with source locations.
555
556 if (!SubLoc.isValid())
557 SubLoc = SuperLoc;
558
Richard Smithe6975e92012-04-17 00:58:00 +0000559 // Resolve the exception specifications, if needed.
560 Superset = ResolveExceptionSpec(SuperLoc, Superset);
561 if (!Superset)
562 return false;
563 Subset = ResolveExceptionSpec(SubLoc, Subset);
564 if (!Subset)
565 return false;
566
Sebastian Redl60618fa2011-03-12 11:50:43 +0000567 ExceptionSpecificationType SuperEST = Superset->getExceptionSpecType();
568
Sebastian Redldced2262009-10-11 09:03:14 +0000569 // If superset contains everything, we're done.
Sebastian Redl60618fa2011-03-12 11:50:43 +0000570 if (SuperEST == EST_None || SuperEST == EST_MSAny)
Sebastian Redldced2262009-10-11 09:03:14 +0000571 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
572
Sebastian Redl60618fa2011-03-12 11:50:43 +0000573 // If there are dependent noexcept specs, assume everything is fine. Unlike
574 // with the equivalency check, this is safe in this case, because we don't
575 // want to merge declarations. Checks after instantiation will catch any
576 // omissions we make here.
577 // We also shortcut checking if a noexcept expression was bad.
578
Sebastian Redl8026f6d2011-03-13 17:09:40 +0000579 FunctionProtoType::NoexceptResult SuperNR =Superset->getNoexceptSpec(Context);
Sebastian Redl60618fa2011-03-12 11:50:43 +0000580 if (SuperNR == FunctionProtoType::NR_BadNoexcept ||
581 SuperNR == FunctionProtoType::NR_Dependent)
582 return false;
583
584 // Another case of the superset containing everything.
585 if (SuperNR == FunctionProtoType::NR_Throw)
586 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
587
588 ExceptionSpecificationType SubEST = Subset->getExceptionSpecType();
589
Richard Smithb9d0b762012-07-27 04:22:15 +0000590 assert(!isUnresolvedExceptionSpec(SuperEST) &&
591 !isUnresolvedExceptionSpec(SubEST) &&
Richard Smith7a614d82011-06-11 17:19:42 +0000592 "Shouldn't see unknown exception specifications here");
593
Sebastian Redldced2262009-10-11 09:03:14 +0000594 // It does not. If the subset contains everything, we've failed.
Sebastian Redl60618fa2011-03-12 11:50:43 +0000595 if (SubEST == EST_None || SubEST == EST_MSAny) {
Sebastian Redldced2262009-10-11 09:03:14 +0000596 Diag(SubLoc, DiagID);
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000597 if (NoteID.getDiagID() != 0)
Sebastian Redldced2262009-10-11 09:03:14 +0000598 Diag(SuperLoc, NoteID);
599 return true;
600 }
601
Sebastian Redl8026f6d2011-03-13 17:09:40 +0000602 FunctionProtoType::NoexceptResult SubNR = Subset->getNoexceptSpec(Context);
Sebastian Redl60618fa2011-03-12 11:50:43 +0000603 if (SubNR == FunctionProtoType::NR_BadNoexcept ||
604 SubNR == FunctionProtoType::NR_Dependent)
605 return false;
606
607 // Another case of the subset containing everything.
608 if (SubNR == FunctionProtoType::NR_Throw) {
609 Diag(SubLoc, DiagID);
610 if (NoteID.getDiagID() != 0)
611 Diag(SuperLoc, NoteID);
612 return true;
613 }
614
615 // If the subset contains nothing, we're done.
616 if (SubEST == EST_DynamicNone || SubNR == FunctionProtoType::NR_Nothrow)
617 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
618
619 // Otherwise, if the superset contains nothing, we've failed.
620 if (SuperEST == EST_DynamicNone || SuperNR == FunctionProtoType::NR_Nothrow) {
621 Diag(SubLoc, DiagID);
622 if (NoteID.getDiagID() != 0)
623 Diag(SuperLoc, NoteID);
624 return true;
625 }
626
627 assert(SuperEST == EST_Dynamic && SubEST == EST_Dynamic &&
628 "Exception spec subset: non-dynamic case slipped through.");
629
630 // Neither contains everything or nothing. Do a proper comparison.
Sebastian Redldced2262009-10-11 09:03:14 +0000631 for (FunctionProtoType::exception_iterator SubI = Subset->exception_begin(),
632 SubE = Subset->exception_end(); SubI != SubE; ++SubI) {
633 // Take one type from the subset.
634 QualType CanonicalSubT = Context.getCanonicalType(*SubI);
Sebastian Redlc3a3b7b2009-10-14 14:38:54 +0000635 // Unwrap pointers and references so that we can do checks within a class
636 // hierarchy. Don't unwrap member pointers; they don't have hierarchy
637 // conversions on the pointee.
Sebastian Redldced2262009-10-11 09:03:14 +0000638 bool SubIsPointer = false;
639 if (const ReferenceType *RefTy = CanonicalSubT->getAs<ReferenceType>())
640 CanonicalSubT = RefTy->getPointeeType();
641 if (const PointerType *PtrTy = CanonicalSubT->getAs<PointerType>()) {
642 CanonicalSubT = PtrTy->getPointeeType();
643 SubIsPointer = true;
644 }
645 bool SubIsClass = CanonicalSubT->isRecordType();
Douglas Gregora4923eb2009-11-16 21:35:15 +0000646 CanonicalSubT = CanonicalSubT.getLocalUnqualifiedType();
Sebastian Redldced2262009-10-11 09:03:14 +0000647
648 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
649 /*DetectVirtual=*/false);
650
651 bool Contained = false;
652 // Make sure it's in the superset.
653 for (FunctionProtoType::exception_iterator SuperI =
654 Superset->exception_begin(), SuperE = Superset->exception_end();
655 SuperI != SuperE; ++SuperI) {
656 QualType CanonicalSuperT = Context.getCanonicalType(*SuperI);
657 // SubT must be SuperT or derived from it, or pointer or reference to
658 // such types.
659 if (const ReferenceType *RefTy = CanonicalSuperT->getAs<ReferenceType>())
660 CanonicalSuperT = RefTy->getPointeeType();
661 if (SubIsPointer) {
662 if (const PointerType *PtrTy = CanonicalSuperT->getAs<PointerType>())
663 CanonicalSuperT = PtrTy->getPointeeType();
664 else {
665 continue;
666 }
667 }
Douglas Gregora4923eb2009-11-16 21:35:15 +0000668 CanonicalSuperT = CanonicalSuperT.getLocalUnqualifiedType();
Sebastian Redldced2262009-10-11 09:03:14 +0000669 // If the types are the same, move on to the next type in the subset.
670 if (CanonicalSubT == CanonicalSuperT) {
671 Contained = true;
672 break;
673 }
674
675 // Otherwise we need to check the inheritance.
676 if (!SubIsClass || !CanonicalSuperT->isRecordType())
677 continue;
678
679 Paths.clear();
680 if (!IsDerivedFrom(CanonicalSubT, CanonicalSuperT, Paths))
681 continue;
682
Douglas Gregore0d5fe22010-05-21 20:29:55 +0000683 if (Paths.isAmbiguous(Context.getCanonicalType(CanonicalSuperT)))
Sebastian Redldced2262009-10-11 09:03:14 +0000684 continue;
685
John McCall6b2accb2010-02-10 09:31:12 +0000686 // Do this check from a context without privileges.
John McCall58e6f342010-03-16 05:22:47 +0000687 switch (CheckBaseClassAccess(SourceLocation(),
John McCall6b2accb2010-02-10 09:31:12 +0000688 CanonicalSuperT, CanonicalSubT,
689 Paths.front(),
John McCall58e6f342010-03-16 05:22:47 +0000690 /*Diagnostic*/ 0,
John McCall6b2accb2010-02-10 09:31:12 +0000691 /*ForceCheck*/ true,
John McCall58e6f342010-03-16 05:22:47 +0000692 /*ForceUnprivileged*/ true)) {
John McCall6b2accb2010-02-10 09:31:12 +0000693 case AR_accessible: break;
694 case AR_inaccessible: continue;
695 case AR_dependent:
696 llvm_unreachable("access check dependent for unprivileged context");
John McCall6b2accb2010-02-10 09:31:12 +0000697 case AR_delayed:
698 llvm_unreachable("access check delayed in non-declaration");
John McCall6b2accb2010-02-10 09:31:12 +0000699 }
Sebastian Redldced2262009-10-11 09:03:14 +0000700
701 Contained = true;
702 break;
703 }
704 if (!Contained) {
705 Diag(SubLoc, DiagID);
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000706 if (NoteID.getDiagID() != 0)
Sebastian Redldced2262009-10-11 09:03:14 +0000707 Diag(SuperLoc, NoteID);
708 return true;
709 }
710 }
711 // We've run half the gauntlet.
712 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
713}
714
715static bool CheckSpecForTypesEquivalent(Sema &S,
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000716 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
Sebastian Redldced2262009-10-11 09:03:14 +0000717 QualType Target, SourceLocation TargetLoc,
718 QualType Source, SourceLocation SourceLoc)
719{
720 const FunctionProtoType *TFunc = GetUnderlyingFunction(Target);
721 if (!TFunc)
722 return false;
723 const FunctionProtoType *SFunc = GetUnderlyingFunction(Source);
724 if (!SFunc)
725 return false;
726
727 return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc,
728 SFunc, SourceLoc);
729}
730
731/// CheckParamExceptionSpec - Check if the parameter and return types of the
732/// two functions have equivalent exception specs. This is part of the
733/// assignment and override compatibility check. We do not check the parameters
734/// of parameter function pointers recursively, as no sane programmer would
735/// even be able to write such a function type.
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000736bool Sema::CheckParamExceptionSpec(const PartialDiagnostic & NoteID,
Sebastian Redldced2262009-10-11 09:03:14 +0000737 const FunctionProtoType *Target, SourceLocation TargetLoc,
738 const FunctionProtoType *Source, SourceLocation SourceLoc)
739{
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000740 if (CheckSpecForTypesEquivalent(*this,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000741 PDiag(diag::err_deep_exception_specs_differ) << 0,
742 PDiag(),
Sebastian Redldced2262009-10-11 09:03:14 +0000743 Target->getResultType(), TargetLoc,
744 Source->getResultType(), SourceLoc))
745 return true;
746
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000747 // We shouldn't even be testing this unless the arguments are otherwise
Sebastian Redldced2262009-10-11 09:03:14 +0000748 // compatible.
749 assert(Target->getNumArgs() == Source->getNumArgs() &&
750 "Functions have different argument counts.");
751 for (unsigned i = 0, E = Target->getNumArgs(); i != E; ++i) {
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000752 if (CheckSpecForTypesEquivalent(*this,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000753 PDiag(diag::err_deep_exception_specs_differ) << 1,
754 PDiag(),
Sebastian Redldced2262009-10-11 09:03:14 +0000755 Target->getArgType(i), TargetLoc,
756 Source->getArgType(i), SourceLoc))
757 return true;
758 }
759 return false;
760}
761
762bool Sema::CheckExceptionSpecCompatibility(Expr *From, QualType ToType)
763{
764 // First we check for applicability.
765 // Target type must be a function, function pointer or function reference.
766 const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType);
767 if (!ToFunc)
768 return false;
769
770 // SourceType must be a function or function pointer.
771 const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType());
772 if (!FromFunc)
773 return false;
774
775 // Now we've got the correct types on both sides, check their compatibility.
776 // This means that the source of the conversion can only throw a subset of
777 // the exceptions of the target, and any exception specs on arguments or
778 // return types must be equivalent.
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000779 return CheckExceptionSpecSubset(PDiag(diag::err_incompatible_exception_specs),
780 PDiag(), ToFunc,
781 From->getSourceRange().getBegin(),
Sebastian Redldced2262009-10-11 09:03:14 +0000782 FromFunc, SourceLocation());
783}
784
785bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
786 const CXXMethodDecl *Old) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000787 if (getLangOpts().CPlusPlus0x && isa<CXXDestructorDecl>(New)) {
Sebastian Redla0448262011-05-20 05:57:18 +0000788 // Don't check uninstantiated template destructors at all. We can only
789 // synthesize correct specs after the template is instantiated.
790 if (New->getParent()->isDependentType())
791 return false;
792 if (New->getParent()->isBeingDefined()) {
793 // The destructor might be updated once the definition is finished. So
794 // remember it and check later.
795 DelayedDestructorExceptionSpecChecks.push_back(std::make_pair(
796 cast<CXXDestructorDecl>(New), cast<CXXDestructorDecl>(Old)));
797 return false;
798 }
Sebastian Redl0ee33912011-05-19 05:13:44 +0000799 }
Francois Pichet0f161592011-05-24 02:11:43 +0000800 unsigned DiagID = diag::err_override_exception_spec;
David Blaikie4e4d0842012-03-11 07:00:24 +0000801 if (getLangOpts().MicrosoftExt)
Francois Pichet0f161592011-05-24 02:11:43 +0000802 DiagID = diag::warn_override_exception_spec;
803 return CheckExceptionSpecSubset(PDiag(DiagID),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000804 PDiag(diag::note_overridden_virtual_function),
Sebastian Redldced2262009-10-11 09:03:14 +0000805 Old->getType()->getAs<FunctionProtoType>(),
806 Old->getLocation(),
807 New->getType()->getAs<FunctionProtoType>(),
808 New->getLocation());
809}
810
Richard Smithe6975e92012-04-17 00:58:00 +0000811static CanThrowResult canSubExprsThrow(Sema &S, const Expr *CE) {
812 Expr *E = const_cast<Expr*>(CE);
813 CanThrowResult R = CT_Cannot;
814 for (Expr::child_range I = E->children(); I && R != CT_Can; ++I)
815 R = mergeCanThrow(R, S.canThrow(cast<Expr>(*I)));
816 return R;
817}
818
819static CanThrowResult canCalleeThrow(Sema &S, const Expr *E,
820 const Decl *D,
821 bool NullThrows = true) {
822 if (!D)
823 return NullThrows ? CT_Can : CT_Cannot;
824
825 // See if we can get a function type from the decl somehow.
826 const ValueDecl *VD = dyn_cast<ValueDecl>(D);
827 if (!VD) // If we have no clue what we're calling, assume the worst.
828 return CT_Can;
829
830 // As an extension, we assume that __attribute__((nothrow)) functions don't
831 // throw.
832 if (isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())
833 return CT_Cannot;
834
835 QualType T = VD->getType();
836 const FunctionProtoType *FT;
837 if ((FT = T->getAs<FunctionProtoType>())) {
838 } else if (const PointerType *PT = T->getAs<PointerType>())
839 FT = PT->getPointeeType()->getAs<FunctionProtoType>();
840 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
841 FT = RT->getPointeeType()->getAs<FunctionProtoType>();
842 else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
843 FT = MT->getPointeeType()->getAs<FunctionProtoType>();
844 else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
845 FT = BT->getPointeeType()->getAs<FunctionProtoType>();
846
847 if (!FT)
848 return CT_Can;
849
850 FT = S.ResolveExceptionSpec(E->getLocStart(), FT);
851 if (!FT)
852 return CT_Can;
853
Richard Smithe6975e92012-04-17 00:58:00 +0000854 return FT->isNothrow(S.Context) ? CT_Cannot : CT_Can;
855}
856
857static CanThrowResult canDynamicCastThrow(const CXXDynamicCastExpr *DC) {
858 if (DC->isTypeDependent())
859 return CT_Dependent;
860
861 if (!DC->getTypeAsWritten()->isReferenceType())
862 return CT_Cannot;
863
864 if (DC->getSubExpr()->isTypeDependent())
865 return CT_Dependent;
866
867 return DC->getCastKind() == clang::CK_Dynamic? CT_Can : CT_Cannot;
868}
869
870static CanThrowResult canTypeidThrow(Sema &S, const CXXTypeidExpr *DC) {
871 if (DC->isTypeOperand())
872 return CT_Cannot;
873
874 Expr *Op = DC->getExprOperand();
875 if (Op->isTypeDependent())
876 return CT_Dependent;
877
878 const RecordType *RT = Op->getType()->getAs<RecordType>();
879 if (!RT)
880 return CT_Cannot;
881
882 if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
883 return CT_Cannot;
884
885 if (Op->Classify(S.Context).isPRValue())
886 return CT_Cannot;
887
888 return CT_Can;
889}
890
891CanThrowResult Sema::canThrow(const Expr *E) {
892 // C++ [expr.unary.noexcept]p3:
893 // [Can throw] if in a potentially-evaluated context the expression would
894 // contain:
895 switch (E->getStmtClass()) {
896 case Expr::CXXThrowExprClass:
897 // - a potentially evaluated throw-expression
898 return CT_Can;
899
900 case Expr::CXXDynamicCastExprClass: {
901 // - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
902 // where T is a reference type, that requires a run-time check
903 CanThrowResult CT = canDynamicCastThrow(cast<CXXDynamicCastExpr>(E));
904 if (CT == CT_Can)
905 return CT;
906 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
907 }
908
909 case Expr::CXXTypeidExprClass:
910 // - a potentially evaluated typeid expression applied to a glvalue
911 // expression whose type is a polymorphic class type
912 return canTypeidThrow(*this, cast<CXXTypeidExpr>(E));
913
914 // - a potentially evaluated call to a function, member function, function
915 // pointer, or member function pointer that does not have a non-throwing
916 // exception-specification
917 case Expr::CallExprClass:
918 case Expr::CXXMemberCallExprClass:
919 case Expr::CXXOperatorCallExprClass:
920 case Expr::UserDefinedLiteralClass: {
921 const CallExpr *CE = cast<CallExpr>(E);
922 CanThrowResult CT;
923 if (E->isTypeDependent())
924 CT = CT_Dependent;
925 else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens()))
926 CT = CT_Cannot;
927 else
928 CT = canCalleeThrow(*this, E, CE->getCalleeDecl());
929 if (CT == CT_Can)
930 return CT;
931 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
932 }
933
934 case Expr::CXXConstructExprClass:
935 case Expr::CXXTemporaryObjectExprClass: {
936 CanThrowResult CT = canCalleeThrow(*this, E,
937 cast<CXXConstructExpr>(E)->getConstructor());
938 if (CT == CT_Can)
939 return CT;
940 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
941 }
942
943 case Expr::LambdaExprClass: {
944 const LambdaExpr *Lambda = cast<LambdaExpr>(E);
945 CanThrowResult CT = CT_Cannot;
946 for (LambdaExpr::capture_init_iterator Cap = Lambda->capture_init_begin(),
947 CapEnd = Lambda->capture_init_end();
948 Cap != CapEnd; ++Cap)
949 CT = mergeCanThrow(CT, canThrow(*Cap));
950 return CT;
951 }
952
953 case Expr::CXXNewExprClass: {
954 CanThrowResult CT;
955 if (E->isTypeDependent())
956 CT = CT_Dependent;
957 else
958 CT = canCalleeThrow(*this, E, cast<CXXNewExpr>(E)->getOperatorNew());
959 if (CT == CT_Can)
960 return CT;
961 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
962 }
963
964 case Expr::CXXDeleteExprClass: {
965 CanThrowResult CT;
966 QualType DTy = cast<CXXDeleteExpr>(E)->getDestroyedType();
967 if (DTy.isNull() || DTy->isDependentType()) {
968 CT = CT_Dependent;
969 } else {
970 CT = canCalleeThrow(*this, E,
971 cast<CXXDeleteExpr>(E)->getOperatorDelete());
972 if (const RecordType *RT = DTy->getAs<RecordType>()) {
973 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
974 CT = mergeCanThrow(CT, canCalleeThrow(*this, E, RD->getDestructor()));
975 }
976 if (CT == CT_Can)
977 return CT;
978 }
979 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
980 }
981
982 case Expr::CXXBindTemporaryExprClass: {
983 // The bound temporary has to be destroyed again, which might throw.
984 CanThrowResult CT = canCalleeThrow(*this, E,
985 cast<CXXBindTemporaryExpr>(E)->getTemporary()->getDestructor());
986 if (CT == CT_Can)
987 return CT;
988 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
989 }
990
991 // ObjC message sends are like function calls, but never have exception
992 // specs.
993 case Expr::ObjCMessageExprClass:
994 case Expr::ObjCPropertyRefExprClass:
995 case Expr::ObjCSubscriptRefExprClass:
996 return CT_Can;
997
998 // All the ObjC literals that are implemented as calls are
999 // potentially throwing unless we decide to close off that
1000 // possibility.
1001 case Expr::ObjCArrayLiteralClass:
1002 case Expr::ObjCDictionaryLiteralClass:
Patrick Beardeb382ec2012-04-19 00:25:12 +00001003 case Expr::ObjCBoxedExprClass:
Richard Smithe6975e92012-04-17 00:58:00 +00001004 return CT_Can;
1005
1006 // Many other things have subexpressions, so we have to test those.
1007 // Some are simple:
1008 case Expr::ConditionalOperatorClass:
1009 case Expr::CompoundLiteralExprClass:
1010 case Expr::CXXConstCastExprClass:
1011 case Expr::CXXDefaultArgExprClass:
1012 case Expr::CXXReinterpretCastExprClass:
1013 case Expr::DesignatedInitExprClass:
1014 case Expr::ExprWithCleanupsClass:
1015 case Expr::ExtVectorElementExprClass:
1016 case Expr::InitListExprClass:
1017 case Expr::MemberExprClass:
1018 case Expr::ObjCIsaExprClass:
1019 case Expr::ObjCIvarRefExprClass:
1020 case Expr::ParenExprClass:
1021 case Expr::ParenListExprClass:
1022 case Expr::ShuffleVectorExprClass:
1023 case Expr::VAArgExprClass:
1024 return canSubExprsThrow(*this, E);
1025
1026 // Some might be dependent for other reasons.
1027 case Expr::ArraySubscriptExprClass:
1028 case Expr::BinaryOperatorClass:
1029 case Expr::CompoundAssignOperatorClass:
1030 case Expr::CStyleCastExprClass:
1031 case Expr::CXXStaticCastExprClass:
1032 case Expr::CXXFunctionalCastExprClass:
1033 case Expr::ImplicitCastExprClass:
1034 case Expr::MaterializeTemporaryExprClass:
1035 case Expr::UnaryOperatorClass: {
1036 CanThrowResult CT = E->isTypeDependent() ? CT_Dependent : CT_Cannot;
1037 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1038 }
1039
1040 // FIXME: We should handle StmtExpr, but that opens a MASSIVE can of worms.
1041 case Expr::StmtExprClass:
1042 return CT_Can;
1043
1044 case Expr::ChooseExprClass:
1045 if (E->isTypeDependent() || E->isValueDependent())
1046 return CT_Dependent;
1047 return canThrow(cast<ChooseExpr>(E)->getChosenSubExpr(Context));
1048
1049 case Expr::GenericSelectionExprClass:
1050 if (cast<GenericSelectionExpr>(E)->isResultDependent())
1051 return CT_Dependent;
1052 return canThrow(cast<GenericSelectionExpr>(E)->getResultExpr());
1053
1054 // Some expressions are always dependent.
1055 case Expr::CXXDependentScopeMemberExprClass:
1056 case Expr::CXXUnresolvedConstructExprClass:
1057 case Expr::DependentScopeDeclRefExprClass:
1058 return CT_Dependent;
1059
1060 case Expr::AsTypeExprClass:
1061 case Expr::BinaryConditionalOperatorClass:
1062 case Expr::BlockExprClass:
1063 case Expr::CUDAKernelCallExprClass:
1064 case Expr::DeclRefExprClass:
1065 case Expr::ObjCBridgedCastExprClass:
1066 case Expr::ObjCIndirectCopyRestoreExprClass:
1067 case Expr::ObjCProtocolExprClass:
1068 case Expr::ObjCSelectorExprClass:
1069 case Expr::OffsetOfExprClass:
1070 case Expr::PackExpansionExprClass:
1071 case Expr::PseudoObjectExprClass:
1072 case Expr::SubstNonTypeTemplateParmExprClass:
1073 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smith9a4db032012-09-12 00:56:43 +00001074 case Expr::FunctionParmPackExprClass:
Richard Smithe6975e92012-04-17 00:58:00 +00001075 case Expr::UnaryExprOrTypeTraitExprClass:
1076 case Expr::UnresolvedLookupExprClass:
1077 case Expr::UnresolvedMemberExprClass:
1078 // FIXME: Can any of the above throw? If so, when?
1079 return CT_Cannot;
1080
1081 case Expr::AddrLabelExprClass:
1082 case Expr::ArrayTypeTraitExprClass:
1083 case Expr::AtomicExprClass:
1084 case Expr::BinaryTypeTraitExprClass:
1085 case Expr::TypeTraitExprClass:
1086 case Expr::CXXBoolLiteralExprClass:
1087 case Expr::CXXNoexceptExprClass:
1088 case Expr::CXXNullPtrLiteralExprClass:
1089 case Expr::CXXPseudoDestructorExprClass:
1090 case Expr::CXXScalarValueInitExprClass:
1091 case Expr::CXXThisExprClass:
1092 case Expr::CXXUuidofExprClass:
1093 case Expr::CharacterLiteralClass:
1094 case Expr::ExpressionTraitExprClass:
1095 case Expr::FloatingLiteralClass:
1096 case Expr::GNUNullExprClass:
1097 case Expr::ImaginaryLiteralClass:
1098 case Expr::ImplicitValueInitExprClass:
1099 case Expr::IntegerLiteralClass:
1100 case Expr::ObjCEncodeExprClass:
1101 case Expr::ObjCStringLiteralClass:
1102 case Expr::ObjCBoolLiteralExprClass:
1103 case Expr::OpaqueValueExprClass:
1104 case Expr::PredefinedExprClass:
1105 case Expr::SizeOfPackExprClass:
1106 case Expr::StringLiteralClass:
1107 case Expr::UnaryTypeTraitExprClass:
1108 // These expressions can never throw.
1109 return CT_Cannot;
1110
1111#define STMT(CLASS, PARENT) case Expr::CLASS##Class:
1112#define STMT_RANGE(Base, First, Last)
1113#define LAST_STMT_RANGE(BASE, FIRST, LAST)
1114#define EXPR(CLASS, PARENT)
1115#define ABSTRACT_STMT(STMT)
1116#include "clang/AST/StmtNodes.inc"
1117 case Expr::NoStmtClass:
1118 llvm_unreachable("Invalid class for expression");
1119 }
1120 llvm_unreachable("Bogus StmtClass");
1121}
1122
Sebastian Redldced2262009-10-11 09:03:14 +00001123} // end namespace clang