Skip to content

Commit c9bccd7

Browse files
committed
Merge branch 'main' into buffer-load-all
2 parents 60e71f3 + a553c62 commit c9bccd7

File tree

2,205 files changed

+76619
-22858
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

2,205 files changed

+76619
-22858
lines changed

clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.cpp

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
//===----------------------------------------------------------------------===//
88

99
#include "ReturnConstRefFromParameterCheck.h"
10+
#include "clang/AST/Expr.h"
1011
#include "clang/ASTMatchers/ASTMatchFinder.h"
1112
#include "clang/ASTMatchers/ASTMatchers.h"
1213

@@ -15,19 +16,24 @@ using namespace clang::ast_matchers;
1516
namespace clang::tidy::bugprone {
1617

1718
void ReturnConstRefFromParameterCheck::registerMatchers(MatchFinder *Finder) {
19+
const auto DRef = ignoringParens(
20+
declRefExpr(
21+
to(parmVarDecl(hasType(hasCanonicalType(
22+
qualType(lValueReferenceType(pointee(
23+
qualType(isConstQualified()))))
24+
.bind("type"))))
25+
.bind("param")))
26+
.bind("dref"));
27+
const auto Func =
28+
functionDecl(hasReturnTypeLoc(loc(
29+
qualType(hasCanonicalType(equalsBoundNode("type"))))))
30+
.bind("func");
31+
32+
Finder->addMatcher(returnStmt(hasReturnValue(DRef), hasAncestor(Func)), this);
1833
Finder->addMatcher(
19-
returnStmt(
20-
hasReturnValue(declRefExpr(
21-
to(parmVarDecl(hasType(hasCanonicalType(
22-
qualType(lValueReferenceType(pointee(
23-
qualType(isConstQualified()))))
24-
.bind("type"))))
25-
.bind("param")))),
26-
hasAncestor(
27-
functionDecl(hasReturnTypeLoc(loc(qualType(
28-
hasCanonicalType(equalsBoundNode("type"))))))
29-
.bind("func")))
30-
.bind("ret"),
34+
returnStmt(hasReturnValue(ignoringParens(conditionalOperator(
35+
eachOf(hasTrueExpression(DRef), hasFalseExpression(DRef)),
36+
hasAncestor(Func))))),
3137
this);
3238
}
3339

@@ -85,8 +91,8 @@ void ReturnConstRefFromParameterCheck::check(
8591
const MatchFinder::MatchResult &Result) {
8692
const auto *FD = Result.Nodes.getNodeAs<FunctionDecl>("func");
8793
const auto *PD = Result.Nodes.getNodeAs<ParmVarDecl>("param");
88-
const auto *R = Result.Nodes.getNodeAs<ReturnStmt>("ret");
89-
const SourceRange Range = R->getRetValue()->getSourceRange();
94+
const auto *DRef = Result.Nodes.getNodeAs<DeclRefExpr>("dref");
95+
const SourceRange Range = DRef->getSourceRange();
9096
if (Range.isInvalid())
9197
return;
9298

clang-tools-extra/clangd/ModulesBuilder.cpp

Lines changed: 41 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
#include "clang/Frontend/FrontendAction.h"
1313
#include "clang/Frontend/FrontendActions.h"
1414
#include "clang/Serialization/ASTReader.h"
15+
#include "clang/Serialization/InMemoryModuleCache.h"
1516

1617
namespace clang {
1718
namespace clangd {
@@ -127,50 +128,68 @@ struct ModuleFile {
127128
std::string ModuleFilePath;
128129
};
129130

130-
bool IsModuleFileUpToDate(
131-
PathRef ModuleFilePath,
132-
const PrerequisiteModules &RequisiteModules) {
133-
IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
134-
CompilerInstance::createDiagnostics(new DiagnosticOptions());
135-
131+
bool IsModuleFileUpToDate(PathRef ModuleFilePath,
132+
const PrerequisiteModules &RequisiteModules,
133+
llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
136134
auto HSOpts = std::make_shared<HeaderSearchOptions>();
137135
RequisiteModules.adjustHeaderSearchOptions(*HSOpts);
138136
HSOpts->ForceCheckCXX20ModulesInputFiles = true;
139137
HSOpts->ValidateASTInputFilesContent = true;
140138

139+
clang::clangd::IgnoreDiagnostics IgnoreDiags;
140+
IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
141+
CompilerInstance::createDiagnostics(new DiagnosticOptions, &IgnoreDiags,
142+
/*ShouldOwnClient=*/false);
143+
144+
LangOptions LangOpts;
145+
LangOpts.SkipODRCheckInGMF = true;
146+
147+
FileManager FileMgr(FileSystemOptions(), VFS);
148+
149+
SourceManager SourceMgr(*Diags, FileMgr);
150+
151+
HeaderSearch HeaderInfo(HSOpts, SourceMgr, *Diags, LangOpts,
152+
/*Target=*/nullptr);
153+
154+
TrivialModuleLoader ModuleLoader;
155+
Preprocessor PP(std::make_shared<PreprocessorOptions>(), *Diags, LangOpts,
156+
SourceMgr, HeaderInfo, ModuleLoader);
157+
158+
IntrusiveRefCntPtr<InMemoryModuleCache> ModuleCache = new InMemoryModuleCache;
141159
PCHContainerOperations PCHOperations;
142-
std::unique_ptr<ASTUnit> Unit = ASTUnit::LoadFromASTFile(
143-
ModuleFilePath.str(), PCHOperations.getRawReader(), ASTUnit::LoadASTOnly,
144-
Diags, FileSystemOptions(), std::move(HSOpts));
160+
ASTReader Reader(PP, *ModuleCache, /*ASTContext=*/nullptr,
161+
PCHOperations.getRawReader(), {});
145162

146-
if (!Unit)
147-
return false;
163+
// We don't need any listener here. By default it will use a validator
164+
// listener.
165+
Reader.setListener(nullptr);
148166

149-
auto Reader = Unit->getASTReader();
150-
if (!Reader)
167+
if (Reader.ReadAST(ModuleFilePath, serialization::MK_MainFile,
168+
SourceLocation(),
169+
ASTReader::ARR_None) != ASTReader::Success)
151170
return false;
152171

153172
bool UpToDate = true;
154-
Reader->getModuleManager().visit([&](serialization::ModuleFile &MF) -> bool {
155-
Reader->visitInputFiles(
173+
Reader.getModuleManager().visit([&](serialization::ModuleFile &MF) -> bool {
174+
Reader.visitInputFiles(
156175
MF, /*IncludeSystem=*/false, /*Complain=*/false,
157176
[&](const serialization::InputFile &IF, bool isSystem) {
158177
if (!IF.getFile() || IF.isOutOfDate())
159178
UpToDate = false;
160179
});
161-
162180
return !UpToDate;
163181
});
164-
165182
return UpToDate;
166183
}
167184

168185
bool IsModuleFilesUpToDate(
169186
llvm::SmallVector<PathRef> ModuleFilePaths,
170-
const PrerequisiteModules &RequisiteModules) {
171-
return llvm::all_of(ModuleFilePaths, [&RequisiteModules](auto ModuleFilePath) {
172-
return IsModuleFileUpToDate(ModuleFilePath, RequisiteModules);
173-
});
187+
const PrerequisiteModules &RequisiteModules,
188+
llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
189+
return llvm::all_of(
190+
ModuleFilePaths, [&RequisiteModules, VFS](auto ModuleFilePath) {
191+
return IsModuleFileUpToDate(ModuleFilePath, RequisiteModules, VFS);
192+
});
174193
}
175194

176195
// StandalonePrerequisiteModules - stands for PrerequisiteModules for which all
@@ -347,7 +366,7 @@ bool StandalonePrerequisiteModules::canReuse(
347366
SmallVector<StringRef> BMIPaths;
348367
for (auto &MF : RequiredModules)
349368
BMIPaths.push_back(MF.ModuleFilePath);
350-
return IsModuleFilesUpToDate(BMIPaths, *this);
369+
return IsModuleFilesUpToDate(BMIPaths, *this, VFS);
351370
}
352371

353372
} // namespace clangd

clang-tools-extra/docs/ReleaseNotes.rst

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,11 @@ Changes in existing checks
163163
<clang-tidy/checks/bugprone/posix-return>` check to support integer literals
164164
as LHS and posix call as RHS of comparison.
165165

166+
- Improved :doc:`bugprone-return-const-ref-from-parameter
167+
<clang-tidy/checks/bugprone/return-const-ref-from-parameter>` check to
168+
diagnose potential dangling references when returning a ``const &`` parameter
169+
by using the conditional operator ``cond ? var1 : var2``.
170+
166171
- Improved :doc:`bugprone-sizeof-expression
167172
<clang-tidy/checks/bugprone/sizeof-expression>` check to find suspicious
168173
usages of ``sizeof()``, ``alignof()``, and ``offsetof()`` when adding or

clang-tools-extra/test/clang-tidy/checkers/bugprone/return-const-ref-from-parameter.cpp

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,10 @@ int const &f3(TConstRef a) { return a; }
2727
int const &f4(TConst &a) { return a; }
2828
// CHECK-MESSAGES: :[[@LINE-1]]:35: warning: returning a constant reference parameter
2929

30+
int const &f5(TConst &a) { return true ? a : a; }
31+
// CHECK-MESSAGES: :[[@LINE-1]]:42: warning: returning a constant reference parameter
32+
// CHECK-MESSAGES: :[[@LINE-2]]:46: warning: returning a constant reference parameter
33+
3034
template <typename T>
3135
const T& tf1(const T &a) { return a; }
3236
// CHECK-MESSAGES: :[[@LINE-1]]:35: warning: returning a constant reference parameter
@@ -47,6 +51,11 @@ template <typename T>
4751
const T& itf4(typename ConstRef<T>::type a) { return a; }
4852
// CHECK-MESSAGES: :[[@LINE-1]]:54: warning: returning a constant reference parameter
4953

54+
template <typename T>
55+
const T& itf5(const T &a) { return true ? a : a; }
56+
// CHECK-MESSAGES: :[[@LINE-1]]:43: warning: returning a constant reference parameter
57+
// CHECK-MESSAGES: :[[@LINE-2]]:47: warning: returning a constant reference parameter
58+
5059
void instantiate(const int &param, const float &paramf, int &mut_param, float &mut_paramf) {
5160
itf1(0);
5261
itf1(param);

clang/Maintainers.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ Sema
7272
Experimental new constant interpreter
7373
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
7474
| Timm Bäder
75-
| tbaeder\@redhat.com (em), tbaeder (Phabricator), tbaederr (GitHub), tbaeder (Discourse), tbaeder (Discord)
75+
| tbaeder\@redhat.com (email), tbaeder (Phabricator), tbaederr (GitHub), tbaeder (Discourse), tbaeder (Discord)
7676
7777

7878
Modules & serialization

clang/bindings/python/tests/cindex/test_access_specifiers.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,14 @@
11
import os
2-
from clang.cindex import Config
2+
3+
from clang.cindex import AccessSpecifier, Config
34

45
if "CLANG_LIBRARY_PATH" in os.environ:
56
Config.set_library_path(os.environ["CLANG_LIBRARY_PATH"])
67

7-
from clang.cindex import AccessSpecifier
8-
from clang.cindex import Cursor
9-
from clang.cindex import TranslationUnit
10-
11-
from .util import get_cursor
12-
from .util import get_tu
13-
148
import unittest
159

10+
from .util import get_cursor, get_tu
11+
1612

1713
class TestAccessSpecifiers(unittest.TestCase):
1814
def test_access_specifiers(self):

clang/bindings/python/tests/cindex/test_cdb.py

Lines changed: 9 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,14 @@
11
import os
2-
from clang.cindex import Config
2+
3+
from clang.cindex import CompilationDatabase, CompilationDatabaseError, Config
34

45
if "CLANG_LIBRARY_PATH" in os.environ:
56
Config.set_library_path(os.environ["CLANG_LIBRARY_PATH"])
67

7-
from clang.cindex import CompilationDatabase
8-
from clang.cindex import CompilationDatabaseError
9-
from clang.cindex import CompileCommands
10-
from clang.cindex import CompileCommand
11-
import os
128
import gc
139
import unittest
1410
import sys
15-
from .util import skip_if_no_fspath
16-
from .util import str_to_path
17-
11+
from pathlib import Path
1812

1913
kInputsDir = os.path.join(os.path.dirname(__file__), "INPUTS")
2014

@@ -31,7 +25,7 @@ def test_create_fail(self):
3125
with open(os.devnull, "wb") as null:
3226
os.dup2(null.fileno(), 2)
3327
with self.assertRaises(CompilationDatabaseError) as cm:
34-
cdb = CompilationDatabase.fromDirectory(path)
28+
CompilationDatabase.fromDirectory(path)
3529
os.dup2(stderr, 2)
3630
os.close(stderr)
3731

@@ -40,21 +34,18 @@ def test_create_fail(self):
4034

4135
def test_create(self):
4236
"""Check we can load a compilation database"""
43-
cdb = CompilationDatabase.fromDirectory(kInputsDir)
37+
CompilationDatabase.fromDirectory(kInputsDir)
4438

4539
def test_lookup_succeed(self):
4640
"""Check we get some results if the file exists in the db"""
4741
cdb = CompilationDatabase.fromDirectory(kInputsDir)
4842
cmds = cdb.getCompileCommands("/home/john.doe/MyProject/project.cpp")
4943
self.assertNotEqual(len(cmds), 0)
5044

51-
@skip_if_no_fspath
5245
def test_lookup_succeed_pathlike(self):
5346
"""Same as test_lookup_succeed, but with PathLikes"""
54-
cdb = CompilationDatabase.fromDirectory(str_to_path(kInputsDir))
55-
cmds = cdb.getCompileCommands(
56-
str_to_path("/home/john.doe/MyProject/project.cpp")
57-
)
47+
cdb = CompilationDatabase.fromDirectory(Path(kInputsDir))
48+
cmds = cdb.getCompileCommands(Path("/home/john.doe/MyProject/project.cpp"))
5849
self.assertNotEqual(len(cmds), 0)
5950

6051
def test_all_compilecommand(self):
@@ -175,7 +166,7 @@ def test_compilationDB_references(self):
175166
cmds = cdb.getCompileCommands("/home/john.doe/MyProject/project.cpp")
176167
del cdb
177168
gc.collect()
178-
workingdir = cmds[0].directory
169+
cmds[0].directory
179170

180171
def test_compilationCommands_references(self):
181172
"""Ensure CompilationsCommand keeps a reference to CompilationCommands"""
@@ -185,4 +176,4 @@ def test_compilationCommands_references(self):
185176
cmd0 = cmds[0]
186177
del cmds
187178
gc.collect()
188-
workingdir = cmd0.directory
179+
cmd0.directory

clang/bindings/python/tests/cindex/test_code_completion.py

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,12 @@
11
import os
2-
from clang.cindex import Config
2+
3+
from clang.cindex import Config, TranslationUnit
34

45
if "CLANG_LIBRARY_PATH" in os.environ:
56
Config.set_library_path(os.environ["CLANG_LIBRARY_PATH"])
67

7-
from clang.cindex import TranslationUnit
8-
98
import unittest
10-
from .util import skip_if_no_fspath
11-
from .util import str_to_path
9+
from pathlib import Path
1210

1311

1412
class TestCodeCompletion(unittest.TestCase):
@@ -57,11 +55,10 @@ def test_code_complete(self):
5755
]
5856
self.check_completion_results(cr, expected)
5957

60-
@skip_if_no_fspath
6158
def test_code_complete_pathlike(self):
6259
files = [
6360
(
64-
str_to_path("fake.c"),
61+
Path("fake.c"),
6562
"""
6663
/// Aaa.
6764
int test1;
@@ -77,14 +74,14 @@ def test_code_complete_pathlike(self):
7774
]
7875

7976
tu = TranslationUnit.from_source(
80-
str_to_path("fake.c"),
77+
Path("fake.c"),
8178
["-std=c99"],
8279
unsaved_files=files,
8380
options=TranslationUnit.PARSE_INCLUDE_BRIEF_COMMENTS_IN_CODE_COMPLETION,
8481
)
8582

8683
cr = tu.codeComplete(
87-
str_to_path("fake.c"),
84+
Path("fake.c"),
8885
9,
8986
1,
9087
unsaved_files=files,

clang/bindings/python/tests/cindex/test_comment.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
import os
2-
from clang.cindex import Config
2+
3+
from clang.cindex import Config, TranslationUnit
34

45
if "CLANG_LIBRARY_PATH" in os.environ:
56
Config.set_library_path(os.environ["CLANG_LIBRARY_PATH"])
67

7-
from clang.cindex import TranslationUnit
8-
from tests.cindex.util import get_cursor
9-
108
import unittest
119

10+
from .util import get_cursor
11+
1212

1313
class TestComment(unittest.TestCase):
1414
def test_comment(self):

0 commit comments

Comments
 (0)