[clang-tools-extra] [clang-doc] add ftime profiling (PR #97644)
https://github.com/PeterChou1 updated https://github.com/llvm/llvm-project/pull/97644 >From ff278188403a6f89e8c13f7a2330d978f31b1ab5 Mon Sep 17 00:00:00 2001 From: PeterChou1 Date: Wed, 3 Jul 2024 15:42:22 -0400 Subject: [PATCH 1/4] [clang-doc] add ftime trace option --- clang-tools-extra/clang-doc/BitcodeReader.cpp | 8 clang-tools-extra/clang-doc/Mapper.cpp| 11 - .../clang-doc/Representation.cpp | 2 + clang-tools-extra/clang-doc/Representation.h | 5 +- .../clang-doc/tool/ClangDocMain.cpp | 47 ++- 5 files changed, 69 insertions(+), 4 deletions(-) diff --git a/clang-tools-extra/clang-doc/BitcodeReader.cpp b/clang-tools-extra/clang-doc/BitcodeReader.cpp index bfb04e7407b38..975dbca3a2ce2 100644 --- a/clang-tools-extra/clang-doc/BitcodeReader.cpp +++ b/clang-tools-extra/clang-doc/BitcodeReader.cpp @@ -10,6 +10,7 @@ #include "llvm/ADT/IndexedMap.h" #include "llvm/Support/Error.h" #include "llvm/Support/raw_ostream.h" +#include "llvm/Support/TimeProfiler.h" #include namespace clang { @@ -670,6 +671,7 @@ llvm::Error ClangDocBitcodeReader::readRecord(unsigned ID, T I) { template <> llvm::Error ClangDocBitcodeReader::readRecord(unsigned ID, Reference *I) { + llvm::TimeTraceScope("clang-doc", "readRecord Reference"); Record R; llvm::StringRef Blob; llvm::Expected MaybeRecID = Stream.readRecord(ID, R, &Blob); @@ -681,6 +683,7 @@ llvm::Error ClangDocBitcodeReader::readRecord(unsigned ID, Reference *I) { // Read a block of records into a single info. template llvm::Error ClangDocBitcodeReader::readBlock(unsigned ID, T I) { + llvm::TimeTraceScope("clang-doc", "readBlock"); if (llvm::Error Err = Stream.EnterSubBlock(ID)) return Err; @@ -711,6 +714,7 @@ llvm::Error ClangDocBitcodeReader::readBlock(unsigned ID, T I) { template llvm::Error ClangDocBitcodeReader::readSubBlock(unsigned ID, T I) { + llvm::TimeTraceScope("clang-doc", "readSubBlock"); switch (ID) { // Blocks can only have certain types of sub blocks. case BI_COMMENT_BLOCK_ID: { @@ -817,6 +821,7 @@ llvm::Error ClangDocBitcodeReader::readSubBlock(unsigned ID, T I) { ClangDocBitcodeReader::Cursor ClangDocBitcodeReader::skipUntilRecordOrBlock(unsigned &BlockOrRecordID) { + llvm::TimeTraceScope("clang-doc", "skipUntilRecordOrBlock"); BlockOrRecordID = 0; while (!Stream.AtEndOfStream()) { @@ -878,6 +883,7 @@ llvm::Error ClangDocBitcodeReader::validateStream() { } llvm::Error ClangDocBitcodeReader::readBlockInfoBlock() { + llvm::TimeTraceScope("clang-doc", "readBlockInfoBlock"); Expected> MaybeBlockInfo = Stream.ReadBlockInfoBlock(); if (!MaybeBlockInfo) @@ -894,6 +900,7 @@ llvm::Error ClangDocBitcodeReader::readBlockInfoBlock() { template llvm::Expected> ClangDocBitcodeReader::createInfo(unsigned ID) { + llvm::TimeTraceScope("clang-doc", "createInfo"); std::unique_ptr I = std::make_unique(); if (auto Err = readBlock(ID, static_cast(I.get( return std::move(Err); @@ -902,6 +909,7 @@ ClangDocBitcodeReader::createInfo(unsigned ID) { llvm::Expected> ClangDocBitcodeReader::readBlockToInfo(unsigned ID) { + llvm::TimeTraceScope("clang-doc", "readBlockToInfo"); switch (ID) { case BI_NAMESPACE_BLOCK_ID: return createInfo(ID); diff --git a/clang-tools-extra/clang-doc/Mapper.cpp b/clang-tools-extra/clang-doc/Mapper.cpp index bb8b7952980ac..a8875473649c1 100644 --- a/clang-tools-extra/clang-doc/Mapper.cpp +++ b/clang-tools-extra/clang-doc/Mapper.cpp @@ -13,11 +13,14 @@ #include "clang/Index/USRGeneration.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/Error.h" +#include "llvm/Support/TimeProfiler.h" namespace clang { namespace doc { void MapASTVisitor::HandleTranslationUnit(ASTContext &Context) { + if (CDCtx.FTimeTrace) +llvm::timeTraceProfilerInitialize(CDCtx.Granularity, "clang-doc"); TraverseDecl(Context.getTranslationUnitDecl()); } @@ -30,6 +33,7 @@ template bool MapASTVisitor::mapDecl(const T *D) { if (D->getParentFunctionOrMethod()) return true; + llvm::timeTraceProfilerBegin("clang-doc", "emit info"); llvm::SmallString<128> USR; // If there is an error generating a USR for the decl, skip this decl. if (index::generateUSRForDecl(D, USR)) @@ -40,7 +44,9 @@ template bool MapASTVisitor::mapDecl(const T *D) { auto I = serialize::emitInfo(D, getComment(D, D->getASTContext()), getLine(D, D->getASTContext()), File, IsFileInRootDir, CDCtx.PublicOnly); + llvm::timeTraceProfilerEnd(); + llvm::timeTraceProfilerBegin("clang-doc", "serialize info"); // A null in place of I indicates that the serializer is skipping this decl // for some reason (e.g. we're only reporting public decls). if (I.first) @@ -49,6 +55,7 @@ template bool MapASTVisitor::mapDecl(const T *D) { if (I.second) CDCtx.ECtx->reportResult(llvm::toHex(llvm::toStringRef(I.second->USR)),
[clang-tools-extra] [clang-doc] add ftime profiling (PR #97644)
https://github.com/PeterChou1 updated https://github.com/llvm/llvm-project/pull/97644 >From ff278188403a6f89e8c13f7a2330d978f31b1ab5 Mon Sep 17 00:00:00 2001 From: PeterChou1 Date: Wed, 3 Jul 2024 15:42:22 -0400 Subject: [PATCH 1/5] [clang-doc] add ftime trace option --- clang-tools-extra/clang-doc/BitcodeReader.cpp | 8 clang-tools-extra/clang-doc/Mapper.cpp| 11 - .../clang-doc/Representation.cpp | 2 + clang-tools-extra/clang-doc/Representation.h | 5 +- .../clang-doc/tool/ClangDocMain.cpp | 47 ++- 5 files changed, 69 insertions(+), 4 deletions(-) diff --git a/clang-tools-extra/clang-doc/BitcodeReader.cpp b/clang-tools-extra/clang-doc/BitcodeReader.cpp index bfb04e7407b38..975dbca3a2ce2 100644 --- a/clang-tools-extra/clang-doc/BitcodeReader.cpp +++ b/clang-tools-extra/clang-doc/BitcodeReader.cpp @@ -10,6 +10,7 @@ #include "llvm/ADT/IndexedMap.h" #include "llvm/Support/Error.h" #include "llvm/Support/raw_ostream.h" +#include "llvm/Support/TimeProfiler.h" #include namespace clang { @@ -670,6 +671,7 @@ llvm::Error ClangDocBitcodeReader::readRecord(unsigned ID, T I) { template <> llvm::Error ClangDocBitcodeReader::readRecord(unsigned ID, Reference *I) { + llvm::TimeTraceScope("clang-doc", "readRecord Reference"); Record R; llvm::StringRef Blob; llvm::Expected MaybeRecID = Stream.readRecord(ID, R, &Blob); @@ -681,6 +683,7 @@ llvm::Error ClangDocBitcodeReader::readRecord(unsigned ID, Reference *I) { // Read a block of records into a single info. template llvm::Error ClangDocBitcodeReader::readBlock(unsigned ID, T I) { + llvm::TimeTraceScope("clang-doc", "readBlock"); if (llvm::Error Err = Stream.EnterSubBlock(ID)) return Err; @@ -711,6 +714,7 @@ llvm::Error ClangDocBitcodeReader::readBlock(unsigned ID, T I) { template llvm::Error ClangDocBitcodeReader::readSubBlock(unsigned ID, T I) { + llvm::TimeTraceScope("clang-doc", "readSubBlock"); switch (ID) { // Blocks can only have certain types of sub blocks. case BI_COMMENT_BLOCK_ID: { @@ -817,6 +821,7 @@ llvm::Error ClangDocBitcodeReader::readSubBlock(unsigned ID, T I) { ClangDocBitcodeReader::Cursor ClangDocBitcodeReader::skipUntilRecordOrBlock(unsigned &BlockOrRecordID) { + llvm::TimeTraceScope("clang-doc", "skipUntilRecordOrBlock"); BlockOrRecordID = 0; while (!Stream.AtEndOfStream()) { @@ -878,6 +883,7 @@ llvm::Error ClangDocBitcodeReader::validateStream() { } llvm::Error ClangDocBitcodeReader::readBlockInfoBlock() { + llvm::TimeTraceScope("clang-doc", "readBlockInfoBlock"); Expected> MaybeBlockInfo = Stream.ReadBlockInfoBlock(); if (!MaybeBlockInfo) @@ -894,6 +900,7 @@ llvm::Error ClangDocBitcodeReader::readBlockInfoBlock() { template llvm::Expected> ClangDocBitcodeReader::createInfo(unsigned ID) { + llvm::TimeTraceScope("clang-doc", "createInfo"); std::unique_ptr I = std::make_unique(); if (auto Err = readBlock(ID, static_cast(I.get( return std::move(Err); @@ -902,6 +909,7 @@ ClangDocBitcodeReader::createInfo(unsigned ID) { llvm::Expected> ClangDocBitcodeReader::readBlockToInfo(unsigned ID) { + llvm::TimeTraceScope("clang-doc", "readBlockToInfo"); switch (ID) { case BI_NAMESPACE_BLOCK_ID: return createInfo(ID); diff --git a/clang-tools-extra/clang-doc/Mapper.cpp b/clang-tools-extra/clang-doc/Mapper.cpp index bb8b7952980ac..a8875473649c1 100644 --- a/clang-tools-extra/clang-doc/Mapper.cpp +++ b/clang-tools-extra/clang-doc/Mapper.cpp @@ -13,11 +13,14 @@ #include "clang/Index/USRGeneration.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/Error.h" +#include "llvm/Support/TimeProfiler.h" namespace clang { namespace doc { void MapASTVisitor::HandleTranslationUnit(ASTContext &Context) { + if (CDCtx.FTimeTrace) +llvm::timeTraceProfilerInitialize(CDCtx.Granularity, "clang-doc"); TraverseDecl(Context.getTranslationUnitDecl()); } @@ -30,6 +33,7 @@ template bool MapASTVisitor::mapDecl(const T *D) { if (D->getParentFunctionOrMethod()) return true; + llvm::timeTraceProfilerBegin("clang-doc", "emit info"); llvm::SmallString<128> USR; // If there is an error generating a USR for the decl, skip this decl. if (index::generateUSRForDecl(D, USR)) @@ -40,7 +44,9 @@ template bool MapASTVisitor::mapDecl(const T *D) { auto I = serialize::emitInfo(D, getComment(D, D->getASTContext()), getLine(D, D->getASTContext()), File, IsFileInRootDir, CDCtx.PublicOnly); + llvm::timeTraceProfilerEnd(); + llvm::timeTraceProfilerBegin("clang-doc", "serialize info"); // A null in place of I indicates that the serializer is skipping this decl // for some reason (e.g. we're only reporting public decls). if (I.first) @@ -49,6 +55,7 @@ template bool MapASTVisitor::mapDecl(const T *D) { if (I.second) CDCtx.ECtx->reportResult(llvm::toHex(llvm::toStringRef(I.second->USR)),
[clang-tools-extra] [clang-doc] add ftime profiling (PR #97644)
https://github.com/PeterChou1 updated https://github.com/llvm/llvm-project/pull/97644 >From 991340e3df02bf48e7952b520ae96f5fbc806393 Mon Sep 17 00:00:00 2001 From: PeterChou1 Date: Thu, 4 Jul 2024 03:28:34 -0400 Subject: [PATCH] [clang-doc] add ftime trace --- clang-tools-extra/clang-doc/BitcodeReader.cpp | 8 +++ clang-tools-extra/clang-doc/Mapper.cpp| 9 +++ .../clang-doc/Representation.cpp | 2 + clang-tools-extra/clang-doc/Representation.h | 5 +- .../clang-doc/tool/ClangDocMain.cpp | 56 +-- 5 files changed, 74 insertions(+), 6 deletions(-) diff --git a/clang-tools-extra/clang-doc/BitcodeReader.cpp b/clang-tools-extra/clang-doc/BitcodeReader.cpp index bfb04e7407b38..eef8c1b6e7f0a 100644 --- a/clang-tools-extra/clang-doc/BitcodeReader.cpp +++ b/clang-tools-extra/clang-doc/BitcodeReader.cpp @@ -9,6 +9,7 @@ #include "BitcodeReader.h" #include "llvm/ADT/IndexedMap.h" #include "llvm/Support/Error.h" +#include "llvm/Support/TimeProfiler.h" #include "llvm/Support/raw_ostream.h" #include @@ -670,6 +671,7 @@ llvm::Error ClangDocBitcodeReader::readRecord(unsigned ID, T I) { template <> llvm::Error ClangDocBitcodeReader::readRecord(unsigned ID, Reference *I) { + llvm::TimeTraceScope("clang-doc", "readRecord Reference"); Record R; llvm::StringRef Blob; llvm::Expected MaybeRecID = Stream.readRecord(ID, R, &Blob); @@ -681,6 +683,7 @@ llvm::Error ClangDocBitcodeReader::readRecord(unsigned ID, Reference *I) { // Read a block of records into a single info. template llvm::Error ClangDocBitcodeReader::readBlock(unsigned ID, T I) { + llvm::TimeTraceScope("readBlock", "ClangDocBitcodeReader"); if (llvm::Error Err = Stream.EnterSubBlock(ID)) return Err; @@ -711,6 +714,7 @@ llvm::Error ClangDocBitcodeReader::readBlock(unsigned ID, T I) { template llvm::Error ClangDocBitcodeReader::readSubBlock(unsigned ID, T I) { + llvm::TimeTraceScope("readSubBlock", "ClangDocBitcodeReader"); switch (ID) { // Blocks can only have certain types of sub blocks. case BI_COMMENT_BLOCK_ID: { @@ -817,6 +821,7 @@ llvm::Error ClangDocBitcodeReader::readSubBlock(unsigned ID, T I) { ClangDocBitcodeReader::Cursor ClangDocBitcodeReader::skipUntilRecordOrBlock(unsigned &BlockOrRecordID) { + llvm::TimeTraceScope("skipUntilRecordOrBlock", "ClangDocBitcodeReader"); BlockOrRecordID = 0; while (!Stream.AtEndOfStream()) { @@ -878,6 +883,7 @@ llvm::Error ClangDocBitcodeReader::validateStream() { } llvm::Error ClangDocBitcodeReader::readBlockInfoBlock() { + llvm::TimeTraceScope("readBlockInfoBlock", "ClangDocBitcodeReader"); Expected> MaybeBlockInfo = Stream.ReadBlockInfoBlock(); if (!MaybeBlockInfo) @@ -894,6 +900,7 @@ llvm::Error ClangDocBitcodeReader::readBlockInfoBlock() { template llvm::Expected> ClangDocBitcodeReader::createInfo(unsigned ID) { + llvm::TimeTraceScope("createInfo", "ClangDocBitcodeReader"); std::unique_ptr I = std::make_unique(); if (auto Err = readBlock(ID, static_cast(I.get( return std::move(Err); @@ -902,6 +909,7 @@ ClangDocBitcodeReader::createInfo(unsigned ID) { llvm::Expected> ClangDocBitcodeReader::readBlockToInfo(unsigned ID) { + llvm::TimeTraceScope("readBlockToInfo", "ClangDocBitcodeReader"); switch (ID) { case BI_NAMESPACE_BLOCK_ID: return createInfo(ID); diff --git a/clang-tools-extra/clang-doc/Mapper.cpp b/clang-tools-extra/clang-doc/Mapper.cpp index bb8b7952980ac..4a9e8721c9ff4 100644 --- a/clang-tools-extra/clang-doc/Mapper.cpp +++ b/clang-tools-extra/clang-doc/Mapper.cpp @@ -13,12 +13,17 @@ #include "clang/Index/USRGeneration.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/Error.h" +#include "llvm/Support/TimeProfiler.h" namespace clang { namespace doc { void MapASTVisitor::HandleTranslationUnit(ASTContext &Context) { + if (CDCtx.FTimeTrace) +llvm::timeTraceProfilerInitialize(CDCtx.Granularity, "clang-doc"); TraverseDecl(Context.getTranslationUnitDecl()); + if (CDCtx.FTimeTrace) +llvm::timeTraceProfilerFinishThread(); } template bool MapASTVisitor::mapDecl(const T *D) { @@ -30,6 +35,7 @@ template bool MapASTVisitor::mapDecl(const T *D) { if (D->getParentFunctionOrMethod()) return true; + llvm::timeTraceProfilerBegin("emit info phase", "emit info"); llvm::SmallString<128> USR; // If there is an error generating a USR for the decl, skip this decl. if (index::generateUSRForDecl(D, USR)) @@ -40,7 +46,9 @@ template bool MapASTVisitor::mapDecl(const T *D) { auto I = serialize::emitInfo(D, getComment(D, D->getASTContext()), getLine(D, D->getASTContext()), File, IsFileInRootDir, CDCtx.PublicOnly); + llvm::timeTraceProfilerEnd(); + llvm::timeTraceProfilerBegin("serializing info", "serializing"); // A null in place of I indicates that the serializer is skipping this decl // for some reason (e.g. we're only reportin
[clang-tools-extra] [llvm] [clang-doc] fix bug introduced by asset test (PR #97540)
https://github.com/PeterChou1 updated https://github.com/llvm/llvm-project/pull/97540 >From b8dd4f6f2005d2e08ae13023905d0f36edd6348b Mon Sep 17 00:00:00 2001 From: PeterChou1 Date: Wed, 3 Jul 2024 04:42:33 -0400 Subject: [PATCH 1/9] [clang-doc] fix path bug introduced by asset test --- clang-tools-extra/clang-doc/tool/CMakeLists.txt | 8 ++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/clang-tools-extra/clang-doc/tool/CMakeLists.txt b/clang-tools-extra/clang-doc/tool/CMakeLists.txt index e93a5728d6b6b..3fd41f187a617 100644 --- a/clang-tools-extra/clang-doc/tool/CMakeLists.txt +++ b/clang-tools-extra/clang-doc/tool/CMakeLists.txt @@ -25,7 +25,11 @@ set(assets ) set(asset_dir "${CMAKE_CURRENT_SOURCE_DIR}/../assets") -set(resource_dir "${CMAKE_BINARY_DIR}/share/clang-doc") +if(MSVC) + set(resource_dir "${CMAKE_BINARY_DIR}/$/share/clang-doc") +else() + set(resource_dir "${CMAKE_BINARY_DIR}/share/clang-doc") +endif() set(out_files) function(copy_files_to_dst src_dir dst_dir file) @@ -52,4 +56,4 @@ add_custom_target(copy-clang-doc-assets COMMENT "Copying Clang-Doc Assets" ) set_target_properties(copy-clang-doc-assets PROPERTIES FOLDER "Clang-Doc/Assets") -add_dependencies(clang-doc copy-clang-doc-assets) +add_dependencies(clang-doc copy-clang-doc-assets) \ No newline at end of file >From cf993cfeeab18be6aa434e159fb625456183d4da Mon Sep 17 00:00:00 2001 From: PeterChou1 Date: Wed, 3 Jul 2024 13:49:26 -0400 Subject: [PATCH 2/9] [clang-doc] modify cmake file to fix asset install path --- clang-tools-extra/clang-doc/tool/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clang-tools-extra/clang-doc/tool/CMakeLists.txt b/clang-tools-extra/clang-doc/tool/CMakeLists.txt index 3fd41f187a617..ddaf8cd4cdbd6 100644 --- a/clang-tools-extra/clang-doc/tool/CMakeLists.txt +++ b/clang-tools-extra/clang-doc/tool/CMakeLists.txt @@ -25,7 +25,7 @@ set(assets ) set(asset_dir "${CMAKE_CURRENT_SOURCE_DIR}/../assets") -if(MSVC) +if("${CMAKE_GENERATOR}" MATCHES "Visual Studio") set(resource_dir "${CMAKE_BINARY_DIR}/$/share/clang-doc") else() set(resource_dir "${CMAKE_BINARY_DIR}/share/clang-doc") >From e389b78848127be9753797d355d196c03e3974fd Mon Sep 17 00:00:00 2001 From: PeterChou1 Date: Wed, 3 Jul 2024 14:14:56 -0400 Subject: [PATCH 3/9] [clang-doc] fix nit --- clang-tools-extra/clang-doc/tool/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clang-tools-extra/clang-doc/tool/CMakeLists.txt b/clang-tools-extra/clang-doc/tool/CMakeLists.txt index ddaf8cd4cdbd6..aaf3c3b8734c8 100644 --- a/clang-tools-extra/clang-doc/tool/CMakeLists.txt +++ b/clang-tools-extra/clang-doc/tool/CMakeLists.txt @@ -56,4 +56,4 @@ add_custom_target(copy-clang-doc-assets COMMENT "Copying Clang-Doc Assets" ) set_target_properties(copy-clang-doc-assets PROPERTIES FOLDER "Clang-Doc/Assets") -add_dependencies(clang-doc copy-clang-doc-assets) \ No newline at end of file +add_dependencies(clang-doc copy-clang-doc-assets) >From 4733341a26ef3b6faa1a00d2e53b0033de440eb7 Mon Sep 17 00:00:00 2001 From: PeterChou1 Date: Wed, 3 Jul 2024 16:04:37 -0400 Subject: [PATCH 4/9] [llvm] modify cmake list to add shared directory --- clang-tools-extra/clang-doc/tool/CMakeLists.txt | 7 +-- llvm/CMakeLists.txt | 6 ++ 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/clang-tools-extra/clang-doc/tool/CMakeLists.txt b/clang-tools-extra/clang-doc/tool/CMakeLists.txt index aaf3c3b8734c8..c908cac9ce2a5 100644 --- a/clang-tools-extra/clang-doc/tool/CMakeLists.txt +++ b/clang-tools-extra/clang-doc/tool/CMakeLists.txt @@ -25,11 +25,6 @@ set(assets ) set(asset_dir "${CMAKE_CURRENT_SOURCE_DIR}/../assets") -if("${CMAKE_GENERATOR}" MATCHES "Visual Studio") - set(resource_dir "${CMAKE_BINARY_DIR}/$/share/clang-doc") -else() - set(resource_dir "${CMAKE_BINARY_DIR}/share/clang-doc") -endif() set(out_files) function(copy_files_to_dst src_dir dst_dir file) @@ -48,7 +43,7 @@ foreach(f ${assets}) install(FILES ${asset_dir}/${f} DESTINATION "${CMAKE_INSTALL_DATADIR}/clang-doc" COMPONENT clang-doc) - copy_files_to_dst(${asset_dir} ${resource_dir} ${f}) + copy_files_to_dst(${asset_dir} ${LLVM_SHARE_DIR} ${f}) endforeach(f) add_custom_target(copy-clang-doc-assets diff --git a/llvm/CMakeLists.txt b/llvm/CMakeLists.txt index 91a2b6181ce0a..0c02498aa6fce 100644 --- a/llvm/CMakeLists.txt +++ b/llvm/CMakeLists.txt @@ -452,6 +452,12 @@ if(WIN32 OR CYGWIN) else() set(LLVM_SHLIB_OUTPUT_INTDIR ${LLVM_LIBRARY_OUTPUT_INTDIR}) endif() +# set shared directory +if(CMAKE_GENERATOR MATCHES "Visual Studio") + set(LLVM_SHARE_DIR "${CMAKE_BINARY_DIR}/$/share") +else() + set(LLVM_SHARE_DIR "${CMAKE_BINARY_DIR}/share") +endif() # Each of them corresponds to llvm-config's. set(LLVM_TOOLS_BINARY_DIR ${LLVM_RUNTIME_OUTPUT_INTDIR}) # --bindir >From 3433bfecffe25077fc1749be6c30512e2e47eadb Mon Sep 17 00:00
[clang-tools-extra] [clang-doc] add ftime profiling (PR #97644)
https://github.com/PeterChou1 updated https://github.com/llvm/llvm-project/pull/97644 >From 991340e3df02bf48e7952b520ae96f5fbc806393 Mon Sep 17 00:00:00 2001 From: PeterChou1 Date: Thu, 4 Jul 2024 03:28:34 -0400 Subject: [PATCH 1/2] [clang-doc] add ftime trace --- clang-tools-extra/clang-doc/BitcodeReader.cpp | 8 +++ clang-tools-extra/clang-doc/Mapper.cpp| 9 +++ .../clang-doc/Representation.cpp | 2 + clang-tools-extra/clang-doc/Representation.h | 5 +- .../clang-doc/tool/ClangDocMain.cpp | 56 +-- 5 files changed, 74 insertions(+), 6 deletions(-) diff --git a/clang-tools-extra/clang-doc/BitcodeReader.cpp b/clang-tools-extra/clang-doc/BitcodeReader.cpp index bfb04e7407b38..eef8c1b6e7f0a 100644 --- a/clang-tools-extra/clang-doc/BitcodeReader.cpp +++ b/clang-tools-extra/clang-doc/BitcodeReader.cpp @@ -9,6 +9,7 @@ #include "BitcodeReader.h" #include "llvm/ADT/IndexedMap.h" #include "llvm/Support/Error.h" +#include "llvm/Support/TimeProfiler.h" #include "llvm/Support/raw_ostream.h" #include @@ -670,6 +671,7 @@ llvm::Error ClangDocBitcodeReader::readRecord(unsigned ID, T I) { template <> llvm::Error ClangDocBitcodeReader::readRecord(unsigned ID, Reference *I) { + llvm::TimeTraceScope("clang-doc", "readRecord Reference"); Record R; llvm::StringRef Blob; llvm::Expected MaybeRecID = Stream.readRecord(ID, R, &Blob); @@ -681,6 +683,7 @@ llvm::Error ClangDocBitcodeReader::readRecord(unsigned ID, Reference *I) { // Read a block of records into a single info. template llvm::Error ClangDocBitcodeReader::readBlock(unsigned ID, T I) { + llvm::TimeTraceScope("readBlock", "ClangDocBitcodeReader"); if (llvm::Error Err = Stream.EnterSubBlock(ID)) return Err; @@ -711,6 +714,7 @@ llvm::Error ClangDocBitcodeReader::readBlock(unsigned ID, T I) { template llvm::Error ClangDocBitcodeReader::readSubBlock(unsigned ID, T I) { + llvm::TimeTraceScope("readSubBlock", "ClangDocBitcodeReader"); switch (ID) { // Blocks can only have certain types of sub blocks. case BI_COMMENT_BLOCK_ID: { @@ -817,6 +821,7 @@ llvm::Error ClangDocBitcodeReader::readSubBlock(unsigned ID, T I) { ClangDocBitcodeReader::Cursor ClangDocBitcodeReader::skipUntilRecordOrBlock(unsigned &BlockOrRecordID) { + llvm::TimeTraceScope("skipUntilRecordOrBlock", "ClangDocBitcodeReader"); BlockOrRecordID = 0; while (!Stream.AtEndOfStream()) { @@ -878,6 +883,7 @@ llvm::Error ClangDocBitcodeReader::validateStream() { } llvm::Error ClangDocBitcodeReader::readBlockInfoBlock() { + llvm::TimeTraceScope("readBlockInfoBlock", "ClangDocBitcodeReader"); Expected> MaybeBlockInfo = Stream.ReadBlockInfoBlock(); if (!MaybeBlockInfo) @@ -894,6 +900,7 @@ llvm::Error ClangDocBitcodeReader::readBlockInfoBlock() { template llvm::Expected> ClangDocBitcodeReader::createInfo(unsigned ID) { + llvm::TimeTraceScope("createInfo", "ClangDocBitcodeReader"); std::unique_ptr I = std::make_unique(); if (auto Err = readBlock(ID, static_cast(I.get( return std::move(Err); @@ -902,6 +909,7 @@ ClangDocBitcodeReader::createInfo(unsigned ID) { llvm::Expected> ClangDocBitcodeReader::readBlockToInfo(unsigned ID) { + llvm::TimeTraceScope("readBlockToInfo", "ClangDocBitcodeReader"); switch (ID) { case BI_NAMESPACE_BLOCK_ID: return createInfo(ID); diff --git a/clang-tools-extra/clang-doc/Mapper.cpp b/clang-tools-extra/clang-doc/Mapper.cpp index bb8b7952980ac..4a9e8721c9ff4 100644 --- a/clang-tools-extra/clang-doc/Mapper.cpp +++ b/clang-tools-extra/clang-doc/Mapper.cpp @@ -13,12 +13,17 @@ #include "clang/Index/USRGeneration.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/Error.h" +#include "llvm/Support/TimeProfiler.h" namespace clang { namespace doc { void MapASTVisitor::HandleTranslationUnit(ASTContext &Context) { + if (CDCtx.FTimeTrace) +llvm::timeTraceProfilerInitialize(CDCtx.Granularity, "clang-doc"); TraverseDecl(Context.getTranslationUnitDecl()); + if (CDCtx.FTimeTrace) +llvm::timeTraceProfilerFinishThread(); } template bool MapASTVisitor::mapDecl(const T *D) { @@ -30,6 +35,7 @@ template bool MapASTVisitor::mapDecl(const T *D) { if (D->getParentFunctionOrMethod()) return true; + llvm::timeTraceProfilerBegin("emit info phase", "emit info"); llvm::SmallString<128> USR; // If there is an error generating a USR for the decl, skip this decl. if (index::generateUSRForDecl(D, USR)) @@ -40,7 +46,9 @@ template bool MapASTVisitor::mapDecl(const T *D) { auto I = serialize::emitInfo(D, getComment(D, D->getASTContext()), getLine(D, D->getASTContext()), File, IsFileInRootDir, CDCtx.PublicOnly); + llvm::timeTraceProfilerEnd(); + llvm::timeTraceProfilerBegin("serializing info", "serializing"); // A null in place of I indicates that the serializer is skipping this decl // for some reason (e.g. we're only repo
[clang-tools-extra] [clang-doc] add ftime profiling (PR #97644)
https://github.com/PeterChou1 updated https://github.com/llvm/llvm-project/pull/97644 >From cbb9d73b4827206ea7f5da58cc4a765a9297d620 Mon Sep 17 00:00:00 2001 From: PeterChou1 Date: Thu, 4 Jul 2024 03:39:22 -0400 Subject: [PATCH] [clang-doc] add ftime trace --- clang-tools-extra/clang-doc/BitcodeReader.cpp | 8 +++ clang-tools-extra/clang-doc/Mapper.cpp| 9 .../clang-doc/Representation.cpp | 2 + clang-tools-extra/clang-doc/Representation.h | 5 +- .../clang-doc/tool/ClangDocMain.cpp | 54 +-- 5 files changed, 72 insertions(+), 6 deletions(-) diff --git a/clang-tools-extra/clang-doc/BitcodeReader.cpp b/clang-tools-extra/clang-doc/BitcodeReader.cpp index bfb04e7407b38..eef8c1b6e7f0a 100644 --- a/clang-tools-extra/clang-doc/BitcodeReader.cpp +++ b/clang-tools-extra/clang-doc/BitcodeReader.cpp @@ -9,6 +9,7 @@ #include "BitcodeReader.h" #include "llvm/ADT/IndexedMap.h" #include "llvm/Support/Error.h" +#include "llvm/Support/TimeProfiler.h" #include "llvm/Support/raw_ostream.h" #include @@ -670,6 +671,7 @@ llvm::Error ClangDocBitcodeReader::readRecord(unsigned ID, T I) { template <> llvm::Error ClangDocBitcodeReader::readRecord(unsigned ID, Reference *I) { + llvm::TimeTraceScope("clang-doc", "readRecord Reference"); Record R; llvm::StringRef Blob; llvm::Expected MaybeRecID = Stream.readRecord(ID, R, &Blob); @@ -681,6 +683,7 @@ llvm::Error ClangDocBitcodeReader::readRecord(unsigned ID, Reference *I) { // Read a block of records into a single info. template llvm::Error ClangDocBitcodeReader::readBlock(unsigned ID, T I) { + llvm::TimeTraceScope("readBlock", "ClangDocBitcodeReader"); if (llvm::Error Err = Stream.EnterSubBlock(ID)) return Err; @@ -711,6 +714,7 @@ llvm::Error ClangDocBitcodeReader::readBlock(unsigned ID, T I) { template llvm::Error ClangDocBitcodeReader::readSubBlock(unsigned ID, T I) { + llvm::TimeTraceScope("readSubBlock", "ClangDocBitcodeReader"); switch (ID) { // Blocks can only have certain types of sub blocks. case BI_COMMENT_BLOCK_ID: { @@ -817,6 +821,7 @@ llvm::Error ClangDocBitcodeReader::readSubBlock(unsigned ID, T I) { ClangDocBitcodeReader::Cursor ClangDocBitcodeReader::skipUntilRecordOrBlock(unsigned &BlockOrRecordID) { + llvm::TimeTraceScope("skipUntilRecordOrBlock", "ClangDocBitcodeReader"); BlockOrRecordID = 0; while (!Stream.AtEndOfStream()) { @@ -878,6 +883,7 @@ llvm::Error ClangDocBitcodeReader::validateStream() { } llvm::Error ClangDocBitcodeReader::readBlockInfoBlock() { + llvm::TimeTraceScope("readBlockInfoBlock", "ClangDocBitcodeReader"); Expected> MaybeBlockInfo = Stream.ReadBlockInfoBlock(); if (!MaybeBlockInfo) @@ -894,6 +900,7 @@ llvm::Error ClangDocBitcodeReader::readBlockInfoBlock() { template llvm::Expected> ClangDocBitcodeReader::createInfo(unsigned ID) { + llvm::TimeTraceScope("createInfo", "ClangDocBitcodeReader"); std::unique_ptr I = std::make_unique(); if (auto Err = readBlock(ID, static_cast(I.get( return std::move(Err); @@ -902,6 +909,7 @@ ClangDocBitcodeReader::createInfo(unsigned ID) { llvm::Expected> ClangDocBitcodeReader::readBlockToInfo(unsigned ID) { + llvm::TimeTraceScope("readBlockToInfo", "ClangDocBitcodeReader"); switch (ID) { case BI_NAMESPACE_BLOCK_ID: return createInfo(ID); diff --git a/clang-tools-extra/clang-doc/Mapper.cpp b/clang-tools-extra/clang-doc/Mapper.cpp index bb8b7952980ac..4a9e8721c9ff4 100644 --- a/clang-tools-extra/clang-doc/Mapper.cpp +++ b/clang-tools-extra/clang-doc/Mapper.cpp @@ -13,12 +13,17 @@ #include "clang/Index/USRGeneration.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/Error.h" +#include "llvm/Support/TimeProfiler.h" namespace clang { namespace doc { void MapASTVisitor::HandleTranslationUnit(ASTContext &Context) { + if (CDCtx.FTimeTrace) +llvm::timeTraceProfilerInitialize(CDCtx.Granularity, "clang-doc"); TraverseDecl(Context.getTranslationUnitDecl()); + if (CDCtx.FTimeTrace) +llvm::timeTraceProfilerFinishThread(); } template bool MapASTVisitor::mapDecl(const T *D) { @@ -30,6 +35,7 @@ template bool MapASTVisitor::mapDecl(const T *D) { if (D->getParentFunctionOrMethod()) return true; + llvm::timeTraceProfilerBegin("emit info phase", "emit info"); llvm::SmallString<128> USR; // If there is an error generating a USR for the decl, skip this decl. if (index::generateUSRForDecl(D, USR)) @@ -40,7 +46,9 @@ template bool MapASTVisitor::mapDecl(const T *D) { auto I = serialize::emitInfo(D, getComment(D, D->getASTContext()), getLine(D, D->getASTContext()), File, IsFileInRootDir, CDCtx.PublicOnly); + llvm::timeTraceProfilerEnd(); + llvm::timeTraceProfilerBegin("serializing info", "serializing"); // A null in place of I indicates that the serializer is skipping this decl // for some reason (e.g. we're only reporti
[clang] [llvm] [Inliner] Propagate more attributes to params when inlining (PR #91101)
goldsteinn wrote: ping https://github.com/llvm/llvm-project/pull/91101 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [llvm] [clang-doc] fix bug introduced by asset test (PR #97540)
https://github.com/PeterChou1 edited https://github.com/llvm/llvm-project/pull/97540 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-doc] add ftime profiling (PR #97644)
https://github.com/PeterChou1 updated https://github.com/llvm/llvm-project/pull/97644 >From cbb9d73b4827206ea7f5da58cc4a765a9297d620 Mon Sep 17 00:00:00 2001 From: PeterChou1 Date: Thu, 4 Jul 2024 03:39:22 -0400 Subject: [PATCH] [clang-doc] add ftime trace --- clang-tools-extra/clang-doc/BitcodeReader.cpp | 8 +++ clang-tools-extra/clang-doc/Mapper.cpp| 9 .../clang-doc/Representation.cpp | 2 + clang-tools-extra/clang-doc/Representation.h | 5 +- .../clang-doc/tool/ClangDocMain.cpp | 54 +-- 5 files changed, 72 insertions(+), 6 deletions(-) diff --git a/clang-tools-extra/clang-doc/BitcodeReader.cpp b/clang-tools-extra/clang-doc/BitcodeReader.cpp index bfb04e7407b380..eef8c1b6e7f0a7 100644 --- a/clang-tools-extra/clang-doc/BitcodeReader.cpp +++ b/clang-tools-extra/clang-doc/BitcodeReader.cpp @@ -9,6 +9,7 @@ #include "BitcodeReader.h" #include "llvm/ADT/IndexedMap.h" #include "llvm/Support/Error.h" +#include "llvm/Support/TimeProfiler.h" #include "llvm/Support/raw_ostream.h" #include @@ -670,6 +671,7 @@ llvm::Error ClangDocBitcodeReader::readRecord(unsigned ID, T I) { template <> llvm::Error ClangDocBitcodeReader::readRecord(unsigned ID, Reference *I) { + llvm::TimeTraceScope("clang-doc", "readRecord Reference"); Record R; llvm::StringRef Blob; llvm::Expected MaybeRecID = Stream.readRecord(ID, R, &Blob); @@ -681,6 +683,7 @@ llvm::Error ClangDocBitcodeReader::readRecord(unsigned ID, Reference *I) { // Read a block of records into a single info. template llvm::Error ClangDocBitcodeReader::readBlock(unsigned ID, T I) { + llvm::TimeTraceScope("readBlock", "ClangDocBitcodeReader"); if (llvm::Error Err = Stream.EnterSubBlock(ID)) return Err; @@ -711,6 +714,7 @@ llvm::Error ClangDocBitcodeReader::readBlock(unsigned ID, T I) { template llvm::Error ClangDocBitcodeReader::readSubBlock(unsigned ID, T I) { + llvm::TimeTraceScope("readSubBlock", "ClangDocBitcodeReader"); switch (ID) { // Blocks can only have certain types of sub blocks. case BI_COMMENT_BLOCK_ID: { @@ -817,6 +821,7 @@ llvm::Error ClangDocBitcodeReader::readSubBlock(unsigned ID, T I) { ClangDocBitcodeReader::Cursor ClangDocBitcodeReader::skipUntilRecordOrBlock(unsigned &BlockOrRecordID) { + llvm::TimeTraceScope("skipUntilRecordOrBlock", "ClangDocBitcodeReader"); BlockOrRecordID = 0; while (!Stream.AtEndOfStream()) { @@ -878,6 +883,7 @@ llvm::Error ClangDocBitcodeReader::validateStream() { } llvm::Error ClangDocBitcodeReader::readBlockInfoBlock() { + llvm::TimeTraceScope("readBlockInfoBlock", "ClangDocBitcodeReader"); Expected> MaybeBlockInfo = Stream.ReadBlockInfoBlock(); if (!MaybeBlockInfo) @@ -894,6 +900,7 @@ llvm::Error ClangDocBitcodeReader::readBlockInfoBlock() { template llvm::Expected> ClangDocBitcodeReader::createInfo(unsigned ID) { + llvm::TimeTraceScope("createInfo", "ClangDocBitcodeReader"); std::unique_ptr I = std::make_unique(); if (auto Err = readBlock(ID, static_cast(I.get( return std::move(Err); @@ -902,6 +909,7 @@ ClangDocBitcodeReader::createInfo(unsigned ID) { llvm::Expected> ClangDocBitcodeReader::readBlockToInfo(unsigned ID) { + llvm::TimeTraceScope("readBlockToInfo", "ClangDocBitcodeReader"); switch (ID) { case BI_NAMESPACE_BLOCK_ID: return createInfo(ID); diff --git a/clang-tools-extra/clang-doc/Mapper.cpp b/clang-tools-extra/clang-doc/Mapper.cpp index bb8b7952980ac6..4a9e8721c9ff47 100644 --- a/clang-tools-extra/clang-doc/Mapper.cpp +++ b/clang-tools-extra/clang-doc/Mapper.cpp @@ -13,12 +13,17 @@ #include "clang/Index/USRGeneration.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/Error.h" +#include "llvm/Support/TimeProfiler.h" namespace clang { namespace doc { void MapASTVisitor::HandleTranslationUnit(ASTContext &Context) { + if (CDCtx.FTimeTrace) +llvm::timeTraceProfilerInitialize(CDCtx.Granularity, "clang-doc"); TraverseDecl(Context.getTranslationUnitDecl()); + if (CDCtx.FTimeTrace) +llvm::timeTraceProfilerFinishThread(); } template bool MapASTVisitor::mapDecl(const T *D) { @@ -30,6 +35,7 @@ template bool MapASTVisitor::mapDecl(const T *D) { if (D->getParentFunctionOrMethod()) return true; + llvm::timeTraceProfilerBegin("emit info phase", "emit info"); llvm::SmallString<128> USR; // If there is an error generating a USR for the decl, skip this decl. if (index::generateUSRForDecl(D, USR)) @@ -40,7 +46,9 @@ template bool MapASTVisitor::mapDecl(const T *D) { auto I = serialize::emitInfo(D, getComment(D, D->getASTContext()), getLine(D, D->getASTContext()), File, IsFileInRootDir, CDCtx.PublicOnly); + llvm::timeTraceProfilerEnd(); + llvm::timeTraceProfilerBegin("serializing info", "serializing"); // A null in place of I indicates that the serializer is skipping this decl // for some reason (e.g. we're only rep
[clang-tools-extra] [clang-doc] add ftime profiling (PR #97644)
https://github.com/PeterChou1 updated https://github.com/llvm/llvm-project/pull/97644 >From cbb9d73b4827206ea7f5da58cc4a765a9297d620 Mon Sep 17 00:00:00 2001 From: PeterChou1 Date: Thu, 4 Jul 2024 03:39:22 -0400 Subject: [PATCH 1/2] [clang-doc] add ftime trace --- clang-tools-extra/clang-doc/BitcodeReader.cpp | 8 +++ clang-tools-extra/clang-doc/Mapper.cpp| 9 .../clang-doc/Representation.cpp | 2 + clang-tools-extra/clang-doc/Representation.h | 5 +- .../clang-doc/tool/ClangDocMain.cpp | 54 +-- 5 files changed, 72 insertions(+), 6 deletions(-) diff --git a/clang-tools-extra/clang-doc/BitcodeReader.cpp b/clang-tools-extra/clang-doc/BitcodeReader.cpp index bfb04e7407b38..eef8c1b6e7f0a 100644 --- a/clang-tools-extra/clang-doc/BitcodeReader.cpp +++ b/clang-tools-extra/clang-doc/BitcodeReader.cpp @@ -9,6 +9,7 @@ #include "BitcodeReader.h" #include "llvm/ADT/IndexedMap.h" #include "llvm/Support/Error.h" +#include "llvm/Support/TimeProfiler.h" #include "llvm/Support/raw_ostream.h" #include @@ -670,6 +671,7 @@ llvm::Error ClangDocBitcodeReader::readRecord(unsigned ID, T I) { template <> llvm::Error ClangDocBitcodeReader::readRecord(unsigned ID, Reference *I) { + llvm::TimeTraceScope("clang-doc", "readRecord Reference"); Record R; llvm::StringRef Blob; llvm::Expected MaybeRecID = Stream.readRecord(ID, R, &Blob); @@ -681,6 +683,7 @@ llvm::Error ClangDocBitcodeReader::readRecord(unsigned ID, Reference *I) { // Read a block of records into a single info. template llvm::Error ClangDocBitcodeReader::readBlock(unsigned ID, T I) { + llvm::TimeTraceScope("readBlock", "ClangDocBitcodeReader"); if (llvm::Error Err = Stream.EnterSubBlock(ID)) return Err; @@ -711,6 +714,7 @@ llvm::Error ClangDocBitcodeReader::readBlock(unsigned ID, T I) { template llvm::Error ClangDocBitcodeReader::readSubBlock(unsigned ID, T I) { + llvm::TimeTraceScope("readSubBlock", "ClangDocBitcodeReader"); switch (ID) { // Blocks can only have certain types of sub blocks. case BI_COMMENT_BLOCK_ID: { @@ -817,6 +821,7 @@ llvm::Error ClangDocBitcodeReader::readSubBlock(unsigned ID, T I) { ClangDocBitcodeReader::Cursor ClangDocBitcodeReader::skipUntilRecordOrBlock(unsigned &BlockOrRecordID) { + llvm::TimeTraceScope("skipUntilRecordOrBlock", "ClangDocBitcodeReader"); BlockOrRecordID = 0; while (!Stream.AtEndOfStream()) { @@ -878,6 +883,7 @@ llvm::Error ClangDocBitcodeReader::validateStream() { } llvm::Error ClangDocBitcodeReader::readBlockInfoBlock() { + llvm::TimeTraceScope("readBlockInfoBlock", "ClangDocBitcodeReader"); Expected> MaybeBlockInfo = Stream.ReadBlockInfoBlock(); if (!MaybeBlockInfo) @@ -894,6 +900,7 @@ llvm::Error ClangDocBitcodeReader::readBlockInfoBlock() { template llvm::Expected> ClangDocBitcodeReader::createInfo(unsigned ID) { + llvm::TimeTraceScope("createInfo", "ClangDocBitcodeReader"); std::unique_ptr I = std::make_unique(); if (auto Err = readBlock(ID, static_cast(I.get( return std::move(Err); @@ -902,6 +909,7 @@ ClangDocBitcodeReader::createInfo(unsigned ID) { llvm::Expected> ClangDocBitcodeReader::readBlockToInfo(unsigned ID) { + llvm::TimeTraceScope("readBlockToInfo", "ClangDocBitcodeReader"); switch (ID) { case BI_NAMESPACE_BLOCK_ID: return createInfo(ID); diff --git a/clang-tools-extra/clang-doc/Mapper.cpp b/clang-tools-extra/clang-doc/Mapper.cpp index bb8b7952980ac..4a9e8721c9ff4 100644 --- a/clang-tools-extra/clang-doc/Mapper.cpp +++ b/clang-tools-extra/clang-doc/Mapper.cpp @@ -13,12 +13,17 @@ #include "clang/Index/USRGeneration.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/Error.h" +#include "llvm/Support/TimeProfiler.h" namespace clang { namespace doc { void MapASTVisitor::HandleTranslationUnit(ASTContext &Context) { + if (CDCtx.FTimeTrace) +llvm::timeTraceProfilerInitialize(CDCtx.Granularity, "clang-doc"); TraverseDecl(Context.getTranslationUnitDecl()); + if (CDCtx.FTimeTrace) +llvm::timeTraceProfilerFinishThread(); } template bool MapASTVisitor::mapDecl(const T *D) { @@ -30,6 +35,7 @@ template bool MapASTVisitor::mapDecl(const T *D) { if (D->getParentFunctionOrMethod()) return true; + llvm::timeTraceProfilerBegin("emit info phase", "emit info"); llvm::SmallString<128> USR; // If there is an error generating a USR for the decl, skip this decl. if (index::generateUSRForDecl(D, USR)) @@ -40,7 +46,9 @@ template bool MapASTVisitor::mapDecl(const T *D) { auto I = serialize::emitInfo(D, getComment(D, D->getASTContext()), getLine(D, D->getASTContext()), File, IsFileInRootDir, CDCtx.PublicOnly); + llvm::timeTraceProfilerEnd(); + llvm::timeTraceProfilerBegin("serializing info", "serializing"); // A null in place of I indicates that the serializer is skipping this decl // for some reason (e.g. we're only rep
[clang] [Clang] Substitute for the type aliases inside of a CTAD guide (PR #94740)
@@ -2220,23 +2220,103 @@ namespace { class ExtractTypeForDeductionGuide : public TreeTransform { llvm::SmallVectorImpl &MaterializedTypedefs; + ClassTemplateDecl *NestedPattern; + const MultiLevelTemplateArgumentList *OuterInstantiationArgs; public: typedef TreeTransform Base; ExtractTypeForDeductionGuide( Sema &SemaRef, - llvm::SmallVectorImpl &MaterializedTypedefs) - : Base(SemaRef), MaterializedTypedefs(MaterializedTypedefs) {} + llvm::SmallVectorImpl &MaterializedTypedefs, + ClassTemplateDecl *NestedPattern, + const MultiLevelTemplateArgumentList *OuterInstantiationArgs) + : Base(SemaRef), MaterializedTypedefs(MaterializedTypedefs), +NestedPattern(NestedPattern), +OuterInstantiationArgs(OuterInstantiationArgs) {} TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); } + /// Returns true if it's safe to substitute \p Typedef with + /// \p OuterInstantiationArgs. + bool mightReferToOuterTemplateParameters(TypedefNameDecl *Typedef) { +if (!NestedPattern) + return false; + +static auto WalkUp = [](DeclContext *DC, DeclContext *TargetDC) { + if (DC->Equals(TargetDC)) +return true; + while (DC->isRecord()) { +if (DC->Equals(TargetDC)) + return true; +DC = DC->getParent(); + } + return false; +}; + +if (WalkUp(Typedef->getDeclContext(), NestedPattern->getTemplatedDecl())) + return true; +if (WalkUp(NestedPattern->getTemplatedDecl(), Typedef->getDeclContext())) + return true; +return false; + } + + QualType + RebuildTemplateSpecializationType(TemplateName Template, +SourceLocation TemplateNameLoc, +TemplateArgumentListInfo &TemplateArgs) { +if (!OuterInstantiationArgs || +!isa_and_present(Template.getAsTemplateDecl())) + return Base::RebuildTemplateSpecializationType(Template, TemplateNameLoc, + TemplateArgs); + +auto *TATD = cast(Template.getAsTemplateDecl()); +auto *Pattern = TATD; +while (Pattern->getInstantiatedFromMemberTemplate()) + Pattern = Pattern->getInstantiatedFromMemberTemplate(); +if (!mightReferToOuterTemplateParameters(Pattern->getTemplatedDecl())) + return Base::RebuildTemplateSpecializationType(Template, TemplateNameLoc, + TemplateArgs); + +Decl *NewD = SemaRef.SubstDecl( +TATD, SemaRef.getASTContext().getTranslationUnitDecl(), hokein wrote: I see, thanks for the link. There is a subtle difference: - In `D80743`, we create a `Decl` by calling `TypeAliasDecl::Create(.., TU, ...)`, which only sets the member `TypeAliasDecl::DeclCtx` to `TU`. - While here, we pass the `TU` to the `SubstDecl`. This has the side effect of adding the `NewD` into the `TU` (in the substitution implementation, `TU->addDecl(NewD)` is called). Consequently, in the AST dump, you will see `NewD` under the `TranslationUnit`, which doesn't look right. I guess we can fix this by calling `TU->removeDecl(NewD)`. Thinking more about this, we should have this information in the AST. Given the example: ```cpp template struct Outer { using Alias = S; template struct Inner { Inner(Alias); }; }; Outer::Inner inner(S()); ``` We're performing a substitution for the `Alias` with `T = int` here. At this point, the `Outer` class specialization should be available. Inside this specialization, we should have the `TypeAliasDecl` `S`. So an alternative would be to reuse this `Decl` rather than creating a new one. I'm not sure if this is feasible. It looks like we don't have a good way to get it from the primary `TypeAliasTemplateDecl` (no specializations in the AST node). A hacky way is to perform a lookup from `Outer`. https://github.com/llvm/llvm-project/pull/94740 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] CTAD alias: fix transformation for require-clause expr Part2. (PR #93533)
hokein wrote: Friendly ping, I'd like to get it landed before the release cut. https://github.com/llvm/llvm-project/pull/93533 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [libclang/python] Refactor enum usage (PR #95608)
DeinAlptraum wrote: @Endilll do you think this needs a second review? If not, could you merge this? Since I don't have commit access https://github.com/llvm/llvm-project/pull/95608 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [flang] [llvm] [InstCombine] Canonicalize constant GEPs to i8 source element type (PR #68882)
nikic wrote: @karthik-man LLVM *always* requires a correct data layout. Yes, that includes InstCombine. https://github.com/llvm/llvm-project/pull/68882 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][analyzer] Improve PointerSubChecker (PR #96501)
dkrupp wrote: > > Even protobuf contains this type of code: > > https://codechecker-demo.eastus.cloudapp.azure.com/Default/report-detail?run=protobuf_v3.13.0_pointersub1&is-unique=on&diff-type=New&checker-name=alpha.core.PointerSub&report-id=5545776&report-hash=1bcd310fbaeccbcc13645b9b277239a2&report-filepath=%2adescriptor.pb.cc > > I still think that this (1) is undeniably undefined behavior (2) isn't > common, so won't cause "spam" problems and (3( can be replaced by > standard-compliant code (`offsetof`) so there is no need to introduce a > special case for it. I agree with @NagyDonat that we don't need special handling of this case in the code, however I think the checker [documentation ](https://clang.llvm.org/docs/analyzer/checkers.html#alpha-core-pointersub-c) should be extended with the description of this special case as it may be a surprising warning from the checker with an example. Specifically that it warns for cases where two pointers are subtracted which point to members of the same struct and suggest the usage of the standard compliant solution: offsetof. So please describe which pointer subtractions the checker accepts and which don't (with examples) and a reference to the standard where it describes the undefined behaviour. https://github.com/llvm/llvm-project/pull/96501 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [libc] [llvm] AMDGPU: Add a subtarget feature for fine-grained remote memory support (PR #96442)
@@ -14,13 +14,14 @@ #define LLVM_CODEGEN_MACHINEBRANCHPROBABILITYINFO_H #include "llvm/CodeGen/MachineBasicBlock.h" -#include "llvm/CodeGen/MachinePassManager.h" #include "llvm/Pass.h" #include "llvm/Support/BranchProbability.h" namespace llvm { -class MachineBranchProbabilityInfo { +class MachineBranchProbabilityInfo : public ImmutablePass { jayfoad wrote: Why does the PR include all this unrelated stuff? Which part am I supposed to review? Normally I just look at the "Files changed" tab. https://github.com/llvm/llvm-project/pull/96442 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [libc] [llvm] AMDGPU: Add a subtarget feature for fine-grained remote memory support (PR #96442)
@@ -14,13 +14,14 @@ #define LLVM_CODEGEN_MACHINEBRANCHPROBABILITYINFO_H #include "llvm/CodeGen/MachineBasicBlock.h" -#include "llvm/CodeGen/MachinePassManager.h" #include "llvm/Pass.h" #include "llvm/Support/BranchProbability.h" namespace llvm { -class MachineBranchProbabilityInfo { +class MachineBranchProbabilityInfo : public ImmutablePass { arsenm wrote: The parts I actually committed. I don't know why "[martinboehme](https://github.com/martinboehme) and others added 14 commits [12 hours ago](https://github.com/llvm/llvm-project/pull/96442#commits-pushed-803aa88)" happened, adding all this other stuff to my personal branch. This has happened several other times, but not consistently https://github.com/llvm/llvm-project/pull/96442 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [libc] [llvm] AMDGPU: Add a subtarget feature for fine-grained remote memory support (PR #96442)
https://github.com/arsenm updated https://github.com/llvm/llvm-project/pull/96442 >From a70da4e0b569d3e83d405a0248e9c71635f29f96 Mon Sep 17 00:00:00 2001 From: martinboehme Date: Wed, 26 Jun 2024 15:01:57 +0200 Subject: [PATCH 01/14] [clang][dataflow] Teach `AnalysisASTVisitor` that `typeid()` can be evaluated. (#96731) We were previously treating the operand of `typeid()` as being definitely unevaluated, but it can be evaluated if it is a glvalue of polymorphic type. This patch includes a test that fails without the fix. --- .../clang/Analysis/FlowSensitive/ASTOps.h | 6 ++- .../Analysis/FlowSensitive/TransferTest.cpp | 43 +++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/clang/include/clang/Analysis/FlowSensitive/ASTOps.h b/clang/include/clang/Analysis/FlowSensitive/ASTOps.h index 925b99af9141a..f9c923a36ad22 100644 --- a/clang/include/clang/Analysis/FlowSensitive/ASTOps.h +++ b/clang/include/clang/Analysis/FlowSensitive/ASTOps.h @@ -113,7 +113,11 @@ class AnalysisASTVisitor : public RecursiveASTVisitor { // nevertheless it appears in the Clang CFG, so we don't exclude it here. bool TraverseDecltypeTypeLoc(DecltypeTypeLoc) { return true; } bool TraverseTypeOfExprTypeLoc(TypeOfExprTypeLoc) { return true; } - bool TraverseCXXTypeidExpr(CXXTypeidExpr *) { return true; } + bool TraverseCXXTypeidExpr(CXXTypeidExpr *TIE) { +if (TIE->isPotentiallyEvaluated()) + return RecursiveASTVisitor::TraverseCXXTypeidExpr(TIE); +return true; + } bool TraverseUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *) { return true; } diff --git a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp index e743eefa5d458..39e7001393e5e 100644 --- a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp +++ b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp @@ -1637,6 +1637,49 @@ TEST(TransferTest, StructModeledFieldsWithAccessor) { }); } +TEST(TransferTest, StructModeledFieldsInTypeid) { + // Test that we model fields mentioned inside a `typeid()` expression only if + // that expression is potentially evaluated -- i.e. if the expression inside + // `typeid()` is a glvalue of polymorphic type (see + // `CXXTypeidExpr::isPotentiallyEvaluated()` and [expr.typeid]p3). + std::string Code = R"( +// Definitions needed for `typeid`. +namespace std { + class type_info {}; + class bad_typeid {}; +} // namespace std + +struct NonPolymorphic {}; + +struct Polymorphic { + virtual ~Polymorphic() = default; +}; + +struct S { + NonPolymorphic *NonPoly; + Polymorphic *Poly; +}; + +void target(S &s) { + typeid(*s.NonPoly); + typeid(*s.Poly); + // [[p]] +} + )"; + runDataflow( + Code, + [](const llvm::StringMap> &Results, + ASTContext &ASTCtx) { +const Environment &Env = getEnvironmentAtAnnotation(Results, "p"); +auto &SLoc = getLocForDecl(ASTCtx, Env, "s"); +std::vector Fields; +for (auto [Field, _] : SLoc.children()) + Fields.push_back(Field); +EXPECT_THAT(Fields, +UnorderedElementsAre(findValueDecl(ASTCtx, "Poly"))); + }); +} + TEST(TransferTest, StructModeledFieldsWithComplicatedInheritance) { std::string Code = R"( struct Base1 { >From 6456b3fc06e6013be6f197912caf91ca77cc2a18 Mon Sep 17 00:00:00 2001 From: martinboehme Date: Wed, 26 Jun 2024 15:40:42 +0200 Subject: [PATCH 02/14] Revert "[clang][dataflow] Teach `AnalysisASTVisitor` that `typeid()` can be evaluated." (#96766) Reverts llvm/llvm-project#96731 It causes CI failures. --- .../clang/Analysis/FlowSensitive/ASTOps.h | 6 +-- .../Analysis/FlowSensitive/TransferTest.cpp | 43 --- 2 files changed, 1 insertion(+), 48 deletions(-) diff --git a/clang/include/clang/Analysis/FlowSensitive/ASTOps.h b/clang/include/clang/Analysis/FlowSensitive/ASTOps.h index f9c923a36ad22..925b99af9141a 100644 --- a/clang/include/clang/Analysis/FlowSensitive/ASTOps.h +++ b/clang/include/clang/Analysis/FlowSensitive/ASTOps.h @@ -113,11 +113,7 @@ class AnalysisASTVisitor : public RecursiveASTVisitor { // nevertheless it appears in the Clang CFG, so we don't exclude it here. bool TraverseDecltypeTypeLoc(DecltypeTypeLoc) { return true; } bool TraverseTypeOfExprTypeLoc(TypeOfExprTypeLoc) { return true; } - bool TraverseCXXTypeidExpr(CXXTypeidExpr *TIE) { -if (TIE->isPotentiallyEvaluated()) - return RecursiveASTVisitor::TraverseCXXTypeidExpr(TIE); -return true; - } + bool TraverseCXXTypeidExpr(CXXTypeidExpr *) { return true; } bool TraverseUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *) { return true; } diff --git a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp index 39e7001393e5e..e743eefa5d458 100644 --- a/clang/unittests/Analysis/
[clang] [libc] [llvm] AMDGPU: Add a subtarget feature for fine-grained remote memory support (PR #96442)
@@ -14,13 +14,14 @@ #define LLVM_CODEGEN_MACHINEBRANCHPROBABILITYINFO_H #include "llvm/CodeGen/MachineBasicBlock.h" -#include "llvm/CodeGen/MachinePassManager.h" #include "llvm/Pass.h" #include "llvm/Support/BranchProbability.h" namespace llvm { -class MachineBranchProbabilityInfo { +class MachineBranchProbabilityInfo : public ImmutablePass { arsenm wrote: This isn't happening for the other patches further up the stack, just this one for some reason https://github.com/llvm/llvm-project/pull/96442 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Warn on backslash-newline-EOF (PR #97585)
https://github.com/MitalAshok updated https://github.com/llvm/llvm-project/pull/97585 >From 8af656659b79d76c971b01f1f4c14dc7315565b8 Mon Sep 17 00:00:00 2001 From: Mital Ashok Date: Fri, 21 Jun 2024 18:55:38 +0100 Subject: [PATCH 1/2] [Clang] Warn on backslash-newline-EOF --- clang/docs/ReleaseNotes.rst | 2 + .../include/clang/Basic/DiagnosticLexKinds.td | 1 + clang/lib/Lex/Lexer.cpp | 39 +-- clang/test/CXX/drs/cwg16xx.cpp| 9 + clang/test/CXX/drs/cwg2747.cpp| 11 ++ clang/test/CXX/drs/cwg27xx.cpp| 2 + .../test/Preprocessor/backslash_newline_eof.c | 12 ++ .../Preprocessor/backslash_without_newline.c | 8 .../Preprocessor/backslash_without_newline.h | 4 ++ clang/www/cxx_dr_status.html | 4 +- 10 files changed, 87 insertions(+), 5 deletions(-) create mode 100644 clang/test/CXX/drs/cwg2747.cpp create mode 100644 clang/test/Preprocessor/backslash_newline_eof.c create mode 100644 clang/test/Preprocessor/backslash_without_newline.c create mode 100644 clang/test/Preprocessor/backslash_without_newline.h diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index f40fd1cd145bb..7c0ac3a504f98 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -647,6 +647,8 @@ Improvements to Clang's diagnostics - Clang now shows implicit deduction guides when diagnosing overload resolution failure. #GH92393. +- Clang now emits ``-Wnewline-eof`` when the last newline is deleted by a preceding backslash. + Improvements to Clang's time-trace -- diff --git a/clang/include/clang/Basic/DiagnosticLexKinds.td b/clang/include/clang/Basic/DiagnosticLexKinds.td index 12d7b8c0205ee..e6b2c1385944c 100644 --- a/clang/include/clang/Basic/DiagnosticLexKinds.td +++ b/clang/include/clang/Basic/DiagnosticLexKinds.td @@ -56,6 +56,7 @@ def ext_no_newline_eof : Extension<"no newline at end of file">, InGroup; def warn_no_newline_eof : Warning<"no newline at end of file">, InGroup, DefaultIgnore; +def note_backslash_newline_eof : Note<"last newline deleted by splice here">; def warn_cxx98_compat_no_newline_eof : Warning< "C++98 requires newline at end of file">, diff --git a/clang/lib/Lex/Lexer.cpp b/clang/lib/Lex/Lexer.cpp index e59c7805b3862..0e540834b473b 100644 --- a/clang/lib/Lex/Lexer.cpp +++ b/clang/lib/Lex/Lexer.cpp @@ -3165,7 +3165,17 @@ bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) { // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue // a pedwarn. - if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) { + if (CurPtr != BufferStart) { +StringRef LastNewline; +if (CurPtr[-1] == '\r' || CurPtr[-1] == '\n') { + LastNewline = StringRef(CurPtr - 1, 1); + if (CurPtr - 1 != BufferStart && CurPtr[-2] != CurPtr[-1] && + (CurPtr[-2] == '\r' || CurPtr[-2] == '\n')) { +// \r\n or \n\r is one newline +LastNewline = StringRef(CurPtr - 2, 2); + } +} + DiagnosticsEngine &Diags = PP->getDiagnostics(); SourceLocation EndLoc = getSourceLocation(BufferEnd); unsigned DiagID; @@ -3183,8 +3193,31 @@ bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) { DiagID = diag::ext_no_newline_eof; } -Diag(BufferEnd, DiagID) - << FixItHint::CreateInsertion(EndLoc, "\n"); +if (LastNewline.empty()) { + Diag(BufferEnd, DiagID) << FixItHint::CreateInsertion(EndLoc, "\n"); +} else { + // While the file physically ends in a newline, the previous + // line might have ended in a splice, so it would be deleted + const char *LastSpliceLocation = LastNewline.data(); + while (LastSpliceLocation != BufferStart && + isHorizontalWhitespace(*--LastSpliceLocation)) +; + + bool LastIsSplice = *LastSpliceLocation == '\\'; + if (*LastSpliceLocation == '/' && LangOpts.Trigraphs) +// Check for "??/" trigraph for "\" +LastIsSplice = +LastSpliceLocation != BufferStart && *--LastSpliceLocation == '?' && +LastSpliceLocation != BufferStart && *--LastSpliceLocation == '?'; + + if (LastIsSplice) { +PP->Diag(getSourceLocation(LastNewline.data(), LastNewline.size()), + DiagID); +Diag(LastSpliceLocation, diag::note_backslash_newline_eof) +<< FixItHint::CreateRemoval(getSourceLocation( + LastSpliceLocation, *LastSpliceLocation == '\\' ? 1 : 3)); + } +} } BufferPtr = CurPtr; diff --git a/clang/test/CXX/drs/cwg16xx.cpp b/clang/test/CXX/drs/cwg16xx.cpp index cf6b45ceabf2c..dca941fa30624 100644 --- a/clang/test/CXX/drs/cwg16xx.cpp +++ b/clang/test/CXX/drs/cwg16xx.cpp @@ -536,3 +536,12 @@ namespace cwg1696 { // cwg1696: 7 }; #endif } + +// cwg1698: yes +// This file intentionally does not end in a ne
[clang-tools-extra] [clang-tidy] Add `bugprone-pointer-arithmetic-on-polymorphic-object` check (PR #91951)
@@ -0,0 +1,81 @@ +//===--- PointerArithmeticOnPolymorphicObjectCheck.cpp - clang-tidy===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "PointerArithmeticOnPolymorphicObjectCheck.h" +#include "clang/AST/ASTContext.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::bugprone { + +namespace { +AST_MATCHER(CXXRecordDecl, isAbstract) { return Node.isAbstract(); } +AST_MATCHER(CXXRecordDecl, isPolymorphic) { return Node.isPolymorphic(); } +} // namespace + +PointerArithmeticOnPolymorphicObjectCheck:: +PointerArithmeticOnPolymorphicObjectCheck(StringRef Name, + ClangTidyContext *Context) +: ClangTidyCheck(Name, Context), + IgnoreInheritedVirtualFunctions( + Options.get("IgnoreInheritedVirtualFunctions", false)) {} + +void PointerArithmeticOnPolymorphicObjectCheck::storeOptions( +ClangTidyOptions::OptionMap &Opts) { + Options.store(Opts, "IgnoreInheritedVirtualFunctions", +IgnoreInheritedVirtualFunctions); +} + +void PointerArithmeticOnPolymorphicObjectCheck::registerMatchers( +MatchFinder *Finder) { + const auto PolymorphicPointerExpr = + expr(hasType(hasCanonicalType(pointerType(pointee(hasCanonicalType( + hasDeclaration(cxxRecordDecl(unless(isFinal()), isPolymorphic()) + .bind("pointee" + .bind("pointer"); + + const auto PointerExprWithVirtualMethod = + expr(hasType(hasCanonicalType( + pointerType(pointee(hasCanonicalType(hasDeclaration( + cxxRecordDecl( + unless(isFinal()), + anyOf(hasMethod(isVirtualAsWritten()), isAbstract())) + .bind("pointee" + .bind("pointer"); + + const auto SelectedPointerExpr = IgnoreInheritedVirtualFunctions + ? PointerExprWithVirtualMethod + : PolymorphicPointerExpr; + + const auto ArraySubscript = arraySubscriptExpr(hasBase(SelectedPointerExpr)); + + const auto BinaryOperators = + binaryOperator(hasAnyOperatorName("+", "-", "+=", "-="), + hasEitherOperand(SelectedPointerExpr)); + + const auto UnaryOperators = unaryOperator( + hasAnyOperatorName("++", "--"), hasUnaryOperand(SelectedPointerExpr)); + + Finder->addMatcher(ArraySubscript, this); + Finder->addMatcher(BinaryOperators, this); + Finder->addMatcher(UnaryOperators, this); +} + +void PointerArithmeticOnPolymorphicObjectCheck::check( +const MatchFinder::MatchResult &Result) { + const auto *PointerExpr = Result.Nodes.getNodeAs("pointer"); + const auto *PointeeDecl = Result.Nodes.getNodeAs("pointee"); + + diag(PointerExpr->getBeginLoc(), + "pointer arithmetic on polymorphic object of type '%0' can result in " + "undefined behavior if the dynamic type differs from the pointer type") + << PointeeDecl->getName() << PointeeDecl->getSourceRange(); Discookie wrote: Whoops that's a typo, well spotted! Fixed. https://github.com/llvm/llvm-project/pull/91951 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Warn on backslash-newline-EOF (PR #97585)
https://github.com/MitalAshok updated https://github.com/llvm/llvm-project/pull/97585 >From 8af656659b79d76c971b01f1f4c14dc7315565b8 Mon Sep 17 00:00:00 2001 From: Mital Ashok Date: Fri, 21 Jun 2024 18:55:38 +0100 Subject: [PATCH 1/3] [Clang] Warn on backslash-newline-EOF --- clang/docs/ReleaseNotes.rst | 2 + .../include/clang/Basic/DiagnosticLexKinds.td | 1 + clang/lib/Lex/Lexer.cpp | 39 +-- clang/test/CXX/drs/cwg16xx.cpp| 9 + clang/test/CXX/drs/cwg2747.cpp| 11 ++ clang/test/CXX/drs/cwg27xx.cpp| 2 + .../test/Preprocessor/backslash_newline_eof.c | 12 ++ .../Preprocessor/backslash_without_newline.c | 8 .../Preprocessor/backslash_without_newline.h | 4 ++ clang/www/cxx_dr_status.html | 4 +- 10 files changed, 87 insertions(+), 5 deletions(-) create mode 100644 clang/test/CXX/drs/cwg2747.cpp create mode 100644 clang/test/Preprocessor/backslash_newline_eof.c create mode 100644 clang/test/Preprocessor/backslash_without_newline.c create mode 100644 clang/test/Preprocessor/backslash_without_newline.h diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index f40fd1cd145bb..7c0ac3a504f98 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -647,6 +647,8 @@ Improvements to Clang's diagnostics - Clang now shows implicit deduction guides when diagnosing overload resolution failure. #GH92393. +- Clang now emits ``-Wnewline-eof`` when the last newline is deleted by a preceding backslash. + Improvements to Clang's time-trace -- diff --git a/clang/include/clang/Basic/DiagnosticLexKinds.td b/clang/include/clang/Basic/DiagnosticLexKinds.td index 12d7b8c0205ee..e6b2c1385944c 100644 --- a/clang/include/clang/Basic/DiagnosticLexKinds.td +++ b/clang/include/clang/Basic/DiagnosticLexKinds.td @@ -56,6 +56,7 @@ def ext_no_newline_eof : Extension<"no newline at end of file">, InGroup; def warn_no_newline_eof : Warning<"no newline at end of file">, InGroup, DefaultIgnore; +def note_backslash_newline_eof : Note<"last newline deleted by splice here">; def warn_cxx98_compat_no_newline_eof : Warning< "C++98 requires newline at end of file">, diff --git a/clang/lib/Lex/Lexer.cpp b/clang/lib/Lex/Lexer.cpp index e59c7805b3862..0e540834b473b 100644 --- a/clang/lib/Lex/Lexer.cpp +++ b/clang/lib/Lex/Lexer.cpp @@ -3165,7 +3165,17 @@ bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) { // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue // a pedwarn. - if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) { + if (CurPtr != BufferStart) { +StringRef LastNewline; +if (CurPtr[-1] == '\r' || CurPtr[-1] == '\n') { + LastNewline = StringRef(CurPtr - 1, 1); + if (CurPtr - 1 != BufferStart && CurPtr[-2] != CurPtr[-1] && + (CurPtr[-2] == '\r' || CurPtr[-2] == '\n')) { +// \r\n or \n\r is one newline +LastNewline = StringRef(CurPtr - 2, 2); + } +} + DiagnosticsEngine &Diags = PP->getDiagnostics(); SourceLocation EndLoc = getSourceLocation(BufferEnd); unsigned DiagID; @@ -3183,8 +3193,31 @@ bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) { DiagID = diag::ext_no_newline_eof; } -Diag(BufferEnd, DiagID) - << FixItHint::CreateInsertion(EndLoc, "\n"); +if (LastNewline.empty()) { + Diag(BufferEnd, DiagID) << FixItHint::CreateInsertion(EndLoc, "\n"); +} else { + // While the file physically ends in a newline, the previous + // line might have ended in a splice, so it would be deleted + const char *LastSpliceLocation = LastNewline.data(); + while (LastSpliceLocation != BufferStart && + isHorizontalWhitespace(*--LastSpliceLocation)) +; + + bool LastIsSplice = *LastSpliceLocation == '\\'; + if (*LastSpliceLocation == '/' && LangOpts.Trigraphs) +// Check for "??/" trigraph for "\" +LastIsSplice = +LastSpliceLocation != BufferStart && *--LastSpliceLocation == '?' && +LastSpliceLocation != BufferStart && *--LastSpliceLocation == '?'; + + if (LastIsSplice) { +PP->Diag(getSourceLocation(LastNewline.data(), LastNewline.size()), + DiagID); +Diag(LastSpliceLocation, diag::note_backslash_newline_eof) +<< FixItHint::CreateRemoval(getSourceLocation( + LastSpliceLocation, *LastSpliceLocation == '\\' ? 1 : 3)); + } +} } BufferPtr = CurPtr; diff --git a/clang/test/CXX/drs/cwg16xx.cpp b/clang/test/CXX/drs/cwg16xx.cpp index cf6b45ceabf2c..dca941fa30624 100644 --- a/clang/test/CXX/drs/cwg16xx.cpp +++ b/clang/test/CXX/drs/cwg16xx.cpp @@ -536,3 +536,12 @@ namespace cwg1696 { // cwg1696: 7 }; #endif } + +// cwg1698: yes +// This file intentionally does not end in a ne
[clang] [Parser][ObjC] Add -Wobjc-prefix-length warning option. (PR #97597)
https://github.com/al45tair updated https://github.com/llvm/llvm-project/pull/97597 >From 02f7c5ef71b382866e02037ce82c85fa6fcbb394 Mon Sep 17 00:00:00 2001 From: Alastair Houghton Date: Wed, 3 Jul 2024 17:00:51 +0100 Subject: [PATCH 1/2] [Parser][ObjC] Add -Wobjc-prefix-length warning option. This lets clang generate warnings automatically if it sees Objective-C names that don't have the correct prefix length. rdar://131055157 --- clang/include/clang/Basic/DiagnosticGroups.td | 1 + .../clang/Basic/DiagnosticParseKinds.td | 7 ++ clang/include/clang/Basic/LangOptions.def | 2 + clang/include/clang/Driver/Options.td | 7 ++ clang/include/clang/Parse/Parser.h| 1 + clang/lib/Driver/ToolChains/Clang.cpp | 1 + clang/lib/Parse/ParseObjc.cpp | 65 +++ clang/test/Parser/objc-prefixes.m | 62 ++ 8 files changed, 146 insertions(+) create mode 100644 clang/test/Parser/objc-prefixes.m diff --git a/clang/include/clang/Basic/DiagnosticGroups.td b/clang/include/clang/Basic/DiagnosticGroups.td index 9431eea1f6be2..0d944434cda38 100644 --- a/clang/include/clang/Basic/DiagnosticGroups.td +++ b/clang/include/clang/Basic/DiagnosticGroups.td @@ -598,6 +598,7 @@ def ObjCPointerIntrospect : DiagGroup<"deprecated-objc-pointer-introspection", [ def ObjCMultipleMethodNames : DiagGroup<"objc-multiple-method-names">; def ObjCFlexibleArray : DiagGroup<"objc-flexible-array">; def ObjCBoxing : DiagGroup<"objc-boxing">; +def ObjCPrefixLength : DiagGroup<"objc-prefix-length">; def CompletionHandler : DiagGroup<"completion-handler">; def CalledOnceParameter : DiagGroup<"called-once-parameter", [CompletionHandler]>; def OpenCLUnsupportedRGBA: DiagGroup<"opencl-unsupported-rgba">; diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td b/clang/include/clang/Basic/DiagnosticParseKinds.td index 12aab09f28556..7e26bd13f9c7b 100644 --- a/clang/include/clang/Basic/DiagnosticParseKinds.td +++ b/clang/include/clang/Basic/DiagnosticParseKinds.td @@ -563,6 +563,13 @@ def err_declaration_does_not_declare_param : Error< "declaration does not declare a parameter">; def err_no_matching_param : Error<"parameter named %0 is missing">; +def warn_objc_unprefixed_class_name : Warning< + "un-prefixed Objective-C class name">, + InGroup; +def warn_objc_unprefixed_protocol_name : Warning< + "un-prefixed Objective-C protocol name">, + InGroup; + /// Objective-C++ parser diagnostics def err_expected_token_instead_of_objcxx_keyword : Error< "expected %0; %1 is a keyword in Objective-C++">; diff --git a/clang/include/clang/Basic/LangOptions.def b/clang/include/clang/Basic/LangOptions.def index 491759e2fcdbb..9df19b01f0b22 100644 --- a/clang/include/clang/Basic/LangOptions.def +++ b/clang/include/clang/Basic/LangOptions.def @@ -351,6 +351,8 @@ LANGOPT(ObjCAutoRefCount , 1, 0, "Objective-C automated reference counting") LANGOPT(ObjCWeakRuntime , 1, 0, "__weak support in the ARC runtime") LANGOPT(ObjCWeak, 1, 0, "Objective-C __weak in ARC and MRC files") LANGOPT(ObjCSubscriptingLegacyRuntime , 1, 0, "Subscripting support in legacy ObjectiveC runtime") +BENIGN_LANGOPT(ObjCPrefixLength, 32, 0, + "if non-zero, warn about Objective-C classes or protocols with names that do not have a prefix of the specified length.") BENIGN_LANGOPT(CompatibilityQualifiedIdBlockParamTypeChecking, 1, 0, "compatibility mode for type checking block parameters " "involving qualified id types") diff --git a/clang/include/clang/Driver/Options.td b/clang/include/clang/Driver/Options.td index 1ede75d3782cd..829efafd03a2c 100644 --- a/clang/include/clang/Driver/Options.td +++ b/clang/include/clang/Driver/Options.td @@ -3418,6 +3418,13 @@ defm objc_exceptions : BoolFOption<"objc-exceptions", PosFlag, NegFlag>; +def Wobjc_prefix_length_EQ: + Joined<["-"], "Wobjc-prefix-length=">, + Visibility<[ClangOption, CC1Option]>, + MetaVarName<"">, + HelpText<"Warn if Objective-C class or protocol names do not start with a prefix of the specified length">, + MarshallingInfoInt>; + defm application_extension : BoolFOption<"application-extension", LangOpts<"AppExt">, DefaultFalse, PosFlaggetBeginLoc(), diag::note_objc_container_start) << (int)ock; } +/// An Objective-C public name (a class name or protocol name) is +/// expected to have a prefix as all names are in a single global +/// namespace. +/// +/// If the -Wobjc-prefix-length is set to N, the name must start +/// with N+1 capital letters, which must be followed by a character +/// that is not a capital letter. +/// +/// For instance, for N set to 2, the following are valid: +/// +/// NSString +/// NSArray +/// +/// but these are not: +/// +/// MyString +/// NSKString +/// NSnotAString +/// +/// We make a special exception for NSCF things when the prefix is set +//
[clang] [Clang] Warn on backslash-newline-EOF (PR #97585)
https://github.com/Sirraide approved this pull request. Thanks, I personally at least find it much easier to tell now at a glance that this makes sense. I’d wait a bit before merging this to see if someone more familiar with either C or the lexer has any more comments on this,. https://github.com/llvm/llvm-project/pull/97585 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Parser][ObjC] Add -Wobjc-prefix-length warning option. (PR #97597)
@@ -0,0 +1,18 @@ +// RUN: %clang_cc1 %s -Wobjc-prefixes=NS,NSCF,NSURL -fsyntax-only -verify al45tair wrote: Hmmm, maybe, yes. Not hard to add. https://github.com/llvm/llvm-project/pull/97597 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Warn on backslash-newline-EOF (PR #97585)
https://github.com/Sirraide edited https://github.com/llvm/llvm-project/pull/97585 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Warn on backslash-newline-EOF (PR #97585)
https://github.com/MitalAshok updated https://github.com/llvm/llvm-project/pull/97585 >From 8af656659b79d76c971b01f1f4c14dc7315565b8 Mon Sep 17 00:00:00 2001 From: Mital Ashok Date: Fri, 21 Jun 2024 18:55:38 +0100 Subject: [PATCH 1/4] [Clang] Warn on backslash-newline-EOF --- clang/docs/ReleaseNotes.rst | 2 + .../include/clang/Basic/DiagnosticLexKinds.td | 1 + clang/lib/Lex/Lexer.cpp | 39 +-- clang/test/CXX/drs/cwg16xx.cpp| 9 + clang/test/CXX/drs/cwg2747.cpp| 11 ++ clang/test/CXX/drs/cwg27xx.cpp| 2 + .../test/Preprocessor/backslash_newline_eof.c | 12 ++ .../Preprocessor/backslash_without_newline.c | 8 .../Preprocessor/backslash_without_newline.h | 4 ++ clang/www/cxx_dr_status.html | 4 +- 10 files changed, 87 insertions(+), 5 deletions(-) create mode 100644 clang/test/CXX/drs/cwg2747.cpp create mode 100644 clang/test/Preprocessor/backslash_newline_eof.c create mode 100644 clang/test/Preprocessor/backslash_without_newline.c create mode 100644 clang/test/Preprocessor/backslash_without_newline.h diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index f40fd1cd145bb0..7c0ac3a504f982 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -647,6 +647,8 @@ Improvements to Clang's diagnostics - Clang now shows implicit deduction guides when diagnosing overload resolution failure. #GH92393. +- Clang now emits ``-Wnewline-eof`` when the last newline is deleted by a preceding backslash. + Improvements to Clang's time-trace -- diff --git a/clang/include/clang/Basic/DiagnosticLexKinds.td b/clang/include/clang/Basic/DiagnosticLexKinds.td index 12d7b8c0205ee9..e6b2c1385944c7 100644 --- a/clang/include/clang/Basic/DiagnosticLexKinds.td +++ b/clang/include/clang/Basic/DiagnosticLexKinds.td @@ -56,6 +56,7 @@ def ext_no_newline_eof : Extension<"no newline at end of file">, InGroup; def warn_no_newline_eof : Warning<"no newline at end of file">, InGroup, DefaultIgnore; +def note_backslash_newline_eof : Note<"last newline deleted by splice here">; def warn_cxx98_compat_no_newline_eof : Warning< "C++98 requires newline at end of file">, diff --git a/clang/lib/Lex/Lexer.cpp b/clang/lib/Lex/Lexer.cpp index e59c7805b38623..0e540834b473ba 100644 --- a/clang/lib/Lex/Lexer.cpp +++ b/clang/lib/Lex/Lexer.cpp @@ -3165,7 +3165,17 @@ bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) { // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue // a pedwarn. - if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) { + if (CurPtr != BufferStart) { +StringRef LastNewline; +if (CurPtr[-1] == '\r' || CurPtr[-1] == '\n') { + LastNewline = StringRef(CurPtr - 1, 1); + if (CurPtr - 1 != BufferStart && CurPtr[-2] != CurPtr[-1] && + (CurPtr[-2] == '\r' || CurPtr[-2] == '\n')) { +// \r\n or \n\r is one newline +LastNewline = StringRef(CurPtr - 2, 2); + } +} + DiagnosticsEngine &Diags = PP->getDiagnostics(); SourceLocation EndLoc = getSourceLocation(BufferEnd); unsigned DiagID; @@ -3183,8 +3193,31 @@ bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) { DiagID = diag::ext_no_newline_eof; } -Diag(BufferEnd, DiagID) - << FixItHint::CreateInsertion(EndLoc, "\n"); +if (LastNewline.empty()) { + Diag(BufferEnd, DiagID) << FixItHint::CreateInsertion(EndLoc, "\n"); +} else { + // While the file physically ends in a newline, the previous + // line might have ended in a splice, so it would be deleted + const char *LastSpliceLocation = LastNewline.data(); + while (LastSpliceLocation != BufferStart && + isHorizontalWhitespace(*--LastSpliceLocation)) +; + + bool LastIsSplice = *LastSpliceLocation == '\\'; + if (*LastSpliceLocation == '/' && LangOpts.Trigraphs) +// Check for "??/" trigraph for "\" +LastIsSplice = +LastSpliceLocation != BufferStart && *--LastSpliceLocation == '?' && +LastSpliceLocation != BufferStart && *--LastSpliceLocation == '?'; + + if (LastIsSplice) { +PP->Diag(getSourceLocation(LastNewline.data(), LastNewline.size()), + DiagID); +Diag(LastSpliceLocation, diag::note_backslash_newline_eof) +<< FixItHint::CreateRemoval(getSourceLocation( + LastSpliceLocation, *LastSpliceLocation == '\\' ? 1 : 3)); + } +} } BufferPtr = CurPtr; diff --git a/clang/test/CXX/drs/cwg16xx.cpp b/clang/test/CXX/drs/cwg16xx.cpp index cf6b45ceabf2cc..dca941fa30624f 100644 --- a/clang/test/CXX/drs/cwg16xx.cpp +++ b/clang/test/CXX/drs/cwg16xx.cpp @@ -536,3 +536,12 @@ namespace cwg1696 { // cwg1696: 7 }; #endif } + +// cwg1698: yes +// This file intentionally does not end
[clang] [Clang] Warn on backslash-newline-EOF (PR #97585)
https://github.com/MitalAshok edited https://github.com/llvm/llvm-project/pull/97585 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Parser][ObjC] Add -Wobjc-prefix-length warning option. (PR #97597)
@@ -204,6 +204,89 @@ void Parser::CheckNestedObjCContexts(SourceLocation AtLoc) Diag(Decl->getBeginLoc(), diag::note_objc_container_start) << (int)ock; } +/// An Objective-C public name (a class name or protocol name) is +/// expected to have a prefix as all names are in a single global +/// namespace. +/// +/// If the `-Wobjc-prefix=` option is active, it specifies a list +/// of permitted prefixes; classes and protocols must start with a +/// prefix from that list. Note that in this case, we check that +/// the name matches (?)?, so e.g. +/// if you specify `-Wobjc-prefix=NS`, then `NSURL` would not be valid; +/// you would want to specify `-Wobjc-prefix=NS,NSURL` in that case. +/// +/// If the -Wobjc-prefix-length is set to N, the name must start +/// with N+1 capital letters, which must be followed by a character +/// that is not a capital letter. +/// +/// For instance, for N set to 2, the following are valid: +/// +/// NSString +/// NSArray +/// +/// but these are not: +/// +/// MyString +/// NSKString +/// NSnotAString +/// +/// We make a special exception for NSCF things when the prefix is set +/// to length 2, because that's an unusual special case in the implementation +/// of the Cocoa frameworks. +/// +/// Names that start with underscores are exempt from this check, but +/// are reserved for the system and should not be used by user code. +bool Parser::isObjCPublicNamePrefixAllowed(StringRef name) { tbaederr wrote: Newly introduced parameters and variables should start with an uppercase letter. https://github.com/llvm/llvm-project/pull/97597 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [Clang][OpenMP] This is addition fix for #92210. (PR #94802)
alexey-bataev wrote: Missed one thing, the assignments for boolean flags must be |=, otherwise we may miss some combinations. https://github.com/llvm/llvm-project/pull/94802 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Parser][ObjC] Add -Wobjc-prefix-length warning option. (PR #97597)
https://github.com/al45tair updated https://github.com/llvm/llvm-project/pull/97597 >From 02f7c5ef71b382866e02037ce82c85fa6fcbb394 Mon Sep 17 00:00:00 2001 From: Alastair Houghton Date: Wed, 3 Jul 2024 17:00:51 +0100 Subject: [PATCH 1/3] [Parser][ObjC] Add -Wobjc-prefix-length warning option. This lets clang generate warnings automatically if it sees Objective-C names that don't have the correct prefix length. rdar://131055157 --- clang/include/clang/Basic/DiagnosticGroups.td | 1 + .../clang/Basic/DiagnosticParseKinds.td | 7 ++ clang/include/clang/Basic/LangOptions.def | 2 + clang/include/clang/Driver/Options.td | 7 ++ clang/include/clang/Parse/Parser.h| 1 + clang/lib/Driver/ToolChains/Clang.cpp | 1 + clang/lib/Parse/ParseObjc.cpp | 65 +++ clang/test/Parser/objc-prefixes.m | 62 ++ 8 files changed, 146 insertions(+) create mode 100644 clang/test/Parser/objc-prefixes.m diff --git a/clang/include/clang/Basic/DiagnosticGroups.td b/clang/include/clang/Basic/DiagnosticGroups.td index 9431eea1f6be2..0d944434cda38 100644 --- a/clang/include/clang/Basic/DiagnosticGroups.td +++ b/clang/include/clang/Basic/DiagnosticGroups.td @@ -598,6 +598,7 @@ def ObjCPointerIntrospect : DiagGroup<"deprecated-objc-pointer-introspection", [ def ObjCMultipleMethodNames : DiagGroup<"objc-multiple-method-names">; def ObjCFlexibleArray : DiagGroup<"objc-flexible-array">; def ObjCBoxing : DiagGroup<"objc-boxing">; +def ObjCPrefixLength : DiagGroup<"objc-prefix-length">; def CompletionHandler : DiagGroup<"completion-handler">; def CalledOnceParameter : DiagGroup<"called-once-parameter", [CompletionHandler]>; def OpenCLUnsupportedRGBA: DiagGroup<"opencl-unsupported-rgba">; diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td b/clang/include/clang/Basic/DiagnosticParseKinds.td index 12aab09f28556..7e26bd13f9c7b 100644 --- a/clang/include/clang/Basic/DiagnosticParseKinds.td +++ b/clang/include/clang/Basic/DiagnosticParseKinds.td @@ -563,6 +563,13 @@ def err_declaration_does_not_declare_param : Error< "declaration does not declare a parameter">; def err_no_matching_param : Error<"parameter named %0 is missing">; +def warn_objc_unprefixed_class_name : Warning< + "un-prefixed Objective-C class name">, + InGroup; +def warn_objc_unprefixed_protocol_name : Warning< + "un-prefixed Objective-C protocol name">, + InGroup; + /// Objective-C++ parser diagnostics def err_expected_token_instead_of_objcxx_keyword : Error< "expected %0; %1 is a keyword in Objective-C++">; diff --git a/clang/include/clang/Basic/LangOptions.def b/clang/include/clang/Basic/LangOptions.def index 491759e2fcdbb..9df19b01f0b22 100644 --- a/clang/include/clang/Basic/LangOptions.def +++ b/clang/include/clang/Basic/LangOptions.def @@ -351,6 +351,8 @@ LANGOPT(ObjCAutoRefCount , 1, 0, "Objective-C automated reference counting") LANGOPT(ObjCWeakRuntime , 1, 0, "__weak support in the ARC runtime") LANGOPT(ObjCWeak, 1, 0, "Objective-C __weak in ARC and MRC files") LANGOPT(ObjCSubscriptingLegacyRuntime , 1, 0, "Subscripting support in legacy ObjectiveC runtime") +BENIGN_LANGOPT(ObjCPrefixLength, 32, 0, + "if non-zero, warn about Objective-C classes or protocols with names that do not have a prefix of the specified length.") BENIGN_LANGOPT(CompatibilityQualifiedIdBlockParamTypeChecking, 1, 0, "compatibility mode for type checking block parameters " "involving qualified id types") diff --git a/clang/include/clang/Driver/Options.td b/clang/include/clang/Driver/Options.td index 1ede75d3782cd..829efafd03a2c 100644 --- a/clang/include/clang/Driver/Options.td +++ b/clang/include/clang/Driver/Options.td @@ -3418,6 +3418,13 @@ defm objc_exceptions : BoolFOption<"objc-exceptions", PosFlag, NegFlag>; +def Wobjc_prefix_length_EQ: + Joined<["-"], "Wobjc-prefix-length=">, + Visibility<[ClangOption, CC1Option]>, + MetaVarName<"">, + HelpText<"Warn if Objective-C class or protocol names do not start with a prefix of the specified length">, + MarshallingInfoInt>; + defm application_extension : BoolFOption<"application-extension", LangOpts<"AppExt">, DefaultFalse, PosFlaggetBeginLoc(), diag::note_objc_container_start) << (int)ock; } +/// An Objective-C public name (a class name or protocol name) is +/// expected to have a prefix as all names are in a single global +/// namespace. +/// +/// If the -Wobjc-prefix-length is set to N, the name must start +/// with N+1 capital letters, which must be followed by a character +/// that is not a capital letter. +/// +/// For instance, for N set to 2, the following are valid: +/// +/// NSString +/// NSArray +/// +/// but these are not: +/// +/// MyString +/// NSKString +/// NSnotAString +/// +/// We make a special exception for NSCF things when the prefix is set +//
[clang] [analyzer] Check the correct first and last elements in cstring.UninitializedRead (PR #95408)
https://github.com/Szelethus closed https://github.com/llvm/llvm-project/pull/95408 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 4835572 - [analyzer] Check the correct first and last elements in cstring.UninitializedRead (#95408)
Author: Kristóf Umann Date: 2024-07-04T13:46:22+02:00 New Revision: 483557224b8d36761f39d5847e17ef7361757f1b URL: https://github.com/llvm/llvm-project/commit/483557224b8d36761f39d5847e17ef7361757f1b DIFF: https://github.com/llvm/llvm-project/commit/483557224b8d36761f39d5847e17ef7361757f1b.diff LOG: [analyzer] Check the correct first and last elements in cstring.UninitializedRead (#95408) I intend to fix this checker up so that we can move it out of alpha. I made a bunch of analyses, and found many similar false positives: ```c++ int t[] = {1,2,3}; memcpy(dst, t, sizeof(t) / sizeof(t[0])); // warn ``` The problem here is the way CStringChecker checks whether the destination and source buffers are initialized: heuristically, it only checks the first and last element. This is fine, however, it retrieves these elements as characters, even if the underlaying object is not a character array. Reading the last byte of an integer is undefined, so the checker emits a bug here. A quick search tells you the rationale: "Both objects are reinterpreted as arrays of unsigned char.". But the static analyzer right now can't check byte-by-byte if a memory region is _initialized_, it can only check if its a well-defined character or not. In this patch, I pry the original array out of the arguments to memcpy (and similar functions), and retrieve the actual first and last elements according to the array's actual element type. Currently, my improvements reduced the number of reports to 29 on these projects: memcached,tmux,curl,twin,vim,openssl,sqlite,ffmpeg,postgres https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?detection-status=New&detection-status=Reopened&detection-status=Unresolved&is-unique=on&run=%2acstring_uninit_upper_bound_patched&newcheck=%2acstring_uninit_upper_bounds_patched&diff-type=New&checker-name=alpha.unix.cstring.UninitializedRead&items-per-page=100 Before my patch, there were 87. https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?detection-status=New&detection-status=Reopened&detection-status=Unresolved&is-unique=on&run=%2acstring_uninit_baseline&newcheck=%2acstring_uninit_upper_bounds_patched&diff-type=New&checker-name=alpha.unix.cstring.UninitializedRead&items-per-page=100 Added: Modified: clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp clang/lib/StaticAnalyzer/Core/MemRegion.cpp clang/test/Analysis/bstring_UninitRead.c Removed: diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h index c0d3fbd0eb961..0d9566285f5d4 100644 --- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h +++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h @@ -34,6 +34,7 @@ #include "llvm/ADT/iterator_range.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/Casting.h" +#include "llvm/Support/ErrorHandling.h" #include #include #include @@ -99,6 +100,8 @@ class MemRegion : public llvm::FoldingSetNode { #define REGION(Id, Parent) Id ## Kind, #define REGION_RANGE(Id, First, Last) BEGIN_##Id = First, END_##Id = Last, #include "clang/StaticAnalyzer/Core/PathSensitive/Regions.def" +#undef REGION +#undef REGION_RANGE }; private: @@ -171,6 +174,8 @@ class MemRegion : public llvm::FoldingSetNode { Kind getKind() const { return kind; } + StringRef getKindStr() const; + template const RegionTy* getAs() const; template LLVM_ATTRIBUTE_RETURNS_NONNULL const RegionTy *castAs() const; diff --git a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp index 238e87a712a43..8dd08f14b2728 100644 --- a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp @@ -12,6 +12,7 @@ //===--===// #include "InterCheckerAPI.h" +#include "clang/AST/OperationKinds.h" #include "clang/Basic/Builtins.h" #include "clang/Basic/CharInfo.h" #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h" @@ -22,10 +23,13 @@ #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicExtent.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h" #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h" +#include "llvm/ADT/APSInt.h" #include "llvm/ADT/STLExtras.h" -#include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringExtras.h" +#include "llvm/Support/Casting.h" #include "llvm/Support/raw_ostream.h" #include #include @@ -304,6 +308,10 @@ class CStringChec
[clang] [analyzer] Check the correct first and last elements in cstring.UninitializedRead (PR #95408)
Szelethus wrote: I merget the PR as is, but I'll keep the warning message in mind, I'm open to changing it as we are getting closer to moving out-of-alpha. https://github.com/llvm/llvm-project/pull/95408 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Compiler messages on HIP SDK for Windows (PR #97668)
yxsamliu wrote: better add a lit test like https://github.com/llvm/llvm-project/blob/main/clang/test/Driver/rocm-detect.hip , but for windows only (`REQUIRES: system-windows`), using `--print-rocm-search-dirs`, and checks `ROCm installation search path`. https://github.com/llvm/llvm-project/pull/97668 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] Check the correct first and last elements in cstring.UninitializedRead (PR #95408)
=?utf-8?q?Kristóf?= Umann , =?utf-8?q?Kristóf?= Umann , =?utf-8?q?Kristóf?= Umann , =?utf-8?q?Kristóf?= Umann , =?utf-8?q?Kristóf?= Umann , =?utf-8?q?Kristóf?= Umann Message-ID: In-Reply-To: llvm-ci wrote: LLVM Buildbot has detected a new failure on builder `sanitizer-x86_64-linux` running on `sanitizer-buildbot1` while building `clang` at step 2 "annotate". Full details are available at: https://lab.llvm.org/buildbot/#/builders/66/builds/1014 Here is the relevant piece of the build log for the reference: ``` Step 2 (annotate) failure: 'python ../sanitizer_buildbot/sanitizers/zorg/buildbot/builders/sanitizers/buildbot_selector.py' (failure) ... llvm-lit: /b/sanitizer-x86_64-linux/build/llvm-project/compiler-rt/test/lit.common.cfg.py:60: warning: Path reported by clang does not exist: "/b/sanitizer-x86_64-linux/build/build_default/lib/clang/19/lib/i386-unknown-linux-gnu". This path was found by running ['/b/sanitizer-x86_64-linux/build/build_default/./bin/clang', '--target=x86_64-unknown-linux-gnu', '-m32', '-print-runtime-dir']. llvm-lit: /b/sanitizer-x86_64-linux/build/llvm-project/compiler-rt/test/lit.common.cfg.py:60: warning: Path reported by clang does not exist: "/b/sanitizer-x86_64-linux/build/build_default/lib/clang/19/lib/x86_64-unknown-linux-gnu". This path was found by running ['/b/sanitizer-x86_64-linux/build/build_default/./bin/clang', '--target=x86_64-unknown-linux-gnu', '-m64', '-print-runtime-dir']. llvm-lit: /b/sanitizer-x86_64-linux/build/llvm-project/compiler-rt/test/lit.common.cfg.py:60: warning: Path reported by clang does not exist: "/b/sanitizer-x86_64-linux/build/build_default/lib/clang/19/lib/x86_64-unknown-linux-gnu". This path was found by running ['/b/sanitizer-x86_64-linux/build/build_default/./bin/clang', '--target=x86_64-unknown-linux-gnu', '-Wthread-safety', '-Wthread-safety-reference', '-Wthread-safety-beta', '-print-runtime-dir']. llvm-lit: /b/sanitizer-x86_64-linux/build/llvm-project/compiler-rt/test/lit.common.cfg.py:60: warning: Path reported by clang does not exist: "/b/sanitizer-x86_64-linux/build/build_default/lib/clang/19/lib/x86_64-unknown-linux-gnu". This path was found by running ['/b/sanitizer-x86_64-linux/build/build_default/./bin/clang', '--target=x86_64-unknown-linux-gnu', '-m64', '-print-runtime-dir']. llvm-lit: /b/sanitizer-x86_64-linux/build/llvm-project/compiler-rt/test/lit.common.cfg.py:60: warning: Path reported by clang does not exist: "/b/sanitizer-x86_64-linux/build/build_default/lib/clang/19/lib/x86_64-unknown-linux-gnu". This path was found by running ['/b/sanitizer-x86_64-linux/build/build_default/./bin/clang', '--target=x86_64-unknown-linux-gnu', '-m64', '-print-runtime-dir']. llvm-lit: /b/sanitizer-x86_64-linux/build/llvm-project/compiler-rt/test/lit.common.cfg.py:60: warning: Path reported by clang does not exist: "/b/sanitizer-x86_64-linux/build/build_default/lib/clang/19/lib/x86_64-unknown-linux-gnu". This path was found by running ['/b/sanitizer-x86_64-linux/build/build_default/./bin/clang', '--target=x86_64-unknown-linux-gnu', '-m64', '-print-runtime-dir']. llvm-lit: /b/sanitizer-x86_64-linux/build/llvm-project/compiler-rt/test/lit.common.cfg.py:60: warning: Path reported by clang does not exist: "/b/sanitizer-x86_64-linux/build/build_default/lib/clang/19/lib/x86_64-unknown-linux-gnu". This path was found by running ['/b/sanitizer-x86_64-linux/build/build_default/./bin/clang', '--target=x86_64-unknown-linux-gnu', '-m64', '-print-runtime-dir']. llvm-lit: /b/sanitizer-x86_64-linux/build/llvm-project/llvm/utils/lit/lit/main.py:72: note: The test suite configuration requested an individual test timeout of 0 seconds but a timeout of 900 seconds was requested on the command line. Forcing timeout to be 900 seconds. -- Testing: 9980 tests, 80 workers -- Testing: 0.. 10.. 20.. 30.. 40.. 50.. 60.. FAIL: libFuzzer-i386-libcxx-Linux :: fuzzer-finalstats.test (2202 of 9980) TEST 'libFuzzer-i386-libcxx-Linux :: fuzzer-finalstats.test' FAILED Exit Code: 1 Command Output (stderr): -- RUN: at line 1: /b/sanitizer-x86_64-linux/build/build_default/./bin/clang -Wthread-safety -Wthread-safety-reference -Wthread-safety-beta --driver-mode=g++ -O2 -gline-tables-only -fsanitize=address,fuzzer -I/b/sanitizer-x86_64-linux/build/llvm-project/compiler-rt/lib/fuzzer -m32 /b/sanitizer-x86_64-linux/build/llvm-project/compiler-rt/test/fuzzer/SimpleTest.cpp -o /b/sanitizer-x86_64-linux/build/build_default/runtimes/runtimes-bins/compiler-rt/test/fuzzer/I386LibcxxLinuxConfig/Output/fuzzer-finalstats.test.tmp-SimpleTest + /b/sanitizer-x86_64-linux/build/build_default/./bin/clang -Wthread-safety -Wthread-safety-reference -Wthread-safety-beta --driver-mode=g++ -O2 -gline-tables-only -fsanitize=address,fuzzer -I/b/sanitizer-x86_64-linux/build/llvm-project/compiler-rt/lib/fuzzer -m32 /b/sanitizer-x86_64-linux/build/llvm-project/compiler-rt/test/fuzzer/SimpleTest.c
[clang] [llvm] [AArch64] Implement GCS ACLE intrinsics (PR #96903)
@@ -855,6 +863,25 @@ __rndrrs(uint64_t *__p) { } #endif +/* 11.2 Guarded Control Stack intrinsics */ +#if defined(__ARM_64BIT_STATE) && __ARM_64BIT_STATE +static __inline__ void * __attribute__((__always_inline__, __nodebug__)) +__gcspr() { + return (void *)__builtin_arm_rsr64("gcspr_el0"); +} + +static __inline__ uint64_t __attribute__((__always_inline__, __nodebug__, target("gcs"))) +__gcspopm() { + return __builtin_arm_gcspopm(0); +} + +static __inline__ const void * __attribute__((__always_inline__, __nodebug__, target("gcs"))) +__gcsss(const void *__stack) { + __builtin_arm_gcsss1(__stack); + return __builtin_arm_gcsss2(0); +} lenary wrote: My concerns are: - builtins eventually become a defacto compiler interface, with users using them directly outside of compiler-only headers (and potentially expecting them to be compatible between gcc and clang). Maybe this is fine, as we can reserve the right to break them (but doing so is still not easy)? The other obvious option is to match the builtin to the ACLE intrinsic, and write C++, as you say, which is not as easy but also not necessarily any better as an implementation. - What happens if the compiler ends up separating these two operations? I guess maybe we can leave this until it is a reported problem. Even if we had one operation until isel, we might still have to make sure that reasonable optimisations were prevented post-isel. I realise that the `sideEffects = 1` on the instructions should prevent a lot of these, but I'm not clear on things that should be side-effect safe but might interact with GCS such as Machine Outliner. https://github.com/llvm/llvm-project/pull/96903 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [TBAA] Emit int TBAA metadata on FP math libcall expf (PR #96025)
https://github.com/vfdff updated https://github.com/llvm/llvm-project/pull/96025 >From ed6292fd0e9119322c39e5f37e2225c76e324101 Mon Sep 17 00:00:00 2001 From: zhongyunde 00443407 Date: Tue, 18 Jun 2024 09:21:07 -0400 Subject: [PATCH 1/7] [TBAA] Emit int TBAA metadata on FP math libcalls Base on the discussion https://discourse.llvm.org/t/fp-can-we-add-pure-attribute-for-math-library-functions-default/79459, math libcalls set errno, so it should emit "int" TBAA metadata on FP libcalls to solve the alias issue. Fix https://github.com/llvm/llvm-project/issues/86635 --- clang/lib/CodeGen/CGBuiltin.cpp | 33 ++- clang/test/CodeGen/math-libcalls-tbaa.cpp | 22 +++ 2 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 clang/test/CodeGen/math-libcalls-tbaa.cpp diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp index 08a89bd123d03..dc4af109cdbdb 100644 --- a/clang/lib/CodeGen/CGBuiltin.cpp +++ b/clang/lib/CodeGen/CGBuiltin.cpp @@ -707,7 +707,38 @@ static RValue emitLibraryCall(CodeGenFunction &CGF, const FunctionDecl *FD, const CallExpr *E, llvm::Constant *calleeValue) { CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E); CGCallee callee = CGCallee::forDirect(calleeValue, GlobalDecl(FD)); - return CGF.EmitCall(E->getCallee()->getType(), callee, E, ReturnValueSlot()); + RValue Call = + CGF.EmitCall(E->getCallee()->getType(), callee, E, ReturnValueSlot()); + + // Check the supported intrinsic. + if (unsigned BuiltinID = FD->getBuiltinID()) { +auto IntrinsicID = [&]() -> unsigned { + switch (BuiltinID) { + case Builtin::BIexpf: + case Builtin::BI__builtin_expf: + case Builtin::BI__builtin_expf128: +return true; + } + // TODO: support more FP math libcalls + return false; +}(); + +if (IntrinsicID) { + llvm::MDBuilder MDHelper(CGF.getLLVMContext()); + MDNode *RootMD; + if (CGF.getLangOpts().CPlusPlus) +RootMD = MDHelper.createTBAARoot("Simple C++ TBAA"); + else +RootMD = MDHelper.createTBAARoot("Simple C/C++ TBAA"); + // Emit "int" TBAA metadata on FP math libcalls. + MDNode *AliasType = MDHelper.createTBAANode("int", RootMD); + MDNode *MDInt = MDHelper.createTBAAStructTagNode(AliasType, AliasType, 0); + + Value *Val = Call.getScalarVal(); + cast(Val)->setMetadata(LLVMContext::MD_tbaa, MDInt); +} + } + return Call; } /// Emit a call to llvm.{sadd,uadd,ssub,usub,smul,umul}.with.overflow.* diff --git a/clang/test/CodeGen/math-libcalls-tbaa.cpp b/clang/test/CodeGen/math-libcalls-tbaa.cpp new file mode 100644 index 0..d5b0741a476cb --- /dev/null +++ b/clang/test/CodeGen/math-libcalls-tbaa.cpp @@ -0,0 +1,22 @@ +// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --version 2 +// RUN: %clang -S -O3 -emit-llvm -o - -x c++ %s | FileCheck %s -check-prefixes=CHECK + +#include + + +// Emit int TBAA metadata on FP math libcalls, which is useful for alias analysis + +// CHECK-LABEL: define dso_local noundef float @_Z3fooPffi +// CHECK-SAME: (ptr nocapture noundef readonly [[NUM:%.*]], float noundef [[R2INV:%.*]], i32 noundef [[N:%.*]]) local_unnamed_addr #[[ATTR0:[0-9]+]] { +// CHECK-NEXT: entry: +// CHECK-NEXT:[[ARRAYIDX:%.*]] = getelementptr inbounds i8, ptr [[NUM]], i64 40 +// CHECK-NEXT:[[TMP0:%.*]] = load float, ptr [[ARRAYIDX]], align 4, !tbaa [[TBAA6:![0-9]+]] +// CHECK-NEXT:[[CALL_I:%.*]] = tail call noundef float @expf(float noundef [[TMP0]]) #[[ATTR2:[0-9]+]], !tbaa [[TBAA10:![0-9]+]] +// CHECK-NEXT:[[MUL:%.*]] = fmul float [[TMP0]], [[CALL_I]] +// CHECK-NEXT:ret float [[MUL]] +// +float foo (float num[], float r2inv, int n) { + const float expm2 = std::exp(num[10]); // Emit TBAA metadata on @expf + float tmp = expm2 * num[10]; + return tmp; +} >From 9990877a2b9736c684c8cabeb03c6d98a3d078ce Mon Sep 17 00:00:00 2001 From: zhongyunde 00443407 Date: Thu, 20 Jun 2024 02:29:11 -0400 Subject: [PATCH 2/7] Address comment, reuse CodeGenTBAA::getRoot --- clang/lib/CodeGen/CGBuiltin.cpp | 6 +- clang/lib/CodeGen/CodeGenModule.h | 2 ++ clang/lib/CodeGen/CodeGenTBAA.h | 8 clang/test/CodeGen/math-libcalls-tbaa.cpp | 20 +++- 4 files changed, 22 insertions(+), 14 deletions(-) diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp index dc4af109cdbdb..3f448e11bca1a 100644 --- a/clang/lib/CodeGen/CGBuiltin.cpp +++ b/clang/lib/CodeGen/CGBuiltin.cpp @@ -725,11 +725,7 @@ static RValue emitLibraryCall(CodeGenFunction &CGF, const FunctionDecl *FD, if (IntrinsicID) { llvm::MDBuilder MDHelper(CGF.getLLVMContext()); - MDNode *RootMD; - if (CGF.getLangOpts().CPlusPlus) -RootMD = MDHelper.createTBAARoot("Simple C++ TBAA"); - else -RootMD = MDHelper.createTBAARoot("Si
[clang] [TBAA] Emit int TBAA metadata on FP math libcall expf (PR #96025)
https://github.com/vfdff edited https://github.com/llvm/llvm-project/pull/96025 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][analyzer][doc] Migrate checkers-related docs from HTML to RST (PR #97032)
https://github.com/gamesh411 updated https://github.com/llvm/llvm-project/pull/97032 From b11a113682a1b998395139e5e4736689c0f9be84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Endre=20F=C3=BCl=C3=B6p?= Date: Wed, 26 Jun 2024 11:09:33 +0200 Subject: [PATCH 1/2] [clang][analyzer][doc] Migrate checkers-related docs from HTML to RST Documentation for the checkers is kept up to date in RST files. This patch removes duplication by replacing the HTML docs with links to docs generated from the RST. --- clang/www/analyzer/alpha_checks.html | 932 +--- clang/www/analyzer/available_checks.html | 1736 +- 2 files changed, 2 insertions(+), 2666 deletions(-) diff --git a/clang/www/analyzer/alpha_checks.html b/clang/www/analyzer/alpha_checks.html index 501a9bcbc82a9..80a3ebe4c6166 100644 --- a/clang/www/analyzer/alpha_checks.html +++ b/clang/www/analyzer/alpha_checks.html @@ -17,938 +17,8 @@ -Alpha Checkers -Experimental checkers in addition to the -Default Checkers. These are checkers with known issues or limitations that -keep them from being on by default. They are likely to have false positives. -Bug reports are welcome but will likely not be investigated for some time. -Patches welcome! - -Clone Alpha Checkers -Core Alpha Checkers -C++ Alpha Checkers -LLVM Checkers -Variable Argument Alpha Checkers -Dead Code Alpha Checkers -OS X Alpha Checkers -Security Alpha Checkers -Unix Alpha Checkers -Non-determinism Alpha Checkers - - - -Clone Alpha Checkers - - -Name, DescriptionExample - - - -alpha.clone.CloneChecker -(C, C++, ObjC) -Reports similar pieces of code. - - -void log(); - -int max(int a, int b) { // warn - log(); - if (a > b) -return a; - return b; -} - -int maxClone(int x, int y) { // similar code here - log(); - if (x > y) -return x; - return y; -} - - - - -Core Alpha Checkers - - -Name, DescriptionExample - - - -alpha.core.BoolAssignment -(ObjC) -Warn about assigning non-{0,1} values to boolean variables. - - -void test() { - BOOL b = -1; // warn -} - - - - -alpha.core.CastSize -(C) -Check when casting a malloc'ed type T, whether the size is a multiple of the -size of T (Works only with unix.Malloc -or alpha.unix.MallocWithAnnotations -checks enabled). - - -void test() { - int *x = (int *)malloc(11); // warn -} - - - - -alpha.core.CastToStruct -(C, C++) -Check for cast from non-struct pointer to struct pointer. - - -// C -struct s {}; - -void test(int *p) { - struct s *ps = (struct s *) p; // warn -} - - -// C++ -class c {}; - -void test(int *p) { - c *pc = (c *) p; // warn -} - - - - -alpha.core.Conversion -(C, C++, ObjC) -Loss of sign or precision in implicit conversions - - -void test(unsigned U, signed S) { - if (S > 10) { -if (U < S) { -} - } - if (S < -10) { -if (U < S) { // warn (loss of sign) -} - } -} - - -void test() { - long long A = 1LL << 60; - short X = A; // warn (loss of precision) -} - - - - -alpha.core.DynamicTypeChecker -(ObjC) -Check for cases where the dynamic and the static type of an -object are unrelated. - - -id date = [NSDate date]; - -// Warning: Object has a dynamic type 'NSDate *' which is -// incompatible with static type 'NSNumber *'" -NSNumber *number = date; -[number doubleValue]; - - - - -alpha.core.FixedAddr -(C) -Check for assignment of a fixed address to a pointer. - - -void test() { - int *p; - p = (int *) 0x1; // warn -} - - - - -alpha.core.IdenticalExpr -(C, C++) -Warn about suspicious uses of identical expressions. - - -// C -void test() { - int a = 5; - int b = a | 4 | a; // warn: identical expr on both sides -} - - -// C++ -bool f(void); - -void test(bool b) { - int i = 10; - if (f()) { // warn: true and false branches are identical -do { - i--; -} while (f()); - } else { -do { - i--; -} while (f()); - } -} - - - - -alpha.core.PointerArithm -(C) -Check for pointer arithmetic on locations other than array -elements. - - -void test() { - int x; - int *p; - p = &x + 1; // warn -} - - - - -alpha.core.PointerSub -(C) -Check for pointer subtractions on two pointers pointing to different memory -chunks. - - -void test() { - int x, y; - int d = &y - &x; // warn -} - - - - -alpha.core.StackAddressAsyncEscape -(C) -Check that addresses to stack memory do not escape the function that involves -dispatch_after or dispatch_async. This checker is -a part of core.StackAddressEscape, but is -https://reviews.llvm.org/D41042>temporarily disabled until some -false positives are fixed. - - -dispatch_block_t test_block_inside_block_async_leak() { - int x = 123; - void (^inner)(void) = ^void(void) { -int y = x; -++y; - }; - void (^outer)(void) = ^void(void) { -int z = x; -++z; -inner(); - }; - return outer; // warn: address of stack-allocated block is captured by a -// returned block -} - - - - -alpha.core.TestAfterDivZero -(C, C++, ObjC) -Check for division by variable that is later compared against 0. -Either t
[clang] [llvm] Support branch hint (PR #97721)
https://github.com/fzou1 created https://github.com/llvm/llvm-project/pull/97721 For more details about this feature, please refer to latest Intel 64 and IA-32 Architectures Optimization Reference Manual Volume 1: https://www.intel.com/content/www/us/en/content-details/821612/intel-64-and-ia-32-architectures-optimization-reference-manual-volume-1.html >From 3c75e22504416afae288723aff34120d88b100db Mon Sep 17 00:00:00 2001 From: Feng Zou Date: Thu, 4 Jul 2024 15:43:12 +0800 Subject: [PATCH] Support branch hint For more details about this feature, please refer to latest Intel 64 and IA-32 Architectures Optimization Reference Manual Volume 1: https://www.intel.com/content/www/us/en/content-details/821612/intel-64-and-ia-32-architectures-optimization-reference-manual-volume-1.html --- clang/lib/Basic/Targets/X86.cpp| 3 + clang/lib/Basic/Targets/X86.h | 1 + llvm/lib/Target/X86/X86.td | 13 +++- llvm/lib/Target/X86/X86MCInstLower.cpp | 24 +++ llvm/test/CodeGen/X86/branch-hint.ll | 95 ++ 5 files changed, 133 insertions(+), 3 deletions(-) create mode 100644 llvm/test/CodeGen/X86/branch-hint.ll diff --git a/clang/lib/Basic/Targets/X86.cpp b/clang/lib/Basic/Targets/X86.cpp index 276d492955207..1f6fc842ddd95 100644 --- a/clang/lib/Basic/Targets/X86.cpp +++ b/clang/lib/Basic/Targets/X86.cpp @@ -457,6 +457,8 @@ bool X86TargetInfo::handleTargetFeatures(std::vector &Features, HasCF = true; } else if (Feature == "+zu") { HasZU = true; +} else if (Feature == "+branch-hint") { + HasBranchHint = true; } X86SSEEnum Level = llvm::StringSwitch(Feature) @@ -1292,6 +1294,7 @@ bool X86TargetInfo::hasFeature(StringRef Feature) const { .Case("nf", HasNF) .Case("cf", HasCF) .Case("zu", HasZU) + .Case("branch-hint", HasBranchHint) .Default(false); } diff --git a/clang/lib/Basic/Targets/X86.h b/clang/lib/Basic/Targets/X86.h index 5ce4953251bc3..a70711f4ae2bb 100644 --- a/clang/lib/Basic/Targets/X86.h +++ b/clang/lib/Basic/Targets/X86.h @@ -174,6 +174,7 @@ class LLVM_LIBRARY_VISIBILITY X86TargetInfo : public TargetInfo { bool HasCF = false; bool HasZU = false; bool HasInlineAsmUseGPR32 = false; + bool HasBranchHint = false; protected: llvm::X86::CPUKind CPU = llvm::X86::CK_None; diff --git a/llvm/lib/Target/X86/X86.td b/llvm/lib/Target/X86/X86.td index 68b78c7c44771..fdd7d5f1ee0e7 100644 --- a/llvm/lib/Target/X86/X86.td +++ b/llvm/lib/Target/X86/X86.td @@ -749,6 +749,11 @@ def TuningUseGLMDivSqrtCosts : SubtargetFeature<"use-glm-div-sqrt-costs", "UseGLMDivSqrtCosts", "true", "Use Goldmont specific floating point div/sqrt costs">; +// Starting with Redwood Cove architecture, the branch has branch taken hint +// (i.e., instruction prefix 3EH). +def TuningBranchHint: SubtargetFeature<"branch-hint", "HasBranchHint", "true", +"Target has branch hint feature">; + //===--===// // X86 CPU Families // TODO: Remove these - use general tuning features to determine codegen. @@ -1124,6 +1129,8 @@ def ProcessorFeatures { FeaturePREFETCHI]; list GNRFeatures = !listconcat(SPRFeatures, GNRAdditionalFeatures); + list GNRAdditionalTuning = [TuningBranchHint]; + list GNRTuning = !listconcat(SPRTuning, GNRAdditionalTuning); // Graniterapids D list GNRDAdditionalFeatures = [FeatureAMXCOMPLEX]; @@ -1815,12 +1822,12 @@ def : ProcModel<"pantherlake", AlderlakePModel, def : ProcModel<"clearwaterforest", AlderlakePModel, ProcessorFeatures.CWFFeatures, ProcessorFeatures.ADLTuning>; def : ProcModel<"graniterapids", SapphireRapidsModel, -ProcessorFeatures.GNRFeatures, ProcessorFeatures.SPRTuning>; +ProcessorFeatures.GNRFeatures, ProcessorFeatures.GNRTuning>; def : ProcModel<"emeraldrapids", SapphireRapidsModel, -ProcessorFeatures.SPRFeatures, ProcessorFeatures.SPRTuning>; +ProcessorFeatures.SPRFeatures, ProcessorFeatures.GNRTuning>; foreach P = ["graniterapids-d", "graniterapids_d"] in { def : ProcModel; +ProcessorFeatures.GNRDFeatures, ProcessorFeatures.GNRTuning>; } // AMD CPUs. diff --git a/llvm/lib/Target/X86/X86MCInstLower.cpp b/llvm/lib/Target/X86/X86MCInstLower.cpp index 00f58f9432e4d..34d95573585c9 100644 --- a/llvm/lib/Target/X86/X86MCInstLower.cpp +++ b/llvm/lib/Target/X86/X86MCInstLower.cpp @@ -25,6 +25,7 @@ #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringExtras.h" +#include "llvm/CodeGen/MachineBranchProbabilityInfo.h" #include "llvm/CodeGen/MachineConstantPool.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineModuleInfoImpls.h" @@ -54,6 +55,14 @@ using namespace llvm; +static cl::opt EnableBranchHint("branch-hi
[clang] [llvm] Support branch hint (PR #97721)
llvmbot wrote: @llvm/pr-subscribers-backend-x86 Author: Feng Zou (fzou1) Changes For more details about this feature, please refer to latest Intel 64 and IA-32 Architectures Optimization Reference Manual Volume 1: https://www.intel.com/content/www/us/en/content-details/821612/intel-64-and-ia-32-architectures-optimization-reference-manual-volume-1.html --- Full diff: https://github.com/llvm/llvm-project/pull/97721.diff 5 Files Affected: - (modified) clang/lib/Basic/Targets/X86.cpp (+3) - (modified) clang/lib/Basic/Targets/X86.h (+1) - (modified) llvm/lib/Target/X86/X86.td (+10-3) - (modified) llvm/lib/Target/X86/X86MCInstLower.cpp (+24) - (added) llvm/test/CodeGen/X86/branch-hint.ll (+95) ``diff diff --git a/clang/lib/Basic/Targets/X86.cpp b/clang/lib/Basic/Targets/X86.cpp index 276d492955207..1f6fc842ddd95 100644 --- a/clang/lib/Basic/Targets/X86.cpp +++ b/clang/lib/Basic/Targets/X86.cpp @@ -457,6 +457,8 @@ bool X86TargetInfo::handleTargetFeatures(std::vector &Features, HasCF = true; } else if (Feature == "+zu") { HasZU = true; +} else if (Feature == "+branch-hint") { + HasBranchHint = true; } X86SSEEnum Level = llvm::StringSwitch(Feature) @@ -1292,6 +1294,7 @@ bool X86TargetInfo::hasFeature(StringRef Feature) const { .Case("nf", HasNF) .Case("cf", HasCF) .Case("zu", HasZU) + .Case("branch-hint", HasBranchHint) .Default(false); } diff --git a/clang/lib/Basic/Targets/X86.h b/clang/lib/Basic/Targets/X86.h index 5ce4953251bc3..a70711f4ae2bb 100644 --- a/clang/lib/Basic/Targets/X86.h +++ b/clang/lib/Basic/Targets/X86.h @@ -174,6 +174,7 @@ class LLVM_LIBRARY_VISIBILITY X86TargetInfo : public TargetInfo { bool HasCF = false; bool HasZU = false; bool HasInlineAsmUseGPR32 = false; + bool HasBranchHint = false; protected: llvm::X86::CPUKind CPU = llvm::X86::CK_None; diff --git a/llvm/lib/Target/X86/X86.td b/llvm/lib/Target/X86/X86.td index 68b78c7c44771..fdd7d5f1ee0e7 100644 --- a/llvm/lib/Target/X86/X86.td +++ b/llvm/lib/Target/X86/X86.td @@ -749,6 +749,11 @@ def TuningUseGLMDivSqrtCosts : SubtargetFeature<"use-glm-div-sqrt-costs", "UseGLMDivSqrtCosts", "true", "Use Goldmont specific floating point div/sqrt costs">; +// Starting with Redwood Cove architecture, the branch has branch taken hint +// (i.e., instruction prefix 3EH). +def TuningBranchHint: SubtargetFeature<"branch-hint", "HasBranchHint", "true", +"Target has branch hint feature">; + //===--===// // X86 CPU Families // TODO: Remove these - use general tuning features to determine codegen. @@ -1124,6 +1129,8 @@ def ProcessorFeatures { FeaturePREFETCHI]; list GNRFeatures = !listconcat(SPRFeatures, GNRAdditionalFeatures); + list GNRAdditionalTuning = [TuningBranchHint]; + list GNRTuning = !listconcat(SPRTuning, GNRAdditionalTuning); // Graniterapids D list GNRDAdditionalFeatures = [FeatureAMXCOMPLEX]; @@ -1815,12 +1822,12 @@ def : ProcModel<"pantherlake", AlderlakePModel, def : ProcModel<"clearwaterforest", AlderlakePModel, ProcessorFeatures.CWFFeatures, ProcessorFeatures.ADLTuning>; def : ProcModel<"graniterapids", SapphireRapidsModel, -ProcessorFeatures.GNRFeatures, ProcessorFeatures.SPRTuning>; +ProcessorFeatures.GNRFeatures, ProcessorFeatures.GNRTuning>; def : ProcModel<"emeraldrapids", SapphireRapidsModel, -ProcessorFeatures.SPRFeatures, ProcessorFeatures.SPRTuning>; +ProcessorFeatures.SPRFeatures, ProcessorFeatures.GNRTuning>; foreach P = ["graniterapids-d", "graniterapids_d"] in { def : ProcModel; +ProcessorFeatures.GNRDFeatures, ProcessorFeatures.GNRTuning>; } // AMD CPUs. diff --git a/llvm/lib/Target/X86/X86MCInstLower.cpp b/llvm/lib/Target/X86/X86MCInstLower.cpp index 00f58f9432e4d..34d95573585c9 100644 --- a/llvm/lib/Target/X86/X86MCInstLower.cpp +++ b/llvm/lib/Target/X86/X86MCInstLower.cpp @@ -25,6 +25,7 @@ #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringExtras.h" +#include "llvm/CodeGen/MachineBranchProbabilityInfo.h" #include "llvm/CodeGen/MachineConstantPool.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineModuleInfoImpls.h" @@ -54,6 +55,14 @@ using namespace llvm; +static cl::opt EnableBranchHint("branch-hint", + cl::desc("Enable branch hint."), + cl::init(false), cl::Hidden); +static cl::opt BranchHintProbabilityThreshold( +"branch-hint-probability-threshold", +cl::desc("The probability threshold of enabling branch hint."), +cl::init(50), cl::Hidden); + namespace { /// X86MCInstLower - This class is used to lower an MachineInstr into an MCInst. @@ -244
[clang] [clang][analyzer][doc] Migrate checkers-related docs from HTML to RST (PR #97032)
https://github.com/gamesh411 updated https://github.com/llvm/llvm-project/pull/97032 From b11a113682a1b998395139e5e4736689c0f9be84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Endre=20F=C3=BCl=C3=B6p?= Date: Wed, 26 Jun 2024 11:09:33 +0200 Subject: [PATCH 1/2] [clang][analyzer][doc] Migrate checkers-related docs from HTML to RST Documentation for the checkers is kept up to date in RST files. This patch removes duplication by replacing the HTML docs with links to docs generated from the RST. --- clang/www/analyzer/alpha_checks.html | 932 +--- clang/www/analyzer/available_checks.html | 1736 +- 2 files changed, 2 insertions(+), 2666 deletions(-) diff --git a/clang/www/analyzer/alpha_checks.html b/clang/www/analyzer/alpha_checks.html index 501a9bcbc82a9..80a3ebe4c6166 100644 --- a/clang/www/analyzer/alpha_checks.html +++ b/clang/www/analyzer/alpha_checks.html @@ -17,938 +17,8 @@ -Alpha Checkers -Experimental checkers in addition to the -Default Checkers. These are checkers with known issues or limitations that -keep them from being on by default. They are likely to have false positives. -Bug reports are welcome but will likely not be investigated for some time. -Patches welcome! - -Clone Alpha Checkers -Core Alpha Checkers -C++ Alpha Checkers -LLVM Checkers -Variable Argument Alpha Checkers -Dead Code Alpha Checkers -OS X Alpha Checkers -Security Alpha Checkers -Unix Alpha Checkers -Non-determinism Alpha Checkers - - - -Clone Alpha Checkers - - -Name, DescriptionExample - - - -alpha.clone.CloneChecker -(C, C++, ObjC) -Reports similar pieces of code. - - -void log(); - -int max(int a, int b) { // warn - log(); - if (a > b) -return a; - return b; -} - -int maxClone(int x, int y) { // similar code here - log(); - if (x > y) -return x; - return y; -} - - - - -Core Alpha Checkers - - -Name, DescriptionExample - - - -alpha.core.BoolAssignment -(ObjC) -Warn about assigning non-{0,1} values to boolean variables. - - -void test() { - BOOL b = -1; // warn -} - - - - -alpha.core.CastSize -(C) -Check when casting a malloc'ed type T, whether the size is a multiple of the -size of T (Works only with unix.Malloc -or alpha.unix.MallocWithAnnotations -checks enabled). - - -void test() { - int *x = (int *)malloc(11); // warn -} - - - - -alpha.core.CastToStruct -(C, C++) -Check for cast from non-struct pointer to struct pointer. - - -// C -struct s {}; - -void test(int *p) { - struct s *ps = (struct s *) p; // warn -} - - -// C++ -class c {}; - -void test(int *p) { - c *pc = (c *) p; // warn -} - - - - -alpha.core.Conversion -(C, C++, ObjC) -Loss of sign or precision in implicit conversions - - -void test(unsigned U, signed S) { - if (S > 10) { -if (U < S) { -} - } - if (S < -10) { -if (U < S) { // warn (loss of sign) -} - } -} - - -void test() { - long long A = 1LL << 60; - short X = A; // warn (loss of precision) -} - - - - -alpha.core.DynamicTypeChecker -(ObjC) -Check for cases where the dynamic and the static type of an -object are unrelated. - - -id date = [NSDate date]; - -// Warning: Object has a dynamic type 'NSDate *' which is -// incompatible with static type 'NSNumber *'" -NSNumber *number = date; -[number doubleValue]; - - - - -alpha.core.FixedAddr -(C) -Check for assignment of a fixed address to a pointer. - - -void test() { - int *p; - p = (int *) 0x1; // warn -} - - - - -alpha.core.IdenticalExpr -(C, C++) -Warn about suspicious uses of identical expressions. - - -// C -void test() { - int a = 5; - int b = a | 4 | a; // warn: identical expr on both sides -} - - -// C++ -bool f(void); - -void test(bool b) { - int i = 10; - if (f()) { // warn: true and false branches are identical -do { - i--; -} while (f()); - } else { -do { - i--; -} while (f()); - } -} - - - - -alpha.core.PointerArithm -(C) -Check for pointer arithmetic on locations other than array -elements. - - -void test() { - int x; - int *p; - p = &x + 1; // warn -} - - - - -alpha.core.PointerSub -(C) -Check for pointer subtractions on two pointers pointing to different memory -chunks. - - -void test() { - int x, y; - int d = &y - &x; // warn -} - - - - -alpha.core.StackAddressAsyncEscape -(C) -Check that addresses to stack memory do not escape the function that involves -dispatch_after or dispatch_async. This checker is -a part of core.StackAddressEscape, but is -https://reviews.llvm.org/D41042>temporarily disabled until some -false positives are fixed. - - -dispatch_block_t test_block_inside_block_async_leak() { - int x = 123; - void (^inner)(void) = ^void(void) { -int y = x; -++y; - }; - void (^outer)(void) = ^void(void) { -int z = x; -++z; -inner(); - }; - return outer; // warn: address of stack-allocated block is captured by a -// returned block -} - - - - -alpha.core.TestAfterDivZero -(C, C++, ObjC) -Check for division by variable that is later compared against 0. -Either t
[clang] [clang][analyzer][doc] Migrate checkers-related docs from HTML to RST (PR #97032)
https://github.com/gamesh411 updated https://github.com/llvm/llvm-project/pull/97032 From b11a113682a1b998395139e5e4736689c0f9be84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Endre=20F=C3=BCl=C3=B6p?= Date: Wed, 26 Jun 2024 11:09:33 +0200 Subject: [PATCH 1/2] [clang][analyzer][doc] Migrate checkers-related docs from HTML to RST Documentation for the checkers is kept up to date in RST files. This patch removes duplication by replacing the HTML docs with links to docs generated from the RST. --- clang/www/analyzer/alpha_checks.html | 932 +--- clang/www/analyzer/available_checks.html | 1736 +- 2 files changed, 2 insertions(+), 2666 deletions(-) diff --git a/clang/www/analyzer/alpha_checks.html b/clang/www/analyzer/alpha_checks.html index 501a9bcbc82a9..80a3ebe4c6166 100644 --- a/clang/www/analyzer/alpha_checks.html +++ b/clang/www/analyzer/alpha_checks.html @@ -17,938 +17,8 @@ -Alpha Checkers -Experimental checkers in addition to the -Default Checkers. These are checkers with known issues or limitations that -keep them from being on by default. They are likely to have false positives. -Bug reports are welcome but will likely not be investigated for some time. -Patches welcome! - -Clone Alpha Checkers -Core Alpha Checkers -C++ Alpha Checkers -LLVM Checkers -Variable Argument Alpha Checkers -Dead Code Alpha Checkers -OS X Alpha Checkers -Security Alpha Checkers -Unix Alpha Checkers -Non-determinism Alpha Checkers - - - -Clone Alpha Checkers - - -Name, DescriptionExample - - - -alpha.clone.CloneChecker -(C, C++, ObjC) -Reports similar pieces of code. - - -void log(); - -int max(int a, int b) { // warn - log(); - if (a > b) -return a; - return b; -} - -int maxClone(int x, int y) { // similar code here - log(); - if (x > y) -return x; - return y; -} - - - - -Core Alpha Checkers - - -Name, DescriptionExample - - - -alpha.core.BoolAssignment -(ObjC) -Warn about assigning non-{0,1} values to boolean variables. - - -void test() { - BOOL b = -1; // warn -} - - - - -alpha.core.CastSize -(C) -Check when casting a malloc'ed type T, whether the size is a multiple of the -size of T (Works only with unix.Malloc -or alpha.unix.MallocWithAnnotations -checks enabled). - - -void test() { - int *x = (int *)malloc(11); // warn -} - - - - -alpha.core.CastToStruct -(C, C++) -Check for cast from non-struct pointer to struct pointer. - - -// C -struct s {}; - -void test(int *p) { - struct s *ps = (struct s *) p; // warn -} - - -// C++ -class c {}; - -void test(int *p) { - c *pc = (c *) p; // warn -} - - - - -alpha.core.Conversion -(C, C++, ObjC) -Loss of sign or precision in implicit conversions - - -void test(unsigned U, signed S) { - if (S > 10) { -if (U < S) { -} - } - if (S < -10) { -if (U < S) { // warn (loss of sign) -} - } -} - - -void test() { - long long A = 1LL << 60; - short X = A; // warn (loss of precision) -} - - - - -alpha.core.DynamicTypeChecker -(ObjC) -Check for cases where the dynamic and the static type of an -object are unrelated. - - -id date = [NSDate date]; - -// Warning: Object has a dynamic type 'NSDate *' which is -// incompatible with static type 'NSNumber *'" -NSNumber *number = date; -[number doubleValue]; - - - - -alpha.core.FixedAddr -(C) -Check for assignment of a fixed address to a pointer. - - -void test() { - int *p; - p = (int *) 0x1; // warn -} - - - - -alpha.core.IdenticalExpr -(C, C++) -Warn about suspicious uses of identical expressions. - - -// C -void test() { - int a = 5; - int b = a | 4 | a; // warn: identical expr on both sides -} - - -// C++ -bool f(void); - -void test(bool b) { - int i = 10; - if (f()) { // warn: true and false branches are identical -do { - i--; -} while (f()); - } else { -do { - i--; -} while (f()); - } -} - - - - -alpha.core.PointerArithm -(C) -Check for pointer arithmetic on locations other than array -elements. - - -void test() { - int x; - int *p; - p = &x + 1; // warn -} - - - - -alpha.core.PointerSub -(C) -Check for pointer subtractions on two pointers pointing to different memory -chunks. - - -void test() { - int x, y; - int d = &y - &x; // warn -} - - - - -alpha.core.StackAddressAsyncEscape -(C) -Check that addresses to stack memory do not escape the function that involves -dispatch_after or dispatch_async. This checker is -a part of core.StackAddressEscape, but is -https://reviews.llvm.org/D41042>temporarily disabled until some -false positives are fixed. - - -dispatch_block_t test_block_inside_block_async_leak() { - int x = 123; - void (^inner)(void) = ^void(void) { -int y = x; -++y; - }; - void (^outer)(void) = ^void(void) { -int z = x; -++z; -inner(); - }; - return outer; // warn: address of stack-allocated block is captured by a -// returned block -} - - - - -alpha.core.TestAfterDivZero -(C, C++, ObjC) -Check for division by variable that is later compared against 0. -Either t
[clang] [clang][analyzer][doc] Migrate checkers-related docs from HTML to RST (PR #97032)
@@ -126,7 +126,7 @@ Cocoa & Core Foundation Memory Management Annotations gamesh411 wrote: I am unsure which one to link to, so I opted for less but not misleading information with this edit. https://github.com/llvm/llvm-project/pull/97032 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [AARCH64][SVE] Add intrinsics for SVE LUTI instructions (PR #97058)
https://github.com/Lukacma updated https://github.com/llvm/llvm-project/pull/97058 >From 4a6c4033f7deddcd4094ebde81402960de85bd80 Mon Sep 17 00:00:00 2001 From: Marian Lukac Date: Fri, 28 Jun 2024 10:13:16 + Subject: [PATCH 1/2] [AARCH64][SVE] Add intrinsics for SVE LUTI instructions --- clang/include/clang/Basic/arm_sve.td | 21 +- .../aarch64-sve2-intrinsics/acle_sve2_luti.c | 336 ++ .../acle_sve2_imm_lane.cpp| 32 ++ llvm/include/llvm/IR/IntrinsicsAArch64.td | 20 ++ llvm/lib/Target/AArch64/SVEInstrFormats.td| 37 +- .../CodeGen/AArch64/sve2-intrinsics-luti.ll | 107 ++ 6 files changed, 551 insertions(+), 2 deletions(-) create mode 100644 clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_luti.c create mode 100644 llvm/test/CodeGen/AArch64/sve2-intrinsics-luti.ll diff --git a/clang/include/clang/Basic/arm_sve.td b/clang/include/clang/Basic/arm_sve.td index 94c093d891156..dc999a5bbb3d8 100644 --- a/clang/include/clang/Basic/arm_sve.td +++ b/clang/include/clang/Basic/arm_sve.td @@ -1939,6 +1939,25 @@ def SVTBL2_BF16 : SInst<"svtbl2[_{d}]", "d2u", "b", MergeNone, "", [VerifyRunti def SVTBX_BF16 : SInst<"svtbx[_{d}]", "dddu", "b", MergeNone, "aarch64_sve_tbx", [VerifyRuntimeMode]>; } + + +// SVE2 - Lookup table +let SVETargetGuard = "sve2,lut", SMETargetGuard = "sme2,lut" in { + def SVLUTI2_B : SInst<"svluti2_lane[_{d}]", "dd[i", "cUc", MergeNone, "aarch64_sve_luti2_lane", [VerifyRuntimeMode], [ImmCheck<2, ImmCheck0_3>]>; + def SVLUTI2_H : SInst<"svluti2_lane[_{d}]", "dd[i", "sUsh", MergeNone, "aarch64_sve_luti2_lane", [VerifyRuntimeMode], [ImmCheck<2, ImmCheck0_7>]>; + + def SVLUTI4_B : SInst<"svluti4_lane[_{d}]", "dd[i", "cUc", MergeNone, "aarch64_sve_luti4_lane", [VerifyRuntimeMode], [ImmCheck<2, ImmCheck0_1>]>; + def SVLUTI4_H : SInst<"svluti4_lane[_{d}]", "dd[i", "sUsh", MergeNone, "aarch64_sve_luti4_lane", [VerifyRuntimeMode], [ImmCheck<2, ImmCheck0_3>]>; + + def SVLUTI4_x2 : SInst<"svluti4_lane[_{d}]_x2", "d2.d[i", "sUsh", MergeNone, "aarch64_sve_luti4_lane_x2", [VerifyRuntimeMode], [ImmCheck<2, ImmCheck0_3>]>; +} + +let SVETargetGuard = "sve2,lut,bf16", SMETargetGuard = "sme2,lut,bf16" in { + def SVLUTI2_BF16 : SInst<"svluti2_lane[_{d}]", "dd[i", "b", MergeNone, "aarch64_sve_luti2_lane", [ VerifyRuntimeMode], [ImmCheck<2, ImmCheck0_7>]>; + def SVLUTI4_BF16 : SInst<"svluti4_lane[_{d}]", "dd[i", "b", MergeNone, "aarch64_sve_luti4_lane", [ VerifyRuntimeMode], [ImmCheck<2, ImmCheck0_3>]>; + def SVLUTI4_BF16_x2 : SInst<"svluti4_lane[_{d}]_x2", "d2.d[i", "b", MergeNone, "aarch64_sve_luti4_lane_x2", [ VerifyRuntimeMode], [ImmCheck<2, ImmCheck0_3>]>; +} + // SVE2 - Optional @@ -2384,4 +2403,4 @@ let SVETargetGuard = "sve2p1", SMETargetGuard = "sme2" in { def SVBFMLSLB_LANE : SInst<"svbfmlslb_lane[_{d}]", "dd$$i", "f", MergeNone, "aarch64_sve_bfmlslb_lane", [IsOverloadNone, VerifyRuntimeMode], [ImmCheck<3, ImmCheck0_7>]>; def SVBFMLSLT_LANE : SInst<"svbfmlslt_lane[_{d}]", "dd$$i", "f", MergeNone, "aarch64_sve_bfmlslt_lane", [IsOverloadNone, VerifyRuntimeMode], [ImmCheck<3, ImmCheck0_7>]>; -} +} \ No newline at end of file diff --git a/clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_luti.c b/clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_luti.c new file mode 100644 index 0..d19246cba2d37 --- /dev/null +++ b/clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_luti.c @@ -0,0 +1,336 @@ +// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py +// REQUIRES: aarch64-registered-target +// RUN: %clang_cc1 -fclang-abi-compat=latest -triple aarch64-none-linux-gnu \ +// RUN: -target-feature +sme -target-feature +sme2 -target-feature +lut -target-feature +bf16 -O1 -Werror -emit-llvm -o - %s | FileCheck %s +// RUN: %clang_cc1 -fclang-abi-compat=latest -DSVE_OVERLOADED_FORMS -triple aarch64-none-linux-gnu \ +// RUN: -target-feature +sve -target-feature +sve2 -target-feature +lut -target-feature +bf16 -O1 -Werror -emit-llvm -o - %s | FileCheck %s +// RUN: %clang_cc1 -fclang-abi-compat=latest -triple aarch64-none-linux-gnu \ +// RUN: -target-feature +sve -target-feature +sve2 -target-feature +lut -target-feature +bf16 -O1 -Werror -emit-llvm -o - -x c++ %s | FileCheck %s -check-prefix=CPP-CHECK +// RUN: %clang_cc1 -fclang-abi-compat=latest -DSVE_OVERLOADED_FORMS -triple aarch64-none-linux-gnu \ +// RUN: -target-feature +sve -target-feature +sve2 -target-feature +lut -target-feature +bf16 -O1 -Werror -emit-llvm -o - -x c++ %s | FileCheck %s -check-prefix=CPP-CHECK +#include + +#if defined __ARM_FEATURE_SME +#define MODE_ATTR __arm_streaming +#else +#define MODE_ATTR +#endif + +#ifdef SVE_OVERLOADED_FORMS +// A simple used,unused... macro, long enough to represent any SVE builtin. +#d
[clang] [llvm] [AARCH64][SVE] Add intrinsics for SVE LUTI instructions (PR #97058)
@@ -0,0 +1,336 @@ +// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py +// REQUIRES: aarch64-registered-target +// RUN: %clang_cc1 -fclang-abi-compat=latest -triple aarch64-none-linux-gnu \ +// RUN: -target-feature +sme -target-feature +sme2 -target-feature +lut -target-feature +bf16 -O1 -Werror -emit-llvm -o - %s | FileCheck %s +// RUN: %clang_cc1 -fclang-abi-compat=latest -DSVE_OVERLOADED_FORMS -triple aarch64-none-linux-gnu \ +// RUN: -target-feature +sve -target-feature +sve2 -target-feature +lut -target-feature +bf16 -O1 -Werror -emit-llvm -o - %s | FileCheck %s +// RUN: %clang_cc1 -fclang-abi-compat=latest -triple aarch64-none-linux-gnu \ +// RUN: -target-feature +sve -target-feature +sve2 -target-feature +lut -target-feature +bf16 -O1 -Werror -emit-llvm -o - -x c++ %s | FileCheck %s -check-prefix=CPP-CHECK +// RUN: %clang_cc1 -fclang-abi-compat=latest -DSVE_OVERLOADED_FORMS -triple aarch64-none-linux-gnu \ +// RUN: -target-feature +sve -target-feature +sve2 -target-feature +lut -target-feature +bf16 -O1 -Werror -emit-llvm -o - -x c++ %s | FileCheck %s -check-prefix=CPP-CHECK +#include Lukacma wrote: doen https://github.com/llvm/llvm-project/pull/97058 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][analyzer][doc] Migrate checkers-related docs from HTML to RST (PR #97032)
https://github.com/gamesh411 closed https://github.com/llvm/llvm-project/pull/97032 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [AARCH64][SVE] Add intrinsics for SVE LUTI instructions (PR #97058)
@@ -10349,6 +10349,16 @@ multiclass sve2_luti2_vector_index { let Inst{23-22} = idx{2-1}; let Inst{12}= idx{0}; } + Lukacma wrote: I am not sure I understood this, but I removed extra whitespaces https://github.com/llvm/llvm-project/pull/97058 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 3cab132 - [clang][analyzer][doc] Migrate checkers-related docs from HTML to RST (#97032)
Author: Endre Fülöp Date: 2024-07-04T15:02:28+02:00 New Revision: 3cab132e94d3c63dbcf20d2acc4879b2b98a0de9 URL: https://github.com/llvm/llvm-project/commit/3cab132e94d3c63dbcf20d2acc4879b2b98a0de9 DIFF: https://github.com/llvm/llvm-project/commit/3cab132e94d3c63dbcf20d2acc4879b2b98a0de9.diff LOG: [clang][analyzer][doc] Migrate checkers-related docs from HTML to RST (#97032) Documentation for the checkers is kept up to date in RST files. This patch removes duplication by replacing the HTML docs with links to docs generated from the RST. Added: Modified: clang/www/analyzer/alpha_checks.html clang/www/analyzer/available_checks.html Removed: diff --git a/clang/www/analyzer/alpha_checks.html b/clang/www/analyzer/alpha_checks.html index 501a9bcbc82a9..1ee44c7d355ba 100644 --- a/clang/www/analyzer/alpha_checks.html +++ b/clang/www/analyzer/alpha_checks.html @@ -2,7 +2,9 @@ "http://www.w3.org/TR/html4/strict.dtd";> - Alpha Checks + Alpha Checkers documentation has moved to clang.llvm.org + https://clang.llvm.org/docs/analyzer/checkers.html#experimental-checkers"/> + https://clang.llvm.org/docs/analyzer/checkers.html#experimental-checkers"; /> @@ -17,938 +19,11 @@ -Alpha Checkers -Experimental checkers in addition to the -Default Checkers. These are checkers with known issues or limitations that -keep them from being on by default. They are likely to have false positives. -Bug reports are welcome but will likely not be investigated for some time. -Patches welcome! - -Clone Alpha Checkers -Core Alpha Checkers -C++ Alpha Checkers -LLVM Checkers -Variable Argument Alpha Checkers -Dead Code Alpha Checkers -OS X Alpha Checkers -Security Alpha Checkers -Unix Alpha Checkers -Non-determinism Alpha Checkers - - - -Clone Alpha Checkers - - -Name, DescriptionExample - - - -alpha.clone.CloneChecker -(C, C++, ObjC) -Reports similar pieces of code. - - -void log(); - -int max(int a, int b) { // warn - log(); - if (a > b) -return a; - return b; -} - -int maxClone(int x, int y) { // similar code here - log(); - if (x > y) -return x; - return y; -} - - - - -Core Alpha Checkers - - -Name, DescriptionExample - - - -alpha.core.BoolAssignment -(ObjC) -Warn about assigning non-{0,1} values to boolean variables. - - -void test() { - BOOL b = -1; // warn -} - - - - -alpha.core.CastSize -(C) -Check when casting a malloc'ed type T, whether the size is a multiple of the -size of T (Works only with unix.Malloc -or alpha.unix.MallocWithAnnotations -checks enabled). - - -void test() { - int *x = (int *)malloc(11); // warn -} - - - - -alpha.core.CastToStruct -(C, C++) -Check for cast from non-struct pointer to struct pointer. - - -// C -struct s {}; - -void test(int *p) { - struct s *ps = (struct s *) p; // warn -} - - -// C++ -class c {}; - -void test(int *p) { - c *pc = (c *) p; // warn -} - - - - -alpha.core.Conversion -(C, C++, ObjC) -Loss of sign or precision in implicit conversions - - -void test(unsigned U, signed S) { - if (S > 10) { -if (U < S) { -} - } - if (S < -10) { -if (U < S) { // warn (loss of sign) -} - } -} - - -void test() { - long long A = 1LL << 60; - short X = A; // warn (loss of precision) -} - - - - -alpha.core.DynamicTypeChecker -(ObjC) -Check for cases where the dynamic and the static type of an -object are unrelated. - - -id date = [NSDate date]; - -// Warning: Object has a dynamic type 'NSDate *' which is -// incompatible with static type 'NSNumber *'" -NSNumber *number = date; -[number doubleValue]; - - - - -alpha.core.FixedAddr -(C) -Check for assignment of a fixed address to a pointer. - - -void test() { - int *p; - p = (int *) 0x1; // warn -} - - - - -alpha.core.IdenticalExpr -(C, C++) -Warn about suspicious uses of identical expressions. - - -// C -void test() { - int a = 5; - int b = a | 4 | a; // warn: identical expr on both sides -} - - -// C++ -bool f(void); - -void test(bool b) { - int i = 10; - if (f()) { // warn: true and false branches are identical -do { - i--; -} while (f()); - } else { -do { - i--; -} while (f()); - } -} - - - - -alpha.core.PointerArithm -(C) -Check for pointer arithmetic on locations other than array -elements. - - -void test() { - int x; - int *p; - p = &x + 1; // warn -} - - - - -alpha.core.PointerSub -(C) -Check for pointer subtractions on two pointers pointing to diff erent memory -chunks. - - -void test() { - int x, y; - int d = &y - &x; // warn -} - - - - -alpha.core.StackAddressAsyncEscape -(C) -Check that addresses to stack memory do not escape the function that involves -dispatch_after or dispatch_async. This checker is -a part of core.StackAddressEscape, but is -https://reviews.llvm.org/D41042>temporarily disabled until some -false positives are fixed. - - -dispatch_block_t test_block_inside_block_async_leak() { - int x = 123; - void
[clang] [llvm] [AARCH64][SVE] Add intrinsics for SVE LUTI instructions (PR #97058)
https://github.com/Lukacma updated https://github.com/llvm/llvm-project/pull/97058 >From 4a6c4033f7deddcd4094ebde81402960de85bd80 Mon Sep 17 00:00:00 2001 From: Marian Lukac Date: Fri, 28 Jun 2024 10:13:16 + Subject: [PATCH 1/2] [AARCH64][SVE] Add intrinsics for SVE LUTI instructions --- clang/include/clang/Basic/arm_sve.td | 21 +- .../aarch64-sve2-intrinsics/acle_sve2_luti.c | 336 ++ .../acle_sve2_imm_lane.cpp| 32 ++ llvm/include/llvm/IR/IntrinsicsAArch64.td | 20 ++ llvm/lib/Target/AArch64/SVEInstrFormats.td| 37 +- .../CodeGen/AArch64/sve2-intrinsics-luti.ll | 107 ++ 6 files changed, 551 insertions(+), 2 deletions(-) create mode 100644 clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_luti.c create mode 100644 llvm/test/CodeGen/AArch64/sve2-intrinsics-luti.ll diff --git a/clang/include/clang/Basic/arm_sve.td b/clang/include/clang/Basic/arm_sve.td index 94c093d891156..dc999a5bbb3d8 100644 --- a/clang/include/clang/Basic/arm_sve.td +++ b/clang/include/clang/Basic/arm_sve.td @@ -1939,6 +1939,25 @@ def SVTBL2_BF16 : SInst<"svtbl2[_{d}]", "d2u", "b", MergeNone, "", [VerifyRunti def SVTBX_BF16 : SInst<"svtbx[_{d}]", "dddu", "b", MergeNone, "aarch64_sve_tbx", [VerifyRuntimeMode]>; } + + +// SVE2 - Lookup table +let SVETargetGuard = "sve2,lut", SMETargetGuard = "sme2,lut" in { + def SVLUTI2_B : SInst<"svluti2_lane[_{d}]", "dd[i", "cUc", MergeNone, "aarch64_sve_luti2_lane", [VerifyRuntimeMode], [ImmCheck<2, ImmCheck0_3>]>; + def SVLUTI2_H : SInst<"svluti2_lane[_{d}]", "dd[i", "sUsh", MergeNone, "aarch64_sve_luti2_lane", [VerifyRuntimeMode], [ImmCheck<2, ImmCheck0_7>]>; + + def SVLUTI4_B : SInst<"svluti4_lane[_{d}]", "dd[i", "cUc", MergeNone, "aarch64_sve_luti4_lane", [VerifyRuntimeMode], [ImmCheck<2, ImmCheck0_1>]>; + def SVLUTI4_H : SInst<"svluti4_lane[_{d}]", "dd[i", "sUsh", MergeNone, "aarch64_sve_luti4_lane", [VerifyRuntimeMode], [ImmCheck<2, ImmCheck0_3>]>; + + def SVLUTI4_x2 : SInst<"svluti4_lane[_{d}]_x2", "d2.d[i", "sUsh", MergeNone, "aarch64_sve_luti4_lane_x2", [VerifyRuntimeMode], [ImmCheck<2, ImmCheck0_3>]>; +} + +let SVETargetGuard = "sve2,lut,bf16", SMETargetGuard = "sme2,lut,bf16" in { + def SVLUTI2_BF16 : SInst<"svluti2_lane[_{d}]", "dd[i", "b", MergeNone, "aarch64_sve_luti2_lane", [ VerifyRuntimeMode], [ImmCheck<2, ImmCheck0_7>]>; + def SVLUTI4_BF16 : SInst<"svluti4_lane[_{d}]", "dd[i", "b", MergeNone, "aarch64_sve_luti4_lane", [ VerifyRuntimeMode], [ImmCheck<2, ImmCheck0_3>]>; + def SVLUTI4_BF16_x2 : SInst<"svluti4_lane[_{d}]_x2", "d2.d[i", "b", MergeNone, "aarch64_sve_luti4_lane_x2", [ VerifyRuntimeMode], [ImmCheck<2, ImmCheck0_3>]>; +} + // SVE2 - Optional @@ -2384,4 +2403,4 @@ let SVETargetGuard = "sve2p1", SMETargetGuard = "sme2" in { def SVBFMLSLB_LANE : SInst<"svbfmlslb_lane[_{d}]", "dd$$i", "f", MergeNone, "aarch64_sve_bfmlslb_lane", [IsOverloadNone, VerifyRuntimeMode], [ImmCheck<3, ImmCheck0_7>]>; def SVBFMLSLT_LANE : SInst<"svbfmlslt_lane[_{d}]", "dd$$i", "f", MergeNone, "aarch64_sve_bfmlslt_lane", [IsOverloadNone, VerifyRuntimeMode], [ImmCheck<3, ImmCheck0_7>]>; -} +} \ No newline at end of file diff --git a/clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_luti.c b/clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_luti.c new file mode 100644 index 0..d19246cba2d37 --- /dev/null +++ b/clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_luti.c @@ -0,0 +1,336 @@ +// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py +// REQUIRES: aarch64-registered-target +// RUN: %clang_cc1 -fclang-abi-compat=latest -triple aarch64-none-linux-gnu \ +// RUN: -target-feature +sme -target-feature +sme2 -target-feature +lut -target-feature +bf16 -O1 -Werror -emit-llvm -o - %s | FileCheck %s +// RUN: %clang_cc1 -fclang-abi-compat=latest -DSVE_OVERLOADED_FORMS -triple aarch64-none-linux-gnu \ +// RUN: -target-feature +sve -target-feature +sve2 -target-feature +lut -target-feature +bf16 -O1 -Werror -emit-llvm -o - %s | FileCheck %s +// RUN: %clang_cc1 -fclang-abi-compat=latest -triple aarch64-none-linux-gnu \ +// RUN: -target-feature +sve -target-feature +sve2 -target-feature +lut -target-feature +bf16 -O1 -Werror -emit-llvm -o - -x c++ %s | FileCheck %s -check-prefix=CPP-CHECK +// RUN: %clang_cc1 -fclang-abi-compat=latest -DSVE_OVERLOADED_FORMS -triple aarch64-none-linux-gnu \ +// RUN: -target-feature +sve -target-feature +sve2 -target-feature +lut -target-feature +bf16 -O1 -Werror -emit-llvm -o - -x c++ %s | FileCheck %s -check-prefix=CPP-CHECK +#include + +#if defined __ARM_FEATURE_SME +#define MODE_ATTR __arm_streaming +#else +#define MODE_ATTR +#endif + +#ifdef SVE_OVERLOADED_FORMS +// A simple used,unused... macro, long enough to represent any SVE builtin. +#d
[clang] [llvm] Support branch hint (PR #97721)
@@ -749,6 +749,11 @@ def TuningUseGLMDivSqrtCosts : SubtargetFeature<"use-glm-div-sqrt-costs", "UseGLMDivSqrtCosts", "true", "Use Goldmont specific floating point div/sqrt costs">; +// Starting with Redwood Cove architecture, the branch has branch taken hint +// (i.e., instruction prefix 3EH). +def TuningBranchHint: SubtargetFeature<"branch-hint", "HasBranchHint", "true", RKSimon wrote: Why have you added this as a Tuning bit and not a Feature bit? Tuning bits are guaranteed to work on all applicable CPUs - they just might not be performant. https://github.com/llvm/llvm-project/pull/97721 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [X86] Support branch hint (PR #97721)
https://github.com/RKSimon edited https://github.com/llvm/llvm-project/pull/97721 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Support --sysroot= for ${arch}-windows-msvc targets (PR #96417)
zmodem wrote: Backing up a bit, where is the sysroot directory that this `--sysroot` flag for windows-msvc points to supposed to come from? I thought this was for pointing clang to an MSVC installation, similar to clang-cl's /winsysroot, but it looks like the code is doing something else. https://github.com/llvm/llvm-project/pull/96417 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] f329e3e - [clang-tidy] Add `bugprone-pointer-arithmetic-on-polymorphic-object` check (#91951)
Author: Discookie Date: 2024-07-04T13:44:31Z New Revision: f329e3ed9070aee3f4c0ebc80ed62f5c4b645d73 URL: https://github.com/llvm/llvm-project/commit/f329e3ed9070aee3f4c0ebc80ed62f5c4b645d73 DIFF: https://github.com/llvm/llvm-project/commit/f329e3ed9070aee3f4c0ebc80ed62f5c4b645d73.diff LOG: [clang-tidy] Add `bugprone-pointer-arithmetic-on-polymorphic-object` check (#91951) Finds pointer arithmetic on classes that declare a virtual function. This check corresponds to the SEI Cert rule [CTR56-CPP: Do not use pointer arithmetic on polymorphic objects](https://wiki.sei.cmu.edu/confluence/display/cplusplus/CTR56-CPP.+Do+not+use+pointer+arithmetic+on+polymorphic+objects). ```cpp struct Base { virtual void ~Base(); }; struct Derived : public Base {}; void foo(Base *b) { b += 1; // passing `Derived` to `foo()` results in UB } ``` [Results on open-source projects](https://codechecker-demo.eastus.cloudapp.azure.com/Default/runs?run=Discookie-ctr56-with-classnames). Most of the Qtbase reports are from having a `virtual override` declaration, and the LLVM reports are true positives, as far as I can tell. Added: clang-tools-extra/clang-tidy/bugprone/PointerArithmeticOnPolymorphicObjectCheck.cpp clang-tools-extra/clang-tidy/bugprone/PointerArithmeticOnPolymorphicObjectCheck.h clang-tools-extra/docs/clang-tidy/checks/bugprone/pointer-arithmetic-on-polymorphic-object.rst clang-tools-extra/docs/clang-tidy/checks/cert/ctr56-cpp.rst clang-tools-extra/test/clang-tidy/checkers/bugprone/pointer-arithmetic-on-polymorphic-object-all.cpp clang-tools-extra/test/clang-tidy/checkers/bugprone/pointer-arithmetic-on-polymorphic-object-decl-only.cpp Modified: clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt clang-tools-extra/clang-tidy/cert/CERTTidyModule.cpp clang-tools-extra/docs/ReleaseNotes.rst clang-tools-extra/docs/clang-tidy/checks/list.rst Removed: diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp index 1b92d2e60cc17..689eb92a3d8d1 100644 --- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp @@ -51,6 +51,7 @@ #include "NotNullTerminatedResultCheck.h" #include "OptionalValueConversionCheck.h" #include "ParentVirtualCallCheck.h" +#include "PointerArithmeticOnPolymorphicObjectCheck.h" #include "PosixReturnCheck.h" #include "RedundantBranchConditionCheck.h" #include "ReservedIdentifierCheck.h" @@ -171,6 +172,8 @@ class BugproneModule : public ClangTidyModule { "bugprone-multiple-statement-macro"); CheckFactories.registerCheck( "bugprone-optional-value-conversion"); +CheckFactories.registerCheck( +"bugprone-pointer-arithmetic-on-polymorphic-object"); CheckFactories.registerCheck( "bugprone-redundant-branch-condition"); CheckFactories.registerCheck( diff --git a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt index 2d303191f8865..cb0d8ae98bac5 100644 --- a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt +++ b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt @@ -48,6 +48,7 @@ add_clang_library(clangTidyBugproneModule NotNullTerminatedResultCheck.cpp OptionalValueConversionCheck.cpp ParentVirtualCallCheck.cpp + PointerArithmeticOnPolymorphicObjectCheck.cpp PosixReturnCheck.cpp RedundantBranchConditionCheck.cpp ReservedIdentifierCheck.cpp diff --git a/clang-tools-extra/clang-tidy/bugprone/PointerArithmeticOnPolymorphicObjectCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/PointerArithmeticOnPolymorphicObjectCheck.cpp new file mode 100644 index 0..6e6ad10fabbb3 --- /dev/null +++ b/clang-tools-extra/clang-tidy/bugprone/PointerArithmeticOnPolymorphicObjectCheck.cpp @@ -0,0 +1,81 @@ +//===--- PointerArithmeticOnPolymorphicObjectCheck.cpp - clang-tidy===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "PointerArithmeticOnPolymorphicObjectCheck.h" +#include "clang/AST/ASTContext.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::bugprone { + +namespace { +AST_MATCHER(CXXRecordDecl, isAbstract) { return Node.isAbstract(); } +AST_MATCHER(CXXRecordDecl, isPolymorphic) { return Node.isPolymorphic(); } +} // namespace + +PointerArithmeticOnPolymorphicObjectCheck:: +PointerArithmeticOnPolymorphicObjectCheck(StringRef Name, +
[clang-tools-extra] [clang-tidy] Add `bugprone-pointer-arithmetic-on-polymorphic-object` check (PR #91951)
https://github.com/Discookie closed https://github.com/llvm/llvm-project/pull/91951 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [X86] Support branch hint (PR #97721)
@@ -749,6 +749,11 @@ def TuningUseGLMDivSqrtCosts : SubtargetFeature<"use-glm-div-sqrt-costs", "UseGLMDivSqrtCosts", "true", "Use Goldmont specific floating point div/sqrt costs">; +// Starting with Redwood Cove architecture, the branch has branch taken hint +// (i.e., instruction prefix 3EH). +def TuningBranchHint: SubtargetFeature<"branch-hint", "HasBranchHint", "true", KanRobert wrote: We can always add `0x3e` to JCC in 64-bit mode. So it does work on all applicable CPUs. https://github.com/llvm/llvm-project/pull/97721 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Parser][ObjC] Add -Wobjc-prefix-length warning option. (PR #97597)
https://github.com/al45tair updated https://github.com/llvm/llvm-project/pull/97597 >From 02f7c5ef71b382866e02037ce82c85fa6fcbb394 Mon Sep 17 00:00:00 2001 From: Alastair Houghton Date: Wed, 3 Jul 2024 17:00:51 +0100 Subject: [PATCH 1/4] [Parser][ObjC] Add -Wobjc-prefix-length warning option. This lets clang generate warnings automatically if it sees Objective-C names that don't have the correct prefix length. rdar://131055157 --- clang/include/clang/Basic/DiagnosticGroups.td | 1 + .../clang/Basic/DiagnosticParseKinds.td | 7 ++ clang/include/clang/Basic/LangOptions.def | 2 + clang/include/clang/Driver/Options.td | 7 ++ clang/include/clang/Parse/Parser.h| 1 + clang/lib/Driver/ToolChains/Clang.cpp | 1 + clang/lib/Parse/ParseObjc.cpp | 65 +++ clang/test/Parser/objc-prefixes.m | 62 ++ 8 files changed, 146 insertions(+) create mode 100644 clang/test/Parser/objc-prefixes.m diff --git a/clang/include/clang/Basic/DiagnosticGroups.td b/clang/include/clang/Basic/DiagnosticGroups.td index 9431eea1f6be2..0d944434cda38 100644 --- a/clang/include/clang/Basic/DiagnosticGroups.td +++ b/clang/include/clang/Basic/DiagnosticGroups.td @@ -598,6 +598,7 @@ def ObjCPointerIntrospect : DiagGroup<"deprecated-objc-pointer-introspection", [ def ObjCMultipleMethodNames : DiagGroup<"objc-multiple-method-names">; def ObjCFlexibleArray : DiagGroup<"objc-flexible-array">; def ObjCBoxing : DiagGroup<"objc-boxing">; +def ObjCPrefixLength : DiagGroup<"objc-prefix-length">; def CompletionHandler : DiagGroup<"completion-handler">; def CalledOnceParameter : DiagGroup<"called-once-parameter", [CompletionHandler]>; def OpenCLUnsupportedRGBA: DiagGroup<"opencl-unsupported-rgba">; diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td b/clang/include/clang/Basic/DiagnosticParseKinds.td index 12aab09f28556..7e26bd13f9c7b 100644 --- a/clang/include/clang/Basic/DiagnosticParseKinds.td +++ b/clang/include/clang/Basic/DiagnosticParseKinds.td @@ -563,6 +563,13 @@ def err_declaration_does_not_declare_param : Error< "declaration does not declare a parameter">; def err_no_matching_param : Error<"parameter named %0 is missing">; +def warn_objc_unprefixed_class_name : Warning< + "un-prefixed Objective-C class name">, + InGroup; +def warn_objc_unprefixed_protocol_name : Warning< + "un-prefixed Objective-C protocol name">, + InGroup; + /// Objective-C++ parser diagnostics def err_expected_token_instead_of_objcxx_keyword : Error< "expected %0; %1 is a keyword in Objective-C++">; diff --git a/clang/include/clang/Basic/LangOptions.def b/clang/include/clang/Basic/LangOptions.def index 491759e2fcdbb..9df19b01f0b22 100644 --- a/clang/include/clang/Basic/LangOptions.def +++ b/clang/include/clang/Basic/LangOptions.def @@ -351,6 +351,8 @@ LANGOPT(ObjCAutoRefCount , 1, 0, "Objective-C automated reference counting") LANGOPT(ObjCWeakRuntime , 1, 0, "__weak support in the ARC runtime") LANGOPT(ObjCWeak, 1, 0, "Objective-C __weak in ARC and MRC files") LANGOPT(ObjCSubscriptingLegacyRuntime , 1, 0, "Subscripting support in legacy ObjectiveC runtime") +BENIGN_LANGOPT(ObjCPrefixLength, 32, 0, + "if non-zero, warn about Objective-C classes or protocols with names that do not have a prefix of the specified length.") BENIGN_LANGOPT(CompatibilityQualifiedIdBlockParamTypeChecking, 1, 0, "compatibility mode for type checking block parameters " "involving qualified id types") diff --git a/clang/include/clang/Driver/Options.td b/clang/include/clang/Driver/Options.td index 1ede75d3782cd..829efafd03a2c 100644 --- a/clang/include/clang/Driver/Options.td +++ b/clang/include/clang/Driver/Options.td @@ -3418,6 +3418,13 @@ defm objc_exceptions : BoolFOption<"objc-exceptions", PosFlag, NegFlag>; +def Wobjc_prefix_length_EQ: + Joined<["-"], "Wobjc-prefix-length=">, + Visibility<[ClangOption, CC1Option]>, + MetaVarName<"">, + HelpText<"Warn if Objective-C class or protocol names do not start with a prefix of the specified length">, + MarshallingInfoInt>; + defm application_extension : BoolFOption<"application-extension", LangOpts<"AppExt">, DefaultFalse, PosFlaggetBeginLoc(), diag::note_objc_container_start) << (int)ock; } +/// An Objective-C public name (a class name or protocol name) is +/// expected to have a prefix as all names are in a single global +/// namespace. +/// +/// If the -Wobjc-prefix-length is set to N, the name must start +/// with N+1 capital letters, which must be followed by a character +/// that is not a capital letter. +/// +/// For instance, for N set to 2, the following are valid: +/// +/// NSString +/// NSArray +/// +/// but these are not: +/// +/// MyString +/// NSKString +/// NSnotAString +/// +/// We make a special exception for NSCF things when the prefix is set +//
[clang] [TBAA] Emit int TBAA metadata on FP math libcall expf (PR #96025)
@@ -0,0 +1,43 @@ +// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --version 5 +// The test may fail as time out on windows +// REQUIRES: system-linux + +// RUN: %clang -S -O3 -emit-llvm -o - -x c++ %s | FileCheck %s -check-prefixes=CHECK,NoNewStructPathTBAA +// RUN: %clang -S -O3 -Xclang -new-struct-path-tbaa -emit-llvm -o - -x c++ %s | FileCheck %s -check-prefixes=CHECK,NewStructPathTBAA + vfdff wrote: hi @zahiraam, It still fail wtih run timeout for window, so would it be better to add this restriction? https://github.com/llvm/llvm-project/pull/96025 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] fix the unexpected controlflow in `ParseTentative.cpp` (PR #95917)
nikic wrote: The TryParseProtocolQualifiers code path can be reached using something like this: ``` struct X { }; void foo() { X; } ``` But I don't know how to make that valid code without it taking some different code path... https://github.com/llvm/llvm-project/pull/95917 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Implement P3144R2 "Deleting a Pointer to an Incomplete Type..." (PR #97733)
https://github.com/Endilll created https://github.com/llvm/llvm-project/pull/97733 This patch implements (not yet published) [P3144R2](https://wiki.edg.com/pub/Wg21stlouis2024/StrawPolls/p3144r2.pdf) "Deleting a Pointer to an Incomplete Type Should be Ill-formed". Wording changes (not yet merged into the working draft) read: > 7.6.2.9 [expr.delete] Delete > If the object being deleted has incomplete class type at the point of > deletion and the complete class has a non-trivial destructor or a deallocation function, the behavior is undefined, the program is ill-formed. We preserve status quo of emitting a warning when deleting a pointer to incomplete type up to, and including, C++23, but make it ill-formed since C++26. Same goes for deleting pointers to `void`, which has been allowed as an extension. >From f009148063ba41d39fc844f4432ceb51377f381c Mon Sep 17 00:00:00 2001 From: Vlad Serebrennikov Date: Thu, 4 Jul 2024 17:05:11 +0300 Subject: [PATCH] [clang] Implement P3144R2 "Deleting a Pointer to an Incomplete Type Should be Ill-formed" --- .../clang/Basic/DiagnosticSemaKinds.td| 2 ++ clang/lib/Sema/SemaExprCXX.cpp| 12 ++--- clang/test/CXX/drs/cwg5xx.cpp | 22 +--- clang/test/SemaCXX/new-delete.cpp | 26 --- 4 files changed, 41 insertions(+), 21 deletions(-) diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index 3df64b2ecef1b2..5c3e311ac63829 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -7991,6 +7991,8 @@ def err_ambiguous_delete_operand : Error< def warn_delete_incomplete : Warning< "deleting pointer to incomplete type %0 may cause undefined behavior">, InGroup; +def err_delete_incomplete : Error< + "cannot delete pointer to incomplete type %0">; def err_delete_incomplete_class_type : Error< "deleting incomplete class type %0; no conversions to pointer type">; def err_delete_explicit_conversion : Error< diff --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp index 69074f92a0286b..fcf2189a308a86 100644 --- a/clang/lib/Sema/SemaExprCXX.cpp +++ b/clang/lib/Sema/SemaExprCXX.cpp @@ -3719,8 +3719,11 @@ Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, // The C++ standard bans deleting a pointer to a non-object type, which // effectively bans deletion of "void*". However, most compilers support // this, so we treat it as a warning unless we're in a SFINAE context. - Diag(StartLoc, diag::ext_delete_void_ptr_operand) -<< Type << Ex.get()->getSourceRange(); + // But we still prohibit this since C++26. + Diag(StartLoc, LangOpts.CPlusPlus26 ? diag::err_delete_incomplete + : diag::ext_delete_void_ptr_operand) + << (LangOpts.CPlusPlus26 ? Pointee : Type) + << Ex.get()->getSourceRange(); } else if (Pointee->isFunctionType() || Pointee->isVoidType() || Pointee->isSizelessType()) { return ExprError(Diag(StartLoc, diag::err_delete_operand) @@ -3729,7 +3732,10 @@ Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, // FIXME: This can result in errors if the definition was imported from a // module but is hidden. if (!RequireCompleteType(StartLoc, Pointee, - diag::warn_delete_incomplete, Ex.get())) { + LangOpts.CPlusPlus26 + ? diag::err_delete_incomplete + : diag::warn_delete_incomplete, + Ex.get())) { if (const RecordType *RT = PointeeElem->getAs()) PointeeRD = cast(RT->getDecl()); } diff --git a/clang/test/CXX/drs/cwg5xx.cpp b/clang/test/CXX/drs/cwg5xx.cpp index 9d890f981348a7..6a0bb7a1966693 100644 --- a/clang/test/CXX/drs/cwg5xx.cpp +++ b/clang/test/CXX/drs/cwg5xx.cpp @@ -1,9 +1,10 @@ -// RUN: %clang_cc1 -std=c++98 %s -verify=expected,cxx98-11,cxx98-14,cxx98-17,cxx98 -fexceptions -fcxx-exceptions -pedantic-errors -// RUN: %clang_cc1 -std=c++11 %s -verify=expected,cxx98-11,cxx98-14,cxx98-17,since-cxx11 -fexceptions -fcxx-exceptions -pedantic-errors -// RUN: %clang_cc1 -std=c++14 %s -verify=expected,cxx98-14,cxx98-17,since-cxx11 -fexceptions -fcxx-exceptions -pedantic-errors -// RUN: %clang_cc1 -std=c++17 %s -verify=expected,since-cxx17,cxx98-17,since-cxx11 -fexceptions -fcxx-exceptions -pedantic-errors -// RUN: %clang_cc1 -std=c++20 %s -verify=expected,since-cxx20,since-cxx17,since-cxx11 -fexceptions -fcxx-exceptions -pedantic-errors -// RUN: %clang_cc1 -std=c++23 %s -verify=expected,since-cxx23,since-cxx20,since-cxx17,since-cxx11 -fexceptions -fcxx-exceptions -pedantic-errors +// RUN: %clang_cc1 -std=c++98 %s -verify=expected,cxx98-23,cxx98-11,cxx98-14,cxx98-17,cxx98 -fexceptions -
[clang] [clang] Implement P3144R2 "Deleting a Pointer to an Incomplete Type..." (PR #97733)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Vlad Serebrennikov (Endilll) Changes This patch implements (not yet published) [P3144R2](https://wiki.edg.com/pub/Wg21stlouis2024/StrawPolls/p3144r2.pdf) "Deleting a Pointer to an Incomplete Type Should be Ill-formed". Wording changes (not yet merged into the working draft) read: > 7.6.2.9 [expr.delete] Delete > If the object being deleted has incomplete class type at the point of deletionand the complete class has a non-trivial destructor or a deallocation function, the behavior is undefined, the program is ill-formed. We preserve status quo of emitting a warning when deleting a pointer to incomplete type up to, and including, C++23, but make it ill-formed since C++26. Same goes for deleting pointers to `void`, which has been allowed as an extension. --- Full diff: https://github.com/llvm/llvm-project/pull/97733.diff 4 Files Affected: - (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+2) - (modified) clang/lib/Sema/SemaExprCXX.cpp (+9-3) - (modified) clang/test/CXX/drs/cwg5xx.cpp (+13-9) - (modified) clang/test/SemaCXX/new-delete.cpp (+17-9) ``diff diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index 3df64b2ecef1b..5c3e311ac6382 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -7991,6 +7991,8 @@ def err_ambiguous_delete_operand : Error< def warn_delete_incomplete : Warning< "deleting pointer to incomplete type %0 may cause undefined behavior">, InGroup; +def err_delete_incomplete : Error< + "cannot delete pointer to incomplete type %0">; def err_delete_incomplete_class_type : Error< "deleting incomplete class type %0; no conversions to pointer type">; def err_delete_explicit_conversion : Error< diff --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp index 69074f92a0286..fcf2189a308a8 100644 --- a/clang/lib/Sema/SemaExprCXX.cpp +++ b/clang/lib/Sema/SemaExprCXX.cpp @@ -3719,8 +3719,11 @@ Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, // The C++ standard bans deleting a pointer to a non-object type, which // effectively bans deletion of "void*". However, most compilers support // this, so we treat it as a warning unless we're in a SFINAE context. - Diag(StartLoc, diag::ext_delete_void_ptr_operand) -<< Type << Ex.get()->getSourceRange(); + // But we still prohibit this since C++26. + Diag(StartLoc, LangOpts.CPlusPlus26 ? diag::err_delete_incomplete + : diag::ext_delete_void_ptr_operand) + << (LangOpts.CPlusPlus26 ? Pointee : Type) + << Ex.get()->getSourceRange(); } else if (Pointee->isFunctionType() || Pointee->isVoidType() || Pointee->isSizelessType()) { return ExprError(Diag(StartLoc, diag::err_delete_operand) @@ -3729,7 +3732,10 @@ Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, // FIXME: This can result in errors if the definition was imported from a // module but is hidden. if (!RequireCompleteType(StartLoc, Pointee, - diag::warn_delete_incomplete, Ex.get())) { + LangOpts.CPlusPlus26 + ? diag::err_delete_incomplete + : diag::warn_delete_incomplete, + Ex.get())) { if (const RecordType *RT = PointeeElem->getAs()) PointeeRD = cast(RT->getDecl()); } diff --git a/clang/test/CXX/drs/cwg5xx.cpp b/clang/test/CXX/drs/cwg5xx.cpp index 9d890f981348a..6a0bb7a196669 100644 --- a/clang/test/CXX/drs/cwg5xx.cpp +++ b/clang/test/CXX/drs/cwg5xx.cpp @@ -1,9 +1,10 @@ -// RUN: %clang_cc1 -std=c++98 %s -verify=expected,cxx98-11,cxx98-14,cxx98-17,cxx98 -fexceptions -fcxx-exceptions -pedantic-errors -// RUN: %clang_cc1 -std=c++11 %s -verify=expected,cxx98-11,cxx98-14,cxx98-17,since-cxx11 -fexceptions -fcxx-exceptions -pedantic-errors -// RUN: %clang_cc1 -std=c++14 %s -verify=expected,cxx98-14,cxx98-17,since-cxx11 -fexceptions -fcxx-exceptions -pedantic-errors -// RUN: %clang_cc1 -std=c++17 %s -verify=expected,since-cxx17,cxx98-17,since-cxx11 -fexceptions -fcxx-exceptions -pedantic-errors -// RUN: %clang_cc1 -std=c++20 %s -verify=expected,since-cxx20,since-cxx17,since-cxx11 -fexceptions -fcxx-exceptions -pedantic-errors -// RUN: %clang_cc1 -std=c++23 %s -verify=expected,since-cxx23,since-cxx20,since-cxx17,since-cxx11 -fexceptions -fcxx-exceptions -pedantic-errors +// RUN: %clang_cc1 -std=c++98 %s -verify=expected,cxx98-23,cxx98-11,cxx98-14,cxx98-17,cxx98 -fexceptions -fcxx-exceptions -pedantic-errors +// RUN: %clang_cc1 -std=c++11 %s -verify=expected,cxx98-23,cxx98-11,cxx98-14,cxx98-17,since-cxx11 -fexceptions -fcxx-exceptions -pedantic-errors +// RUN: %clang_cc1
[clang] [clang] Implement P3144R2 "Deleting a Pointer to an Incomplete Type..." (PR #97733)
https://github.com/Sirraide approved this pull request. LGTM, generally speaking, but do we maybe want change the old diagnostic to mention that it’s ‘incompatible w/ C++26’ or however we usually phrase that? https://github.com/llvm/llvm-project/pull/97733 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Implement P3144R2 "Deleting a Pointer to an Incomplete Type..." (PR #97733)
Sirraide wrote: Oh also, this still needs a release note and an entry in the C++ support docs, doesn’t it? https://github.com/llvm/llvm-project/pull/97733 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] CTAD alias: fix transformation for require-clause expr Part2. (PR #93533)
https://github.com/mizvekov approved this pull request. https://github.com/llvm/llvm-project/pull/93533 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)
kadircet wrote: Hi @ChuanqiXu9, I was on vacation and just returned, i'll provide next round of feedback quite soon. https://github.com/llvm/llvm-project/pull/66462 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Substitute for the type aliases inside of a CTAD guide (PR #94740)
@@ -2220,23 +2220,103 @@ namespace { class ExtractTypeForDeductionGuide : public TreeTransform { llvm::SmallVectorImpl &MaterializedTypedefs; + ClassTemplateDecl *NestedPattern; + const MultiLevelTemplateArgumentList *OuterInstantiationArgs; public: typedef TreeTransform Base; ExtractTypeForDeductionGuide( Sema &SemaRef, - llvm::SmallVectorImpl &MaterializedTypedefs) - : Base(SemaRef), MaterializedTypedefs(MaterializedTypedefs) {} + llvm::SmallVectorImpl &MaterializedTypedefs, + ClassTemplateDecl *NestedPattern, + const MultiLevelTemplateArgumentList *OuterInstantiationArgs) + : Base(SemaRef), MaterializedTypedefs(MaterializedTypedefs), +NestedPattern(NestedPattern), +OuterInstantiationArgs(OuterInstantiationArgs) {} TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); } + /// Returns true if it's safe to substitute \p Typedef with + /// \p OuterInstantiationArgs. + bool mightReferToOuterTemplateParameters(TypedefNameDecl *Typedef) { +if (!NestedPattern) + return false; + +static auto WalkUp = [](DeclContext *DC, DeclContext *TargetDC) { + if (DC->Equals(TargetDC)) +return true; + while (DC->isRecord()) { +if (DC->Equals(TargetDC)) + return true; +DC = DC->getParent(); + } + return false; +}; + +if (WalkUp(Typedef->getDeclContext(), NestedPattern->getTemplatedDecl())) + return true; +if (WalkUp(NestedPattern->getTemplatedDecl(), Typedef->getDeclContext())) + return true; +return false; + } + + QualType + RebuildTemplateSpecializationType(TemplateName Template, +SourceLocation TemplateNameLoc, +TemplateArgumentListInfo &TemplateArgs) { +if (!OuterInstantiationArgs || +!isa_and_present(Template.getAsTemplateDecl())) + return Base::RebuildTemplateSpecializationType(Template, TemplateNameLoc, + TemplateArgs); + +auto *TATD = cast(Template.getAsTemplateDecl()); +auto *Pattern = TATD; +while (Pattern->getInstantiatedFromMemberTemplate()) + Pattern = Pattern->getInstantiatedFromMemberTemplate(); +if (!mightReferToOuterTemplateParameters(Pattern->getTemplatedDecl())) + return Base::RebuildTemplateSpecializationType(Template, TemplateNameLoc, + TemplateArgs); + +Decl *NewD = SemaRef.SubstDecl( +TATD, SemaRef.getASTContext().getTranslationUnitDecl(), zyn0217 wrote: > There is a subtle difference: Thanks for spotting that! This is indeed something I've overlooked. Looking at the `SubstDecl` again, I think we can take the middle-ground approach: we call `TemplateDeclInstantiator::InstantiateTypeAliasTemplateDecl()` directly when we want to instantiate a TypedefNameDecl. This is a plausible approach to me because 1) We could save the recursion into the `DeclVisitor` from `SubstDecl` because we already know the `Decl` is a `TypedefDecl`. 2) This avoids the accidental Decl injection, although we have to tweak the `TemplateDeclInstantiator` a bit. 3) Re: `So an alternative would be to reuse this Decl rather than creating a new one`: granted that we could find that instantiated Decl, we still have to *copy* the Decl, which is in part a duplicate work of the instantiation logic, because we want the transformed Decl to live in the CXXDeductionGuideDecl - I think we can still leverage this instantiation mechanism to keep it intelligible. https://github.com/llvm/llvm-project/pull/94740 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Substitute for the type aliases inside of a CTAD guide (PR #94740)
https://github.com/zyn0217 updated https://github.com/llvm/llvm-project/pull/94740 >From 2f60e51f2017e4448047f64983b2f22cdb67e816 Mon Sep 17 00:00:00 2001 From: Younan Zhang Date: Fri, 7 Jun 2024 18:08:10 +0800 Subject: [PATCH 1/6] [Clang] Substitute for the type aliases inside of a CTAD guide --- clang/docs/ReleaseNotes.rst | 1 + clang/lib/Sema/SemaTemplate.cpp | 96 +-- .../SemaTemplate/nested-deduction-guides.cpp | 70 ++ 3 files changed, 160 insertions(+), 7 deletions(-) diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 0c700d23257bf..3f6d040b0ddf1 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -823,6 +823,7 @@ Bug Fixes to C++ Support differering by their constraints when only one of these function was variadic. - Fix a crash when a variable is captured by a block nested inside a lambda. (Fixes #GH93625). - Fixed a type constraint substitution issue involving a generic lambda expression. (#GH93821) +- Fixed a CTAD substitution bug involving type aliases that reference outer template parameters. (#GH94614). Bug Fixes to AST Handling ^ diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp index 40a759ea330de..1e921dd26bd7d 100644 --- a/clang/lib/Sema/SemaTemplate.cpp +++ b/clang/lib/Sema/SemaTemplate.cpp @@ -2220,23 +2220,101 @@ namespace { class ExtractTypeForDeductionGuide : public TreeTransform { llvm::SmallVectorImpl &MaterializedTypedefs; + ClassTemplateDecl *NestedPattern; + const MultiLevelTemplateArgumentList *OuterInstantiationArgs; public: typedef TreeTransform Base; ExtractTypeForDeductionGuide( Sema &SemaRef, - llvm::SmallVectorImpl &MaterializedTypedefs) - : Base(SemaRef), MaterializedTypedefs(MaterializedTypedefs) {} + llvm::SmallVectorImpl &MaterializedTypedefs, + ClassTemplateDecl *NestedPattern, + const MultiLevelTemplateArgumentList *OuterInstantiationArgs) + : Base(SemaRef), MaterializedTypedefs(MaterializedTypedefs), +NestedPattern(NestedPattern), +OuterInstantiationArgs(OuterInstantiationArgs) {} TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); } + bool mightReferToOuterTemplateParameters(TypedefNameDecl *Typedef) { +if (!NestedPattern) + return false; + +static auto WalkUp = [](DeclContext *DC, DeclContext *TargetDC) { + if (DC == TargetDC) +return true; + while (!DC->isTranslationUnit()) { +if (DC->Equals(TargetDC)) + return true; +DC = DC->getParent(); + } + return false; +}; + +if (WalkUp(Typedef->getDeclContext(), NestedPattern->getTemplatedDecl())) + return true; +if (WalkUp(NestedPattern->getTemplatedDecl(), Typedef->getDeclContext())) + return true; +return false; + } + + QualType + RebuildTemplateSpecializationType(TemplateName Template, +SourceLocation TemplateNameLoc, +TemplateArgumentListInfo &TemplateArgs) { +if (!OuterInstantiationArgs || +!isa_and_present(Template.getAsTemplateDecl())) + return Base::RebuildTemplateSpecializationType(Template, TemplateNameLoc, + TemplateArgs); + +auto *TATD = cast(Template.getAsTemplateDecl()); +auto *Pattern = TATD; +while (Pattern->getInstantiatedFromMemberTemplate()) + Pattern = Pattern->getInstantiatedFromMemberTemplate(); +if (!mightReferToOuterTemplateParameters(Pattern->getTemplatedDecl())) + return Base::RebuildTemplateSpecializationType(Template, TemplateNameLoc, + TemplateArgs); + +Decl *NewD = SemaRef.SubstDecl( +TATD, SemaRef.getASTContext().getTranslationUnitDecl(), +*OuterInstantiationArgs); +if (!NewD) + return QualType(); + +auto *NewTATD = cast(NewD); +MaterializedTypedefs.push_back(NewTATD->getTemplatedDecl()); + +return Base::RebuildTemplateSpecializationType( +TemplateName(NewTATD), TemplateNameLoc, TemplateArgs); + } + QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) { ASTContext &Context = SemaRef.getASTContext(); TypedefNameDecl *OrigDecl = TL.getTypedefNameDecl(); TypedefNameDecl *Decl = OrigDecl; // Transform the underlying type of the typedef and clone the Decl only if // the typedef has a dependent context. -if (OrigDecl->getDeclContext()->isDependentContext()) { +bool InDependentContext = OrigDecl->getDeclContext()->isDependentContext(); + +// A typedef/alias Decl within the NestedPattern may reference the outer +// template parameters. They're substituted with corresponding instantiation +// arguments here and in RebuildTemplateSpecializationType() above. +// Otherwise, we would have a
[clang] [clang] Implement P3144R2 "Deleting a Pointer to an Incomplete Type..." (PR #97733)
@@ -7991,6 +7991,8 @@ def err_ambiguous_delete_operand : Error< def warn_delete_incomplete : Warning< "deleting pointer to incomplete type %0 may cause undefined behavior">, cor3ntin wrote: ```suggestion "deleting pointer to incomplete type %0 is incompatible with C++2c and may cause undefined behavior">, ``` https://github.com/llvm/llvm-project/pull/97733 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Access tls_guard via llvm.threadlocal.address (PR #96633)
@@ -1070,13 +1084,20 @@ CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn, // Mark as initialized before initializing anything else. If the // initializers use previously-initialized thread_local vars, that's // probably supposed to be OK, but the standard doesn't say. - Builder.CreateStore(llvm::ConstantInt::get(GuardVal->getType(),1), Guard); - - // The guard variable can't ever change again. + // Get the thread-local address via intrinsic. + if (IsTLS) +GuardAddr = GuardAddr.withPointer( +Builder.CreateThreadLocalAddress(Guard.getPointer()), +NotKnownNonNull); + Builder.CreateStore(llvm::ConstantInt::get(GuardVal->getType(), 1), + GuardAddr); + + // Emit invariant start for TLS guard address. EmitInvariantStart( Guard.getPointer(), CharUnits::fromQuantity( - CGM.getDataLayout().getTypeAllocSize(GuardVal->getType(; + CGM.getDataLayout().getTypeAllocSize(GuardVal->getType())), + IsTLS); nikola-tesic-ns wrote: Am I allowed to reuse TLS address for invariant start intrinsic (example 1), or I need to access via intrinsic each time (example 2)? If the latter is true, I would need to recalculate the `GuardAddr` again. example 1: ``` %tls_addr1 = call align 1 ptr @llvm.threadlocal.address.p0(ptr align 1 @__tls_guard) store i8 1, ptr %tls_addr1, align 1 %3 = call ptr @llvm.invariant.start.p0(i64 1, ptr %tls_addr1) ``` example 2: ``` %tls_addr1 = call align 1 ptr @llvm.threadlocal.address.p0(ptr align 1 @__tls_guard) store i8 1, ptr %tls_addr1, align 1 %tls_addr2 = call align 1 ptr @llvm.threadlocal.address.p0(ptr align 1 @__tls_guard) %4 = call ptr @llvm.invariant.start.p0(i64 1, ptr %tls_addr2) ``` https://github.com/llvm/llvm-project/pull/96633 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [AArch64] Add getHostCPUFeatures to query for enabled features in cpu… (PR #97749)
https://github.com/neildhickey created https://github.com/llvm/llvm-project/pull/97749 …info This pull request adds code to call getHostCPUInfo into the AArch64 Target Parser to query the cpuinfo for the device in the case where we are compiling with -mcpu=native >From c942cb269560c6472a814e2d31f1545c6b80a890 Mon Sep 17 00:00:00 2001 From: Neil Hickey Date: Wed, 3 Jul 2024 07:22:46 -0700 Subject: [PATCH] [AArch64] Add getHostCPUFeatures to query for enabled features in cpuinfo --- clang/lib/Driver/ToolChains/Arch/AArch64.cpp | 17 + 1 file changed, 17 insertions(+) diff --git a/clang/lib/Driver/ToolChains/Arch/AArch64.cpp b/clang/lib/Driver/ToolChains/Arch/AArch64.cpp index ec248b80251ea..2862c297622fa 100644 --- a/clang/lib/Driver/ToolChains/Arch/AArch64.cpp +++ b/clang/lib/Driver/ToolChains/Arch/AArch64.cpp @@ -445,4 +445,21 @@ void aarch64::getAArch64TargetFeatures(const Driver &D, if (Args.getLastArg(options::OPT_mno_bti_at_return_twice)) Features.push_back("+no-bti-at-return-twice"); + + // Parse AArch64 CPU Features + const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ); + StringRef CPUName; + + if (CPUArg) { +CPUName = CPUArg->getValue(); +if (CPUName == "native") { + llvm::StringMap HostFeatures; + if (llvm::sys::getHostCPUFeatures(HostFeatures)) { +for (auto &F : HostFeatures) { + Features.push_back( +Args.MakeArgString((F.second ? "+" : "-") + F.first())); +} + } +} + } } ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [AArch64] Add getHostCPUFeatures to query for enabled features in cpu… (PR #97749)
llvmbot wrote: @llvm/pr-subscribers-clang Author: None (neildhickey) Changes …info This pull request adds code to call getHostCPUInfo into the AArch64 Target Parser to query the cpuinfo for the device in the case where we are compiling with -mcpu=native --- Full diff: https://github.com/llvm/llvm-project/pull/97749.diff 1 Files Affected: - (modified) clang/lib/Driver/ToolChains/Arch/AArch64.cpp (+17) ``diff diff --git a/clang/lib/Driver/ToolChains/Arch/AArch64.cpp b/clang/lib/Driver/ToolChains/Arch/AArch64.cpp index ec248b80251ea3..2862c297622fa9 100644 --- a/clang/lib/Driver/ToolChains/Arch/AArch64.cpp +++ b/clang/lib/Driver/ToolChains/Arch/AArch64.cpp @@ -445,4 +445,21 @@ void aarch64::getAArch64TargetFeatures(const Driver &D, if (Args.getLastArg(options::OPT_mno_bti_at_return_twice)) Features.push_back("+no-bti-at-return-twice"); + + // Parse AArch64 CPU Features + const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ); + StringRef CPUName; + + if (CPUArg) { +CPUName = CPUArg->getValue(); +if (CPUName == "native") { + llvm::StringMap HostFeatures; + if (llvm::sys::getHostCPUFeatures(HostFeatures)) { +for (auto &F : HostFeatures) { + Features.push_back( +Args.MakeArgString((F.second ? "+" : "-") + F.first())); +} + } +} + } } `` https://github.com/llvm/llvm-project/pull/97749 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [AArch64] Add getHostCPUFeatures to query for enabled features in cpu… (PR #97749)
github-actions[bot] wrote: :warning: C/C++ code formatter, clang-format found issues in your code. :warning: You can test this locally with the following command: ``bash git-clang-format --diff d43ec97de081755990264049eba09cb7c83cb321 c942cb269560c6472a814e2d31f1545c6b80a890 -- clang/lib/Driver/ToolChains/Arch/AArch64.cpp `` View the diff from clang-format here. ``diff diff --git a/clang/lib/Driver/ToolChains/Arch/AArch64.cpp b/clang/lib/Driver/ToolChains/Arch/AArch64.cpp index 2862c29762..ddf9973616 100644 --- a/clang/lib/Driver/ToolChains/Arch/AArch64.cpp +++ b/clang/lib/Driver/ToolChains/Arch/AArch64.cpp @@ -457,7 +457,7 @@ void aarch64::getAArch64TargetFeatures(const Driver &D, if (llvm::sys::getHostCPUFeatures(HostFeatures)) { for (auto &F : HostFeatures) { Features.push_back( -Args.MakeArgString((F.second ? "+" : "-") + F.first())); + Args.MakeArgString((F.second ? "+" : "-") + F.first())); } } } `` https://github.com/llvm/llvm-project/pull/97749 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] CTAD alias: fix transformation for require-clause expr Part2. (PR #93533)
github-actions[bot] wrote: :warning: C/C++ code formatter, clang-format found issues in your code. :warning: You can test this locally with the following command: ``bash git-clang-format --diff 79d6f52c4f56fbada3e14fa924c370e27418222e 251f179e1fc654381b90a2746799c044344499f3 -- clang/lib/Sema/SemaTemplate.cpp clang/test/AST/ast-dump-ctad-alias.cpp clang/test/SemaCXX/cxx20-ctad-type-alias.cpp `` View the diff from clang-format here. ``diff diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp index 62a41b2936..07b3f793b3 100644 --- a/clang/lib/Sema/SemaTemplate.cpp +++ b/clang/lib/Sema/SemaTemplate.cpp @@ -2743,8 +2743,7 @@ Expr * buildAssociatedConstraints(Sema &SemaRef, FunctionTemplateDecl *F, TypeAliasTemplateDecl *AliasTemplate, ArrayRef DeduceResults, - unsigned FirstUndeducedParamIdx, - Expr *IsDeducible) { + unsigned FirstUndeducedParamIdx, Expr *IsDeducible) { Expr *RC = F->getTemplateParameters()->getRequiresClause(); if (!RC) return IsDeducible; @@ -2805,7 +2804,7 @@ buildAssociatedConstraints(Sema &SemaRef, FunctionTemplateDecl *F, for (unsigned Index = 0; Index < DeduceResults.size(); ++Index) { const auto &D = DeduceResults[Index]; if (D.isNull()) { // non-deduced template parameters of f - NamedDecl* TP = F->getTemplateParameters()->getParam(Index); + NamedDecl *TP = F->getTemplateParameters()->getParam(Index); MultiLevelTemplateArgumentList Args; Args.setKind(TemplateSubstitutionKind::Rewrite); Args.addOuterTemplateArguments(TemplateArgsForBuildingRC); @@ -3153,9 +3152,9 @@ BuildDeductionGuideForTypeAlias(Sema &SemaRef, Expr *IsDeducible = buildIsDeducibleConstraint( SemaRef, AliasTemplate, FPrime->getReturnType(), FPrimeTemplateParams); -Expr *RequiresClause = buildAssociatedConstraints( -SemaRef, F, AliasTemplate, DeduceResults, -FirstUndeducedParamIdx, IsDeducible); +Expr *RequiresClause = +buildAssociatedConstraints(SemaRef, F, AliasTemplate, DeduceResults, + FirstUndeducedParamIdx, IsDeducible); auto *FPrimeTemplateParamList = TemplateParameterList::Create( Context, AliasTemplate->getTemplateParameters()->getTemplateLoc(), `` https://github.com/llvm/llvm-project/pull/93533 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Parser][ObjC] Add -Wobjc-prefix-length warning option. (PR #97597)
https://github.com/al45tair updated https://github.com/llvm/llvm-project/pull/97597 >From 02f7c5ef71b382866e02037ce82c85fa6fcbb394 Mon Sep 17 00:00:00 2001 From: Alastair Houghton Date: Wed, 3 Jul 2024 17:00:51 +0100 Subject: [PATCH 1/5] [Parser][ObjC] Add -Wobjc-prefix-length warning option. This lets clang generate warnings automatically if it sees Objective-C names that don't have the correct prefix length. rdar://131055157 --- clang/include/clang/Basic/DiagnosticGroups.td | 1 + .../clang/Basic/DiagnosticParseKinds.td | 7 ++ clang/include/clang/Basic/LangOptions.def | 2 + clang/include/clang/Driver/Options.td | 7 ++ clang/include/clang/Parse/Parser.h| 1 + clang/lib/Driver/ToolChains/Clang.cpp | 1 + clang/lib/Parse/ParseObjc.cpp | 65 +++ clang/test/Parser/objc-prefixes.m | 62 ++ 8 files changed, 146 insertions(+) create mode 100644 clang/test/Parser/objc-prefixes.m diff --git a/clang/include/clang/Basic/DiagnosticGroups.td b/clang/include/clang/Basic/DiagnosticGroups.td index 9431eea1f6be2..0d944434cda38 100644 --- a/clang/include/clang/Basic/DiagnosticGroups.td +++ b/clang/include/clang/Basic/DiagnosticGroups.td @@ -598,6 +598,7 @@ def ObjCPointerIntrospect : DiagGroup<"deprecated-objc-pointer-introspection", [ def ObjCMultipleMethodNames : DiagGroup<"objc-multiple-method-names">; def ObjCFlexibleArray : DiagGroup<"objc-flexible-array">; def ObjCBoxing : DiagGroup<"objc-boxing">; +def ObjCPrefixLength : DiagGroup<"objc-prefix-length">; def CompletionHandler : DiagGroup<"completion-handler">; def CalledOnceParameter : DiagGroup<"called-once-parameter", [CompletionHandler]>; def OpenCLUnsupportedRGBA: DiagGroup<"opencl-unsupported-rgba">; diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td b/clang/include/clang/Basic/DiagnosticParseKinds.td index 12aab09f28556..7e26bd13f9c7b 100644 --- a/clang/include/clang/Basic/DiagnosticParseKinds.td +++ b/clang/include/clang/Basic/DiagnosticParseKinds.td @@ -563,6 +563,13 @@ def err_declaration_does_not_declare_param : Error< "declaration does not declare a parameter">; def err_no_matching_param : Error<"parameter named %0 is missing">; +def warn_objc_unprefixed_class_name : Warning< + "un-prefixed Objective-C class name">, + InGroup; +def warn_objc_unprefixed_protocol_name : Warning< + "un-prefixed Objective-C protocol name">, + InGroup; + /// Objective-C++ parser diagnostics def err_expected_token_instead_of_objcxx_keyword : Error< "expected %0; %1 is a keyword in Objective-C++">; diff --git a/clang/include/clang/Basic/LangOptions.def b/clang/include/clang/Basic/LangOptions.def index 491759e2fcdbb..9df19b01f0b22 100644 --- a/clang/include/clang/Basic/LangOptions.def +++ b/clang/include/clang/Basic/LangOptions.def @@ -351,6 +351,8 @@ LANGOPT(ObjCAutoRefCount , 1, 0, "Objective-C automated reference counting") LANGOPT(ObjCWeakRuntime , 1, 0, "__weak support in the ARC runtime") LANGOPT(ObjCWeak, 1, 0, "Objective-C __weak in ARC and MRC files") LANGOPT(ObjCSubscriptingLegacyRuntime , 1, 0, "Subscripting support in legacy ObjectiveC runtime") +BENIGN_LANGOPT(ObjCPrefixLength, 32, 0, + "if non-zero, warn about Objective-C classes or protocols with names that do not have a prefix of the specified length.") BENIGN_LANGOPT(CompatibilityQualifiedIdBlockParamTypeChecking, 1, 0, "compatibility mode for type checking block parameters " "involving qualified id types") diff --git a/clang/include/clang/Driver/Options.td b/clang/include/clang/Driver/Options.td index 1ede75d3782cd..829efafd03a2c 100644 --- a/clang/include/clang/Driver/Options.td +++ b/clang/include/clang/Driver/Options.td @@ -3418,6 +3418,13 @@ defm objc_exceptions : BoolFOption<"objc-exceptions", PosFlag, NegFlag>; +def Wobjc_prefix_length_EQ: + Joined<["-"], "Wobjc-prefix-length=">, + Visibility<[ClangOption, CC1Option]>, + MetaVarName<"">, + HelpText<"Warn if Objective-C class or protocol names do not start with a prefix of the specified length">, + MarshallingInfoInt>; + defm application_extension : BoolFOption<"application-extension", LangOpts<"AppExt">, DefaultFalse, PosFlaggetBeginLoc(), diag::note_objc_container_start) << (int)ock; } +/// An Objective-C public name (a class name or protocol name) is +/// expected to have a prefix as all names are in a single global +/// namespace. +/// +/// If the -Wobjc-prefix-length is set to N, the name must start +/// with N+1 capital letters, which must be followed by a character +/// that is not a capital letter. +/// +/// For instance, for N set to 2, the following are valid: +/// +/// NSString +/// NSArray +/// +/// but these are not: +/// +/// MyString +/// NSKString +/// NSnotAString +/// +/// We make a special exception for NSCF things when the prefix is set +//
[clang] [clang] CTAD alias: fix transformation for require-clause expr Part2. (PR #93533)
https://github.com/hokein updated https://github.com/llvm/llvm-project/pull/93533 >From b0b8d5b064c35e4f0b66e2538c4172afa9665dbe Mon Sep 17 00:00:00 2001 From: Haojian Wu Date: Fri, 17 May 2024 15:28:48 +0200 Subject: [PATCH 1/4] [clang] CTAD alias: fix transformation for require-clause expr Part2. In the https://github.com/llvm/llvm-project/pull/90961 fix, we miss a case where the undeduced template parameters of the underlying deduction guide is not transformed, which leaves incorrect depth/index information, and causes crash when evaluating the constraints. This patch fix this missing case. Fixes #92596 Fixes #92212 --- clang/lib/Sema/SemaTemplate.cpp | 32 clang/test/AST/ast-dump-ctad-alias.cpp | 25 +++ clang/test/SemaCXX/cxx20-ctad-type-alias.cpp | 25 +++ 3 files changed, 76 insertions(+), 6 deletions(-) diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp index 6879a9a274b5c..08c6858f7e776 100644 --- a/clang/lib/Sema/SemaTemplate.cpp +++ b/clang/lib/Sema/SemaTemplate.cpp @@ -2743,6 +2743,7 @@ Expr * buildAssociatedConstraints(Sema &SemaRef, FunctionTemplateDecl *F, TypeAliasTemplateDecl *AliasTemplate, ArrayRef DeduceResults, + unsigned UndeducedTemplateParameterStartIndex, Expr *IsDeducible) { Expr *RC = F->getTemplateParameters()->getRequiresClause(); if (!RC) @@ -2803,8 +2804,22 @@ buildAssociatedConstraints(Sema &SemaRef, FunctionTemplateDecl *F, for (unsigned Index = 0; Index < DeduceResults.size(); ++Index) { const auto &D = DeduceResults[Index]; -if (D.isNull()) +if (D.isNull()) { // non-deduced template parameters of f + auto TP = F->getTemplateParameters()->getParam(Index); + MultiLevelTemplateArgumentList Args; + Args.setKind(TemplateSubstitutionKind::Rewrite); + Args.addOuterTemplateArguments(TemplateArgsForBuildingRC); + // Rebuild the template parameter with updated depth and index. + NamedDecl *NewParam = transformTemplateParameter( + SemaRef, F->getDeclContext(), TP, Args, + /*NewIndex=*/UndeducedTemplateParameterStartIndex++, + getTemplateParameterDepth(TP) + AdjustDepth); + + assert(TemplateArgsForBuildingRC[Index].isNull()); + TemplateArgsForBuildingRC[Index] = Context.getCanonicalTemplateArgument( + Context.getInjectedTemplateArg(NewParam)); continue; +} TemplateArgumentLoc Input = SemaRef.getTrivialTemplateArgumentLoc(D, QualType(), SourceLocation{}); TemplateArgumentLoc Output; @@ -2820,9 +2835,11 @@ buildAssociatedConstraints(Sema &SemaRef, FunctionTemplateDecl *F, MultiLevelTemplateArgumentList ArgsForBuildingRC; ArgsForBuildingRC.setKind(clang::TemplateSubstitutionKind::Rewrite); ArgsForBuildingRC.addOuterTemplateArguments(TemplateArgsForBuildingRC); - // For 2), if the underlying F is instantiated from a member template, we need - // the entire template argument list, as the constraint AST in the - // require-clause of F remains completely uninstantiated. + // For 2), if the underlying function template F is nested in a class template + // (either instantiated from an explicitly-written deduction guide, or + // synthesized from a constructor), we need the entire template argument list, + // as the constraint AST in the require-clause of F remains completely + // uninstantiated. // // For example: // template // depth 0 @@ -2845,7 +2862,8 @@ buildAssociatedConstraints(Sema &SemaRef, FunctionTemplateDecl *F, // We add the outer template arguments which is [int] to the multi-level arg // list to ensure that the occurrence U in `C` will be replaced with int // during the substitution. - if (F->getInstantiatedFromMemberTemplate()) { + if (F->getLexicalDeclContext()->getDeclKind() == + clang::Decl::ClassTemplateSpecialization) { auto OuterLevelArgs = SemaRef.getTemplateInstantiationArgs( F, F->getLexicalDeclContext(), /*Final=*/false, /*Innermost=*/std::nullopt, @@ -3063,6 +3081,7 @@ BuildDeductionGuideForTypeAlias(Sema &SemaRef, Context.getInjectedTemplateArg(NewParam)); TransformedDeducedAliasArgs[AliasTemplateParamIdx] = NewTemplateArgument; } + unsigned UndeducedTemplateParameterStartIndex = FPrimeTemplateParams.size(); // ...followed by the template parameters of f that were not deduced // (including their default template arguments) for (unsigned FTemplateParamIdx : NonDeducedTemplateParamsInFIndex) { @@ -3132,7 +3151,8 @@ BuildDeductionGuideForTypeAlias(Sema &SemaRef, Expr *IsDeducible = buildIsDeducibleConstraint( SemaRef, AliasTemplate, FPrime->getReturnType(), FPrimeTemplateParams); Expr *RequiresClause = buildAssociatedConstraints( -SemaRef, F, AliasTemplate, DeduceResults, IsDeducible); +SemaRef,
[clang] [Clang] Warn on backslash-newline-EOF (PR #97585)
@@ -536,3 +536,12 @@ namespace cwg1696 { // cwg1696: 7 }; #endif } + +// cwg1698: yes Endilll wrote: ```suggestion // cwg1698: 2.7 ``` https://github.com/llvm/llvm-project/pull/97585 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Warn on backslash-newline-EOF (PR #97585)
@@ -0,0 +1,11 @@ +// RUN: %clang_cc1 -std=c++11 -pedantic-errors -verify=expected %s -E | FileCheck %s --strict-whitespace --allow-empty Endilll wrote: We run DR tests in complete range of C++ versions. https://github.com/llvm/llvm-project/pull/97585 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 834ecc8 - [clang] CTAD alias: fix transformation for require-clause expr Part2. (#93533)
Author: Haojian Wu Date: 2024-07-04T18:45:33+02:00 New Revision: 834ecc8b2ad44859f5bcaac9f92178e469390a51 URL: https://github.com/llvm/llvm-project/commit/834ecc8b2ad44859f5bcaac9f92178e469390a51 DIFF: https://github.com/llvm/llvm-project/commit/834ecc8b2ad44859f5bcaac9f92178e469390a51.diff LOG: [clang] CTAD alias: fix transformation for require-clause expr Part2. (#93533) In the https://github.com/llvm/llvm-project/pull/90961 fix, we miss a case where the undeduced template parameters of the underlying deduction guide are not transformed, which leaves incorrect depth/index information, and causes crashes when evaluating constraints. This patch fix this missing case. Fixes #92596 Fixes #92212 Added: Modified: clang/lib/Sema/SemaTemplate.cpp clang/test/AST/ast-dump-ctad-alias.cpp clang/test/SemaCXX/cxx20-ctad-type-alias.cpp Removed: diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp index 6879a9a274b5c..07b3f793b3a29 100644 --- a/clang/lib/Sema/SemaTemplate.cpp +++ b/clang/lib/Sema/SemaTemplate.cpp @@ -2743,7 +2743,7 @@ Expr * buildAssociatedConstraints(Sema &SemaRef, FunctionTemplateDecl *F, TypeAliasTemplateDecl *AliasTemplate, ArrayRef DeduceResults, - Expr *IsDeducible) { + unsigned FirstUndeducedParamIdx, Expr *IsDeducible) { Expr *RC = F->getTemplateParameters()->getRequiresClause(); if (!RC) return IsDeducible; @@ -2803,8 +2803,22 @@ buildAssociatedConstraints(Sema &SemaRef, FunctionTemplateDecl *F, for (unsigned Index = 0; Index < DeduceResults.size(); ++Index) { const auto &D = DeduceResults[Index]; -if (D.isNull()) +if (D.isNull()) { // non-deduced template parameters of f + NamedDecl *TP = F->getTemplateParameters()->getParam(Index); + MultiLevelTemplateArgumentList Args; + Args.setKind(TemplateSubstitutionKind::Rewrite); + Args.addOuterTemplateArguments(TemplateArgsForBuildingRC); + // Rebuild the template parameter with updated depth and index. + NamedDecl *NewParam = transformTemplateParameter( + SemaRef, F->getDeclContext(), TP, Args, + /*NewIndex=*/FirstUndeducedParamIdx, + getTemplateParameterDepth(TP) + AdjustDepth); + FirstUndeducedParamIdx += 1; + assert(TemplateArgsForBuildingRC[Index].isNull()); + TemplateArgsForBuildingRC[Index] = Context.getCanonicalTemplateArgument( + Context.getInjectedTemplateArg(NewParam)); continue; +} TemplateArgumentLoc Input = SemaRef.getTrivialTemplateArgumentLoc(D, QualType(), SourceLocation{}); TemplateArgumentLoc Output; @@ -2820,8 +2834,8 @@ buildAssociatedConstraints(Sema &SemaRef, FunctionTemplateDecl *F, MultiLevelTemplateArgumentList ArgsForBuildingRC; ArgsForBuildingRC.setKind(clang::TemplateSubstitutionKind::Rewrite); ArgsForBuildingRC.addOuterTemplateArguments(TemplateArgsForBuildingRC); - // For 2), if the underlying F is instantiated from a member template, we need - // the entire template argument list, as the constraint AST in the + // For 2), if the underlying deduction guide F is nested in a class template, + // we need the entire template argument list, as the constraint AST in the // require-clause of F remains completely uninstantiated. // // For example: @@ -2845,7 +2859,13 @@ buildAssociatedConstraints(Sema &SemaRef, FunctionTemplateDecl *F, // We add the outer template arguments which is [int] to the multi-level arg // list to ensure that the occurrence U in `C` will be replaced with int // during the substitution. - if (F->getInstantiatedFromMemberTemplate()) { + // + // NOTE: The underlying deduction guide F is instantiated -- either from an + // explicitly-written deduction guide member, or from a constructor. + // getInstantiatedFromMemberTemplate() can only handle the former case, so we + // check the DeclContext kind. + if (F->getLexicalDeclContext()->getDeclKind() == + clang::Decl::ClassTemplateSpecialization) { auto OuterLevelArgs = SemaRef.getTemplateInstantiationArgs( F, F->getLexicalDeclContext(), /*Final=*/false, /*Innermost=*/std::nullopt, @@ -3063,6 +3083,7 @@ BuildDeductionGuideForTypeAlias(Sema &SemaRef, Context.getInjectedTemplateArg(NewParam)); TransformedDeducedAliasArgs[AliasTemplateParamIdx] = NewTemplateArgument; } + unsigned FirstUndeducedParamIdx = FPrimeTemplateParams.size(); // ...followed by the template parameters of f that were not deduced // (including their default template arguments) for (unsigned FTemplateParamIdx : NonDeducedTemplateParamsInFIndex) { @@ -3131,8 +3152,9 @@ BuildDeductionGuideForTypeAlias(Sema &SemaRef, Expr *IsDeducible = buildIsDeducibleConstraint( SemaRef, AliasTemplate, FPrime-
[clang] [clang] CTAD alias: fix transformation for require-clause expr Part2. (PR #93533)
https://github.com/hokein closed https://github.com/llvm/llvm-project/pull/93533 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Warn on backslash-newline-EOF (PR #97585)
https://github.com/MitalAshok updated https://github.com/llvm/llvm-project/pull/97585 >From 8af656659b79d76c971b01f1f4c14dc7315565b8 Mon Sep 17 00:00:00 2001 From: Mital Ashok Date: Fri, 21 Jun 2024 18:55:38 +0100 Subject: [PATCH 1/5] [Clang] Warn on backslash-newline-EOF --- clang/docs/ReleaseNotes.rst | 2 + .../include/clang/Basic/DiagnosticLexKinds.td | 1 + clang/lib/Lex/Lexer.cpp | 39 +-- clang/test/CXX/drs/cwg16xx.cpp| 9 + clang/test/CXX/drs/cwg2747.cpp| 11 ++ clang/test/CXX/drs/cwg27xx.cpp| 2 + .../test/Preprocessor/backslash_newline_eof.c | 12 ++ .../Preprocessor/backslash_without_newline.c | 8 .../Preprocessor/backslash_without_newline.h | 4 ++ clang/www/cxx_dr_status.html | 4 +- 10 files changed, 87 insertions(+), 5 deletions(-) create mode 100644 clang/test/CXX/drs/cwg2747.cpp create mode 100644 clang/test/Preprocessor/backslash_newline_eof.c create mode 100644 clang/test/Preprocessor/backslash_without_newline.c create mode 100644 clang/test/Preprocessor/backslash_without_newline.h diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index f40fd1cd145bb..7c0ac3a504f98 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -647,6 +647,8 @@ Improvements to Clang's diagnostics - Clang now shows implicit deduction guides when diagnosing overload resolution failure. #GH92393. +- Clang now emits ``-Wnewline-eof`` when the last newline is deleted by a preceding backslash. + Improvements to Clang's time-trace -- diff --git a/clang/include/clang/Basic/DiagnosticLexKinds.td b/clang/include/clang/Basic/DiagnosticLexKinds.td index 12d7b8c0205ee..e6b2c1385944c 100644 --- a/clang/include/clang/Basic/DiagnosticLexKinds.td +++ b/clang/include/clang/Basic/DiagnosticLexKinds.td @@ -56,6 +56,7 @@ def ext_no_newline_eof : Extension<"no newline at end of file">, InGroup; def warn_no_newline_eof : Warning<"no newline at end of file">, InGroup, DefaultIgnore; +def note_backslash_newline_eof : Note<"last newline deleted by splice here">; def warn_cxx98_compat_no_newline_eof : Warning< "C++98 requires newline at end of file">, diff --git a/clang/lib/Lex/Lexer.cpp b/clang/lib/Lex/Lexer.cpp index e59c7805b3862..0e540834b473b 100644 --- a/clang/lib/Lex/Lexer.cpp +++ b/clang/lib/Lex/Lexer.cpp @@ -3165,7 +3165,17 @@ bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) { // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue // a pedwarn. - if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) { + if (CurPtr != BufferStart) { +StringRef LastNewline; +if (CurPtr[-1] == '\r' || CurPtr[-1] == '\n') { + LastNewline = StringRef(CurPtr - 1, 1); + if (CurPtr - 1 != BufferStart && CurPtr[-2] != CurPtr[-1] && + (CurPtr[-2] == '\r' || CurPtr[-2] == '\n')) { +// \r\n or \n\r is one newline +LastNewline = StringRef(CurPtr - 2, 2); + } +} + DiagnosticsEngine &Diags = PP->getDiagnostics(); SourceLocation EndLoc = getSourceLocation(BufferEnd); unsigned DiagID; @@ -3183,8 +3193,31 @@ bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) { DiagID = diag::ext_no_newline_eof; } -Diag(BufferEnd, DiagID) - << FixItHint::CreateInsertion(EndLoc, "\n"); +if (LastNewline.empty()) { + Diag(BufferEnd, DiagID) << FixItHint::CreateInsertion(EndLoc, "\n"); +} else { + // While the file physically ends in a newline, the previous + // line might have ended in a splice, so it would be deleted + const char *LastSpliceLocation = LastNewline.data(); + while (LastSpliceLocation != BufferStart && + isHorizontalWhitespace(*--LastSpliceLocation)) +; + + bool LastIsSplice = *LastSpliceLocation == '\\'; + if (*LastSpliceLocation == '/' && LangOpts.Trigraphs) +// Check for "??/" trigraph for "\" +LastIsSplice = +LastSpliceLocation != BufferStart && *--LastSpliceLocation == '?' && +LastSpliceLocation != BufferStart && *--LastSpliceLocation == '?'; + + if (LastIsSplice) { +PP->Diag(getSourceLocation(LastNewline.data(), LastNewline.size()), + DiagID); +Diag(LastSpliceLocation, diag::note_backslash_newline_eof) +<< FixItHint::CreateRemoval(getSourceLocation( + LastSpliceLocation, *LastSpliceLocation == '\\' ? 1 : 3)); + } +} } BufferPtr = CurPtr; diff --git a/clang/test/CXX/drs/cwg16xx.cpp b/clang/test/CXX/drs/cwg16xx.cpp index cf6b45ceabf2c..dca941fa30624 100644 --- a/clang/test/CXX/drs/cwg16xx.cpp +++ b/clang/test/CXX/drs/cwg16xx.cpp @@ -536,3 +536,12 @@ namespace cwg1696 { // cwg1696: 7 }; #endif } + +// cwg1698: yes +// This file intentionally does not end in a ne
[clang] [Parser][ObjC] Add -Wobjc-prefix-length warning option. (PR #97597)
https://github.com/al45tair updated https://github.com/llvm/llvm-project/pull/97597 >From 02f7c5ef71b382866e02037ce82c85fa6fcbb394 Mon Sep 17 00:00:00 2001 From: Alastair Houghton Date: Wed, 3 Jul 2024 17:00:51 +0100 Subject: [PATCH 1/6] [Parser][ObjC] Add -Wobjc-prefix-length warning option. This lets clang generate warnings automatically if it sees Objective-C names that don't have the correct prefix length. rdar://131055157 --- clang/include/clang/Basic/DiagnosticGroups.td | 1 + .../clang/Basic/DiagnosticParseKinds.td | 7 ++ clang/include/clang/Basic/LangOptions.def | 2 + clang/include/clang/Driver/Options.td | 7 ++ clang/include/clang/Parse/Parser.h| 1 + clang/lib/Driver/ToolChains/Clang.cpp | 1 + clang/lib/Parse/ParseObjc.cpp | 65 +++ clang/test/Parser/objc-prefixes.m | 62 ++ 8 files changed, 146 insertions(+) create mode 100644 clang/test/Parser/objc-prefixes.m diff --git a/clang/include/clang/Basic/DiagnosticGroups.td b/clang/include/clang/Basic/DiagnosticGroups.td index 9431eea1f6be22..0d944434cda387 100644 --- a/clang/include/clang/Basic/DiagnosticGroups.td +++ b/clang/include/clang/Basic/DiagnosticGroups.td @@ -598,6 +598,7 @@ def ObjCPointerIntrospect : DiagGroup<"deprecated-objc-pointer-introspection", [ def ObjCMultipleMethodNames : DiagGroup<"objc-multiple-method-names">; def ObjCFlexibleArray : DiagGroup<"objc-flexible-array">; def ObjCBoxing : DiagGroup<"objc-boxing">; +def ObjCPrefixLength : DiagGroup<"objc-prefix-length">; def CompletionHandler : DiagGroup<"completion-handler">; def CalledOnceParameter : DiagGroup<"called-once-parameter", [CompletionHandler]>; def OpenCLUnsupportedRGBA: DiagGroup<"opencl-unsupported-rgba">; diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td b/clang/include/clang/Basic/DiagnosticParseKinds.td index 12aab09f285567..7e26bd13f9c7bc 100644 --- a/clang/include/clang/Basic/DiagnosticParseKinds.td +++ b/clang/include/clang/Basic/DiagnosticParseKinds.td @@ -563,6 +563,13 @@ def err_declaration_does_not_declare_param : Error< "declaration does not declare a parameter">; def err_no_matching_param : Error<"parameter named %0 is missing">; +def warn_objc_unprefixed_class_name : Warning< + "un-prefixed Objective-C class name">, + InGroup; +def warn_objc_unprefixed_protocol_name : Warning< + "un-prefixed Objective-C protocol name">, + InGroup; + /// Objective-C++ parser diagnostics def err_expected_token_instead_of_objcxx_keyword : Error< "expected %0; %1 is a keyword in Objective-C++">; diff --git a/clang/include/clang/Basic/LangOptions.def b/clang/include/clang/Basic/LangOptions.def index 491759e2fcdbb9..9df19b01f0b22d 100644 --- a/clang/include/clang/Basic/LangOptions.def +++ b/clang/include/clang/Basic/LangOptions.def @@ -351,6 +351,8 @@ LANGOPT(ObjCAutoRefCount , 1, 0, "Objective-C automated reference counting") LANGOPT(ObjCWeakRuntime , 1, 0, "__weak support in the ARC runtime") LANGOPT(ObjCWeak, 1, 0, "Objective-C __weak in ARC and MRC files") LANGOPT(ObjCSubscriptingLegacyRuntime , 1, 0, "Subscripting support in legacy ObjectiveC runtime") +BENIGN_LANGOPT(ObjCPrefixLength, 32, 0, + "if non-zero, warn about Objective-C classes or protocols with names that do not have a prefix of the specified length.") BENIGN_LANGOPT(CompatibilityQualifiedIdBlockParamTypeChecking, 1, 0, "compatibility mode for type checking block parameters " "involving qualified id types") diff --git a/clang/include/clang/Driver/Options.td b/clang/include/clang/Driver/Options.td index 1ede75d3782cdc..829efafd03a2c0 100644 --- a/clang/include/clang/Driver/Options.td +++ b/clang/include/clang/Driver/Options.td @@ -3418,6 +3418,13 @@ defm objc_exceptions : BoolFOption<"objc-exceptions", PosFlag, NegFlag>; +def Wobjc_prefix_length_EQ: + Joined<["-"], "Wobjc-prefix-length=">, + Visibility<[ClangOption, CC1Option]>, + MetaVarName<"">, + HelpText<"Warn if Objective-C class or protocol names do not start with a prefix of the specified length">, + MarshallingInfoInt>; + defm application_extension : BoolFOption<"application-extension", LangOpts<"AppExt">, DefaultFalse, PosFlaggetBeginLoc(), diag::note_objc_container_start) << (int)ock; } +/// An Objective-C public name (a class name or protocol name) is +/// expected to have a prefix as all names are in a single global +/// namespace. +/// +/// If the -Wobjc-prefix-length is set to N, the name must start +/// with N+1 capital letters, which must be followed by a character +/// that is not a capital letter. +/// +/// For instance, for N set to 2, the following are valid: +/// +/// NSString +/// NSArray +/// +/// but these are not: +/// +/// MyString +/// NSKString +/// NSnotAString +/// +/// We make a special exception for NSCF things when the prefix is
[clang] [llvm] Fix MSVC 1920+ auto NTTP mangling for pointers to members (PR #97007)
https://github.com/MaxEW707 closed https://github.com/llvm/llvm-project/pull/97007 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] d1dc416 - Fix MSVC 1920+ auto NTTP mangling for pointers to members (#97007)
Author: Max Winkler Date: 2024-07-04T10:17:32-07:00 New Revision: d1dc4169838381688a74f245cdaedbe9fce13848 URL: https://github.com/llvm/llvm-project/commit/d1dc4169838381688a74f245cdaedbe9fce13848 DIFF: https://github.com/llvm/llvm-project/commit/d1dc4169838381688a74f245cdaedbe9fce13848.diff LOG: Fix MSVC 1920+ auto NTTP mangling for pointers to members (#97007) Fixes https://github.com/llvm/llvm-project/issues/70899. This is a continuation of https://github.com/llvm/llvm-project/pull/92477 for pointers to member data and pointers to member functions. The mangled name must be prefixed with `$M ` for the deduced type of the nttp parameter. Added: clang/test/CodeGenCXX/mangle-ms-auto-templates-memptrs.cpp clang/test/CodeGenCXX/mangle-ms-auto-templates-nullptr.cpp Modified: clang/docs/ReleaseNotes.rst clang/lib/AST/MicrosoftMangle.cpp llvm/lib/Demangle/MicrosoftDemangle.cpp llvm/test/Demangle/ms-auto-templates.test Removed: diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index f149684214567d..36cf615a4287cc 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -106,6 +106,13 @@ ABI Changes in This Version earlier versions of Clang unless such code is built with the compiler option `-fms-compatibility-version=19.14` to imitate the MSVC 1914 mangling behavior. +- Fixed Microsoft name mangling for auto non-type template arguments of pointer + to member type for MSVC 1920+. This change resolves incompatibilities with code + compiled by MSVC 1920+ but will introduce incompatibilities with code compiled by + earlier versions of Clang unless such code is built with the compiler option + `-fms-compatibility-version=19.14` to imitate the MSVC 1914 mangling behavior. + (GH#70899). + AST Dumping Potentially Breaking Changes diff --git a/clang/lib/AST/MicrosoftMangle.cpp b/clang/lib/AST/MicrosoftMangle.cpp index 7f1e9ab02ec261..fac14ce1dce8ce 100644 --- a/clang/lib/AST/MicrosoftMangle.cpp +++ b/clang/lib/AST/MicrosoftMangle.cpp @@ -368,11 +368,15 @@ class MicrosoftCXXNameMangler { void mangleFunctionEncoding(GlobalDecl GD, bool ShouldMangle); void mangleVariableEncoding(const VarDecl *VD); void mangleMemberDataPointer(const CXXRecordDecl *RD, const ValueDecl *VD, + const NonTypeTemplateParmDecl *PD, + QualType TemplateArgType, StringRef Prefix = "$"); void mangleMemberDataPointerInClassNTTP(const CXXRecordDecl *, const ValueDecl *); void mangleMemberFunctionPointer(const CXXRecordDecl *RD, const CXXMethodDecl *MD, + const NonTypeTemplateParmDecl *PD, + QualType TemplateArgType, StringRef Prefix = "$"); void mangleFunctionPointer(const FunctionDecl *FD, const NonTypeTemplateParmDecl *PD, @@ -673,12 +677,17 @@ void MicrosoftCXXNameMangler::mangleVariableEncoding(const VarDecl *VD) { } } -void MicrosoftCXXNameMangler::mangleMemberDataPointer(const CXXRecordDecl *RD, - const ValueDecl *VD, - StringRef Prefix) { +void MicrosoftCXXNameMangler::mangleMemberDataPointer( +const CXXRecordDecl *RD, const ValueDecl *VD, +const NonTypeTemplateParmDecl *PD, QualType TemplateArgType, +StringRef Prefix) { // ::= // ::= $F // ::= $G + // + // ::= $ M + // ::= $ M F + // ::= $ M G int64_t FieldOffset; int64_t VBTableOffset; @@ -707,7 +716,18 @@ void MicrosoftCXXNameMangler::mangleMemberDataPointer(const CXXRecordDecl *RD, case MSInheritanceModel::Unspecified: Code = 'G'; break; } - Out << Prefix << Code; + Out << Prefix; + + if (VD && + getASTContext().getLangOpts().isCompatibleWithMSVC( + LangOptions::MSVC2019) && + PD && PD->getType()->getTypeClass() == Type::Auto && + !TemplateArgType.isNull()) { +Out << "M"; +mangleType(TemplateArgType, SourceRange(), QMM_Drop); + } + + Out << Code; mangleNumber(FieldOffset); @@ -728,7 +748,7 @@ void MicrosoftCXXNameMangler::mangleMemberDataPointerInClassNTTP( // ::= 8 @ @ if (IM != MSInheritanceModel::Single && IM != MSInheritanceModel::Multiple) -return mangleMemberDataPointer(RD, VD, ""); +return mangleMemberDataPointer(RD, VD, nullptr, QualType(), ""); if (!VD) { Out << 'N'; @@ -742,14 +762,19 @@ void MicrosoftCXXNameMangler::mangleMemberDataPointerInClassNTTP( Out << '@'; } -void -MicrosoftCXXNameMangler::mangleMemberFun
[clang] [llvm] [Clang][LLVM][AArch64] Add intrinsic for LUTI4 SME2 instruction (PR #97755)
https://github.com/CarolineConcatto created https://github.com/llvm/llvm-project/pull/97755 This patch adds these intrinsics: // Variants are also available for: _s8 svuint8x4_t svluti4_zt_u8_x4(uint64_t zt0, svuint8x2_t zn) __arm_streaming __arm_in("zt0"); according to PR#324[1] [1]ARM-software/acle#324 >From 22f5bb7cab1673632f1fa5438a35f861c16d63b2 Mon Sep 17 00:00:00 2001 From: Caroline Concatto Date: Thu, 4 Jul 2024 17:10:36 + Subject: [PATCH] [Clang][LLVM][AArch64] Add intrinsic for LUTI4 SME2 instruction This patch adds these intrinsics: // Variants are also available for: _s8 svuint8x4_t svluti4_zt_u8_x4(uint64_t zt0, svuint8x2_t zn) __arm_streaming __arm_in("zt0"); according to PR#324[1] [1]ARM-software/acle#324 --- clang/include/clang/Basic/arm_sme.td | 5 ++ .../acle_sme2_luti4_zt.c | 82 +++ .../aarch64-sme2-intrinsics/acle_sme2_imm.cpp | 5 ++ llvm/include/llvm/IR/IntrinsicsAArch64.td | 6 ++ .../Target/AArch64/AArch64ISelDAGToDAG.cpp| 19 - .../lib/Target/AArch64/AArch64SMEInstrInfo.td | 2 +- .../AArch64/sme2-intrinsics-write-zt.ll | 17 7 files changed, 132 insertions(+), 4 deletions(-) create mode 100644 clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_luti4_zt.c create mode 100644 llvm/test/CodeGen/AArch64/sme2-intrinsics-write-zt.ll diff --git a/clang/include/clang/Basic/arm_sme.td b/clang/include/clang/Basic/arm_sme.td index ce8908f566f2f..e4a61caae733e 100644 --- a/clang/include/clang/Basic/arm_sme.td +++ b/clang/include/clang/Basic/arm_sme.td @@ -817,4 +817,9 @@ multiclass ZAReadzArray{ defm SVREADZ_VG2 : ZAReadzArray<"2">; defm SVREADZ_VG4 : ZAReadzArray<"4">; + +let SMETargetGuard = "sme2,sme-lutv2" in { + def SVLUTI4_ZT_X4 : SInst<"svluti4_zt_{d}_x4", "4i2", "cUc", MergeNone, "aarch64_sme_luti4_zt_x4", [IsStreaming, IsInOutZT0], [ImmCheck<0, ImmCheck0_0>]>; +} + } // let SVETargetGuard = InvalidMode diff --git a/clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_luti4_zt.c b/clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_luti4_zt.c new file mode 100644 index 0..2e7cd0939f516 --- /dev/null +++ b/clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_luti4_zt.c @@ -0,0 +1,82 @@ +// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --version 5 +// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +bf16 -target-feature +sme -target-feature +sme2 -target-feature +sme-lutv2 -O2 -Werror -Wall -emit-llvm -o - %s | FileCheck %s +// RUN: %clang_cc1 -x c++ -triple aarch64-none-linux-gnu -target-feature +bf16 -target-feature +sme -target-feature +sme2 -target-feature +sme-lutv2 -O2 -Werror -Wall -emit-llvm -o - %s | FileCheck %s -check-prefix CHECK-CXX +// RUN: %clang_cc1 -DSVE_OVERLOADED_FORMS -triple aarch64-none-linux-gnu -target-feature +bf16 -target-feature +sme -target-feature +sme2 -target-feature +sme-lutv2 -O2 -Werror -Wall -emit-llvm -o - %s | FileCheck %s +// RUN: %clang_cc1 -DSVE_OVERLOADED_FORMS -x c++ -triple aarch64-none-linux-gnu -target-feature +bf16 -target-feature +sme -target-feature +sme2 -target-feature +sme-lutv2 -O2 -Werror -Wall -emit-llvm -o - %s | FileCheck %s -check-prefix CHECK-CXX + +// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +bf16 -target-feature +sme -target-feature +sme2 -target-feature +sme-lutv2 -O2 -S -Werror -Wall -o /dev/null %s +// REQUIRES: aarch64-registered-target + +#include + +// CHECK-LABEL: define dso_local @test_luti4_zt_u8_x4( +// CHECK-SAME: [[OP:%.*]]) local_unnamed_addr #[[ATTR0:[0-9]+]] { +// CHECK-NEXT: [[ENTRY:.*:]] +// CHECK-NEXT:[[TMP0:%.*]] = tail call @llvm.vector.extract.nxv16i8.nxv32i8( [[OP]], i64 0) +// CHECK-NEXT:[[TMP1:%.*]] = tail call @llvm.vector.extract.nxv16i8.nxv32i8( [[OP]], i64 16) +// CHECK-NEXT:[[TMP2:%.*]] = tail call { , , , } @llvm.aarch64.sme.luti4.zt.x4.nxv16i8(i32 0, [[TMP0]], [[TMP1]]) +// CHECK-NEXT:[[TMP3:%.*]] = extractvalue { , , , } [[TMP2]], 0 +// CHECK-NEXT:[[TMP4:%.*]] = tail call @llvm.vector.insert.nxv64i8.nxv16i8( poison, [[TMP3]], i64 0) +// CHECK-NEXT:[[TMP5:%.*]] = extractvalue { , , , } [[TMP2]], 1 +// CHECK-NEXT:[[TMP6:%.*]] = tail call @llvm.vector.insert.nxv64i8.nxv16i8( [[TMP4]], [[TMP5]], i64 16) +// CHECK-NEXT:[[TMP7:%.*]] = extractvalue { , , , } [[TMP2]], 2 +// CHECK-NEXT:[[TMP8:%.*]] = tail call @llvm.vector.insert.nxv64i8.nxv16i8( [[TMP6]], [[TMP7]], i64 32) +// CHECK-NEXT:[[TMP9:%.*]] = extractvalue { , , , } [[TMP2]], 3 +// CHECK-NEXT:[[TMP10:%.*]] = tail call @llvm.vector.insert.nxv64i8.nxv16i8( [[TMP8]], [[TMP9]], i64 48) +// CHECK-NEXT:ret [[TMP10]] +// +// CHECK-CXX-LABEL: define dso_local @_Z19test_luti4_zt_u8_x411svuint8x2_t( +// CHECK-CXX-SAME: [[OP:%.*]]) local_unnamed_addr #[[ATTR0:[0-9]+]] { +// CHECK-CXX-NEXT: [[ENTRY:.*:]] +// CHECK-CXX-NEXT:[[TMP0:%.*]] = tail call
[clang] [llvm] [Clang][LLVM][AArch64] Add intrinsic for LUTI4 SME2 instruction (PR #97755)
llvmbot wrote: @llvm/pr-subscribers-clang @llvm/pr-subscribers-backend-aarch64 Author: None (CarolineConcatto) Changes This patch adds these intrinsics: // Variants are also available for: _s8 svuint8x4_t svluti4_zt_u8_x4(uint64_t zt0, svuint8x2_t zn) __arm_streaming __arm_in("zt0"); according to PR#324[1] [1]ARM-software/acle#324 --- Full diff: https://github.com/llvm/llvm-project/pull/97755.diff 7 Files Affected: - (modified) clang/include/clang/Basic/arm_sme.td (+5) - (added) clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_luti4_zt.c (+82) - (modified) clang/test/Sema/aarch64-sme2-intrinsics/acle_sme2_imm.cpp (+5) - (modified) llvm/include/llvm/IR/IntrinsicsAArch64.td (+6) - (modified) llvm/lib/Target/AArch64/AArch64ISelDAGToDAG.cpp (+16-3) - (modified) llvm/lib/Target/AArch64/AArch64SMEInstrInfo.td (+1-1) - (added) llvm/test/CodeGen/AArch64/sme2-intrinsics-write-zt.ll (+17) ``diff diff --git a/clang/include/clang/Basic/arm_sme.td b/clang/include/clang/Basic/arm_sme.td index ce8908f566f2fd..e4a61caae733ec 100644 --- a/clang/include/clang/Basic/arm_sme.td +++ b/clang/include/clang/Basic/arm_sme.td @@ -817,4 +817,9 @@ multiclass ZAReadzArray{ defm SVREADZ_VG2 : ZAReadzArray<"2">; defm SVREADZ_VG4 : ZAReadzArray<"4">; + +let SMETargetGuard = "sme2,sme-lutv2" in { + def SVLUTI4_ZT_X4 : SInst<"svluti4_zt_{d}_x4", "4i2", "cUc", MergeNone, "aarch64_sme_luti4_zt_x4", [IsStreaming, IsInOutZT0], [ImmCheck<0, ImmCheck0_0>]>; +} + } // let SVETargetGuard = InvalidMode diff --git a/clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_luti4_zt.c b/clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_luti4_zt.c new file mode 100644 index 00..2e7cd0939f516b --- /dev/null +++ b/clang/test/CodeGen/aarch64-sme2-intrinsics/acle_sme2_luti4_zt.c @@ -0,0 +1,82 @@ +// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --version 5 +// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +bf16 -target-feature +sme -target-feature +sme2 -target-feature +sme-lutv2 -O2 -Werror -Wall -emit-llvm -o - %s | FileCheck %s +// RUN: %clang_cc1 -x c++ -triple aarch64-none-linux-gnu -target-feature +bf16 -target-feature +sme -target-feature +sme2 -target-feature +sme-lutv2 -O2 -Werror -Wall -emit-llvm -o - %s | FileCheck %s -check-prefix CHECK-CXX +// RUN: %clang_cc1 -DSVE_OVERLOADED_FORMS -triple aarch64-none-linux-gnu -target-feature +bf16 -target-feature +sme -target-feature +sme2 -target-feature +sme-lutv2 -O2 -Werror -Wall -emit-llvm -o - %s | FileCheck %s +// RUN: %clang_cc1 -DSVE_OVERLOADED_FORMS -x c++ -triple aarch64-none-linux-gnu -target-feature +bf16 -target-feature +sme -target-feature +sme2 -target-feature +sme-lutv2 -O2 -Werror -Wall -emit-llvm -o - %s | FileCheck %s -check-prefix CHECK-CXX + +// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +bf16 -target-feature +sme -target-feature +sme2 -target-feature +sme-lutv2 -O2 -S -Werror -Wall -o /dev/null %s +// REQUIRES: aarch64-registered-target + +#include + +// CHECK-LABEL: define dso_local @test_luti4_zt_u8_x4( +// CHECK-SAME: [[OP:%.*]]) local_unnamed_addr #[[ATTR0:[0-9]+]] { +// CHECK-NEXT: [[ENTRY:.*:]] +// CHECK-NEXT:[[TMP0:%.*]] = tail call @llvm.vector.extract.nxv16i8.nxv32i8( [[OP]], i64 0) +// CHECK-NEXT:[[TMP1:%.*]] = tail call @llvm.vector.extract.nxv16i8.nxv32i8( [[OP]], i64 16) +// CHECK-NEXT:[[TMP2:%.*]] = tail call { , , , } @llvm.aarch64.sme.luti4.zt.x4.nxv16i8(i32 0, [[TMP0]], [[TMP1]]) +// CHECK-NEXT:[[TMP3:%.*]] = extractvalue { , , , } [[TMP2]], 0 +// CHECK-NEXT:[[TMP4:%.*]] = tail call @llvm.vector.insert.nxv64i8.nxv16i8( poison, [[TMP3]], i64 0) +// CHECK-NEXT:[[TMP5:%.*]] = extractvalue { , , , } [[TMP2]], 1 +// CHECK-NEXT:[[TMP6:%.*]] = tail call @llvm.vector.insert.nxv64i8.nxv16i8( [[TMP4]], [[TMP5]], i64 16) +// CHECK-NEXT:[[TMP7:%.*]] = extractvalue { , , , } [[TMP2]], 2 +// CHECK-NEXT:[[TMP8:%.*]] = tail call @llvm.vector.insert.nxv64i8.nxv16i8( [[TMP6]], [[TMP7]], i64 32) +// CHECK-NEXT:[[TMP9:%.*]] = extractvalue { , , , } [[TMP2]], 3 +// CHECK-NEXT:[[TMP10:%.*]] = tail call @llvm.vector.insert.nxv64i8.nxv16i8( [[TMP8]], [[TMP9]], i64 48) +// CHECK-NEXT:ret [[TMP10]] +// +// CHECK-CXX-LABEL: define dso_local @_Z19test_luti4_zt_u8_x411svuint8x2_t( +// CHECK-CXX-SAME: [[OP:%.*]]) local_unnamed_addr #[[ATTR0:[0-9]+]] { +// CHECK-CXX-NEXT: [[ENTRY:.*:]] +// CHECK-CXX-NEXT:[[TMP0:%.*]] = tail call @llvm.vector.extract.nxv16i8.nxv32i8( [[OP]], i64 0) +// CHECK-CXX-NEXT:[[TMP1:%.*]] = tail call @llvm.vector.extract.nxv16i8.nxv32i8( [[OP]], i64 16) +// CHECK-CXX-NEXT:[[TMP2:%.*]] = tail call { , , , } @llvm.aarch64.sme.luti4.zt.x4.nxv16i8(i32 0, [[TMP0]], [[TMP1]]) +// CHECK-CXX-NEXT:[[TMP3:%.*]] = extractvalue { , , , } [[TMP2]], 0 +// CHECK-CXX-NEXT:[[TMP4:%.*]] = tail call @llvm.vector.insert.nx
[clang] [clang] Support --sysroot= for ${arch}-windows-msvc targets (PR #96417)
trcrsired wrote: > Backing up a bit, where is the sysroot directory that this `--sysroot` flag > for windows-msvc points to supposed to come from? > > I thought this was for pointing clang to an MSVC installation, similar to > clang-cl's /winsysroot, but it looks like the code is doing something else. https://github.com/trcrsired/windows-msvc-sysroot/tree/main I extract all files from msvc installations and windows SDK and put them in the format of what a normal sysroot would do on other platforms. Basically, unify the behavior with another platform. https://github.com/llvm/llvm-project/pull/96417 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][analyzer][doc] Migrate user-related docs from HTML to RST (PR #97034)
@@ -96,11 +96,11 @@ Download Mac OS X Latest build (10.8+): - + checker-279.tar.bz2 (built November 14, 2016) gamesh411 wrote: @haoNoQ Thanks for the insights! I'll also create another PR to clean up the index.html and finish the developer section. There will be questions about what to do with open projects and checker ideas, but let's discuss it later in that PR. https://github.com/llvm/llvm-project/pull/97034 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][analyzer][doc] Migrate user-related docs from HTML to RST (PR #97034)
gamesh411 wrote: * Updated the HTML pages to use the redirect logic in available_checks.html (instead of deleting them). * Updated the usages of 'the static analyzer' in the files touched by this patch. @steakhal, @NagyDonat, @haoNoQ Thanks for the snappy review! https://github.com/llvm/llvm-project/pull/97034 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [X86][CodeGen] security check cookie execute only when needed (PR #95904)
mahesh-attarde wrote: @RKSimon @MaskRay @efriedma-quic can we merge please? https://github.com/llvm/llvm-project/pull/95904 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][FMV] Do not omit explicit default target_version attribute. (PR #96628)
https://github.com/ilinpv approved this pull request. Look good, thanks for refactoring and removing obsolete checks after FMV changes related to ordering and default version. https://github.com/llvm/llvm-project/pull/96628 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][FMV] Do not omit explicit default target_version attribute. (PR #96628)
https://github.com/labrinea updated https://github.com/llvm/llvm-project/pull/96628 >From ff4635208e9cd83c6735c95ebf12125ca737029a Mon Sep 17 00:00:00 2001 From: Alexandros Lamprineas Date: Tue, 25 Jun 2024 00:27:45 +0100 Subject: [PATCH 1/3] [clang][FMV] Do not omit explicit default target_version attribute. Fixes a crash and cleans up some dead code. namespace Foo { int bar(); __attribute((target_version("default"))) int bar() { return 0; } __attribute((target_version("mops"))) int bar() { return 1; } } $ clang++ --target=aarch64-linux-gnu --rtlib=compiler-rt fmv.cpp None multiversion type isn't valid here UNREACHABLE executed at clang/lib/CodeGen/CodeGenModule.cpp:1840! ... getMangledNameImpl clang::CodeGen::CodeGenModule::getMangledName clang::CodeGen::CodeGenModule::EmitGlobal --- clang/include/clang/Sema/Sema.h | 3 +- clang/lib/Sema/SemaDecl.cpp | 45 +--- clang/lib/Sema/SemaDeclAttr.cpp | 16 ++--- clang/test/CodeGen/attr-target-version.c | 88 clang/test/CodeGenCXX/fmv-namespace.cpp | 60 clang/test/Sema/attr-target-version.c| 5 +- 6 files changed, 118 insertions(+), 99 deletions(-) diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h index 2e7af0f691cbb..31bb81705a742 100644 --- a/clang/include/clang/Sema/Sema.h +++ b/clang/include/clang/Sema/Sema.h @@ -3786,8 +3786,7 @@ class Sema final : public SemaBase { StringRef Name); bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str); - bool checkTargetVersionAttr(SourceLocation LiteralLoc, Decl *D, - StringRef &Str, bool &isDefault); + bool checkTargetVersionAttr(SourceLocation Loc, Decl *D, StringRef Str); bool checkTargetClonesAttrString( SourceLocation LiteralLoc, StringRef Str, const StringLiteral *Literal, Decl *D, bool &HasDefault, bool &HasCommas, bool &HasNotDefault, diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp index 029ccf944c513..572c46eed1aaa 100644 --- a/clang/lib/Sema/SemaDecl.cpp +++ b/clang/lib/Sema/SemaDecl.cpp @@ -11465,6 +11465,10 @@ static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) { // otherwise it is treated as a normal function. if (TA && !TA->isDefaultVersion()) return false; + // The target_version attribute only causes Multiversioning if this + // declaration is NOT the default version. + if (TVA && TVA->isDefaultVersion()) +return false; if ((TA || TVA) && CheckMultiVersionValue(S, FD)) { FD->setInvalidDecl(); @@ -11498,11 +11502,9 @@ static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To) { if (MVKindTo == MultiVersionKind::None && (MVKindFrom == MultiVersionKind::TargetVersion || - MVKindFrom == MultiVersionKind::TargetClones)) { -To->setIsMultiVersion(); + MVKindFrom == MultiVersionKind::TargetClones)) To->addAttr(TargetVersionAttr::CreateImplicit( To->getASTContext(), "default", To->getSourceRange())); - } } static bool CheckTargetCausesMultiVersioning(Sema &S, FunctionDecl *OldFD, @@ -11523,10 +11525,16 @@ static bool CheckTargetCausesMultiVersioning(Sema &S, FunctionDecl *OldFD, const auto *OldTVA = OldFD->getAttr(); // If the old decl is NOT MultiVersioned yet, and we don't cause that // to change, this is a simple redeclaration. - if ((NewTA && !NewTA->isDefaultVersion() && - (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) || - (NewTVA && !NewTVA->isDefaultVersion() && - (!OldTVA || OldTVA->getName() == NewTVA->getName( + if (NewTA && !NewTA->isDefaultVersion() && + (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) +return false; + + // The target_version attribute only causes Multiversioning if this + // declaration is NOT the default version. Moreover, the old declaration + // must be the default version (either explicitly via the attribute, + // or implicitly without it). + if (NewTVA && + (NewTVA->isDefaultVersion() || (OldTVA && !OldTVA->isDefaultVersion( return false; // Otherwise, this decl causes MultiVersioning. @@ -11543,8 +11551,7 @@ static bool CheckTargetCausesMultiVersioning(Sema &S, FunctionDecl *OldFD, } // If this is 'default', permit the forward declaration. - if ((NewTA && NewTA->isDefaultVersion() && !OldTA) || - (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) { + if (NewTA && NewTA->isDefaultVersion() && !OldTA) { Redeclaration = true; OldDecl = OldFD; OldFD->setIsMultiVersion(); @@ -11947,24 +11954,8 @@ static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, FunctionDecl *OldFD = OldDecl->getAsFunction(); - if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None) { -if (NewTVA || !OldFD->getAttr()) - return false; -if (!NewFD->getType()->getAs()) { - // Multiversion
[clang] d1c911f - [clang][FMV] Do not omit explicit default target_version attribute. (#96628)
Author: Alexandros Lamprineas Date: 2024-07-04T20:04:11+01:00 New Revision: d1c911ffe48eef23817d11c900dec30e0e3b5ae4 URL: https://github.com/llvm/llvm-project/commit/d1c911ffe48eef23817d11c900dec30e0e3b5ae4 DIFF: https://github.com/llvm/llvm-project/commit/d1c911ffe48eef23817d11c900dec30e0e3b5ae4.diff LOG: [clang][FMV] Do not omit explicit default target_version attribute. (#96628) Fixes a crash and cleans up some dead code. namespace Foo { int bar(); __attribute((target_version("default"))) int bar() { return 0; } __attribute((target_version("mops"))) int bar() { return 1; } } $ clang++ --target=aarch64-linux-gnu --rtlib=compiler-rt fmv.cpp None multiversion type isn't valid here UNREACHABLE executed at clang/lib/CodeGen/CodeGenModule.cpp:1840! ... getMangledNameImpl clang::CodeGen::CodeGenModule::getMangledName clang::CodeGen::CodeGenModule::EmitGlobal Added: Modified: clang/include/clang/Sema/Sema.h clang/lib/Sema/SemaDecl.cpp clang/lib/Sema/SemaDeclAttr.cpp clang/test/CodeGen/attr-target-version.c clang/test/CodeGenCXX/fmv-namespace.cpp clang/test/Sema/attr-target-version.c Removed: diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h index 0dbc819f6223a..fb3a5d25c635c 100644 --- a/clang/include/clang/Sema/Sema.h +++ b/clang/include/clang/Sema/Sema.h @@ -4533,8 +4533,7 @@ class Sema final : public SemaBase { bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str); /// Check Target Version attrs - bool checkTargetVersionAttr(SourceLocation LiteralLoc, Decl *D, - StringRef &Str, bool &isDefault); + bool checkTargetVersionAttr(SourceLocation Loc, Decl *D, StringRef Str); bool checkTargetClonesAttrString( SourceLocation LiteralLoc, StringRef Str, const StringLiteral *Literal, Decl *D, bool &HasDefault, bool &HasCommas, bool &HasNotDefault, diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp index 262a2547e23fd..b3bfdacb01790 100644 --- a/clang/lib/Sema/SemaDecl.cpp +++ b/clang/lib/Sema/SemaDecl.cpp @@ -11201,6 +11201,10 @@ static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) { // otherwise it is treated as a normal function. if (TA && !TA->isDefaultVersion()) return false; + // The target_version attribute only causes Multiversioning if this + // declaration is NOT the default version. + if (TVA && TVA->isDefaultVersion()) +return false; if ((TA || TVA) && CheckMultiVersionValue(S, FD)) { FD->setInvalidDecl(); @@ -11234,18 +11238,16 @@ static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To) { if (MVKindTo == MultiVersionKind::None && (MVKindFrom == MultiVersionKind::TargetVersion || - MVKindFrom == MultiVersionKind::TargetClones)) { -To->setIsMultiVersion(); + MVKindFrom == MultiVersionKind::TargetClones)) To->addAttr(TargetVersionAttr::CreateImplicit( To->getASTContext(), "default", To->getSourceRange())); - } } -static bool CheckTargetCausesMultiVersioning(Sema &S, FunctionDecl *OldFD, - FunctionDecl *NewFD, - bool &Redeclaration, - NamedDecl *&OldDecl, - LookupResult &Previous) { +static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD, + FunctionDecl *NewFD, + bool &Redeclaration, + NamedDecl *&OldDecl, + LookupResult &Previous) { assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion"); // The definitions should be allowed in any order. If we have discovered @@ -11256,13 +11258,16 @@ static bool CheckTargetCausesMultiVersioning(Sema &S, FunctionDecl *OldFD, const auto *NewTA = NewFD->getAttr(); const auto *NewTVA = NewFD->getAttr(); const auto *OldTA = OldFD->getAttr(); - const auto *OldTVA = OldFD->getAttr(); + // If the old decl is NOT MultiVersioned yet, and we don't cause that // to change, this is a simple redeclaration. - if ((NewTA && !NewTA->isDefaultVersion() && - (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) || - (NewTVA && !NewTVA->isDefaultVersion() && - (!OldTVA || OldTVA->getName() == NewTVA->getName( + if (NewTA && !NewTA->isDefaultVersion() && + (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) +return false; + + // The target_version attribute only causes Multiversioning if this + // declaration is NOT the default version. + if (NewTVA && NewTVA->isDefaultVersion()) return false; // Otherwise, this decl causes MultiVersioning. @@ -11279,8 +11
[clang] [clang][FMV] Do not omit explicit default target_version attribute. (PR #96628)
https://github.com/labrinea closed https://github.com/llvm/llvm-project/pull/96628 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][FMV] Do not omit explicit default target_version attribute. (PR #96628)
llvm-ci wrote: LLVM Buildbot has detected a new failure on builder `lldb-x86_64-debian` running on `lldb-x86_64-debian` while building `clang` at step 6 "test". Full details are available at: https://lab.llvm.org/buildbot/#/builders/162/builds/1430 Here is the relevant piece of the build log for the reference: ``` Step 6 (test) failure: build (failure) ... PASS: lldb-api :: macosx/load-kext/TestLoadKext.py (1080 of 2628) UNSUPPORTED: lldb-api :: python_api/target-arch-from-module/TestTargetArchFromModule.py (1081 of 2628) UNSUPPORTED: lldb-api :: lang/objc/global_ptrs/TestGlobalObjects.py (1082 of 2628) PASS: lldb-api :: commands/version/TestVersion.py (1083 of 2628) UNSUPPORTED: lldb-api :: lang/objc/modules-inline-functions/TestModulesInlineFunctions.py (1084 of 2628) UNSUPPORTED: lldb-api :: lang/objc/foundation/TestObjCMethods.py (1085 of 2628) UNSUPPORTED: lldb-api :: functionalities/type_lookup/TestTypeLookup.py (1086 of 2628) UNSUPPORTED: lldb-api :: macosx/stack-corefile/TestStackCorefile.py (1087 of 2628) UNSUPPORTED: lldb-api :: functionalities/interactive_scripted_process/TestInteractiveScriptedProcess.py (1088 of 2628) UNSUPPORTED: lldb-api :: commands/expression/weak_symbols/TestWeakSymbols.py (1089 of 2628) FAIL: lldb-shell :: SymbolFile/DWARF/x86/dwp-foreign-type-units.cpp (1090 of 2628) TEST 'lldb-shell :: SymbolFile/DWARF/x86/dwp-foreign-type-units.cpp' FAILED Exit Code: 1 Command Output (stderr): -- RUN: at line 21: /home/worker/2.0.1/lldb-x86_64-debian/build/bin/clang --target=specify-a-target-or-use-a-_host-substitution -target x86_64-pc-linux -gdwarf-5 -gsplit-dwarf-fdebug-types-section -gpubnames -c /home/worker/2.0.1/lldb-x86_64-debian/llvm-project/lldb/test/Shell/SymbolFile/DWARF/x86/dwp-foreign-type-units.cpp -o /home/worker/2.0.1/lldb-x86_64-debian/build/tools/lldb/test/Shell/SymbolFile/DWARF/x86/Output/dwp-foreign-type-units.cpp.tmp.main.o + /home/worker/2.0.1/lldb-x86_64-debian/build/bin/clang --target=specify-a-target-or-use-a-_host-substitution -target x86_64-pc-linux -gdwarf-5 -gsplit-dwarf -fdebug-types-section -gpubnames -c /home/worker/2.0.1/lldb-x86_64-debian/llvm-project/lldb/test/Shell/SymbolFile/DWARF/x86/dwp-foreign-type-units.cpp -o /home/worker/2.0.1/lldb-x86_64-debian/build/tools/lldb/test/Shell/SymbolFile/DWARF/x86/Output/dwp-foreign-type-units.cpp.tmp.main.o RUN: at line 23: /home/worker/2.0.1/lldb-x86_64-debian/build/bin/clang --target=specify-a-target-or-use-a-_host-substitution -target x86_64-pc-linux -gdwarf-5 -gsplit-dwarf -DVARIANT-fdebug-types-section -gpubnames -c /home/worker/2.0.1/lldb-x86_64-debian/llvm-project/lldb/test/Shell/SymbolFile/DWARF/x86/dwp-foreign-type-units.cpp -o /home/worker/2.0.1/lldb-x86_64-debian/build/tools/lldb/test/Shell/SymbolFile/DWARF/x86/Output/dwp-foreign-type-units.cpp.tmp.foo.o + /home/worker/2.0.1/lldb-x86_64-debian/build/bin/clang --target=specify-a-target-or-use-a-_host-substitution -target x86_64-pc-linux -gdwarf-5 -gsplit-dwarf -DVARIANT -fdebug-types-section -gpubnames -c /home/worker/2.0.1/lldb-x86_64-debian/llvm-project/lldb/test/Shell/SymbolFile/DWARF/x86/dwp-foreign-type-units.cpp -o /home/worker/2.0.1/lldb-x86_64-debian/build/tools/lldb/test/Shell/SymbolFile/DWARF/x86/Output/dwp-foreign-type-units.cpp.tmp.foo.o RUN: at line 25: /home/worker/2.0.1/lldb-x86_64-debian/build/bin/ld.lld /home/worker/2.0.1/lldb-x86_64-debian/build/tools/lldb/test/Shell/SymbolFile/DWARF/x86/Output/dwp-foreign-type-units.cpp.tmp.main.o /home/worker/2.0.1/lldb-x86_64-debian/build/tools/lldb/test/Shell/SymbolFile/DWARF/x86/Output/dwp-foreign-type-units.cpp.tmp.foo.o -o /home/worker/2.0.1/lldb-x86_64-debian/build/tools/lldb/test/Shell/SymbolFile/DWARF/x86/Output/dwp-foreign-type-units.cpp.tmp + /home/worker/2.0.1/lldb-x86_64-debian/build/bin/ld.lld /home/worker/2.0.1/lldb-x86_64-debian/build/tools/lldb/test/Shell/SymbolFile/DWARF/x86/Output/dwp-foreign-type-units.cpp.tmp.main.o /home/worker/2.0.1/lldb-x86_64-debian/build/tools/lldb/test/Shell/SymbolFile/DWARF/x86/Output/dwp-foreign-type-units.cpp.tmp.foo.o -o /home/worker/2.0.1/lldb-x86_64-debian/build/tools/lldb/test/Shell/SymbolFile/DWARF/x86/Output/dwp-foreign-type-units.cpp.tmp ld.lld: warning: cannot find entry symbol _start; not setting start address RUN: at line 28: rm -f /home/worker/2.0.1/lldb-x86_64-debian/build/tools/lldb/test/Shell/SymbolFile/DWARF/x86/Output/dwp-foreign-type-units.cpp.tmp.dwp + rm -f /home/worker/2.0.1/lldb-x86_64-debian/build/tools/lldb/test/Shell/SymbolFile/DWARF/x86/Output/dwp-foreign-type-units.cpp.tmp.dwp RUN: at line 29: /home/worker/2.0.1/lldb-x86_64-debian/build/bin/lldb --no-lldbinit -S /home/worker/2.0.1/lldb-x86_64-debian/build/tools/lldb/test/Shell/lit-lldb-init-quiet -o "type lookup IntegerType"-o "type lookup FloatType"-o "type lookup CustomType"-b /home/worker/2.0.1/lldb-x86_64-debian/build/tools/lldb/test/Shell/SymbolFile/DWARF/x
[clang] [llvm] [PowerPC] Add support for -mcpu=pwr11 / -mtune=pwr11 (PR #97760)
https://github.com/azhan92 created https://github.com/llvm/llvm-project/pull/97760 This PR adds support for -mcpu=pwr11/power11 and -mtune=pwr11/power11 in clang and llvm. >From abc838a57ffd1fb97206d76c3b8a8ed04fa18799 Mon Sep 17 00:00:00 2001 From: Alison Zhang Date: Thu, 4 Jul 2024 15:25:09 -0400 Subject: [PATCH 1/2] Add support for -mcpu=pwr11 / -mtune=pwr11 --- clang/lib/Basic/Targets/PPC.cpp | 39 --- clang/lib/Basic/Targets/PPC.h | 19 ++--- clang/lib/Driver/ToolChains/Arch/PPC.cpp | 3 ++ clang/test/Misc/target-invalid-cpu-note.c | 2 +- clang/test/Preprocessor/init-ppc64.c | 20 ++ llvm/lib/Target/PowerPC/PPC.td| 21 -- llvm/lib/Target/PowerPC/PPCISelLowering.cpp | 1 + .../Target/PowerPC/PPCTargetTransformInfo.cpp | 4 +- llvm/lib/TargetParser/Host.cpp| 1 + 9 files changed, 85 insertions(+), 25 deletions(-) diff --git a/clang/lib/Basic/Targets/PPC.cpp b/clang/lib/Basic/Targets/PPC.cpp index 89c5566f7ad09..78ee7fa7fcc76 100644 --- a/clang/lib/Basic/Targets/PPC.cpp +++ b/clang/lib/Basic/Targets/PPC.cpp @@ -383,6 +383,8 @@ void PPCTargetInfo::getTargetDefines(const LangOptions &Opts, Builder.defineMacro("_ARCH_PWR9"); if (ArchDefs & ArchDefinePwr10) Builder.defineMacro("_ARCH_PWR10"); + if (ArchDefs & ArchDefinePwr11) +Builder.defineMacro("_ARCH_PWR11"); if (ArchDefs & ArchDefineA2) Builder.defineMacro("_ARCH_A2"); if (ArchDefs & ArchDefineE500) @@ -620,10 +622,17 @@ bool PPCTargetInfo::initFeatureMap( addP10SpecificFeatures(Features); } - // Future CPU should include all of the features of Power 10 as well as any + // Power11 includes all the same features as Power10 plus any features specific + // to the Power11 core. + if (CPU == "pwr11" || CPU == "power11") { +initFeatureMap(Features, Diags, "pwr10", FeaturesVec); +addP11SpecificFeatures(Features); + } + + // Future CPU should include all of the features of Power 11 as well as any // additional features (yet to be determined) specific to it. if (CPU == "future") { -initFeatureMap(Features, Diags, "pwr10", FeaturesVec); +initFeatureMap(Features, Diags, "pwr11", FeaturesVec); addFutureSpecificFeatures(Features); } @@ -694,6 +703,10 @@ void PPCTargetInfo::addP10SpecificFeatures( Features["isa-v31-instructions"] = true; } +// Add any Power11 specific features. +void PPCTargetInfo::addP11SpecificFeatures( +llvm::StringMap &Features) const {} + // Add features specific to the "Future" CPU. void PPCTargetInfo::addFutureSpecificFeatures( llvm::StringMap &Features) const {} @@ -867,17 +880,17 @@ ArrayRef PPCTargetInfo::getGCCAddlRegNames() const { } static constexpr llvm::StringLiteral ValidCPUNames[] = { -{"generic"}, {"440"}, {"450"},{"601"}, {"602"}, -{"603"}, {"603e"},{"603ev"}, {"604"}, {"604e"}, -{"620"}, {"630"}, {"g3"}, {"7400"}, {"g4"}, -{"7450"},{"g4+"}, {"750"},{"8548"}, {"970"}, -{"g5"}, {"a2"}, {"e500"}, {"e500mc"},{"e5500"}, -{"power3"}, {"pwr3"},{"power4"}, {"pwr4"}, {"power5"}, -{"pwr5"},{"power5x"}, {"pwr5x"}, {"power6"},{"pwr6"}, -{"power6x"}, {"pwr6x"}, {"power7"}, {"pwr7"}, {"power8"}, -{"pwr8"},{"power9"}, {"pwr9"}, {"power10"}, {"pwr10"}, -{"powerpc"}, {"ppc"}, {"ppc32"}, {"powerpc64"}, {"ppc64"}, -{"powerpc64le"}, {"ppc64le"}, {"future"}}; +{"generic"}, {"440"}, {"450"}, {"601"}, {"602"}, +{"603"}, {"603e"},{"603ev"}, {"604"}, {"604e"}, +{"620"}, {"630"}, {"g3"}, {"7400"},{"g4"}, +{"7450"}, {"g4+"}, {"750"}, {"8548"},{"970"}, +{"g5"},{"a2"}, {"e500"},{"e500mc"}, {"e5500"}, +{"power3"},{"pwr3"},{"power4"}, {"pwr4"},{"power5"}, +{"pwr5"}, {"power5x"}, {"pwr5x"}, {"power6"}, {"pwr6"}, +{"power6x"}, {"pwr6x"}, {"power7"}, {"pwr7"},{"power8"}, +{"pwr8"}, {"power9"}, {"pwr9"},{"power10"}, {"pwr10"}, +{"power11"}, {"pwr11"}, {"powerpc"}, {"ppc"}, {"ppc32"}, +{"powerpc64"}, {"ppc64"}, {"powerpc64le"}, {"ppc64le"}, {"future"}}; bool PPCTargetInfo::isValidCPUName(StringRef Name) const { return llvm::is_contained(ValidCPUNames, Name); diff --git a/clang/lib/Basic/Targets/PPC.h b/clang/lib/Basic/Targets/PPC.h index e4d6a02386da5..7bc366c6178e1 100644 --- a/clang/lib/Basic/Targets/PPC.h +++ b/clang/lib/Basic/Targets/PPC.h @@ -44,8 +44,9 @@ class LLVM_LIBRARY_VISIBILITY PPCTargetInfo : public TargetInfo { ArchDefinePwr8 = 1 << 12, ArchDefinePwr9 = 1 << 13, ArchDefinePwr10 = 1 << 14, -ArchDefineFuture = 1 << 15, -ArchDefineA2 = 1 << 16, +ArchDefinePwr11 = 1 << 15, +Ar
[clang] [llvm] [PowerPC] Add support for -mcpu=pwr11 / -mtune=pwr11 (PR #97760)
llvmbot wrote: @llvm/pr-subscribers-clang @llvm/pr-subscribers-backend-powerpc Author: None (azhan92) Changes This PR adds support for -mcpu=pwr11/power11 and -mtune=pwr11/power11 in clang and llvm. --- Full diff: https://github.com/llvm/llvm-project/pull/97760.diff 9 Files Affected: - (modified) clang/lib/Basic/Targets/PPC.cpp (+26-13) - (modified) clang/lib/Basic/Targets/PPC.h (+13-6) - (modified) clang/lib/Driver/ToolChains/Arch/PPC.cpp (+3) - (modified) clang/test/Misc/target-invalid-cpu-note.c (+1-1) - (modified) clang/test/Preprocessor/init-ppc64.c (+20) - (modified) llvm/lib/Target/PowerPC/PPC.td (+18-3) - (modified) llvm/lib/Target/PowerPC/PPCISelLowering.cpp (+1) - (modified) llvm/lib/Target/PowerPC/PPCTargetTransformInfo.cpp (+2-2) - (modified) llvm/lib/TargetParser/Host.cpp (+1) ``diff diff --git a/clang/lib/Basic/Targets/PPC.cpp b/clang/lib/Basic/Targets/PPC.cpp index 89c5566f7ad09..78ee7fa7fcc76 100644 --- a/clang/lib/Basic/Targets/PPC.cpp +++ b/clang/lib/Basic/Targets/PPC.cpp @@ -383,6 +383,8 @@ void PPCTargetInfo::getTargetDefines(const LangOptions &Opts, Builder.defineMacro("_ARCH_PWR9"); if (ArchDefs & ArchDefinePwr10) Builder.defineMacro("_ARCH_PWR10"); + if (ArchDefs & ArchDefinePwr11) +Builder.defineMacro("_ARCH_PWR11"); if (ArchDefs & ArchDefineA2) Builder.defineMacro("_ARCH_A2"); if (ArchDefs & ArchDefineE500) @@ -620,10 +622,17 @@ bool PPCTargetInfo::initFeatureMap( addP10SpecificFeatures(Features); } - // Future CPU should include all of the features of Power 10 as well as any + // Power11 includes all the same features as Power10 plus any features specific + // to the Power11 core. + if (CPU == "pwr11" || CPU == "power11") { +initFeatureMap(Features, Diags, "pwr10", FeaturesVec); +addP11SpecificFeatures(Features); + } + + // Future CPU should include all of the features of Power 11 as well as any // additional features (yet to be determined) specific to it. if (CPU == "future") { -initFeatureMap(Features, Diags, "pwr10", FeaturesVec); +initFeatureMap(Features, Diags, "pwr11", FeaturesVec); addFutureSpecificFeatures(Features); } @@ -694,6 +703,10 @@ void PPCTargetInfo::addP10SpecificFeatures( Features["isa-v31-instructions"] = true; } +// Add any Power11 specific features. +void PPCTargetInfo::addP11SpecificFeatures( +llvm::StringMap &Features) const {} + // Add features specific to the "Future" CPU. void PPCTargetInfo::addFutureSpecificFeatures( llvm::StringMap &Features) const {} @@ -867,17 +880,17 @@ ArrayRef PPCTargetInfo::getGCCAddlRegNames() const { } static constexpr llvm::StringLiteral ValidCPUNames[] = { -{"generic"}, {"440"}, {"450"},{"601"}, {"602"}, -{"603"}, {"603e"},{"603ev"}, {"604"}, {"604e"}, -{"620"}, {"630"}, {"g3"}, {"7400"}, {"g4"}, -{"7450"},{"g4+"}, {"750"},{"8548"}, {"970"}, -{"g5"}, {"a2"}, {"e500"}, {"e500mc"},{"e5500"}, -{"power3"}, {"pwr3"},{"power4"}, {"pwr4"}, {"power5"}, -{"pwr5"},{"power5x"}, {"pwr5x"}, {"power6"},{"pwr6"}, -{"power6x"}, {"pwr6x"}, {"power7"}, {"pwr7"}, {"power8"}, -{"pwr8"},{"power9"}, {"pwr9"}, {"power10"}, {"pwr10"}, -{"powerpc"}, {"ppc"}, {"ppc32"}, {"powerpc64"}, {"ppc64"}, -{"powerpc64le"}, {"ppc64le"}, {"future"}}; +{"generic"}, {"440"}, {"450"}, {"601"}, {"602"}, +{"603"}, {"603e"},{"603ev"}, {"604"}, {"604e"}, +{"620"}, {"630"}, {"g3"}, {"7400"},{"g4"}, +{"7450"}, {"g4+"}, {"750"}, {"8548"},{"970"}, +{"g5"},{"a2"}, {"e500"},{"e500mc"}, {"e5500"}, +{"power3"},{"pwr3"},{"power4"}, {"pwr4"},{"power5"}, +{"pwr5"}, {"power5x"}, {"pwr5x"}, {"power6"}, {"pwr6"}, +{"power6x"}, {"pwr6x"}, {"power7"}, {"pwr7"},{"power8"}, +{"pwr8"}, {"power9"}, {"pwr9"},{"power10"}, {"pwr10"}, +{"power11"}, {"pwr11"}, {"powerpc"}, {"ppc"}, {"ppc32"}, +{"powerpc64"}, {"ppc64"}, {"powerpc64le"}, {"ppc64le"}, {"future"}}; bool PPCTargetInfo::isValidCPUName(StringRef Name) const { return llvm::is_contained(ValidCPUNames, Name); diff --git a/clang/lib/Basic/Targets/PPC.h b/clang/lib/Basic/Targets/PPC.h index e4d6a02386da5..c1f0cfc1481d6 100644 --- a/clang/lib/Basic/Targets/PPC.h +++ b/clang/lib/Basic/Targets/PPC.h @@ -44,8 +44,9 @@ class LLVM_LIBRARY_VISIBILITY PPCTargetInfo : public TargetInfo { ArchDefinePwr8 = 1 << 12, ArchDefinePwr9 = 1 << 13, ArchDefinePwr10 = 1 << 14, -ArchDefineFuture = 1 << 15, -ArchDefineA2 = 1 << 16, +ArchDefinePwr11 = 1 << 15, +ArchDefineFuture = 1 << 16, +ArchDefineA2 = 1 << 17, ArchDefineE500 = 1 << 18 } ArchDefineTypes; @@ -165,11
[clang] [FMV][AArch64] Do not emit ifunc resolver on use. (PR #97761)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Alexandros Lamprineas (labrinea) Changes It was raised in https://github.com/llvm/llvm-project/issues/81494 that we are not generating correct code when there is no TU-local caller. The suggestion was to emit a resolver: * Whenever there is a use in the TU. * When the TU has a definition of the default version. See the comment for more details: https://github.com/llvm/llvm-project/issues/81494#issuecomment-1985963497 This got addressed with https://github.com/llvm/llvm-project/pull/84405. Generating a resolver on use means that we may end up with multiple resolvers across different translation units. Those resolvers may not be the same because each translation unit may contain different version declarations (user's fault). Therefore the order of linking the final image determines which of these weak symbols gets selected, resulting in non consisted behavior. I am proposing to stop emitting a resolver on use and only do so in the translation unit which contains the default defition. This way we guarantee the existance of a single resolver. Now, when a versioned function is used we want to emit a declaration of the function symbol omitting the multiversion mangling. I have added a requirement to ACLE mandating that all the function versions are declared in the translation unit which contains the default definition: https://github.com/ARM-software/acle/pull/328 --- Patch is 103.86 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/97761.diff 7 Files Affected: - (modified) clang/lib/CodeGen/CodeGenModule.cpp (+44-46) - (modified) clang/test/CodeGen/aarch64-mixed-target-attributes.c (+3-3) - (modified) clang/test/CodeGen/attr-target-clones-aarch64.c (+174-174) - (modified) clang/test/CodeGen/attr-target-version.c (+355-449) - (modified) clang/test/CodeGenCXX/attr-target-clones-aarch64.cpp (+112-98) - (modified) clang/test/CodeGenCXX/attr-target-version.cpp (+59-22) - (modified) clang/test/CodeGenCXX/fmv-namespace.cpp (+17-32) ``diff diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp index 99e986d371cac..ede1b641584f3 100644 --- a/clang/lib/CodeGen/CodeGenModule.cpp +++ b/clang/lib/CodeGen/CodeGenModule.cpp @@ -3772,8 +3772,7 @@ void CodeGenModule::EmitGlobal(GlobalDecl GD) { // Forward declarations are emitted lazily on first use. if (!FD->doesThisDeclarationHaveABody()) { if (!FD->doesDeclarationForceExternallyVisibleDefinition() && - (!FD->isMultiVersion() || - !FD->getASTContext().getTargetInfo().getTriple().isAArch64())) + (!FD->isMultiVersion() || !getTarget().getTriple().isAArch64())) return; StringRef MangledName = getMangledName(GD); @@ -4167,23 +4166,6 @@ llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM, return llvm::GlobalValue::WeakODRLinkage; } -static FunctionDecl *createDefaultTargetVersionFrom(const FunctionDecl *FD) { - auto *DeclCtx = const_cast(FD->getDeclContext()); - TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); - StorageClass SC = FD->getStorageClass(); - DeclarationName Name = FD->getNameInfo().getName(); - - FunctionDecl *NewDecl = - FunctionDecl::Create(FD->getASTContext(), DeclCtx, FD->getBeginLoc(), - FD->getEndLoc(), Name, TInfo->getType(), TInfo, SC); - - NewDecl->setIsMultiVersion(); - NewDecl->addAttr(TargetVersionAttr::CreateImplicit( - NewDecl->getASTContext(), "default", NewDecl->getSourceRange())); - - return NewDecl; -} - void CodeGenModule::emitMultiVersionFunctions() { std::vector MVFuncsToEmit; MultiVersionFuncs.swap(MVFuncsToEmit); @@ -4210,9 +4192,7 @@ void CodeGenModule::emitMultiVersionFunctions() { return cast(Func); }; -bool HasDefaultDecl = !FD->isTargetVersionMultiVersion(); -bool ShouldEmitResolver = -!getContext().getTargetInfo().getTriple().isAArch64(); +bool ShouldEmitResolver = !getTarget().getTriple().isAArch64(); SmallVector Options; getContext().forEachMultiversionedFunctionVersion( @@ -4224,10 +4204,8 @@ void CodeGenModule::emitMultiVersionFunctions() { llvm::Function *Func = createFunction(CurFD); Options.emplace_back(Func, TA->getArchitecture(), Feats); } else if (const auto *TVA = CurFD->getAttr()) { -bool HasDefaultDef = TVA->isDefaultVersion() && - CurFD->doesThisDeclarationHaveABody(); -HasDefaultDecl |= TVA->isDefaultVersion(); -ShouldEmitResolver |= (CurFD->isUsed() || HasDefaultDef); +ShouldEmitResolver |= (TVA->isDefaultVersion() && + CurFD->doesThisDeclarationHaveABody()); TVA->getFeatures(Feats); llvm::Function *Func = createFunction(CurFD); Options.emplace_back(Func, /*Architecture*/ "", Feats);
[clang] [FMV][AArch64] Do not emit ifunc resolver on use. (PR #97761)
llvmbot wrote: @llvm/pr-subscribers-clang-codegen Author: Alexandros Lamprineas (labrinea) Changes It was raised in https://github.com/llvm/llvm-project/issues/81494 that we are not generating correct code when there is no TU-local caller. The suggestion was to emit a resolver: * Whenever there is a use in the TU. * When the TU has a definition of the default version. See the comment for more details: https://github.com/llvm/llvm-project/issues/81494#issuecomment-1985963497 This got addressed with https://github.com/llvm/llvm-project/pull/84405. Generating a resolver on use means that we may end up with multiple resolvers across different translation units. Those resolvers may not be the same because each translation unit may contain different version declarations (user's fault). Therefore the order of linking the final image determines which of these weak symbols gets selected, resulting in non consisted behavior. I am proposing to stop emitting a resolver on use and only do so in the translation unit which contains the default defition. This way we guarantee the existance of a single resolver. Now, when a versioned function is used we want to emit a declaration of the function symbol omitting the multiversion mangling. I have added a requirement to ACLE mandating that all the function versions are declared in the translation unit which contains the default definition: https://github.com/ARM-software/acle/pull/328 --- Patch is 103.86 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/97761.diff 7 Files Affected: - (modified) clang/lib/CodeGen/CodeGenModule.cpp (+44-46) - (modified) clang/test/CodeGen/aarch64-mixed-target-attributes.c (+3-3) - (modified) clang/test/CodeGen/attr-target-clones-aarch64.c (+174-174) - (modified) clang/test/CodeGen/attr-target-version.c (+355-449) - (modified) clang/test/CodeGenCXX/attr-target-clones-aarch64.cpp (+112-98) - (modified) clang/test/CodeGenCXX/attr-target-version.cpp (+59-22) - (modified) clang/test/CodeGenCXX/fmv-namespace.cpp (+17-32) ``diff diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp index 99e986d371cac..ede1b641584f3 100644 --- a/clang/lib/CodeGen/CodeGenModule.cpp +++ b/clang/lib/CodeGen/CodeGenModule.cpp @@ -3772,8 +3772,7 @@ void CodeGenModule::EmitGlobal(GlobalDecl GD) { // Forward declarations are emitted lazily on first use. if (!FD->doesThisDeclarationHaveABody()) { if (!FD->doesDeclarationForceExternallyVisibleDefinition() && - (!FD->isMultiVersion() || - !FD->getASTContext().getTargetInfo().getTriple().isAArch64())) + (!FD->isMultiVersion() || !getTarget().getTriple().isAArch64())) return; StringRef MangledName = getMangledName(GD); @@ -4167,23 +4166,6 @@ llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM, return llvm::GlobalValue::WeakODRLinkage; } -static FunctionDecl *createDefaultTargetVersionFrom(const FunctionDecl *FD) { - auto *DeclCtx = const_cast(FD->getDeclContext()); - TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); - StorageClass SC = FD->getStorageClass(); - DeclarationName Name = FD->getNameInfo().getName(); - - FunctionDecl *NewDecl = - FunctionDecl::Create(FD->getASTContext(), DeclCtx, FD->getBeginLoc(), - FD->getEndLoc(), Name, TInfo->getType(), TInfo, SC); - - NewDecl->setIsMultiVersion(); - NewDecl->addAttr(TargetVersionAttr::CreateImplicit( - NewDecl->getASTContext(), "default", NewDecl->getSourceRange())); - - return NewDecl; -} - void CodeGenModule::emitMultiVersionFunctions() { std::vector MVFuncsToEmit; MultiVersionFuncs.swap(MVFuncsToEmit); @@ -4210,9 +4192,7 @@ void CodeGenModule::emitMultiVersionFunctions() { return cast(Func); }; -bool HasDefaultDecl = !FD->isTargetVersionMultiVersion(); -bool ShouldEmitResolver = -!getContext().getTargetInfo().getTriple().isAArch64(); +bool ShouldEmitResolver = !getTarget().getTriple().isAArch64(); SmallVector Options; getContext().forEachMultiversionedFunctionVersion( @@ -4224,10 +4204,8 @@ void CodeGenModule::emitMultiVersionFunctions() { llvm::Function *Func = createFunction(CurFD); Options.emplace_back(Func, TA->getArchitecture(), Feats); } else if (const auto *TVA = CurFD->getAttr()) { -bool HasDefaultDef = TVA->isDefaultVersion() && - CurFD->doesThisDeclarationHaveABody(); -HasDefaultDecl |= TVA->isDefaultVersion(); -ShouldEmitResolver |= (CurFD->isUsed() || HasDefaultDef); +ShouldEmitResolver |= (TVA->isDefaultVersion() && + CurFD->doesThisDeclarationHaveABody()); TVA->getFeatures(Feats); llvm::Function *Func = createFunction(CurFD); Options.emplace_back(Func, /*Architecture*/ "",
[clang] [llvm] [PowerPC] Add support for -mcpu=pwr11 / -mtune=pwr11 (PR #97760)
github-actions[bot] wrote: :warning: C/C++ code formatter, clang-format found issues in your code. :warning: You can test this locally with the following command: ``bash git-clang-format --diff d1dc4169838381688a74f245cdaedbe9fce13848 cbcbf4cd1a0e07986268955e598047efdd069dcc -- clang/lib/Basic/Targets/PPC.cpp clang/lib/Basic/Targets/PPC.h clang/lib/Driver/ToolChains/Arch/PPC.cpp clang/test/Misc/target-invalid-cpu-note.c clang/test/Preprocessor/init-ppc64.c llvm/lib/Target/PowerPC/PPCISelLowering.cpp llvm/lib/Target/PowerPC/PPCTargetTransformInfo.cpp llvm/lib/TargetParser/Host.cpp `` View the diff from clang-format here. ``diff diff --git a/clang/lib/Basic/Targets/PPC.cpp b/clang/lib/Basic/Targets/PPC.cpp index 78ee7fa7fc..19363beabf 100644 --- a/clang/lib/Basic/Targets/PPC.cpp +++ b/clang/lib/Basic/Targets/PPC.cpp @@ -622,8 +622,8 @@ bool PPCTargetInfo::initFeatureMap( addP10SpecificFeatures(Features); } - // Power11 includes all the same features as Power10 plus any features specific - // to the Power11 core. + // Power11 includes all the same features as Power10 plus any features + // specific to the Power11 core. if (CPU == "pwr11" || CPU == "power11") { initFeatureMap(Features, Diags, "pwr10", FeaturesVec); addP11SpecificFeatures(Features); diff --git a/clang/lib/Basic/Targets/PPC.h b/clang/lib/Basic/Targets/PPC.h index c1f0cfc148..b57f855c63 100644 --- a/clang/lib/Basic/Targets/PPC.h +++ b/clang/lib/Basic/Targets/PPC.h @@ -172,10 +172,10 @@ public: ArchDefinePwr5x | ArchDefinePwr5 | ArchDefinePwr4 | ArchDefinePpcgr | ArchDefinePpcsq) .Case("future", - ArchDefineFuture | ArchDefinePwr11 | ArchDefinePwr10 | - ArchDefinePwr9 | ArchDefinePwr8 | ArchDefinePwr7 | - ArchDefinePwr6 | ArchDefinePwr5x | ArchDefinePwr5 | - ArchDefinePwr4 | ArchDefinePpcgr | ArchDefinePpcsq) +ArchDefineFuture | ArchDefinePwr11 | ArchDefinePwr10 | +ArchDefinePwr9 | ArchDefinePwr8 | ArchDefinePwr7 | +ArchDefinePwr6 | ArchDefinePwr5x | ArchDefinePwr5 | +ArchDefinePwr4 | ArchDefinePpcgr | ArchDefinePpcsq) .Cases("8548", "e500", ArchDefineE500) .Default(ArchDefineNone); } `` https://github.com/llvm/llvm-project/pull/97760 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits