1//===--- ExceptionAnalyzer.cpp - clang-tidy -------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "ExceptionAnalyzer.h"
10
11namespace clang::tidy::utils {
12
13void ExceptionAnalyzer::ExceptionInfo::registerException(
14 const Type *ExceptionType, const ThrowInfo &ThrowInfo) {
15 assert(ExceptionType != nullptr && "Only valid types are accepted");
16 Behaviour = State::Throwing;
17 ThrownExceptions.insert(KV: {ExceptionType, ThrowInfo});
18}
19
20void ExceptionAnalyzer::ExceptionInfo::registerExceptions(
21 const Throwables &Exceptions) {
22 if (Exceptions.empty())
23 return;
24 Behaviour = State::Throwing;
25 ThrownExceptions.insert_range(R: Exceptions);
26}
27
28ExceptionAnalyzer::ExceptionInfo &ExceptionAnalyzer::ExceptionInfo::merge(
29 const ExceptionAnalyzer::ExceptionInfo &Other) {
30 // Only the following two cases require an update to the local
31 // 'Behaviour'. If the local entity is already throwing there will be no
32 // change and if the other entity is throwing the merged entity will throw
33 // as well.
34 // If one of both entities is 'Unknown' and the other one does not throw
35 // the merged entity is 'Unknown' as well.
36 if (Other.Behaviour == State::Throwing)
37 Behaviour = State::Throwing;
38 else if (Other.Behaviour == State::Unknown && Behaviour == State::NotThrowing)
39 Behaviour = State::Unknown;
40
41 ContainsUnknown = ContainsUnknown || Other.ContainsUnknown;
42 ThrownExceptions.insert_range(R: Other.ThrownExceptions);
43 return *this;
44}
45
46// FIXME: This could be ported to clang later.
47namespace {
48
49bool isUnambiguousPublicBaseClass(const Type *DerivedType,
50 const Type *BaseType) {
51 const auto *DerivedClass =
52 DerivedType->getCanonicalTypeUnqualified()->getAsCXXRecordDecl();
53 const auto *BaseClass =
54 BaseType->getCanonicalTypeUnqualified()->getAsCXXRecordDecl();
55 if (!DerivedClass || !BaseClass)
56 return false;
57
58 CXXBasePaths Paths;
59 Paths.setOrigin(DerivedClass);
60
61 bool IsPublicBaseClass = false;
62 DerivedClass->lookupInBases(
63 BaseMatches: [&BaseClass, &IsPublicBaseClass](const CXXBaseSpecifier *BS,
64 CXXBasePath &) {
65 if (BS->getType()
66 ->getCanonicalTypeUnqualified()
67 ->getAsCXXRecordDecl() == BaseClass &&
68 BS->getAccessSpecifier() == AS_public) {
69 IsPublicBaseClass = true;
70 return true;
71 }
72
73 return false;
74 },
75 Paths);
76
77 return !Paths.isAmbiguous(BaseType: BaseType->getCanonicalTypeUnqualified()) &&
78 IsPublicBaseClass;
79}
80
81inline bool isPointerOrPointerToMember(const Type *T) {
82 return T->isPointerType() || T->isMemberPointerType();
83}
84
85std::optional<QualType> getPointeeOrArrayElementQualType(QualType T) {
86 if (T->isAnyPointerType() || T->isMemberPointerType())
87 return T->getPointeeType();
88
89 if (T->isArrayType())
90 return T->getAsArrayTypeUnsafe()->getElementType();
91
92 return std::nullopt;
93}
94
95bool isBaseOf(const Type *DerivedType, const Type *BaseType) {
96 const auto *DerivedClass = DerivedType->getAsCXXRecordDecl();
97 const auto *BaseClass = BaseType->getAsCXXRecordDecl();
98 if (!DerivedClass || !BaseClass)
99 return false;
100
101 return !DerivedClass->forallBases(
102 BaseMatches: [BaseClass](const CXXRecordDecl *Cur) { return Cur != BaseClass; });
103}
104
105// Check if T1 is more or Equally qualified than T2.
106bool moreOrEquallyQualified(QualType T1, QualType T2) {
107 return T1.getQualifiers().isStrictSupersetOf(Other: T2.getQualifiers()) ||
108 T1.getQualifiers() == T2.getQualifiers();
109}
110
111bool isStandardPointerConvertible(QualType From, QualType To) {
112 assert((From->isPointerType() || From->isMemberPointerType()) &&
113 (To->isPointerType() || To->isMemberPointerType()) &&
114 "Pointer conversion should be performed on pointer types only.");
115
116 if (!moreOrEquallyQualified(T1: To->getPointeeType(), T2: From->getPointeeType()))
117 return false;
118
119 // (1)
120 // A null pointer constant can be converted to a pointer type ...
121 // The conversion of a null pointer constant to a pointer to cv-qualified type
122 // is a single conversion, and not the sequence of a pointer conversion
123 // followed by a qualification conversion. A null pointer constant of integral
124 // type can be converted to a prvalue of type std::nullptr_t
125 if (To->isPointerType() && From->isNullPtrType())
126 return true;
127
128 // (2)
129 // A prvalue of type “pointer to cv T”, where T is an object type, can be
130 // converted to a prvalue of type “pointer to cv void”.
131 if (To->isVoidPointerType() && From->isObjectPointerType())
132 return true;
133
134 // (3)
135 // A prvalue of type “pointer to cv D”, where D is a complete class type, can
136 // be converted to a prvalue of type “pointer to cv B”, where B is a base
137 // class of D. If B is an inaccessible or ambiguous base class of D, a program
138 // that necessitates this conversion is ill-formed.
139 if (const auto *RD = From->getPointeeCXXRecordDecl()) {
140 if (RD->isCompleteDefinition() &&
141 isBaseOf(DerivedType: From->getPointeeType().getTypePtr(),
142 BaseType: To->getPointeeType().getTypePtr())) {
143 // If B is an inaccessible or ambiguous base class of D, a program
144 // that necessitates this conversion is ill-formed
145 return isUnambiguousPublicBaseClass(DerivedType: From->getPointeeType().getTypePtr(),
146 BaseType: To->getPointeeType().getTypePtr());
147 }
148 }
149
150 return false;
151}
152
153bool isFunctionPointerConvertible(QualType From, QualType To) {
154 if (!From->isFunctionPointerType() && !From->isFunctionType() &&
155 !From->isMemberFunctionPointerType())
156 return false;
157
158 if (!To->isFunctionPointerType() && !To->isMemberFunctionPointerType())
159 return false;
160
161 if (To->isFunctionPointerType()) {
162 if (From->isFunctionPointerType())
163 return To->getPointeeType() == From->getPointeeType();
164
165 if (From->isFunctionType())
166 return To->getPointeeType() == From;
167
168 return false;
169 }
170
171 if (To->isMemberFunctionPointerType()) {
172 if (!From->isMemberFunctionPointerType())
173 return false;
174
175 const auto *FromMember = cast<MemberPointerType>(Val&: From);
176 const auto *ToMember = cast<MemberPointerType>(Val&: To);
177
178 // Note: converting Derived::* to Base::* is a different kind of conversion,
179 // called Pointer-to-member conversion.
180 return FromMember->getQualifier() == ToMember->getQualifier() &&
181 FromMember->getMostRecentCXXRecordDecl() ==
182 ToMember->getMostRecentCXXRecordDecl() &&
183 FromMember->getPointeeType() == ToMember->getPointeeType();
184 }
185
186 return false;
187}
188
189// Checks if From is qualification convertible to To based on the current
190// LangOpts. If From is any array, we perform the array to pointer conversion
191// first. The function only performs checks based on C++ rules, which can differ
192// from the C rules.
193//
194// The function should only be called in C++ mode.
195bool isQualificationConvertiblePointer(QualType From, QualType To,
196 LangOptions LangOpts) {
197
198 // [N4659 7.5 (1)]
199 // A cv-decomposition of a type T is a sequence of cv_i and P_i such that T is
200 // cv_0 P_0 cv_1 P_1 ... cv_n−1 P_n−1 cv_n U” for n > 0,
201 // where each cv_i is a set of cv-qualifiers, and each P_i is “pointer to”,
202 // “pointer to member of class C_i of type”, “array of N_i”, or
203 // “array of unknown bound of”.
204 //
205 // If P_i designates an array, the cv-qualifiers cv_i+1 on the element type
206 // are also taken as the cv-qualifiers cvi of the array.
207 //
208 // The n-tuple of cv-qualifiers after the first one in the longest
209 // cv-decomposition of T, that is, cv_1, cv_2, ... , cv_n, is called the
210 // cv-qualification signature of T.
211
212 // NOLINTNEXTLINE (readability-identifier-naming): Preserve original notation
213 auto IsValidP_i = [](QualType P) {
214 return P->isPointerType() || P->isMemberPointerType() ||
215 P->isConstantArrayType() || P->isIncompleteArrayType();
216 };
217
218 // NOLINTNEXTLINE (readability-identifier-naming): Preserve original notation
219 auto IsSameP_i = [](QualType P1, QualType P2) {
220 if (P1->isPointerType())
221 return P2->isPointerType();
222
223 if (P1->isMemberPointerType())
224 return P2->isMemberPointerType() &&
225 P1->getAs<MemberPointerType>()->getMostRecentCXXRecordDecl() ==
226 P2->getAs<MemberPointerType>()->getMostRecentCXXRecordDecl();
227
228 if (P1->isConstantArrayType())
229 return P2->isConstantArrayType() &&
230 cast<ConstantArrayType>(Val&: P1)->getSize() ==
231 cast<ConstantArrayType>(Val&: P2)->getSize();
232
233 if (P1->isIncompleteArrayType())
234 return P2->isIncompleteArrayType();
235
236 return false;
237 };
238
239 // (2)
240 // Two types From and To are similar if they have cv-decompositions with the
241 // same n such that corresponding P_i components are the same [(added by
242 // N4849 7.3.5) or one is “array of N_i” and the other is “array of unknown
243 // bound of”], and the types denoted by U are the same.
244 //
245 // (3)
246 // A prvalue expression of type From can be converted to type To if the
247 // following conditions are satisfied:
248 // - From and To are similar
249 // - For every i > 0, if const is in cv_i of From then const is in cv_i of
250 // To, and similarly for volatile.
251 // - [(derived from addition by N4849 7.3.5) If P_i of From is “array of
252 // unknown bound of”, P_i of To is “array of unknown bound of”.]
253 // - If the cv_i of From and cv_i of To are different, then const is in every
254 // cv_k of To for 0 < k < i.
255
256 int I = 0;
257 bool ConstUntilI = true;
258 auto SatisfiesCVRules = [&I, &ConstUntilI](const QualType &From,
259 const QualType &To) {
260 if (I > 1) {
261 if (From.getQualifiers() != To.getQualifiers() && !ConstUntilI)
262 return false;
263 }
264
265 if (I > 0) {
266 if (From.isConstQualified() && !To.isConstQualified())
267 return false;
268
269 if (From.isVolatileQualified() && !To.isVolatileQualified())
270 return false;
271
272 ConstUntilI = To.isConstQualified();
273 }
274
275 return true;
276 };
277
278 while (IsValidP_i(From) && IsValidP_i(To)) {
279 // Remove every sugar.
280 From = From.getCanonicalType();
281 To = To.getCanonicalType();
282
283 if (!SatisfiesCVRules(From, To))
284 return false;
285
286 if (!IsSameP_i(From, To)) {
287 if (LangOpts.CPlusPlus20) {
288 if (From->isConstantArrayType() && !To->isIncompleteArrayType())
289 return false;
290
291 if (From->isIncompleteArrayType() && !To->isIncompleteArrayType())
292 return false;
293
294 } else {
295 return false;
296 }
297 }
298
299 ++I;
300 std::optional<QualType> FromPointeeOrElem =
301 getPointeeOrArrayElementQualType(T: From);
302 std::optional<QualType> ToPointeeOrElem =
303 getPointeeOrArrayElementQualType(T: To);
304
305 assert(FromPointeeOrElem &&
306 "From pointer or array has no pointee or element!");
307 assert(ToPointeeOrElem && "To pointer or array has no pointee or element!");
308
309 From = *FromPointeeOrElem;
310 To = *ToPointeeOrElem;
311 }
312
313 // In this case the length (n) of From and To are not the same.
314 if (IsValidP_i(From) || IsValidP_i(To))
315 return false;
316
317 // We hit U.
318 if (!SatisfiesCVRules(From, To))
319 return false;
320
321 return From.getTypePtr() == To.getTypePtr();
322}
323} // namespace
324
325static bool canThrow(const FunctionDecl *Func) {
326 // consteval specifies that every call to the function must produce a
327 // compile-time constant, which cannot evaluate a throw expression without
328 // producing a compilation error.
329 if (Func->isConsteval())
330 return false;
331
332 const auto *FunProto = Func->getType()->getAs<FunctionProtoType>();
333 if (!FunProto)
334 return true;
335
336 switch (FunProto->canThrow()) {
337 case CT_Cannot:
338 return false;
339 case CT_Dependent: {
340 const Expr *NoexceptExpr = FunProto->getNoexceptExpr();
341 if (!NoexceptExpr)
342 return true; // no noexcept - can throw
343
344 if (NoexceptExpr->isValueDependent())
345 return true; // depend on template - some instance can throw
346
347 bool Result = false;
348 if (!NoexceptExpr->EvaluateAsBooleanCondition(Result, Ctx: Func->getASTContext(),
349 /*InConstantContext=*/true))
350 return true; // complex X condition in noexcept(X), cannot validate,
351 // assume that may throw
352 return !Result; // noexcept(false) - can throw
353 }
354 default:
355 return true;
356 };
357}
358
359ExceptionAnalyzer::ExceptionInfo::Throwables
360ExceptionAnalyzer::ExceptionInfo::filterByCatch(const Type *HandlerTy,
361 const ASTContext &Context) {
362 llvm::SmallVector<const Type *, 8> TypesToDelete;
363 for (const auto &ThrownException : ThrownExceptions) {
364 const Type *ExceptionTy = ThrownException.getFirst();
365 CanQualType ExceptionCanTy = ExceptionTy->getCanonicalTypeUnqualified();
366 CanQualType HandlerCanTy = HandlerTy->getCanonicalTypeUnqualified();
367
368 // The handler is of type cv T or cv T& and E and T are the same type
369 // (ignoring the top-level cv-qualifiers) ...
370 if (ExceptionCanTy == HandlerCanTy) {
371 TypesToDelete.push_back(Elt: ExceptionTy);
372 }
373
374 // The handler is of type cv T or cv T& and T is an unambiguous public base
375 // class of E ...
376 else if (isUnambiguousPublicBaseClass(DerivedType: ExceptionCanTy->getTypePtr(),
377 BaseType: HandlerCanTy->getTypePtr())) {
378 TypesToDelete.push_back(Elt: ExceptionTy);
379 }
380
381 if (HandlerCanTy->getTypeClass() == Type::RValueReference ||
382 (HandlerCanTy->getTypeClass() == Type::LValueReference &&
383 !HandlerCanTy->getTypePtr()->getPointeeType().isConstQualified()))
384 continue;
385 // The handler is of type cv T or const T& where T is a pointer or
386 // pointer-to-member type and E is a pointer or pointer-to-member type that
387 // can be converted to T by one or more of ...
388 if (isPointerOrPointerToMember(T: HandlerCanTy->getTypePtr()) &&
389 isPointerOrPointerToMember(T: ExceptionCanTy->getTypePtr())) {
390 // A standard pointer conversion not involving conversions to pointers to
391 // private or protected or ambiguous classes ...
392 if (isStandardPointerConvertible(From: ExceptionCanTy, To: HandlerCanTy)) {
393 TypesToDelete.push_back(Elt: ExceptionTy);
394 }
395 // A function pointer conversion ...
396 else if (isFunctionPointerConvertible(From: ExceptionCanTy, To: HandlerCanTy)) {
397 TypesToDelete.push_back(Elt: ExceptionTy);
398 }
399 // A a qualification conversion ...
400 else if (isQualificationConvertiblePointer(From: ExceptionCanTy, To: HandlerCanTy,
401 LangOpts: Context.getLangOpts())) {
402 TypesToDelete.push_back(Elt: ExceptionTy);
403 }
404 }
405
406 // The handler is of type cv T or const T& where T is a pointer or
407 // pointer-to-member type and E is std::nullptr_t.
408 else if (isPointerOrPointerToMember(T: HandlerCanTy->getTypePtr()) &&
409 ExceptionCanTy->isNullPtrType()) {
410 TypesToDelete.push_back(Elt: ExceptionTy);
411 }
412 }
413
414 Throwables DeletedExceptions;
415
416 for (const Type *TypeToDelete : TypesToDelete) {
417 const auto DeleteIt = ThrownExceptions.find(Val: TypeToDelete);
418 if (DeleteIt != ThrownExceptions.end()) {
419 DeletedExceptions.insert(KV: *DeleteIt);
420 ThrownExceptions.erase(I: DeleteIt);
421 }
422 }
423
424 reevaluateBehaviour();
425 return DeletedExceptions;
426}
427
428ExceptionAnalyzer::ExceptionInfo &
429ExceptionAnalyzer::ExceptionInfo::filterIgnoredExceptions(
430 const llvm::StringSet<> &IgnoredTypes, bool IgnoreBadAlloc) {
431 llvm::SmallVector<const Type *, 8> TypesToDelete;
432 // Note: Using a 'SmallSet' with 'llvm::remove_if()' is not possible.
433 // Therefore this slightly hacky implementation is required.
434 for (const auto &ThrownException : ThrownExceptions) {
435 const Type *T = ThrownException.getFirst();
436 if (const auto *TD = T->getAsTagDecl()) {
437 if (TD->getDeclName().isIdentifier()) {
438 if ((IgnoreBadAlloc &&
439 (TD->getName() == "bad_alloc" && TD->isInStdNamespace())) ||
440 (IgnoredTypes.contains(key: TD->getName())))
441 TypesToDelete.push_back(Elt: T);
442 }
443 }
444 }
445 for (const Type *T : TypesToDelete)
446 ThrownExceptions.erase(Val: T);
447
448 reevaluateBehaviour();
449 return *this;
450}
451
452void ExceptionAnalyzer::ExceptionInfo::clear() {
453 Behaviour = State::NotThrowing;
454 ContainsUnknown = false;
455 ThrownExceptions.clear();
456}
457
458void ExceptionAnalyzer::ExceptionInfo::reevaluateBehaviour() {
459 if (ThrownExceptions.empty())
460 if (ContainsUnknown)
461 Behaviour = State::Unknown;
462 else
463 Behaviour = State::NotThrowing;
464 else
465 Behaviour = State::Throwing;
466}
467ExceptionAnalyzer::ExceptionInfo ExceptionAnalyzer::throwsException(
468 const FunctionDecl *Func, const ExceptionInfo::Throwables &Caught,
469 CallStack &CallStack, SourceLocation CallLoc) {
470 if (!Func || CallStack.contains(Key: Func) ||
471 (!CallStack.empty() && !canThrow(Func)))
472 return ExceptionInfo::createNonThrowing();
473
474 if (const Stmt *Body = Func->getBody()) {
475 CallStack.insert(KV: {Func, CallLoc});
476 ExceptionInfo Result = throwsException(St: Body, Caught, CallStack);
477
478 // For a constructor, we also have to check the initializers.
479 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: Func)) {
480 for (const CXXCtorInitializer *Init : Ctor->inits()) {
481 ExceptionInfo Excs =
482 throwsException(St: Init->getInit(), Caught, CallStack);
483 Result.merge(Other: Excs);
484 }
485 }
486
487 CallStack.erase(Key: Func);
488 return Result;
489 }
490
491 auto Result = ExceptionInfo::createUnknown();
492 if (const auto *FPT = Func->getType()->getAs<FunctionProtoType>()) {
493 for (const QualType &Ex : FPT->exceptions()) {
494 CallStack.insert(KV: {Func, CallLoc});
495 Result.registerException(
496 ExceptionType: Ex.getTypePtr(),
497 ThrowInfo: {.Loc: Func->getExceptionSpecSourceRange().getBegin(), .Stack: CallStack});
498 CallStack.erase(Key: Func);
499 }
500 }
501 return Result;
502}
503
504/// Analyzes a single statement on it's throwing behaviour. This is in principle
505/// possible except some 'Unknown' functions are called.
506ExceptionAnalyzer::ExceptionInfo
507ExceptionAnalyzer::throwsException(const Stmt *St,
508 const ExceptionInfo::Throwables &Caught,
509 CallStack &CallStack) {
510 auto Results = ExceptionInfo::createNonThrowing();
511 if (!St)
512 return Results;
513
514 if (const auto *Throw = dyn_cast<CXXThrowExpr>(Val: St)) {
515 if (const auto *ThrownExpr = Throw->getSubExpr()) {
516 const auto *ThrownType =
517 ThrownExpr->getType()->getUnqualifiedDesugaredType();
518 if (ThrownType->isReferenceType())
519 ThrownType = ThrownType->castAs<ReferenceType>()
520 ->getPointeeType()
521 ->getUnqualifiedDesugaredType();
522 Results.registerException(
523 ExceptionType: ThrownExpr->getType()->getUnqualifiedDesugaredType(),
524 ThrowInfo: {.Loc: Throw->getBeginLoc(), .Stack: CallStack});
525 } else
526 // A rethrow of a caught exception happens which makes it possible
527 // to throw all exception that are caught in the 'catch' clause of
528 // the parent try-catch block.
529 Results.registerExceptions(Exceptions: Caught);
530 } else if (const auto *Try = dyn_cast<CXXTryStmt>(Val: St)) {
531 ExceptionInfo Uncaught =
532 throwsException(St: Try->getTryBlock(), Caught, CallStack);
533 for (unsigned I = 0; I < Try->getNumHandlers(); ++I) {
534 const CXXCatchStmt *Catch = Try->getHandler(i: I);
535
536 // Everything is caught through 'catch(...)'.
537 if (!Catch->getExceptionDecl()) {
538 ExceptionInfo Rethrown = throwsException(
539 St: Catch->getHandlerBlock(), Caught: Uncaught.getExceptions(), CallStack);
540 Results.merge(Other: Rethrown);
541 Uncaught.clear();
542 } else {
543 const auto *CaughtType =
544 Catch->getCaughtType()->getUnqualifiedDesugaredType();
545 if (CaughtType->isReferenceType()) {
546 CaughtType = CaughtType->castAs<ReferenceType>()
547 ->getPointeeType()
548 ->getUnqualifiedDesugaredType();
549 }
550
551 // If the caught exception will catch multiple previously potential
552 // thrown types (because it's sensitive to inheritance) the throwing
553 // situation changes. First of all filter the exception types and
554 // analyze if the baseclass-exception is rethrown.
555 const ExceptionInfo::Throwables FilteredExceptions =
556 Uncaught.filterByCatch(HandlerTy: CaughtType,
557 Context: Catch->getExceptionDecl()->getASTContext());
558 if (!FilteredExceptions.empty()) {
559 ExceptionInfo Rethrown = throwsException(
560 St: Catch->getHandlerBlock(), Caught: FilteredExceptions, CallStack);
561 Results.merge(Other: Rethrown);
562 }
563 }
564 }
565 Results.merge(Other: Uncaught);
566 } else if (const auto *Call = dyn_cast<CallExpr>(Val: St)) {
567 if (const FunctionDecl *Func = Call->getDirectCallee()) {
568 ExceptionInfo Excs =
569 throwsException(Func, Caught, CallStack, CallLoc: Call->getBeginLoc());
570 Results.merge(Other: Excs);
571 }
572 } else if (const auto *Construct = dyn_cast<CXXConstructExpr>(Val: St)) {
573 ExceptionInfo Excs = throwsException(Func: Construct->getConstructor(), Caught,
574 CallStack, CallLoc: Construct->getBeginLoc());
575 Results.merge(Other: Excs);
576 } else if (const auto *DefaultInit = dyn_cast<CXXDefaultInitExpr>(Val: St)) {
577 ExceptionInfo Excs =
578 throwsException(St: DefaultInit->getExpr(), Caught, CallStack);
579 Results.merge(Other: Excs);
580 } else if (const auto *Coro = dyn_cast<CoroutineBodyStmt>(Val: St)) {
581 for (const Stmt *Child : Coro->childrenExclBody()) {
582 if (Child != Coro->getExceptionHandler()) {
583 ExceptionInfo Excs = throwsException(St: Child, Caught, CallStack);
584 Results.merge(Other: Excs);
585 }
586 }
587 ExceptionInfo Excs = throwsException(St: Coro->getBody(), Caught, CallStack);
588 Results.merge(Other: throwsException(St: Coro->getExceptionHandler(),
589 Caught: Excs.getExceptions(), CallStack));
590 for (const auto &Exception : Excs.getExceptions()) {
591 const Type *ExcType = Exception.getFirst();
592 if (const CXXRecordDecl *ThrowableRec = ExcType->getAsCXXRecordDecl()) {
593 ExceptionInfo DestructorExcs = throwsException(
594 Func: ThrowableRec->getDestructor(), Caught, CallStack, CallLoc: SourceLocation{});
595 Results.merge(Other: DestructorExcs);
596 }
597 }
598 } else {
599 for (const Stmt *Child : St->children()) {
600 ExceptionInfo Excs = throwsException(St: Child, Caught, CallStack);
601 Results.merge(Other: Excs);
602 }
603 }
604 return Results;
605}
606
607ExceptionAnalyzer::ExceptionInfo
608ExceptionAnalyzer::analyzeImpl(const FunctionDecl *Func) {
609 ExceptionInfo ExceptionList;
610
611 // Check if the function has already been analyzed and reuse that result.
612 const auto CacheEntry = FunctionCache.find(Val: Func);
613 if (CacheEntry == FunctionCache.end()) {
614 CallStack CallStack;
615 ExceptionList = throwsException(Func, Caught: ExceptionInfo::Throwables(),
616 CallStack, CallLoc: Func->getLocation());
617
618 // Cache the result of the analysis. This is done prior to filtering
619 // because it is best to keep as much information as possible.
620 // The results here might be relevant to different analysis passes
621 // with different needs as well.
622 FunctionCache.try_emplace(Key: Func, Args&: ExceptionList);
623 } else
624 ExceptionList = CacheEntry->getSecond();
625
626 return ExceptionList;
627}
628
629ExceptionAnalyzer::ExceptionInfo
630ExceptionAnalyzer::analyzeImpl(const Stmt *Stmt) {
631 CallStack CallStack;
632 return throwsException(St: Stmt, Caught: ExceptionInfo::Throwables(), CallStack);
633}
634
635template <typename T>
636ExceptionAnalyzer::ExceptionInfo
637ExceptionAnalyzer::analyzeDispatch(const T *Node) {
638 ExceptionInfo ExceptionList = analyzeImpl(Node);
639
640 if (ExceptionList.getBehaviour() == State::NotThrowing ||
641 ExceptionList.getBehaviour() == State::Unknown)
642 return ExceptionList;
643
644 // Remove all ignored exceptions from the list of exceptions that can be
645 // thrown.
646 ExceptionList.filterIgnoredExceptions(IgnoredTypes: IgnoredExceptions, IgnoreBadAlloc);
647
648 return ExceptionList;
649}
650
651ExceptionAnalyzer::ExceptionInfo
652ExceptionAnalyzer::analyze(const FunctionDecl *Func) {
653 return analyzeDispatch(Node: Func);
654}
655
656ExceptionAnalyzer::ExceptionInfo ExceptionAnalyzer::analyze(const Stmt *Stmt) {
657 return analyzeDispatch(Node: Stmt);
658}
659
660} // namespace clang::tidy::utils
661

source code of clang-tools-extra/clang-tidy/utils/ExceptionAnalyzer.cpp