Skip to content

Commit c4f83a0

Browse files
[clang-tidy] new check misc-use-internal-linkage (#90830)
Add new check misc-use-internal-linkage to detect variable and function can be marked as static. --------- Co-authored-by: Danny Mösch <[email protected]>
1 parent 0cdb0b7 commit c4f83a0

File tree

13 files changed

+258
-0
lines changed

13 files changed

+258
-0
lines changed

clang-tools-extra/clang-tidy/misc/CMakeLists.txt

+1
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ add_clang_library(clangTidyMiscModule
4141
UnusedParametersCheck.cpp
4242
UnusedUsingDeclsCheck.cpp
4343
UseAnonymousNamespaceCheck.cpp
44+
UseInternalLinkageCheck.cpp
4445

4546
LINK_LIBS
4647
clangTidy

clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp

+3
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
#include "UnusedParametersCheck.h"
3232
#include "UnusedUsingDeclsCheck.h"
3333
#include "UseAnonymousNamespaceCheck.h"
34+
#include "UseInternalLinkageCheck.h"
3435

3536
namespace clang::tidy {
3637
namespace misc {
@@ -78,6 +79,8 @@ class MiscModule : public ClangTidyModule {
7879
"misc-unused-using-decls");
7980
CheckFactories.registerCheck<UseAnonymousNamespaceCheck>(
8081
"misc-use-anonymous-namespace");
82+
CheckFactories.registerCheck<UseInternalLinkageCheck>(
83+
"misc-use-internal-linkage");
8184
}
8285
};
8386

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
//===--- UseInternalLinkageCheck.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 "UseInternalLinkageCheck.h"
10+
#include "../utils/FileExtensionsUtils.h"
11+
#include "clang/AST/Decl.h"
12+
#include "clang/ASTMatchers/ASTMatchFinder.h"
13+
#include "clang/ASTMatchers/ASTMatchers.h"
14+
#include "clang/ASTMatchers/ASTMatchersMacros.h"
15+
#include "clang/Basic/SourceLocation.h"
16+
#include "clang/Basic/Specifiers.h"
17+
#include "llvm/ADT/STLExtras.h"
18+
19+
using namespace clang::ast_matchers;
20+
21+
namespace clang::tidy::misc {
22+
23+
namespace {
24+
25+
AST_MATCHER(Decl, isFirstDecl) { return Node.isFirstDecl(); }
26+
27+
static bool isInMainFile(SourceLocation L, SourceManager &SM,
28+
const FileExtensionsSet &HeaderFileExtensions) {
29+
for (;;) {
30+
if (utils::isSpellingLocInHeaderFile(L, SM, HeaderFileExtensions))
31+
return false;
32+
if (SM.isInMainFile(L))
33+
return true;
34+
// not in header file but not in main file
35+
L = SM.getIncludeLoc(SM.getFileID(L));
36+
if (L.isValid())
37+
continue;
38+
// Conservative about the unknown
39+
return false;
40+
}
41+
}
42+
43+
AST_MATCHER_P(Decl, isAllRedeclsInMainFile, FileExtensionsSet,
44+
HeaderFileExtensions) {
45+
return llvm::all_of(Node.redecls(), [&](const Decl *D) {
46+
return isInMainFile(D->getLocation(),
47+
Finder->getASTContext().getSourceManager(),
48+
HeaderFileExtensions);
49+
});
50+
}
51+
52+
AST_POLYMORPHIC_MATCHER(isExternStorageClass,
53+
AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
54+
VarDecl)) {
55+
return Node.getStorageClass() == SC_Extern;
56+
}
57+
58+
} // namespace
59+
60+
void UseInternalLinkageCheck::registerMatchers(MatchFinder *Finder) {
61+
auto Common =
62+
allOf(isFirstDecl(), isAllRedeclsInMainFile(HeaderFileExtensions),
63+
unless(anyOf(
64+
// 1. internal linkage
65+
isStaticStorageClass(), isInAnonymousNamespace(),
66+
// 2. explicit external linkage
67+
isExternStorageClass(), isExternC(),
68+
// 3. template
69+
isExplicitTemplateSpecialization(),
70+
// 4. friend
71+
hasAncestor(friendDecl()))));
72+
Finder->addMatcher(
73+
functionDecl(Common, unless(cxxMethodDecl()), unless(isMain()))
74+
.bind("fn"),
75+
this);
76+
Finder->addMatcher(varDecl(Common, hasGlobalStorage()).bind("var"), this);
77+
}
78+
79+
static constexpr StringRef Message =
80+
"%0 %1 can be made static or moved into an anonymous namespace "
81+
"to enforce internal linkage";
82+
83+
void UseInternalLinkageCheck::check(const MatchFinder::MatchResult &Result) {
84+
if (const auto *FD = Result.Nodes.getNodeAs<FunctionDecl>("fn")) {
85+
diag(FD->getLocation(), Message) << "function" << FD;
86+
return;
87+
}
88+
if (const auto *VD = Result.Nodes.getNodeAs<VarDecl>("var")) {
89+
diag(VD->getLocation(), Message) << "variable" << VD;
90+
return;
91+
}
92+
llvm_unreachable("");
93+
}
94+
95+
} // namespace clang::tidy::misc
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
//===--- UseInternalLinkageCheck.h - clang-tidy -----------------*- 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+
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_USEINTERNALLINKAGECHECK_H
10+
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_USEINTERNALLINKAGECHECK_H
11+
12+
#include "../ClangTidyCheck.h"
13+
14+
namespace clang::tidy::misc {
15+
16+
/// Detects variables and functions that can be marked as static or moved into
17+
/// an anonymous namespace to enforce internal linkage.
18+
///
19+
/// For the user-facing documentation see:
20+
/// http://clang.llvm.org/extra/clang-tidy/checks/misc/use-internal-linkage.html
21+
class UseInternalLinkageCheck : public ClangTidyCheck {
22+
public:
23+
UseInternalLinkageCheck(StringRef Name, ClangTidyContext *Context)
24+
: ClangTidyCheck(Name, Context),
25+
HeaderFileExtensions(Context->getHeaderFileExtensions()) {}
26+
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
27+
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
28+
std::optional<TraversalKind> getCheckTraversalKind() const override {
29+
return TK_IgnoreUnlessSpelledInSource;
30+
}
31+
32+
private:
33+
FileExtensionsSet HeaderFileExtensions;
34+
};
35+
36+
} // namespace clang::tidy::misc
37+
38+
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_USEINTERNALLINKAGECHECK_H

clang-tools-extra/docs/ReleaseNotes.rst

+6
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,12 @@ New checks
148148
to reading out-of-bounds data due to inadequate or incorrect string null
149149
termination.
150150

151+
- New :doc:`misc-use-internal-linkage
152+
<clang-tidy/checks/misc/use-internal-linkage>` check.
153+
154+
Detects variables and functions that can be marked as static or moved into
155+
an anonymous namespace to enforce internal linkage.
156+
151157
- New :doc:`modernize-min-max-use-initializer-list
152158
<clang-tidy/checks/modernize/min-max-use-initializer-list>` check.
153159

clang-tools-extra/docs/clang-tidy/checks/list.rst

+1
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,7 @@ Clang-Tidy Checks
267267
:doc:`misc-unused-parameters <misc/unused-parameters>`, "Yes"
268268
:doc:`misc-unused-using-decls <misc/unused-using-decls>`, "Yes"
269269
:doc:`misc-use-anonymous-namespace <misc/use-anonymous-namespace>`,
270+
:doc:`misc-use-internal-linkage <misc/use-internal-linkage>`,
270271
:doc:`modernize-avoid-bind <modernize/avoid-bind>`, "Yes"
271272
:doc:`modernize-avoid-c-arrays <modernize/avoid-c-arrays>`,
272273
:doc:`modernize-concat-nested-namespaces <modernize/concat-nested-namespaces>`, "Yes"
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
.. title:: clang-tidy - misc-use-internal-linkage
2+
3+
misc-use-internal-linkage
4+
=========================
5+
6+
Detects variables and functions that can be marked as static or moved into
7+
an anonymous namespace to enforce internal linkage.
8+
9+
Static functions and variables are scoped to a single file. Marking functions
10+
and variables as static helps to better remove dead code. In addition, it gives
11+
the compiler more information and allows for more aggressive optimizations.
12+
13+
Example:
14+
15+
.. code-block:: c++
16+
17+
int v1; // can be marked as static
18+
19+
void fn1(); // can be marked as static
20+
21+
namespace {
22+
// already in anonymous namespace
23+
int v2;
24+
void fn2();
25+
}
26+
// already declared as extern
27+
extern int v2;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
#pragma once
2+
3+
void func_header();
4+
5+
#include "func_h.inc"
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
void func_cpp_inc();
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
void func_h_inc();
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
#pragma once
2+
3+
extern int gloabl_header;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// RUN: %check_clang_tidy %s misc-use-internal-linkage %t -- -- -I%S/Inputs/use-internal-linkage
2+
3+
#include "func.h"
4+
5+
void func() {}
6+
// CHECK-MESSAGES: :[[@LINE-1]]:6: warning: function 'func'
7+
8+
template<class T>
9+
void func_template() {}
10+
// CHECK-MESSAGES: :[[@LINE-1]]:6: warning: function 'func_template'
11+
12+
void func_cpp_inc();
13+
// CHECK-MESSAGES: :[[@LINE-1]]:6: warning: function 'func_cpp_inc'
14+
15+
#include "func_cpp.inc"
16+
17+
void func_h_inc();
18+
19+
struct S {
20+
void method();
21+
};
22+
void S::method() {}
23+
24+
void func_header();
25+
extern void func_extern();
26+
static void func_static();
27+
namespace {
28+
void func_anonymous_ns();
29+
} // namespace
30+
31+
int main(int argc, const char*argv[]) {}
32+
33+
extern "C" {
34+
void func_extern_c_1() {}
35+
}
36+
37+
extern "C" void func_extern_c_2() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// RUN: %check_clang_tidy %s misc-use-internal-linkage %t -- -- -I%S/Inputs/use-internal-linkage
2+
3+
#include "var.h"
4+
5+
int global;
6+
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: variable 'global'
7+
8+
template<class T>
9+
T global_template;
10+
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: variable 'global_template'
11+
12+
int gloabl_header;
13+
14+
extern int global_extern;
15+
16+
static int global_static;
17+
18+
namespace {
19+
static int global_anonymous_ns;
20+
namespace NS {
21+
static int global_anonymous_ns;
22+
}
23+
}
24+
25+
static void f(int para) {
26+
int local;
27+
static int local_static;
28+
}
29+
30+
struct S {
31+
int m1;
32+
static int m2;
33+
};
34+
int S::m2;
35+
36+
extern "C" {
37+
int global_in_extern_c_1;
38+
}
39+
40+
extern "C" int global_in_extern_c_2;

0 commit comments

Comments
 (0)