clang-tools 22.0.0git
DynamicStaticInitializersCheck.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
11#include "clang/AST/ASTContext.h"
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13
14using namespace clang::ast_matchers;
15
16namespace clang::tidy::bugprone {
17
18namespace {
19
20AST_MATCHER(clang::VarDecl, hasConstantDeclaration) {
21 if (Node.isConstexpr())
22 return true;
23 const Expr *Init = Node.getInit();
24 if (Init && !Init->isValueDependent())
25 return Node.evaluateValue();
26 return false;
27}
28
29} // namespace
30
32 StringRef Name, ClangTidyContext *Context)
33 : ClangTidyCheck(Name, Context),
34 HeaderFileExtensions(Context->getHeaderFileExtensions()) {}
35
37 Finder->addMatcher(
38 varDecl(hasGlobalStorage(), unless(hasConstantDeclaration())).bind("var"),
39 this);
40}
41
43 const MatchFinder::MatchResult &Result) {
44 const auto *Var = Result.Nodes.getNodeAs<VarDecl>("var");
45 const SourceLocation Loc = Var->getLocation();
46 if (!Loc.isValid() || !utils::isPresumedLocInHeaderFile(
47 Loc, *Result.SourceManager, HeaderFileExtensions))
48 return;
49 // If the initializer is a constant expression, then the compiler
50 // doesn't have to dynamically initialize it.
51 diag(Loc,
52 "static variable %0 may be dynamically initialized in this header file")
53 << Var;
54}
55
56} // namespace clang::tidy::bugprone
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
DynamicStaticInitializersCheck(StringRef Name, ClangTidyContext *Context)
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
void registerMatchers(ast_matchers::MatchFinder *Finder) override
AST_MATCHER(BinaryOperator, isRelationalOperator)
bool isPresumedLocInHeaderFile(SourceLocation Loc, SourceManager &SM, const FileExtensionsSet &HeaderFileExtensions)
Checks whether presumed location of Loc is in header file.