clang-tools 23.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(VarDecl, hasConstantDeclaration) {
21 if (Node.isConstexpr() || Node.hasAttr<ConstInitAttr>())
22 return true;
23 if (const VarDecl *Def = Node.getDefinition();
24 Def && (Def->isConstexpr() || Def->hasAttr<ConstInitAttr>()))
25 return true;
26 const Expr *Init = Node.getInit();
27 if (Init && !Init->isValueDependent())
28 return Node.evaluateValue();
29 return false;
30}
31
32} // namespace
33
37
39 Finder->addMatcher(
40 varDecl(hasGlobalStorage(), unless(hasConstantDeclaration())).bind("var"),
41 this);
42}
43
45 const MatchFinder::MatchResult &Result) {
46 const auto *Var = Result.Nodes.getNodeAs<VarDecl>("var");
47 const SourceLocation Loc = Var->getLocation();
48 if (!Loc.isValid() ||
49 !utils::isPresumedLocInHeaderFile(Loc, *Result.SourceManager,
50 getHeaderFileExtensions()))
51 return;
52 // If the initializer is a constant expression, then the compiler
53 // doesn't have to dynamically initialize it.
54 diag(Loc,
55 "static variable %0 may be dynamically initialized in this header file")
56 << Var;
57}
58
59} // 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.