10#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12#include "clang/ASTMatchers/ASTMatchersMacros.h"
13#include "clang/Lex/Lexer.h"
21AST_MATCHER(ImplicitCastExpr, isPartOfExplicitCast) {
22 return Node.isPartOfExplicitCast();
24AST_MATCHER(Expr, containsErrors) {
return Node.containsErrors(); }
28 assert(E == E->IgnoreParens() &&
"Already skipped all parens!");
31 const auto *BO = dyn_cast<BinaryOperator>(E);
32 if (!BO || BO->getOpcode() != BO_Mul)
35 return BO->getLHS()->IgnoreParens();
42 UseCXXStaticCastsInCppSources(
43 Options.get(
"UseCXXStaticCastsInCppSources", true)),
44 UseCXXHeadersInCppSources(Options.get(
"UseCXXHeadersInCppSources", true)),
45 IgnoreConstantIntExpr(Options.get(
"IgnoreConstantIntExpr", false)),
46 IncludeInserter(Options.getLocalOrGlobal(
"IncludeStyle",
47 utils::IncludeSorter::IS_LLVM),
48 areDiagsSelfContained()) {}
51 const SourceManager &SM, Preprocessor *
PP, Preprocessor *ModuleExpanderPP) {
52 IncludeInserter.registerPreprocessor(
PP);
57 Options.store(Opts,
"UseCXXStaticCastsInCppSources",
58 UseCXXStaticCastsInCppSources);
59 Options.store(Opts,
"UseCXXHeadersInCppSources", UseCXXHeadersInCppSources);
60 Options.store(Opts,
"IgnoreConstantIntExpr", IgnoreConstantIntExpr);
61 Options.store(Opts,
"IncludeStyle", IncludeInserter.getStyle());
64std::optional<FixItHint>
65ImplicitWideningOfMultiplicationResultCheck::includeStddefHeader(
66 SourceLocation File) {
67 return IncludeInserter.createIncludeInsertion(
68 Result->SourceManager->getFileID(File),
69 ShouldUseCXXHeader ?
"<cstddef>" :
"<stddef.h>");
72void ImplicitWideningOfMultiplicationResultCheck::handleImplicitCastExpr(
73 const ImplicitCastExpr *ICE) {
74 const ASTContext *Context = Result->Context;
76 const Expr *E = ICE->getSubExpr()->IgnoreParens();
77 const QualType Ty = ICE->getType();
78 const QualType ETy = E->getType();
80 assert(!ETy->isDependentType() && !Ty->isDependentType() &&
81 "Don't expect to ever get here in template Context.");
84 const unsigned SrcWidth = Context->getIntWidth(ETy);
85 const unsigned TgtWidth = Context->getIntWidth(Ty);
86 if (TgtWidth <= SrcWidth)
91 if (IgnoreConstantIntExpr && ETy->isIntegerType() &&
92 !ETy->isUnsignedIntegerType()) {
93 if (
const auto ConstExprResult = E->getIntegerConstantExpr(*Context)) {
94 const auto TypeSize = Context->getTypeSize(ETy);
95 const llvm::APSInt WidenedResult = ConstExprResult->extOrTrunc(TypeSize);
96 if (WidenedResult <= llvm::APSInt::getMaxValue(TypeSize,
false) &&
97 WidenedResult >= llvm::APSInt::getMinValue(TypeSize,
false))
109 diag(E->getBeginLoc(),
"performing an implicit widening conversion to type "
110 "%0 of a multiplication performed in type %1")
111 << Ty << E->getType();
114 const auto Diag = diag(E->getBeginLoc(),
115 "make conversion explicit to silence this warning",
117 << E->getSourceRange();
118 const SourceLocation EndLoc = Lexer::getLocForEndOfToken(
119 E->getEndLoc(), 0, *Result->SourceManager, getLangOpts());
120 if (ShouldUseCXXStaticCast)
121 Diag << FixItHint::CreateInsertion(
122 E->getBeginLoc(),
"static_cast<" + Ty.getAsString() +
">(")
123 << FixItHint::CreateInsertion(EndLoc,
")");
125 Diag << FixItHint::CreateInsertion(E->getBeginLoc(),
126 "(" + Ty.getAsString() +
")(")
127 << FixItHint::CreateInsertion(EndLoc,
")");
128 Diag << includeStddefHeader(E->getBeginLoc());
134 if (Ty->isSignedIntegerType() == ETy->isSignedIntegerType()) {
136 }
else if (Ty->isSignedIntegerType()) {
137 assert(ETy->isUnsignedIntegerType() &&
138 "Expected source type to be signed.");
139 WideExprTy = Context->getCorrespondingUnsignedType(Ty);
141 assert(Ty->isUnsignedIntegerType() &&
142 "Expected target type to be unsigned.");
143 assert(ETy->isSignedIntegerType() &&
144 "Expected source type to be unsigned.");
145 WideExprTy = Context->getCorrespondingSignedType(Ty);
150 diag(E->getBeginLoc(),
"perform multiplication in a wider type",
152 << LHS->getSourceRange();
154 if (ShouldUseCXXStaticCast)
155 Diag << FixItHint::CreateInsertion(LHS->getBeginLoc(),
157 WideExprTy.getAsString() +
">(")
158 << FixItHint::CreateInsertion(
159 Lexer::getLocForEndOfToken(LHS->getEndLoc(), 0,
160 *Result->SourceManager,
164 Diag << FixItHint::CreateInsertion(LHS->getBeginLoc(),
165 "(" + WideExprTy.getAsString() +
")");
166 Diag << includeStddefHeader(LHS->getBeginLoc());
170void ImplicitWideningOfMultiplicationResultCheck::handlePointerOffsetting(
172 const ASTContext *Context = Result->Context;
176 const Expr *PointerExpr =
nullptr, *IndexExpr =
nullptr;
177 if (
const auto *BO = dyn_cast<BinaryOperator>(E)) {
178 PointerExpr = BO->getLHS();
179 IndexExpr = BO->getRHS();
180 }
else if (
const auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
181 PointerExpr = ASE->getLHS();
182 IndexExpr = ASE->getRHS();
187 if (IndexExpr->getType()->isPointerType())
188 std::swap(PointerExpr, IndexExpr);
190 if (!PointerExpr->getType()->isPointerType() ||
191 IndexExpr->getType()->isPointerType())
194 IndexExpr = IndexExpr->IgnoreParens();
196 const QualType IndexExprType = IndexExpr->getType();
200 if (IndexExprType->isDependentType())
203 const QualType SSizeTy = Context->getPointerDiffType();
204 const QualType USizeTy = Context->getSizeType();
205 const QualType SizeTy =
206 IndexExprType->isSignedIntegerType() ? SSizeTy : USizeTy;
209 const StringRef TyAsString =
210 IndexExprType->isSignedIntegerType() ?
"ptrdiff_t" :
"size_t";
213 if (Context->getIntWidth(IndexExprType) >= Context->getIntWidth(SizeTy))
223 diag(E->getBeginLoc(),
224 "result of multiplication in type %0 is used as a pointer offset after "
225 "an implicit widening conversion to type '%1'")
226 << IndexExprType << TyAsString;
229 const auto Diag = diag(IndexExpr->getBeginLoc(),
230 "make conversion explicit to silence this warning",
232 << IndexExpr->getSourceRange();
233 const SourceLocation EndLoc = Lexer::getLocForEndOfToken(
234 IndexExpr->getEndLoc(), 0, *Result->SourceManager, getLangOpts());
235 if (ShouldUseCXXStaticCast)
236 Diag << FixItHint::CreateInsertion(
237 IndexExpr->getBeginLoc(),
238 (Twine(
"static_cast<") + TyAsString +
">(").str())
239 << FixItHint::CreateInsertion(EndLoc,
")");
241 Diag << FixItHint::CreateInsertion(IndexExpr->getBeginLoc(),
242 (Twine(
"(") + TyAsString +
")(").str())
243 << FixItHint::CreateInsertion(EndLoc,
")");
244 Diag << includeStddefHeader(IndexExpr->getBeginLoc());
249 diag(IndexExpr->getBeginLoc(),
"perform multiplication in a wider type",
251 << LHS->getSourceRange();
253 if (ShouldUseCXXStaticCast)
254 Diag << FixItHint::CreateInsertion(
256 (Twine(
"static_cast<") + TyAsString +
">(").str())
257 << FixItHint::CreateInsertion(
258 Lexer::getLocForEndOfToken(IndexExpr->getEndLoc(), 0,
259 *Result->SourceManager,
263 Diag << FixItHint::CreateInsertion(LHS->getBeginLoc(),
264 (Twine(
"(") + TyAsString +
")").str());
265 Diag << includeStddefHeader(LHS->getBeginLoc());
270 MatchFinder *Finder) {
271 Finder->addMatcher(implicitCastExpr(unless(anyOf(containsErrors(),
272 isInTemplateInstantiation(),
273 isPartOfExplicitCast())),
274 hasCastKind(CK_IntegralCast))
278 arraySubscriptExpr(unless(isInTemplateInstantiation())).bind(
"x"),
this);
279 Finder->addMatcher(binaryOperator(unless(isInTemplateInstantiation()),
280 hasType(isAnyPointer()),
281 hasAnyOperatorName(
"+",
"-",
"+=",
"-="))
287 const MatchFinder::MatchResult &Result) {
288 this->Result = &Result;
289 ShouldUseCXXStaticCast =
290 UseCXXStaticCastsInCppSources && Result.Context->getLangOpts().CPlusPlus;
292 UseCXXHeadersInCppSources && Result.Context->getLangOpts().CPlusPlus;
294 if (
const auto *MatchedDecl = Result.Nodes.getNodeAs<ImplicitCastExpr>(
"x"))
295 handleImplicitCastExpr(MatchedDecl);
296 else if (
const auto *MatchedDecl =
297 Result.Nodes.getNodeAs<ArraySubscriptExpr>(
"x"))
298 handlePointerOffsetting(MatchedDecl);
299 else if (
const auto *MatchedDecl =
300 Result.Nodes.getNodeAs<BinaryOperator>(
"x"))
301 handlePointerOffsetting(MatchedDecl);
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
ImplicitWideningOfMultiplicationResultCheck(StringRef Name, ClangTidyContext *Context)
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) override
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
void registerMatchers(ast_matchers::MatchFinder *Finder) override
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
static const Expr * getLHSOfMulBinOp(const Expr *E)
AST_MATCHER(BinaryOperator, isRelationalOperator)
llvm::StringMap< ClangTidyValue > OptionMap