SemaExceptionSpec.cpp 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312
  1. //===--- SemaExceptionSpec.cpp - C++ Exception Specifications ---*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file provides Sema routines for C++ exception specification testing.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/Sema/SemaInternal.h"
  13. #include "clang/AST/ASTMutationListener.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/Basic/Diagnostic.h"
  19. #include "clang/Basic/SourceManager.h"
  20. #include "llvm/ADT/SmallPtrSet.h"
  21. #include "llvm/ADT/SmallString.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. /// HACK: libstdc++ has a bug where it shadows std::swap with a member
  34. /// swap function then tries to call std::swap unqualified from the exception
  35. /// specification of that function. This function detects whether we're in
  36. /// such a case and turns off delay-parsing of exception specifications.
  37. bool Sema::isLibstdcxxEagerExceptionSpecHack(const Declarator &D) {
  38. auto *RD = dyn_cast<CXXRecordDecl>(CurContext);
  39. // All the problem cases are member functions named "swap" within class
  40. // templates declared directly within namespace std or std::__debug or
  41. // std::__profile.
  42. if (!RD || !RD->getIdentifier() || !RD->getDescribedClassTemplate() ||
  43. !D.getIdentifier() || !D.getIdentifier()->isStr("swap"))
  44. return false;
  45. auto *ND = dyn_cast<NamespaceDecl>(RD->getDeclContext());
  46. if (!ND)
  47. return false;
  48. bool IsInStd = ND->isStdNamespace();
  49. if (!IsInStd) {
  50. // This isn't a direct member of namespace std, but it might still be
  51. // libstdc++'s std::__debug::array or std::__profile::array.
  52. IdentifierInfo *II = ND->getIdentifier();
  53. if (!II || !(II->isStr("__debug") || II->isStr("__profile")) ||
  54. !ND->isInStdNamespace())
  55. return false;
  56. }
  57. // Only apply this hack within a system header.
  58. if (!Context.getSourceManager().isInSystemHeader(D.getBeginLoc()))
  59. return false;
  60. return llvm::StringSwitch<bool>(RD->getIdentifier()->getName())
  61. .Case("array", true)
  62. .Case("pair", IsInStd)
  63. .Case("priority_queue", IsInStd)
  64. .Case("stack", IsInStd)
  65. .Case("queue", IsInStd)
  66. .Default(false);
  67. }
  68. ExprResult Sema::ActOnNoexceptSpec(SourceLocation NoexceptLoc,
  69. Expr *NoexceptExpr,
  70. ExceptionSpecificationType &EST) {
  71. // FIXME: This is bogus, a noexcept expression is not a condition.
  72. ExprResult Converted = CheckBooleanCondition(NoexceptLoc, NoexceptExpr);
  73. if (Converted.isInvalid())
  74. return Converted;
  75. if (Converted.get()->isValueDependent()) {
  76. EST = EST_DependentNoexcept;
  77. return Converted;
  78. }
  79. llvm::APSInt Result;
  80. Converted = VerifyIntegerConstantExpression(
  81. Converted.get(), &Result,
  82. diag::err_noexcept_needs_constant_expression,
  83. /*AllowFold*/ false);
  84. if (!Converted.isInvalid())
  85. EST = !Result ? EST_NoexceptFalse : EST_NoexceptTrue;
  86. return Converted;
  87. }
  88. /// CheckSpecifiedExceptionType - Check if the given type is valid in an
  89. /// exception specification. Incomplete types, or pointers to incomplete types
  90. /// other than void are not allowed.
  91. ///
  92. /// \param[in,out] T The exception type. This will be decayed to a pointer type
  93. /// when the input is an array or a function type.
  94. bool Sema::CheckSpecifiedExceptionType(QualType &T, SourceRange Range) {
  95. // C++11 [except.spec]p2:
  96. // A type cv T, "array of T", or "function returning T" denoted
  97. // in an exception-specification is adjusted to type T, "pointer to T", or
  98. // "pointer to function returning T", respectively.
  99. //
  100. // We also apply this rule in C++98.
  101. if (T->isArrayType())
  102. T = Context.getArrayDecayedType(T);
  103. else if (T->isFunctionType())
  104. T = Context.getPointerType(T);
  105. int Kind = 0;
  106. QualType PointeeT = T;
  107. if (const PointerType *PT = T->getAs<PointerType>()) {
  108. PointeeT = PT->getPointeeType();
  109. Kind = 1;
  110. // cv void* is explicitly permitted, despite being a pointer to an
  111. // incomplete type.
  112. if (PointeeT->isVoidType())
  113. return false;
  114. } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
  115. PointeeT = RT->getPointeeType();
  116. Kind = 2;
  117. if (RT->isRValueReferenceType()) {
  118. // C++11 [except.spec]p2:
  119. // A type denoted in an exception-specification shall not denote [...]
  120. // an rvalue reference type.
  121. Diag(Range.getBegin(), diag::err_rref_in_exception_spec)
  122. << T << Range;
  123. return true;
  124. }
  125. }
  126. // C++11 [except.spec]p2:
  127. // A type denoted in an exception-specification shall not denote an
  128. // incomplete type other than a class currently being defined [...].
  129. // A type denoted in an exception-specification shall not denote a
  130. // pointer or reference to an incomplete type, other than (cv) void* or a
  131. // pointer or reference to a class currently being defined.
  132. // In Microsoft mode, downgrade this to a warning.
  133. unsigned DiagID = diag::err_incomplete_in_exception_spec;
  134. bool ReturnValueOnError = true;
  135. if (getLangOpts().MicrosoftExt) {
  136. DiagID = diag::ext_incomplete_in_exception_spec;
  137. ReturnValueOnError = false;
  138. }
  139. if (!(PointeeT->isRecordType() &&
  140. PointeeT->getAs<RecordType>()->isBeingDefined()) &&
  141. RequireCompleteType(Range.getBegin(), PointeeT, DiagID, Kind, Range))
  142. return ReturnValueOnError;
  143. return false;
  144. }
  145. /// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer
  146. /// to member to a function with an exception specification. This means that
  147. /// it is invalid to add another level of indirection.
  148. bool Sema::CheckDistantExceptionSpec(QualType T) {
  149. // C++17 removes this rule in favor of putting exception specifications into
  150. // the type system.
  151. if (getLangOpts().CPlusPlus17)
  152. return false;
  153. if (const PointerType *PT = T->getAs<PointerType>())
  154. T = PT->getPointeeType();
  155. else if (const MemberPointerType *PT = T->getAs<MemberPointerType>())
  156. T = PT->getPointeeType();
  157. else
  158. return false;
  159. const FunctionProtoType *FnT = T->getAs<FunctionProtoType>();
  160. if (!FnT)
  161. return false;
  162. return FnT->hasExceptionSpec();
  163. }
  164. const FunctionProtoType *
  165. Sema::ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT) {
  166. if (FPT->getExceptionSpecType() == EST_Unparsed) {
  167. Diag(Loc, diag::err_exception_spec_not_parsed);
  168. return nullptr;
  169. }
  170. if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
  171. return FPT;
  172. FunctionDecl *SourceDecl = FPT->getExceptionSpecDecl();
  173. const FunctionProtoType *SourceFPT =
  174. SourceDecl->getType()->castAs<FunctionProtoType>();
  175. // If the exception specification has already been resolved, just return it.
  176. if (!isUnresolvedExceptionSpec(SourceFPT->getExceptionSpecType()))
  177. return SourceFPT;
  178. // Compute or instantiate the exception specification now.
  179. if (SourceFPT->getExceptionSpecType() == EST_Unevaluated)
  180. EvaluateImplicitExceptionSpec(Loc, cast<CXXMethodDecl>(SourceDecl));
  181. else
  182. InstantiateExceptionSpec(Loc, SourceDecl);
  183. const FunctionProtoType *Proto =
  184. SourceDecl->getType()->castAs<FunctionProtoType>();
  185. if (Proto->getExceptionSpecType() == clang::EST_Unparsed) {
  186. Diag(Loc, diag::err_exception_spec_not_parsed);
  187. Proto = nullptr;
  188. }
  189. return Proto;
  190. }
  191. void
  192. Sema::UpdateExceptionSpec(FunctionDecl *FD,
  193. const FunctionProtoType::ExceptionSpecInfo &ESI) {
  194. // If we've fully resolved the exception specification, notify listeners.
  195. if (!isUnresolvedExceptionSpec(ESI.Type))
  196. if (auto *Listener = getASTMutationListener())
  197. Listener->ResolvedExceptionSpec(FD);
  198. for (FunctionDecl *Redecl : FD->redecls())
  199. Context.adjustExceptionSpec(Redecl, ESI);
  200. }
  201. static bool exceptionSpecNotKnownYet(const FunctionDecl *FD) {
  202. auto *MD = dyn_cast<CXXMethodDecl>(FD);
  203. if (!MD)
  204. return false;
  205. auto EST = MD->getType()->castAs<FunctionProtoType>()->getExceptionSpecType();
  206. return EST == EST_Unparsed ||
  207. (EST == EST_Unevaluated && MD->getParent()->isBeingDefined());
  208. }
  209. static bool CheckEquivalentExceptionSpecImpl(
  210. Sema &S, const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID,
  211. const FunctionProtoType *Old, SourceLocation OldLoc,
  212. const FunctionProtoType *New, SourceLocation NewLoc,
  213. bool *MissingExceptionSpecification = nullptr,
  214. bool *MissingEmptyExceptionSpecification = nullptr,
  215. bool AllowNoexceptAllMatchWithNoSpec = false, bool IsOperatorNew = false);
  216. /// Determine whether a function has an implicitly-generated exception
  217. /// specification.
  218. static bool hasImplicitExceptionSpec(FunctionDecl *Decl) {
  219. if (!isa<CXXDestructorDecl>(Decl) &&
  220. Decl->getDeclName().getCXXOverloadedOperator() != OO_Delete &&
  221. Decl->getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
  222. return false;
  223. // For a function that the user didn't declare:
  224. // - if this is a destructor, its exception specification is implicit.
  225. // - if this is 'operator delete' or 'operator delete[]', the exception
  226. // specification is as-if an explicit exception specification was given
  227. // (per [basic.stc.dynamic]p2).
  228. if (!Decl->getTypeSourceInfo())
  229. return isa<CXXDestructorDecl>(Decl);
  230. const FunctionProtoType *Ty =
  231. Decl->getTypeSourceInfo()->getType()->getAs<FunctionProtoType>();
  232. return !Ty->hasExceptionSpec();
  233. }
  234. bool Sema::CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New) {
  235. // Just completely ignore this under -fno-exceptions prior to C++17.
  236. // In C++17 onwards, the exception specification is part of the type and
  237. // we will diagnose mismatches anyway, so it's better to check for them here.
  238. if (!getLangOpts().CXXExceptions && !getLangOpts().CPlusPlus17)
  239. return false;
  240. OverloadedOperatorKind OO = New->getDeclName().getCXXOverloadedOperator();
  241. bool IsOperatorNew = OO == OO_New || OO == OO_Array_New;
  242. bool MissingExceptionSpecification = false;
  243. bool MissingEmptyExceptionSpecification = false;
  244. unsigned DiagID = diag::err_mismatched_exception_spec;
  245. bool ReturnValueOnError = true;
  246. if (getLangOpts().MicrosoftExt) {
  247. DiagID = diag::ext_mismatched_exception_spec;
  248. ReturnValueOnError = false;
  249. }
  250. // If we're befriending a member function of a class that's currently being
  251. // defined, we might not be able to work out its exception specification yet.
  252. // If not, defer the check until later.
  253. if (exceptionSpecNotKnownYet(Old) || exceptionSpecNotKnownYet(New)) {
  254. DelayedEquivalentExceptionSpecChecks.push_back({New, Old});
  255. return false;
  256. }
  257. // Check the types as written: they must match before any exception
  258. // specification adjustment is applied.
  259. if (!CheckEquivalentExceptionSpecImpl(
  260. *this, PDiag(DiagID), PDiag(diag::note_previous_declaration),
  261. Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
  262. New->getType()->getAs<FunctionProtoType>(), New->getLocation(),
  263. &MissingExceptionSpecification, &MissingEmptyExceptionSpecification,
  264. /*AllowNoexceptAllMatchWithNoSpec=*/true, IsOperatorNew)) {
  265. // C++11 [except.spec]p4 [DR1492]:
  266. // If a declaration of a function has an implicit
  267. // exception-specification, other declarations of the function shall
  268. // not specify an exception-specification.
  269. if (getLangOpts().CPlusPlus11 && getLangOpts().CXXExceptions &&
  270. hasImplicitExceptionSpec(Old) != hasImplicitExceptionSpec(New)) {
  271. Diag(New->getLocation(), diag::ext_implicit_exception_spec_mismatch)
  272. << hasImplicitExceptionSpec(Old);
  273. if (Old->getLocation().isValid())
  274. Diag(Old->getLocation(), diag::note_previous_declaration);
  275. }
  276. return false;
  277. }
  278. // The failure was something other than an missing exception
  279. // specification; return an error, except in MS mode where this is a warning.
  280. if (!MissingExceptionSpecification)
  281. return ReturnValueOnError;
  282. const FunctionProtoType *NewProto =
  283. New->getType()->castAs<FunctionProtoType>();
  284. // The new function declaration is only missing an empty exception
  285. // specification "throw()". If the throw() specification came from a
  286. // function in a system header that has C linkage, just add an empty
  287. // exception specification to the "new" declaration. Note that C library
  288. // implementations are permitted to add these nothrow exception
  289. // specifications.
  290. //
  291. // Likewise if the old function is a builtin.
  292. if (MissingEmptyExceptionSpecification && NewProto &&
  293. (Old->getLocation().isInvalid() ||
  294. Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
  295. Old->getBuiltinID()) &&
  296. Old->isExternC()) {
  297. New->setType(Context.getFunctionType(
  298. NewProto->getReturnType(), NewProto->getParamTypes(),
  299. NewProto->getExtProtoInfo().withExceptionSpec(EST_DynamicNone)));
  300. return false;
  301. }
  302. const FunctionProtoType *OldProto =
  303. Old->getType()->castAs<FunctionProtoType>();
  304. FunctionProtoType::ExceptionSpecInfo ESI = OldProto->getExceptionSpecType();
  305. if (ESI.Type == EST_Dynamic) {
  306. // FIXME: What if the exceptions are described in terms of the old
  307. // prototype's parameters?
  308. ESI.Exceptions = OldProto->exceptions();
  309. }
  310. if (ESI.Type == EST_NoexceptFalse)
  311. ESI.Type = EST_None;
  312. if (ESI.Type == EST_NoexceptTrue)
  313. ESI.Type = EST_BasicNoexcept;
  314. // For dependent noexcept, we can't just take the expression from the old
  315. // prototype. It likely contains references to the old prototype's parameters.
  316. if (ESI.Type == EST_DependentNoexcept) {
  317. New->setInvalidDecl();
  318. } else {
  319. // Update the type of the function with the appropriate exception
  320. // specification.
  321. New->setType(Context.getFunctionType(
  322. NewProto->getReturnType(), NewProto->getParamTypes(),
  323. NewProto->getExtProtoInfo().withExceptionSpec(ESI)));
  324. }
  325. if (getLangOpts().MicrosoftExt && ESI.Type != EST_DependentNoexcept) {
  326. // Allow missing exception specifications in redeclarations as an extension.
  327. DiagID = diag::ext_ms_missing_exception_specification;
  328. ReturnValueOnError = false;
  329. } else if (New->isReplaceableGlobalAllocationFunction() &&
  330. ESI.Type != EST_DependentNoexcept) {
  331. // Allow missing exception specifications in redeclarations as an extension,
  332. // when declaring a replaceable global allocation function.
  333. DiagID = diag::ext_missing_exception_specification;
  334. ReturnValueOnError = false;
  335. } else {
  336. DiagID = diag::err_missing_exception_specification;
  337. ReturnValueOnError = true;
  338. }
  339. // Warn about the lack of exception specification.
  340. SmallString<128> ExceptionSpecString;
  341. llvm::raw_svector_ostream OS(ExceptionSpecString);
  342. switch (OldProto->getExceptionSpecType()) {
  343. case EST_DynamicNone:
  344. OS << "throw()";
  345. break;
  346. case EST_Dynamic: {
  347. OS << "throw(";
  348. bool OnFirstException = true;
  349. for (const auto &E : OldProto->exceptions()) {
  350. if (OnFirstException)
  351. OnFirstException = false;
  352. else
  353. OS << ", ";
  354. OS << E.getAsString(getPrintingPolicy());
  355. }
  356. OS << ")";
  357. break;
  358. }
  359. case EST_BasicNoexcept:
  360. OS << "noexcept";
  361. break;
  362. case EST_DependentNoexcept:
  363. case EST_NoexceptFalse:
  364. case EST_NoexceptTrue:
  365. OS << "noexcept(";
  366. assert(OldProto->getNoexceptExpr() != nullptr && "Expected non-null Expr");
  367. OldProto->getNoexceptExpr()->printPretty(OS, nullptr, getPrintingPolicy());
  368. OS << ")";
  369. break;
  370. default:
  371. llvm_unreachable("This spec type is compatible with none.");
  372. }
  373. SourceLocation FixItLoc;
  374. if (TypeSourceInfo *TSInfo = New->getTypeSourceInfo()) {
  375. TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
  376. // FIXME: Preserve enough information so that we can produce a correct fixit
  377. // location when there is a trailing return type.
  378. if (auto FTLoc = TL.getAs<FunctionProtoTypeLoc>())
  379. if (!FTLoc.getTypePtr()->hasTrailingReturn())
  380. FixItLoc = getLocForEndOfToken(FTLoc.getLocalRangeEnd());
  381. }
  382. if (FixItLoc.isInvalid())
  383. Diag(New->getLocation(), DiagID)
  384. << New << OS.str();
  385. else {
  386. Diag(New->getLocation(), DiagID)
  387. << New << OS.str()
  388. << FixItHint::CreateInsertion(FixItLoc, " " + OS.str().str());
  389. }
  390. if (Old->getLocation().isValid())
  391. Diag(Old->getLocation(), diag::note_previous_declaration);
  392. return ReturnValueOnError;
  393. }
  394. /// CheckEquivalentExceptionSpec - Check if the two types have equivalent
  395. /// exception specifications. Exception specifications are equivalent if
  396. /// they allow exactly the same set of exception types. It does not matter how
  397. /// that is achieved. See C++ [except.spec]p2.
  398. bool Sema::CheckEquivalentExceptionSpec(
  399. const FunctionProtoType *Old, SourceLocation OldLoc,
  400. const FunctionProtoType *New, SourceLocation NewLoc) {
  401. if (!getLangOpts().CXXExceptions)
  402. return false;
  403. unsigned DiagID = diag::err_mismatched_exception_spec;
  404. if (getLangOpts().MicrosoftExt)
  405. DiagID = diag::ext_mismatched_exception_spec;
  406. bool Result = CheckEquivalentExceptionSpecImpl(
  407. *this, PDiag(DiagID), PDiag(diag::note_previous_declaration),
  408. Old, OldLoc, New, NewLoc);
  409. // In Microsoft mode, mismatching exception specifications just cause a warning.
  410. if (getLangOpts().MicrosoftExt)
  411. return false;
  412. return Result;
  413. }
  414. /// CheckEquivalentExceptionSpec - Check if the two types have compatible
  415. /// exception specifications. See C++ [except.spec]p3.
  416. ///
  417. /// \return \c false if the exception specifications match, \c true if there is
  418. /// a problem. If \c true is returned, either a diagnostic has already been
  419. /// produced or \c *MissingExceptionSpecification is set to \c true.
  420. static bool CheckEquivalentExceptionSpecImpl(
  421. Sema &S, const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID,
  422. const FunctionProtoType *Old, SourceLocation OldLoc,
  423. const FunctionProtoType *New, SourceLocation NewLoc,
  424. bool *MissingExceptionSpecification,
  425. bool *MissingEmptyExceptionSpecification,
  426. bool AllowNoexceptAllMatchWithNoSpec, bool IsOperatorNew) {
  427. if (MissingExceptionSpecification)
  428. *MissingExceptionSpecification = false;
  429. if (MissingEmptyExceptionSpecification)
  430. *MissingEmptyExceptionSpecification = false;
  431. Old = S.ResolveExceptionSpec(NewLoc, Old);
  432. if (!Old)
  433. return false;
  434. New = S.ResolveExceptionSpec(NewLoc, New);
  435. if (!New)
  436. return false;
  437. // C++0x [except.spec]p3: Two exception-specifications are compatible if:
  438. // - both are non-throwing, regardless of their form,
  439. // - both have the form noexcept(constant-expression) and the constant-
  440. // expressions are equivalent,
  441. // - both are dynamic-exception-specifications that have the same set of
  442. // adjusted types.
  443. //
  444. // C++0x [except.spec]p12: An exception-specification is non-throwing if it is
  445. // of the form throw(), noexcept, or noexcept(constant-expression) where the
  446. // constant-expression yields true.
  447. //
  448. // C++0x [except.spec]p4: If any declaration of a function has an exception-
  449. // specifier that is not a noexcept-specification allowing all exceptions,
  450. // all declarations [...] of that function shall have a compatible
  451. // exception-specification.
  452. //
  453. // That last point basically means that noexcept(false) matches no spec.
  454. // It's considered when AllowNoexceptAllMatchWithNoSpec is true.
  455. ExceptionSpecificationType OldEST = Old->getExceptionSpecType();
  456. ExceptionSpecificationType NewEST = New->getExceptionSpecType();
  457. assert(!isUnresolvedExceptionSpec(OldEST) &&
  458. !isUnresolvedExceptionSpec(NewEST) &&
  459. "Shouldn't see unknown exception specifications here");
  460. CanThrowResult OldCanThrow = Old->canThrow();
  461. CanThrowResult NewCanThrow = New->canThrow();
  462. // Any non-throwing specifications are compatible.
  463. if (OldCanThrow == CT_Cannot && NewCanThrow == CT_Cannot)
  464. return false;
  465. // Any throws-anything specifications are usually compatible.
  466. if (OldCanThrow == CT_Can && OldEST != EST_Dynamic &&
  467. NewCanThrow == CT_Can && NewEST != EST_Dynamic) {
  468. // The exception is that the absence of an exception specification only
  469. // matches noexcept(false) for functions, as described above.
  470. if (!AllowNoexceptAllMatchWithNoSpec &&
  471. ((OldEST == EST_None && NewEST == EST_NoexceptFalse) ||
  472. (OldEST == EST_NoexceptFalse && NewEST == EST_None))) {
  473. // This is the disallowed case.
  474. } else {
  475. return false;
  476. }
  477. }
  478. // C++14 [except.spec]p3:
  479. // Two exception-specifications are compatible if [...] both have the form
  480. // noexcept(constant-expression) and the constant-expressions are equivalent
  481. if (OldEST == EST_DependentNoexcept && NewEST == EST_DependentNoexcept) {
  482. llvm::FoldingSetNodeID OldFSN, NewFSN;
  483. Old->getNoexceptExpr()->Profile(OldFSN, S.Context, true);
  484. New->getNoexceptExpr()->Profile(NewFSN, S.Context, true);
  485. if (OldFSN == NewFSN)
  486. return false;
  487. }
  488. // Dynamic exception specifications with the same set of adjusted types
  489. // are compatible.
  490. if (OldEST == EST_Dynamic && NewEST == EST_Dynamic) {
  491. bool Success = true;
  492. // Both have a dynamic exception spec. Collect the first set, then compare
  493. // to the second.
  494. llvm::SmallPtrSet<CanQualType, 8> OldTypes, NewTypes;
  495. for (const auto &I : Old->exceptions())
  496. OldTypes.insert(S.Context.getCanonicalType(I).getUnqualifiedType());
  497. for (const auto &I : New->exceptions()) {
  498. CanQualType TypePtr = S.Context.getCanonicalType(I).getUnqualifiedType();
  499. if (OldTypes.count(TypePtr))
  500. NewTypes.insert(TypePtr);
  501. else {
  502. Success = false;
  503. break;
  504. }
  505. }
  506. if (Success && OldTypes.size() == NewTypes.size())
  507. return false;
  508. }
  509. // As a special compatibility feature, under C++0x we accept no spec and
  510. // throw(std::bad_alloc) as equivalent for operator new and operator new[].
  511. // This is because the implicit declaration changed, but old code would break.
  512. if (S.getLangOpts().CPlusPlus11 && IsOperatorNew) {
  513. const FunctionProtoType *WithExceptions = nullptr;
  514. if (OldEST == EST_None && NewEST == EST_Dynamic)
  515. WithExceptions = New;
  516. else if (OldEST == EST_Dynamic && NewEST == EST_None)
  517. WithExceptions = Old;
  518. if (WithExceptions && WithExceptions->getNumExceptions() == 1) {
  519. // One has no spec, the other throw(something). If that something is
  520. // std::bad_alloc, all conditions are met.
  521. QualType Exception = *WithExceptions->exception_begin();
  522. if (CXXRecordDecl *ExRecord = Exception->getAsCXXRecordDecl()) {
  523. IdentifierInfo* Name = ExRecord->getIdentifier();
  524. if (Name && Name->getName() == "bad_alloc") {
  525. // It's called bad_alloc, but is it in std?
  526. if (ExRecord->isInStdNamespace()) {
  527. return false;
  528. }
  529. }
  530. }
  531. }
  532. }
  533. // If the caller wants to handle the case that the new function is
  534. // incompatible due to a missing exception specification, let it.
  535. if (MissingExceptionSpecification && OldEST != EST_None &&
  536. NewEST == EST_None) {
  537. // The old type has an exception specification of some sort, but
  538. // the new type does not.
  539. *MissingExceptionSpecification = true;
  540. if (MissingEmptyExceptionSpecification && OldCanThrow == CT_Cannot) {
  541. // The old type has a throw() or noexcept(true) exception specification
  542. // and the new type has no exception specification, and the caller asked
  543. // to handle this itself.
  544. *MissingEmptyExceptionSpecification = true;
  545. }
  546. return true;
  547. }
  548. S.Diag(NewLoc, DiagID);
  549. if (NoteID.getDiagID() != 0 && OldLoc.isValid())
  550. S.Diag(OldLoc, NoteID);
  551. return true;
  552. }
  553. bool Sema::CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
  554. const PartialDiagnostic &NoteID,
  555. const FunctionProtoType *Old,
  556. SourceLocation OldLoc,
  557. const FunctionProtoType *New,
  558. SourceLocation NewLoc) {
  559. if (!getLangOpts().CXXExceptions)
  560. return false;
  561. return CheckEquivalentExceptionSpecImpl(*this, DiagID, NoteID, Old, OldLoc,
  562. New, NewLoc);
  563. }
  564. bool Sema::handlerCanCatch(QualType HandlerType, QualType ExceptionType) {
  565. // [except.handle]p3:
  566. // A handler is a match for an exception object of type E if:
  567. // HandlerType must be ExceptionType or derived from it, or pointer or
  568. // reference to such types.
  569. const ReferenceType *RefTy = HandlerType->getAs<ReferenceType>();
  570. if (RefTy)
  571. HandlerType = RefTy->getPointeeType();
  572. // -- the handler is of type cv T or cv T& and E and T are the same type
  573. if (Context.hasSameUnqualifiedType(ExceptionType, HandlerType))
  574. return true;
  575. // FIXME: ObjC pointer types?
  576. if (HandlerType->isPointerType() || HandlerType->isMemberPointerType()) {
  577. if (RefTy && (!HandlerType.isConstQualified() ||
  578. HandlerType.isVolatileQualified()))
  579. return false;
  580. // -- the handler is of type cv T or const T& where T is a pointer or
  581. // pointer to member type and E is std::nullptr_t
  582. if (ExceptionType->isNullPtrType())
  583. return true;
  584. // -- the handler is of type cv T or const T& where T is a pointer or
  585. // pointer to member type and E is a pointer or pointer to member type
  586. // that can be converted to T by one or more of
  587. // -- a qualification conversion
  588. // -- a function pointer conversion
  589. bool LifetimeConv;
  590. QualType Result;
  591. // FIXME: Should we treat the exception as catchable if a lifetime
  592. // conversion is required?
  593. if (IsQualificationConversion(ExceptionType, HandlerType, false,
  594. LifetimeConv) ||
  595. IsFunctionConversion(ExceptionType, HandlerType, Result))
  596. return true;
  597. // -- a standard pointer conversion [...]
  598. if (!ExceptionType->isPointerType() || !HandlerType->isPointerType())
  599. return false;
  600. // Handle the "qualification conversion" portion.
  601. Qualifiers EQuals, HQuals;
  602. ExceptionType = Context.getUnqualifiedArrayType(
  603. ExceptionType->getPointeeType(), EQuals);
  604. HandlerType = Context.getUnqualifiedArrayType(
  605. HandlerType->getPointeeType(), HQuals);
  606. if (!HQuals.compatiblyIncludes(EQuals))
  607. return false;
  608. if (HandlerType->isVoidType() && ExceptionType->isObjectType())
  609. return true;
  610. // The only remaining case is a derived-to-base conversion.
  611. }
  612. // -- the handler is of type cg T or cv T& and T is an unambiguous public
  613. // base class of E
  614. if (!ExceptionType->isRecordType() || !HandlerType->isRecordType())
  615. return false;
  616. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  617. /*DetectVirtual=*/false);
  618. if (!IsDerivedFrom(SourceLocation(), ExceptionType, HandlerType, Paths) ||
  619. Paths.isAmbiguous(Context.getCanonicalType(HandlerType)))
  620. return false;
  621. // Do this check from a context without privileges.
  622. switch (CheckBaseClassAccess(SourceLocation(), HandlerType, ExceptionType,
  623. Paths.front(),
  624. /*Diagnostic*/ 0,
  625. /*ForceCheck*/ true,
  626. /*ForceUnprivileged*/ true)) {
  627. case AR_accessible: return true;
  628. case AR_inaccessible: return false;
  629. case AR_dependent:
  630. llvm_unreachable("access check dependent for unprivileged context");
  631. case AR_delayed:
  632. llvm_unreachable("access check delayed in non-declaration");
  633. }
  634. llvm_unreachable("unexpected access check result");
  635. }
  636. /// CheckExceptionSpecSubset - Check whether the second function type's
  637. /// exception specification is a subset (or equivalent) of the first function
  638. /// type. This is used by override and pointer assignment checks.
  639. bool Sema::CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
  640. const PartialDiagnostic &NestedDiagID,
  641. const PartialDiagnostic &NoteID,
  642. const FunctionProtoType *Superset,
  643. SourceLocation SuperLoc,
  644. const FunctionProtoType *Subset,
  645. SourceLocation SubLoc) {
  646. // Just auto-succeed under -fno-exceptions.
  647. if (!getLangOpts().CXXExceptions)
  648. return false;
  649. // FIXME: As usual, we could be more specific in our error messages, but
  650. // that better waits until we've got types with source locations.
  651. if (!SubLoc.isValid())
  652. SubLoc = SuperLoc;
  653. // Resolve the exception specifications, if needed.
  654. Superset = ResolveExceptionSpec(SuperLoc, Superset);
  655. if (!Superset)
  656. return false;
  657. Subset = ResolveExceptionSpec(SubLoc, Subset);
  658. if (!Subset)
  659. return false;
  660. ExceptionSpecificationType SuperEST = Superset->getExceptionSpecType();
  661. ExceptionSpecificationType SubEST = Subset->getExceptionSpecType();
  662. assert(!isUnresolvedExceptionSpec(SuperEST) &&
  663. !isUnresolvedExceptionSpec(SubEST) &&
  664. "Shouldn't see unknown exception specifications here");
  665. // If there are dependent noexcept specs, assume everything is fine. Unlike
  666. // with the equivalency check, this is safe in this case, because we don't
  667. // want to merge declarations. Checks after instantiation will catch any
  668. // omissions we make here.
  669. if (SuperEST == EST_DependentNoexcept || SubEST == EST_DependentNoexcept)
  670. return false;
  671. CanThrowResult SuperCanThrow = Superset->canThrow();
  672. CanThrowResult SubCanThrow = Subset->canThrow();
  673. // If the superset contains everything or the subset contains nothing, we're
  674. // done.
  675. if ((SuperCanThrow == CT_Can && SuperEST != EST_Dynamic) ||
  676. SubCanThrow == CT_Cannot)
  677. return CheckParamExceptionSpec(NestedDiagID, NoteID, Superset, SuperLoc,
  678. Subset, SubLoc);
  679. // If the subset contains everything or the superset contains nothing, we've
  680. // failed.
  681. if ((SubCanThrow == CT_Can && SubEST != EST_Dynamic) ||
  682. SuperCanThrow == CT_Cannot) {
  683. Diag(SubLoc, DiagID);
  684. if (NoteID.getDiagID() != 0)
  685. Diag(SuperLoc, NoteID);
  686. return true;
  687. }
  688. assert(SuperEST == EST_Dynamic && SubEST == EST_Dynamic &&
  689. "Exception spec subset: non-dynamic case slipped through.");
  690. // Neither contains everything or nothing. Do a proper comparison.
  691. for (QualType SubI : Subset->exceptions()) {
  692. if (const ReferenceType *RefTy = SubI->getAs<ReferenceType>())
  693. SubI = RefTy->getPointeeType();
  694. // Make sure it's in the superset.
  695. bool Contained = false;
  696. for (QualType SuperI : Superset->exceptions()) {
  697. // [except.spec]p5:
  698. // the target entity shall allow at least the exceptions allowed by the
  699. // source
  700. //
  701. // We interpret this as meaning that a handler for some target type would
  702. // catch an exception of each source type.
  703. if (handlerCanCatch(SuperI, SubI)) {
  704. Contained = true;
  705. break;
  706. }
  707. }
  708. if (!Contained) {
  709. Diag(SubLoc, DiagID);
  710. if (NoteID.getDiagID() != 0)
  711. Diag(SuperLoc, NoteID);
  712. return true;
  713. }
  714. }
  715. // We've run half the gauntlet.
  716. return CheckParamExceptionSpec(NestedDiagID, NoteID, Superset, SuperLoc,
  717. Subset, SubLoc);
  718. }
  719. static bool
  720. CheckSpecForTypesEquivalent(Sema &S, const PartialDiagnostic &DiagID,
  721. const PartialDiagnostic &NoteID, QualType Target,
  722. SourceLocation TargetLoc, QualType Source,
  723. SourceLocation SourceLoc) {
  724. const FunctionProtoType *TFunc = GetUnderlyingFunction(Target);
  725. if (!TFunc)
  726. return false;
  727. const FunctionProtoType *SFunc = GetUnderlyingFunction(Source);
  728. if (!SFunc)
  729. return false;
  730. return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc,
  731. SFunc, SourceLoc);
  732. }
  733. /// CheckParamExceptionSpec - Check if the parameter and return types of the
  734. /// two functions have equivalent exception specs. This is part of the
  735. /// assignment and override compatibility check. We do not check the parameters
  736. /// of parameter function pointers recursively, as no sane programmer would
  737. /// even be able to write such a function type.
  738. bool Sema::CheckParamExceptionSpec(const PartialDiagnostic &DiagID,
  739. const PartialDiagnostic &NoteID,
  740. const FunctionProtoType *Target,
  741. SourceLocation TargetLoc,
  742. const FunctionProtoType *Source,
  743. SourceLocation SourceLoc) {
  744. auto RetDiag = DiagID;
  745. RetDiag << 0;
  746. if (CheckSpecForTypesEquivalent(
  747. *this, RetDiag, PDiag(),
  748. Target->getReturnType(), TargetLoc, Source->getReturnType(),
  749. SourceLoc))
  750. return true;
  751. // We shouldn't even be testing this unless the arguments are otherwise
  752. // compatible.
  753. assert(Target->getNumParams() == Source->getNumParams() &&
  754. "Functions have different argument counts.");
  755. for (unsigned i = 0, E = Target->getNumParams(); i != E; ++i) {
  756. auto ParamDiag = DiagID;
  757. ParamDiag << 1;
  758. if (CheckSpecForTypesEquivalent(
  759. *this, ParamDiag, PDiag(),
  760. Target->getParamType(i), TargetLoc, Source->getParamType(i),
  761. SourceLoc))
  762. return true;
  763. }
  764. return false;
  765. }
  766. bool Sema::CheckExceptionSpecCompatibility(Expr *From, QualType ToType) {
  767. // First we check for applicability.
  768. // Target type must be a function, function pointer or function reference.
  769. const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType);
  770. if (!ToFunc || ToFunc->hasDependentExceptionSpec())
  771. return false;
  772. // SourceType must be a function or function pointer.
  773. const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType());
  774. if (!FromFunc || FromFunc->hasDependentExceptionSpec())
  775. return false;
  776. unsigned DiagID = diag::err_incompatible_exception_specs;
  777. unsigned NestedDiagID = diag::err_deep_exception_specs_differ;
  778. // This is not an error in C++17 onwards, unless the noexceptness doesn't
  779. // match, but in that case we have a full-on type mismatch, not just a
  780. // type sugar mismatch.
  781. if (getLangOpts().CPlusPlus17) {
  782. DiagID = diag::warn_incompatible_exception_specs;
  783. NestedDiagID = diag::warn_deep_exception_specs_differ;
  784. }
  785. // Now we've got the correct types on both sides, check their compatibility.
  786. // This means that the source of the conversion can only throw a subset of
  787. // the exceptions of the target, and any exception specs on arguments or
  788. // return types must be equivalent.
  789. //
  790. // FIXME: If there is a nested dependent exception specification, we should
  791. // not be checking it here. This is fine:
  792. // template<typename T> void f() {
  793. // void (*p)(void (*) throw(T));
  794. // void (*q)(void (*) throw(int)) = p;
  795. // }
  796. // ... because it might be instantiated with T=int.
  797. return CheckExceptionSpecSubset(PDiag(DiagID), PDiag(NestedDiagID), PDiag(),
  798. ToFunc, From->getSourceRange().getBegin(),
  799. FromFunc, SourceLocation()) &&
  800. !getLangOpts().CPlusPlus17;
  801. }
  802. bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
  803. const CXXMethodDecl *Old) {
  804. // If the new exception specification hasn't been parsed yet, skip the check.
  805. // We'll get called again once it's been parsed.
  806. if (New->getType()->castAs<FunctionProtoType>()->getExceptionSpecType() ==
  807. EST_Unparsed)
  808. return false;
  809. // Don't check uninstantiated template destructors at all. We can only
  810. // synthesize correct specs after the template is instantiated.
  811. if (isa<CXXDestructorDecl>(New) && New->getParent()->isDependentType())
  812. return false;
  813. // If the old exception specification hasn't been parsed yet, or the new
  814. // exception specification can't be computed yet, remember that we need to
  815. // perform this check when we get to the end of the outermost
  816. // lexically-surrounding class.
  817. if (exceptionSpecNotKnownYet(Old) || exceptionSpecNotKnownYet(New)) {
  818. DelayedOverridingExceptionSpecChecks.push_back({New, Old});
  819. return false;
  820. }
  821. unsigned DiagID = diag::err_override_exception_spec;
  822. if (getLangOpts().MicrosoftExt)
  823. DiagID = diag::ext_override_exception_spec;
  824. return CheckExceptionSpecSubset(PDiag(DiagID),
  825. PDiag(diag::err_deep_exception_specs_differ),
  826. PDiag(diag::note_overridden_virtual_function),
  827. Old->getType()->getAs<FunctionProtoType>(),
  828. Old->getLocation(),
  829. New->getType()->getAs<FunctionProtoType>(),
  830. New->getLocation());
  831. }
  832. static CanThrowResult canSubExprsThrow(Sema &S, const Expr *E) {
  833. CanThrowResult R = CT_Cannot;
  834. for (const Stmt *SubStmt : E->children()) {
  835. R = mergeCanThrow(R, S.canThrow(cast<Expr>(SubStmt)));
  836. if (R == CT_Can)
  837. break;
  838. }
  839. return R;
  840. }
  841. static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D) {
  842. // As an extension, we assume that __attribute__((nothrow)) functions don't
  843. // throw.
  844. if (D && isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())
  845. return CT_Cannot;
  846. QualType T;
  847. // In C++1z, just look at the function type of the callee.
  848. if (S.getLangOpts().CPlusPlus17 && isa<CallExpr>(E)) {
  849. E = cast<CallExpr>(E)->getCallee();
  850. T = E->getType();
  851. if (T->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
  852. // Sadly we don't preserve the actual type as part of the "bound member"
  853. // placeholder, so we need to reconstruct it.
  854. E = E->IgnoreParenImpCasts();
  855. // Could be a call to a pointer-to-member or a plain member access.
  856. if (auto *Op = dyn_cast<BinaryOperator>(E)) {
  857. assert(Op->getOpcode() == BO_PtrMemD || Op->getOpcode() == BO_PtrMemI);
  858. T = Op->getRHS()->getType()
  859. ->castAs<MemberPointerType>()->getPointeeType();
  860. } else {
  861. T = cast<MemberExpr>(E)->getMemberDecl()->getType();
  862. }
  863. }
  864. } else if (const ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D))
  865. T = VD->getType();
  866. else
  867. // If we have no clue what we're calling, assume the worst.
  868. return CT_Can;
  869. const FunctionProtoType *FT;
  870. if ((FT = T->getAs<FunctionProtoType>())) {
  871. } else if (const PointerType *PT = T->getAs<PointerType>())
  872. FT = PT->getPointeeType()->getAs<FunctionProtoType>();
  873. else if (const ReferenceType *RT = T->getAs<ReferenceType>())
  874. FT = RT->getPointeeType()->getAs<FunctionProtoType>();
  875. else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
  876. FT = MT->getPointeeType()->getAs<FunctionProtoType>();
  877. else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
  878. FT = BT->getPointeeType()->getAs<FunctionProtoType>();
  879. if (!FT)
  880. return CT_Can;
  881. FT = S.ResolveExceptionSpec(E->getBeginLoc(), FT);
  882. if (!FT)
  883. return CT_Can;
  884. return FT->canThrow();
  885. }
  886. static CanThrowResult canDynamicCastThrow(const CXXDynamicCastExpr *DC) {
  887. if (DC->isTypeDependent())
  888. return CT_Dependent;
  889. if (!DC->getTypeAsWritten()->isReferenceType())
  890. return CT_Cannot;
  891. if (DC->getSubExpr()->isTypeDependent())
  892. return CT_Dependent;
  893. return DC->getCastKind() == clang::CK_Dynamic? CT_Can : CT_Cannot;
  894. }
  895. static CanThrowResult canTypeidThrow(Sema &S, const CXXTypeidExpr *DC) {
  896. if (DC->isTypeOperand())
  897. return CT_Cannot;
  898. Expr *Op = DC->getExprOperand();
  899. if (Op->isTypeDependent())
  900. return CT_Dependent;
  901. const RecordType *RT = Op->getType()->getAs<RecordType>();
  902. if (!RT)
  903. return CT_Cannot;
  904. if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
  905. return CT_Cannot;
  906. if (Op->Classify(S.Context).isPRValue())
  907. return CT_Cannot;
  908. return CT_Can;
  909. }
  910. CanThrowResult Sema::canThrow(const Expr *E) {
  911. // C++ [expr.unary.noexcept]p3:
  912. // [Can throw] if in a potentially-evaluated context the expression would
  913. // contain:
  914. switch (E->getStmtClass()) {
  915. case Expr::ConstantExprClass:
  916. return canThrow(cast<ConstantExpr>(E)->getSubExpr());
  917. case Expr::CXXThrowExprClass:
  918. // - a potentially evaluated throw-expression
  919. return CT_Can;
  920. case Expr::CXXDynamicCastExprClass: {
  921. // - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
  922. // where T is a reference type, that requires a run-time check
  923. CanThrowResult CT = canDynamicCastThrow(cast<CXXDynamicCastExpr>(E));
  924. if (CT == CT_Can)
  925. return CT;
  926. return mergeCanThrow(CT, canSubExprsThrow(*this, E));
  927. }
  928. case Expr::CXXTypeidExprClass:
  929. // - a potentially evaluated typeid expression applied to a glvalue
  930. // expression whose type is a polymorphic class type
  931. return canTypeidThrow(*this, cast<CXXTypeidExpr>(E));
  932. // - a potentially evaluated call to a function, member function, function
  933. // pointer, or member function pointer that does not have a non-throwing
  934. // exception-specification
  935. case Expr::CallExprClass:
  936. case Expr::CXXMemberCallExprClass:
  937. case Expr::CXXOperatorCallExprClass:
  938. case Expr::UserDefinedLiteralClass: {
  939. const CallExpr *CE = cast<CallExpr>(E);
  940. CanThrowResult CT;
  941. if (E->isTypeDependent())
  942. CT = CT_Dependent;
  943. else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens()))
  944. CT = CT_Cannot;
  945. else
  946. CT = canCalleeThrow(*this, E, CE->getCalleeDecl());
  947. if (CT == CT_Can)
  948. return CT;
  949. return mergeCanThrow(CT, canSubExprsThrow(*this, E));
  950. }
  951. case Expr::CXXConstructExprClass:
  952. case Expr::CXXTemporaryObjectExprClass: {
  953. CanThrowResult CT = canCalleeThrow(*this, E,
  954. cast<CXXConstructExpr>(E)->getConstructor());
  955. if (CT == CT_Can)
  956. return CT;
  957. return mergeCanThrow(CT, canSubExprsThrow(*this, E));
  958. }
  959. case Expr::CXXInheritedCtorInitExprClass:
  960. return canCalleeThrow(*this, E,
  961. cast<CXXInheritedCtorInitExpr>(E)->getConstructor());
  962. case Expr::LambdaExprClass: {
  963. const LambdaExpr *Lambda = cast<LambdaExpr>(E);
  964. CanThrowResult CT = CT_Cannot;
  965. for (LambdaExpr::const_capture_init_iterator
  966. Cap = Lambda->capture_init_begin(),
  967. CapEnd = Lambda->capture_init_end();
  968. Cap != CapEnd; ++Cap)
  969. CT = mergeCanThrow(CT, canThrow(*Cap));
  970. return CT;
  971. }
  972. case Expr::CXXNewExprClass: {
  973. CanThrowResult CT;
  974. if (E->isTypeDependent())
  975. CT = CT_Dependent;
  976. else
  977. CT = canCalleeThrow(*this, E, cast<CXXNewExpr>(E)->getOperatorNew());
  978. if (CT == CT_Can)
  979. return CT;
  980. return mergeCanThrow(CT, canSubExprsThrow(*this, E));
  981. }
  982. case Expr::CXXDeleteExprClass: {
  983. CanThrowResult CT;
  984. QualType DTy = cast<CXXDeleteExpr>(E)->getDestroyedType();
  985. if (DTy.isNull() || DTy->isDependentType()) {
  986. CT = CT_Dependent;
  987. } else {
  988. CT = canCalleeThrow(*this, E,
  989. cast<CXXDeleteExpr>(E)->getOperatorDelete());
  990. if (const RecordType *RT = DTy->getAs<RecordType>()) {
  991. const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
  992. const CXXDestructorDecl *DD = RD->getDestructor();
  993. if (DD)
  994. CT = mergeCanThrow(CT, canCalleeThrow(*this, E, DD));
  995. }
  996. if (CT == CT_Can)
  997. return CT;
  998. }
  999. return mergeCanThrow(CT, canSubExprsThrow(*this, E));
  1000. }
  1001. case Expr::CXXBindTemporaryExprClass: {
  1002. // The bound temporary has to be destroyed again, which might throw.
  1003. CanThrowResult CT = canCalleeThrow(*this, E,
  1004. cast<CXXBindTemporaryExpr>(E)->getTemporary()->getDestructor());
  1005. if (CT == CT_Can)
  1006. return CT;
  1007. return mergeCanThrow(CT, canSubExprsThrow(*this, E));
  1008. }
  1009. // ObjC message sends are like function calls, but never have exception
  1010. // specs.
  1011. case Expr::ObjCMessageExprClass:
  1012. case Expr::ObjCPropertyRefExprClass:
  1013. case Expr::ObjCSubscriptRefExprClass:
  1014. return CT_Can;
  1015. // All the ObjC literals that are implemented as calls are
  1016. // potentially throwing unless we decide to close off that
  1017. // possibility.
  1018. case Expr::ObjCArrayLiteralClass:
  1019. case Expr::ObjCDictionaryLiteralClass:
  1020. case Expr::ObjCBoxedExprClass:
  1021. return CT_Can;
  1022. // Many other things have subexpressions, so we have to test those.
  1023. // Some are simple:
  1024. case Expr::CoawaitExprClass:
  1025. case Expr::ConditionalOperatorClass:
  1026. case Expr::CompoundLiteralExprClass:
  1027. case Expr::CoyieldExprClass:
  1028. case Expr::CXXConstCastExprClass:
  1029. case Expr::CXXReinterpretCastExprClass:
  1030. case Expr::CXXStdInitializerListExprClass:
  1031. case Expr::DesignatedInitExprClass:
  1032. case Expr::DesignatedInitUpdateExprClass:
  1033. case Expr::ExprWithCleanupsClass:
  1034. case Expr::ExtVectorElementExprClass:
  1035. case Expr::InitListExprClass:
  1036. case Expr::ArrayInitLoopExprClass:
  1037. case Expr::MemberExprClass:
  1038. case Expr::ObjCIsaExprClass:
  1039. case Expr::ObjCIvarRefExprClass:
  1040. case Expr::ParenExprClass:
  1041. case Expr::ParenListExprClass:
  1042. case Expr::ShuffleVectorExprClass:
  1043. case Expr::ConvertVectorExprClass:
  1044. case Expr::VAArgExprClass:
  1045. return canSubExprsThrow(*this, E);
  1046. // Some might be dependent for other reasons.
  1047. case Expr::ArraySubscriptExprClass:
  1048. case Expr::OMPArraySectionExprClass:
  1049. case Expr::BinaryOperatorClass:
  1050. case Expr::DependentCoawaitExprClass:
  1051. case Expr::CompoundAssignOperatorClass:
  1052. case Expr::CStyleCastExprClass:
  1053. case Expr::CXXStaticCastExprClass:
  1054. case Expr::CXXFunctionalCastExprClass:
  1055. case Expr::ImplicitCastExprClass:
  1056. case Expr::MaterializeTemporaryExprClass:
  1057. case Expr::UnaryOperatorClass: {
  1058. CanThrowResult CT = E->isTypeDependent() ? CT_Dependent : CT_Cannot;
  1059. return mergeCanThrow(CT, canSubExprsThrow(*this, E));
  1060. }
  1061. // FIXME: We should handle StmtExpr, but that opens a MASSIVE can of worms.
  1062. case Expr::StmtExprClass:
  1063. return CT_Can;
  1064. case Expr::CXXDefaultArgExprClass:
  1065. return canThrow(cast<CXXDefaultArgExpr>(E)->getExpr());
  1066. case Expr::CXXDefaultInitExprClass:
  1067. return canThrow(cast<CXXDefaultInitExpr>(E)->getExpr());
  1068. case Expr::ChooseExprClass:
  1069. if (E->isTypeDependent() || E->isValueDependent())
  1070. return CT_Dependent;
  1071. return canThrow(cast<ChooseExpr>(E)->getChosenSubExpr());
  1072. case Expr::GenericSelectionExprClass:
  1073. if (cast<GenericSelectionExpr>(E)->isResultDependent())
  1074. return CT_Dependent;
  1075. return canThrow(cast<GenericSelectionExpr>(E)->getResultExpr());
  1076. // Some expressions are always dependent.
  1077. case Expr::CXXDependentScopeMemberExprClass:
  1078. case Expr::CXXUnresolvedConstructExprClass:
  1079. case Expr::DependentScopeDeclRefExprClass:
  1080. case Expr::CXXFoldExprClass:
  1081. return CT_Dependent;
  1082. case Expr::AsTypeExprClass:
  1083. case Expr::BinaryConditionalOperatorClass:
  1084. case Expr::BlockExprClass:
  1085. case Expr::CUDAKernelCallExprClass:
  1086. case Expr::DeclRefExprClass:
  1087. case Expr::ObjCBridgedCastExprClass:
  1088. case Expr::ObjCIndirectCopyRestoreExprClass:
  1089. case Expr::ObjCProtocolExprClass:
  1090. case Expr::ObjCSelectorExprClass:
  1091. case Expr::ObjCAvailabilityCheckExprClass:
  1092. case Expr::OffsetOfExprClass:
  1093. case Expr::PackExpansionExprClass:
  1094. case Expr::PseudoObjectExprClass:
  1095. case Expr::SubstNonTypeTemplateParmExprClass:
  1096. case Expr::SubstNonTypeTemplateParmPackExprClass:
  1097. case Expr::FunctionParmPackExprClass:
  1098. case Expr::UnaryExprOrTypeTraitExprClass:
  1099. case Expr::UnresolvedLookupExprClass:
  1100. case Expr::UnresolvedMemberExprClass:
  1101. case Expr::TypoExprClass:
  1102. // FIXME: Can any of the above throw? If so, when?
  1103. return CT_Cannot;
  1104. case Expr::AddrLabelExprClass:
  1105. case Expr::ArrayTypeTraitExprClass:
  1106. case Expr::AtomicExprClass:
  1107. case Expr::TypeTraitExprClass:
  1108. case Expr::CXXBoolLiteralExprClass:
  1109. case Expr::CXXNoexceptExprClass:
  1110. case Expr::CXXNullPtrLiteralExprClass:
  1111. case Expr::CXXPseudoDestructorExprClass:
  1112. case Expr::CXXScalarValueInitExprClass:
  1113. case Expr::CXXThisExprClass:
  1114. case Expr::CXXUuidofExprClass:
  1115. case Expr::CharacterLiteralClass:
  1116. case Expr::ExpressionTraitExprClass:
  1117. case Expr::FloatingLiteralClass:
  1118. case Expr::GNUNullExprClass:
  1119. case Expr::ImaginaryLiteralClass:
  1120. case Expr::ImplicitValueInitExprClass:
  1121. case Expr::IntegerLiteralClass:
  1122. case Expr::FixedPointLiteralClass:
  1123. case Expr::ArrayInitIndexExprClass:
  1124. case Expr::NoInitExprClass:
  1125. case Expr::ObjCEncodeExprClass:
  1126. case Expr::ObjCStringLiteralClass:
  1127. case Expr::ObjCBoolLiteralExprClass:
  1128. case Expr::OpaqueValueExprClass:
  1129. case Expr::PredefinedExprClass:
  1130. case Expr::SizeOfPackExprClass:
  1131. case Expr::StringLiteralClass:
  1132. case Expr::SourceLocExprClass:
  1133. // These expressions can never throw.
  1134. return CT_Cannot;
  1135. case Expr::MSPropertyRefExprClass:
  1136. case Expr::MSPropertySubscriptExprClass:
  1137. llvm_unreachable("Invalid class for expression");
  1138. #define STMT(CLASS, PARENT) case Expr::CLASS##Class:
  1139. #define STMT_RANGE(Base, First, Last)
  1140. #define LAST_STMT_RANGE(BASE, FIRST, LAST)
  1141. #define EXPR(CLASS, PARENT)
  1142. #define ABSTRACT_STMT(STMT)
  1143. #include "clang/AST/StmtNodes.inc"
  1144. case Expr::NoStmtClass:
  1145. llvm_unreachable("Invalid class for expression");
  1146. }
  1147. llvm_unreachable("Bogus StmtClass");
  1148. }
  1149. } // end namespace clang