1//===--- IntegerDivisionCheck.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 "IntegerDivisionCheck.h"
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(InnerMatcher: 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 NodeMatch: traverse(TK: TK_AsIs,
31 InnerMatcher: binaryOperator(
32 hasOperatorName(Name: "/"), hasLHS(InnerMatcher: expr(IntType)),
33 hasRHS(InnerMatcher: expr(IntType)),
34 hasAncestor(castExpr(hasCastKind(Kind: CK_IntegralToFloating))
35 .bind(ID: "FloatCast")),
36 unless(hasAncestor(expr(
37 Exceptions,
38 hasAncestor(castExpr(equalsBoundNode(ID: "FloatCast")))))))
39 .bind(ID: "IntDiv")),
40 Action: this);
41}
42
43void IntegerDivisionCheck::check(const MatchFinder::MatchResult &Result) {
44 const auto *IntDiv = Result.Nodes.getNodeAs<BinaryOperator>(ID: "IntDiv");
45 diag(Loc: IntDiv->getBeginLoc(), Description: "result of integer division used in a floating "
46 "point context; possible loss of precision");
47}
48
49} // namespace clang::tidy::bugprone
50

Provided by KDAB

Privacy Policy
Improve your Profiling and Debugging skills
Find out more

source code of clang-tools-extra/clang-tidy/bugprone/IntegerDivisionCheck.cpp