Skip to content

[InstCombine] Don't look at ConstantData users #103302

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -136,8 +136,8 @@ struct Header {
}
StringRef verbatim() const { return std::get<Verbatim>(Storage); }

/// Absolute path for the header when it's a physical file. Otherwise just
/// the spelling without surrounding quotes/brackets.
/// For phiscal files, either absolute path or path relative to the execution
/// root. Otherwise just the spelling without surrounding quotes/brackets.
llvm::StringRef resolvedPath() const;

private:
Expand Down
41 changes: 21 additions & 20 deletions clang-tools-extra/include-cleaner/lib/Analysis.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ analyze(llvm::ArrayRef<Decl *> ASTRoots,
const PragmaIncludes *PI, const Preprocessor &PP,
llvm::function_ref<bool(llvm::StringRef)> HeaderFilter) {
auto &SM = PP.getSourceManager();
const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID());
const auto MainFile = *SM.getFileEntryRefForID(SM.getMainFileID());
llvm::DenseSet<const Include *> Used;
llvm::StringSet<> Missing;
if (!HeaderFilter)
Expand All @@ -95,37 +95,38 @@ analyze(llvm::ArrayRef<Decl *> ASTRoots,
for (const Header &H : Providers) {
if (H.kind() == Header::Physical &&
(H.physical() == MainFile ||
(ResourceDir && H.physical().getDir() == *ResourceDir))) {
H.physical().getDir() == ResourceDir)) {
Satisfied = true;
}
for (const Include *I : Inc.match(H)) {
Used.insert(I);
Satisfied = true;
}
}
if (!Satisfied && !Providers.empty() &&
Ref.RT == RefType::Explicit &&
!HeaderFilter(Providers.front().resolvedPath())) {
// Check if we have any headers with the same spelling, in edge
// cases like `#include_next "foo.h"`, the user can't ever
// include the physical foo.h, but can have a spelling that
// refers to it.
auto Spelling = spellHeader(
{Providers.front(), PP.getHeaderSearchInfo(), MainFile});
for (const Include *I : Inc.match(Header{Spelling})) {
Used.insert(I);
Satisfied = true;
}
if (!Satisfied)
Missing.insert(std::move(Spelling));
// Bail out if we can't (or need not) insert an include.
if (Satisfied || Providers.empty() || Ref.RT != RefType::Explicit)
return;
if (HeaderFilter(Providers.front().resolvedPath()))
return;
// Check if we have any headers with the same spelling, in edge
// cases like `#include_next "foo.h"`, the user can't ever
// include the physical foo.h, but can have a spelling that
// refers to it.
auto Spelling = spellHeader(
{Providers.front(), PP.getHeaderSearchInfo(), MainFile});
for (const Include *I : Inc.match(Header{Spelling})) {
Used.insert(I);
Satisfied = true;
}
if (!Satisfied)
Missing.insert(std::move(Spelling));
});

AnalysisResults Results;
for (const Include &I : Inc.all()) {
if (Used.contains(&I) || !I.Resolved ||
HeaderFilter(I.Resolved->getFileEntry().tryGetRealPathName()) ||
(ResourceDir && I.Resolved->getFileEntry().getDir() == *ResourceDir))
HeaderFilter(I.Resolved->getName()) ||
I.Resolved->getDir() == ResourceDir)
continue;
if (PI) {
if (PI->shouldKeep(*I.Resolved))
Expand All @@ -137,7 +138,7 @@ analyze(llvm::ArrayRef<Decl *> ASTRoots,
// Since most private -> public mappings happen in a verbatim way, we
// check textually here. This might go wrong in presence of symlinks or
// header mappings. But that's not different than rest of the places.
if (MainFile->tryGetRealPathName().ends_with(PHeader))
if (MainFile.getName().ends_with(PHeader))
continue;
}
}
Expand Down
19 changes: 2 additions & 17 deletions clang-tools-extra/include-cleaner/lib/HTMLReport.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
//===----------------------------------------------------------------------===//

