Coverage Report

Created: 2023-11-11 10:31

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/StaticAnalyzer/Checkers/ConversionChecker.cpp
Line
Count
Source (jump to first uncovered line)
1
//=== ConversionChecker.cpp -------------------------------------*- C++ -*-===//
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
// Check that there is no loss of sign/precision in assignments, comparisons
10
// and multiplications.
11
//
12
// ConversionChecker uses path sensitive analysis to determine possible values
13
// of expressions. A warning is reported when:
14
// * a negative value is implicitly converted to an unsigned value in an
15
//   assignment, comparison or multiplication.
16
// * assignment / initialization when the source value is greater than the max
17
//   value of the target integer type
18
// * assignment / initialization when the source integer is above the range
19
//   where the target floating point type can represent all integers
20
//
21
// Many compilers and tools have similar checks that are based on semantic
22
// analysis. Those checks are sound but have poor precision. ConversionChecker
23
// is an alternative to those checks.
24
//
25
//===----------------------------------------------------------------------===//
26
#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
27
#include "clang/AST/ParentMap.h"
28
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
29
#include "clang/StaticAnalyzer/Core/Checker.h"
30
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
31
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
32
#include "llvm/ADT/APFloat.h"
33
34
#include <climits>
35
36
using namespace clang;
37
using namespace ento;
38
39
namespace {
40
class ConversionChecker : public Checker<check::PreStmt<ImplicitCastExpr>> {
41
public:
42
  void checkPreStmt(const ImplicitCastExpr *Cast, CheckerContext &C) const;
43
44
private:
45
  mutable std::unique_ptr<BugType> BT;
46
47
  bool isLossOfPrecision(const ImplicitCastExpr *Cast, QualType DestType,
48
                         CheckerContext &C) const;
49
50
  bool isLossOfSign(const ImplicitCastExpr *Cast, CheckerContext &C) const;
51
52
  void reportBug(ExplodedNode *N, const Expr *E, CheckerContext &C,
53
                 const char Msg[]) const;
54
};
55
}
56
57
void ConversionChecker::checkPreStmt(const ImplicitCastExpr *Cast,
58
10.1k
                                     CheckerContext &C) const {
59
  // Don't warn for implicit conversions to bool
60
10.1k
  if (Cast->getType()->isBooleanType())
61
246
    return;
62
63
  // Don't warn for loss of sign/precision in macros.
64
9.88k
  if (Cast->getExprLoc().isMacroID())
65
89
    return;
66
67
  // Get Parent.
68
9.79k
  const ParentMap &PM = C.getLocationContext()->getParentMap();
69
9.79k
  const Stmt *Parent = PM.getParent(Cast);
70
9.79k
  if (!Parent)
71
14
    return;
72
  // Dont warn if this is part of an explicit cast
73
9.77k
  if (isa<ExplicitCastExpr>(Parent))
74
173
    return;
75
76
9.60k
  bool LossOfSign = false;
77
9.60k
  bool LossOfPrecision = false;
78
79
  // Loss of sign/precision in binary operation.
80
9.60k
  if (const auto *B = dyn_cast<BinaryOperator>(Parent)) {
81
3.18k
    BinaryOperator::Opcode Opc = B->getOpcode();
82
3.18k
    if (Opc == BO_Assign) {
83
609
      if (!Cast->IgnoreParenImpCasts()->isEvaluatable(C.getASTContext())) {
84
495
        LossOfSign = isLossOfSign(Cast, C);
85
495
        LossOfPrecision = isLossOfPrecision(Cast, Cast->getType(), C);
86
495
      }
87
2.57k
    } else if (Opc == BO_AddAssign || 
Opc == BO_SubAssign2.57k
) {
88
      // No loss of sign.
89
11
      LossOfPrecision = isLossOfPrecision(Cast, B->getLHS()->getType(), C);
90
2.56k
    } else if (Opc == BO_MulAssign) {
91
25
      LossOfSign = isLossOfSign(Cast, C);
92
25
      LossOfPrecision = isLossOfPrecision(Cast, B->getLHS()->getType(), C);
93
2.53k
    } else if (Opc == BO_DivAssign || 
Opc == BO_RemAssign2.52k
) {
94
14
      LossOfSign = isLossOfSign(Cast, C);
95
      // No loss of precision.
96
2.52k
    } else if (Opc == BO_AndAssign) {
97
5
      LossOfSign = isLossOfSign(Cast, C);
98
      // No loss of precision.
99
2.52k
    } else if (Opc == BO_OrAssign || 
Opc == BO_XorAssign2.51k
) {
100
4
      LossOfSign = isLossOfSign(Cast, C);
101
4
      LossOfPrecision = isLossOfPrecision(Cast, B->getLHS()->getType(), C);
102
2.51k
    } else if (B->isRelationalOp() || 
B->isMultiplicativeOp()1.88k
) {
103
790
      LossOfSign = isLossOfSign(Cast, C);
104
790
    }
105
6.42k
  } else if (isa<DeclStmt, ReturnStmt>(Parent)) {
106
736
    if (!Cast->IgnoreParenImpCasts()->isEvaluatable(C.getASTContext())) {
107
474
      LossOfSign = isLossOfSign(Cast, C);
108
474
      LossOfPrecision = isLossOfPrecision(Cast, Cast->getType(), C);
109
474
    }
110
5.68k
  } else {
111
5.68k
    LossOfSign = isLossOfSign(Cast, C);
112
5.68k
    LossOfPrecision = isLossOfPrecision(Cast, Cast->getType(), C);
113
5.68k
  }
114
115
9.60k
  if (LossOfSign || 
LossOfPrecision9.58k
) {
116
    // Generate an error node.
117
26
    ExplodedNode *N = C.generateNonFatalErrorNode(C.getState());
118
26
    if (!N)
119
0
      return;
120
26
    if (LossOfSign)
121
15
      reportBug(N, Cast, C, "Loss of sign in implicit conversion");
122
26
    if (LossOfPrecision)
123
11
      reportBug(N, Cast, C, "Loss of precision in implicit conversion");
124
26
  }
125
9.60k
}
126
127
void ConversionChecker::reportBug(ExplodedNode *N, const Expr *E,
128
26
                                  CheckerContext &C, const char Msg[]) const {
129
26
  if (!BT)
130
2
    BT.reset(new BugType(this, "Conversion"));
131
132
  // Generate a report for this bug.
133
26
  auto R = std::make_unique<PathSensitiveBugReport>(*BT, Msg, N);
134
26
  bugreporter::trackExpressionValue(N, E, *R);
135
26
  C.emitReport(std::move(R));
136
26
}
137
138
bool ConversionChecker::isLossOfPrecision(const ImplicitCastExpr *Cast,
139
                                          QualType DestType,
140
6.69k
                                          CheckerContext &C) const {
141
  // Don't warn about explicit loss of precision.
142
6.69k
  if (Cast->isEvaluatable(C.getASTContext()))
143
2.11k
    return false;
144
145
4.58k
  QualType SubType = Cast->IgnoreParenImpCasts()->getType();
146
147
4.58k
  if (!DestType->isRealType() || 
!SubType->isIntegerType()1.98k
)
148
2.65k
    return false;
149
150
1.93k
  const bool isFloat = DestType->isFloatingType();
151
152
1.93k
  const auto &AC = C.getASTContext();
153
154
  // We will find the largest RepresentsUntilExp value such that the DestType
155
  // can exactly represent all nonnegative integers below 2^RepresentsUntilExp.
156
1.93k
  unsigned RepresentsUntilExp;
157
158
1.93k
  if (isFloat) {
159
7
    const llvm::fltSemantics &Sema = AC.getFloatTypeSemantics(DestType);
160
7
    RepresentsUntilExp = llvm::APFloat::semanticsPrecision(Sema);
161
1.92k
  } else {
162
1.92k
    RepresentsUntilExp = AC.getIntWidth(DestType);
163
1.92k
    if (RepresentsUntilExp == 1) {
164
      // This is just casting a number to bool, probably not a bug.
165
0
      return false;
166
0
    }
167
1.92k
    if (DestType->isSignedIntegerType())
168
1.57k
      RepresentsUntilExp--;
169
1.92k
  }
170
171
1.93k
  if (RepresentsUntilExp >= sizeof(unsigned long long) * CHAR_BIT) {
172
    // Avoid overflow in our later calculations.
173
67
    return false;
174
67
  }
175
176
1.86k
  unsigned CorrectedSrcWidth = AC.getIntWidth(SubType);
177
1.86k
  if (SubType->isSignedIntegerType())
178
1.43k
    CorrectedSrcWidth--;
179
180
1.86k
  if (RepresentsUntilExp >= CorrectedSrcWidth) {
181
    // Simple case: the destination can store all values of the source type.
182
1.59k
    return false;
183
1.59k
  }
184
185
265
  unsigned long long MaxVal = 1ULL << RepresentsUntilExp;
186
265
  if (isFloat) {
187
    // If this is a floating point type, it can also represent MaxVal exactly.
188
5
    MaxVal++;
189
5
  }
190
265
  return C.isGreaterOrEqual(Cast->getSubExpr(), MaxVal);
191
  // TODO: maybe also check negative values with too large magnitude.
192
1.86k
}
193
194
bool ConversionChecker::isLossOfSign(const ImplicitCastExpr *Cast,
195
7.49k
                                     CheckerContext &C) const {
196
7.49k
  QualType CastType = Cast->getType();
197
7.49k
  QualType SubType = Cast->IgnoreParenImpCasts()->getType();
198
199
7.49k
  if (!CastType->isUnsignedIntegerType() || 
!SubType->isSignedIntegerType()685
)
200
7.27k
    return false;
201
202
218
  return C.isNegative(Cast->getSubExpr());
203
7.49k
}
204
205
77
void ento::registerConversionChecker(CheckerManager &mgr) {
206
77
  mgr.registerChecker<ConversionChecker>();
207
77
}
208
209
154
bool ento::shouldRegisterConversionChecker(const CheckerManager &mgr) {
210
154
  return true;
211
154
}