1 | //===--- BitwisePointerCastCheck.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 "BitwisePointerCastCheck.h" |
10 | #include "clang/ASTMatchers/ASTMatchFinder.h" |
11 | |
12 | using namespace clang::ast_matchers; |
13 | |
14 | namespace clang::tidy::bugprone { |
15 | |
16 | void BitwisePointerCastCheck::registerMatchers(MatchFinder *Finder) { |
17 | if (getLangOpts().CPlusPlus20) { |
18 | auto IsPointerType = refersToType(InnerMatcher: qualType(isAnyPointer())); |
19 | Finder->addMatcher(NodeMatch: callExpr(hasDeclaration(InnerMatcher: functionDecl(allOf( |
20 | hasName(Name: "::std::bit_cast"), |
21 | hasTemplateArgument(N: 0, InnerMatcher: IsPointerType), |
22 | hasTemplateArgument(N: 1, InnerMatcher: IsPointerType))))) |
23 | .bind(ID: "bit_cast"), |
24 | Action: this); |
25 | } |
26 | |
27 | auto IsDoublePointerType = |
28 | hasType(InnerMatcher: qualType(pointsTo(InnerMatcher: qualType(isAnyPointer())))); |
29 | Finder->addMatcher(NodeMatch: callExpr(hasArgument(N: 0, InnerMatcher: IsDoublePointerType), |
30 | hasArgument(N: 1, InnerMatcher: IsDoublePointerType), |
31 | hasDeclaration(InnerMatcher: functionDecl(hasName(Name: "::memcpy")))) |
32 | .bind(ID: "memcpy"), |
33 | Action: this); |
34 | } |
35 | |
36 | void BitwisePointerCastCheck::check(const MatchFinder::MatchResult &Result) { |
37 | if (const auto *Call = Result.Nodes.getNodeAs<CallExpr>(ID: "bit_cast")) |
38 | diag(Loc: Call->getBeginLoc(), |
39 | Description: "do not use 'std::bit_cast' to cast between pointers") |
40 | << Call->getSourceRange(); |
41 | else if (const auto *Call = Result.Nodes.getNodeAs<CallExpr>(ID: "memcpy")) |
42 | diag(Loc: Call->getBeginLoc(), Description: "do not use 'memcpy' to cast between pointers") |
43 | << Call->getSourceRange(); |
44 | } |
45 | |
46 | } // namespace clang::tidy::bugprone |
47 |