#include "AnalysisInternal.h"
#include "clang-include-cleaner/IncludeSpeller.h"
#include "clang-include-cleaner/Types.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/PrettyPrinter.h"
Expand Down Expand Up @@ -167,22 +168,6 @@ class Reporter {
return "semiused";
}

std::string spellHeader(const Header &H) {
switch (H.kind()) {
case Header::Physical: {
bool IsAngled = false;
std::string Path = HS.suggestPathToFileForDiagnostics(
H.physical(), MainFE->tryGetRealPathName(), &IsAngled);
return IsAngled ? "<" + Path + ">" : "\"" + Path + "\"";
}
case Header::Standard:
return H.standard().name().str();
case Header::Verbatim:
return H.verbatim().str();
}
llvm_unreachable("Unknown Header kind");
}

void fillTarget(Ref &R) {
// Duplicates logic from walkUsed(), which doesn't expose SymbolLocations.
for (auto &Loc : locateSymbol(R.Sym))
Expand All @@ -204,7 +189,7 @@ class Reporter {
R.Includes.end());

if (!R.Headers.empty())
R.Insert = spellHeader(R.Headers.front());
R.Insert = spellHeader({R.Headers.front(), HS, MainFE});
}

public:
Expand Down
3 changes: 1 addition & 2 deletions clang-tools-extra/include-cleaner/lib/Types.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
#include "TypesInternal.h"
#include "clang/AST/Decl.h"
#include "clang/Basic/FileEntry.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
Expand Down Expand Up @@ -48,7 +47,7 @@ llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Symbol &S) {
llvm::StringRef Header::resolvedPath() const {
switch (kind()) {
case include_cleaner::Header::Physical:
return physical().getFileEntry().tryGetRealPathName();
return physical().getName();
case include_cleaner::Header::Standard:
return standard().name().trim("<>\"");
case include_cleaner::Header::Verbatim:
Expand Down
2 changes: 1 addition & 1 deletion clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ class Action : public clang::ASTFrontendAction {
writeHTML();

llvm::StringRef Path =
SM.getFileEntryForID(SM.getMainFileID())->tryGetRealPathName();
SM.getFileEntryRefForID(SM.getMainFileID())->getName();
assert(!Path.empty() && "Main file path not known?");
llvm::StringRef Code = SM.getBufferData(SM.getMainFileID());

Expand Down
75 changes: 73 additions & 2 deletions clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,12 @@
#include "clang/Testing/TestAST.h"
#include "clang/Tooling/Inclusions/StandardLibrary.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/ScopedPrinter.h"
#include "llvm/Support/VirtualFileSystem.h"
#include "llvm/Testing/Annotations/Annotations.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
Expand Down Expand Up @@ -204,21 +207,37 @@ class AnalyzeTest : public testing::Test {
TestInputs Inputs;
PragmaIncludes PI;
RecordedPP PP;
llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> ExtraFS = nullptr;

AnalyzeTest() {
Inputs.MakeAction = [this] {
struct Hook : public SyntaxOnlyAction {
public:
Hook(RecordedPP &PP, PragmaIncludes &PI) : PP(PP), PI(PI) {}
Hook(RecordedPP &PP, PragmaIncludes &PI,
llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> ExtraFS)
: PP(PP), PI(PI), ExtraFS(std::move(ExtraFS)) {}
bool BeginSourceFileAction(clang::CompilerInstance &CI) override {
CI.getPreprocessor().addPPCallbacks(PP.record(CI.getPreprocessor()));
PI.record(CI);
return true;
}

bool BeginInvocation(CompilerInstance &CI) override {
if (!ExtraFS)
return true;
auto OverlayFS =
llvm::makeIntrusiveRefCnt<llvm::vfs::OverlayFileSystem>(
CI.getFileManager().getVirtualFileSystemPtr());
OverlayFS->pushOverlay(ExtraFS);
CI.getFileManager().setVirtualFileSystem(std::move(OverlayFS));
return true;
}

RecordedPP &PP;
PragmaIncludes &PI;
llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> ExtraFS;
};
return std::make_unique<Hook>(PP, PI);
return std::make_unique<Hook>(PP, PI, ExtraFS);
};
}
};
Expand Down Expand Up @@ -322,6 +341,58 @@ TEST_F(AnalyzeTest, DifferentHeaderSameSpelling) {
EXPECT_THAT(Results.Missing, testing::IsEmpty());
}

TEST_F(AnalyzeTest, SpellingIncludesWithSymlinks) {
llvm::Annotations Code(R"cpp(
#include "header.h"
void $bar^bar() {
$foo^foo();
}
)cpp");
Inputs.Code = Code.code();
ExtraFS = llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
ExtraFS->addFile("content_for/0", /*ModificationTime=*/{},
llvm::MemoryBuffer::getMemBufferCopy(guard(R"cpp(
#include "inner.h"
)cpp")));
ExtraFS->addSymbolicLink("header.h", "content_for/0",
/*ModificationTime=*/{});
ExtraFS->addFile("content_for/1", /*ModificationTime=*/{},
llvm::MemoryBuffer::getMemBufferCopy(guard(R"cpp(
void foo();
)cpp")));
ExtraFS->addSymbolicLink("inner.h", "content_for/1",
/*ModificationTime=*/{});

TestAST AST(Inputs);
std::vector<Decl *> DeclsInTU;
for (auto *D : AST.context().getTranslationUnitDecl()->decls())
DeclsInTU.push_back(D);
auto Results = analyze(DeclsInTU, {}, PP.Includes, &PI, AST.preprocessor());
// Check that we're spelling header using the symlink, and not underlying
// path.
EXPECT_THAT(Results.Missing, testing::ElementsAre("\"inner.h\""));
// header.h should be unused.
EXPECT_THAT(Results.Unused, Not(testing::IsEmpty()));

{
// Make sure filtering is also applied to symlink, not underlying file.
auto HeaderFilter = [](llvm::StringRef Path) { return Path == "inner.h"; };
Results = analyze(DeclsInTU, {}, PP.Includes, &PI, AST.preprocessor(),
HeaderFilter);
EXPECT_THAT(Results.Missing, testing::ElementsAre("\"inner.h\""));
// header.h should be unused.
EXPECT_THAT(Results.Unused, Not(testing::IsEmpty()));
}
{
auto HeaderFilter = [](llvm::StringRef Path) { return Path == "header.h"; };
Results = analyze(DeclsInTU, {}, PP.Includes, &PI, AST.preprocessor(),
HeaderFilter);
// header.h should be ignored now.
EXPECT_THAT(Results.Unused, Not(testing::IsEmpty()));
EXPECT_THAT(Results.Missing, testing::ElementsAre("\"inner.h\""));
}
}

TEST(FixIncludes, Basic) {
llvm::StringRef Code = R"cpp(#include "d.h"
#include "a.h"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,7 @@ class DummyIncludeSpeller : public IncludeSpeller {
return "<bits/stdc++.h>";
if (Input.H.kind() != Header::Physical)
return "";
llvm::StringRef AbsolutePath =
Input.H.physical().getFileEntry().tryGetRealPathName();
llvm::StringRef AbsolutePath = Input.H.resolvedPath();
std::string RootWithSeparator{testRoot()};
RootWithSeparator += llvm::sys::path::get_separator();
if (!AbsolutePath.consume_front(llvm::StringRef{RootWithSeparator}))
Expand Down
48 changes: 35 additions & 13 deletions clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
#include "clang-include-cleaner/Types.h"
#include "clang/AST/Decl.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/FileEntry.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Frontend/CompilerInvocation.h"
Expand All @@ -24,6 +25,7 @@
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/VirtualFileSystem.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Testing/Annotations/Annotations.h"
Expand Down Expand Up @@ -53,9 +55,11 @@ MATCHER_P(named, N, "") {
}

MATCHER_P(FileNamed, N, "") {
if (arg.getFileEntry().tryGetRealPathName() == N)
llvm::StringRef ActualName =
llvm::sys::path::remove_leading_dotslash(arg.getName());
if (ActualName == N)
return true;
*result_listener << arg.getFileEntry().tryGetRealPathName().str();
*result_listener << ActualName.str();
return false;
}

Expand Down Expand Up @@ -317,7 +321,8 @@ class PragmaIncludeTest : public ::testing::Test {
}

TestAST build(bool ResetPragmaIncludes = true) {
if (ResetPragmaIncludes) PI = PragmaIncludes();
if (ResetPragmaIncludes)
PI = PragmaIncludes();
return TestAST(Inputs);
}

Expand Down Expand Up @@ -535,16 +540,33 @@ TEST_F(PragmaIncludeTest, IWYUExportBlock) {
TestAST Processed = build();
auto &FM = Processed.fileManager();

EXPECT_THAT(PI.getExporters(FM.getFile("private1.h").get(), FM),
testing::UnorderedElementsAre(FileNamed("export1.h"),
FileNamed("normal.h")));
EXPECT_THAT(PI.getExporters(FM.getFile("private2.h").get(), FM),
testing::UnorderedElementsAre(FileNamed("export1.h")));
EXPECT_THAT(PI.getExporters(FM.getFile("private3.h").get(), FM),
testing::UnorderedElementsAre(FileNamed("export1.h")));

EXPECT_TRUE(PI.getExporters(FM.getFile("foo.h").get(), FM).empty());
EXPECT_TRUE(PI.getExporters(FM.getFile("bar.h").get(), FM).empty());
auto GetNames = [](llvm::ArrayRef<FileEntryRef> FEs) {
std::string Result;
llvm::raw_string_ostream OS(Result);
for (auto &FE : FEs) {
OS << FE.getName() << " ";
}
OS.flush();
return Result;
};
auto Exporters = PI.getExporters(FM.getFile("private1.h").get(), FM);
EXPECT_THAT(Exporters, testing::UnorderedElementsAre(FileNamed("export1.h"),
FileNamed("normal.h")))
<< GetNames(Exporters);

Exporters = PI.getExporters(FM.getFile("private2.h").get(), FM);
EXPECT_THAT(Exporters, testing::UnorderedElementsAre(FileNamed("export1.h")))
<< GetNames(Exporters);

Exporters = PI.getExporters(FM.getFile("private3.h").get(), FM);
EXPECT_THAT(Exporters, testing::UnorderedElementsAre(FileNamed("export1.h")))
<< GetNames(Exporters);

Exporters = PI.getExporters(FM.getFile("foo.h").get(), FM);
EXPECT_TRUE(Exporters.empty()) << GetNames(Exporters);

Exporters = PI.getExporters(FM.getFile("bar.h").get(), FM);
EXPECT_TRUE(Exporters.empty()) << GetNames(Exporters);
}

TEST_F(PragmaIncludeTest, SelfContained) {
Expand Down
12 changes: 12 additions & 0 deletions clang/docs/APINotes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,18 @@ declaration kind), all of which are optional:
- Name: tzdb
SwiftCopyable: false

:SwiftConformsTo:

Allows annotating a C++ class as conforming to a Swift protocol. Equivalent
to ``SWIFT_CONFORMS_TO_PROTOCOL``. The value is a module-qualified name of a
Swift protocol.

::

Tags:
- Name: vector
SwiftConformsTo: Cxx.CxxSequence

:Availability, AvailabilityMsg:

A value of "nonswift" is equivalent to ``NS_SWIFT_UNAVAILABLE``. A value of
Expand Down
Loading
Loading