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