clang-tools 22.0.0git
IntegerDivisionCheck.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
10#include "clang/ASTMatchers/ASTMatchFinder.h"
11
12using namespace clang::ast_matchers;
13
14namespace clang::tidy::bugprone {
15
16void IntegerDivisionCheck::registerMatchers(MatchFinder *Finder) {
17 const auto IntType = hasType(isInteger());
18
19 const auto BinaryOperators = binaryOperator(
20 hasAnyOperatorName("%", "<<", ">>", "<<", "^", "|", "&", "||", "&&", "<",
21 ">", "<=", ">=", "==", "!="));
22
23 const auto UnaryOperators = unaryOperator(hasAnyOperatorName("~", "!"));
24
25 const auto Exceptions =
26 anyOf(BinaryOperators, conditionalOperator(), binaryConditionalOperator(),
27 callExpr(IntType), explicitCastExpr(IntType), UnaryOperators);
28
29 Finder->addMatcher(
30 traverse(TK_AsIs,
31 binaryOperator(
32 hasOperatorName("/"), hasLHS(expr(IntType)),
33 hasRHS(expr(IntType)),
34 hasAncestor(castExpr(hasCastKind(CK_IntegralToFloating))
35 .bind("FloatCast")),
36 unless(hasAncestor(expr(
37 Exceptions,
38 hasAncestor(castExpr(equalsBoundNode("FloatCast")))))))
39 .bind("IntDiv")),
40 this);
41}
42
43void IntegerDivisionCheck::check(const MatchFinder::MatchResult &Result) {
44 const auto *IntDiv = Result.Nodes.getNodeAs<BinaryOperator>("IntDiv");
45 diag(IntDiv->getBeginLoc(), "result of integer division used in a floating "
46 "point context; possible loss of precision");
47}
48
49} // namespace clang::tidy::bugprone
void registerMatchers(ast_matchers::MatchFinder *Finder) override
void check(const ast_matchers::MatchFinder::MatchResult &Result) override