SemaExceptionSpec.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  1. //===--- 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. #include "clang/Sema/SemaInternal.h"
  14. #include "clang/AST/CXXInheritance.h"
  15. #include "clang/AST/Expr.h"
  16. #include "clang/AST/ExprCXX.h"
  17. #include "clang/AST/TypeLoc.h"
  18. #include "clang/Lex/Preprocessor.h"
  19. #include "clang/Basic/Diagnostic.h"
  20. #include "clang/Basic/SourceManager.h"
  21. #include "llvm/ADT/SmallPtrSet.h"
  22. namespace clang {
  23. static const FunctionProtoType *GetUnderlyingFunction(QualType T)
  24. {
  25. if (const PointerType *PtrTy = T->getAs<PointerType>())
  26. T = PtrTy->getPointeeType();
  27. else if (const ReferenceType *RefTy = T->getAs<ReferenceType>())
  28. T = RefTy->getPointeeType();
  29. else if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
  30. T = MPTy->getPointeeType();
  31. return T->getAs<FunctionProtoType>();
  32. }
  33. /// CheckSpecifiedExceptionType - Check if the given type is valid in an
  34. /// exception specification. Incomplete types, or pointers to incomplete types
  35. /// other than void are not allowed.
  36. bool Sema::CheckSpecifiedExceptionType(QualType T, const SourceRange &Range) {
  37. // This check (and the similar one below) deals with issue 437, that changes
  38. // C++ 9.2p2 this way:
  39. // Within the class member-specification, the class is regarded as complete
  40. // within function bodies, default arguments, exception-specifications, and
  41. // constructor ctor-initializers (including such things in nested classes).
  42. if (T->isRecordType() && T->getAs<RecordType>()->isBeingDefined())
  43. return false;
  44. // C++ 15.4p2: A type denoted in an exception-specification shall not denote
  45. // an incomplete type.
  46. if (RequireCompleteType(Range.getBegin(), T,
  47. PDiag(diag::err_incomplete_in_exception_spec) << /*direct*/0 << Range))
  48. return true;
  49. // C++ 15.4p2: A type denoted in an exception-specification shall not denote
  50. // an incomplete type a pointer or reference to an incomplete type, other
  51. // than (cv) void*.
  52. int kind;
  53. if (const PointerType* IT = T->getAs<PointerType>()) {
  54. T = IT->getPointeeType();
  55. kind = 1;
  56. } else if (const ReferenceType* IT = T->getAs<ReferenceType>()) {
  57. T = IT->getPointeeType();
  58. kind = 2;
  59. } else
  60. return false;
  61. // Again as before
  62. if (T->isRecordType() && T->getAs<RecordType>()->isBeingDefined())
  63. return false;
  64. if (!T->isVoidType() && RequireCompleteType(Range.getBegin(), T,
  65. PDiag(diag::err_incomplete_in_exception_spec) << kind << Range))
  66. return true;
  67. return false;
  68. }
  69. /// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer
  70. /// to member to a function with an exception specification. This means that
  71. /// it is invalid to add another level of indirection.
  72. bool Sema::CheckDistantExceptionSpec(QualType T) {
  73. if (const PointerType *PT = T->getAs<PointerType>())
  74. T = PT->getPointeeType();
  75. else if (const MemberPointerType *PT = T->getAs<MemberPointerType>())
  76. T = PT->getPointeeType();
  77. else
  78. return false;
  79. const FunctionProtoType *FnT = T->getAs<FunctionProtoType>();
  80. if (!FnT)
  81. return false;
  82. return FnT->hasExceptionSpec();
  83. }
  84. bool Sema::CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New) {
  85. OverloadedOperatorKind OO = New->getDeclName().getCXXOverloadedOperator();
  86. bool IsOperatorNew = OO == OO_New || OO == OO_Array_New;
  87. bool MissingExceptionSpecification = false;
  88. bool MissingEmptyExceptionSpecification = false;
  89. unsigned DiagID = diag::err_mismatched_exception_spec;
  90. if (getLangOptions().MicrosoftExt)
  91. DiagID = diag::warn_mismatched_exception_spec;
  92. if (!CheckEquivalentExceptionSpec(PDiag(DiagID),
  93. PDiag(diag::note_previous_declaration),
  94. Old->getType()->getAs<FunctionProtoType>(),
  95. Old->getLocation(),
  96. New->getType()->getAs<FunctionProtoType>(),
  97. New->getLocation(),
  98. &MissingExceptionSpecification,
  99. &MissingEmptyExceptionSpecification,
  100. /*AllowNoexceptAllMatchWithNoSpec=*/true,
  101. IsOperatorNew))
  102. return false;
  103. // The failure was something other than an empty exception
  104. // specification; return an error.
  105. if (!MissingExceptionSpecification && !MissingEmptyExceptionSpecification)
  106. return true;
  107. const FunctionProtoType *NewProto
  108. = New->getType()->getAs<FunctionProtoType>();
  109. // The new function declaration is only missing an empty exception
  110. // specification "throw()". If the throw() specification came from a
  111. // function in a system header that has C linkage, just add an empty
  112. // exception specification to the "new" declaration. This is an
  113. // egregious workaround for glibc, which adds throw() specifications
  114. // to many libc functions as an optimization. Unfortunately, that
  115. // optimization isn't permitted by the C++ standard, so we're forced
  116. // to work around it here.
  117. if (MissingEmptyExceptionSpecification && NewProto &&
  118. (Old->getLocation().isInvalid() ||
  119. Context.getSourceManager().isInSystemHeader(Old->getLocation())) &&
  120. Old->isExternC()) {
  121. FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
  122. EPI.ExceptionSpecType = EST_DynamicNone;
  123. QualType NewType = Context.getFunctionType(NewProto->getResultType(),
  124. NewProto->arg_type_begin(),
  125. NewProto->getNumArgs(),
  126. EPI);
  127. New->setType(NewType);
  128. return false;
  129. }
  130. if (MissingExceptionSpecification && NewProto) {
  131. const FunctionProtoType *OldProto
  132. = Old->getType()->getAs<FunctionProtoType>();
  133. FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
  134. EPI.ExceptionSpecType = OldProto->getExceptionSpecType();
  135. if (EPI.ExceptionSpecType == EST_Dynamic) {
  136. EPI.NumExceptions = OldProto->getNumExceptions();
  137. EPI.Exceptions = OldProto->exception_begin();
  138. } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
  139. // FIXME: We can't just take the expression from the old prototype. It
  140. // likely contains references to the old prototype's parameters.
  141. }
  142. // Update the type of the function with the appropriate exception
  143. // specification.
  144. QualType NewType = Context.getFunctionType(NewProto->getResultType(),
  145. NewProto->arg_type_begin(),
  146. NewProto->getNumArgs(),
  147. EPI);
  148. New->setType(NewType);
  149. // If exceptions are disabled, suppress the warning about missing
  150. // exception specifications for new and delete operators.
  151. if (!getLangOptions().CXXExceptions) {
  152. switch (New->getDeclName().getCXXOverloadedOperator()) {
  153. case OO_New:
  154. case OO_Array_New:
  155. case OO_Delete:
  156. case OO_Array_Delete:
  157. if (New->getDeclContext()->isTranslationUnit())
  158. return false;
  159. break;
  160. default:
  161. break;
  162. }
  163. }
  164. // Warn about the lack of exception specification.
  165. llvm::SmallString<128> ExceptionSpecString;
  166. llvm::raw_svector_ostream OS(ExceptionSpecString);
  167. switch (OldProto->getExceptionSpecType()) {
  168. case EST_DynamicNone:
  169. OS << "throw()";
  170. break;
  171. case EST_Dynamic: {
  172. OS << "throw(";
  173. bool OnFirstException = true;
  174. for (FunctionProtoType::exception_iterator E = OldProto->exception_begin(),
  175. EEnd = OldProto->exception_end();
  176. E != EEnd;
  177. ++E) {
  178. if (OnFirstException)
  179. OnFirstException = false;
  180. else
  181. OS << ", ";
  182. OS << E->getAsString(getPrintingPolicy());
  183. }
  184. OS << ")";
  185. break;
  186. }
  187. case EST_BasicNoexcept:
  188. OS << "noexcept";
  189. break;
  190. case EST_ComputedNoexcept:
  191. OS << "noexcept(";
  192. OldProto->getNoexceptExpr()->printPretty(OS, Context, 0,
  193. getPrintingPolicy());
  194. OS << ")";
  195. break;
  196. default:
  197. llvm_unreachable("This spec type is compatible with none.");
  198. }
  199. OS.flush();
  200. SourceLocation FixItLoc;
  201. if (TypeSourceInfo *TSInfo = New->getTypeSourceInfo()) {
  202. TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
  203. if (const FunctionTypeLoc *FTLoc = dyn_cast<FunctionTypeLoc>(&TL))
  204. FixItLoc = PP.getLocForEndOfToken(FTLoc->getLocalRangeEnd());
  205. }
  206. if (FixItLoc.isInvalid())
  207. Diag(New->getLocation(), diag::warn_missing_exception_specification)
  208. << New << OS.str();
  209. else {
  210. // FIXME: This will get more complicated with C++0x
  211. // late-specified return types.
  212. Diag(New->getLocation(), diag::warn_missing_exception_specification)
  213. << New << OS.str()
  214. << FixItHint::CreateInsertion(FixItLoc, " " + OS.str().str());
  215. }
  216. if (!Old->getLocation().isInvalid())
  217. Diag(Old->getLocation(), diag::note_previous_declaration);
  218. return false;
  219. }
  220. Diag(New->getLocation(), DiagID);
  221. Diag(Old->getLocation(), diag::note_previous_declaration);
  222. return true;
  223. }
  224. /// CheckEquivalentExceptionSpec - Check if the two types have equivalent
  225. /// exception specifications. Exception specifications are equivalent if
  226. /// they allow exactly the same set of exception types. It does not matter how
  227. /// that is achieved. See C++ [except.spec]p2.
  228. bool Sema::CheckEquivalentExceptionSpec(
  229. const FunctionProtoType *Old, SourceLocation OldLoc,
  230. const FunctionProtoType *New, SourceLocation NewLoc) {
  231. unsigned DiagID = diag::err_mismatched_exception_spec;
  232. if (getLangOptions().MicrosoftExt)
  233. DiagID = diag::warn_mismatched_exception_spec;
  234. return CheckEquivalentExceptionSpec(
  235. PDiag(DiagID),
  236. PDiag(diag::note_previous_declaration),
  237. Old, OldLoc, New, NewLoc);
  238. }
  239. /// CheckEquivalentExceptionSpec - Check if the two types have compatible
  240. /// exception specifications. See C++ [except.spec]p3.
  241. bool Sema::CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
  242. const PartialDiagnostic & NoteID,
  243. const FunctionProtoType *Old,
  244. SourceLocation OldLoc,
  245. const FunctionProtoType *New,
  246. SourceLocation NewLoc,
  247. bool *MissingExceptionSpecification,
  248. bool*MissingEmptyExceptionSpecification,
  249. bool AllowNoexceptAllMatchWithNoSpec,
  250. bool IsOperatorNew) {
  251. // Just completely ignore this under -fno-exceptions.
  252. if (!getLangOptions().CXXExceptions)
  253. return false;
  254. if (MissingExceptionSpecification)
  255. *MissingExceptionSpecification = false;
  256. if (MissingEmptyExceptionSpecification)
  257. *MissingEmptyExceptionSpecification = false;
  258. // C++0x [except.spec]p3: Two exception-specifications are compatible if:
  259. // - both are non-throwing, regardless of their form,
  260. // - both have the form noexcept(constant-expression) and the constant-
  261. // expressions are equivalent,
  262. // - both are dynamic-exception-specifications that have the same set of
  263. // adjusted types.
  264. //
  265. // C++0x [except.spec]p12: An exception-specifcation is non-throwing if it is
  266. // of the form throw(), noexcept, or noexcept(constant-expression) where the
  267. // constant-expression yields true.
  268. //
  269. // C++0x [except.spec]p4: If any declaration of a function has an exception-
  270. // specifier that is not a noexcept-specification allowing all exceptions,
  271. // all declarations [...] of that function shall have a compatible
  272. // exception-specification.
  273. //
  274. // That last point basically means that noexcept(false) matches no spec.
  275. // It's considered when AllowNoexceptAllMatchWithNoSpec is true.
  276. ExceptionSpecificationType OldEST = Old->getExceptionSpecType();
  277. ExceptionSpecificationType NewEST = New->getExceptionSpecType();
  278. assert(OldEST != EST_Delayed && NewEST != EST_Delayed &&
  279. "Shouldn't see unknown exception specifications here");
  280. // Shortcut the case where both have no spec.
  281. if (OldEST == EST_None && NewEST == EST_None)
  282. return false;
  283. FunctionProtoType::NoexceptResult OldNR = Old->getNoexceptSpec(Context);
  284. FunctionProtoType::NoexceptResult NewNR = New->getNoexceptSpec(Context);
  285. if (OldNR == FunctionProtoType::NR_BadNoexcept ||
  286. NewNR == FunctionProtoType::NR_BadNoexcept)
  287. return false;
  288. // Dependent noexcept specifiers are compatible with each other, but nothing
  289. // else.
  290. // One noexcept is compatible with another if the argument is the same
  291. if (OldNR == NewNR &&
  292. OldNR != FunctionProtoType::NR_NoNoexcept &&
  293. NewNR != FunctionProtoType::NR_NoNoexcept)
  294. return false;
  295. if (OldNR != NewNR &&
  296. OldNR != FunctionProtoType::NR_NoNoexcept &&
  297. NewNR != FunctionProtoType::NR_NoNoexcept) {
  298. Diag(NewLoc, DiagID);
  299. if (NoteID.getDiagID() != 0)
  300. Diag(OldLoc, NoteID);
  301. return true;
  302. }
  303. // The MS extension throw(...) is compatible with itself.
  304. if (OldEST == EST_MSAny && NewEST == EST_MSAny)
  305. return false;
  306. // It's also compatible with no spec.
  307. if ((OldEST == EST_None && NewEST == EST_MSAny) ||
  308. (OldEST == EST_MSAny && NewEST == EST_None))
  309. return false;
  310. // It's also compatible with noexcept(false).
  311. if (OldEST == EST_MSAny && NewNR == FunctionProtoType::NR_Throw)
  312. return false;
  313. if (NewEST == EST_MSAny && OldNR == FunctionProtoType::NR_Throw)
  314. return false;
  315. // As described above, noexcept(false) matches no spec only for functions.
  316. if (AllowNoexceptAllMatchWithNoSpec) {
  317. if (OldEST == EST_None && NewNR == FunctionProtoType::NR_Throw)
  318. return false;
  319. if (NewEST == EST_None && OldNR == FunctionProtoType::NR_Throw)
  320. return false;
  321. }
  322. // Any non-throwing specifications are compatible.
  323. bool OldNonThrowing = OldNR == FunctionProtoType::NR_Nothrow ||
  324. OldEST == EST_DynamicNone;
  325. bool NewNonThrowing = NewNR == FunctionProtoType::NR_Nothrow ||
  326. NewEST == EST_DynamicNone;
  327. if (OldNonThrowing && NewNonThrowing)
  328. return false;
  329. // As a special compatibility feature, under C++0x we accept no spec and
  330. // throw(std::bad_alloc) as equivalent for operator new and operator new[].
  331. // This is because the implicit declaration changed, but old code would break.
  332. if (getLangOptions().CPlusPlus0x && IsOperatorNew) {
  333. const FunctionProtoType *WithExceptions = 0;
  334. if (OldEST == EST_None && NewEST == EST_Dynamic)
  335. WithExceptions = New;
  336. else if (OldEST == EST_Dynamic && NewEST == EST_None)
  337. WithExceptions = Old;
  338. if (WithExceptions && WithExceptions->getNumExceptions() == 1) {
  339. // One has no spec, the other throw(something). If that something is
  340. // std::bad_alloc, all conditions are met.
  341. QualType Exception = *WithExceptions->exception_begin();
  342. if (CXXRecordDecl *ExRecord = Exception->getAsCXXRecordDecl()) {
  343. IdentifierInfo* Name = ExRecord->getIdentifier();
  344. if (Name && Name->getName() == "bad_alloc") {
  345. // It's called bad_alloc, but is it in std?
  346. DeclContext* DC = ExRecord->getDeclContext();
  347. DC = DC->getEnclosingNamespaceContext();
  348. if (NamespaceDecl* NS = dyn_cast<NamespaceDecl>(DC)) {
  349. IdentifierInfo* NSName = NS->getIdentifier();
  350. DC = DC->getParent();
  351. if (NSName && NSName->getName() == "std" &&
  352. DC->getEnclosingNamespaceContext()->isTranslationUnit()) {
  353. return false;
  354. }
  355. }
  356. }
  357. }
  358. }
  359. }
  360. // At this point, the only remaining valid case is two matching dynamic
  361. // specifications. We return here unless both specifications are dynamic.
  362. if (OldEST != EST_Dynamic || NewEST != EST_Dynamic) {
  363. if (MissingExceptionSpecification && Old->hasExceptionSpec() &&
  364. !New->hasExceptionSpec()) {
  365. // The old type has an exception specification of some sort, but
  366. // the new type does not.
  367. *MissingExceptionSpecification = true;
  368. if (MissingEmptyExceptionSpecification && OldNonThrowing) {
  369. // The old type has a throw() or noexcept(true) exception specification
  370. // and the new type has no exception specification, and the caller asked
  371. // to handle this itself.
  372. *MissingEmptyExceptionSpecification = true;
  373. }
  374. return true;
  375. }
  376. Diag(NewLoc, DiagID);
  377. if (NoteID.getDiagID() != 0)
  378. Diag(OldLoc, NoteID);
  379. return true;
  380. }
  381. assert(OldEST == EST_Dynamic && NewEST == EST_Dynamic &&
  382. "Exception compatibility logic error: non-dynamic spec slipped through.");
  383. bool Success = true;
  384. // Both have a dynamic exception spec. Collect the first set, then compare
  385. // to the second.
  386. llvm::SmallPtrSet<CanQualType, 8> OldTypes, NewTypes;
  387. for (FunctionProtoType::exception_iterator I = Old->exception_begin(),
  388. E = Old->exception_end(); I != E; ++I)
  389. OldTypes.insert(Context.getCanonicalType(*I).getUnqualifiedType());
  390. for (FunctionProtoType::exception_iterator I = New->exception_begin(),
  391. E = New->exception_end(); I != E && Success; ++I) {
  392. CanQualType TypePtr = Context.getCanonicalType(*I).getUnqualifiedType();
  393. if(OldTypes.count(TypePtr))
  394. NewTypes.insert(TypePtr);
  395. else
  396. Success = false;
  397. }
  398. Success = Success && OldTypes.size() == NewTypes.size();
  399. if (Success) {
  400. return false;
  401. }
  402. Diag(NewLoc, DiagID);
  403. if (NoteID.getDiagID() != 0)
  404. Diag(OldLoc, NoteID);
  405. return true;
  406. }
  407. /// CheckExceptionSpecSubset - Check whether the second function type's
  408. /// exception specification is a subset (or equivalent) of the first function
  409. /// type. This is used by override and pointer assignment checks.
  410. bool Sema::CheckExceptionSpecSubset(
  411. const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
  412. const FunctionProtoType *Superset, SourceLocation SuperLoc,
  413. const FunctionProtoType *Subset, SourceLocation SubLoc) {
  414. // Just auto-succeed under -fno-exceptions.
  415. if (!getLangOptions().CXXExceptions)
  416. return false;
  417. // FIXME: As usual, we could be more specific in our error messages, but
  418. // that better waits until we've got types with source locations.
  419. if (!SubLoc.isValid())
  420. SubLoc = SuperLoc;
  421. ExceptionSpecificationType SuperEST = Superset->getExceptionSpecType();
  422. // If superset contains everything, we're done.
  423. if (SuperEST == EST_None || SuperEST == EST_MSAny)
  424. return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
  425. // If there are dependent noexcept specs, assume everything is fine. Unlike
  426. // with the equivalency check, this is safe in this case, because we don't
  427. // want to merge declarations. Checks after instantiation will catch any
  428. // omissions we make here.
  429. // We also shortcut checking if a noexcept expression was bad.
  430. FunctionProtoType::NoexceptResult SuperNR =Superset->getNoexceptSpec(Context);
  431. if (SuperNR == FunctionProtoType::NR_BadNoexcept ||
  432. SuperNR == FunctionProtoType::NR_Dependent)
  433. return false;
  434. // Another case of the superset containing everything.
  435. if (SuperNR == FunctionProtoType::NR_Throw)
  436. return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
  437. ExceptionSpecificationType SubEST = Subset->getExceptionSpecType();
  438. assert(SuperEST != EST_Delayed && SubEST != EST_Delayed &&
  439. "Shouldn't see unknown exception specifications here");
  440. // It does not. If the subset contains everything, we've failed.
  441. if (SubEST == EST_None || SubEST == EST_MSAny) {
  442. Diag(SubLoc, DiagID);
  443. if (NoteID.getDiagID() != 0)
  444. Diag(SuperLoc, NoteID);
  445. return true;
  446. }
  447. FunctionProtoType::NoexceptResult SubNR = Subset->getNoexceptSpec(Context);
  448. if (SubNR == FunctionProtoType::NR_BadNoexcept ||
  449. SubNR == FunctionProtoType::NR_Dependent)
  450. return false;
  451. // Another case of the subset containing everything.
  452. if (SubNR == FunctionProtoType::NR_Throw) {
  453. Diag(SubLoc, DiagID);
  454. if (NoteID.getDiagID() != 0)
  455. Diag(SuperLoc, NoteID);
  456. return true;
  457. }
  458. // If the subset contains nothing, we're done.
  459. if (SubEST == EST_DynamicNone || SubNR == FunctionProtoType::NR_Nothrow)
  460. return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
  461. // Otherwise, if the superset contains nothing, we've failed.
  462. if (SuperEST == EST_DynamicNone || SuperNR == FunctionProtoType::NR_Nothrow) {
  463. Diag(SubLoc, DiagID);
  464. if (NoteID.getDiagID() != 0)
  465. Diag(SuperLoc, NoteID);
  466. return true;
  467. }
  468. assert(SuperEST == EST_Dynamic && SubEST == EST_Dynamic &&
  469. "Exception spec subset: non-dynamic case slipped through.");
  470. // Neither contains everything or nothing. Do a proper comparison.
  471. for (FunctionProtoType::exception_iterator SubI = Subset->exception_begin(),
  472. SubE = Subset->exception_end(); SubI != SubE; ++SubI) {
  473. // Take one type from the subset.
  474. QualType CanonicalSubT = Context.getCanonicalType(*SubI);
  475. // Unwrap pointers and references so that we can do checks within a class
  476. // hierarchy. Don't unwrap member pointers; they don't have hierarchy
  477. // conversions on the pointee.
  478. bool SubIsPointer = false;
  479. if (const ReferenceType *RefTy = CanonicalSubT->getAs<ReferenceType>())
  480. CanonicalSubT = RefTy->getPointeeType();
  481. if (const PointerType *PtrTy = CanonicalSubT->getAs<PointerType>()) {
  482. CanonicalSubT = PtrTy->getPointeeType();
  483. SubIsPointer = true;
  484. }
  485. bool SubIsClass = CanonicalSubT->isRecordType();
  486. CanonicalSubT = CanonicalSubT.getLocalUnqualifiedType();
  487. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  488. /*DetectVirtual=*/false);
  489. bool Contained = false;
  490. // Make sure it's in the superset.
  491. for (FunctionProtoType::exception_iterator SuperI =
  492. Superset->exception_begin(), SuperE = Superset->exception_end();
  493. SuperI != SuperE; ++SuperI) {
  494. QualType CanonicalSuperT = Context.getCanonicalType(*SuperI);
  495. // SubT must be SuperT or derived from it, or pointer or reference to
  496. // such types.
  497. if (const ReferenceType *RefTy = CanonicalSuperT->getAs<ReferenceType>())
  498. CanonicalSuperT = RefTy->getPointeeType();
  499. if (SubIsPointer) {
  500. if (const PointerType *PtrTy = CanonicalSuperT->getAs<PointerType>())
  501. CanonicalSuperT = PtrTy->getPointeeType();
  502. else {
  503. continue;
  504. }
  505. }
  506. CanonicalSuperT = CanonicalSuperT.getLocalUnqualifiedType();
  507. // If the types are the same, move on to the next type in the subset.
  508. if (CanonicalSubT == CanonicalSuperT) {
  509. Contained = true;
  510. break;
  511. }
  512. // Otherwise we need to check the inheritance.
  513. if (!SubIsClass || !CanonicalSuperT->isRecordType())
  514. continue;
  515. Paths.clear();
  516. if (!IsDerivedFrom(CanonicalSubT, CanonicalSuperT, Paths))
  517. continue;
  518. if (Paths.isAmbiguous(Context.getCanonicalType(CanonicalSuperT)))
  519. continue;
  520. // Do this check from a context without privileges.
  521. switch (CheckBaseClassAccess(SourceLocation(),
  522. CanonicalSuperT, CanonicalSubT,
  523. Paths.front(),
  524. /*Diagnostic*/ 0,
  525. /*ForceCheck*/ true,
  526. /*ForceUnprivileged*/ true)) {
  527. case AR_accessible: break;
  528. case AR_inaccessible: continue;
  529. case AR_dependent:
  530. llvm_unreachable("access check dependent for unprivileged context");
  531. case AR_delayed:
  532. llvm_unreachable("access check delayed in non-declaration");
  533. }
  534. Contained = true;
  535. break;
  536. }
  537. if (!Contained) {
  538. Diag(SubLoc, DiagID);
  539. if (NoteID.getDiagID() != 0)
  540. Diag(SuperLoc, NoteID);
  541. return true;
  542. }
  543. }
  544. // We've run half the gauntlet.
  545. return CheckParamExceptionSpec(NoteID, Superset, SuperLoc, Subset, SubLoc);
  546. }
  547. static bool CheckSpecForTypesEquivalent(Sema &S,
  548. const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
  549. QualType Target, SourceLocation TargetLoc,
  550. QualType Source, SourceLocation SourceLoc)
  551. {
  552. const FunctionProtoType *TFunc = GetUnderlyingFunction(Target);
  553. if (!TFunc)
  554. return false;
  555. const FunctionProtoType *SFunc = GetUnderlyingFunction(Source);
  556. if (!SFunc)
  557. return false;
  558. return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc,
  559. SFunc, SourceLoc);
  560. }
  561. /// CheckParamExceptionSpec - Check if the parameter and return types of the
  562. /// two functions have equivalent exception specs. This is part of the
  563. /// assignment and override compatibility check. We do not check the parameters
  564. /// of parameter function pointers recursively, as no sane programmer would
  565. /// even be able to write such a function type.
  566. bool Sema::CheckParamExceptionSpec(const PartialDiagnostic & NoteID,
  567. const FunctionProtoType *Target, SourceLocation TargetLoc,
  568. const FunctionProtoType *Source, SourceLocation SourceLoc)
  569. {
  570. if (CheckSpecForTypesEquivalent(*this,
  571. PDiag(diag::err_deep_exception_specs_differ) << 0,
  572. PDiag(),
  573. Target->getResultType(), TargetLoc,
  574. Source->getResultType(), SourceLoc))
  575. return true;
  576. // We shouldn't even be testing this unless the arguments are otherwise
  577. // compatible.
  578. assert(Target->getNumArgs() == Source->getNumArgs() &&
  579. "Functions have different argument counts.");
  580. for (unsigned i = 0, E = Target->getNumArgs(); i != E; ++i) {
  581. if (CheckSpecForTypesEquivalent(*this,
  582. PDiag(diag::err_deep_exception_specs_differ) << 1,
  583. PDiag(),
  584. Target->getArgType(i), TargetLoc,
  585. Source->getArgType(i), SourceLoc))
  586. return true;
  587. }
  588. return false;
  589. }
  590. bool Sema::CheckExceptionSpecCompatibility(Expr *From, QualType ToType)
  591. {
  592. // First we check for applicability.
  593. // Target type must be a function, function pointer or function reference.
  594. const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType);
  595. if (!ToFunc)
  596. return false;
  597. // SourceType must be a function or function pointer.
  598. const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType());
  599. if (!FromFunc)
  600. return false;
  601. // Now we've got the correct types on both sides, check their compatibility.
  602. // This means that the source of the conversion can only throw a subset of
  603. // the exceptions of the target, and any exception specs on arguments or
  604. // return types must be equivalent.
  605. return CheckExceptionSpecSubset(PDiag(diag::err_incompatible_exception_specs),
  606. PDiag(), ToFunc,
  607. From->getSourceRange().getBegin(),
  608. FromFunc, SourceLocation());
  609. }
  610. bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
  611. const CXXMethodDecl *Old) {
  612. if (getLangOptions().CPlusPlus0x && isa<CXXDestructorDecl>(New)) {
  613. // Don't check uninstantiated template destructors at all. We can only
  614. // synthesize correct specs after the template is instantiated.
  615. if (New->getParent()->isDependentType())
  616. return false;
  617. if (New->getParent()->isBeingDefined()) {
  618. // The destructor might be updated once the definition is finished. So
  619. // remember it and check later.
  620. DelayedDestructorExceptionSpecChecks.push_back(std::make_pair(
  621. cast<CXXDestructorDecl>(New), cast<CXXDestructorDecl>(Old)));
  622. return false;
  623. }
  624. }
  625. unsigned DiagID = diag::err_override_exception_spec;
  626. if (getLangOptions().MicrosoftExt)
  627. DiagID = diag::warn_override_exception_spec;
  628. return CheckExceptionSpecSubset(PDiag(DiagID),
  629. PDiag(diag::note_overridden_virtual_function),
  630. Old->getType()->getAs<FunctionProtoType>(),
  631. Old->getLocation(),
  632. New->getType()->getAs<FunctionProtoType>(),
  633. New->getLocation());
  634. }
  635. } // end namespace clang