SemaExceptionSpec.cpp 48 KB

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