SemaExceptionSpec.cpp 49 KB

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