blob: 1d21b9760c78a4c10d5f78c62298ed67c578922c [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"
23
24namespace clang {
25
26static const FunctionProtoType *GetUnderlyingFunction(QualType T)
27{
28 if (const PointerType *PtrTy = T->getAs<PointerType>())
29 T = PtrTy->getPointeeType();
30 else if (const ReferenceType *RefTy = T->getAs<ReferenceType>())
31 T = RefTy->getPointeeType();
Sebastian Redlc3a3b7b2009-10-14 14:38:54 +000032 else if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
33 T = MPTy->getPointeeType();
Sebastian Redldced2262009-10-11 09:03:14 +000034 return T->getAs<FunctionProtoType>();
35}
36
37/// CheckSpecifiedExceptionType - Check if the given type is valid in an
38/// exception specification. Incomplete types, or pointers to incomplete types
39/// other than void are not allowed.
40bool Sema::CheckSpecifiedExceptionType(QualType T, const SourceRange &Range) {
Sebastian Redldced2262009-10-11 09:03:14 +000041
Douglas Gregor0966f352009-12-10 18:13:52 +000042 // This check (and the similar one below) deals with issue 437, that changes
43 // C++ 9.2p2 this way:
44 // Within the class member-specification, the class is regarded as complete
45 // within function bodies, default arguments, exception-specifications, and
46 // constructor ctor-initializers (including such things in nested classes).
47 if (T->isRecordType() && T->getAs<RecordType>()->isBeingDefined())
48 return false;
49
Sebastian Redldced2262009-10-11 09:03:14 +000050 // C++ 15.4p2: A type denoted in an exception-specification shall not denote
51 // an incomplete type.
Sebastian Redl491b84c2009-10-14 14:59:48 +000052 if (RequireCompleteType(Range.getBegin(), T,
53 PDiag(diag::err_incomplete_in_exception_spec) << /*direct*/0 << Range))
54 return true;
Sebastian Redldced2262009-10-11 09:03:14 +000055
56 // C++ 15.4p2: A type denoted in an exception-specification shall not denote
57 // an incomplete type a pointer or reference to an incomplete type, other
58 // than (cv) void*.
59 int kind;
60 if (const PointerType* IT = T->getAs<PointerType>()) {
61 T = IT->getPointeeType();
62 kind = 1;
63 } else if (const ReferenceType* IT = T->getAs<ReferenceType>()) {
64 T = IT->getPointeeType();
65 kind = 2;
66 } else
67 return false;
68
Douglas Gregor0966f352009-12-10 18:13:52 +000069 // Again as before
70 if (T->isRecordType() && T->getAs<RecordType>()->isBeingDefined())
71 return false;
72
Sebastian Redl491b84c2009-10-14 14:59:48 +000073 if (!T->isVoidType() && RequireCompleteType(Range.getBegin(), T,
Douglas Gregor0966f352009-12-10 18:13:52 +000074 PDiag(diag::err_incomplete_in_exception_spec) << kind << Range))
Sebastian Redl491b84c2009-10-14 14:59:48 +000075 return true;
Sebastian Redldced2262009-10-11 09:03:14 +000076
77 return false;
78}
79
80/// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer
81/// to member to a function with an exception specification. This means that
82/// it is invalid to add another level of indirection.
83bool Sema::CheckDistantExceptionSpec(QualType T) {
84 if (const PointerType *PT = T->getAs<PointerType>())
85 T = PT->getPointeeType();
86 else if (const MemberPointerType *PT = T->getAs<MemberPointerType>())
87 T = PT->getPointeeType();
88 else
89 return false;
90
91 const FunctionProtoType *FnT = T->getAs<FunctionProtoType>();
92 if (!FnT)
93 return false;
94
95 return FnT->hasExceptionSpec();
96}
97
Douglas Gregore13ad832010-02-12 07:32:17 +000098bool Sema::CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New) {
Sebastian Redl99439d42011-03-15 19:52:30 +000099 OverloadedOperatorKind OO = New->getDeclName().getCXXOverloadedOperator();
100 bool IsOperatorNew = OO == OO_New || OO == OO_Array_New;
Douglas Gregor2eef8292010-03-24 07:14:45 +0000101 bool MissingExceptionSpecification = false;
Douglas Gregore13ad832010-02-12 07:32:17 +0000102 bool MissingEmptyExceptionSpecification = false;
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000103 if (!CheckEquivalentExceptionSpec(PDiag(diag::err_mismatched_exception_spec),
104 PDiag(diag::note_previous_declaration),
Douglas Gregore13ad832010-02-12 07:32:17 +0000105 Old->getType()->getAs<FunctionProtoType>(),
106 Old->getLocation(),
107 New->getType()->getAs<FunctionProtoType>(),
108 New->getLocation(),
Douglas Gregor2eef8292010-03-24 07:14:45 +0000109 &MissingExceptionSpecification,
Sebastian Redl60618fa2011-03-12 11:50:43 +0000110 &MissingEmptyExceptionSpecification,
Sebastian Redl99439d42011-03-15 19:52:30 +0000111 /*AllowNoexceptAllMatchWithNoSpec=*/true,
112 IsOperatorNew))
Douglas Gregore13ad832010-02-12 07:32:17 +0000113 return false;
114
115 // The failure was something other than an empty exception
116 // specification; return an error.
Douglas Gregor2eef8292010-03-24 07:14:45 +0000117 if (!MissingExceptionSpecification && !MissingEmptyExceptionSpecification)
Douglas Gregore13ad832010-02-12 07:32:17 +0000118 return true;
119
John McCalle23cf432010-12-14 08:05:40 +0000120 const FunctionProtoType *NewProto
121 = New->getType()->getAs<FunctionProtoType>();
122
Douglas Gregore13ad832010-02-12 07:32:17 +0000123 // The new function declaration is only missing an empty exception
124 // specification "throw()". If the throw() specification came from a
125 // function in a system header that has C linkage, just add an empty
126 // exception specification to the "new" declaration. This is an
127 // egregious workaround for glibc, which adds throw() specifications
128 // to many libc functions as an optimization. Unfortunately, that
129 // optimization isn't permitted by the C++ standard, so we're forced
130 // to work around it here.
John McCalle23cf432010-12-14 08:05:40 +0000131 if (MissingEmptyExceptionSpecification && NewProto &&
Douglas Gregor2eef8292010-03-24 07:14:45 +0000132 (Old->getLocation().isInvalid() ||
133 Context.getSourceManager().isInSystemHeader(Old->getLocation())) &&
Douglas Gregore13ad832010-02-12 07:32:17 +0000134 Old->isExternC()) {
John McCalle23cf432010-12-14 08:05:40 +0000135 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
Sebastian Redl60618fa2011-03-12 11:50:43 +0000136 EPI.ExceptionSpecType = EST_DynamicNone;
Douglas Gregore13ad832010-02-12 07:32:17 +0000137 QualType NewType = Context.getFunctionType(NewProto->getResultType(),
138 NewProto->arg_type_begin(),
139 NewProto->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +0000140 EPI);
Douglas Gregore13ad832010-02-12 07:32:17 +0000141 New->setType(NewType);
142 return false;
143 }
144
John McCalle23cf432010-12-14 08:05:40 +0000145 if (MissingExceptionSpecification && NewProto) {
Douglas Gregor2eef8292010-03-24 07:14:45 +0000146 const FunctionProtoType *OldProto
147 = Old->getType()->getAs<FunctionProtoType>();
148
John McCalle23cf432010-12-14 08:05:40 +0000149 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
Sebastian Redl60618fa2011-03-12 11:50:43 +0000150 EPI.ExceptionSpecType = OldProto->getExceptionSpecType();
151 if (EPI.ExceptionSpecType == EST_Dynamic) {
152 EPI.NumExceptions = OldProto->getNumExceptions();
153 EPI.Exceptions = OldProto->exception_begin();
154 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
155 // FIXME: We can't just take the expression from the old prototype. It
156 // likely contains references to the old prototype's parameters.
157 }
John McCalle23cf432010-12-14 08:05:40 +0000158
Douglas Gregor2eef8292010-03-24 07:14:45 +0000159 // Update the type of the function with the appropriate exception
160 // specification.
161 QualType NewType = Context.getFunctionType(NewProto->getResultType(),
162 NewProto->arg_type_begin(),
163 NewProto->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +0000164 EPI);
Douglas Gregor2eef8292010-03-24 07:14:45 +0000165 New->setType(NewType);
166
167 // If exceptions are disabled, suppress the warning about missing
168 // exception specifications for new and delete operators.
John McCall018591f2011-03-02 02:04:40 +0000169 if (!getLangOptions().CXXExceptions) {
Douglas Gregor2eef8292010-03-24 07:14:45 +0000170 switch (New->getDeclName().getCXXOverloadedOperator()) {
171 case OO_New:
172 case OO_Array_New:
173 case OO_Delete:
174 case OO_Array_Delete:
175 if (New->getDeclContext()->isTranslationUnit())
176 return false;
177 break;
178
179 default:
180 break;
181 }
182 }
183
184 // Warn about the lack of exception specification.
185 llvm::SmallString<128> ExceptionSpecString;
186 llvm::raw_svector_ostream OS(ExceptionSpecString);
Sebastian Redl60618fa2011-03-12 11:50:43 +0000187 switch (OldProto->getExceptionSpecType()) {
188 case EST_DynamicNone:
189 OS << "throw()";
190 break;
191
192 case EST_Dynamic: {
193 OS << "throw(";
194 bool OnFirstException = true;
195 for (FunctionProtoType::exception_iterator E = OldProto->exception_begin(),
196 EEnd = OldProto->exception_end();
197 E != EEnd;
198 ++E) {
199 if (OnFirstException)
200 OnFirstException = false;
201 else
202 OS << ", ";
203
204 OS << E->getAsString(Context.PrintingPolicy);
205 }
206 OS << ")";
207 break;
Douglas Gregor2eef8292010-03-24 07:14:45 +0000208 }
Sebastian Redl60618fa2011-03-12 11:50:43 +0000209
210 case EST_BasicNoexcept:
211 OS << "noexcept";
212 break;
213
214 case EST_ComputedNoexcept:
215 OS << "noexcept(";
216 OldProto->getNoexceptExpr()->printPretty(OS, Context, 0,
217 Context.PrintingPolicy);
218 OS << ")";
219 break;
220
221 default:
222 assert(false && "This spec type is compatible with none.");
223 }
Douglas Gregor2eef8292010-03-24 07:14:45 +0000224 OS.flush();
225
Abramo Bagnara796aa442011-03-12 11:17:06 +0000226 SourceLocation FixItLoc;
Douglas Gregor2eef8292010-03-24 07:14:45 +0000227 if (TypeSourceInfo *TSInfo = New->getTypeSourceInfo()) {
Abramo Bagnara723df242010-12-14 22:11:44 +0000228 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
Douglas Gregor2eef8292010-03-24 07:14:45 +0000229 if (const FunctionTypeLoc *FTLoc = dyn_cast<FunctionTypeLoc>(&TL))
Abramo Bagnara796aa442011-03-12 11:17:06 +0000230 FixItLoc = PP.getLocForEndOfToken(FTLoc->getLocalRangeEnd());
Douglas Gregor2eef8292010-03-24 07:14:45 +0000231 }
232
Abramo Bagnara796aa442011-03-12 11:17:06 +0000233 if (FixItLoc.isInvalid())
Douglas Gregor2eef8292010-03-24 07:14:45 +0000234 Diag(New->getLocation(), diag::warn_missing_exception_specification)
235 << New << OS.str();
236 else {
237 // FIXME: This will get more complicated with C++0x
238 // late-specified return types.
239 Diag(New->getLocation(), diag::warn_missing_exception_specification)
240 << New << OS.str()
Abramo Bagnara796aa442011-03-12 11:17:06 +0000241 << FixItHint::CreateInsertion(FixItLoc, " " + OS.str().str());
Douglas Gregor2eef8292010-03-24 07:14:45 +0000242 }
243
244 if (!Old->getLocation().isInvalid())
245 Diag(Old->getLocation(), diag::note_previous_declaration);
246
247 return false;
248 }
249
Douglas Gregore13ad832010-02-12 07:32:17 +0000250 Diag(New->getLocation(), diag::err_mismatched_exception_spec);
251 Diag(Old->getLocation(), diag::note_previous_declaration);
252 return true;
253}
254
Sebastian Redldced2262009-10-11 09:03:14 +0000255/// CheckEquivalentExceptionSpec - Check if the two types have equivalent
256/// exception specifications. Exception specifications are equivalent if
257/// they allow exactly the same set of exception types. It does not matter how
258/// that is achieved. See C++ [except.spec]p2.
259bool Sema::CheckEquivalentExceptionSpec(
260 const FunctionProtoType *Old, SourceLocation OldLoc,
261 const FunctionProtoType *New, SourceLocation NewLoc) {
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000262 return CheckEquivalentExceptionSpec(
263 PDiag(diag::err_mismatched_exception_spec),
264 PDiag(diag::note_previous_declaration),
Sebastian Redldced2262009-10-11 09:03:14 +0000265 Old, OldLoc, New, NewLoc);
266}
267
Sebastian Redl60618fa2011-03-12 11:50:43 +0000268/// CheckEquivalentExceptionSpec - Check if the two types have compatible
269/// exception specifications. See C++ [except.spec]p3.
270bool Sema::CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
Douglas Gregor2eef8292010-03-24 07:14:45 +0000271 const PartialDiagnostic & NoteID,
Sebastian Redl60618fa2011-03-12 11:50:43 +0000272 const FunctionProtoType *Old,
Douglas Gregor2eef8292010-03-24 07:14:45 +0000273 SourceLocation OldLoc,
Sebastian Redl60618fa2011-03-12 11:50:43 +0000274 const FunctionProtoType *New,
Douglas Gregor2eef8292010-03-24 07:14:45 +0000275 SourceLocation NewLoc,
276 bool *MissingExceptionSpecification,
Sebastian Redl60618fa2011-03-12 11:50:43 +0000277 bool*MissingEmptyExceptionSpecification,
Sebastian Redl99439d42011-03-15 19:52:30 +0000278 bool AllowNoexceptAllMatchWithNoSpec,
279 bool IsOperatorNew) {
John McCall811d0be2010-05-28 08:37:35 +0000280 // Just completely ignore this under -fno-exceptions.
John McCall018591f2011-03-02 02:04:40 +0000281 if (!getLangOptions().CXXExceptions)
John McCall811d0be2010-05-28 08:37:35 +0000282 return false;
283
Douglas Gregor2eef8292010-03-24 07:14:45 +0000284 if (MissingExceptionSpecification)
285 *MissingExceptionSpecification = false;
286
Douglas Gregore13ad832010-02-12 07:32:17 +0000287 if (MissingEmptyExceptionSpecification)
288 *MissingEmptyExceptionSpecification = false;
289
Sebastian Redl60618fa2011-03-12 11:50:43 +0000290 // C++0x [except.spec]p3: Two exception-specifications are compatible if:
291 // - both are non-throwing, regardless of their form,
292 // - both have the form noexcept(constant-expression) and the constant-
293 // expressions are equivalent,
294 // - one exception-specification is a noexcept-specification allowing all
295 // exceptions and the other is of the form throw(type-id-list), or
296 // - both are dynamic-exception-specifications that have the same set of
297 // adjusted types.
298 //
299 // C++0x [except.spec]p12: An exception-specifcation is non-throwing if it is
300 // of the form throw(), noexcept, or noexcept(constant-expression) where the
301 // constant-expression yields true.
302 //
303 // CWG 1073 Proposed resolution: Strike the third bullet above.
304 //
305 // C++0x [except.spec]p4: If any declaration of a function has an exception-
306 // specifier that is not a noexcept-specification allowing all exceptions,
307 // all declarations [...] of that function shall have a compatible
308 // exception-specification.
309 //
310 // That last point basically means that noexcept(false) matches no spec.
311 // It's considered when AllowNoexceptAllMatchWithNoSpec is true.
312
313 ExceptionSpecificationType OldEST = Old->getExceptionSpecType();
314 ExceptionSpecificationType NewEST = New->getExceptionSpecType();
315
316 // Shortcut the case where both have no spec.
317 if (OldEST == EST_None && NewEST == EST_None)
318 return false;
319
Sebastian Redl8026f6d2011-03-13 17:09:40 +0000320 FunctionProtoType::NoexceptResult OldNR = Old->getNoexceptSpec(Context);
321 FunctionProtoType::NoexceptResult NewNR = New->getNoexceptSpec(Context);
Sebastian Redl60618fa2011-03-12 11:50:43 +0000322 if (OldNR == FunctionProtoType::NR_BadNoexcept ||
323 NewNR == FunctionProtoType::NR_BadNoexcept)
324 return false;
325
326 // Dependent noexcept specifiers are compatible with each other, but nothing
327 // else.
328 // One noexcept is compatible with another if the argument is the same
329 if (OldNR == NewNR &&
330 OldNR != FunctionProtoType::NR_NoNoexcept &&
331 NewNR != FunctionProtoType::NR_NoNoexcept)
332 return false;
333 if (OldNR != NewNR &&
334 OldNR != FunctionProtoType::NR_NoNoexcept &&
335 NewNR != FunctionProtoType::NR_NoNoexcept) {
336 Diag(NewLoc, DiagID);
337 if (NoteID.getDiagID() != 0)
338 Diag(OldLoc, NoteID);
339 return true;
Douglas Gregor5b6f7692010-08-30 15:04:51 +0000340 }
341
Sebastian Redl60618fa2011-03-12 11:50:43 +0000342 if (getLangOptions().Microsoft) {
343 // Treat throw(whatever) as throw(...) to be compatible with MS headers.
344 if (OldEST == EST_Dynamic)
345 OldEST = EST_MSAny;
346 if (NewEST == EST_Dynamic)
347 NewEST = EST_MSAny;
348 }
349
350 // The MS extension throw(...) is compatible with itself.
351 if (OldEST == EST_MSAny && NewEST == EST_MSAny)
Sebastian Redldced2262009-10-11 09:03:14 +0000352 return false;
Sebastian Redl60618fa2011-03-12 11:50:43 +0000353
354 // It's also compatible with no spec.
355 if ((OldEST == EST_None && NewEST == EST_MSAny) ||
356 (OldEST == EST_MSAny && NewEST == EST_None))
357 return false;
358
359 // It's also compatible with noexcept(false).
360 if (OldEST == EST_MSAny && NewNR == FunctionProtoType::NR_Throw)
361 return false;
362 if (NewEST == EST_MSAny && OldNR == FunctionProtoType::NR_Throw)
363 return false;
364
365 // As described above, noexcept(false) matches no spec only for functions.
366 if (AllowNoexceptAllMatchWithNoSpec) {
367 if (OldEST == EST_None && NewNR == FunctionProtoType::NR_Throw)
368 return false;
369 if (NewEST == EST_None && OldNR == FunctionProtoType::NR_Throw)
370 return false;
371 }
372
373 // Any non-throwing specifications are compatible.
374 bool OldNonThrowing = OldNR == FunctionProtoType::NR_Nothrow ||
375 OldEST == EST_DynamicNone;
376 bool NewNonThrowing = NewNR == FunctionProtoType::NR_Nothrow ||
377 NewEST == EST_DynamicNone;
378 if (OldNonThrowing && NewNonThrowing)
379 return false;
380
Sebastian Redl99439d42011-03-15 19:52:30 +0000381 // As a special compatibility feature, under C++0x we accept no spec and
382 // throw(std::bad_alloc) as equivalent for operator new and operator new[].
383 // This is because the implicit declaration changed, but old code would break.
384 if (getLangOptions().CPlusPlus0x && IsOperatorNew) {
385 const FunctionProtoType *WithExceptions = 0;
386 if (OldEST == EST_None && NewEST == EST_Dynamic)
387 WithExceptions = New;
388 else if (OldEST == EST_Dynamic && NewEST == EST_None)
389 WithExceptions = Old;
390 if (WithExceptions && WithExceptions->getNumExceptions() == 1) {
391 // One has no spec, the other throw(something). If that something is
392 // std::bad_alloc, all conditions are met.
393 QualType Exception = *WithExceptions->exception_begin();
394 if (CXXRecordDecl *ExRecord = Exception->getAsCXXRecordDecl()) {
395 IdentifierInfo* Name = ExRecord->getIdentifier();
396 if (Name && Name->getName() == "bad_alloc") {
397 // It's called bad_alloc, but is it in std?
398 DeclContext* DC = ExRecord->getDeclContext();
399 while (DC && !isa<NamespaceDecl>(DC))
400 DC = DC->getParent();
401 if (DC) {
402 NamespaceDecl* NS = cast<NamespaceDecl>(DC);
403 IdentifierInfo* NSName = NS->getIdentifier();
404 if (NSName && NSName->getName() == "std" &&
405 isa<TranslationUnitDecl>(NS->getParent()))
406 return false;
407 }
408 }
409 }
410 }
411 }
412
Sebastian Redl60618fa2011-03-12 11:50:43 +0000413 // At this point, the only remaining valid case is two matching dynamic
414 // specifications. We return here unless both specifications are dynamic.
415 if (OldEST != EST_Dynamic || NewEST != EST_Dynamic) {
Douglas Gregor2eef8292010-03-24 07:14:45 +0000416 if (MissingExceptionSpecification && Old->hasExceptionSpec() &&
Douglas Gregore13ad832010-02-12 07:32:17 +0000417 !New->hasExceptionSpec()) {
Douglas Gregor2eef8292010-03-24 07:14:45 +0000418 // The old type has an exception specification of some sort, but
419 // the new type does not.
420 *MissingExceptionSpecification = true;
421
Sebastian Redl60618fa2011-03-12 11:50:43 +0000422 if (MissingEmptyExceptionSpecification && OldNonThrowing) {
423 // The old type has a throw() or noexcept(true) exception specification
424 // and the new type has no exception specification, and the caller asked
Douglas Gregor2eef8292010-03-24 07:14:45 +0000425 // to handle this itself.
426 *MissingEmptyExceptionSpecification = true;
427 }
428
Douglas Gregore13ad832010-02-12 07:32:17 +0000429 return true;
430 }
431
Sebastian Redldced2262009-10-11 09:03:14 +0000432 Diag(NewLoc, DiagID);
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000433 if (NoteID.getDiagID() != 0)
Sebastian Redldced2262009-10-11 09:03:14 +0000434 Diag(OldLoc, NoteID);
435 return true;
436 }
437
Sebastian Redl60618fa2011-03-12 11:50:43 +0000438 assert(OldEST == EST_Dynamic && NewEST == EST_Dynamic &&
439 "Exception compatibility logic error: non-dynamic spec slipped through.");
440
Sebastian Redldced2262009-10-11 09:03:14 +0000441 bool Success = true;
Sebastian Redl60618fa2011-03-12 11:50:43 +0000442 // Both have a dynamic exception spec. Collect the first set, then compare
Sebastian Redldced2262009-10-11 09:03:14 +0000443 // to the second.
Sebastian Redl1219d152009-10-14 15:06:25 +0000444 llvm::SmallPtrSet<CanQualType, 8> OldTypes, NewTypes;
Sebastian Redldced2262009-10-11 09:03:14 +0000445 for (FunctionProtoType::exception_iterator I = Old->exception_begin(),
446 E = Old->exception_end(); I != E; ++I)
Sebastian Redl1219d152009-10-14 15:06:25 +0000447 OldTypes.insert(Context.getCanonicalType(*I).getUnqualifiedType());
Sebastian Redldced2262009-10-11 09:03:14 +0000448
449 for (FunctionProtoType::exception_iterator I = New->exception_begin(),
Sebastian Redl5db4d902009-10-11 09:11:23 +0000450 E = New->exception_end(); I != E && Success; ++I) {
Sebastian Redl1219d152009-10-14 15:06:25 +0000451 CanQualType TypePtr = Context.getCanonicalType(*I).getUnqualifiedType();
Sebastian Redl5db4d902009-10-11 09:11:23 +0000452 if(OldTypes.count(TypePtr))
453 NewTypes.insert(TypePtr);
454 else
455 Success = false;
456 }
Sebastian Redldced2262009-10-11 09:03:14 +0000457
Sebastian Redl5db4d902009-10-11 09:11:23 +0000458 Success = Success && OldTypes.size() == NewTypes.size();
Sebastian Redldced2262009-10-11 09:03:14 +0000459
460 if (Success) {
461 return false;
462 }
463 Diag(NewLoc, DiagID);
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000464 if (NoteID.getDiagID() != 0)
Sebastian Redldced2262009-10-11 09:03:14 +0000465 Diag(OldLoc, NoteID);
466 return true;
467}
468
469/// CheckExceptionSpecSubset - Check whether the second function type's
470/// exception specification is a subset (or equivalent) of the first function
471/// type. This is used by override and pointer assignment checks.
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000472bool Sema::CheckExceptionSpecSubset(
473 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
Sebastian Redldced2262009-10-11 09:03:14 +0000474 const FunctionProtoType *Superset, SourceLocation SuperLoc,
475 const FunctionProtoType *Subset, SourceLocation SubLoc) {
John McCall811d0be2010-05-28 08:37:35 +0000476
477 // Just auto-succeed under -fno-exceptions.
John McCall018591f2011-03-02 02:04:40 +0000478 if (!getLangOptions().CXXExceptions)
John McCall811d0be2010-05-28 08:37:35 +0000479 return false;
480
Sebastian Redldced2262009-10-11 09:03:14 +0000481 // FIXME: As usual, we could be more specific in our error messages, but
482 // that better waits until we've got types with source locations.
483
484 if (!SubLoc.isValid())
485 SubLoc = SuperLoc;
486
Sebastian Redl60618fa2011-03-12 11:50:43 +0000487 ExceptionSpecificationType SuperEST = Superset->getExceptionSpecType();
488
Sebastian Redldced2262009-10-11 09:03:14 +0000489 // If superset contains everything, we're done.
Sebastian Redl60618fa2011-03-12 11:50:43 +0000490 if (SuperEST == EST_None || SuperEST == EST_MSAny)
Sebastian Redldced2262009-10-11 09:03:14 +0000491 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
492
Sebastian Redl60618fa2011-03-12 11:50:43 +0000493 // If there are dependent noexcept specs, assume everything is fine. Unlike
494 // with the equivalency check, this is safe in this case, because we don't
495 // want to merge declarations. Checks after instantiation will catch any
496 // omissions we make here.
497 // We also shortcut checking if a noexcept expression was bad.
498
Sebastian Redl8026f6d2011-03-13 17:09:40 +0000499 FunctionProtoType::NoexceptResult SuperNR =Superset->getNoexceptSpec(Context);
Sebastian Redl60618fa2011-03-12 11:50:43 +0000500 if (SuperNR == FunctionProtoType::NR_BadNoexcept ||
501 SuperNR == FunctionProtoType::NR_Dependent)
502 return false;
503
504 // Another case of the superset containing everything.
505 if (SuperNR == FunctionProtoType::NR_Throw)
506 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
507
508 ExceptionSpecificationType SubEST = Subset->getExceptionSpecType();
509
Sebastian Redldced2262009-10-11 09:03:14 +0000510 // It does not. If the subset contains everything, we've failed.
Sebastian Redl60618fa2011-03-12 11:50:43 +0000511 if (SubEST == EST_None || SubEST == EST_MSAny) {
Sebastian Redldced2262009-10-11 09:03:14 +0000512 Diag(SubLoc, DiagID);
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000513 if (NoteID.getDiagID() != 0)
Sebastian Redldced2262009-10-11 09:03:14 +0000514 Diag(SuperLoc, NoteID);
515 return true;
516 }
517
Sebastian Redl8026f6d2011-03-13 17:09:40 +0000518 FunctionProtoType::NoexceptResult SubNR = Subset->getNoexceptSpec(Context);
Sebastian Redl60618fa2011-03-12 11:50:43 +0000519 if (SubNR == FunctionProtoType::NR_BadNoexcept ||
520 SubNR == FunctionProtoType::NR_Dependent)
521 return false;
522
523 // Another case of the subset containing everything.
524 if (SubNR == FunctionProtoType::NR_Throw) {
525 Diag(SubLoc, DiagID);
526 if (NoteID.getDiagID() != 0)
527 Diag(SuperLoc, NoteID);
528 return true;
529 }
530
531 // If the subset contains nothing, we're done.
532 if (SubEST == EST_DynamicNone || SubNR == FunctionProtoType::NR_Nothrow)
533 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
534
535 // Otherwise, if the superset contains nothing, we've failed.
536 if (SuperEST == EST_DynamicNone || SuperNR == FunctionProtoType::NR_Nothrow) {
537 Diag(SubLoc, DiagID);
538 if (NoteID.getDiagID() != 0)
539 Diag(SuperLoc, NoteID);
540 return true;
541 }
542
543 assert(SuperEST == EST_Dynamic && SubEST == EST_Dynamic &&
544 "Exception spec subset: non-dynamic case slipped through.");
545
546 // Neither contains everything or nothing. Do a proper comparison.
Sebastian Redldced2262009-10-11 09:03:14 +0000547 for (FunctionProtoType::exception_iterator SubI = Subset->exception_begin(),
548 SubE = Subset->exception_end(); SubI != SubE; ++SubI) {
549 // Take one type from the subset.
550 QualType CanonicalSubT = Context.getCanonicalType(*SubI);
Sebastian Redlc3a3b7b2009-10-14 14:38:54 +0000551 // Unwrap pointers and references so that we can do checks within a class
552 // hierarchy. Don't unwrap member pointers; they don't have hierarchy
553 // conversions on the pointee.
Sebastian Redldced2262009-10-11 09:03:14 +0000554 bool SubIsPointer = false;
555 if (const ReferenceType *RefTy = CanonicalSubT->getAs<ReferenceType>())
556 CanonicalSubT = RefTy->getPointeeType();
557 if (const PointerType *PtrTy = CanonicalSubT->getAs<PointerType>()) {
558 CanonicalSubT = PtrTy->getPointeeType();
559 SubIsPointer = true;
560 }
561 bool SubIsClass = CanonicalSubT->isRecordType();
Douglas Gregora4923eb2009-11-16 21:35:15 +0000562 CanonicalSubT = CanonicalSubT.getLocalUnqualifiedType();
Sebastian Redldced2262009-10-11 09:03:14 +0000563
564 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
565 /*DetectVirtual=*/false);
566
567 bool Contained = false;
568 // Make sure it's in the superset.
569 for (FunctionProtoType::exception_iterator SuperI =
570 Superset->exception_begin(), SuperE = Superset->exception_end();
571 SuperI != SuperE; ++SuperI) {
572 QualType CanonicalSuperT = Context.getCanonicalType(*SuperI);
573 // SubT must be SuperT or derived from it, or pointer or reference to
574 // such types.
575 if (const ReferenceType *RefTy = CanonicalSuperT->getAs<ReferenceType>())
576 CanonicalSuperT = RefTy->getPointeeType();
577 if (SubIsPointer) {
578 if (const PointerType *PtrTy = CanonicalSuperT->getAs<PointerType>())
579 CanonicalSuperT = PtrTy->getPointeeType();
580 else {
581 continue;
582 }
583 }
Douglas Gregora4923eb2009-11-16 21:35:15 +0000584 CanonicalSuperT = CanonicalSuperT.getLocalUnqualifiedType();
Sebastian Redldced2262009-10-11 09:03:14 +0000585 // If the types are the same, move on to the next type in the subset.
586 if (CanonicalSubT == CanonicalSuperT) {
587 Contained = true;
588 break;
589 }
590
591 // Otherwise we need to check the inheritance.
592 if (!SubIsClass || !CanonicalSuperT->isRecordType())
593 continue;
594
595 Paths.clear();
596 if (!IsDerivedFrom(CanonicalSubT, CanonicalSuperT, Paths))
597 continue;
598
Douglas Gregore0d5fe22010-05-21 20:29:55 +0000599 if (Paths.isAmbiguous(Context.getCanonicalType(CanonicalSuperT)))
Sebastian Redldced2262009-10-11 09:03:14 +0000600 continue;
601
John McCall6b2accb2010-02-10 09:31:12 +0000602 // Do this check from a context without privileges.
John McCall58e6f342010-03-16 05:22:47 +0000603 switch (CheckBaseClassAccess(SourceLocation(),
John McCall6b2accb2010-02-10 09:31:12 +0000604 CanonicalSuperT, CanonicalSubT,
605 Paths.front(),
John McCall58e6f342010-03-16 05:22:47 +0000606 /*Diagnostic*/ 0,
John McCall6b2accb2010-02-10 09:31:12 +0000607 /*ForceCheck*/ true,
John McCall58e6f342010-03-16 05:22:47 +0000608 /*ForceUnprivileged*/ true)) {
John McCall6b2accb2010-02-10 09:31:12 +0000609 case AR_accessible: break;
610 case AR_inaccessible: continue;
611 case AR_dependent:
612 llvm_unreachable("access check dependent for unprivileged context");
613 break;
614 case AR_delayed:
615 llvm_unreachable("access check delayed in non-declaration");
616 break;
617 }
Sebastian Redldced2262009-10-11 09:03:14 +0000618
619 Contained = true;
620 break;
621 }
622 if (!Contained) {
623 Diag(SubLoc, DiagID);
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000624 if (NoteID.getDiagID() != 0)
Sebastian Redldced2262009-10-11 09:03:14 +0000625 Diag(SuperLoc, NoteID);
626 return true;
627 }
628 }
629 // We've run half the gauntlet.
630 return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
631}
632
633static bool CheckSpecForTypesEquivalent(Sema &S,
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000634 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
Sebastian Redldced2262009-10-11 09:03:14 +0000635 QualType Target, SourceLocation TargetLoc,
636 QualType Source, SourceLocation SourceLoc)
637{
638 const FunctionProtoType *TFunc = GetUnderlyingFunction(Target);
639 if (!TFunc)
640 return false;
641 const FunctionProtoType *SFunc = GetUnderlyingFunction(Source);
642 if (!SFunc)
643 return false;
644
645 return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc,
646 SFunc, SourceLoc);
647}
648
649/// CheckParamExceptionSpec - Check if the parameter and return types of the
650/// two functions have equivalent exception specs. This is part of the
651/// assignment and override compatibility check. We do not check the parameters
652/// of parameter function pointers recursively, as no sane programmer would
653/// even be able to write such a function type.
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000654bool Sema::CheckParamExceptionSpec(const PartialDiagnostic & NoteID,
Sebastian Redldced2262009-10-11 09:03:14 +0000655 const FunctionProtoType *Target, SourceLocation TargetLoc,
656 const FunctionProtoType *Source, SourceLocation SourceLoc)
657{
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000658 if (CheckSpecForTypesEquivalent(*this,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000659 PDiag(diag::err_deep_exception_specs_differ) << 0,
660 PDiag(),
Sebastian Redldced2262009-10-11 09:03:14 +0000661 Target->getResultType(), TargetLoc,
662 Source->getResultType(), SourceLoc))
663 return true;
664
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000665 // We shouldn't even be testing this unless the arguments are otherwise
Sebastian Redldced2262009-10-11 09:03:14 +0000666 // compatible.
667 assert(Target->getNumArgs() == Source->getNumArgs() &&
668 "Functions have different argument counts.");
669 for (unsigned i = 0, E = Target->getNumArgs(); i != E; ++i) {
Sebastian Redl37c38ec2009-10-14 16:09:29 +0000670 if (CheckSpecForTypesEquivalent(*this,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000671 PDiag(diag::err_deep_exception_specs_differ) << 1,
672 PDiag(),
Sebastian Redldced2262009-10-11 09:03:14 +0000673 Target->getArgType(i), TargetLoc,
674 Source->getArgType(i), SourceLoc))
675 return true;
676 }
677 return false;
678}
679
680bool Sema::CheckExceptionSpecCompatibility(Expr *From, QualType ToType)
681{
682 // First we check for applicability.
683 // Target type must be a function, function pointer or function reference.
684 const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType);
685 if (!ToFunc)
686 return false;
687
688 // SourceType must be a function or function pointer.
689 const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType());
690 if (!FromFunc)
691 return false;
692
693 // Now we've got the correct types on both sides, check their compatibility.
694 // This means that the source of the conversion can only throw a subset of
695 // the exceptions of the target, and any exception specs on arguments or
696 // return types must be equivalent.
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000697 return CheckExceptionSpecSubset(PDiag(diag::err_incompatible_exception_specs),
698 PDiag(), ToFunc,
699 From->getSourceRange().getBegin(),
Sebastian Redldced2262009-10-11 09:03:14 +0000700 FromFunc, SourceLocation());
701}
702
703bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
704 const CXXMethodDecl *Old) {
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000705 return CheckExceptionSpecSubset(PDiag(diag::err_override_exception_spec),
706 PDiag(diag::note_overridden_virtual_function),
Sebastian Redldced2262009-10-11 09:03:14 +0000707 Old->getType()->getAs<FunctionProtoType>(),
708 Old->getLocation(),
709 New->getType()->getAs<FunctionProtoType>(),
710 New->getLocation());
711}
712
713} // end namespace clang