[clang] [CodeGen] Remove unused includes (NFC) (PR #116459)
https://github.com/kazutakahirata closed https://github.com/llvm/llvm-project/pull/116459 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Parse] Remove ParseDiagnostic.h (PR #116496)
cor3ntin wrote: Can you explain what is the perceived benefit of this change? Thanks https://github.com/llvm/llvm-project/pull/116496 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clangd] Harden incomingCalls() against possible misinterpretation of a range as pertaining to the wrong file (PR #111616)
https://github.com/HighCommander4 updated https://github.com/llvm/llvm-project/pull/111616 >From 3d0c93948072cd2412a656a38f48de3d6e23e996 Mon Sep 17 00:00:00 2001 From: timon-ul Date: Sun, 3 Nov 2024 07:38:25 +0100 Subject: [PATCH 1/3] Support call hierarchy for fields and non-local variables (#113900) Fixes https://github.com/clangd/clangd/issues/1308 --- clang-tools-extra/clangd/XRefs.cpp| 5 ++- .../clangd/unittests/CallHierarchyTests.cpp | 45 +++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/clang-tools-extra/clangd/XRefs.cpp b/clang-tools-extra/clangd/XRefs.cpp index f94cadeffaa298..70107e8a5b1517 100644 --- a/clang-tools-extra/clangd/XRefs.cpp +++ b/clang-tools-extra/clangd/XRefs.cpp @@ -2238,7 +2238,10 @@ prepareCallHierarchy(ParsedAST &AST, Position Pos, PathRef TUPath) { for (const NamedDecl *Decl : getDeclAtPosition(AST, *Loc, {})) { if (!(isa(Decl) && cast(Decl)->isFunctionOrMethod()) && -Decl->getKind() != Decl::Kind::FunctionTemplate) +Decl->getKind() != Decl::Kind::FunctionTemplate && +!(Decl->getKind() == Decl::Kind::Var && + !cast(Decl)->isLocalVarDecl()) && +Decl->getKind() != Decl::Kind::Field) continue; if (auto CHI = declToCallHierarchyItem(*Decl, AST.tuPath())) Result.emplace_back(std::move(*CHI)); diff --git a/clang-tools-extra/clangd/unittests/CallHierarchyTests.cpp b/clang-tools-extra/clangd/unittests/CallHierarchyTests.cpp index 6fa76aa6094bf2..b2278ff12735dc 100644 --- a/clang-tools-extra/clangd/unittests/CallHierarchyTests.cpp +++ b/clang-tools-extra/clangd/unittests/CallHierarchyTests.cpp @@ -446,6 +446,51 @@ TEST(CallHierarchy, CallInLocalVarDecl) { AllOf(from(withName("caller3")), fromRanges(Source.range("call3"); } +TEST(CallHierarchy, HierarchyOnField) { + // Tests that the call hierarchy works on fields. + Annotations Source(R"cpp( +struct Vars { + int v^ar1 = 1; +}; +void caller() { + Vars values; + values.$Callee[[var1]]; +} + )cpp"); + TestTU TU = TestTU::withCode(Source.code()); + auto AST = TU.build(); + auto Index = TU.index(); + + std::vector Items = + prepareCallHierarchy(AST, Source.point(), testPath(TU.Filename)); + ASSERT_THAT(Items, ElementsAre(withName("var1"))); + auto IncomingLevel1 = incomingCalls(Items[0], Index.get()); + ASSERT_THAT(IncomingLevel1, + ElementsAre(AllOf(from(withName("caller")), +fromRanges(Source.range("Callee"); +} + +TEST(CallHierarchy, HierarchyOnVar) { + // Tests that the call hierarchy works on non-local variables. + Annotations Source(R"cpp( +int v^ar = 1; +void caller() { + $Callee[[var]]; +} + )cpp"); + TestTU TU = TestTU::withCode(Source.code()); + auto AST = TU.build(); + auto Index = TU.index(); + + std::vector Items = + prepareCallHierarchy(AST, Source.point(), testPath(TU.Filename)); + ASSERT_THAT(Items, ElementsAre(withName("var"))); + auto IncomingLevel1 = incomingCalls(Items[0], Index.get()); + ASSERT_THAT(IncomingLevel1, + ElementsAre(AllOf(from(withName("caller")), +fromRanges(Source.range("Callee"); +} + } // namespace } // namespace clangd } // namespace clang >From 8e1e1995344e511b846c500b8cc4eca02012c6b3 Mon Sep 17 00:00:00 2001 From: Kazu Hirata Date: Fri, 11 Oct 2024 09:00:39 -0700 Subject: [PATCH 2/3] [clangd] Simplify code with *Map::operator[] (NFC) (#111939) --- clang-tools-extra/clangd/Headers.cpp | 4 ++-- clang-tools-extra/clangd/XRefs.cpp | 3 +-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/clang-tools-extra/clangd/Headers.cpp b/clang-tools-extra/clangd/Headers.cpp index 75f8668e7bef06..b537417bd10568 100644 --- a/clang-tools-extra/clangd/Headers.cpp +++ b/clang-tools-extra/clangd/Headers.cpp @@ -75,8 +75,8 @@ class IncludeStructure::RecordHeaders : public PPCallbacks { IDs.push_back(HID); } } - Out->MainFileIncludesBySpelling.try_emplace(Inc.Written) - .first->second.push_back(Out->MainFileIncludes.size() - 1); + Out->MainFileIncludesBySpelling[Inc.Written].push_back( + Out->MainFileIncludes.size() - 1); } // Record include graph (not just for main-file includes) diff --git a/clang-tools-extra/clangd/XRefs.cpp b/clang-tools-extra/clangd/XRefs.cpp index 70107e8a5b1517..4fd11307857ff8 100644 --- a/clang-tools-extra/clangd/XRefs.cpp +++ b/clang-tools-extra/clangd/XRefs.cpp @@ -2285,8 +2285,7 @@ incomingCalls(const CallHierarchyItem &Item, const SymbolIndex *Index) { elog("incomingCalls failed to convert location: {0}", Loc.takeError()); return; } -auto It = CallsIn.try_emplace(R.Container, std::vector{}).first; -It->second.push_back(Loc->range); +CallsIn[R.Container].push_back(Loc->range); ContainerLookup.IDs.insert(R.Container); }); >From
[clang-tools-extra] [clangd] Harden incomingCalls() against possible misinterpretation of a range as pertaining to the wrong file (PR #111616)
https://github.com/HighCommander4 updated https://github.com/llvm/llvm-project/pull/111616 >From c72cc8dedc165091654eb5d922927319327f34c4 Mon Sep 17 00:00:00 2001 From: Nathan Ridge Date: Tue, 8 Oct 2024 21:43:55 -0400 Subject: [PATCH] [clangd] Harden incomingCalls() against possible misinterpretation of a range as pertaining to the wrong file --- clang-tools-extra/clangd/XRefs.cpp| 23 +++ .../clangd/unittests/CallHierarchyTests.cpp | 29 +++ 2 files changed, 47 insertions(+), 5 deletions(-) diff --git a/clang-tools-extra/clangd/XRefs.cpp b/clang-tools-extra/clangd/XRefs.cpp index f94cadeffaa298..424b6800f1960f 100644 --- a/clang-tools-extra/clangd/XRefs.cpp +++ b/clang-tools-extra/clangd/XRefs.cpp @@ -63,6 +63,7 @@ #include "llvm/ADT/StringRef.h" #include "llvm/Support/Casting.h" #include "llvm/Support/Error.h" +#include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" #include @@ -2272,7 +2273,7 @@ incomingCalls(const CallHierarchyItem &Item, const SymbolIndex *Index) { // Initially store the ranges in a map keyed by SymbolID of the caller. // This allows us to group different calls with the same caller // into the same CallHierarchyIncomingCall. - llvm::DenseMap> CallsIn; + llvm::DenseMap> CallsIn; // We can populate the ranges based on a refs request only. As we do so, we // also accumulate the container IDs into a lookup request. LookupRequest ContainerLookup; @@ -2282,8 +2283,8 @@ incomingCalls(const CallHierarchyItem &Item, const SymbolIndex *Index) { elog("incomingCalls failed to convert location: {0}", Loc.takeError()); return; } -auto It = CallsIn.try_emplace(R.Container, std::vector{}).first; -It->second.push_back(Loc->range); +auto It = CallsIn.try_emplace(R.Container, std::vector{}).first; +It->second.push_back(*Loc); ContainerLookup.IDs.insert(R.Container); }); @@ -2292,9 +2293,21 @@ incomingCalls(const CallHierarchyItem &Item, const SymbolIndex *Index) { Index->lookup(ContainerLookup, [&](const Symbol &Caller) { auto It = CallsIn.find(Caller.ID); assert(It != CallsIn.end()); -if (auto CHI = symbolToCallHierarchyItem(Caller, Item.uri.file())) +if (auto CHI = symbolToCallHierarchyItem(Caller, Item.uri.file())) { + std::vector FromRanges; + for (const Location &L : It->second) { +if (L.uri != CHI->uri) { + // Call location not in same file as caller. + // This can happen in some edge cases. There's not much we can do, + // since the protocol only allows returning ranges interpreted as + // being in the caller's file. + continue; +} +FromRanges.push_back(L.range); + } Results.push_back( - CallHierarchyIncomingCall{std::move(*CHI), std::move(It->second)}); + CallHierarchyIncomingCall{std::move(*CHI), std::move(FromRanges)}); +} }); // Sort results by name of container. llvm::sort(Results, [](const CallHierarchyIncomingCall &A, diff --git a/clang-tools-extra/clangd/unittests/CallHierarchyTests.cpp b/clang-tools-extra/clangd/unittests/CallHierarchyTests.cpp index 6fa76aa6094bf2..9518bc5041bcca 100644 --- a/clang-tools-extra/clangd/unittests/CallHierarchyTests.cpp +++ b/clang-tools-extra/clangd/unittests/CallHierarchyTests.cpp @@ -446,6 +446,35 @@ TEST(CallHierarchy, CallInLocalVarDecl) { AllOf(from(withName("caller3")), fromRanges(Source.range("call3"); } +TEST(CallHierarchy, CallInDifferentFileThanCaller) { + Annotations Header(R"cpp( +#define WALDO void caller() { + )cpp"); + Annotations Source(R"cpp( +void call^ee(); +WALDO + callee(); +} + )cpp"); + auto TU = TestTU::withCode(Source.code()); + TU.HeaderCode = Header.code(); + auto AST = TU.build(); + auto Index = TU.index(); + + std::vector Items = + prepareCallHierarchy(AST, Source.point(), testPath(TU.Filename)); + ASSERT_THAT(Items, ElementsAre(withName("callee"))); + + auto Incoming = incomingCalls(Items[0], Index.get()); + + // The only call site is in the source file, which is a different file from + // the declaration of the function containing the call, which is in the + // header. The protocol does not allow us to represent such calls, so we drop + // them. (The call hierarchy item itself is kept.) + EXPECT_THAT(Incoming, + ElementsAre(AllOf(from(withName("caller")), fromRanges(; +} + } // namespace } // namespace clangd } // namespace clang ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clangd] Harden incomingCalls() against possible misinterpretation of a range as pertaining to the wrong file (PR #111616)
HighCommander4 wrote: Updated patch with the following changes: * Resolve the potential UAF by storing `clangd::Location` rather than `SymbolLocation` in the `CallsIn` map * Add a testcase for the scenario from [this thread](https://github.com/llvm/llvm-project/pull/111616#discussion_r1810411700) Should be ready for another round of review. https://github.com/llvm/llvm-project/pull/111616 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clangd] Harden incomingCalls() against possible misinterpretation of a range as pertaining to the wrong file (PR #111616)
https://github.com/HighCommander4 updated https://github.com/llvm/llvm-project/pull/111616 >From d8f59628643bc6eb4d572949d7f9df6df42f0146 Mon Sep 17 00:00:00 2001 From: Nathan Ridge Date: Tue, 8 Oct 2024 21:43:55 -0400 Subject: [PATCH] [clangd] Harden incomingCalls() against possible misinterpretation of a range as pertaining to the wrong file --- clang-tools-extra/clangd/XRefs.cpp| 21 +++--- .../clangd/unittests/CallHierarchyTests.cpp | 29 +++ 2 files changed, 46 insertions(+), 4 deletions(-) diff --git a/clang-tools-extra/clangd/XRefs.cpp b/clang-tools-extra/clangd/XRefs.cpp index 4fd11307857ff8..61fa66180376cd 100644 --- a/clang-tools-extra/clangd/XRefs.cpp +++ b/clang-tools-extra/clangd/XRefs.cpp @@ -63,6 +63,7 @@ #include "llvm/ADT/StringRef.h" #include "llvm/Support/Casting.h" #include "llvm/Support/Error.h" +#include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" #include @@ -2275,7 +2276,7 @@ incomingCalls(const CallHierarchyItem &Item, const SymbolIndex *Index) { // Initially store the ranges in a map keyed by SymbolID of the caller. // This allows us to group different calls with the same caller // into the same CallHierarchyIncomingCall. - llvm::DenseMap> CallsIn; + llvm::DenseMap> CallsIn; // We can populate the ranges based on a refs request only. As we do so, we // also accumulate the container IDs into a lookup request. LookupRequest ContainerLookup; @@ -2285,7 +2286,7 @@ incomingCalls(const CallHierarchyItem &Item, const SymbolIndex *Index) { elog("incomingCalls failed to convert location: {0}", Loc.takeError()); return; } -CallsIn[R.Container].push_back(Loc->range); +CallsIn[R.Container].push_back(*Loc); ContainerLookup.IDs.insert(R.Container); }); @@ -2294,9 +2295,21 @@ incomingCalls(const CallHierarchyItem &Item, const SymbolIndex *Index) { Index->lookup(ContainerLookup, [&](const Symbol &Caller) { auto It = CallsIn.find(Caller.ID); assert(It != CallsIn.end()); -if (auto CHI = symbolToCallHierarchyItem(Caller, Item.uri.file())) +if (auto CHI = symbolToCallHierarchyItem(Caller, Item.uri.file())) { + std::vector FromRanges; + for (const Location &L : It->second) { +if (L.uri != CHI->uri) { + // Call location not in same file as caller. + // This can happen in some edge cases. There's not much we can do, + // since the protocol only allows returning ranges interpreted as + // being in the caller's file. + continue; +} +FromRanges.push_back(L.range); + } Results.push_back( - CallHierarchyIncomingCall{std::move(*CHI), std::move(It->second)}); + CallHierarchyIncomingCall{std::move(*CHI), std::move(FromRanges)}); +} }); // Sort results by name of container. llvm::sort(Results, [](const CallHierarchyIncomingCall &A, diff --git a/clang-tools-extra/clangd/unittests/CallHierarchyTests.cpp b/clang-tools-extra/clangd/unittests/CallHierarchyTests.cpp index b2278ff12735dc..8821d3aad9c784 100644 --- a/clang-tools-extra/clangd/unittests/CallHierarchyTests.cpp +++ b/clang-tools-extra/clangd/unittests/CallHierarchyTests.cpp @@ -491,6 +491,35 @@ TEST(CallHierarchy, HierarchyOnVar) { fromRanges(Source.range("Callee"); } +TEST(CallHierarchy, CallInDifferentFileThanCaller) { + Annotations Header(R"cpp( +#define WALDO void caller() { + )cpp"); + Annotations Source(R"cpp( +void call^ee(); +WALDO + callee(); +} + )cpp"); + auto TU = TestTU::withCode(Source.code()); + TU.HeaderCode = Header.code(); + auto AST = TU.build(); + auto Index = TU.index(); + + std::vector Items = + prepareCallHierarchy(AST, Source.point(), testPath(TU.Filename)); + ASSERT_THAT(Items, ElementsAre(withName("callee"))); + + auto Incoming = incomingCalls(Items[0], Index.get()); + + // The only call site is in the source file, which is a different file from + // the declaration of the function containing the call, which is in the + // header. The protocol does not allow us to represent such calls, so we drop + // them. (The call hierarchy item itself is kept.) + EXPECT_THAT(Incoming, + ElementsAre(AllOf(from(withName("caller")), fromRanges(; +} + } // namespace } // namespace clangd } // namespace clang ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [ObjC] Expand isClassLayoutKnownStatically to base classes as long as the implementation of it is known (PR #85465)
https://github.com/AreaZR updated https://github.com/llvm/llvm-project/pull/85465 >From ffbc1da0d631f3969be4f470f5f446b34adf49fc Mon Sep 17 00:00:00 2001 From: Rose Date: Fri, 15 Mar 2024 16:43:10 -0400 Subject: [PATCH] [ObjC] Expand isClassLayoutKnownStatically to base classes as long as the implementation of it is known Only NSObject we can trust the layout of won't change even though we cannot directly see its @implementation. --- clang/lib/CodeGen/CGObjCMac.cpp | 9 - clang/test/CodeGenObjC/arc-blocks.m | 8 ++--- clang/test/CodeGenObjC/arc-property.m | 22 +--- clang/test/CodeGenObjC/arc-weak-property.m| 5 ++- clang/test/CodeGenObjC/arc.m | 18 -- clang/test/CodeGenObjC/arm64-int32-ivar.m | 5 ++- .../test/CodeGenObjC/bitfield-ivar-offsets.m | 5 ++- .../constant-non-fragile-ivar-offset.m| 34 +-- clang/test/CodeGenObjC/direct-method.m| 3 +- clang/test/CodeGenObjC/hidden-visibility.m| 2 +- clang/test/CodeGenObjC/interface-layout-64.m | 16 + .../CodeGenObjC/ivar-base-as-invariant-load.m | 5 ++- clang/test/CodeGenObjC/metadata-symbols-64.m | 4 +-- .../nontrivial-c-struct-property.m| 4 ++- .../CodeGenObjC/objc-asm-attribute-test.m | 5 +-- clang/test/CodeGenObjC/ubsan-bool.m | 4 ++- 16 files changed, 96 insertions(+), 53 deletions(-) diff --git a/clang/lib/CodeGen/CGObjCMac.cpp b/clang/lib/CodeGen/CGObjCMac.cpp index 7b85dcc2c7984f..6ad08c52256ae9 100644 --- a/clang/lib/CodeGen/CGObjCMac.cpp +++ b/clang/lib/CodeGen/CGObjCMac.cpp @@ -1592,6 +1592,11 @@ class CGObjCNonFragileABIMac : public CGObjCCommonMac { bool isClassLayoutKnownStatically(const ObjCInterfaceDecl *ID) { // Test a class by checking its superclasses up to // its base class if it has one. + +// Cannot check a null class +if (!ID) + return false; + for (; ID; ID = ID->getSuperClass()) { // The layout of base class NSObject // is guaranteed to be statically known @@ -1603,7 +1608,9 @@ class CGObjCNonFragileABIMac : public CGObjCCommonMac { if (!ID->getImplementation()) return false; } -return false; + +// We know the layout of all the intermediate classes and superclasses. +return true; } public: diff --git a/clang/test/CodeGenObjC/arc-blocks.m b/clang/test/CodeGenObjC/arc-blocks.m index bed55bf18fe59f..72bf35c2e117e5 100644 --- a/clang/test/CodeGenObjC/arc-blocks.m +++ b/clang/test/CodeGenObjC/arc-blocks.m @@ -422,16 +422,16 @@ @interface Test12 @implementation Test12 @synthesize ablock, nblock; // CHECK:define internal ptr @"\01-[Test12 ablock]"( -// CHECK:call ptr @objc_getProperty(ptr noundef {{%.*}}, ptr noundef {{%.*}}, i64 noundef {{%.*}}, i1 noundef zeroext true) +// CHECK:call ptr @objc_getProperty(ptr noundef {{%.*}}, ptr noundef {{%.*}}, i64 noundef 0, i1 noundef zeroext true) // CHECK:define internal void @"\01-[Test12 setAblock:]"( -// CHECK:call void @objc_setProperty(ptr noundef {{%.*}}, ptr noundef {{%.*}}, i64 noundef {{%.*}}, ptr noundef {{%.*}}, i1 noundef zeroext true, i1 noundef zeroext true) +// CHECK:call void @objc_setProperty(ptr noundef {{%.*}}, ptr noundef {{%.*}}, i64 noundef 0, ptr noundef {{%.*}}, i1 noundef zeroext true, i1 noundef zeroext true) // CHECK:define internal ptr @"\01-[Test12 nblock]"( -// CHECK:%add.ptr = getelementptr inbounds i8, ptr %0, i64 %ivar +// CHECK:%add.ptr = getelementptr inbounds i8, ptr %0, i64 8 // CHECK:define internal void @"\01-[Test12 setNblock:]"( -// CHECK:call void @objc_setProperty(ptr noundef {{%.*}}, ptr noundef {{%.*}}, i64 noundef {{%.*}}, ptr noundef {{%.*}}, i1 noundef zeroext false, i1 noundef zeroext true) +// CHECK:call void @objc_setProperty(ptr noundef {{%.*}}, ptr noundef {{%.*}}, i64 noundef 8, ptr noundef {{%.*}}, i1 noundef zeroext false, i1 noundef zeroext true) @end void test13(id x) { diff --git a/clang/test/CodeGenObjC/arc-property.m b/clang/test/CodeGenObjC/arc-property.m index f57be6b4f6be41..3209993cc6d32c 100644 --- a/clang/test/CodeGenObjC/arc-property.m +++ b/clang/test/CodeGenObjC/arc-property.m @@ -22,16 +22,14 @@ @implementation Test1 @end // The getter should be a simple load. // CHECK:define internal ptr @"\01-[Test1 pointer]"( -// CHECK: [[OFFSET:%.*]] = load i64, ptr @"OBJC_IVAR_$_Test1.pointer" -// CHECK-NEXT: [[T1:%.*]] = getelementptr inbounds i8, ptr {{%.*}}, i64 [[OFFSET]] +// CHECK: [[T1:%.*]] = getelementptr inbounds i8, ptr {{%.*}}, i64 0 // CHECK-NEXT: [[T3:%.*]] = load ptr, ptr [[T1]], align 8 // CHECK-NEXT: ret ptr [[T3]] // The setter should be using objc_setProperty. // CHECK:define internal void @"\01-[Test1 setPointer:]"( -// CHECK: [[OFFSET:%.*]] = load i64, ptr @"OBJC_IVAR_$_Test1.pointer" -// CHECK-NEXT: [[T1:%.*]] = load ptr, ptr {{%.*}} -// CHECK-NEXT: call void @obj
[clang] [Clang][ScanDeps] Fix error message typo (PR #88404)
Arthapz wrote: Ping https://github.com/llvm/llvm-project/pull/88404 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][Parser] Make 'T...[N]' within a function parameter a valid pack expansion prior to C++2c (PR #116332)
efriedma-quic wrote: We basically have the following options here: 1. Use C++23 semantics in C++23 mode, with a warning. 2. Use C++2c semantics in C++23 mode, with a warning. 3. Reject the construct with a hard error in C++23 mode. (2) and (3) are basically removing the pack expansion parse from the C++23 grammar. Maybe we should ask the committee for a DR number to explicitly bless this approach. https://github.com/llvm/llvm-project/pull/116332 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Added a PthreadCreateChecker and attempted to register it (PR #116515)
https://github.com/MaxSanchez99 updated https://github.com/llvm/llvm-project/pull/116515 >From 029c4183c5685ac3047aec9154a593339b206a48 Mon Sep 17 00:00:00 2001 From: Maximino Sanchez Jr Date: Sat, 16 Nov 2024 18:35:39 -0600 Subject: [PATCH] Added a PthreadCreateChecker and attempted to register it --- .../clang/StaticAnalyzer/Checkers/Checkers.td | 4 ++ clang/lib/Headers/CMakeLists.txt | 3 +- .../StaticAnalyzer/Checkers/CMakeLists.txt| 1 + .../Checkers/PthreadCreateChecker.cpp | 46 +++ clang/test/Analysis/pthreadcreate.c | 31 + 5 files changed, 84 insertions(+), 1 deletion(-) create mode 100644 clang/lib/StaticAnalyzer/Checkers/PthreadCreateChecker.cpp create mode 100644 clang/test/Analysis/pthreadcreate.c diff --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td index b03e707d638742..e7b08b89c358d5 100644 --- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td +++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td @@ -606,6 +606,10 @@ def ChrootChecker : Checker<"Chroot">, HelpText<"Check improper use of chroot">, Documentation; +def PthreadCreateChecker : Checker<"PthreadCreate">, + HelpText<"Check for creation of pthread">, + Documentation; + def PthreadLockChecker : Checker<"PthreadLock">, HelpText<"Simple lock -> unlock checker">, Dependencies<[PthreadLockBase]>, diff --git a/clang/lib/Headers/CMakeLists.txt b/clang/lib/Headers/CMakeLists.txt index a094305bcec5e4..4154dea674cbbc 100644 --- a/clang/lib/Headers/CMakeLists.txt +++ b/clang/lib/Headers/CMakeLists.txt @@ -379,7 +379,8 @@ set(zos_wrapper_files include(GetClangResourceDir) get_clang_resource_dir(output_dir PREFIX ${LLVM_LIBRARY_OUTPUT_INTDIR}/.. SUBDIR include) -set(out_files) +set(out_files +../../test/Analysis/pthreadcreate.c) set(generated_files) set(arm_common_generated_files) diff --git a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt index f40318f46dea1a..ace537837de5f3 100644 --- a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt +++ b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt @@ -92,6 +92,7 @@ add_clang_library(clangStaticAnalyzerCheckers PaddingChecker.cpp PointerArithChecker.cpp PointerSubChecker.cpp + PthreadCreateChecker.cpp PthreadLockChecker.cpp PutenvStackArrayChecker.cpp RetainCountChecker/RetainCountChecker.cpp diff --git a/clang/lib/StaticAnalyzer/Checkers/PthreadCreateChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/PthreadCreateChecker.cpp new file mode 100644 index 00..e9225fb780c867 --- /dev/null +++ b/clang/lib/StaticAnalyzer/Checkers/PthreadCreateChecker.cpp @@ -0,0 +1,46 @@ +// +// Created by MaxSa on 11/13/2024. +// + +#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" +#include "clang/StaticAnalyzer/Core/Checker.h" +#include "clang/StaticAnalyzer/Core/CheckerManager.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" + +using namespace clang; +using namespace ento; + +class PthreadCreateChecker : public Checker { +public: + void checkPostCall(const CallEvent &Call, CheckerContext &Context) const; + +}; + +void PthreadCreateChecker::checkPostCall(const CallEvent &Call, CheckerContext &Context) const { + const FunctionDecl *FuncID = Call.getDecl()->getAsFunction(); + if (!FuncID) { +return; + } + + if (FuncID->getName() == "pthread_create") { +SVal returnVal = Call.getReturnValue(); +if (returnVal.isZeroConstant()) { + llvm::errs() << "Pthread has been created\n"; +} + } +} + +// Register checker +void ento::registerPthreadCreateChecker(CheckerManager &mgr) { + mgr.registerChecker(); +} + +bool ento::shouldRegisterPthreadCreateChecker(const CheckerManager &mgr) { + return true; +} + + + diff --git a/clang/test/Analysis/pthreadcreate.c b/clang/test/Analysis/pthreadcreate.c new file mode 100644 index 00..0ca6f13d4ecb45 --- /dev/null +++ b/clang/test/Analysis/pthreadcreate.c @@ -0,0 +1,31 @@ +// +// Created by MaxSa on 11/14/2024. +// + +#include +#include +#include + + +void* thread_function(void* arg) { + printf("thread_function start\n"); + return nullptr; +} + +int main() { + pthread_t thread; + int arg = 42; + + if (pthread_create(&thread, NULL, thread_function, &arg)) { +perror("pthread_create"); +exit(1); + } + + if (pthread_join(thread, nullptr)) { +perror("pthread_join"); +exit(1); + } + + printf("thread exit\n"); + return 0; +} \ No newline at end of file ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Added a PthreadCreateChecker and attempted to register it (PR #116515)
llvmbot wrote: @llvm/pr-subscribers-clang-static-analyzer-1 Author: None (MaxSanchez99) Changes --- Full diff: https://github.com/llvm/llvm-project/pull/116515.diff 5 Files Affected: - (modified) clang/include/clang/StaticAnalyzer/Checkers/Checkers.td (+4) - (modified) clang/lib/Headers/CMakeLists.txt (+2-1) - (modified) clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt (+1) - (added) clang/lib/StaticAnalyzer/Checkers/PthreadCreateChecker.cpp (+46) - (added) clang/test/Analysis/pthreadcreate.c (+31) ``diff diff --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td index b03e707d638742..e7b08b89c358d5 100644 --- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td +++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td @@ -606,6 +606,10 @@ def ChrootChecker : Checker<"Chroot">, HelpText<"Check improper use of chroot">, Documentation; +def PthreadCreateChecker : Checker<"PthreadCreate">, + HelpText<"Check for creation of pthread">, + Documentation; + def PthreadLockChecker : Checker<"PthreadLock">, HelpText<"Simple lock -> unlock checker">, Dependencies<[PthreadLockBase]>, diff --git a/clang/lib/Headers/CMakeLists.txt b/clang/lib/Headers/CMakeLists.txt index a094305bcec5e4..4154dea674cbbc 100644 --- a/clang/lib/Headers/CMakeLists.txt +++ b/clang/lib/Headers/CMakeLists.txt @@ -379,7 +379,8 @@ set(zos_wrapper_files include(GetClangResourceDir) get_clang_resource_dir(output_dir PREFIX ${LLVM_LIBRARY_OUTPUT_INTDIR}/.. SUBDIR include) -set(out_files) +set(out_files +../../test/Analysis/pthreadcreate.c) set(generated_files) set(arm_common_generated_files) diff --git a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt index f40318f46dea1a..ace537837de5f3 100644 --- a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt +++ b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt @@ -92,6 +92,7 @@ add_clang_library(clangStaticAnalyzerCheckers PaddingChecker.cpp PointerArithChecker.cpp PointerSubChecker.cpp + PthreadCreateChecker.cpp PthreadLockChecker.cpp PutenvStackArrayChecker.cpp RetainCountChecker/RetainCountChecker.cpp diff --git a/clang/lib/StaticAnalyzer/Checkers/PthreadCreateChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/PthreadCreateChecker.cpp new file mode 100644 index 00..e9225fb780c867 --- /dev/null +++ b/clang/lib/StaticAnalyzer/Checkers/PthreadCreateChecker.cpp @@ -0,0 +1,46 @@ +// +// Created by MaxSa on 11/13/2024. +// + +#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" +#include "clang/StaticAnalyzer/Core/Checker.h" +#include "clang/StaticAnalyzer/Core/CheckerManager.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" + +using namespace clang; +using namespace ento; + +class PthreadCreateChecker : public Checker { +public: + void checkPostCall(const CallEvent &Call, CheckerContext &Context) const; + +}; + +void PthreadCreateChecker::checkPostCall(const CallEvent &Call, CheckerContext &Context) const { + const FunctionDecl *FuncID = Call.getDecl()->getAsFunction(); + if (!FuncID) { +return; + } + + if (FuncID->getName() == "pthread_create") { +SVal returnVal = Call.getReturnValue(); +if (returnVal.isZeroConstant()) { + llvm::errs() << "Pthread has been created\n"; +} + } +} + +// Register checker +void ento::registerPthreadCreateChecker(CheckerManager &mgr) { + mgr.registerChecker(); +} + +bool ento::shouldRegisterPthreadCreateChecker(const CheckerManager &mgr) { + return true; +} + + + diff --git a/clang/test/Analysis/pthreadcreate.c b/clang/test/Analysis/pthreadcreate.c new file mode 100644 index 00..0ca6f13d4ecb45 --- /dev/null +++ b/clang/test/Analysis/pthreadcreate.c @@ -0,0 +1,31 @@ +// +// Created by MaxSa on 11/14/2024. +// + +#include +#include +#include + + +void* thread_function(void* arg) { + printf("thread_function start\n"); + return nullptr; +} + +int main() { + pthread_t thread; + int arg = 42; + + if (pthread_create(&thread, NULL, thread_function, &arg)) { +perror("pthread_create"); +exit(1); + } + + if (pthread_join(thread, nullptr)) { +perror("pthread_join"); +exit(1); + } + + printf("thread exit\n"); + return 0; +} \ No newline at end of file `` https://github.com/llvm/llvm-project/pull/116515 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Added a PthreadCreateChecker and attempted to register it (PR #116515)
github-actions[bot] wrote: Thank you for submitting a Pull Request (PR) to the LLVM Project! This PR will be automatically labeled and the relevant teams will be notified. If you wish to, you can add reviewers by using the "Reviewers" section on this page. If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using `@` followed by their GitHub username. If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers. If you have further questions, they may be answered by the [LLVM GitHub User Guide](https://llvm.org/docs/GitHub.html). You can also ask questions in a comment on this PR, on the [LLVM Discord](https://discord.com/invite/xS7Z362) or on the [forums](https://discourse.llvm.org/). https://github.com/llvm/llvm-project/pull/116515 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-tools-extra] [analyzer] Remove alpha.core.IdenticalExpr Checker (PR #114715)
@@ -269,6 +473,21 @@ void BranchCloneCheck::check(const MatchFinder::MatchResult &Result) { return; } + if (const auto *IS = Result.Nodes.getNodeAs("ifWithDescendantIf")) { +const Stmt *Then = IS->getThen(); +auto CS = dyn_cast(Then); +if (CS && (!CS->body_empty())) { + const auto *InnerIf = dyn_cast(*CS->body_begin()); + if (InnerIf && isIdenticalStmt(Context, IS->getCond(), InnerIf->getCond(), + /*IgnoreSideEffects=*/false)) { HerrCai0907 wrote: I mean we can do this check in ast_matcher to reduce the cost https://github.com/llvm/llvm-project/pull/114715 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [docs][asan][lsan] Drop list of supported architechures (PR #116302)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Vitaly Buka (vitalybuka) Changes Full list is quite long, and quality of implementation can vary. Drop the lists to avoid confusion like https://github.com/rust-lang/rust/pull/123617#issuecomment-2471695102 We don't maintain these for other sanitizers. --- Full diff: https://github.com/llvm/llvm-project/pull/116302.diff 2 Files Affected: - (modified) clang/docs/AddressSanitizer.rst (+6-8) - (modified) clang/docs/LeakSanitizer.rst (+5-5) ``diff diff --git a/clang/docs/AddressSanitizer.rst b/clang/docs/AddressSanitizer.rst index d937cbfdf583c4..8d9295f246f0d3 100644 --- a/clang/docs/AddressSanitizer.rst +++ b/clang/docs/AddressSanitizer.rst @@ -326,15 +326,13 @@ Supported Platforms AddressSanitizer is supported on: -* Linux i386/x86\_64 (tested on Ubuntu 12.04) -* macOS 10.7 - 10.11 (i386/x86\_64) +* Linux +* macOS * iOS Simulator -* Android ARM -* NetBSD i386/x86\_64 -* FreeBSD i386/x86\_64 (tested on FreeBSD 11-current) -* Windows 8.1+ (i386/x86\_64) - -Ports to various other platforms are in progress. +* Android +* NetBSD +* FreeBSD +* Windows 8.1+ Current Status == diff --git a/clang/docs/LeakSanitizer.rst b/clang/docs/LeakSanitizer.rst index adcb6421c6a1f9..ecdb87f0b259dd 100644 --- a/clang/docs/LeakSanitizer.rst +++ b/clang/docs/LeakSanitizer.rst @@ -54,11 +54,11 @@ constraints in mind and may compromise the security of the resulting executable. Supported Platforms === -* Android aarch64/i386/x86_64 -* Fuchsia aarch64/x86_64 -* Linux arm/aarch64/mips64/ppc64/ppc64le/riscv64/s390x/i386/x86\_64 -* macOS aarch64/i386/x86\_64 -* NetBSD i386/x86_64 +* Android +* Fuchsia +* Linux +* macOS +* NetBSD More Information `` https://github.com/llvm/llvm-project/pull/116302 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Added a PthreadCreateChecker and attempted to register it (PR #116515)
steakhal wrote: Could you please ellaborate your intentions and motives? The PR description wasn't clear to me. @MaxSanchez99 https://github.com/llvm/llvm-project/pull/116515 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][ScanDeps] Fix error message typo (PR #88404)
Arthapz wrote: observed this today, this should be merge :D  https://github.com/llvm/llvm-project/pull/88404 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [lld] [Clang][MinGW] Pass --functionpadmin to the linker when -fms-hotpatch is used (PR #116512)
cjacek wrote: GCC offers the `ms_hook_prologue` function attribute as an alternative. It provides similar guarantees: it inserts a hardcoded prologue and adds padding. However, it applies on a per-function basis, so there isn’t an easy way to make the entire module hotpatchable. In GCC, the padding is handled directly by the compiler, with no linker involvement, which emits assembly like: ``` .globl _func .def_func; .scl2; .type 32; .endef .long0x .long0x .long0x .long0x _func: .byte 0x8b, 0xff, 0x55, 0x8b, 0xec movl$1, %eax popl%ebp ret ``` https://github.com/llvm/llvm-project/pull/116512 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] SemaFunctionEffects: Fix bug where lambdas produced by template expansion weren't verified. (PR #116505)
Sirraide wrote: > Something like: The function template is pretty much what I meant, yeah, but by ‘templated lambda’ I meant either one that is an implicit template because one of its parameters is declared with `auto` (`[](auto x)`) or one that has an explicit template parameter list (`[]`). https://github.com/llvm/llvm-project/pull/116505 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Lex] Remove unused includes (NFC) (PR #116460)
https://github.com/nikic approved this pull request. https://github.com/llvm/llvm-project/pull/116460 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] SemaFunctionEffects: Fix bug where lambdas produced by template expansion weren't verified. (PR #116505)
https://github.com/dougsonos created https://github.com/llvm/llvm-project/pull/116505 Lambdas are added to the list of Decls to verify using `Sema::maybeAddDeclWithEffects()`. Up until now this call was in `ActOnLambdaExpr`, which happens in the context of a template but not in the context of template expansion. Template expansion calls `BuildLambdaExpr`, so move the call to `Sema::maybeAddDeclWithEffects()` there. Fixing this created a not-previously-seen situation where the custom "In template expansion here" diagnostic didn't have a valid location. This breaks tests because there's a note with no location. For now I've just skipped emitting the diagnostic but maybe there's a better solution. >From d235d3ea8bb3cabfc8db9d87233455a93fa23c05 Mon Sep 17 00:00:00 2001 From: Doug Wyatt Date: Sat, 16 Nov 2024 11:59:03 -0800 Subject: [PATCH] [Clang] SemaFunctionEffects: Fix bug where lambdas produced by template expansion were not verified. --- clang/lib/Sema/SemaFunctionEffects.cpp | 3 ++- clang/lib/Sema/SemaLambda.cpp | 3 +-- .../test/Sema/attr-nonblocking-constraints.cpp | 17 + 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/clang/lib/Sema/SemaFunctionEffects.cpp b/clang/lib/Sema/SemaFunctionEffects.cpp index 4b5ddb74b1262f..6fe4d2353a2282 100644 --- a/clang/lib/Sema/SemaFunctionEffects.cpp +++ b/clang/lib/Sema/SemaFunctionEffects.cpp @@ -807,7 +807,8 @@ class Analyzer { auto MaybeAddTemplateNote = [&](const Decl *D) { if (const FunctionDecl *FD = dyn_cast(D)) { -while (FD != nullptr && FD->isTemplateInstantiation()) { +while (FD != nullptr && FD->isTemplateInstantiation() && + FD->getPointOfInstantiation().isValid()) { S.Diag(FD->getPointOfInstantiation(), diag::note_func_effect_from_template); FD = FD->getTemplateInstantiationPattern(); diff --git a/clang/lib/Sema/SemaLambda.cpp b/clang/lib/Sema/SemaLambda.cpp index e7afa0f4c81fc4..a67c0b2b367d1a 100644 --- a/clang/lib/Sema/SemaLambda.cpp +++ b/clang/lib/Sema/SemaLambda.cpp @@ -1950,8 +1950,6 @@ ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body) { LambdaScopeInfo LSI = *cast(FunctionScopes.back()); ActOnFinishFunctionBody(LSI.CallOperator, Body); - maybeAddDeclWithEffects(LSI.CallOperator); - return BuildLambdaExpr(StartLoc, Body->getEndLoc(), &LSI); } @@ -2284,6 +2282,7 @@ ExprResult Sema::BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: break; } +maybeAddDeclWithEffects(LSI->CallOperator); } return MaybeBindToTemporary(Lambda); diff --git a/clang/test/Sema/attr-nonblocking-constraints.cpp b/clang/test/Sema/attr-nonblocking-constraints.cpp index cc9108c0a4fbd6..87cbcc9713859f 100644 --- a/clang/test/Sema/attr-nonblocking-constraints.cpp +++ b/clang/test/Sema/attr-nonblocking-constraints.cpp @@ -144,6 +144,23 @@ void nb9() [[clang::nonblocking]] expected-note {{in template expansion here}} } +// Make sure we verify lambdas produced from template expansions. +struct HasTemplatedLambda { + void (*fptr)() [[clang::nonblocking]]; + + template + HasTemplatedLambda(const C&) + : fptr{ []() [[clang::nonblocking]] { + auto* y = new int; // expected-warning {{lambda with 'nonblocking' attribute must not allocate or deallocate memory}} + } } + {} +}; + +void nb9a() +{ + HasTemplatedLambda bad(42); +} + void nb10( void (*fp1)(), // expected-note {{function pointer cannot be inferred 'nonblocking'}} void (*fp2)() [[clang::nonblocking]] ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] SemaFunctionEffects: Fix bug where lambdas produced by template expansion weren't verified. (PR #116505)
https://github.com/Sirraide approved this pull request. Ah yeah, I should have noticed that in review: `ActOnX` is generally only called during parsing, whereas `BuildX` is also called during template instantiation. As for the template notes, I don’t have a good solution for those either... Also, we *do* have tests for function templates and generic lambdas, right? If not, we should definitely add some. https://github.com/llvm/llvm-project/pull/116505 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] avoid adding consteval condition as the last statement to preserve valid CFG (PR #116513)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Oleksandr T. (a-tarasyuk) Changes Fixes #116485 --- Full diff: https://github.com/llvm/llvm-project/pull/116513.diff 3 Files Affected: - (modified) clang/docs/ReleaseNotes.rst (+2) - (modified) clang/lib/Analysis/CFG.cpp (+4-1) - (modified) clang/test/SemaCXX/constexpr-return-non-void-cxx2b.cpp (+6) ``diff diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index a8830a5658c7da..d81085d011b866 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -535,6 +535,8 @@ Improvements to Clang's diagnostics - Improved diagnostic message for ``__builtin_bit_cast`` size mismatch (#GH115870). +- Clang now diagnoses missing return value in functions containing ``if consteval`` (#GH116485). + Improvements to Clang's time-trace -- diff --git a/clang/lib/Analysis/CFG.cpp b/clang/lib/Analysis/CFG.cpp index f678ac6f2ff36a..7a6bd8b6f8d070 100644 --- a/clang/lib/Analysis/CFG.cpp +++ b/clang/lib/Analysis/CFG.cpp @@ -3177,11 +3177,14 @@ CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) { if (!I->isConsteval()) KnownVal = tryEvaluateBool(I->getCond()); -// Add the successors. If we know that specific branches are +// Add the successors. If we know that specific branches are // unreachable, inform addSuccessor() of that knowledge. addSuccessor(Block, ThenBlock, /* IsReachable = */ !KnownVal.isFalse()); addSuccessor(Block, ElseBlock, /* IsReachable = */ !KnownVal.isTrue()); +if (I->isConsteval()) + return Block; + // Add the condition as the last statement in the new block. This may // create new blocks as the condition may contain control-flow. Any newly // created blocks will be pointed to be "Block". diff --git a/clang/test/SemaCXX/constexpr-return-non-void-cxx2b.cpp b/clang/test/SemaCXX/constexpr-return-non-void-cxx2b.cpp index 25d1f8df7f7166..3d993f000e8dda 100644 --- a/clang/test/SemaCXX/constexpr-return-non-void-cxx2b.cpp +++ b/clang/test/SemaCXX/constexpr-return-non-void-cxx2b.cpp @@ -5,3 +5,9 @@ static_assert(__is_same(decltype([] constexpr -> int { }( )), int)); // expected consteval int g() { } // expected-warning {{non-void function does not return a value}} static_assert(__is_same(decltype([] consteval -> int { }( )), int)); // expected-warning {{non-void lambda does not return a value}} + +namespace GH116485 { +int h() { +if consteval { } +} // expected-warning {{non-void function does not return a value}} +} `` https://github.com/llvm/llvm-project/pull/116513 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Parse] Remove ParseDiagnostic.h (PR #116496)
llvmbot wrote: @llvm/pr-subscribers-hlsl Author: Kazu Hirata (kazutakahirata) Changes This patch removes clang/Parse/ParseDiagnostic.h because it just forwards to clang/Basic/DiagnosticParse.h. --- Full diff: https://github.com/llvm/llvm-project/pull/116496.diff 17 Files Affected: - (removed) clang/include/clang/Parse/ParseDiagnostic.h (-14) - (modified) clang/include/clang/Parse/RAIIObjectsForParser.h (+1-1) - (modified) clang/include/module.modulemap (-1) - (modified) clang/lib/Parse/ParseAST.cpp (+1-1) - (modified) clang/lib/Parse/ParseCXXInlineMethods.cpp (+1-1) - (modified) clang/lib/Parse/ParseDecl.cpp (+1-1) - (modified) clang/lib/Parse/ParseDeclCXX.cpp (+1-1) - (modified) clang/lib/Parse/ParseExprCXX.cpp (+1-1) - (modified) clang/lib/Parse/ParseHLSL.cpp (+1-1) - (modified) clang/lib/Parse/ParseInit.cpp (+1-1) - (modified) clang/lib/Parse/ParseObjc.cpp (+1-1) - (modified) clang/lib/Parse/ParseOpenACC.cpp (+1-1) - (modified) clang/lib/Parse/ParseOpenMP.cpp (+1-1) - (modified) clang/lib/Parse/ParsePragma.cpp (+1-1) - (modified) clang/lib/Parse/ParseTemplate.cpp (+1-1) - (modified) clang/lib/Parse/ParseTentative.cpp (+1-1) - (modified) clang/lib/Parse/Parser.cpp (+1-1) ``diff diff --git a/clang/include/clang/Parse/ParseDiagnostic.h b/clang/include/clang/Parse/ParseDiagnostic.h deleted file mode 100644 index f174464b78419c..00 --- a/clang/include/clang/Parse/ParseDiagnostic.h +++ /dev/null @@ -1,14 +0,0 @@ -//===--- DiagnosticParse.h - Diagnostics for libparse ---*- C++ -*-===// -// -// 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 -// -//===--===// - -#ifndef LLVM_CLANG_PARSE_PARSEDIAGNOSTIC_H -#define LLVM_CLANG_PARSE_PARSEDIAGNOSTIC_H - -#include "clang/Basic/DiagnosticParse.h" - -#endif diff --git a/clang/include/clang/Parse/RAIIObjectsForParser.h b/clang/include/clang/Parse/RAIIObjectsForParser.h index f4fa518ef27d01..480efccb19cf7f 100644 --- a/clang/include/clang/Parse/RAIIObjectsForParser.h +++ b/clang/include/clang/Parse/RAIIObjectsForParser.h @@ -14,7 +14,7 @@ #ifndef LLVM_CLANG_PARSE_RAIIOBJECTSFORPARSER_H #define LLVM_CLANG_PARSE_RAIIOBJECTSFORPARSER_H -#include "clang/Parse/ParseDiagnostic.h" +#include "clang/Basic/DiagnosticParse.h" #include "clang/Parse/Parser.h" #include "clang/Sema/DelayedDiagnostic.h" #include "clang/Sema/ParsedTemplate.h" diff --git a/clang/include/module.modulemap b/clang/include/module.modulemap index 6f18c0a49641c9..b399f0beee59a1 100644 --- a/clang/include/module.modulemap +++ b/clang/include/module.modulemap @@ -116,7 +116,6 @@ module Clang_Diagnostics { module Frontend { header "clang/Frontend/FrontendDiagnostic.h" export * } module Lex { header "clang/Lex/LexDiagnostic.h" export * } module Parse { header "clang/Parse/ParseDiagnostic.h" export * } - module Sema { header "clang/Sema/SemaDiagnostic.h" export * } module Serialization { header "clang/Serialization/SerializationDiagnostic.h" export * } module Refactoring { header "clang/Tooling/Refactoring/RefactoringDiagnostic.h" export * } } diff --git a/clang/lib/Parse/ParseAST.cpp b/clang/lib/Parse/ParseAST.cpp index e008cc0e38ceda..761f84070681e6 100644 --- a/clang/lib/Parse/ParseAST.cpp +++ b/clang/lib/Parse/ParseAST.cpp @@ -15,7 +15,7 @@ #include "clang/AST/ASTContext.h" #include "clang/AST/ExternalASTSource.h" #include "clang/AST/Stmt.h" -#include "clang/Parse/ParseDiagnostic.h" +#include "clang/Basic/DiagnosticParse.h" #include "clang/Parse/Parser.h" #include "clang/Sema/CodeCompleteConsumer.h" #include "clang/Sema/EnterExpressionEvaluationContext.h" diff --git a/clang/lib/Parse/ParseCXXInlineMethods.cpp b/clang/lib/Parse/ParseCXXInlineMethods.cpp index b461743833c82a..2ec66fe95708e1 100644 --- a/clang/lib/Parse/ParseCXXInlineMethods.cpp +++ b/clang/lib/Parse/ParseCXXInlineMethods.cpp @@ -11,7 +11,7 @@ //===--===// #include "clang/AST/DeclTemplate.h" -#include "clang/Parse/ParseDiagnostic.h" +#include "clang/Basic/DiagnosticParse.h" #include "clang/Parse/Parser.h" #include "clang/Parse/RAIIObjectsForParser.h" #include "clang/Sema/DeclSpec.h" diff --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp index 31984453487aef..aa5c2d28d429ac 100644 --- a/clang/lib/Parse/ParseDecl.cpp +++ b/clang/lib/Parse/ParseDecl.cpp @@ -17,9 +17,9 @@ #include "clang/Basic/AttributeCommonInfo.h" #include "clang/Basic/Attributes.h" #include "clang/Basic/CharInfo.h" +#include "clang/Basic/DiagnosticParse.h" #include "clang/Basic/TargetInfo.h" #include "clang/Basic/TokenKinds.h" -#include "clang/Parse/ParseDiagnostic.h" #include "clang/Parse/Parser.h" #include "clang/Parse/RAIIObjectsForParser.h" #include "clang/Sema/En
[clang] [Parse] Remove ParseDiagnostic.h (PR #116496)
https://github.com/kazutakahirata created https://github.com/llvm/llvm-project/pull/116496 This patch removes clang/Parse/ParseDiagnostic.h because it just forwards to clang/Basic/DiagnosticParse.h. >From 62d97fa37e10f478cb02651abb38dde9d03da76d Mon Sep 17 00:00:00 2001 From: Kazu Hirata Date: Sat, 16 Nov 2024 08:32:24 -0800 Subject: [PATCH] [Parse] Remove ParseDiagnostic.h This patch removes clang/Parse/ParseDiagnostic.h because it just forwards to clang/Basic/DiagnosticParse.h. --- clang/include/clang/Parse/ParseDiagnostic.h | 14 -- clang/include/clang/Parse/RAIIObjectsForParser.h | 2 +- clang/include/module.modulemap | 1 - clang/lib/Parse/ParseAST.cpp | 2 +- clang/lib/Parse/ParseCXXInlineMethods.cpp| 2 +- clang/lib/Parse/ParseDecl.cpp| 2 +- clang/lib/Parse/ParseDeclCXX.cpp | 2 +- clang/lib/Parse/ParseExprCXX.cpp | 2 +- clang/lib/Parse/ParseHLSL.cpp| 2 +- clang/lib/Parse/ParseInit.cpp| 2 +- clang/lib/Parse/ParseObjc.cpp| 2 +- clang/lib/Parse/ParseOpenACC.cpp | 2 +- clang/lib/Parse/ParseOpenMP.cpp | 2 +- clang/lib/Parse/ParsePragma.cpp | 2 +- clang/lib/Parse/ParseTemplate.cpp| 2 +- clang/lib/Parse/ParseTentative.cpp | 2 +- clang/lib/Parse/Parser.cpp | 2 +- 17 files changed, 15 insertions(+), 30 deletions(-) delete mode 100644 clang/include/clang/Parse/ParseDiagnostic.h diff --git a/clang/include/clang/Parse/ParseDiagnostic.h b/clang/include/clang/Parse/ParseDiagnostic.h deleted file mode 100644 index f174464b78419c..00 --- a/clang/include/clang/Parse/ParseDiagnostic.h +++ /dev/null @@ -1,14 +0,0 @@ -//===--- DiagnosticParse.h - Diagnostics for libparse ---*- C++ -*-===// -// -// 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 -// -//===--===// - -#ifndef LLVM_CLANG_PARSE_PARSEDIAGNOSTIC_H -#define LLVM_CLANG_PARSE_PARSEDIAGNOSTIC_H - -#include "clang/Basic/DiagnosticParse.h" - -#endif diff --git a/clang/include/clang/Parse/RAIIObjectsForParser.h b/clang/include/clang/Parse/RAIIObjectsForParser.h index f4fa518ef27d01..480efccb19cf7f 100644 --- a/clang/include/clang/Parse/RAIIObjectsForParser.h +++ b/clang/include/clang/Parse/RAIIObjectsForParser.h @@ -14,7 +14,7 @@ #ifndef LLVM_CLANG_PARSE_RAIIOBJECTSFORPARSER_H #define LLVM_CLANG_PARSE_RAIIOBJECTSFORPARSER_H -#include "clang/Parse/ParseDiagnostic.h" +#include "clang/Basic/DiagnosticParse.h" #include "clang/Parse/Parser.h" #include "clang/Sema/DelayedDiagnostic.h" #include "clang/Sema/ParsedTemplate.h" diff --git a/clang/include/module.modulemap b/clang/include/module.modulemap index 6f18c0a49641c9..b399f0beee59a1 100644 --- a/clang/include/module.modulemap +++ b/clang/include/module.modulemap @@ -116,7 +116,6 @@ module Clang_Diagnostics { module Frontend { header "clang/Frontend/FrontendDiagnostic.h" export * } module Lex { header "clang/Lex/LexDiagnostic.h" export * } module Parse { header "clang/Parse/ParseDiagnostic.h" export * } - module Sema { header "clang/Sema/SemaDiagnostic.h" export * } module Serialization { header "clang/Serialization/SerializationDiagnostic.h" export * } module Refactoring { header "clang/Tooling/Refactoring/RefactoringDiagnostic.h" export * } } diff --git a/clang/lib/Parse/ParseAST.cpp b/clang/lib/Parse/ParseAST.cpp index e008cc0e38ceda..761f84070681e6 100644 --- a/clang/lib/Parse/ParseAST.cpp +++ b/clang/lib/Parse/ParseAST.cpp @@ -15,7 +15,7 @@ #include "clang/AST/ASTContext.h" #include "clang/AST/ExternalASTSource.h" #include "clang/AST/Stmt.h" -#include "clang/Parse/ParseDiagnostic.h" +#include "clang/Basic/DiagnosticParse.h" #include "clang/Parse/Parser.h" #include "clang/Sema/CodeCompleteConsumer.h" #include "clang/Sema/EnterExpressionEvaluationContext.h" diff --git a/clang/lib/Parse/ParseCXXInlineMethods.cpp b/clang/lib/Parse/ParseCXXInlineMethods.cpp index b461743833c82a..2ec66fe95708e1 100644 --- a/clang/lib/Parse/ParseCXXInlineMethods.cpp +++ b/clang/lib/Parse/ParseCXXInlineMethods.cpp @@ -11,7 +11,7 @@ //===--===// #include "clang/AST/DeclTemplate.h" -#include "clang/Parse/ParseDiagnostic.h" +#include "clang/Basic/DiagnosticParse.h" #include "clang/Parse/Parser.h" #include "clang/Parse/RAIIObjectsForParser.h" #include "clang/Sema/DeclSpec.h" diff --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp index 31984453487aef..aa5c2d28d429ac 100644 --- a/clang/lib/Parse/ParseDecl.cpp +++ b/clang/lib/Parse/ParseDecl.cpp @@ -17,9 +17,9 @@ #include
[clang-tools-extra] [clang-tidy][modernize-use-starts-ends-with] Fix minor mistake in error message (PR #116132)
https://github.com/nicovank updated https://github.com/llvm/llvm-project/pull/116132 >From 56fd8556333a86a63903ffd370d307cf9484fd5a Mon Sep 17 00:00:00 2001 From: Nicolas van Kempen Date: Sat, 16 Nov 2024 15:35:13 -0500 Subject: [PATCH] [clang-tidy][modernize-use-starts-ends-with] Fix minor mistake in error message In one of the cases recently added to this check in #110448, the error message is no longer accurate as the comparison is not with zero. #116033 brought my attention to this as it may add another comparison without zero. Remove the `[!=] 0` part of the diagnostic. This is in line with some other checks e.g. modernize-use-emplace. ``` > cat tmp.cpp #include bool f(std::string u, std::string v) { return u.rfind(v) == u.size() - v.size(); } # Before. > ./build/bin/clang-tidy -checks="-*,modernize-use-starts-ends-with" tmp.cpp -- > -std=c++20 tmp.cpp:3:12: warning: use ends_with instead of rfind() == 0 [modernize-use-starts-ends-with] 3 | return u.rfind(v) == u.size() - v.size(); |^~ |ends_with( ) # After. > ./build/bin/clang-tidy -checks="-*,modernize-use-starts-ends-with" tmp.cpp -- > -std=c++20 tmp.cpp:3:12: warning: use ends_with instead of rfind [modernize-use-starts-ends-with] 3 | return u.rfind(v) == u.size() - v.size(); |^~ |ends_with( ) ``` --- .../clang-tidy/modernize/UseStartsEndsWithCheck.cpp| 9 +++-- clang-tools-extra/docs/ReleaseNotes.rst| 3 ++- .../checkers/modernize/use-starts-ends-with.cpp| 10 +- 3 files changed, 10 insertions(+), 12 deletions(-) diff --git a/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp index 1231f954298adc..4d8f6dbc2cc11b 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp @@ -189,11 +189,8 @@ void UseStartsEndsWithCheck::check(const MatchFinder::MatchResult &Result) { if (ComparisonExpr->getBeginLoc().isMacroID()) return; - const bool Neg = ComparisonExpr->getOpcode() == BO_NE; - - auto Diagnostic = - diag(FindExpr->getExprLoc(), "use %0 instead of %1() %select{==|!=}2 0") - << ReplacementFunction->getName() << FindFun->getName() << Neg; + auto Diagnostic = diag(FindExpr->getExprLoc(), "use %0 instead of %1") +<< ReplacementFunction->getName() << FindFun->getName(); // Remove possible arguments after search expression and ' [!=]= .+' suffix. Diagnostic << FixItHint::CreateReplacement( @@ -215,7 +212,7 @@ void UseStartsEndsWithCheck::check(const MatchFinder::MatchResult &Result) { (ReplacementFunction->getName() + "(").str()); // Add possible negation '!'. - if (Neg) + if (ComparisonExpr->getOpcode() == BO_NE) Diagnostic << FixItHint::CreateInsertion(FindExpr->getBeginLoc(), "!"); } diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst index db971f08ca3dbc..9a0728e706b223 100644 --- a/clang-tools-extra/docs/ReleaseNotes.rst +++ b/clang-tools-extra/docs/ReleaseNotes.rst @@ -244,7 +244,8 @@ Changes in existing checks - Improved :doc:`modernize-use-starts-ends-with ` check to handle two cases - that can be replaced with ``ends_with`` + that can be replaced with ``ends_with``, and a small adjustment to the + diagnostic message. - Improved :doc:`modernize-use-std-format ` check to support replacing diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-starts-ends-with.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-starts-ends-with.cpp index 91477241e82e54..fc60d972f2e0ea 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-starts-ends-with.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-starts-ends-with.cpp @@ -36,7 +36,7 @@ void test(std::string s, std::string_view sv, sub_string ss, sub_sub_string sss, string_like sl, string_like_camel slc, prefer_underscore_version puv, prefer_underscore_version_flip puvf) { s.find("a") == 0; - // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with instead of find() == 0 + // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with instead of find [modernize-use-starts-ends-with] // CHECK-FIXES: s.starts_with("a"); (s)).find("a" == ((0)); @@ -68,7 +68,7 @@ void test(std::string s, std::string_view sv, sub_string ss, sub_sub_string sss, // CHECK-FIXES: !s.starts_with("a"); s.rfind("a", 0) == 0; - // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with instead of rfind() == 0 + // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with instead of rfind [modernize-use-starts-ends-with] // CHECK-FIXES: s.starts_with("a"); s.rfind(s, 0)
[clang-tools-extra] [clang-tidy][modernize-use-starts-ends-with] Fix minor mistake in error message (PR #116132)
https://github.com/nicovank updated https://github.com/llvm/llvm-project/pull/116132 >From 56fd8556333a86a63903ffd370d307cf9484fd5a Mon Sep 17 00:00:00 2001 From: Nicolas van Kempen Date: Sat, 16 Nov 2024 15:35:13 -0500 Subject: [PATCH] [clang-tidy][modernize-use-starts-ends-with] Fix minor mistake in error message In one of the cases recently added to this check in #110448, the error message is no longer accurate as the comparison is not with zero. #116033 brought my attention to this as it may add another comparison without zero. Remove the `[!=] 0` part of the diagnostic. This is in line with some other checks e.g. modernize-use-emplace. ``` > cat tmp.cpp #include bool f(std::string u, std::string v) { return u.rfind(v) == u.size() - v.size(); } # Before. > ./build/bin/clang-tidy -checks="-*,modernize-use-starts-ends-with" tmp.cpp -- > -std=c++20 tmp.cpp:3:12: warning: use ends_with instead of rfind() == 0 [modernize-use-starts-ends-with] 3 | return u.rfind(v) == u.size() - v.size(); |^~ |ends_with( ) # After. > ./build/bin/clang-tidy -checks="-*,modernize-use-starts-ends-with" tmp.cpp -- > -std=c++20 tmp.cpp:3:12: warning: use ends_with instead of rfind [modernize-use-starts-ends-with] 3 | return u.rfind(v) == u.size() - v.size(); |^~ |ends_with( ) ``` --- .../clang-tidy/modernize/UseStartsEndsWithCheck.cpp| 9 +++-- clang-tools-extra/docs/ReleaseNotes.rst| 3 ++- .../checkers/modernize/use-starts-ends-with.cpp| 10 +- 3 files changed, 10 insertions(+), 12 deletions(-) diff --git a/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp index 1231f954298adc..4d8f6dbc2cc11b 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp @@ -189,11 +189,8 @@ void UseStartsEndsWithCheck::check(const MatchFinder::MatchResult &Result) { if (ComparisonExpr->getBeginLoc().isMacroID()) return; - const bool Neg = ComparisonExpr->getOpcode() == BO_NE; - - auto Diagnostic = - diag(FindExpr->getExprLoc(), "use %0 instead of %1() %select{==|!=}2 0") - << ReplacementFunction->getName() << FindFun->getName() << Neg; + auto Diagnostic = diag(FindExpr->getExprLoc(), "use %0 instead of %1") +<< ReplacementFunction->getName() << FindFun->getName(); // Remove possible arguments after search expression and ' [!=]= .+' suffix. Diagnostic << FixItHint::CreateReplacement( @@ -215,7 +212,7 @@ void UseStartsEndsWithCheck::check(const MatchFinder::MatchResult &Result) { (ReplacementFunction->getName() + "(").str()); // Add possible negation '!'. - if (Neg) + if (ComparisonExpr->getOpcode() == BO_NE) Diagnostic << FixItHint::CreateInsertion(FindExpr->getBeginLoc(), "!"); } diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst index db971f08ca3dbc..9a0728e706b223 100644 --- a/clang-tools-extra/docs/ReleaseNotes.rst +++ b/clang-tools-extra/docs/ReleaseNotes.rst @@ -244,7 +244,8 @@ Changes in existing checks - Improved :doc:`modernize-use-starts-ends-with ` check to handle two cases - that can be replaced with ``ends_with`` + that can be replaced with ``ends_with``, and a small adjustment to the + diagnostic message. - Improved :doc:`modernize-use-std-format ` check to support replacing diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-starts-ends-with.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-starts-ends-with.cpp index 91477241e82e54..fc60d972f2e0ea 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-starts-ends-with.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-starts-ends-with.cpp @@ -36,7 +36,7 @@ void test(std::string s, std::string_view sv, sub_string ss, sub_sub_string sss, string_like sl, string_like_camel slc, prefer_underscore_version puv, prefer_underscore_version_flip puvf) { s.find("a") == 0; - // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with instead of find() == 0 + // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with instead of find [modernize-use-starts-ends-with] // CHECK-FIXES: s.starts_with("a"); (s)).find("a" == ((0)); @@ -68,7 +68,7 @@ void test(std::string s, std::string_view sv, sub_string ss, sub_sub_string sss, // CHECK-FIXES: !s.starts_with("a"); s.rfind("a", 0) == 0; - // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with instead of rfind() == 0 + // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with instead of rfind [modernize-use-starts-ends-with] // CHECK-FIXES: s.starts_with("a"); s.rfind(s, 0)
[clang-tools-extra] [clang-tidy][modernize-use-starts-ends-with] Fix minor mistake in error message (PR #116132)
https://github.com/nicovank updated https://github.com/llvm/llvm-project/pull/116132 >From 5c52bea612c677352d555ce8100d222f149414d0 Mon Sep 17 00:00:00 2001 From: Nicolas van Kempen Date: Sat, 16 Nov 2024 15:41:00 -0500 Subject: [PATCH] [clang-tidy][modernize-use-starts-ends-with] Fix minor mistake in error message In one of the cases recently added to this check in #110448, the error message is no longer accurate as the comparison is not with zero. #116033 brought my attention to this as it may add another comparison without zero. Remove the `[!=] 0` part of the diagnostic. This is in line with some other checks e.g. modernize-use-emplace. ``` > cat tmp.cpp #include bool f(std::string u, std::string v) { return u.rfind(v) == u.size() - v.size(); } # Before. > ./build/bin/clang-tidy -checks="-*,modernize-use-starts-ends-with" tmp.cpp -- > -std=c++20 tmp.cpp:3:12: warning: use ends_with instead of rfind() == 0 [modernize-use-starts-ends-with] 3 | return u.rfind(v) == u.size() - v.size(); |^~ |ends_with( ) # After. > ./build/bin/clang-tidy -checks="-*,modernize-use-starts-ends-with" tmp.cpp -- > -std=c++20 tmp.cpp:3:12: warning: use ends_with instead of rfind [modernize-use-starts-ends-with] 3 | return u.rfind(v) == u.size() - v.size(); |^~ |ends_with( ) ``` --- .../clang-tidy/modernize/UseStartsEndsWithCheck.cpp| 9 +++-- clang-tools-extra/docs/ReleaseNotes.rst| 3 ++- .../checkers/modernize/use-starts-ends-with.cpp| 10 +- 3 files changed, 10 insertions(+), 12 deletions(-) diff --git a/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp index 1231f954298adc..4d8f6dbc2cc11b 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp @@ -189,11 +189,8 @@ void UseStartsEndsWithCheck::check(const MatchFinder::MatchResult &Result) { if (ComparisonExpr->getBeginLoc().isMacroID()) return; - const bool Neg = ComparisonExpr->getOpcode() == BO_NE; - - auto Diagnostic = - diag(FindExpr->getExprLoc(), "use %0 instead of %1() %select{==|!=}2 0") - << ReplacementFunction->getName() << FindFun->getName() << Neg; + auto Diagnostic = diag(FindExpr->getExprLoc(), "use %0 instead of %1") +<< ReplacementFunction->getName() << FindFun->getName(); // Remove possible arguments after search expression and ' [!=]= .+' suffix. Diagnostic << FixItHint::CreateReplacement( @@ -215,7 +212,7 @@ void UseStartsEndsWithCheck::check(const MatchFinder::MatchResult &Result) { (ReplacementFunction->getName() + "(").str()); // Add possible negation '!'. - if (Neg) + if (ComparisonExpr->getOpcode() == BO_NE) Diagnostic << FixItHint::CreateInsertion(FindExpr->getBeginLoc(), "!"); } diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst index db971f08ca3dbc..9a0728e706b223 100644 --- a/clang-tools-extra/docs/ReleaseNotes.rst +++ b/clang-tools-extra/docs/ReleaseNotes.rst @@ -244,7 +244,8 @@ Changes in existing checks - Improved :doc:`modernize-use-starts-ends-with ` check to handle two cases - that can be replaced with ``ends_with`` + that can be replaced with ``ends_with``, and a small adjustment to the + diagnostic message. - Improved :doc:`modernize-use-std-format ` check to support replacing diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-starts-ends-with.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-starts-ends-with.cpp index 91477241e82e54..c9a6beb41bbb86 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-starts-ends-with.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-starts-ends-with.cpp @@ -36,7 +36,7 @@ void test(std::string s, std::string_view sv, sub_string ss, sub_sub_string sss, string_like sl, string_like_camel slc, prefer_underscore_version puv, prefer_underscore_version_flip puvf) { s.find("a") == 0; - // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with instead of find() == 0 + // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with instead of find [modernize-use-starts-ends-with] // CHECK-FIXES: s.starts_with("a"); (s)).find("a" == ((0)); @@ -68,7 +68,7 @@ void test(std::string s, std::string_view sv, sub_string ss, sub_sub_string sss, // CHECK-FIXES: !s.starts_with("a"); s.rfind("a", 0) == 0; - // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with instead of rfind() == 0 + // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with instead of rfind [modernize-use-starts-ends-with] // CHECK-FIXES: s.starts_with("a"); s.rfind(s, 0)
[clang] [Clang] Fix name lookup for dependent bases (PR #114978)
https://github.com/vbe-sc updated https://github.com/llvm/llvm-project/pull/114978 >From 0de2ff271efd672bae0b4974c404149da79ff747 Mon Sep 17 00:00:00 2001 From: vb-sc Date: Tue, 5 Nov 2024 15:46:57 +0300 Subject: [PATCH] [clang] Fix name lookup for dependent bases --- clang/lib/AST/CXXInheritance.cpp | 14 ++ clang/test/CXX/drs/cwg5xx.cpp| 48 ++-- 2 files changed, 55 insertions(+), 7 deletions(-) diff --git a/clang/lib/AST/CXXInheritance.cpp b/clang/lib/AST/CXXInheritance.cpp index eb265a872c1259..b2e77037c10c72 100644 --- a/clang/lib/AST/CXXInheritance.cpp +++ b/clang/lib/AST/CXXInheritance.cpp @@ -170,13 +170,19 @@ bool CXXBasePaths::lookupInBases(ASTContext &Context, QualType BaseType = Context.getCanonicalType(BaseSpec.getType()).getUnqualifiedType(); +bool isCurrentInstantiation = false; +if (auto *BaseRecord = +cast(BaseSpec.getType()->getAsRecordDecl())) + isCurrentInstantiation = BaseRecord->isDependentContext() && + BaseRecord->isCurrentInstantiation(Record); // C++ [temp.dep]p3: // In the definition of a class template or a member of a class template, // if a base class of the class template depends on a template-parameter, // the base class scope is not examined during unqualified name lookup // either at the point of definition of the class template or member or // during an instantiation of the class tem- plate or member. -if (!LookupInDependent && BaseType->isDependentType()) +if (!LookupInDependent && +(BaseType->isDependentType() && !isCurrentInstantiation)) continue; // Determine whether we need to visit this base class at all, @@ -244,9 +250,8 @@ bool CXXBasePaths::lookupInBases(ASTContext &Context, return FoundPath; } } else if (VisitBase) { - CXXRecordDecl *BaseRecord; + CXXRecordDecl *BaseRecord = nullptr; if (LookupInDependent) { -BaseRecord = nullptr; const TemplateSpecializationType *TST = BaseSpec.getType()->getAs(); if (!TST) { @@ -265,8 +270,7 @@ bool CXXBasePaths::lookupInBases(ASTContext &Context, BaseRecord = nullptr; } } else { -BaseRecord = cast( -BaseSpec.getType()->castAs()->getDecl()); +BaseRecord = cast(BaseSpec.getType()->getAsRecordDecl()); } if (BaseRecord && lookupInBases(Context, BaseRecord, BaseMatches, LookupInDependent)) { diff --git a/clang/test/CXX/drs/cwg5xx.cpp b/clang/test/CXX/drs/cwg5xx.cpp index ed0c7159dfc889..0d53a9d07d76de 100644 --- a/clang/test/CXX/drs/cwg5xx.cpp +++ b/clang/test/CXX/drs/cwg5xx.cpp @@ -1178,17 +1178,61 @@ namespace cwg590 { // cwg590: yes template typename A::B::C A::B::C::f(A::B::C) {} } -namespace cwg591 { // cwg591: no +namespace cwg591 { // cwg591: yes template struct A { typedef int M; struct B { typedef void M; struct C; + struct D; +}; + }; + + template struct G { +struct B { + typedef int M; + struct C { +typedef void M; +struct D; + }; +}; + }; + + template struct H { +template struct B { + typedef int M; + template struct C { +typedef void M; +struct D; +struct P; + }; }; }; template struct A::B::C : A { -// FIXME: Should find member of non-dependent base class A. +M m; + }; + + template struct G::B::C::D : B { +M m; + }; + + template + template + template + struct H::B::C::D : B { +M m; + }; + + template struct A::B::D : A { +M m; +// expected-error@-1 {{field has incomplete type 'M' (aka 'void'}} + }; + + template + template + template + struct H::B::C::P : B { M m; // expected-error@-1 {{field has incomplete type 'M' (aka 'void'}} }; ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Fix name lookup for dependent bases (PR #114978)
https://github.com/vbe-sc updated https://github.com/llvm/llvm-project/pull/114978 >From 11c24e5592bfdf8849bb415580d37a6f545e4952 Mon Sep 17 00:00:00 2001 From: vb-sc Date: Tue, 5 Nov 2024 15:46:57 +0300 Subject: [PATCH] [clang] Fix name lookup for dependent bases --- clang/lib/AST/CXXInheritance.cpp | 14 ++ clang/test/CXX/drs/cwg5xx.cpp| 48 ++-- 2 files changed, 55 insertions(+), 7 deletions(-) diff --git a/clang/lib/AST/CXXInheritance.cpp b/clang/lib/AST/CXXInheritance.cpp index eb265a872c1259..b2e77037c10c72 100644 --- a/clang/lib/AST/CXXInheritance.cpp +++ b/clang/lib/AST/CXXInheritance.cpp @@ -170,13 +170,19 @@ bool CXXBasePaths::lookupInBases(ASTContext &Context, QualType BaseType = Context.getCanonicalType(BaseSpec.getType()).getUnqualifiedType(); +bool isCurrentInstantiation = false; +if (auto *BaseRecord = +cast(BaseSpec.getType()->getAsRecordDecl())) + isCurrentInstantiation = BaseRecord->isDependentContext() && + BaseRecord->isCurrentInstantiation(Record); // C++ [temp.dep]p3: // In the definition of a class template or a member of a class template, // if a base class of the class template depends on a template-parameter, // the base class scope is not examined during unqualified name lookup // either at the point of definition of the class template or member or // during an instantiation of the class tem- plate or member. -if (!LookupInDependent && BaseType->isDependentType()) +if (!LookupInDependent && +(BaseType->isDependentType() && !isCurrentInstantiation)) continue; // Determine whether we need to visit this base class at all, @@ -244,9 +250,8 @@ bool CXXBasePaths::lookupInBases(ASTContext &Context, return FoundPath; } } else if (VisitBase) { - CXXRecordDecl *BaseRecord; + CXXRecordDecl *BaseRecord = nullptr; if (LookupInDependent) { -BaseRecord = nullptr; const TemplateSpecializationType *TST = BaseSpec.getType()->getAs(); if (!TST) { @@ -265,8 +270,7 @@ bool CXXBasePaths::lookupInBases(ASTContext &Context, BaseRecord = nullptr; } } else { -BaseRecord = cast( -BaseSpec.getType()->castAs()->getDecl()); +BaseRecord = cast(BaseSpec.getType()->getAsRecordDecl()); } if (BaseRecord && lookupInBases(Context, BaseRecord, BaseMatches, LookupInDependent)) { diff --git a/clang/test/CXX/drs/cwg5xx.cpp b/clang/test/CXX/drs/cwg5xx.cpp index ed0c7159dfc889..0d53a9d07d76de 100644 --- a/clang/test/CXX/drs/cwg5xx.cpp +++ b/clang/test/CXX/drs/cwg5xx.cpp @@ -1178,17 +1178,61 @@ namespace cwg590 { // cwg590: yes template typename A::B::C A::B::C::f(A::B::C) {} } -namespace cwg591 { // cwg591: no +namespace cwg591 { // cwg591: yes template struct A { typedef int M; struct B { typedef void M; struct C; + struct D; +}; + }; + + template struct G { +struct B { + typedef int M; + struct C { +typedef void M; +struct D; + }; +}; + }; + + template struct H { +template struct B { + typedef int M; + template struct C { +typedef void M; +struct D; +struct P; + }; }; }; template struct A::B::C : A { -// FIXME: Should find member of non-dependent base class A. +M m; + }; + + template struct G::B::C::D : B { +M m; + }; + + template + template + template + struct H::B::C::D : B { +M m; + }; + + template struct A::B::D : A { +M m; +// expected-error@-1 {{field has incomplete type 'M' (aka 'void'}} + }; + + template + template + template + struct H::B::C::P : B { M m; // expected-error@-1 {{field has incomplete type 'M' (aka 'void'}} }; ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Fix name lookup for dependent bases (PR #114978)
https://github.com/vbe-sc updated https://github.com/llvm/llvm-project/pull/114978 >From 11c24e5592bfdf8849bb415580d37a6f545e4952 Mon Sep 17 00:00:00 2001 From: vb-sc Date: Tue, 5 Nov 2024 15:46:57 +0300 Subject: [PATCH] [clang] Fix name lookup for dependent bases --- clang/lib/AST/CXXInheritance.cpp | 14 ++ clang/test/CXX/drs/cwg5xx.cpp| 48 ++-- 2 files changed, 55 insertions(+), 7 deletions(-) diff --git a/clang/lib/AST/CXXInheritance.cpp b/clang/lib/AST/CXXInheritance.cpp index eb265a872c1259..b2e77037c10c72 100644 --- a/clang/lib/AST/CXXInheritance.cpp +++ b/clang/lib/AST/CXXInheritance.cpp @@ -170,13 +170,19 @@ bool CXXBasePaths::lookupInBases(ASTContext &Context, QualType BaseType = Context.getCanonicalType(BaseSpec.getType()).getUnqualifiedType(); +bool isCurrentInstantiation = false; +if (auto *BaseRecord = +cast(BaseSpec.getType()->getAsRecordDecl())) + isCurrentInstantiation = BaseRecord->isDependentContext() && + BaseRecord->isCurrentInstantiation(Record); // C++ [temp.dep]p3: // In the definition of a class template or a member of a class template, // if a base class of the class template depends on a template-parameter, // the base class scope is not examined during unqualified name lookup // either at the point of definition of the class template or member or // during an instantiation of the class tem- plate or member. -if (!LookupInDependent && BaseType->isDependentType()) +if (!LookupInDependent && +(BaseType->isDependentType() && !isCurrentInstantiation)) continue; // Determine whether we need to visit this base class at all, @@ -244,9 +250,8 @@ bool CXXBasePaths::lookupInBases(ASTContext &Context, return FoundPath; } } else if (VisitBase) { - CXXRecordDecl *BaseRecord; + CXXRecordDecl *BaseRecord = nullptr; if (LookupInDependent) { -BaseRecord = nullptr; const TemplateSpecializationType *TST = BaseSpec.getType()->getAs(); if (!TST) { @@ -265,8 +270,7 @@ bool CXXBasePaths::lookupInBases(ASTContext &Context, BaseRecord = nullptr; } } else { -BaseRecord = cast( -BaseSpec.getType()->castAs()->getDecl()); +BaseRecord = cast(BaseSpec.getType()->getAsRecordDecl()); } if (BaseRecord && lookupInBases(Context, BaseRecord, BaseMatches, LookupInDependent)) { diff --git a/clang/test/CXX/drs/cwg5xx.cpp b/clang/test/CXX/drs/cwg5xx.cpp index ed0c7159dfc889..0d53a9d07d76de 100644 --- a/clang/test/CXX/drs/cwg5xx.cpp +++ b/clang/test/CXX/drs/cwg5xx.cpp @@ -1178,17 +1178,61 @@ namespace cwg590 { // cwg590: yes template typename A::B::C A::B::C::f(A::B::C) {} } -namespace cwg591 { // cwg591: no +namespace cwg591 { // cwg591: yes template struct A { typedef int M; struct B { typedef void M; struct C; + struct D; +}; + }; + + template struct G { +struct B { + typedef int M; + struct C { +typedef void M; +struct D; + }; +}; + }; + + template struct H { +template struct B { + typedef int M; + template struct C { +typedef void M; +struct D; +struct P; + }; }; }; template struct A::B::C : A { -// FIXME: Should find member of non-dependent base class A. +M m; + }; + + template struct G::B::C::D : B { +M m; + }; + + template + template + template + struct H::B::C::D : B { +M m; + }; + + template struct A::B::D : A { +M m; +// expected-error@-1 {{field has incomplete type 'M' (aka 'void'}} + }; + + template + template + template + struct H::B::C::P : B { M m; // expected-error@-1 {{field has incomplete type 'M' (aka 'void'}} }; ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Fix name lookup for dependent bases (PR #114978)
https://github.com/vbe-sc updated https://github.com/llvm/llvm-project/pull/114978 >From 5a48960ab73890b10381b4e7ebd32d3f66246bdd Mon Sep 17 00:00:00 2001 From: vb-sc Date: Tue, 5 Nov 2024 15:46:57 +0300 Subject: [PATCH] [clang] Fix name lookup for dependent bases --- clang/lib/AST/CXXInheritance.cpp | 16 +++ clang/test/CXX/drs/cwg5xx.cpp| 48 ++-- 2 files changed, 57 insertions(+), 7 deletions(-) diff --git a/clang/lib/AST/CXXInheritance.cpp b/clang/lib/AST/CXXInheritance.cpp index eb265a872c1259..7961dbc0c7c8a3 100644 --- a/clang/lib/AST/CXXInheritance.cpp +++ b/clang/lib/AST/CXXInheritance.cpp @@ -170,13 +170,21 @@ bool CXXBasePaths::lookupInBases(ASTContext &Context, QualType BaseType = Context.getCanonicalType(BaseSpec.getType()).getUnqualifiedType(); +bool isCurrentInstantiation = isa(BaseType); +if (!isCurrentInstantiation) { + if (auto *BaseRecord = cast_or_null( + BaseSpec.getType()->getAsRecordDecl())) +isCurrentInstantiation = BaseRecord->isDependentContext() && + BaseRecord->isCurrentInstantiation(Record); +} // C++ [temp.dep]p3: // In the definition of a class template or a member of a class template, // if a base class of the class template depends on a template-parameter, // the base class scope is not examined during unqualified name lookup // either at the point of definition of the class template or member or // during an instantiation of the class tem- plate or member. -if (!LookupInDependent && BaseType->isDependentType()) +if (!LookupInDependent && +(BaseType->isDependentType() && !isCurrentInstantiation)) continue; // Determine whether we need to visit this base class at all, @@ -244,9 +252,8 @@ bool CXXBasePaths::lookupInBases(ASTContext &Context, return FoundPath; } } else if (VisitBase) { - CXXRecordDecl *BaseRecord; + CXXRecordDecl *BaseRecord = nullptr; if (LookupInDependent) { -BaseRecord = nullptr; const TemplateSpecializationType *TST = BaseSpec.getType()->getAs(); if (!TST) { @@ -265,8 +272,7 @@ bool CXXBasePaths::lookupInBases(ASTContext &Context, BaseRecord = nullptr; } } else { -BaseRecord = cast( -BaseSpec.getType()->castAs()->getDecl()); +BaseRecord = cast(BaseSpec.getType()->getAsRecordDecl()); } if (BaseRecord && lookupInBases(Context, BaseRecord, BaseMatches, LookupInDependent)) { diff --git a/clang/test/CXX/drs/cwg5xx.cpp b/clang/test/CXX/drs/cwg5xx.cpp index ed0c7159dfc889..0d53a9d07d76de 100644 --- a/clang/test/CXX/drs/cwg5xx.cpp +++ b/clang/test/CXX/drs/cwg5xx.cpp @@ -1178,17 +1178,61 @@ namespace cwg590 { // cwg590: yes template typename A::B::C A::B::C::f(A::B::C) {} } -namespace cwg591 { // cwg591: no +namespace cwg591 { // cwg591: yes template struct A { typedef int M; struct B { typedef void M; struct C; + struct D; +}; + }; + + template struct G { +struct B { + typedef int M; + struct C { +typedef void M; +struct D; + }; +}; + }; + + template struct H { +template struct B { + typedef int M; + template struct C { +typedef void M; +struct D; +struct P; + }; }; }; template struct A::B::C : A { -// FIXME: Should find member of non-dependent base class A. +M m; + }; + + template struct G::B::C::D : B { +M m; + }; + + template + template + template + struct H::B::C::D : B { +M m; + }; + + template struct A::B::D : A { +M m; +// expected-error@-1 {{field has incomplete type 'M' (aka 'void'}} + }; + + template + template + template + struct H::B::C::P : B { M m; // expected-error@-1 {{field has incomplete type 'M' (aka 'void'}} }; ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Lex] Remove unused includes (NFC) (PR #116460)
https://github.com/kazutakahirata closed https://github.com/llvm/llvm-project/pull/116460 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 7642759 - [Lex] Remove unused includes (NFC) (#116460)
Author: Kazu Hirata Date: 2024-11-16T12:14:06-08:00 New Revision: 764275949897533a4be0728250e69a94d228fbc5 URL: https://github.com/llvm/llvm-project/commit/764275949897533a4be0728250e69a94d228fbc5 DIFF: https://github.com/llvm/llvm-project/commit/764275949897533a4be0728250e69a94d228fbc5.diff LOG: [Lex] Remove unused includes (NFC) (#116460) Identified with misc-include-cleaner. Added: Modified: clang/lib/Lex/HeaderMap.cpp clang/lib/Lex/HeaderSearch.cpp clang/lib/Lex/InitHeaderSearch.cpp clang/lib/Lex/Lexer.cpp clang/lib/Lex/MacroArgs.cpp clang/lib/Lex/MacroInfo.cpp clang/lib/Lex/ModuleMap.cpp clang/lib/Lex/PPCallbacks.cpp clang/lib/Lex/PPDirectives.cpp clang/lib/Lex/PPExpressions.cpp clang/lib/Lex/PPLexerChange.cpp clang/lib/Lex/PPMacroExpansion.cpp clang/lib/Lex/Pragma.cpp clang/lib/Lex/PreprocessingRecord.cpp clang/lib/Lex/Preprocessor.cpp clang/lib/Lex/PreprocessorLexer.cpp clang/lib/Lex/TokenLexer.cpp Removed: diff --git a/clang/lib/Lex/HeaderMap.cpp b/clang/lib/Lex/HeaderMap.cpp index b04f67a4b2ed3c..14731f29486c8c 100644 --- a/clang/lib/Lex/HeaderMap.cpp +++ b/clang/lib/Lex/HeaderMap.cpp @@ -14,13 +14,10 @@ #include "clang/Basic/CharInfo.h" #include "clang/Basic/FileManager.h" #include "clang/Lex/HeaderMapTypes.h" -#include "llvm/ADT/SmallString.h" #include "llvm/Support/Compiler.h" -#include "llvm/Support/DataTypes.h" #include "llvm/Support/Debug.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/MemoryBuffer.h" -#include "llvm/Support/SwapByteOrder.h" #include "llvm/Support/SystemZ/zOSSupport.h" #include #include diff --git a/clang/lib/Lex/HeaderSearch.cpp b/clang/lib/Lex/HeaderSearch.cpp index c5614a8e0ee526..bf8fe44e4ca9ca 100644 --- a/clang/lib/Lex/HeaderSearch.cpp +++ b/clang/lib/Lex/HeaderSearch.cpp @@ -24,7 +24,6 @@ #include "clang/Lex/ModuleMap.h" #include "clang/Lex/Preprocessor.h" #include "llvm/ADT/APInt.h" -#include "llvm/ADT/Hashing.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/SmallVector.h" diff --git a/clang/lib/Lex/InitHeaderSearch.cpp b/clang/lib/Lex/InitHeaderSearch.cpp index cb3941fa948211..ea02f5dfb62644 100644 --- a/clang/lib/Lex/InitHeaderSearch.cpp +++ b/clang/lib/Lex/InitHeaderSearch.cpp @@ -10,7 +10,6 @@ // //===--===// -#include "clang/Basic/DiagnosticFrontend.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/LangOptions.h" #include "clang/Config/config.h" // C_INCLUDE_DIRS @@ -18,8 +17,6 @@ #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/HeaderSearchOptions.h" #include "llvm/ADT/SmallPtrSet.h" -#include "llvm/ADT/SmallString.h" -#include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/ErrorHandling.h" diff --git a/clang/lib/Lex/Lexer.cpp b/clang/lib/Lex/Lexer.cpp index 12cb46042c946b..e58c8bc72ae5b3 100644 --- a/clang/lib/Lex/Lexer.cpp +++ b/clang/lib/Lex/Lexer.cpp @@ -32,7 +32,6 @@ #include "llvm/ADT/StringSwitch.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/ConvertUTF.h" -#include "llvm/Support/MathExtras.h" #include "llvm/Support/MemoryBufferRef.h" #include "llvm/Support/NativeFormatting.h" #include "llvm/Support/Unicode.h" diff --git a/clang/lib/Lex/MacroArgs.cpp b/clang/lib/Lex/MacroArgs.cpp index c54f69bb9ead39..2f97d9e02bc117 100644 --- a/clang/lib/Lex/MacroArgs.cpp +++ b/clang/lib/Lex/MacroArgs.cpp @@ -14,7 +14,6 @@ #include "clang/Lex/LexDiagnostic.h" #include "clang/Lex/MacroInfo.h" #include "clang/Lex/Preprocessor.h" -#include "llvm/ADT/SmallString.h" #include "llvm/Support/SaveAndRestore.h" #include diff --git a/clang/lib/Lex/MacroInfo.cpp b/clang/lib/Lex/MacroInfo.cpp index dfdf463665f3c1..c33276ea71cb7a 100644 --- a/clang/lib/Lex/MacroInfo.cpp +++ b/clang/lib/Lex/MacroInfo.cpp @@ -18,8 +18,6 @@ #include "clang/Basic/TokenKinds.h" #include "clang/Lex/Preprocessor.h" #include "clang/Lex/Token.h" -#include "llvm/ADT/StringRef.h" -#include "llvm/Support/Casting.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/raw_ostream.h" #include diff --git a/clang/lib/Lex/ModuleMap.cpp b/clang/lib/Lex/ModuleMap.cpp index dc9d2bfd5629c9..ccf94f6345ff28 100644 --- a/clang/lib/Lex/ModuleMap.cpp +++ b/clang/lib/Lex/ModuleMap.cpp @@ -30,7 +30,6 @@ #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallPtrSet.h" -#include "llvm/ADT/SmallString.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringRef.h" @@ -38,7 +37,6 @@ #include "llvm/Support/Allocator.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/ErrorHandling.h" -#include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "llvm/Support/VirtualFileSys
[clang] [Clang] SemaFunctionEffects: Fix bug where lambdas produced by template expansion weren't verified. (PR #116505)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Doug Wyatt (dougsonos) Changes Lambdas are added to the list of Decls to verify using `Sema::maybeAddDeclWithEffects()`. Up until now this call was in `ActOnLambdaExpr`, which happens in the context of a template but not in the context of template expansion. Template expansion calls `BuildLambdaExpr`, so move the call to `Sema::maybeAddDeclWithEffects()` there. Fixing this created a not-previously-seen situation where the custom "In template expansion here" diagnostic didn't have a valid location. This breaks tests because there's a note with no location. For now I've just skipped emitting the diagnostic but maybe there's a better solution. --- Full diff: https://github.com/llvm/llvm-project/pull/116505.diff 3 Files Affected: - (modified) clang/lib/Sema/SemaFunctionEffects.cpp (+2-1) - (modified) clang/lib/Sema/SemaLambda.cpp (+1-2) - (modified) clang/test/Sema/attr-nonblocking-constraints.cpp (+17) ``diff diff --git a/clang/lib/Sema/SemaFunctionEffects.cpp b/clang/lib/Sema/SemaFunctionEffects.cpp index 4b5ddb74b1262f..6fe4d2353a2282 100644 --- a/clang/lib/Sema/SemaFunctionEffects.cpp +++ b/clang/lib/Sema/SemaFunctionEffects.cpp @@ -807,7 +807,8 @@ class Analyzer { auto MaybeAddTemplateNote = [&](const Decl *D) { if (const FunctionDecl *FD = dyn_cast(D)) { -while (FD != nullptr && FD->isTemplateInstantiation()) { +while (FD != nullptr && FD->isTemplateInstantiation() && + FD->getPointOfInstantiation().isValid()) { S.Diag(FD->getPointOfInstantiation(), diag::note_func_effect_from_template); FD = FD->getTemplateInstantiationPattern(); diff --git a/clang/lib/Sema/SemaLambda.cpp b/clang/lib/Sema/SemaLambda.cpp index e7afa0f4c81fc4..a67c0b2b367d1a 100644 --- a/clang/lib/Sema/SemaLambda.cpp +++ b/clang/lib/Sema/SemaLambda.cpp @@ -1950,8 +1950,6 @@ ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body) { LambdaScopeInfo LSI = *cast(FunctionScopes.back()); ActOnFinishFunctionBody(LSI.CallOperator, Body); - maybeAddDeclWithEffects(LSI.CallOperator); - return BuildLambdaExpr(StartLoc, Body->getEndLoc(), &LSI); } @@ -2284,6 +2282,7 @@ ExprResult Sema::BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: break; } +maybeAddDeclWithEffects(LSI->CallOperator); } return MaybeBindToTemporary(Lambda); diff --git a/clang/test/Sema/attr-nonblocking-constraints.cpp b/clang/test/Sema/attr-nonblocking-constraints.cpp index cc9108c0a4fbd6..87cbcc9713859f 100644 --- a/clang/test/Sema/attr-nonblocking-constraints.cpp +++ b/clang/test/Sema/attr-nonblocking-constraints.cpp @@ -144,6 +144,23 @@ void nb9() [[clang::nonblocking]] expected-note {{in template expansion here}} } +// Make sure we verify lambdas produced from template expansions. +struct HasTemplatedLambda { + void (*fptr)() [[clang::nonblocking]]; + + template + HasTemplatedLambda(const C&) + : fptr{ []() [[clang::nonblocking]] { + auto* y = new int; // expected-warning {{lambda with 'nonblocking' attribute must not allocate or deallocate memory}} + } } + {} +}; + +void nb9a() +{ + HasTemplatedLambda bad(42); +} + void nb10( void (*fp1)(), // expected-note {{function pointer cannot be inferred 'nonblocking'}} void (*fp2)() [[clang::nonblocking]] `` https://github.com/llvm/llvm-project/pull/116505 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [lld] [Clang][MinGW] Pass --functionpadmin to the linker when -fms-hotpatch is used (PR #116512)
https://github.com/cjacek created https://github.com/llvm/llvm-project/pull/116512 None >From c13f631c8074c85242fd1f639fd09aae78fede6a Mon Sep 17 00:00:00 2001 From: Jacek Caban Date: Sat, 16 Nov 2024 14:16:58 +0100 Subject: [PATCH 1/2] [LLD][MinGW] Add support for --functionpadmin option This introduces the MinGW counterpart of lld-link's -functionpadmin. --- lld/MinGW/Driver.cpp | 8 lld/MinGW/Options.td | 3 +++ lld/test/MinGW/driver.test | 7 +++ 3 files changed, 18 insertions(+) diff --git a/lld/MinGW/Driver.cpp b/lld/MinGW/Driver.cpp index 553698d4f537fc..706687202b19fb 100644 --- a/lld/MinGW/Driver.cpp +++ b/lld/MinGW/Driver.cpp @@ -329,6 +329,14 @@ bool link(ArrayRef argsArr, llvm::raw_ostream &stdoutOS, add("-build-id"); } + if (auto *a = args.getLastArg(OPT_functionpadmin)) { +StringRef v = a->getValue(); +if (v.empty()) + add("-functionpadmin"); +else + add("-functionpadmin:" + v); + } + if (args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false)) add("-WX"); else diff --git a/lld/MinGW/Options.td b/lld/MinGW/Options.td index ff7e21fa808f39..abe5e5c82ca3ff 100644 --- a/lld/MinGW/Options.td +++ b/lld/MinGW/Options.td @@ -215,6 +215,9 @@ defm error_limit: def build_id: J<"build-id=">, HelpText<"Generate build ID note (pass none to disable)">, MetaVarName<"">; def : F<"build-id">, Alias, HelpText<"Alias for --build-id=">; +def functionpadmin: J<"functionpadmin=">, HelpText<"Prepares an image for hotpatching">, + MetaVarName<"">; +def : F<"functionpadmin">, Alias, HelpText<"Alias for --functionpadmin=">; // Alias def alias_Bdynamic_call_shared: Flag<["-"], "call_shared">, Alias; diff --git a/lld/test/MinGW/driver.test b/lld/test/MinGW/driver.test index 2831d155fef128..ed6bc880f8f2d9 100644 --- a/lld/test/MinGW/driver.test +++ b/lld/test/MinGW/driver.test @@ -445,6 +445,13 @@ RUN: ld.lld -### foo.o -m i386pep --build-id=fast 2>&1 | FileCheck -check-prefix BUILD_ID_WARN: unsupported build id hashing: fast, using default hashing. BUILD_ID_WARN: -build-id{{ }} +RUN: ld.lld -### foo.o -m i386pep --functionpadmin= 2>&1 | FileCheck -check-prefix=FUNCTIONPADMIN %s +RUN: ld.lld -### foo.o -m i386pep --functionpadmin 2>&1 | FileCheck -check-prefix=FUNCTIONPADMIN %s +FUNCTIONPADMIN: -functionpadmin{{ }} + +RUN: ld.lld -### foo.o -m i386pep --functionpadmin=2 2>&1 | FileCheck -check-prefix=FUNCTIONPADMIN2 %s +FUNCTIONPADMIN2: -functionpadmin:2{{ }} + RUN: ld.lld -### foo.o -m i386pep --build-id=none 2>&1 | FileCheck -check-prefix=NO_BUILD_ID %s RUN: ld.lld -### foo.o -m i386pep -s 2>&1 | FileCheck -check-prefix=NO_BUILD_ID %s RUN: ld.lld -### foo.o -m i386pep -S 2>&1 | FileCheck -check-prefix=NO_BUILD_ID %s >From 51ebafdc3f6ec6251f042b8a13175f3b017f1833 Mon Sep 17 00:00:00 2001 From: Jacek Caban Date: Sat, 16 Nov 2024 14:32:55 +0100 Subject: [PATCH 2/2] [clang][MinGW] Pass --functionpadmin to the linker when -fms-hotpatch is used --- clang/lib/Driver/ToolChains/MinGW.cpp | 3 +++ clang/test/Driver/mingw.cpp | 4 2 files changed, 7 insertions(+) diff --git a/clang/lib/Driver/ToolChains/MinGW.cpp b/clang/lib/Driver/ToolChains/MinGW.cpp index e51daca5025a80..963de81027ca9f 100644 --- a/clang/lib/Driver/ToolChains/MinGW.cpp +++ b/clang/lib/Driver/ToolChains/MinGW.cpp @@ -188,6 +188,9 @@ void tools::MinGW::Linker::ConstructJob(Compilation &C, const JobAction &JA, << A->getSpelling() << GuardArgs; } + if (Args.hasArg(options::OPT_fms_hotpatch)) +CmdArgs.push_back("--functionpadmin"); + CmdArgs.push_back("-o"); const char *OutputFile = Output.getFilename(); // GCC implicitly adds an .exe extension if it is given an output file name diff --git a/clang/test/Driver/mingw.cpp b/clang/test/Driver/mingw.cpp index 4a9ba4d259b46f..9790c86a364f85 100644 --- a/clang/test/Driver/mingw.cpp +++ b/clang/test/Driver/mingw.cpp @@ -84,3 +84,7 @@ // RUN: %clang --target=arm64ec-windows-gnu -### -o /dev/null %s 2>&1 \ // RUN: | FileCheck %s --check-prefix CHECK_MINGW_EC_LINK // CHECK_MINGW_EC_LINK: "-m" "arm64ecpe" + +// RUN: %clang --target=i686-windows-gnu -fms-hotpatch -### -- %s 2>&1 \ +// RUN:| FileCheck %s --check-prefix=FUNCTIONPADMIN +// FUNCTIONPADMIN: "--functionpadmin" ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [lld] [Clang][MinGW] Pass --functionpadmin to the linker when -fms-hotpatch is used (PR #116512)
llvmbot wrote: @llvm/pr-subscribers-clang @llvm/pr-subscribers-lld Author: Jacek Caban (cjacek) Changes --- Full diff: https://github.com/llvm/llvm-project/pull/116512.diff 5 Files Affected: - (modified) clang/lib/Driver/ToolChains/MinGW.cpp (+3) - (modified) clang/test/Driver/mingw.cpp (+4) - (modified) lld/MinGW/Driver.cpp (+8) - (modified) lld/MinGW/Options.td (+3) - (modified) lld/test/MinGW/driver.test (+7) ``diff diff --git a/clang/lib/Driver/ToolChains/MinGW.cpp b/clang/lib/Driver/ToolChains/MinGW.cpp index e51daca5025a80..963de81027ca9f 100644 --- a/clang/lib/Driver/ToolChains/MinGW.cpp +++ b/clang/lib/Driver/ToolChains/MinGW.cpp @@ -188,6 +188,9 @@ void tools::MinGW::Linker::ConstructJob(Compilation &C, const JobAction &JA, << A->getSpelling() << GuardArgs; } + if (Args.hasArg(options::OPT_fms_hotpatch)) +CmdArgs.push_back("--functionpadmin"); + CmdArgs.push_back("-o"); const char *OutputFile = Output.getFilename(); // GCC implicitly adds an .exe extension if it is given an output file name diff --git a/clang/test/Driver/mingw.cpp b/clang/test/Driver/mingw.cpp index 4a9ba4d259b46f..9790c86a364f85 100644 --- a/clang/test/Driver/mingw.cpp +++ b/clang/test/Driver/mingw.cpp @@ -84,3 +84,7 @@ // RUN: %clang --target=arm64ec-windows-gnu -### -o /dev/null %s 2>&1 \ // RUN: | FileCheck %s --check-prefix CHECK_MINGW_EC_LINK // CHECK_MINGW_EC_LINK: "-m" "arm64ecpe" + +// RUN: %clang --target=i686-windows-gnu -fms-hotpatch -### -- %s 2>&1 \ +// RUN:| FileCheck %s --check-prefix=FUNCTIONPADMIN +// FUNCTIONPADMIN: "--functionpadmin" diff --git a/lld/MinGW/Driver.cpp b/lld/MinGW/Driver.cpp index 553698d4f537fc..706687202b19fb 100644 --- a/lld/MinGW/Driver.cpp +++ b/lld/MinGW/Driver.cpp @@ -329,6 +329,14 @@ bool link(ArrayRef argsArr, llvm::raw_ostream &stdoutOS, add("-build-id"); } + if (auto *a = args.getLastArg(OPT_functionpadmin)) { +StringRef v = a->getValue(); +if (v.empty()) + add("-functionpadmin"); +else + add("-functionpadmin:" + v); + } + if (args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false)) add("-WX"); else diff --git a/lld/MinGW/Options.td b/lld/MinGW/Options.td index ff7e21fa808f39..abe5e5c82ca3ff 100644 --- a/lld/MinGW/Options.td +++ b/lld/MinGW/Options.td @@ -215,6 +215,9 @@ defm error_limit: def build_id: J<"build-id=">, HelpText<"Generate build ID note (pass none to disable)">, MetaVarName<"">; def : F<"build-id">, Alias, HelpText<"Alias for --build-id=">; +def functionpadmin: J<"functionpadmin=">, HelpText<"Prepares an image for hotpatching">, + MetaVarName<"">; +def : F<"functionpadmin">, Alias, HelpText<"Alias for --functionpadmin=">; // Alias def alias_Bdynamic_call_shared: Flag<["-"], "call_shared">, Alias; diff --git a/lld/test/MinGW/driver.test b/lld/test/MinGW/driver.test index 2831d155fef128..ed6bc880f8f2d9 100644 --- a/lld/test/MinGW/driver.test +++ b/lld/test/MinGW/driver.test @@ -445,6 +445,13 @@ RUN: ld.lld -### foo.o -m i386pep --build-id=fast 2>&1 | FileCheck -check-prefix BUILD_ID_WARN: unsupported build id hashing: fast, using default hashing. BUILD_ID_WARN: -build-id{{ }} +RUN: ld.lld -### foo.o -m i386pep --functionpadmin= 2>&1 | FileCheck -check-prefix=FUNCTIONPADMIN %s +RUN: ld.lld -### foo.o -m i386pep --functionpadmin 2>&1 | FileCheck -check-prefix=FUNCTIONPADMIN %s +FUNCTIONPADMIN: -functionpadmin{{ }} + +RUN: ld.lld -### foo.o -m i386pep --functionpadmin=2 2>&1 | FileCheck -check-prefix=FUNCTIONPADMIN2 %s +FUNCTIONPADMIN2: -functionpadmin:2{{ }} + RUN: ld.lld -### foo.o -m i386pep --build-id=none 2>&1 | FileCheck -check-prefix=NO_BUILD_ID %s RUN: ld.lld -### foo.o -m i386pep -s 2>&1 | FileCheck -check-prefix=NO_BUILD_ID %s RUN: ld.lld -### foo.o -m i386pep -S 2>&1 | FileCheck -check-prefix=NO_BUILD_ID %s `` https://github.com/llvm/llvm-project/pull/116512 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [lld] [Clang][MinGW] Pass --functionpadmin to the linker when -fms-hotpatch is used (PR #116512)
llvmbot wrote: @llvm/pr-subscribers-clang-driver Author: Jacek Caban (cjacek) Changes --- Full diff: https://github.com/llvm/llvm-project/pull/116512.diff 5 Files Affected: - (modified) clang/lib/Driver/ToolChains/MinGW.cpp (+3) - (modified) clang/test/Driver/mingw.cpp (+4) - (modified) lld/MinGW/Driver.cpp (+8) - (modified) lld/MinGW/Options.td (+3) - (modified) lld/test/MinGW/driver.test (+7) ``diff diff --git a/clang/lib/Driver/ToolChains/MinGW.cpp b/clang/lib/Driver/ToolChains/MinGW.cpp index e51daca5025a80..963de81027ca9f 100644 --- a/clang/lib/Driver/ToolChains/MinGW.cpp +++ b/clang/lib/Driver/ToolChains/MinGW.cpp @@ -188,6 +188,9 @@ void tools::MinGW::Linker::ConstructJob(Compilation &C, const JobAction &JA, << A->getSpelling() << GuardArgs; } + if (Args.hasArg(options::OPT_fms_hotpatch)) +CmdArgs.push_back("--functionpadmin"); + CmdArgs.push_back("-o"); const char *OutputFile = Output.getFilename(); // GCC implicitly adds an .exe extension if it is given an output file name diff --git a/clang/test/Driver/mingw.cpp b/clang/test/Driver/mingw.cpp index 4a9ba4d259b46f..9790c86a364f85 100644 --- a/clang/test/Driver/mingw.cpp +++ b/clang/test/Driver/mingw.cpp @@ -84,3 +84,7 @@ // RUN: %clang --target=arm64ec-windows-gnu -### -o /dev/null %s 2>&1 \ // RUN: | FileCheck %s --check-prefix CHECK_MINGW_EC_LINK // CHECK_MINGW_EC_LINK: "-m" "arm64ecpe" + +// RUN: %clang --target=i686-windows-gnu -fms-hotpatch -### -- %s 2>&1 \ +// RUN:| FileCheck %s --check-prefix=FUNCTIONPADMIN +// FUNCTIONPADMIN: "--functionpadmin" diff --git a/lld/MinGW/Driver.cpp b/lld/MinGW/Driver.cpp index 553698d4f537fc..706687202b19fb 100644 --- a/lld/MinGW/Driver.cpp +++ b/lld/MinGW/Driver.cpp @@ -329,6 +329,14 @@ bool link(ArrayRef argsArr, llvm::raw_ostream &stdoutOS, add("-build-id"); } + if (auto *a = args.getLastArg(OPT_functionpadmin)) { +StringRef v = a->getValue(); +if (v.empty()) + add("-functionpadmin"); +else + add("-functionpadmin:" + v); + } + if (args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false)) add("-WX"); else diff --git a/lld/MinGW/Options.td b/lld/MinGW/Options.td index ff7e21fa808f39..abe5e5c82ca3ff 100644 --- a/lld/MinGW/Options.td +++ b/lld/MinGW/Options.td @@ -215,6 +215,9 @@ defm error_limit: def build_id: J<"build-id=">, HelpText<"Generate build ID note (pass none to disable)">, MetaVarName<"">; def : F<"build-id">, Alias, HelpText<"Alias for --build-id=">; +def functionpadmin: J<"functionpadmin=">, HelpText<"Prepares an image for hotpatching">, + MetaVarName<"">; +def : F<"functionpadmin">, Alias, HelpText<"Alias for --functionpadmin=">; // Alias def alias_Bdynamic_call_shared: Flag<["-"], "call_shared">, Alias; diff --git a/lld/test/MinGW/driver.test b/lld/test/MinGW/driver.test index 2831d155fef128..ed6bc880f8f2d9 100644 --- a/lld/test/MinGW/driver.test +++ b/lld/test/MinGW/driver.test @@ -445,6 +445,13 @@ RUN: ld.lld -### foo.o -m i386pep --build-id=fast 2>&1 | FileCheck -check-prefix BUILD_ID_WARN: unsupported build id hashing: fast, using default hashing. BUILD_ID_WARN: -build-id{{ }} +RUN: ld.lld -### foo.o -m i386pep --functionpadmin= 2>&1 | FileCheck -check-prefix=FUNCTIONPADMIN %s +RUN: ld.lld -### foo.o -m i386pep --functionpadmin 2>&1 | FileCheck -check-prefix=FUNCTIONPADMIN %s +FUNCTIONPADMIN: -functionpadmin{{ }} + +RUN: ld.lld -### foo.o -m i386pep --functionpadmin=2 2>&1 | FileCheck -check-prefix=FUNCTIONPADMIN2 %s +FUNCTIONPADMIN2: -functionpadmin:2{{ }} + RUN: ld.lld -### foo.o -m i386pep --build-id=none 2>&1 | FileCheck -check-prefix=NO_BUILD_ID %s RUN: ld.lld -### foo.o -m i386pep -s 2>&1 | FileCheck -check-prefix=NO_BUILD_ID %s RUN: ld.lld -### foo.o -m i386pep -S 2>&1 | FileCheck -check-prefix=NO_BUILD_ID %s `` https://github.com/llvm/llvm-project/pull/116512 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [lld] [Clang][MinGW] Pass --functionpadmin to the linker when -fms-hotpatch is used (PR #116512)
cjacek wrote: This PR depends on #116511. It updates `-fms-hotpatch` to behave similarly during linking as it does in MSVC mode. However, one limitation remains: object files are marked as hotpatchable through CodeView data, so this is only effective when `-gcodeview` is enabled. This is similar to the behavior of Clang in MSVC mode when debug info is not enabled. MSVC seems to always emit `S_COMPILE3`, even when debug info is disabled (in which case, it does not emit any other debug information). https://github.com/llvm/llvm-project/pull/116512 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [lld] [Clang][MinGW] Pass --functionpadmin to the linker when -fms-hotpatch is used (PR #116512)
https://github.com/mstorsjo approved this pull request. This looks reasonable. Is this something that GCC doesn't have? IIRC they do have some support for hotpatchability in some way - can you briefly summarize what they have and what we have in common and what differs? https://github.com/llvm/llvm-project/pull/116512 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Fix name lookup for dependent bases (PR #114978)
vbe-sc wrote: > I don't think this patch fixes the following case: > > ```c++ > template > struct A > { > struct B > { > using X = int; > > struct C > { > using X = void; > > struct D; > }; > }; > }; > > template > struct A::B::C::D : B > { > X x; // error: field has incomplete type 'X' (aka 'void') > }; > ``` > > Regardless, this patch should probably include this as a test. Many thanks for your answer! You're right, this test failed with this patch, but I've already fixed it (see the new changes). Moreover, I have added more tests that should and shouldn't compile. https://github.com/llvm/llvm-project/pull/114978 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Fix name lookup for dependent bases (PR #114978)
kolobabka wrote: > I don't think this patch fixes the following case: > > ```c++ > template > struct A > { > struct B > { > using X = int; > > struct C > { > using X = void; > > struct D; > }; > }; > }; > > template > struct A::B::C::D : B > { > X x; // error: field has incomplete type 'X' (aka 'void') > }; > ``` > > Regardless, this patch should probably include this as a test. Many thanks for your answer! Yor're right, this test failed with this patch, but I've fixed it yet (see new changes). Moreover, I have added more tests to verify cases that should compile and those that shouldn't. https://github.com/llvm/llvm-project/pull/114978 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] avoid adding consteval condition as the last statement to preserve valid CFG (PR #116513)
https://github.com/a-tarasyuk created https://github.com/llvm/llvm-project/pull/116513 Fixes #116485 >From 69689f6ba5ac1715cc1df6cf08b79bb4b8bbe107 Mon Sep 17 00:00:00 2001 From: Oleksandr T Date: Sun, 17 Nov 2024 01:34:42 +0200 Subject: [PATCH] [Clang] avoid adding consteval condition as the last statement to preserve valid CFG --- clang/docs/ReleaseNotes.rst| 2 ++ clang/lib/Analysis/CFG.cpp | 5 - clang/test/SemaCXX/constexpr-return-non-void-cxx2b.cpp | 6 ++ 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index a8830a5658c7da..d81085d011b866 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -535,6 +535,8 @@ Improvements to Clang's diagnostics - Improved diagnostic message for ``__builtin_bit_cast`` size mismatch (#GH115870). +- Clang now diagnoses missing return value in functions containing ``if consteval`` (#GH116485). + Improvements to Clang's time-trace -- diff --git a/clang/lib/Analysis/CFG.cpp b/clang/lib/Analysis/CFG.cpp index f678ac6f2ff36a..7a6bd8b6f8d070 100644 --- a/clang/lib/Analysis/CFG.cpp +++ b/clang/lib/Analysis/CFG.cpp @@ -3177,11 +3177,14 @@ CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) { if (!I->isConsteval()) KnownVal = tryEvaluateBool(I->getCond()); -// Add the successors. If we know that specific branches are +// Add the successors. If we know that specific branches are // unreachable, inform addSuccessor() of that knowledge. addSuccessor(Block, ThenBlock, /* IsReachable = */ !KnownVal.isFalse()); addSuccessor(Block, ElseBlock, /* IsReachable = */ !KnownVal.isTrue()); +if (I->isConsteval()) + return Block; + // Add the condition as the last statement in the new block. This may // create new blocks as the condition may contain control-flow. Any newly // created blocks will be pointed to be "Block". diff --git a/clang/test/SemaCXX/constexpr-return-non-void-cxx2b.cpp b/clang/test/SemaCXX/constexpr-return-non-void-cxx2b.cpp index 25d1f8df7f7166..3d993f000e8dda 100644 --- a/clang/test/SemaCXX/constexpr-return-non-void-cxx2b.cpp +++ b/clang/test/SemaCXX/constexpr-return-non-void-cxx2b.cpp @@ -5,3 +5,9 @@ static_assert(__is_same(decltype([] constexpr -> int { }( )), int)); // expected consteval int g() { } // expected-warning {{non-void function does not return a value}} static_assert(__is_same(decltype([] consteval -> int { }( )), int)); // expected-warning {{non-void lambda does not return a value}} + +namespace GH116485 { +int h() { +if consteval { } +} // expected-warning {{non-void function does not return a value}} +} ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Parse] Remove ParseDiagnostic.h (PR #116496)
kazutakahirata wrote: > Can you explain what is the perceived benefit of this change? Thanks Sure. - We'll have less code. - We'll have fewer "false positives" from clangd's "unused include" warnings. The .cpp files are not using anything declared in `ParseDiagnostic.h` because, after all, `ParseDiagnostic.h` does not declare anything in C++ (classes, functions, templates, etc). Is there a (possibly unwritten) policy of some sort for `Parse/*.cpp` to use `ParseDiagnostic.h` instead of `DiagnosticParse.h` so that, for example, we can add things to `ParseDiagnostic.h` and get them shared instantly among `Parse/*.cpp`? https://github.com/llvm/llvm-project/pull/116496 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][Parser] Make 'T...[N]' within a function parameter a valid pack expansion prior to C++2c (PR #116332)
cor3ntin wrote: I did think about this more, and given we made the feature an extension we should not have 2 different meaning in different contexts, so I think improving the diagnostic is really the only thing we should consider here https://github.com/llvm/llvm-project/pull/116332 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [libcxx] [Clang] Implement CWG2369 "Ordering between constraints and substitution" (PR #102857)
cor3ntin wrote: @zyn0217 should we wait then? https://github.com/llvm/llvm-project/pull/102857 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy][modernize-use-starts-ends-with] Fix minor mistake in error message (PR #116132)
https://github.com/nicovank updated https://github.com/llvm/llvm-project/pull/116132 >From 5c52bea612c677352d555ce8100d222f149414d0 Mon Sep 17 00:00:00 2001 From: Nicolas van Kempen Date: Sat, 16 Nov 2024 15:41:00 -0500 Subject: [PATCH] [clang-tidy][modernize-use-starts-ends-with] Fix minor mistake in error message In one of the cases recently added to this check in #110448, the error message is no longer accurate as the comparison is not with zero. #116033 brought my attention to this as it may add another comparison without zero. Remove the `[!=] 0` part of the diagnostic. This is in line with some other checks e.g. modernize-use-emplace. ``` > cat tmp.cpp #include bool f(std::string u, std::string v) { return u.rfind(v) == u.size() - v.size(); } # Before. > ./build/bin/clang-tidy -checks="-*,modernize-use-starts-ends-with" tmp.cpp -- > -std=c++20 tmp.cpp:3:12: warning: use ends_with instead of rfind() == 0 [modernize-use-starts-ends-with] 3 | return u.rfind(v) == u.size() - v.size(); |^~ |ends_with( ) # After. > ./build/bin/clang-tidy -checks="-*,modernize-use-starts-ends-with" tmp.cpp -- > -std=c++20 tmp.cpp:3:12: warning: use ends_with instead of rfind [modernize-use-starts-ends-with] 3 | return u.rfind(v) == u.size() - v.size(); |^~ |ends_with( ) ``` --- .../clang-tidy/modernize/UseStartsEndsWithCheck.cpp| 9 +++-- clang-tools-extra/docs/ReleaseNotes.rst| 3 ++- .../checkers/modernize/use-starts-ends-with.cpp| 10 +- 3 files changed, 10 insertions(+), 12 deletions(-) diff --git a/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp index 1231f954298adc..4d8f6dbc2cc11b 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp @@ -189,11 +189,8 @@ void UseStartsEndsWithCheck::check(const MatchFinder::MatchResult &Result) { if (ComparisonExpr->getBeginLoc().isMacroID()) return; - const bool Neg = ComparisonExpr->getOpcode() == BO_NE; - - auto Diagnostic = - diag(FindExpr->getExprLoc(), "use %0 instead of %1() %select{==|!=}2 0") - << ReplacementFunction->getName() << FindFun->getName() << Neg; + auto Diagnostic = diag(FindExpr->getExprLoc(), "use %0 instead of %1") +<< ReplacementFunction->getName() << FindFun->getName(); // Remove possible arguments after search expression and ' [!=]= .+' suffix. Diagnostic << FixItHint::CreateReplacement( @@ -215,7 +212,7 @@ void UseStartsEndsWithCheck::check(const MatchFinder::MatchResult &Result) { (ReplacementFunction->getName() + "(").str()); // Add possible negation '!'. - if (Neg) + if (ComparisonExpr->getOpcode() == BO_NE) Diagnostic << FixItHint::CreateInsertion(FindExpr->getBeginLoc(), "!"); } diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst index db971f08ca3dbc..9a0728e706b223 100644 --- a/clang-tools-extra/docs/ReleaseNotes.rst +++ b/clang-tools-extra/docs/ReleaseNotes.rst @@ -244,7 +244,8 @@ Changes in existing checks - Improved :doc:`modernize-use-starts-ends-with ` check to handle two cases - that can be replaced with ``ends_with`` + that can be replaced with ``ends_with``, and a small adjustment to the + diagnostic message. - Improved :doc:`modernize-use-std-format ` check to support replacing diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-starts-ends-with.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-starts-ends-with.cpp index 91477241e82e54..c9a6beb41bbb86 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-starts-ends-with.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-starts-ends-with.cpp @@ -36,7 +36,7 @@ void test(std::string s, std::string_view sv, sub_string ss, sub_sub_string sss, string_like sl, string_like_camel slc, prefer_underscore_version puv, prefer_underscore_version_flip puvf) { s.find("a") == 0; - // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with instead of find() == 0 + // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with instead of find [modernize-use-starts-ends-with] // CHECK-FIXES: s.starts_with("a"); (s)).find("a" == ((0)); @@ -68,7 +68,7 @@ void test(std::string s, std::string_view sv, sub_string ss, sub_sub_string sss, // CHECK-FIXES: !s.starts_with("a"); s.rfind("a", 0) == 0; - // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with instead of rfind() == 0 + // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with instead of rfind [modernize-use-starts-ends-with] // CHECK-FIXES: s.starts_with("a"); s.rfind(s, 0)
[clang] [MS] Add /Zc:tlsGuards option to control tls guard emission (PR #113830)
llvm-ci wrote: LLVM Buildbot has detected a new failure on builder `sanitizer-x86_64-linux-bootstrap-asan` running on `sanitizer-buildbot2` while building `clang` at step 2 "annotate". Full details are available at: https://lab.llvm.org/buildbot/#/builders/52/builds/3768 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: /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506: note: using lld-link: /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/lld-link llvm-lit: /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506: note: using ld64.lld: /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/ld64.lld llvm-lit: /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506: note: using wasm-ld: /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/wasm-ld llvm-lit: /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506: note: using ld.lld: /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/ld.lld llvm-lit: /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506: note: using lld-link: /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/lld-link llvm-lit: /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506: note: using ld64.lld: /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/ld64.lld llvm-lit: /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506: note: using wasm-ld: /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/wasm-ld llvm-lit: /home/b/sanitizer-x86_64-linux-bootstrap-asan/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: 87238 of 87239 tests, 88 workers -- Testing: 0.. 10.. 20.. 30.. 40.. 50.. 60.. 70.. 80.. 90. FAIL: lld :: ELF/aarch64-feature-gcs.s (85099 of 87238) TEST 'lld :: ELF/aarch64-feature-gcs.s' FAILED Exit Code: 1 Command Output (stderr): -- RUN: at line 2: rm -rf /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/tools/lld/test/ELF/Output/aarch64-feature-gcs.s.tmp && split-file /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/lld/test/ELF/aarch64-feature-gcs.s /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/tools/lld/test/ELF/Output/aarch64-feature-gcs.s.tmp && cd /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/tools/lld/test/ELF/Output/aarch64-feature-gcs.s.tmp + rm -rf /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/tools/lld/test/ELF/Output/aarch64-feature-gcs.s.tmp + split-file /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/lld/test/ELF/aarch64-feature-gcs.s /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/tools/lld/test/ELF/Output/aarch64-feature-gcs.s.tmp + cd /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/tools/lld/test/ELF/Output/aarch64-feature-gcs.s.tmp RUN: at line 3: /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/llvm-mc -filetype=obj -triple=aarch64-linux-gnu func1-gcs.s -o func1-gcs.o + /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/llvm-mc -filetype=obj -triple=aarch64-linux-gnu func1-gcs.s -o func1-gcs.o RUN: at line 4: /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/llvm-mc -filetype=obj -triple=aarch64-linux-gnu func2.s -o func2.o + /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/llvm-mc -filetype=obj -triple=aarch64-linux-gnu func2.s -o func2.o RUN: at line 5: /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/llvm-mc -filetype=obj -triple=aarch64-linux-gnu func2-gcs.s -o func2-gcs.o + /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/llvm-mc -filetype=obj -triple=aarch64-linux-gnu func2-gcs.s -o func2-gcs.o RUN: at line 6: /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/llvm-mc -filetype=obj -triple=aarch64-linux-gnu func3.s -o func3.o + /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/llvm-mc -filetype=obj -triple=aarch64-linux-gnu func3.s -o func3.o RUN: at line 7: /home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/llvm-mc -filetype=obj -triple=aarch64-linux-gnu func3-gcs.s -o func3
[clang] [Clang] SemaFunctionEffects: Fix bug where lambdas produced by template expansion weren't verified. (PR #116505)
https://github.com/dougsonos updated https://github.com/llvm/llvm-project/pull/116505 >From d235d3ea8bb3cabfc8db9d87233455a93fa23c05 Mon Sep 17 00:00:00 2001 From: Doug Wyatt Date: Sat, 16 Nov 2024 11:59:03 -0800 Subject: [PATCH 1/2] [Clang] SemaFunctionEffects: Fix bug where lambdas produced by template expansion were not verified. --- clang/lib/Sema/SemaFunctionEffects.cpp | 3 ++- clang/lib/Sema/SemaLambda.cpp | 3 +-- .../test/Sema/attr-nonblocking-constraints.cpp | 17 + 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/clang/lib/Sema/SemaFunctionEffects.cpp b/clang/lib/Sema/SemaFunctionEffects.cpp index 4b5ddb74b1262f..6fe4d2353a2282 100644 --- a/clang/lib/Sema/SemaFunctionEffects.cpp +++ b/clang/lib/Sema/SemaFunctionEffects.cpp @@ -807,7 +807,8 @@ class Analyzer { auto MaybeAddTemplateNote = [&](const Decl *D) { if (const FunctionDecl *FD = dyn_cast(D)) { -while (FD != nullptr && FD->isTemplateInstantiation()) { +while (FD != nullptr && FD->isTemplateInstantiation() && + FD->getPointOfInstantiation().isValid()) { S.Diag(FD->getPointOfInstantiation(), diag::note_func_effect_from_template); FD = FD->getTemplateInstantiationPattern(); diff --git a/clang/lib/Sema/SemaLambda.cpp b/clang/lib/Sema/SemaLambda.cpp index e7afa0f4c81fc4..a67c0b2b367d1a 100644 --- a/clang/lib/Sema/SemaLambda.cpp +++ b/clang/lib/Sema/SemaLambda.cpp @@ -1950,8 +1950,6 @@ ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body) { LambdaScopeInfo LSI = *cast(FunctionScopes.back()); ActOnFinishFunctionBody(LSI.CallOperator, Body); - maybeAddDeclWithEffects(LSI.CallOperator); - return BuildLambdaExpr(StartLoc, Body->getEndLoc(), &LSI); } @@ -2284,6 +2282,7 @@ ExprResult Sema::BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: break; } +maybeAddDeclWithEffects(LSI->CallOperator); } return MaybeBindToTemporary(Lambda); diff --git a/clang/test/Sema/attr-nonblocking-constraints.cpp b/clang/test/Sema/attr-nonblocking-constraints.cpp index cc9108c0a4fbd6..87cbcc9713859f 100644 --- a/clang/test/Sema/attr-nonblocking-constraints.cpp +++ b/clang/test/Sema/attr-nonblocking-constraints.cpp @@ -144,6 +144,23 @@ void nb9() [[clang::nonblocking]] expected-note {{in template expansion here}} } +// Make sure we verify lambdas produced from template expansions. +struct HasTemplatedLambda { + void (*fptr)() [[clang::nonblocking]]; + + template + HasTemplatedLambda(const C&) + : fptr{ []() [[clang::nonblocking]] { + auto* y = new int; // expected-warning {{lambda with 'nonblocking' attribute must not allocate or deallocate memory}} + } } + {} +}; + +void nb9a() +{ + HasTemplatedLambda bad(42); +} + void nb10( void (*fp1)(), // expected-note {{function pointer cannot be inferred 'nonblocking'}} void (*fp2)() [[clang::nonblocking]] >From a2e28fb65ab0b9f134793dfdc91ec564e65561e7 Mon Sep 17 00:00:00 2001 From: Doug Wyatt Date: Sat, 16 Nov 2024 17:39:24 -0800 Subject: [PATCH 2/2] Add more tests. --- .../test/Sema/attr-nonblocking-constraints.cpp | 18 ++ 1 file changed, 18 insertions(+) diff --git a/clang/test/Sema/attr-nonblocking-constraints.cpp b/clang/test/Sema/attr-nonblocking-constraints.cpp index 87cbcc9713859f..bbc909f627f4c3 100644 --- a/clang/test/Sema/attr-nonblocking-constraints.cpp +++ b/clang/test/Sema/attr-nonblocking-constraints.cpp @@ -161,6 +161,24 @@ void nb9a() HasTemplatedLambda bad(42); } +// Templated function and lambda. +template +void TemplatedFunc(T x) [[clang::nonblocking]] { + auto* ptr = new T; // expected-warning {{function with 'nonblocking' attribute must not allocate or deallocate memory}} +} + +void nb9b() [[clang::nonblocking]] { + TemplatedFunc(42); // expected-note {{in template expansion here}} + + auto foo = [](auto x) [[clang::nonblocking]] { + auto* ptr = new int; // expected-warning {{lambda with 'nonblocking' attribute must not allocate or deallocate memory}} + return x; + }; + + // Note that foo() won't be validated unless instantiated. + foo(42); +} + void nb10( void (*fp1)(), // expected-note {{function pointer cannot be inferred 'nonblocking'}} void (*fp2)() [[clang::nonblocking]] ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] SemaFunctionEffects: Fix bug where lambdas produced by template expansion weren't verified. (PR #116505)
dougsonos wrote: Thanks for the quick look. > Ah yeah, I should have noticed that in review: `ActOnX` is generally only > called during parsing, whereas `BuildX` is also called during template > instantiation. I actually do think it might have come up early in one of the giant reviews, but gotten lost amongst the bigger issues. > Also, we _do_ have tests for function templates and generic lambdas, right? > If not, we should definitely add some. Something like: ```c++ template void TemplatedFunc(T x) [[clang::nonblocking]] { auto* ptr = new T; // expected-warning {{function with 'nonblocking' attribute must not allocate or deallocate memory}} } template auto TemplatedLambda = [](T x) [[clang::nonblocking]] { auto* ptr = new T; // expected-warning {{lambda with 'nonblocking' attribute must not allocate or deallocate memory}} }; void nb9b() [[clang::nonblocking]] { TemplatedFunc(42); // expected-note {{in template expansion here}} TemplatedLambda(42); } ``` ? https://github.com/llvm/llvm-project/pull/116505 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Add new option: WrapNamespaceBodyWithNewlines (PR #106145)
https://github.com/dmasloff updated https://github.com/llvm/llvm-project/pull/106145 >From 219424f9cd3477d9290c8766eaa857234a1ae387 Mon Sep 17 00:00:00 2001 From: dmasloff Date: Mon, 26 Aug 2024 22:11:05 +0300 Subject: [PATCH 1/6] [clang-format] Add new option: WrapNamespaceBodyWithNewlines --- clang/docs/ClangFormatStyleOptions.rst | 42 clang/include/clang/Format/Format.h | 40 +++- clang/lib/Format/Format.cpp | 15 ++ clang/lib/Format/UnwrappedLineFormatter.cpp | 42 clang/unittests/Format/FormatTest.cpp | 205 5 files changed, 343 insertions(+), 1 deletion(-) diff --git a/clang/docs/ClangFormatStyleOptions.rst b/clang/docs/ClangFormatStyleOptions.rst index a427d7cd40fcdd..06ac88fc337983 100644 --- a/clang/docs/ClangFormatStyleOptions.rst +++ b/clang/docs/ClangFormatStyleOptions.rst @@ -6652,6 +6652,48 @@ the configuration (without a prefix: ``Auto``). For example: BOOST_PP_STRINGIZE +.. _WrapNamespaceBodyWithEmptyLines: + +**WrapNamespaceBodyWithEmptyLines** (``WrapNamespaceBodyWithEmptyLinesStyle``) :versionbadge:`clang-format 19` :ref:`¶ ` + Controls number of empty lines at the begging and at the end of + namespace definition. + + Possible values: + + * ``WNBWELS_Never`` (in configuration: ``Never``) +Removes all empty lines at the beginning and at the end of +namespace definition. + +.. code-block:: c++ + + namespace N1 { + namespace N2 +function(); + } + } + + * ``WNBWELS_Always`` (in configuration: ``Always``) +Always adds an empty line at the beginning and at the end of +namespace definition. MaxEmptyLinesToKeep is also applied, but +empty lines between consecutive namespace declarations are +always removed. + +.. code-block:: c++ + + namespace N1 { + namespace N2 { + +function(); + + } + } + + * ``WNBWELS_Leave`` (in configuration: ``Leave``) +Keeps existing newlines at the beginning and at the end of +namespace definition using MaxEmptyLinesToKeep for formatting. + + + .. END_FORMAT_STYLE_OPTIONS Adding additional style options diff --git a/clang/include/clang/Format/Format.h b/clang/include/clang/Format/Format.h index d8b62c7652a0f6..963c7cbe1f8809 100644 --- a/clang/include/clang/Format/Format.h +++ b/clang/include/clang/Format/Format.h @@ -5057,6 +5057,43 @@ struct FormatStyle { /// \version 11 std::vector WhitespaceSensitiveMacros; + /// Different styles for modify number of empty lines in + /// the beginning and at the of end of namespaces. + enum WrapNamespaceBodyWithEmptyLinesStyle : int8_t { +/// Removes all empty lines at the beginning and at the end of +/// namespace definition. +/// \code +/// namespace N1 { +/// namespace N2 +/// function(); +/// } +/// } +/// \endcode +WNBWELS_Never, +/// Always adds an empty line at the beginning and at the end of +/// namespace definition. MaxEmptyLinesToKeep is also applied, but +/// empty lines between consecutive namespace declarations are +/// always removed. +/// \code +/// namespace N1 { +/// namespace N2 { +/// +/// function(); +/// +/// } +/// } +/// \endcode +WNBWELS_Always, +/// Keeps existing newlines at the beginning and at the end of +/// namespace definition using MaxEmptyLinesToKeep for formatting. +WNBWELS_Leave + }; + + /// Controls number of empty lines at the begging and at the end of + /// namespace definition. + /// \version 19 + WrapNamespaceBodyWithEmptyLinesStyle WrapNamespaceBodyWithEmptyLines; + bool operator==(const FormatStyle &R) const { return AccessModifierOffset == R.AccessModifierOffset && AlignAfterOpenBracket == R.AlignAfterOpenBracket && @@ -5234,7 +5271,8 @@ struct FormatStyle { TypenameMacros == R.TypenameMacros && UseTab == R.UseTab && VerilogBreakBetweenInstancePorts == R.VerilogBreakBetweenInstancePorts && - WhitespaceSensitiveMacros == R.WhitespaceSensitiveMacros; + WhitespaceSensitiveMacros == R.WhitespaceSensitiveMacros && + WrapNamespaceBodyWithEmptyLines == R.WrapNamespaceBodyWithEmptyLines; } std::optional GetLanguageStyle(LanguageKind Language) const; diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp index d2463b892fbb96..b0d2836e9c69c2 100644 --- a/clang/lib/Format/Format.cpp +++ b/clang/lib/Format/Format.cpp @@ -829,6 +829,18 @@ template <> struct ScalarEnumerationTraits { } }; +template <> +struct ScalarEnumerationTraits< +FormatStyle::WrapNamespaceBodyWithEmptyLinesStyle> { + static void + enumeration(IO &IO, + FormatStyle::WrapNamespaceBodyWithEmptyLinesStyle &Value) { +IO.enumCase(Value, "Never", FormatStyle::WNBWELS_Never); +IO.enumCase(Value, "Always", FormatStyle::WNBWELS_Always); +IO.enumCase(Value
[clang] Added a PthreadCreateChecker and attempted to register it (PR #116515)
https://github.com/MaxSanchez99 created https://github.com/llvm/llvm-project/pull/116515 None >From 029c4183c5685ac3047aec9154a593339b206a48 Mon Sep 17 00:00:00 2001 From: Maximino Sanchez Jr Date: Sat, 16 Nov 2024 18:35:39 -0600 Subject: [PATCH] Added a PthreadCreateChecker and attempted to register it --- .../clang/StaticAnalyzer/Checkers/Checkers.td | 4 ++ clang/lib/Headers/CMakeLists.txt | 3 +- .../StaticAnalyzer/Checkers/CMakeLists.txt| 1 + .../Checkers/PthreadCreateChecker.cpp | 46 +++ clang/test/Analysis/pthreadcreate.c | 31 + 5 files changed, 84 insertions(+), 1 deletion(-) create mode 100644 clang/lib/StaticAnalyzer/Checkers/PthreadCreateChecker.cpp create mode 100644 clang/test/Analysis/pthreadcreate.c diff --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td index b03e707d638742..e7b08b89c358d5 100644 --- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td +++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td @@ -606,6 +606,10 @@ def ChrootChecker : Checker<"Chroot">, HelpText<"Check improper use of chroot">, Documentation; +def PthreadCreateChecker : Checker<"PthreadCreate">, + HelpText<"Check for creation of pthread">, + Documentation; + def PthreadLockChecker : Checker<"PthreadLock">, HelpText<"Simple lock -> unlock checker">, Dependencies<[PthreadLockBase]>, diff --git a/clang/lib/Headers/CMakeLists.txt b/clang/lib/Headers/CMakeLists.txt index a094305bcec5e4..4154dea674cbbc 100644 --- a/clang/lib/Headers/CMakeLists.txt +++ b/clang/lib/Headers/CMakeLists.txt @@ -379,7 +379,8 @@ set(zos_wrapper_files include(GetClangResourceDir) get_clang_resource_dir(output_dir PREFIX ${LLVM_LIBRARY_OUTPUT_INTDIR}/.. SUBDIR include) -set(out_files) +set(out_files +../../test/Analysis/pthreadcreate.c) set(generated_files) set(arm_common_generated_files) diff --git a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt index f40318f46dea1a..ace537837de5f3 100644 --- a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt +++ b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt @@ -92,6 +92,7 @@ add_clang_library(clangStaticAnalyzerCheckers PaddingChecker.cpp PointerArithChecker.cpp PointerSubChecker.cpp + PthreadCreateChecker.cpp PthreadLockChecker.cpp PutenvStackArrayChecker.cpp RetainCountChecker/RetainCountChecker.cpp diff --git a/clang/lib/StaticAnalyzer/Checkers/PthreadCreateChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/PthreadCreateChecker.cpp new file mode 100644 index 00..e9225fb780c867 --- /dev/null +++ b/clang/lib/StaticAnalyzer/Checkers/PthreadCreateChecker.cpp @@ -0,0 +1,46 @@ +// +// Created by MaxSa on 11/13/2024. +// + +#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" +#include "clang/StaticAnalyzer/Core/Checker.h" +#include "clang/StaticAnalyzer/Core/CheckerManager.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" + +using namespace clang; +using namespace ento; + +class PthreadCreateChecker : public Checker { +public: + void checkPostCall(const CallEvent &Call, CheckerContext &Context) const; + +}; + +void PthreadCreateChecker::checkPostCall(const CallEvent &Call, CheckerContext &Context) const { + const FunctionDecl *FuncID = Call.getDecl()->getAsFunction(); + if (!FuncID) { +return; + } + + if (FuncID->getName() == "pthread_create") { +SVal returnVal = Call.getReturnValue(); +if (returnVal.isZeroConstant()) { + llvm::errs() << "Pthread has been created\n"; +} + } +} + +// Register checker +void ento::registerPthreadCreateChecker(CheckerManager &mgr) { + mgr.registerChecker(); +} + +bool ento::shouldRegisterPthreadCreateChecker(const CheckerManager &mgr) { + return true; +} + + + diff --git a/clang/test/Analysis/pthreadcreate.c b/clang/test/Analysis/pthreadcreate.c new file mode 100644 index 00..0ca6f13d4ecb45 --- /dev/null +++ b/clang/test/Analysis/pthreadcreate.c @@ -0,0 +1,31 @@ +// +// Created by MaxSa on 11/14/2024. +// + +#include +#include +#include + + +void* thread_function(void* arg) { + printf("thread_function start\n"); + return nullptr; +} + +int main() { + pthread_t thread; + int arg = 42; + + if (pthread_create(&thread, NULL, thread_function, &arg)) { +perror("pthread_create"); +exit(1); + } + + if (pthread_join(thread, nullptr)) { +perror("pthread_join"); +exit(1); + } + + printf("thread exit\n"); + return 0; +} \ No newline at end of file ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] Reland "[LLVM] Add IRNormalizer Pass" (PR #113780)
llvm-ci wrote: LLVM Buildbot has detected a new failure on builder `clang-ppc64-aix` running on `aix-ppc64` while building `llvm` at step 3 "clean-build-dir". Full details are available at: https://lab.llvm.org/buildbot/#/builders/64/builds/1464 Here is the relevant piece of the build log for the reference ``` Step 3 (clean-build-dir) failure: Delete failed. (failure) (timed out) Step 6 (test-build-unified-tree-check-all) failure: test (failure) TEST 'Clang :: ClangScanDeps/verbose.test' FAILED Exit Code: 1 Command Output (stderr): -- RUN: at line 1: rm -rf /home/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/build/tools/clang/test/ClangScanDeps/Output/verbose.test.tmp + rm -rf /home/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/build/tools/clang/test/ClangScanDeps/Output/verbose.test.tmp RUN: at line 2: split-file /home/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/llvm-project/clang/test/ClangScanDeps/verbose.test /home/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/build/tools/clang/test/ClangScanDeps/Output/verbose.test.tmp + split-file /home/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/llvm-project/clang/test/ClangScanDeps/verbose.test /home/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/build/tools/clang/test/ClangScanDeps/Output/verbose.test.tmp RUN: at line 3: sed -e "s|DIR|/home/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/build/tools/clang/test/ClangScanDeps/Output/verbose.test.tmp|g" /home/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/build/tools/clang/test/ClangScanDeps/Output/verbose.test.tmp/cdb.json.in > /home/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/build/tools/clang/test/ClangScanDeps/Output/verbose.test.tmp/cdb.json + sed -e 's|DIR|/home/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/build/tools/clang/test/ClangScanDeps/Output/verbose.test.tmp|g' /home/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/build/tools/clang/test/ClangScanDeps/Output/verbose.test.tmp/cdb.json.in RUN: at line 5: /home/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/build/bin/clang-scan-deps -compilation-database /home/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/build/tools/clang/test/ClangScanDeps/Output/verbose.test.tmp/cdb.json -v -o /home/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/build/tools/clang/test/ClangScanDeps/Output/verbose.test.tmp/result.json 2>&1 | /home/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/build/bin/FileCheck /home/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/llvm-project/clang/test/ClangScanDeps/verbose.test + /home/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/build/bin/clang-scan-deps -compilation-database /home/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/build/tools/clang/test/ClangScanDeps/Output/verbose.test.tmp/cdb.json -v -o /home/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/build/tools/clang/test/ClangScanDeps/Output/verbose.test.tmp/result.json + /home/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/build/bin/FileCheck /home/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/llvm-project/clang/test/ClangScanDeps/verbose.test /home/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/llvm-project/clang/test/ClangScanDeps/verbose.test:6:11: error: CHECK: expected string not found in input // CHECK: *** Virtual File System Stats: ^ :1:1: note: scanning from here PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/ and include the crash backtrace. ^ :1:8: note: possible intended match here PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/ and include the crash backtrace. ^ Input file: Check file: /home/powerllvm/powerllvm_env/aix-ppc64/clang-ppc64-aix/llvm-project/clang/test/ClangScanDeps/verbose.test -dump-input=help explains the following input dump. Input was: << 1: PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/ and include the crash backtrace. check:6'0 X~~~ error: no match found check:6'1? possible intended match >> -- ``` https://github.com/llvm/llvm-project/pull/113780 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [NFC][Clang][TableGen] Fix file header comments (PR #116491)
llvmbot wrote: @llvm/pr-subscribers-backend-risc-v Author: Rahul Joshi (jurahul) Changes --- Full diff: https://github.com/llvm/llvm-project/pull/116491.diff 21 Files Affected: - (modified) clang/utils/TableGen/ASTTableGen.cpp (+1-1) - (modified) clang/utils/TableGen/ClangASTNodesEmitter.cpp (+1-1) - (modified) clang/utils/TableGen/ClangASTPropertiesEmitter.cpp (+1-1) - (modified) clang/utils/TableGen/ClangAttrEmitter.cpp (+1-1) - (modified) clang/utils/TableGen/ClangBuiltinsEmitter.cpp (+1-1) - (modified) clang/utils/TableGen/ClangCommentCommandInfoEmitter.cpp (+1-1) - (modified) clang/utils/TableGen/ClangCommentHTMLNamedCharacterReferenceEmitter.cpp (+1-1) - (modified) clang/utils/TableGen/ClangCommentHTMLTagsEmitter.cpp (+1-1) - (modified) clang/utils/TableGen/ClangDataCollectorsEmitter.cpp (+12) - (modified) clang/utils/TableGen/ClangDiagnosticsEmitter.cpp (+1-1) - (modified) clang/utils/TableGen/ClangOpcodesEmitter.cpp (+1-1) - (modified) clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp (+1-1) - (modified) clang/utils/TableGen/ClangOptionDocEmitter.cpp (+1-1) - (modified) clang/utils/TableGen/ClangSACheckersEmitter.cpp (+1-1) - (modified) clang/utils/TableGen/ClangSyntaxEmitter.cpp (+1-1) - (modified) clang/utils/TableGen/ClangTypeNodesEmitter.cpp (+1-1) - (modified) clang/utils/TableGen/MveEmitter.cpp (+1-1) - (modified) clang/utils/TableGen/NeonEmitter.cpp (+1-1) - (modified) clang/utils/TableGen/RISCVVEmitter.cpp (+1-1) - (modified) clang/utils/TableGen/SveEmitter.cpp (+4-4) - (modified) clang/utils/TableGen/TableGen.cpp (+1-1) ``diff diff --git a/clang/utils/TableGen/ASTTableGen.cpp b/clang/utils/TableGen/ASTTableGen.cpp index e689a67c5ed810..6fa744fb547e2d 100644 --- a/clang/utils/TableGen/ASTTableGen.cpp +++ b/clang/utils/TableGen/ASTTableGen.cpp @@ -1,4 +1,4 @@ -//=== ASTTableGen.cpp - Helper functions for working with AST records -===// +//===-- ASTTableGen.cpp - Helper functions for working with AST records ---===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. diff --git a/clang/utils/TableGen/ClangASTNodesEmitter.cpp b/clang/utils/TableGen/ClangASTNodesEmitter.cpp index 9421f48d5487ca..16749d11836246 100644 --- a/clang/utils/TableGen/ClangASTNodesEmitter.cpp +++ b/clang/utils/TableGen/ClangASTNodesEmitter.cpp @@ -1,4 +1,4 @@ -//=== ClangASTNodesEmitter.cpp - Generate Clang AST node tables -*- C++ -*-===// +//===-- ClangASTNodesEmitter.cpp - Generate Clang AST node tables -===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. diff --git a/clang/utils/TableGen/ClangASTPropertiesEmitter.cpp b/clang/utils/TableGen/ClangASTPropertiesEmitter.cpp index da64f006dd3bd1..acff6febeb8cfa 100644 --- a/clang/utils/TableGen/ClangASTPropertiesEmitter.cpp +++ b/clang/utils/TableGen/ClangASTPropertiesEmitter.cpp @@ -1,4 +1,4 @@ -//=== ClangASTPropsEmitter.cpp - Generate Clang AST properties --*- C++ -*-===// +//===-- ClangASTPropsEmitter.cpp - Generate Clang AST properties --===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. diff --git a/clang/utils/TableGen/ClangAttrEmitter.cpp b/clang/utils/TableGen/ClangAttrEmitter.cpp index b36633f9a59aa5..4aa7594ffa6eb7 100644 --- a/clang/utils/TableGen/ClangAttrEmitter.cpp +++ b/clang/utils/TableGen/ClangAttrEmitter.cpp @@ -1,4 +1,4 @@ -//===- ClangAttrEmitter.cpp - Generate Clang attribute handling =-*- C++ -*--=// +//===-- ClangAttrEmitter.cpp - Generate Clang attribute handling --===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. diff --git a/clang/utils/TableGen/ClangBuiltinsEmitter.cpp b/clang/utils/TableGen/ClangBuiltinsEmitter.cpp index 57a1fc06b26b16..6c3604adc92b99 100644 --- a/clang/utils/TableGen/ClangBuiltinsEmitter.cpp +++ b/clang/utils/TableGen/ClangBuiltinsEmitter.cpp @@ -1,4 +1,4 @@ -//=- ClangBuiltinsEmitter.cpp - Generate Clang builtins tables -*- C++ -*-// +//===-- ClangBuiltinsEmitter.cpp - Generate Clang builtins tables -===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. diff --git a/clang/utils/TableGen/ClangCommentCommandInfoEmitter.cpp b/clang/utils/TableGen/ClangCommentCommandInfoEmitter.cpp index 45a97425ef920a..f15e30cd3f8f40 100644 --- a/clang/utils/TableGen/ClangCommentCommandInfoEmitter.cpp +++ b/clang/utils/TableGen/ClangCommentCommandInfoEmitter.cpp @@ -1,4 +1,4 @@ -//===--- ClangCommentCommandInfoEmitter.cpp - Generate command lists -// +//===-- ClangCommentCommandInfoEmitter.cpp - Generate command lists ---===//
[clang] [NFC][Clang][TableGen] Fix file header comments (PR #116491)
https://github.com/jurahul ready_for_review https://github.com/llvm/llvm-project/pull/116491 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 71b3b32 - [Clang] [MS] Add /Zc:tlsGuards option to control tls guard emission (#113830)
Author: Maurice Heumann Date: 2024-11-16T17:15:47+01:00 New Revision: 71b3b32c6ec8e4691b67b2571b4f44cdd15cb588 URL: https://github.com/llvm/llvm-project/commit/71b3b32c6ec8e4691b67b2571b4f44cdd15cb588 DIFF: https://github.com/llvm/llvm-project/commit/71b3b32c6ec8e4691b67b2571b4f44cdd15cb588.diff LOG: [Clang] [MS] Add /Zc:tlsGuards option to control tls guard emission (#113830) This adds an option to control whether guards for on-demand TLS initialization in combination with Microsoft's CXX ABI are emitted or not. The behaviour should match with Microsoft: https://learn.microsoft.com/en-us/cpp/build/reference/zc-tlsguards?view=msvc-170 This fixes #103484 Added: Modified: clang/include/clang/Basic/CodeGenOptions.def clang/include/clang/Driver/Options.td clang/lib/CodeGen/MicrosoftCXXABI.cpp clang/lib/Driver/ToolChains/Clang.cpp clang/test/CodeGenCXX/ms-thread_local.cpp clang/test/Driver/cl-zc.cpp Removed: diff --git a/clang/include/clang/Basic/CodeGenOptions.def b/clang/include/clang/Basic/CodeGenOptions.def index e45370bde74a5d..4cf22c4ee08ce0 100644 --- a/clang/include/clang/Basic/CodeGenOptions.def +++ b/clang/include/clang/Basic/CodeGenOptions.def @@ -155,6 +155,7 @@ VALUE_CODEGENOPT(PatchableFunctionEntryOffset , 32, 0) CODEGENOPT(HotPatch, 1, 0) ///< Supports the Microsoft /HOTPATCH flag and ///< generates a 'patchable-function' attribute. +CODEGENOPT(TlsGuards , 1, 1) ///< Controls emission of tls guards via -fms-tls-guards CODEGENOPT(JMCInstrument, 1, 0) ///< Set when -fjmc is enabled. CODEGENOPT(InstrumentForProfiling , 1, 0) ///< Set when -pg is enabled. CODEGENOPT(CallFEntry , 1, 0) ///< Set when -mfentry is enabled. diff --git a/clang/include/clang/Driver/Options.td b/clang/include/clang/Driver/Options.td index 0a94a7185df8c7..d7230dd7272fd6 100644 --- a/clang/include/clang/Driver/Options.td +++ b/clang/include/clang/Driver/Options.td @@ -4072,6 +4072,11 @@ defm threadsafe_statics : BoolFOption<"threadsafe-statics", NegFlag, PosFlag>; +defm ms_tls_guards : BoolFOption<"ms-tls-guards", + CodeGenOpts<"TlsGuards">, DefaultTrue, + NegFlag, + PosFlag>; def ftime_report : Flag<["-"], "ftime-report">, Group, Visibility<[ClangOption, CC1Option]>, MarshallingInfoFlag>; @@ -8635,6 +8640,12 @@ def _SLASH_Zc_threadSafeInit : CLFlag<"Zc:threadSafeInit">, def _SLASH_Zc_threadSafeInit_ : CLFlag<"Zc:threadSafeInit-">, HelpText<"Disable thread-safe initialization of static variables">, Alias; +def _SLASH_Zc_tlsGuards : CLFlag<"Zc:tlsGuards">, + HelpText<"Enable on-demand initialization of thread-local variables">, + Alias; +def _SLASH_Zc_tlsGuards_ : CLFlag<"Zc:tlsGuards-">, + HelpText<"Disable on-demand initialization of thread-local variables">, + Alias; def _SLASH_Zc_trigraphs : CLFlag<"Zc:trigraphs">, HelpText<"Enable trigraphs">, Alias; def _SLASH_Zc_trigraphs_off : CLFlag<"Zc:trigraphs-">, diff --git a/clang/lib/CodeGen/MicrosoftCXXABI.cpp b/clang/lib/CodeGen/MicrosoftCXXABI.cpp index 3802dc8bcafc49..d587daac5a88a9 100644 --- a/clang/lib/CodeGen/MicrosoftCXXABI.cpp +++ b/clang/lib/CodeGen/MicrosoftCXXABI.cpp @@ -431,6 +431,7 @@ class MicrosoftCXXABI : public CGCXXABI { bool usesThreadWrapperFunction(const VarDecl *VD) const override { return getContext().getLangOpts().isCompatibleWithMSVC( LangOptions::MSVC2019_5) && + CGM.getCodeGenOpts().TlsGuards && (!isEmittedWithConstantInitializer(VD) || mayNeedDestruction(VD)); } LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD, diff --git a/clang/lib/Driver/ToolChains/Clang.cpp b/clang/lib/Driver/ToolChains/Clang.cpp index 3133b8f5762389..d3eec9fea0d498 100644 --- a/clang/lib/Driver/ToolChains/Clang.cpp +++ b/clang/lib/Driver/ToolChains/Clang.cpp @@ -7317,6 +7317,10 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA, (!IsWindowsMSVC || IsMSVC2015Compatible))) CmdArgs.push_back("-fno-threadsafe-statics"); + if (!Args.hasFlag(options::OPT_fms_tls_guards, options::OPT_fno_ms_tls_guards, +true)) +CmdArgs.push_back("-fno-ms-tls-guards"); + // Add -fno-assumptions, if it was specified. if (!Args.hasFlag(options::OPT_fassumptions, options::OPT_fno_assumptions, true)) diff --git a/clang/test/CodeGenCXX/ms-thread_local.cpp b/clang/test/CodeGenCXX/ms-thread_local.cpp index cb0e8720c19b8b..1e1d1db0744b29 100644 --- a/clang/test/CodeGenCXX/ms-thread_local.cpp +++ b/clang/test/CodeGenCXX/ms-thread_local.cpp @@ -1,5 +1,6 @@ // RUN: %clang_cc1 %s -std=c++1y -triple=i686-pc-win32 -fms-compatibility-version=19.25 -emit-llvm -o - | FileCheck %s // RUN: %clang_cc1 %s -std=c++1y -triple=i686-pc-win32 -fms-compatibility-version=19.20 -emit-llvm -o - | FileCheck %s -check-prefix=CHECK-LEGACY +// RU
[clang] [MS] Add /Zc:tlsGuards option to control tls guard emission (PR #113830)
https://github.com/Sirraide closed https://github.com/llvm/llvm-project/pull/113830 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] BPU Machine basic block placement fuzz (PR #116492)
https://github.com/dee-tree created https://github.com/llvm/llvm-project/pull/116492 - Non-optimal machine basic block placement via fuzz option - machine block frequency inversion under the special option >From 8376db35a7a7736d78bb7f0febf38203e415b489 Mon Sep 17 00:00:00 2001 From: Arseny Bochkarev Date: Wed, 25 Sep 2024 19:59:26 +0300 Subject: [PATCH 1/4] [Fuzz] Add compiler-assisted fuzzer prototype --- .../clang/Basic/DiagnosticDriverKinds.td | 6 ++ clang/include/clang/Driver/Options.td | 27 +++ clang/lib/Driver/ToolChains/Clang.cpp | 71 ++-- llvm/CMakeLists.txt | 1 + .../llvm/CompilerAssistedFuzzing/FuzzInfo.h | 43 ++ llvm/lib/CMakeLists.txt | 2 +- llvm/lib/CodeGen/CMakeLists.txt | 1 + .../CompilerAssistedFuzzing/CMakeLists.txt| 9 +++ llvm/lib/CompilerAssistedFuzzing/FuzzInfo.cpp | 81 +++ llvm/lib/Support/CMakeLists.txt | 1 + llvm/lib/Support/Statistic.cpp| 20 - 11 files changed, 255 insertions(+), 7 deletions(-) create mode 100644 llvm/include/llvm/CompilerAssistedFuzzing/FuzzInfo.h create mode 100644 llvm/lib/CompilerAssistedFuzzing/CMakeLists.txt create mode 100644 llvm/lib/CompilerAssistedFuzzing/FuzzInfo.cpp diff --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td b/clang/include/clang/Basic/DiagnosticDriverKinds.td index 97573fcf20c1fb..f59c0e286e49e9 100644 --- a/clang/include/clang/Basic/DiagnosticDriverKinds.td +++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td @@ -826,6 +826,12 @@ def warn_android_unversioned_fallback : Warning< def err_drv_triple_version_invalid : Error< "version '%0' in target triple '%1' is invalid">; +def err_empty_option_value : Error< + "empty value for %0 option">; + +def warn_use_fseed : Warning<"Fuzzing with seed: %0">, + InGroup>; + def warn_missing_include_dirs : Warning< "no such include directory: '%0'">, InGroup, DefaultIgnore; } diff --git a/clang/include/clang/Driver/Options.td b/clang/include/clang/Driver/Options.td index 23bd686a85f526..264ebd3541de15 100644 --- a/clang/include/clang/Driver/Options.td +++ b/clang/include/clang/Driver/Options.td @@ -6730,6 +6730,33 @@ let Flags = [TargetSpecific] in { defm android_pad_segment : BooleanFFlag<"android-pad-segment">, Group; } // let Flags = [TargetSpecific] +// Compiler-assisted fuzzing options +def fuzz_EQ : Joined<["--"], "fuzz=">, + Flags<[NoXarchOption, HelpHidden]>, Group, + HelpText<"Fuzz selected compiler components, RISC-V only." + "Usage: --fuzz=\"[|...]\"">, + Values<"all, scheduler, mbb-placement, regalloc, isel, alloca">; + +def fseed_EQ : Joined<["--"], "fseed=">, + Flags<[NoXarchOption, HelpHidden]>, Group, + HelpText<"Specify fuzzing seed. (RISC-V only)">; + +def fseed_dump : Flag<["-"], "fseed-dump">, + Visibility<[ClangOption, CLOption]>, + Group, HelpText<"Dump fuzz seed. (RISC-V only)">; + +def fno_fseed_dump : Flag<["-"], "fno-fseed-dump">, + Visibility<[ClangOption, CLOption]>, + Group, HelpText<"Disable fuzz seed dump. (RISC-V only)">; + +def fuzz_stats_dump : Flag<["-"], "fuzz-stats-dump">, + Visibility<[ClangOption, CLOption]>, + Group, HelpText<"Dump only fuzz statistics.">; + +def fno_fuzz_stats_dump : Flag<["-"], "fno-fuzz-stats-dump">, + Visibility<[ClangOption, CLOption]>, + Group, HelpText<"Dump not only fuzz statistics.">; + //===--===// // FLangOption + NoXarchOption //===--===// diff --git a/clang/lib/Driver/ToolChains/Clang.cpp b/clang/lib/Driver/ToolChains/Clang.cpp index 0bab48caf1a5e2..c10cd539942040 100644 --- a/clang/lib/Driver/ToolChains/Clang.cpp +++ b/clang/lib/Driver/ToolChains/Clang.cpp @@ -7646,11 +7646,17 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA, // Setup statistics file output. SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D); - if (!StatsFile.empty()) { -CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile)); -if (D.CCPrintInternalStats) - CmdArgs.push_back("-stats-file-append"); - } + auto FuzzStatsDump = Args.hasFlag(options::OPT_fuzz_stats_dump, +options::OPT_fno_fuzz_stats_dump, false); + if (!StatsFile.empty() || FuzzStatsDump) { +if (FuzzStatsDump) { + CmdArgs.push_back("-mllvm"); + CmdArgs.push_back("-fuzz-only-stats"); +} +if (StatsFile.empty()) { + StatsFile.assign(Output.getFilename()); + llvm::sys::path::replace_extension(StatsFile, "stats"); +} // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option // parser. @@ -8050,6 +8056,61 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA, Input.getInputArg().renderAsInput(Args, CmdArgs); } + // Handle --fuzz= + StringRef Fu
[clang] [llvm] BPU Machine basic block placement fuzz (PR #116492)
github-actions[bot] wrote: Thank you for submitting a Pull Request (PR) to the LLVM Project! This PR will be automatically labeled and the relevant teams will be notified. If you wish to, you can add reviewers by using the "Reviewers" section on this page. If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using `@` followed by their GitHub username. If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers. If you have further questions, they may be answered by the [LLVM GitHub User Guide](https://llvm.org/docs/GitHub.html). You can also ask questions in a comment on this PR, on the [LLVM Discord](https://discord.com/invite/xS7Z362) or on the [forums](https://discourse.llvm.org/). https://github.com/llvm/llvm-project/pull/116492 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [NFC][Clang][TableGen] Fix file header comments (PR #116491)
https://github.com/kazutakahirata approved this pull request. LGTM. Thanks! https://github.com/llvm/llvm-project/pull/116491 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [NFC][Clang][TableGen] Fix file header comments (PR #116491)
https://github.com/jurahul created https://github.com/llvm/llvm-project/pull/116491 None >From a69664043703506d4331ff008d97de0c978a8aed Mon Sep 17 00:00:00 2001 From: Rahul Joshi Date: Fri, 15 Nov 2024 09:49:12 -0800 Subject: [PATCH] [NFC][Clang][TableGen] Fix file header comments --- clang/utils/TableGen/ASTTableGen.cpp | 2 +- clang/utils/TableGen/ClangASTNodesEmitter.cpp| 2 +- clang/utils/TableGen/ClangASTPropertiesEmitter.cpp | 2 +- clang/utils/TableGen/ClangAttrEmitter.cpp| 2 +- clang/utils/TableGen/ClangBuiltinsEmitter.cpp| 2 +- .../TableGen/ClangCommentCommandInfoEmitter.cpp | 2 +- ...langCommentHTMLNamedCharacterReferenceEmitter.cpp | 2 +- clang/utils/TableGen/ClangCommentHTMLTagsEmitter.cpp | 2 +- clang/utils/TableGen/ClangDataCollectorsEmitter.cpp | 12 clang/utils/TableGen/ClangDiagnosticsEmitter.cpp | 2 +- clang/utils/TableGen/ClangOpcodesEmitter.cpp | 2 +- clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp | 2 +- clang/utils/TableGen/ClangOptionDocEmitter.cpp | 2 +- clang/utils/TableGen/ClangSACheckersEmitter.cpp | 2 +- clang/utils/TableGen/ClangSyntaxEmitter.cpp | 2 +- clang/utils/TableGen/ClangTypeNodesEmitter.cpp | 2 +- clang/utils/TableGen/MveEmitter.cpp | 2 +- clang/utils/TableGen/NeonEmitter.cpp | 2 +- clang/utils/TableGen/RISCVVEmitter.cpp | 2 +- clang/utils/TableGen/SveEmitter.cpp | 8 clang/utils/TableGen/TableGen.cpp| 2 +- 21 files changed, 35 insertions(+), 23 deletions(-) diff --git a/clang/utils/TableGen/ASTTableGen.cpp b/clang/utils/TableGen/ASTTableGen.cpp index e689a67c5ed810..6fa744fb547e2d 100644 --- a/clang/utils/TableGen/ASTTableGen.cpp +++ b/clang/utils/TableGen/ASTTableGen.cpp @@ -1,4 +1,4 @@ -//=== ASTTableGen.cpp - Helper functions for working with AST records -===// +//===-- ASTTableGen.cpp - Helper functions for working with AST records ---===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. diff --git a/clang/utils/TableGen/ClangASTNodesEmitter.cpp b/clang/utils/TableGen/ClangASTNodesEmitter.cpp index 9421f48d5487ca..16749d11836246 100644 --- a/clang/utils/TableGen/ClangASTNodesEmitter.cpp +++ b/clang/utils/TableGen/ClangASTNodesEmitter.cpp @@ -1,4 +1,4 @@ -//=== ClangASTNodesEmitter.cpp - Generate Clang AST node tables -*- C++ -*-===// +//===-- ClangASTNodesEmitter.cpp - Generate Clang AST node tables -===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. diff --git a/clang/utils/TableGen/ClangASTPropertiesEmitter.cpp b/clang/utils/TableGen/ClangASTPropertiesEmitter.cpp index da64f006dd3bd1..acff6febeb8cfa 100644 --- a/clang/utils/TableGen/ClangASTPropertiesEmitter.cpp +++ b/clang/utils/TableGen/ClangASTPropertiesEmitter.cpp @@ -1,4 +1,4 @@ -//=== ClangASTPropsEmitter.cpp - Generate Clang AST properties --*- C++ -*-===// +//===-- ClangASTPropsEmitter.cpp - Generate Clang AST properties --===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. diff --git a/clang/utils/TableGen/ClangAttrEmitter.cpp b/clang/utils/TableGen/ClangAttrEmitter.cpp index b36633f9a59aa5..4aa7594ffa6eb7 100644 --- a/clang/utils/TableGen/ClangAttrEmitter.cpp +++ b/clang/utils/TableGen/ClangAttrEmitter.cpp @@ -1,4 +1,4 @@ -//===- ClangAttrEmitter.cpp - Generate Clang attribute handling =-*- C++ -*--=// +//===-- ClangAttrEmitter.cpp - Generate Clang attribute handling --===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. diff --git a/clang/utils/TableGen/ClangBuiltinsEmitter.cpp b/clang/utils/TableGen/ClangBuiltinsEmitter.cpp index 57a1fc06b26b16..6c3604adc92b99 100644 --- a/clang/utils/TableGen/ClangBuiltinsEmitter.cpp +++ b/clang/utils/TableGen/ClangBuiltinsEmitter.cpp @@ -1,4 +1,4 @@ -//=- ClangBuiltinsEmitter.cpp - Generate Clang builtins tables -*- C++ -*-// +//===-- ClangBuiltinsEmitter.cpp - Generate Clang builtins tables -===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. diff --git a/clang/utils/TableGen/ClangCommentCommandInfoEmitter.cpp b/clang/utils/TableGen/ClangCommentCommandInfoEmitter.cpp index 45a97425ef920a..f15e30cd3f8f40 100644 --- a/clang/utils/TableGen/ClangCommentCommandInfoEmitter.cpp +++ b/clang/utils/TableGen/ClangCommentCommandInfoEmitter.cpp @@ -1,4 +1,4 @@ -//===--- ClangCommentCommandInfoEmitter.cpp - Generate command lists -// +//===-- ClangCommentCommandInfoEmitt
[clang] [llvm] BPU Machine basic block placement fuzz (PR #116492)
llvmbot wrote: @llvm/pr-subscribers-llvm-analysis Author: Dmitriy Sokolov (dee-tree) Changes - Non-optimal machine basic block placement via fuzz option - machine block frequency inversion under the special option --- Patch is 20.87 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/116492.diff 13 Files Affected: - (modified) clang/include/clang/Basic/DiagnosticDriverKinds.td (+6) - (modified) clang/include/clang/Driver/Options.td (+27) - (modified) clang/lib/Driver/ToolChains/Clang.cpp (+66-4) - (modified) llvm/CMakeLists.txt (+1) - (added) llvm/include/llvm/CompilerAssistedFuzzing/FuzzInfo.h (+44) - (modified) llvm/lib/Analysis/BlockFrequencyInfoImpl.cpp (+16) - (modified) llvm/lib/CMakeLists.txt (+1-1) - (modified) llvm/lib/CodeGen/CMakeLists.txt (+1) - (modified) llvm/lib/CodeGen/MachineBlockPlacement.cpp (+44-13) - (added) llvm/lib/CompilerAssistedFuzzing/CMakeLists.txt (+9) - (added) llvm/lib/CompilerAssistedFuzzing/FuzzInfo.cpp (+82) - (modified) llvm/lib/Support/CMakeLists.txt (+1) - (modified) llvm/lib/Support/Statistic.cpp (+19-1) ``diff diff --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td b/clang/include/clang/Basic/DiagnosticDriverKinds.td index 97573fcf20c1fb..73766d45c29a58 100644 --- a/clang/include/clang/Basic/DiagnosticDriverKinds.td +++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td @@ -826,6 +826,12 @@ def warn_android_unversioned_fallback : Warning< def err_drv_triple_version_invalid : Error< "version '%0' in target triple '%1' is invalid">; +def err_empty_option_value : Error< + "empty value for %0 option">; + +def warn_use_fseed : Warning<"fuzzing with seed: %0">, + InGroup>; + def warn_missing_include_dirs : Warning< "no such include directory: '%0'">, InGroup, DefaultIgnore; } diff --git a/clang/include/clang/Driver/Options.td b/clang/include/clang/Driver/Options.td index 23bd686a85f526..502826ff325524 100644 --- a/clang/include/clang/Driver/Options.td +++ b/clang/include/clang/Driver/Options.td @@ -6730,6 +6730,33 @@ let Flags = [TargetSpecific] in { defm android_pad_segment : BooleanFFlag<"android-pad-segment">, Group; } // let Flags = [TargetSpecific] +// Compiler-assisted fuzzing options +def fuzz_EQ : Joined<["--"], "fuzz=">, + Flags<[NoXarchOption, HelpHidden]>, Group, + HelpText<"Fuzz selected compiler components, RISC-V only." + "Usage: --fuzz=\"[|...]\"">, + Values<"all, scheduler, mbb-placement, regalloc, isel, alloca, bpu">; + +def fseed_EQ : Joined<["--"], "fseed=">, + Flags<[NoXarchOption, HelpHidden]>, Group, + HelpText<"Specify fuzzing seed. (RISC-V only)">; + +def fseed_dump : Flag<["-"], "fseed-dump">, + Visibility<[ClangOption, CLOption]>, + Group, HelpText<"Dump fuzz seed. (RISC-V only)">; + +def fno_fseed_dump : Flag<["-"], "fno-fseed-dump">, + Visibility<[ClangOption, CLOption]>, + Group, HelpText<"Disable fuzz seed dump. (RISC-V only)">; + +def fuzz_stats_dump : Flag<["-"], "fuzz-stats-dump">, + Visibility<[ClangOption, CLOption]>, + Group, HelpText<"Dump only fuzz statistics.">; + +def fno_fuzz_stats_dump : Flag<["-"], "fno-fuzz-stats-dump">, + Visibility<[ClangOption, CLOption]>, + Group, HelpText<"Dump not only fuzz statistics.">; + //===--===// // FLangOption + NoXarchOption //===--===// diff --git a/clang/lib/Driver/ToolChains/Clang.cpp b/clang/lib/Driver/ToolChains/Clang.cpp index 0bab48caf1a5e2..563adaa813eb09 100644 --- a/clang/lib/Driver/ToolChains/Clang.cpp +++ b/clang/lib/Driver/ToolChains/Clang.cpp @@ -7646,10 +7646,17 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA, // Setup statistics file output. SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D); - if (!StatsFile.empty()) { -CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile)); -if (D.CCPrintInternalStats) - CmdArgs.push_back("-stats-file-append"); + auto FuzzStatsDump = Args.hasFlag(options::OPT_fuzz_stats_dump, +options::OPT_fno_fuzz_stats_dump, false); + if (!StatsFile.empty() || FuzzStatsDump) { +if (FuzzStatsDump) { + CmdArgs.push_back("-mllvm"); + CmdArgs.push_back("-fuzz-only-stats"); +} +if (StatsFile.empty()) { + StatsFile.assign(Output.getFilename()); + llvm::sys::path::replace_extension(StatsFile, "stats"); +} } // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option @@ -8050,6 +8057,61 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA, Input.getInputArg().renderAsInput(Args, CmdArgs); } + // Handle --fuzz= + StringRef FuzzOptions = Args.getLastArgValue(options::OPT_fuzz_EQ).trim(); + if (!FuzzOptions.empty()) { +auto Tail = FuzzOptions; +llvm::SmallVector ActualOpts; + +do { + auto Pair = Tail
[clang] [llvm] BPU Machine basic block placement fuzz (PR #116492)
llvmbot wrote: @llvm/pr-subscribers-clang-driver Author: Dmitriy Sokolov (dee-tree) Changes - Non-optimal machine basic block placement via fuzz option - machine block frequency inversion under the special option --- Patch is 20.87 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/116492.diff 13 Files Affected: - (modified) clang/include/clang/Basic/DiagnosticDriverKinds.td (+6) - (modified) clang/include/clang/Driver/Options.td (+27) - (modified) clang/lib/Driver/ToolChains/Clang.cpp (+66-4) - (modified) llvm/CMakeLists.txt (+1) - (added) llvm/include/llvm/CompilerAssistedFuzzing/FuzzInfo.h (+44) - (modified) llvm/lib/Analysis/BlockFrequencyInfoImpl.cpp (+16) - (modified) llvm/lib/CMakeLists.txt (+1-1) - (modified) llvm/lib/CodeGen/CMakeLists.txt (+1) - (modified) llvm/lib/CodeGen/MachineBlockPlacement.cpp (+44-13) - (added) llvm/lib/CompilerAssistedFuzzing/CMakeLists.txt (+9) - (added) llvm/lib/CompilerAssistedFuzzing/FuzzInfo.cpp (+82) - (modified) llvm/lib/Support/CMakeLists.txt (+1) - (modified) llvm/lib/Support/Statistic.cpp (+19-1) ``diff diff --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td b/clang/include/clang/Basic/DiagnosticDriverKinds.td index 97573fcf20c1fb..73766d45c29a58 100644 --- a/clang/include/clang/Basic/DiagnosticDriverKinds.td +++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td @@ -826,6 +826,12 @@ def warn_android_unversioned_fallback : Warning< def err_drv_triple_version_invalid : Error< "version '%0' in target triple '%1' is invalid">; +def err_empty_option_value : Error< + "empty value for %0 option">; + +def warn_use_fseed : Warning<"fuzzing with seed: %0">, + InGroup>; + def warn_missing_include_dirs : Warning< "no such include directory: '%0'">, InGroup, DefaultIgnore; } diff --git a/clang/include/clang/Driver/Options.td b/clang/include/clang/Driver/Options.td index 23bd686a85f526..502826ff325524 100644 --- a/clang/include/clang/Driver/Options.td +++ b/clang/include/clang/Driver/Options.td @@ -6730,6 +6730,33 @@ let Flags = [TargetSpecific] in { defm android_pad_segment : BooleanFFlag<"android-pad-segment">, Group; } // let Flags = [TargetSpecific] +// Compiler-assisted fuzzing options +def fuzz_EQ : Joined<["--"], "fuzz=">, + Flags<[NoXarchOption, HelpHidden]>, Group, + HelpText<"Fuzz selected compiler components, RISC-V only." + "Usage: --fuzz=\"[|...]\"">, + Values<"all, scheduler, mbb-placement, regalloc, isel, alloca, bpu">; + +def fseed_EQ : Joined<["--"], "fseed=">, + Flags<[NoXarchOption, HelpHidden]>, Group, + HelpText<"Specify fuzzing seed. (RISC-V only)">; + +def fseed_dump : Flag<["-"], "fseed-dump">, + Visibility<[ClangOption, CLOption]>, + Group, HelpText<"Dump fuzz seed. (RISC-V only)">; + +def fno_fseed_dump : Flag<["-"], "fno-fseed-dump">, + Visibility<[ClangOption, CLOption]>, + Group, HelpText<"Disable fuzz seed dump. (RISC-V only)">; + +def fuzz_stats_dump : Flag<["-"], "fuzz-stats-dump">, + Visibility<[ClangOption, CLOption]>, + Group, HelpText<"Dump only fuzz statistics.">; + +def fno_fuzz_stats_dump : Flag<["-"], "fno-fuzz-stats-dump">, + Visibility<[ClangOption, CLOption]>, + Group, HelpText<"Dump not only fuzz statistics.">; + //===--===// // FLangOption + NoXarchOption //===--===// diff --git a/clang/lib/Driver/ToolChains/Clang.cpp b/clang/lib/Driver/ToolChains/Clang.cpp index 0bab48caf1a5e2..563adaa813eb09 100644 --- a/clang/lib/Driver/ToolChains/Clang.cpp +++ b/clang/lib/Driver/ToolChains/Clang.cpp @@ -7646,10 +7646,17 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA, // Setup statistics file output. SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D); - if (!StatsFile.empty()) { -CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile)); -if (D.CCPrintInternalStats) - CmdArgs.push_back("-stats-file-append"); + auto FuzzStatsDump = Args.hasFlag(options::OPT_fuzz_stats_dump, +options::OPT_fno_fuzz_stats_dump, false); + if (!StatsFile.empty() || FuzzStatsDump) { +if (FuzzStatsDump) { + CmdArgs.push_back("-mllvm"); + CmdArgs.push_back("-fuzz-only-stats"); +} +if (StatsFile.empty()) { + StatsFile.assign(Output.getFilename()); + llvm::sys::path::replace_extension(StatsFile, "stats"); +} } // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option @@ -8050,6 +8057,61 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA, Input.getInputArg().renderAsInput(Args, CmdArgs); } + // Handle --fuzz= + StringRef FuzzOptions = Args.getLastArgValue(options::OPT_fuzz_EQ).trim(); + if (!FuzzOptions.empty()) { +auto Tail = FuzzOptions; +llvm::SmallVector ActualOpts; + +do { + auto Pair = Tail.
[clang] [llvm] BPU Machine basic block placement fuzz (PR #116492)
https://github.com/dee-tree closed https://github.com/llvm/llvm-project/pull/116492 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [Opened-by-mistake] BPU Machine basic block placement fuzz (PR #116492)
https://github.com/dee-tree edited https://github.com/llvm/llvm-project/pull/116492 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [Opened-by-mistake] BPU Machine basic block placement fuzz (PR #116492)
https://github.com/dee-tree edited https://github.com/llvm/llvm-project/pull/116492 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [llvm] [llvm] add support for mustache templating language (PR #105893)
@@ -0,0 +1,724 @@ +//===-- Mustache.cpp --===// +// +// 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 "llvm/Support/Mustache.h" +#include "llvm/Support/Error.h" +#include "llvm/Support/raw_ostream.h" +#include + +using namespace llvm; +using namespace llvm::json; + +namespace llvm { +namespace mustache { + +class Token { +public: + enum class Type { +Text, +Variable, +Partial, +SectionOpen, +SectionClose, +InvertSectionOpen, +UnescapeVariable, +Comment, + }; + + Token(StringRef Str); + + Token(StringRef RawBody, StringRef Str, char Identifier); + + StringRef getTokenBody() const { return TokenBody; }; + + StringRef getRawBody() const { return RawBody; }; + + void setTokenBody(StringRef NewBody) { TokenBody = NewBody.str(); }; + + Accessor getAccessor() const { return Accessor; }; + + Type getType() const { return TokenType; }; + + void setIndentation(size_t NewIndentation) { Indentation = NewIndentation; }; + + size_t getIndentation() const { return Indentation; }; + + static Type getTokenType(char Identifier); + +private: + size_t Indentation; + Type TokenType; + // RawBody is the original string that was tokenized + std::string RawBody; + Accessor Accessor; + // TokenBody is the original string with the identifier removed + std::string TokenBody; +}; + +class ASTNode { +public: + enum Type { +Root, +Text, +Partial, +Variable, +UnescapeVariable, +Section, +InvertSection, + }; + + ASTNode() : T(Type::Root), ParentContext(nullptr) {}; + + ASTNode(StringRef Body, ASTNode *Parent) + : T(Type::Text), Body(Body), Parent(Parent), ParentContext(nullptr) {}; + + // Constructor for Section/InvertSection/Variable/UnescapeVariable + ASTNode(Type T, Accessor Accessor, ASTNode *Parent) + : T(T), Parent(Parent), Children({}), Accessor(Accessor), +ParentContext(nullptr) {}; + + void addChild(ASTNode *Child) { Children.emplace_back(Child); }; + + void setBody(StringRef NewBody) { Body = NewBody; }; + + void setRawBody(StringRef NewBody) { RawBody = NewBody; }; + + void setIndentation(size_t NewIndentation) { Indentation = NewIndentation; }; + + void render(const llvm::json::Value &Data, llvm::raw_ostream &OS); + + void setUpNode(llvm::BumpPtrAllocator &Alloc, StringMap &Partials, + StringMap &Lambdas, + StringMap &SectionLambdas, + DenseMap &Escapes); + +private: + void renderLambdas(const llvm::json::Value &Contexts, llvm::raw_ostream &OS, + Lambda &L); + + void renderSectionLambdas(const llvm::json::Value &Contexts, +llvm::raw_ostream &OS, SectionLambda &L); + + void renderPartial(const llvm::json::Value &Contexts, llvm::raw_ostream &OS, + ASTNode *Partial); + + void renderChild(const llvm::json::Value &Context, llvm::raw_ostream &OS); + + const llvm::json::Value *findContext(); + + llvm::BumpPtrAllocator *Allocator; + StringMap *Partials; + StringMap *Lambdas; + StringMap *SectionLambdas; + DenseMap *Escapes; + Type T; + size_t Indentation = 0; + std::string RawBody; + std::string Body; + ASTNode *Parent; + // TODO: switch implementation to SmallVector + std::vector Children; + const Accessor Accessor; + const llvm::json::Value *ParentContext; +}; + +// Custom stream to escape strings +class EscapeStringStream : public raw_ostream { +public: + explicit EscapeStringStream(llvm::raw_ostream &WrappedStream, + DenseMap &Escape) + : Escape(Escape), WrappedStream(WrappedStream) { +SetUnbuffered(); + } + +protected: + void write_impl(const char *Ptr, size_t Size) override { +llvm::StringRef Data(Ptr, Size); +for (char C : Data) { + auto It = Escape.find(C); + if (It != Escape.end()) +WrappedStream << It->getSecond(); + else +WrappedStream << C; +} + } + + uint64_t current_pos() const override { return WrappedStream.tell(); } + +private: + DenseMap &Escape; + llvm::raw_ostream &WrappedStream; +}; + +// Custom stream to add indentation used to for rendering partials +class AddIndentationStringStream : public raw_ostream { +public: + explicit AddIndentationStringStream(llvm::raw_ostream &WrappedStream, + size_t Indentation) + : Indentation(Indentation), WrappedStream(WrappedStream) { +SetUnbuffered(); + } + +protected: + void write_impl(const char *Ptr, size_t Size) override { +llvm::StringRef Data(Ptr, Size); +std::string Indent(Indentation, ' '); +for (char C : Data) { + WrappedStream << C; + if (C == '\n') +
[clang] [analyzer] Handle [[assume(cond)]] as __builtin_assume(cond) (PR #116462)
https://github.com/vinay-deshmukh updated https://github.com/llvm/llvm-project/pull/116462 >From 336eb74f2c60ec74004f6c3625ba8bcf464e40b5 Mon Sep 17 00:00:00 2001 From: Vinay Deshmukh <32487576+vinay-deshm...@users.noreply.github.com> Date: Fri, 15 Nov 2024 07:37:17 -0500 Subject: [PATCH] [analyzer] Handle `[[assume(cond)]]` as `__builtin_assume(cond)` Resolves #100762 --- .../Core/PathSensitive/ExprEngine.h | 4 ++ clang/lib/Analysis/CFG.cpp| 52 +++ clang/lib/StaticAnalyzer/Core/ExprEngine.cpp | 8 ++- .../lib/StaticAnalyzer/Core/ExprEngineCXX.cpp | 27 ++ clang/test/Analysis/out-of-bounds-new.cpp | 16 ++ 5 files changed, 106 insertions(+), 1 deletion(-) diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h index 8c7493e27fcaa6..078a1d840d0516 100644 --- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h +++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h @@ -498,6 +498,10 @@ class ExprEngine { void VisitInitListExpr(const InitListExpr *E, ExplodedNode *Pred, ExplodedNodeSet &Dst); + /// VisitAttributedStmt - Transfer function logic for AttributedStmt + void VisitAttributedStmt(const AttributedStmt *A, ExplodedNode *Pred, + ExplodedNodeSet &Dst); + /// VisitLogicalExpr - Transfer function logic for '&&', '||' void VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred, ExplodedNodeSet &Dst); diff --git a/clang/lib/Analysis/CFG.cpp b/clang/lib/Analysis/CFG.cpp index f678ac6f2ff36a..edf5eefa374807 100644 --- a/clang/lib/Analysis/CFG.cpp +++ b/clang/lib/Analysis/CFG.cpp @@ -456,6 +456,45 @@ reverse_children::reverse_children(Stmt *S) { IE->getNumInits()); return; } +case Stmt::AttributedStmtClass: { + AttributedStmt *attrStmt = cast(S); + assert(attrStmt); + + { +// for an attributed stmt, the "children()" returns only the NullStmt +// (;) but semantically the "children" are supposed to be the +// expressions _within_ i.e. the two square brackets i.e. [[ HERE ]] +// so we add the subexpressions first, _then_ add the "children" + +for (auto *child : attrStmt->children()) { + llvm::errs() << "\nchildren="; + child->dump(); +} + +for (const Attr *attr : attrStmt->getAttrs()) { + { +llvm::errs() << "\nattr="; +attr->printPretty(llvm::errs(), PrintingPolicy{LangOptions{}}); + } + + // i.e. one `assume()` + CXXAssumeAttr const *assumeAttr = llvm::dyn_cast(attr); + if (!assumeAttr) { +continue; + } + // Only handles [[ assume() ]] right now + Expr *assumption = assumeAttr->getAssumption(); + childrenBuf.push_back(assumption); +} + +// children() for an AttributedStmt is NullStmt(;) +llvm::append_range(childrenBuf, attrStmt->children()); + +// This needs to be done *after* childrenBuf has been populated. +children = childrenBuf; + } + return; +} default: break; } @@ -2475,6 +2514,14 @@ static bool isFallthroughStatement(const AttributedStmt *A) { return isFallthrough; } +static bool isCXXAssumeAttr(const AttributedStmt *A) { + bool hasAssumeAttr = hasSpecificAttr(A->getAttrs()); + + assert((!hasAssumeAttr || isa(A->getSubStmt())) && + "expected [[assume]] not to have children"); + return hasAssumeAttr; +} + CFGBlock *CFGBuilder::VisitAttributedStmt(AttributedStmt *A, AddStmtChoice asc) { // AttributedStmts for [[likely]] can have arbitrary statements as children, @@ -2490,6 +2537,11 @@ CFGBlock *CFGBuilder::VisitAttributedStmt(AttributedStmt *A, appendStmt(Block, A); } + if (isCXXAssumeAttr(A) && asc.alwaysAdd(*this, A)) { +autoCreateBlock(); +appendStmt(Block, A); + } + return VisitChildren(A); } diff --git a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp index 22eab9f66418d4..cbc83f1dbda145 100644 --- a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp +++ b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp @@ -1946,7 +1946,6 @@ void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred, // to be explicitly evaluated. case Stmt::PredefinedExprClass: case Stmt::AddrLabelExprClass: -case Stmt::AttributedStmtClass: case Stmt::IntegerLiteralClass: case Stmt::FixedPointLiteralClass: case Stmt::CharacterLiteralClass: @@ -1977,6 +1976,13 @@ void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred, break; } +case Stmt::AttributedStmtClass: { + Bldr.takeNodes(Pred); + VisitAttributedStmt(cast(S), Pred, Dst); + Bldr.
[clang] [Clang][Parser] Make 'T...[N]' within a function parameter a valid pack expansion prior to C++2c (PR #116332)
cor3ntin wrote: I am not sure we want to keep supporting the old syntax, even in older language modes (notably, it isn't supported by other compilers and is at best missleading), but I'd like more people to chime in on that. I'm all for improving diagnostics though. https://github.com/llvm/llvm-project/pull/116332 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CodeGen] Remove unused includes (NFC) (PR #116459)
https://github.com/nikic approved this pull request. https://github.com/llvm/llvm-project/pull/116459 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Lex] Remove unused includes (NFC) (PR #116460)
@@ -14,14 +14,10 @@ #include "clang/Basic/CharInfo.h" #include "clang/Basic/FileManager.h" #include "clang/Lex/HeaderMapTypes.h" -#include "llvm/ADT/SmallString.h" #include "llvm/Support/Compiler.h" -#include "llvm/Support/DataTypes.h" #include "llvm/Support/Debug.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/MemoryBuffer.h" -#include "llvm/Support/SwapByteOrder.h" -#include "llvm/Support/SystemZ/zOSSupport.h" nikic wrote: I think this one might be needed due to the use of strnlen in this file? https://github.com/llvm/llvm-project/pull/116460 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][AMDGPU] Avoid Using `byval` for `ndrange_t` when emitting `__enqueue_kernel_basic` (PR #116435)
https://github.com/shiltian edited https://github.com/llvm/llvm-project/pull/116435 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Sema] Remove unused includes (NFC) (PR #116461)
https://github.com/nikic approved this pull request. https://github.com/llvm/llvm-project/pull/116461 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Enhance modernize-use-starts-ends-with to handle substr patterns (PR #116033)
https://github.com/hjanuschka updated https://github.com/llvm/llvm-project/pull/116033 >From 5b937c431486d23a696b536aa9dde560447b5756 Mon Sep 17 00:00:00 2001 From: Helmut Januschka Date: Wed, 13 Nov 2024 12:52:36 +0100 Subject: [PATCH] [clang-tidy] Enhance modernize-use-starts-ends-with with substr detection Enhances the modernize-use-starts-ends-with check to detect substr-based patterns that can be replaced with starts_with() (C++20). This improves code readability and efficiency by avoiding temporary string creation. New patterns detected: str.substr(0, n) == "foo" -> str.starts_with("foo") "foo" == str.substr(0, n) -> str.starts_with("foo") str.substr(0, n) != "foo" -> !str.starts_with("foo") str.substr(0, strlen("foo")) == "foo" -> str.starts_with("foo") str.substr(0, prefix.size()) == "foo" -> str.starts_with("foo") The enhancement: - Integrates with existing starts_with patterns - Handles substr with zero first argument - Supports length via literals, strlen(), and size()/length() - Validates string literal length matches - Handles both == and != operators Part of modernize-use-starts-ends-with check. --- .../modernize/UseStartsEndsWithCheck.cpp | 94 --- clang-tools-extra/docs/ReleaseNotes.rst | 5 +- .../checks/modernize/use-starts-ends-with.rst | 34 ++-- .../clang-tidy/checkers/Inputs/Headers/string | 2 + .../modernize/use-starts-ends-with.cpp| 159 -- 5 files changed, 195 insertions(+), 99 deletions(-) diff --git a/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp index 1231f954298adc..7dca11549a32b3 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp @@ -30,6 +30,17 @@ struct NotLengthExprForStringNode { IntegerLiteralSizeNode->getValue().getZExtValue(); } + if (const auto *DeclRefNode = Node.get()) { +if (const auto *VD = dyn_cast(DeclRefNode->getDecl())) { + if (VD->hasInit() && VD->getType().isConstQualified()) { +if (const auto *Init = dyn_cast(VD->getInit())) { + return StringLiteralNode->getLength() != + Init->getValue().getZExtValue(); +} + } +} + } + if (const auto *StrlenNode = Node.get()) { if (StrlenNode->getDirectCallee()->getName() != "strlen" || StrlenNode->getNumArgs() != 1) { @@ -171,10 +182,37 @@ void UseStartsEndsWithCheck::registerMatchers(MatchFinder *Finder) { hasRHS(lengthExprForStringNode("needle") .bind("expr"), this); + + Finder->addMatcher( + cxxOperatorCallExpr( + hasAnyOperatorName("==", "!="), + anyOf( + hasOperands( + cxxMemberCallExpr( + argumentCountIs(2), hasArgument(0, ZeroLiteral), + // Use the existing lengthExprForStringNode matcher + hasArgument(1, lengthExprForStringNode("needle")), + callee( + cxxMethodDecl(hasName("substr"), +ofClass(OnClassWithStartsWithFunction)) + .bind("find_fun"))) + .bind("find_expr"), + expr().bind("needle")), + hasOperands(expr().bind("needle"), + cxxMemberCallExpr( + argumentCountIs(2), hasArgument(0, ZeroLiteral), + hasArgument(1, lengthExprForStringNode("needle")), + callee(cxxMethodDecl( + hasName("substr"), + ofClass(OnClassWithStartsWithFunction)) + .bind("find_fun"))) + .bind("find_expr" + .bind("expr"), + this); } void UseStartsEndsWithCheck::check(const MatchFinder::MatchResult &Result) { - const auto *ComparisonExpr = Result.Nodes.getNodeAs("expr"); + const auto *ComparisonExpr = Result.Nodes.getNodeAs("expr"); const auto *FindExpr = Result.Nodes.getNodeAs("find_expr"); const auto *FindFun = Result.Nodes.getNodeAs("find_fun"); const auto *SearchExpr = Result.Nodes.getNodeAs("needle"); @@ -183,40 +221,50 @@ void UseStartsEndsWithCheck::check(const MatchFinder::MatchResult &Result) { const auto *EndsWithFunction = Result.Nodes.getNodeAs("ends_with_fun"); assert(bool(StartsWithFunction) != bool(EndsWithFunction)); + const CXXMethodDecl *ReplacementFunction = StartsWithFunction ? StartsWithFunction : EndsWithFunction; if (ComparisonExpr->getBeginLoc().isMacroID()) return; - const bool Neg = ComparisonExpr->getOpcode() == BO_NE; + bo
[clang-tools-extra] [clang-tidy] Enhance modernize-use-starts-ends-with to handle substr patterns (PR #116033)
https://github.com/hjanuschka updated https://github.com/llvm/llvm-project/pull/116033 >From b149670c72ce08ace1f36c44d794f422f70708ed Mon Sep 17 00:00:00 2001 From: Helmut Januschka Date: Wed, 13 Nov 2024 12:52:36 +0100 Subject: [PATCH] [clang-tidy] Enhance modernize-use-starts-ends-with with substr detection Enhances the modernize-use-starts-ends-with check to detect substr-based patterns that can be replaced with starts_with() (C++20). This improves code readability and efficiency by avoiding temporary string creation. New patterns detected: str.substr(0, n) == "foo" -> str.starts_with("foo") "foo" == str.substr(0, n) -> str.starts_with("foo") str.substr(0, n) != "foo" -> !str.starts_with("foo") str.substr(0, strlen("foo")) == "foo" -> str.starts_with("foo") str.substr(0, prefix.size()) == "foo" -> str.starts_with("foo") The enhancement: - Integrates with existing starts_with patterns - Handles substr with zero first argument - Supports length via literals, strlen(), and size()/length() - Validates string literal length matches - Handles both == and != operators Part of modernize-use-starts-ends-with check. --- .../modernize/UseStartsEndsWithCheck.cpp | 93 +++--- clang-tools-extra/docs/ReleaseNotes.rst | 5 +- .../checks/modernize/use-starts-ends-with.rst | 34 ++-- .../clang-tidy/checkers/Inputs/Headers/string | 2 + .../modernize/use-starts-ends-with.cpp| 159 -- 5 files changed, 194 insertions(+), 99 deletions(-) diff --git a/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp index 1231f954298adc..0924f834ffc443 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp @@ -30,6 +30,17 @@ struct NotLengthExprForStringNode { IntegerLiteralSizeNode->getValue().getZExtValue(); } + if (const auto *DeclRefNode = Node.get()) { +if (const auto *VD = dyn_cast(DeclRefNode->getDecl())) { + if (VD->hasInit() && VD->getType().isConstQualified()) { +if (const auto *Init = dyn_cast(VD->getInit())) { + return StringLiteralNode->getLength() != + Init->getValue().getZExtValue(); +} + } +} + } + if (const auto *StrlenNode = Node.get()) { if (StrlenNode->getDirectCallee()->getName() != "strlen" || StrlenNode->getNumArgs() != 1) { @@ -171,10 +182,36 @@ void UseStartsEndsWithCheck::registerMatchers(MatchFinder *Finder) { hasRHS(lengthExprForStringNode("needle") .bind("expr"), this); + + Finder->addMatcher( + cxxOperatorCallExpr( + hasAnyOperatorName("==", "!="), + anyOf( + hasOperands( + cxxMemberCallExpr( + argumentCountIs(2), hasArgument(0, ZeroLiteral), + hasArgument(1, lengthExprForStringNode("needle")), + callee( + cxxMethodDecl(hasName("substr"), +ofClass(OnClassWithStartsWithFunction)) + .bind("find_fun"))) + .bind("find_expr"), + expr().bind("needle")), + hasOperands(expr().bind("needle"), + cxxMemberCallExpr( + argumentCountIs(2), hasArgument(0, ZeroLiteral), + hasArgument(1, lengthExprForStringNode("needle")), + callee(cxxMethodDecl( + hasName("substr"), + ofClass(OnClassWithStartsWithFunction)) + .bind("find_fun"))) + .bind("find_expr" + .bind("expr"), + this); } void UseStartsEndsWithCheck::check(const MatchFinder::MatchResult &Result) { - const auto *ComparisonExpr = Result.Nodes.getNodeAs("expr"); + const auto *ComparisonExpr = Result.Nodes.getNodeAs("expr"); const auto *FindExpr = Result.Nodes.getNodeAs("find_expr"); const auto *FindFun = Result.Nodes.getNodeAs("find_fun"); const auto *SearchExpr = Result.Nodes.getNodeAs("needle"); @@ -183,40 +220,50 @@ void UseStartsEndsWithCheck::check(const MatchFinder::MatchResult &Result) { const auto *EndsWithFunction = Result.Nodes.getNodeAs("ends_with_fun"); assert(bool(StartsWithFunction) != bool(EndsWithFunction)); + const CXXMethodDecl *ReplacementFunction = StartsWithFunction ? StartsWithFunction : EndsWithFunction; if (ComparisonExpr->getBeginLoc().isMacroID()) return; - const bool Neg = ComparisonExpr->getOpcode() == BO_NE; + bool Neg; + if (const auto *BO = llvm::dyn_cast(ComparisonExpr)) { +Neg =
[clang-tools-extra] [clang-tidy] Enhance modernize-use-starts-ends-with to handle substr patterns (PR #116033)
https://github.com/hjanuschka commented: @nicovank feedback addressed * added support for .size() * more tests - incl. macros https://github.com/llvm/llvm-project/pull/116033 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-tools-extra] [analyzer] Remove alpha.core.IdenticalExpr Checker (PR #114715)
@@ -102,6 +102,210 @@ void BranchCloneCheck::registerMatchers(MatchFinder *Finder) { this); Finder->addMatcher(switchStmt().bind("switch"), this); Finder->addMatcher(conditionalOperator().bind("condOp"), this); + Finder->addMatcher(ifStmt(hasDescendant(ifStmt())).bind("ifWithDescendantIf"), vabridgers wrote: Hello @HerrCai0907 , I do not fully understand your suggestion. Could you describe what you mean by "move the later check to here"? Thanks for taking the time to review. Best! https://github.com/llvm/llvm-project/pull/114715 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [Driver][SYCL] Add initial SYCL offload compilation support (PR #107493)
llvm-ci wrote: LLVM Buildbot has detected a new failure on builder `lld-x86_64-win` running on `as-worker-93` while building `clang,llvm` at step 7 "test-build-unified-tree-check-all". Full details are available at: https://lab.llvm.org/buildbot/#/builders/146/builds/1609 Here is the relevant piece of the build log for the reference ``` Step 7 (test-build-unified-tree-check-all) failure: test (failure) TEST 'LLVM-Unit :: Support/./SupportTests.exe/37/87' FAILED Script(shard): -- GTEST_OUTPUT=json:C:\a\lld-x86_64-win\build\unittests\Support\.\SupportTests.exe-LLVM-Unit-13348-37-87.json GTEST_SHUFFLE=0 GTEST_TOTAL_SHARDS=87 GTEST_SHARD_INDEX=37 C:\a\lld-x86_64-win\build\unittests\Support\.\SupportTests.exe -- Script: -- C:\a\lld-x86_64-win\build\unittests\Support\.\SupportTests.exe --gtest_filter=ProgramEnvTest.CreateProcessLongPath -- C:\a\lld-x86_64-win\llvm-project\llvm\unittests\Support\ProgramTest.cpp(160): error: Expected equality of these values: 0 RC Which is: -2 C:\a\lld-x86_64-win\llvm-project\llvm\unittests\Support\ProgramTest.cpp(163): error: fs::remove(Twine(LongPath)): did not return errc::success. error number: 13 error message: permission denied C:\a\lld-x86_64-win\llvm-project\llvm\unittests\Support\ProgramTest.cpp:160 Expected equality of these values: 0 RC Which is: -2 C:\a\lld-x86_64-win\llvm-project\llvm\unittests\Support\ProgramTest.cpp:163 fs::remove(Twine(LongPath)): did not return errc::success. error number: 13 error message: permission denied ``` https://github.com/llvm/llvm-project/pull/107493 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Avoid Using `byval` for `ndrange_t` when emitting `__enqueue_kernel_basic` (PR #116435)
https://github.com/arsenm approved this pull request. I'm not sure where __enqueue_kernel_basic is defined, but the signature it's declared with doesn't even have byval. This code certainly shouldn't have to be manually fixing up ABI details in any case https://github.com/llvm/llvm-project/pull/116435 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Enhance modernize-use-starts-ends-with to handle substr patterns (PR #116033)
https://github.com/hjanuschka updated https://github.com/llvm/llvm-project/pull/116033 >From 23b4bcdf52041aad1c5581e0f7dc01028770a154 Mon Sep 17 00:00:00 2001 From: Helmut Januschka Date: Wed, 13 Nov 2024 12:52:36 +0100 Subject: [PATCH] [clang-tidy] Enhance modernize-use-starts-ends-with with substr detection Enhances the modernize-use-starts-ends-with check to detect substr-based patterns that can be replaced with starts_with() (C++20). This improves code readability and efficiency by avoiding temporary string creation. New patterns detected: str.substr(0, n) == "foo" -> str.starts_with("foo") "foo" == str.substr(0, n) -> str.starts_with("foo") str.substr(0, n) != "foo" -> !str.starts_with("foo") str.substr(0, strlen("foo")) == "foo" -> str.starts_with("foo") str.substr(0, prefix.size()) == "foo" -> str.starts_with("foo") The enhancement: - Integrates with existing starts_with patterns - Handles substr with zero first argument - Supports length via literals, strlen(), and size()/length() - Validates string literal length matches - Handles both == and != operators Part of modernize-use-starts-ends-with check. --- .../modernize/UseStartsEndsWithCheck.cpp | 114 ++--- .../modernize/UseStartsEndsWithCheck.h| 1 + clang-tools-extra/docs/ReleaseNotes.rst | 5 +- .../checks/modernize/use-starts-ends-with.rst | 34 ++-- .../clang-tidy/checkers/Inputs/Headers/string | 2 + .../modernize/use-starts-ends-with.cpp| 159 -- 6 files changed, 216 insertions(+), 99 deletions(-) diff --git a/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp index 1231f954298adc..12ff31dfa03541 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp @@ -30,6 +30,17 @@ struct NotLengthExprForStringNode { IntegerLiteralSizeNode->getValue().getZExtValue(); } + if (const auto *DeclRefNode = Node.get()) { +if (const auto *VD = dyn_cast(DeclRefNode->getDecl())) { + if (VD->hasInit() && VD->getType().isConstQualified()) { +if (const auto *Init = dyn_cast(VD->getInit())) { + return StringLiteralNode->getLength() != + Init->getValue().getZExtValue(); +} + } +} + } + if (const auto *StrlenNode = Node.get()) { if (StrlenNode->getDirectCallee()->getName() != "strlen" || StrlenNode->getNumArgs() != 1) { @@ -171,10 +182,64 @@ void UseStartsEndsWithCheck::registerMatchers(MatchFinder *Finder) { hasRHS(lengthExprForStringNode("needle") .bind("expr"), this); + + Finder->addMatcher( + cxxOperatorCallExpr( + hasAnyOperatorName("==", "!="), + anyOf( + hasOperands( + cxxMemberCallExpr( + argumentCountIs(2), hasArgument(0, ZeroLiteral), + hasArgument(1, lengthExprForStringNode("needle")), + callee( + cxxMethodDecl(hasName("substr"), +ofClass(OnClassWithStartsWithFunction)) + .bind("find_fun"))) + .bind("find_expr"), + expr().bind("needle")), + hasOperands(expr().bind("needle"), + cxxMemberCallExpr( + argumentCountIs(2), hasArgument(0, ZeroLiteral), + hasArgument(1, lengthExprForStringNode("needle")), + callee(cxxMethodDecl( + hasName("substr"), + ofClass(OnClassWithStartsWithFunction)) + .bind("find_fun"))) + .bind("find_expr" + .bind("expr"), + this); +} + +bool UseStartsEndsWithCheck::isNegativeComparison(const Expr* ComparisonExpr) { + // Handle direct != operator + if (const auto *BO = llvm::dyn_cast(ComparisonExpr)) { +return BO->getOpcode() == BO_NE; + } + + // Handle operator!= call + if (const auto *Op = llvm::dyn_cast(ComparisonExpr)) { +return Op->getOperator() == OO_ExclaimEqual; + } + + // Handle rewritten !(expr == expr) + if (const auto *UO = llvm::dyn_cast(ComparisonExpr)) { +if (UO->getOpcode() == UO_LNot) { + if (const auto *InnerBO = + llvm::dyn_cast(UO->getSubExpr()->IgnoreParens())) { +return InnerBO->getOpcode() == BO_EQ; + } + if (const auto *InnerOp = + llvm::dyn_cast(UO->getSubExpr()->IgnoreParens())) { +return InnerOp->getOperator() == OO_EqualEqual; + } +} + } + + return false; } void UseStartsEndsWithCheck::check(const Matc
[clang] [analyzer] [MallocChecker] Less aggressive analysis of functions (PR #116383)
https://github.com/likeamahoney edited https://github.com/llvm/llvm-project/pull/116383 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Enhance modernize-use-starts-ends-with to handle substr patterns (PR #116033)
https://github.com/hjanuschka edited https://github.com/llvm/llvm-project/pull/116033 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Thread safety analysis: Fix substitution for operator calls (PR #116487)
llvmbot wrote: @llvm/pr-subscribers-clang-analysis @llvm/pr-subscribers-clang Author: Aaron Puchert (aaronpuchert) Changes For operator calls that go to methods we need to substitute the first parameter for "this" and the following parameters into the function parameters, instead of substituting all of them into the parameters. This revealed an issue about lambdas. An existing test accidentally worked because the substitution bug was covered by a speciality of lambdas: a CXXThisExpr in a lambda CXXMethodDecl does not refer to the implicit this argument of the method, but to a captured "this" from the context the lambda was created in. This can happen for operator calls, where it worked due to the substitution bug (we treated the implicit this argument incorrectly as parameter), and for regular calls (i.e. obj.operator()(args) instead of obj(args)), where it didn't work. The correct fix seems to be to clear the self-argument on a lambda call. Lambdas can only capture "this" inside methods, and calls to the lambda in that scope cannot substitute anything for "this". --- Full diff: https://github.com/llvm/llvm-project/pull/116487.diff 2 Files Affected: - (modified) clang/lib/Analysis/ThreadSafetyCommon.cpp (+18-2) - (modified) clang/test/SemaCXX/warn-thread-safety-analysis.cpp (+29) ``diff diff --git a/clang/lib/Analysis/ThreadSafetyCommon.cpp b/clang/lib/Analysis/ThreadSafetyCommon.cpp index cbcfefdc525490..1df89802baa9ce 100644 --- a/clang/lib/Analysis/ThreadSafetyCommon.cpp +++ b/clang/lib/Analysis/ThreadSafetyCommon.cpp @@ -135,14 +135,30 @@ CapabilityExpr SExprBuilder::translateAttrExpr(const Expr *AttrExp, Ctx.NumArgs = CE->getNumArgs(); Ctx.FunArgs = CE->getArgs(); } else if (const auto *CE = dyn_cast(DeclExp)) { -Ctx.NumArgs = CE->getNumArgs(); -Ctx.FunArgs = CE->getArgs(); +// Calls to operators that are members need to be treated like member calls. +if (isa(CE) && isa(D)) { + Ctx.SelfArg = CE->getArg(0); + Ctx.SelfArrow = false; + Ctx.NumArgs = CE->getNumArgs() - 1; + Ctx.FunArgs = CE->getArgs() + 1; +} else { + Ctx.NumArgs = CE->getNumArgs(); + Ctx.FunArgs = CE->getArgs(); +} } else if (const auto *CE = dyn_cast(DeclExp)) { Ctx.SelfArg = nullptr; // Will be set below Ctx.NumArgs = CE->getNumArgs(); Ctx.FunArgs = CE->getArgs(); } + // Usually we want to substitute the self-argument for "this", but lambdas + // are an exception: "this" on or in a lambda call operator doesn't refer + // to the lambda, but to captured "this" in the context it was created in. + // This can happen for operator calls and member calls, so fix it up here. + if (const auto *CMD = dyn_cast(D)) +if (CMD->getParent()->isLambda()) + Ctx.SelfArg = nullptr; + if (Self) { assert(!Ctx.SelfArg && "Ambiguous self argument"); assert(isa(D) && "Self argument requires function"); diff --git a/clang/test/SemaCXX/warn-thread-safety-analysis.cpp b/clang/test/SemaCXX/warn-thread-safety-analysis.cpp index 8477200456d985..3c52c8165d8529 100644 --- a/clang/test/SemaCXX/warn-thread-safety-analysis.cpp +++ b/clang/test/SemaCXX/warn-thread-safety-analysis.cpp @@ -1593,8 +1593,12 @@ namespace substitution_test { void unlockData() UNLOCK_FUNCTION(mu); void doSomething() EXCLUSIVE_LOCKS_REQUIRED(mu) { } +void operator()() EXCLUSIVE_LOCKS_REQUIRED(mu) { } + +MyData operator+(const MyData& other) const SHARED_LOCKS_REQUIRED(mu, other.mu); }; + MyData operator-(const MyData& a, const MyData& b) SHARED_LOCKS_REQUIRED(a.mu, b.mu); class DataLocker { public: @@ -1607,6 +1611,27 @@ namespace substitution_test { public: void foo(MyData* d) EXCLUSIVE_LOCKS_REQUIRED(d->mu) { } +void subst(MyData& d) { + d.doSomething(); // expected-warning {{calling function 'doSomething' requires holding mutex 'd.mu' exclusively}} + d(); // expected-warning {{calling function 'operator()' requires holding mutex 'd.mu' exclusively}} + d.operator()(); // expected-warning {{calling function 'operator()' requires holding mutex 'd.mu' exclusively}} + + d.lockData(); + d.doSomething(); + d(); + d.operator()(); + d.unlockData(); +} + +void binop(MyData& a, MyData& b) EXCLUSIVE_LOCKS_REQUIRED(a.mu) { + a + b; // expected-warning {{calling function 'operator+' requires holding mutex 'b.mu'}} + // expected-note@-1 {{found near match 'a.mu'}} + b + a; // expected-warning {{calling function 'operator+' requires holding mutex 'b.mu'}} + // expected-note@-1 {{found near match 'a.mu'}} + a - b; // expected-warning {{calling function 'operator-' requires holding mutex 'b.mu'}} + // expected-note@-1 {{found near match 'a.mu'}} +} + void bar1(MyData* d) { d->lockData(); foo(d); @@ -5172,9 +5197,13 @@ class Foo { }; func1(); // e
[clang] Revert "[HLSL] Add implicit resource element type concepts to AST" (PR #116305)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Joshua Batista (bob80905) Changes Reverts llvm/llvm-project#112600 --- Full diff: https://github.com/llvm/llvm-project/pull/116305.diff 6 Files Affected: - (modified) clang/lib/Sema/HLSLExternalSemaSource.cpp (+12-205) - (modified) clang/test/AST/HLSL/RWBuffer-AST.hlsl (+2-18) - (modified) clang/test/AST/HLSL/StructuredBuffer-AST.hlsl (+2-2) - (removed) clang/test/AST/HLSL/is_typed_resource_element_compatible_concept.hlsl (-10) - (modified) clang/test/SemaHLSL/BuiltIns/RWBuffers.hlsl (+2-13) - (modified) clang/test/SemaHLSL/BuiltIns/StructuredBuffers.hlsl (+2-2) ``diff diff --git a/clang/lib/Sema/HLSLExternalSemaSource.cpp b/clang/lib/Sema/HLSLExternalSemaSource.cpp index d90a7d3c697a04..cac15b974a276e 100644 --- a/clang/lib/Sema/HLSLExternalSemaSource.cpp +++ b/clang/lib/Sema/HLSLExternalSemaSource.cpp @@ -289,9 +289,8 @@ struct BuiltinTypeDeclBuilder { } TemplateParameterListBuilder addTemplateArgumentList(Sema &S); - BuiltinTypeDeclBuilder & - addSimpleTemplateParams(Sema &S, ArrayRef Names, ConceptDecl *CD); - BuiltinTypeDeclBuilder &addConceptSpecializationExpr(Sema &S); + BuiltinTypeDeclBuilder &addSimpleTemplateParams(Sema &S, + ArrayRef Names); }; struct TemplateParameterListBuilder { @@ -313,129 +312,30 @@ struct TemplateParameterListBuilder { S.Context, Builder.Record->getDeclContext(), SourceLocation(), SourceLocation(), /* TemplateDepth */ 0, Position, &S.Context.Idents.get(Name, tok::TokenKind::identifier), -/* Typename */ true, -/* ParameterPack */ false, -/* HasTypeConstraint*/ false); +/* Typename */ false, +/* ParameterPack */ false); if (!DefaultValue.isNull()) Decl->setDefaultArgument( S.Context, S.getTrivialTemplateArgumentLoc(DefaultValue, QualType(), SourceLocation())); + Params.emplace_back(Decl); return *this; } - /* - The concept specialization expression (CSE) constructed in - constructConceptSpecializationExpr is constructed so that it - matches the CSE that is constructed when parsing the below C++ code: - - template - concept is_typed_resource_element_compatible = sizeof(T) <= 16; - - template requires - is_typed_resource_element_compatible - struct RWBuffer { - element_type Val; - }; - - int fn() { - RWBuffer Buf; - } - - When dumping the AST and filtering for "RWBuffer", the resulting AST - structure is what we're trying to construct below, specifically the - CSE portion. - */ - ConceptSpecializationExpr * - constructConceptSpecializationExpr(Sema &S, ConceptDecl *CD) { -ASTContext &Context = S.getASTContext(); -SourceLocation Loc = Builder.Record->getBeginLoc(); -DeclarationNameInfo DNI(CD->getDeclName(), Loc); -NestedNameSpecifierLoc NNSLoc; -DeclContext *DC = Builder.Record->getDeclContext(); -TemplateArgumentListInfo TALI(Loc, Loc); - -// Assume that the concept decl has just one template parameter -// This parameter should have been added when CD was constructed -// in getTypedBufferConceptDecl -assert(CD->getTemplateParameters()->size() == 1 && - "unexpected concept decl parameter count"); -TemplateTypeParmDecl *ConceptTTPD = dyn_cast( -CD->getTemplateParameters()->getParam(0)); - -// this TemplateTypeParmDecl is the template for the resource, and is -// used to construct a template argumentthat will be used -// to construct the ImplicitConceptSpecializationDecl -TemplateTypeParmDecl *T = TemplateTypeParmDecl::Create( -Context, // AST context -Builder.Record->getDeclContext(), // DeclContext -SourceLocation(), SourceLocation(), -/*depth=*/0,// Depth in the template parameter list -/*position=*/0, // Position in the template parameter list -/*id=*/nullptr, // Identifier for 'T' -/*Typename=*/true, // Indicates this is a 'typename' or 'class' -/*ParameterPack=*/false,// Not a parameter pack -/*HasTypeConstraint=*/false // Has no type constraint -); - -T->setDeclContext(DC); - -QualType ConceptTType = Context.getTypeDeclType(ConceptTTPD); - -// this is the 2nd template argument node, on which -// the concept constraint is actually being applied: 'element_type' -TemplateArgument ConceptTA = TemplateArgument(ConceptTType); - -QualType CSETType = Context.getTypeDeclType(T); - -// this is the 1st template argument node, which represents -// the abstract type that a concept would refer to: 'T' -TemplateArgument CSETA = TemplateArgument(CSETType); - -ImplicitConceptSpecializationDecl *ImplicitCSEDecl = -ImplicitConceptSpecializationDecl::Create( -Context, Builder.R
[clang] [Driver] Remove unused includes (NFC) (PR #116316)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Kazu Hirata (kazutakahirata) Changes Identified with misc-include-cleaner. --- Full diff: https://github.com/llvm/llvm-project/pull/116316.diff 12 Files Affected: - (modified) clang/lib/Driver/Compilation.cpp (-3) - (modified) clang/lib/Driver/Distro.cpp (-1) - (modified) clang/lib/Driver/Driver.cpp (-1) - (modified) clang/lib/Driver/DriverOptions.cpp (-2) - (modified) clang/lib/Driver/Job.cpp (-2) - (modified) clang/lib/Driver/Multilib.cpp (-4) - (modified) clang/lib/Driver/MultilibBuilder.cpp (-1) - (modified) clang/lib/Driver/OffloadBundler.cpp (-1) - (modified) clang/lib/Driver/SanitizerArgs.cpp (-3) - (modified) clang/lib/Driver/ToolChain.cpp (-2) - (modified) clang/lib/Driver/Types.cpp (-3) - (modified) clang/lib/Driver/XRayArgs.cpp (-3) ``diff diff --git a/clang/lib/Driver/Compilation.cpp b/clang/lib/Driver/Compilation.cpp index ad077d5bbfa69a..4d4080507175c2 100644 --- a/clang/lib/Driver/Compilation.cpp +++ b/clang/lib/Driver/Compilation.cpp @@ -10,13 +10,10 @@ #include "clang/Basic/LLVM.h" #include "clang/Driver/Action.h" #include "clang/Driver/Driver.h" -#include "clang/Driver/DriverDiagnostic.h" #include "clang/Driver/Job.h" #include "clang/Driver/Options.h" #include "clang/Driver/ToolChain.h" #include "clang/Driver/Util.h" -#include "llvm/ADT/STLExtras.h" -#include "llvm/ADT/SmallVector.h" #include "llvm/Option/ArgList.h" #include "llvm/Option/OptSpecifier.h" #include "llvm/Option/Option.h" diff --git a/clang/lib/Driver/Distro.cpp b/clang/lib/Driver/Distro.cpp index 3d1bce027f664d..3cc79535de8dab 100644 --- a/clang/lib/Driver/Distro.cpp +++ b/clang/lib/Driver/Distro.cpp @@ -8,7 +8,6 @@ #include "clang/Driver/Distro.h" #include "clang/Basic/LLVM.h" -#include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Support/ErrorOr.h" diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp index 93e85f7dffe35a..a0f4329e36136b 100644 --- a/clang/lib/Driver/Driver.cpp +++ b/clang/lib/Driver/Driver.cpp @@ -56,7 +56,6 @@ #include "clang/Config/config.h" #include "clang/Driver/Action.h" #include "clang/Driver/Compilation.h" -#include "clang/Driver/DriverDiagnostic.h" #include "clang/Driver/InputInfo.h" #include "clang/Driver/Job.h" #include "clang/Driver/Options.h" diff --git a/clang/lib/Driver/DriverOptions.cpp b/clang/lib/Driver/DriverOptions.cpp index b25801a8f3f494..053e7f1c6404fe 100644 --- a/clang/lib/Driver/DriverOptions.cpp +++ b/clang/lib/Driver/DriverOptions.cpp @@ -7,9 +7,7 @@ //===--===// #include "clang/Driver/Options.h" -#include "llvm/ADT/STLExtras.h" #include "llvm/Option/OptTable.h" -#include "llvm/Option/Option.h" #include using namespace clang::driver; diff --git a/clang/lib/Driver/Job.cpp b/clang/lib/Driver/Job.cpp index fe2f7242b04a51..ae2f1cd1f56c99 100644 --- a/clang/lib/Driver/Job.cpp +++ b/clang/lib/Driver/Job.cpp @@ -9,7 +9,6 @@ #include "clang/Driver/Job.h" #include "clang/Basic/LLVM.h" #include "clang/Driver/Driver.h" -#include "clang/Driver/DriverDiagnostic.h" #include "clang/Driver/InputInfo.h" #include "clang/Driver/Tool.h" #include "clang/Driver/ToolChain.h" @@ -26,7 +25,6 @@ #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Program.h" #include "llvm/Support/raw_ostream.h" -#include #include #include #include diff --git a/clang/lib/Driver/Multilib.cpp b/clang/lib/Driver/Multilib.cpp index c56417c6f6d0b0..0207e0f2eb2ded 100644 --- a/clang/lib/Driver/Multilib.cpp +++ b/clang/lib/Driver/Multilib.cpp @@ -8,15 +8,11 @@ #include "clang/Driver/Multilib.h" #include "clang/Basic/LLVM.h" -#include "clang/Basic/Version.h" #include "clang/Driver/Driver.h" #include "llvm/ADT/DenseSet.h" -#include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Compiler.h" -#include "llvm/Support/Error.h" #include "llvm/Support/ErrorHandling.h" -#include "llvm/Support/Path.h" #include "llvm/Support/Regex.h" #include "llvm/Support/VersionTuple.h" #include "llvm/Support/YAMLParser.h" diff --git a/clang/lib/Driver/MultilibBuilder.cpp b/clang/lib/Driver/MultilibBuilder.cpp index 4b365a164c4586..4fbe9d9047bde5 100644 --- a/clang/lib/Driver/MultilibBuilder.cpp +++ b/clang/lib/Driver/MultilibBuilder.cpp @@ -8,7 +8,6 @@ #include "clang/Driver/MultilibBuilder.h" #include "ToolChains/CommonArgs.h" -#include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringMap.h" #include "llvm/Support/Path.h" #include "llvm/Support/Regex.h" diff --git a/clang/lib/Driver/OffloadBundler.cpp b/clang/lib/Driver/OffloadBundler.cpp index 687a38333e1287..87d7303d938c90 100644 --- a/clang/lib/Driver/OffloadBundler.cpp +++ b/clang/lib/Driver/OffloadBundler.cpp @@ -17,7 +17,6 @@ #include "clang/Driver/OffloadBundler.h" #include "clang/Basic/Cuda.h" #include "clang/Basic/TargetID.h" -#include "clang/Ba
[clang] [libcxx] [Clang] Implement CWG2369 "Ordering between constraints and substitution" (PR #102857)
zyn0217 wrote: Sadly I think I should figure out a way to remove reliance on the refactoring work of `getTemplateInstantiationArgs()`, as it is still unstable at this point. https://github.com/llvm/llvm-project/pull/102857 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [MS] Add /Zc:tlsGuards option to control tls guard emission (PR #113830)
https://github.com/momo5502 updated https://github.com/llvm/llvm-project/pull/113830 >From 722a446023bd394c85c6eebf66e7bb5631a92a4d Mon Sep 17 00:00:00 2001 From: momo5502 Date: Sun, 27 Oct 2024 20:02:00 +0100 Subject: [PATCH] [MS] Add /Zc:tlsGuards option to control tls guard emission --- clang/include/clang/Basic/CodeGenOptions.def | 1 + clang/include/clang/Driver/Options.td| 11 +++ clang/lib/CodeGen/MicrosoftCXXABI.cpp| 1 + clang/lib/Driver/ToolChains/Clang.cpp| 4 clang/test/CodeGenCXX/ms-thread_local.cpp| 4 clang/test/Driver/cl-zc.cpp | 3 +++ 6 files changed, 24 insertions(+) diff --git a/clang/include/clang/Basic/CodeGenOptions.def b/clang/include/clang/Basic/CodeGenOptions.def index e45370bde74a5d..4cf22c4ee08ce0 100644 --- a/clang/include/clang/Basic/CodeGenOptions.def +++ b/clang/include/clang/Basic/CodeGenOptions.def @@ -155,6 +155,7 @@ VALUE_CODEGENOPT(PatchableFunctionEntryOffset , 32, 0) CODEGENOPT(HotPatch, 1, 0) ///< Supports the Microsoft /HOTPATCH flag and ///< generates a 'patchable-function' attribute. +CODEGENOPT(TlsGuards , 1, 1) ///< Controls emission of tls guards via -fms-tls-guards CODEGENOPT(JMCInstrument, 1, 0) ///< Set when -fjmc is enabled. CODEGENOPT(InstrumentForProfiling , 1, 0) ///< Set when -pg is enabled. CODEGENOPT(CallFEntry , 1, 0) ///< Set when -mfentry is enabled. diff --git a/clang/include/clang/Driver/Options.td b/clang/include/clang/Driver/Options.td index 0a94a7185df8c7..d7230dd7272fd6 100644 --- a/clang/include/clang/Driver/Options.td +++ b/clang/include/clang/Driver/Options.td @@ -4072,6 +4072,11 @@ defm threadsafe_statics : BoolFOption<"threadsafe-statics", NegFlag, PosFlag>; +defm ms_tls_guards : BoolFOption<"ms-tls-guards", + CodeGenOpts<"TlsGuards">, DefaultTrue, + NegFlag, + PosFlag>; def ftime_report : Flag<["-"], "ftime-report">, Group, Visibility<[ClangOption, CC1Option]>, MarshallingInfoFlag>; @@ -8635,6 +8640,12 @@ def _SLASH_Zc_threadSafeInit : CLFlag<"Zc:threadSafeInit">, def _SLASH_Zc_threadSafeInit_ : CLFlag<"Zc:threadSafeInit-">, HelpText<"Disable thread-safe initialization of static variables">, Alias; +def _SLASH_Zc_tlsGuards : CLFlag<"Zc:tlsGuards">, + HelpText<"Enable on-demand initialization of thread-local variables">, + Alias; +def _SLASH_Zc_tlsGuards_ : CLFlag<"Zc:tlsGuards-">, + HelpText<"Disable on-demand initialization of thread-local variables">, + Alias; def _SLASH_Zc_trigraphs : CLFlag<"Zc:trigraphs">, HelpText<"Enable trigraphs">, Alias; def _SLASH_Zc_trigraphs_off : CLFlag<"Zc:trigraphs-">, diff --git a/clang/lib/CodeGen/MicrosoftCXXABI.cpp b/clang/lib/CodeGen/MicrosoftCXXABI.cpp index 3802dc8bcafc49..d587daac5a88a9 100644 --- a/clang/lib/CodeGen/MicrosoftCXXABI.cpp +++ b/clang/lib/CodeGen/MicrosoftCXXABI.cpp @@ -431,6 +431,7 @@ class MicrosoftCXXABI : public CGCXXABI { bool usesThreadWrapperFunction(const VarDecl *VD) const override { return getContext().getLangOpts().isCompatibleWithMSVC( LangOptions::MSVC2019_5) && + CGM.getCodeGenOpts().TlsGuards && (!isEmittedWithConstantInitializer(VD) || mayNeedDestruction(VD)); } LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD, diff --git a/clang/lib/Driver/ToolChains/Clang.cpp b/clang/lib/Driver/ToolChains/Clang.cpp index 3133b8f5762389..d3eec9fea0d498 100644 --- a/clang/lib/Driver/ToolChains/Clang.cpp +++ b/clang/lib/Driver/ToolChains/Clang.cpp @@ -7317,6 +7317,10 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA, (!IsWindowsMSVC || IsMSVC2015Compatible))) CmdArgs.push_back("-fno-threadsafe-statics"); + if (!Args.hasFlag(options::OPT_fms_tls_guards, options::OPT_fno_ms_tls_guards, +true)) +CmdArgs.push_back("-fno-ms-tls-guards"); + // Add -fno-assumptions, if it was specified. if (!Args.hasFlag(options::OPT_fassumptions, options::OPT_fno_assumptions, true)) diff --git a/clang/test/CodeGenCXX/ms-thread_local.cpp b/clang/test/CodeGenCXX/ms-thread_local.cpp index cb0e8720c19b8b..1e1d1db0744b29 100644 --- a/clang/test/CodeGenCXX/ms-thread_local.cpp +++ b/clang/test/CodeGenCXX/ms-thread_local.cpp @@ -1,5 +1,6 @@ // RUN: %clang_cc1 %s -std=c++1y -triple=i686-pc-win32 -fms-compatibility-version=19.25 -emit-llvm -o - | FileCheck %s // RUN: %clang_cc1 %s -std=c++1y -triple=i686-pc-win32 -fms-compatibility-version=19.20 -emit-llvm -o - | FileCheck %s -check-prefix=CHECK-LEGACY +// RUN: %clang_cc1 %s -std=c++1y -triple=i686-pc-win32 -fms-compatibility-version=19.25 -fno-ms-tls-guards -emit-llvm -o - | FileCheck %s -check-prefix=CHECK-NO-GUARDS // RUN: %clang_cc1 %s -std=c++1y -triple=i686-pc-win32 -fms-compatibility-version=19.25 -ftls-model=local-dynamic -emit-llvm -o - | FileCheck %s -check-prefix=CHECK-LD struct A { @@ -23,17 +24,20 @@ thread_local A a =
[clang] [Clang][Parser] Make 'T...[N]' within a function parameter a valid pack expansion prior to C++2c (PR #116332)
https://github.com/zyn0217 updated https://github.com/llvm/llvm-project/pull/116332 >From 5973de1d4c368a26fd179954a13de94595f35575 Mon Sep 17 00:00:00 2001 From: Younan Zhang Date: Fri, 15 Nov 2024 14:09:14 +0800 Subject: [PATCH 1/2] [Clang][Parser] Make 'T...[N]' within a function parameter a valid pack expansion prior to C++2c --- .../clang/Basic/DiagnosticParseKinds.td | 5 clang/lib/Parse/ParseExprCXX.cpp | 18 ++ .../CXX/dcl.decl/dcl.meaning/dcl.fct/p13.cpp | 5 ++-- clang/test/Parser/cxx0x-decl.cpp | 8 ++- .../SemaCXX/cxx2c-pack-indexing-ext-diags.cpp | 24 +++ 5 files changed, 52 insertions(+), 8 deletions(-) diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td b/clang/include/clang/Basic/DiagnosticParseKinds.td index 0da509280068ad..7b408f3eed5ba5 100644 --- a/clang/include/clang/Basic/DiagnosticParseKinds.td +++ b/clang/include/clang/Basic/DiagnosticParseKinds.td @@ -718,6 +718,11 @@ def warn_empty_init_statement : Warning< "has no effect">, InGroup, DefaultIgnore; def err_keyword_as_parameter : Error < "invalid parameter name: '%0' is a keyword">; +def warn_pre_cxx26_ambiguous_pack_indexing_type : Warning< + "parameter packs without specifying a name would become a pack indexing " + "declaration in C++2c onwards">, InGroup; +def note_add_a_name_to_pre_cxx26_parameter_packs : Note< + "add a name to disambiguate">; // C++ derived classes def err_dup_virtual : Error<"duplicate 'virtual' in base specifier">; diff --git a/clang/lib/Parse/ParseExprCXX.cpp b/clang/lib/Parse/ParseExprCXX.cpp index ce3624f366a2a1..c596785b267b5b 100644 --- a/clang/lib/Parse/ParseExprCXX.cpp +++ b/clang/lib/Parse/ParseExprCXX.cpp @@ -242,7 +242,25 @@ bool Parser::ParseOptionalCXXScopeSpecifier( SourceLocation Start = Tok.getLocation(); DeclSpec DS(AttrFactory); SourceLocation CCLoc; +TentativeParsingAction MaybePackIndexing(*this, /*Unannotated=*/true); SourceLocation EndLoc = ParsePackIndexingType(DS); +// C++ [cpp23.dcl.dcl-2]: +// Previously, T...[n] would declare a pack of function parameters. +// T...[n] is now a pack-index-specifier. [...] Valid C++ 2023 code that +// declares a pack of parameters without specifying a declarator-id +// becomes ill-formed. +if (!Tok.is(tok::coloncolon) && !getLangOpts().CPlusPlus26 && +getCurScope()->isFunctionDeclarationScope()) { + Diag(DS.getEllipsisLoc(), + diag::warn_pre_cxx26_ambiguous_pack_indexing_type); + Diag(DS.getEllipsisLoc(), + diag::note_add_a_name_to_pre_cxx26_parameter_packs); + MaybePackIndexing.Revert(); + return false; +} + +MaybePackIndexing.Commit(); + if (DS.getTypeSpecType() == DeclSpec::TST_error) return false; diff --git a/clang/test/CXX/dcl.decl/dcl.meaning/dcl.fct/p13.cpp b/clang/test/CXX/dcl.decl/dcl.meaning/dcl.fct/p13.cpp index dbb6e60d9b93d7..0ae08da280b152 100644 --- a/clang/test/CXX/dcl.decl/dcl.meaning/dcl.fct/p13.cpp +++ b/clang/test/CXX/dcl.decl/dcl.meaning/dcl.fct/p13.cpp @@ -58,8 +58,9 @@ void b(T[] ...); template void c(T ... []); // expected-error {{expected expression}} \ - // expected-error {{'T' does not refer to the name of a parameter pack}} \ - // expected-warning {{pack indexing is a C++2c extension}} + // expected-error {{type 'T[]' of function parameter pack does not contain any unexpanded parameter packs}} \ + // expected-warning {{would become a pack indexing declaration in C++2c onwards}} \ + // expected-note {{add a name to disambiguate}} template void d(T ... x[]); // expected-error{{type 'T[]' of function parameter pack does not contain any unexpanded parameter packs}} diff --git a/clang/test/Parser/cxx0x-decl.cpp b/clang/test/Parser/cxx0x-decl.cpp index a0b3266c738ff5..91b97df459df92 100644 --- a/clang/test/Parser/cxx0x-decl.cpp +++ b/clang/test/Parser/cxx0x-decl.cpp @@ -214,12 +214,8 @@ struct MemberComponentOrder : Base { void NoMissingSemicolonHere(struct S [3]); template void NoMissingSemicolonHereEither(struct S... [N]); -// expected-error@-1 {{'S' does not refer to the name of a parameter pack}} \ -// expected-error@-1 {{declaration of anonymous struct must be a definition}} \ -// expected-error@-1 {{expected parameter declarator}} \ -// expected-error@-1 {{pack indexing is a C++2c extension}} \ - - +// expected-warning@-1 {{parameter packs without specifying a name would become a pack indexing declaration in C++2c onwards}} \ +// expected-note@-1 {{add a name to disambiguate}} // This must be at the end of the file; we used to look ahead past the EOF token here. // expected-error@+1 {{expected unqualified-id}} expected-error@+1{{expected ';'}} diff --git a/clang/test/SemaCXX/cxx2c-pack-indexing-ext-diags.cpp b/clang/test/SemaCXX/cxx2c-pack-indexing-ext-diags.
[clang] [flang] [clang][driver] When -fveclib=ArmPL flag is in use, always link against libamath (PR #116432)
https://github.com/pawosm-arm updated https://github.com/llvm/llvm-project/pull/116432 >From 865831ba2fb4778e8a1c25402b1cff70abd44d6b Mon Sep 17 00:00:00 2001 From: Pawel Osmialowski Date: Fri, 15 Nov 2024 15:22:21 + Subject: [PATCH] [clang][driver] When -fveclib=ArmPL flag is in use, always link against libamath Using `-fveclib=ArmPL` without `-lamath` likely effects in the link-time errors. --- clang/lib/Driver/ToolChains/CommonArgs.cpp | 10 ++ clang/test/Driver/fveclib.c| 11 +++ flang/test/Driver/fveclib.f90 | 11 +++ 3 files changed, 32 insertions(+) diff --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp b/clang/lib/Driver/ToolChains/CommonArgs.cpp index cbba4289eb9450..913797dec123fc 100644 --- a/clang/lib/Driver/ToolChains/CommonArgs.cpp +++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp @@ -490,6 +490,16 @@ void tools::AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs, else A.renderAsInput(Args, CmdArgs); } + if (const Arg *A = Args.getLastArg(options::OPT_fveclib)) { +if (A->getNumValues() == 1) { + StringRef V = A->getValue(); + if (V == "ArmPL") { +CmdArgs.push_back(Args.MakeArgString("-lamath")); +CmdArgs.push_back(Args.MakeArgString("-lm")); +addArchSpecificRPath(TC, Args, CmdArgs); + } +} + } } void tools::addLinkerCompressDebugSectionsOption( diff --git a/clang/test/Driver/fveclib.c b/clang/test/Driver/fveclib.c index 8b233b0023398f..3c1defda2270c3 100644 --- a/clang/test/Driver/fveclib.c +++ b/clang/test/Driver/fveclib.c @@ -102,3 +102,14 @@ /* Verify no warning when math-errno is re-enabled for a different veclib (that does not imply -fno-math-errno). */ // RUN: %clang -### --target=aarch64-linux-gnu -fveclib=ArmPL -fmath-errno -fveclib=LIBMVEC %s 2>&1 | FileCheck --check-prefix=CHECK-REPEAT-VECLIB %s // CHECK-REPEAT-VECLIB-NOT: math errno enabled + +/* Verify that vectorized routines library is being linked in. */ +// RUN: %clang -### --target=aarch64-linux-gnu -fveclib=ArmPL %s 2>&1 | FileCheck --check-prefix=CHECK-LINKING-ARMPL %s +// CHECK-LINKING-ARMPL: "-lamath" +// CHECK-LINKING-ARMPL-SAME: "-lm" + +/* Verify that the RPATH is being set when needed. */ +// RUN: %clang -### --target=aarch64-linux-gnu -resource-dir=%S/../../../clang/test/Driver/Inputs/resource_dir_with_arch_subdir -frtlib-add-rpath -fveclib=ArmPL %s 2>&1 | FileCheck --check-prefix=CHECK-RPATH-ARMPL %s +// CHECK-RPATH-ARMPL: "-lamath" +// CHECK-RPATH-ARMPL-SAME: "-lm" +// CHECK-RPATH-ARMPL-SAME: "-rpath" diff --git a/flang/test/Driver/fveclib.f90 b/flang/test/Driver/fveclib.f90 index 14c59b0616f828..fc3df02c015165 100644 --- a/flang/test/Driver/fveclib.f90 +++ b/flang/test/Driver/fveclib.f90 @@ -30,3 +30,14 @@ ! TODO: if we add support for -nostdlib or -nodefaultlibs we need to test that ! these prevent "-framework Accelerate" being added on Darwin + +! RUN: %flang -### --target=aarch64-linux-gnu -fveclib=ArmPL %s 2>&1 | FileCheck --check-prefix=CHECK-LINKING-ARMPL %s +! CHECK-LINKING-ARMPL: "-lamath" +! CHECK-LINKING-ARMPL-SAME: "-lm" + +! RUN: %flang -### --target=aarch64-linux-gnu -resource-dir=%S/../../../clang/test/Driver/Inputs/resource_dir_with_arch_subdir -frtlib-add-rpath -fveclib=ArmPL %s 2>&1 | FileCheck --check-prefix=CHECK-RPATH-ARMPL %s +! CHECK-RPATH-ARMPL: "-lamath" +! CHECK-RPATH-ARMPL-SAME: "-lm" +! We need to see "-rpath" at least twice, one for veclib, one for the Fortran runtime +! CHECK-RPATH-ARMPL-SAME: "-rpath" +! CHECK-RPATH-ARMPL-SAME: "-rpath" ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Enhance modernize-use-starts-ends-with to handle substr patterns (PR #116033)
@@ -266,3 +269,53 @@ void test(std::string s, std::string_view sv, sub_string ss, sub_sub_string sss, s.compare(0, 1, "ab") == 0; s.rfind(suffix, 1) == s.size() - suffix.size(); } + +void test_substr() { +std::string str("hello world"); +std::string prefix = "hello"; + +// Basic pattern +str.substr(0, 5) == "hello"; +// CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with instead of substr == [modernize-use-starts-ends-with] +// CHECK-FIXES: str.starts_with("hello"); + +// With string literal on left side +"hello" == str.substr(0, 5); +// CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with instead of substr == [modernize-use-starts-ends-with] +// CHECK-FIXES: str.starts_with("hello"); + +// Inequality comparison +str.substr(0, 5) != "world"; +// CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with instead of substr != [modernize-use-starts-ends-with] +// CHECK-FIXES: !str.starts_with("world"); + +// Ensure non-zero start position is not transformed +str.substr(1, 5) == "hello"; +str.substr(0, 4) == "hello"; // Length mismatch + +size_t len = 5; +str.substr(0, len) == "hello"; // Non-constant length + +// String literal with size calculation +str.substr(0, strlen("hello")) == "hello"; +// CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with instead of substr == [modernize-use-starts-ends-with] +// CHECK-FIXES: str.starts_with("hello"); + +str.substr(0, prefix.size()) == prefix; +// CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with instead of substr == [modernize-use-starts-ends-with] +// CHECK-FIXES: str.starts_with(prefix); + + // Tests to verify macro behavior +#define STARTS_WITH(X, Y) (X).substr(0, (Y).size()) == (Y) +STARTS_WITH(str, prefix); + +#define SUBSTR(X, A, B) (X).substr((A), (B)) +SUBSTR(str, 0, 6) == "prefix"; + +#define STR() str +SUBSTR(STR(), 0, 6) == "prefix"; + +"prefix" == SUBSTR(STR(), 0, 6); +// CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with instead of substr == [modernize-use-starts-ends-with] hjanuschka wrote: @nicovank just curious about this one - it emits a warning, but does not suggest a fix think its a bit more complicated as it is somehow nested macros?! https://github.com/llvm/llvm-project/pull/116033 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Thread safety analysis: Fix substitution for operator calls (PR #116487)
https://github.com/aaronpuchert created https://github.com/llvm/llvm-project/pull/116487 For operator calls that go to methods we need to substitute the first parameter for "this" and the following parameters into the function parameters, instead of substituting all of them into the parameters. This revealed an issue about lambdas. An existing test accidentally worked because the substitution bug was covered by a speciality of lambdas: a CXXThisExpr in a lambda CXXMethodDecl does not refer to the implicit this argument of the method, but to a captured "this" from the context the lambda was created in. This can happen for operator calls, where it worked due to the substitution bug (we treated the implicit this argument incorrectly as parameter), and for regular calls (i.e. obj.operator()(args) instead of obj(args)), where it didn't work. The correct fix seems to be to clear the self-argument on a lambda call. Lambdas can only capture "this" inside methods, and calls to the lambda in that scope cannot substitute anything for "this". >From 685e1b00ade1e4b27a2b4e505107f4c15d3b6c21 Mon Sep 17 00:00:00 2001 From: Aaron Puchert Date: Fri, 15 Nov 2024 23:23:07 +0100 Subject: [PATCH] Thread safety analysis: Fix substitution for operator calls For operator calls that go to methods we need to substitute the first parameter for "this" and the following parameters into the function parameters, instead of substituting all of them into the parameters. This revealed an issue about lambdas. An existing test accidentally worked because the substitution bug was covered by a speciality of lambdas: a CXXThisExpr in a lambda CXXMethodDecl does not refer to the implicit this argument of the method, but to a captured "this" from the context the lambda was created in. This can happen for operator calls, where it worked due to the substitution bug (we treated the implicit this argument incorrectly as parameter), and for regular calls (i.e. obj.operator()(args) instead of obj(args)), where it didn't work. The correct fix seems to be to clear the self-argument on a lambda call. Lambdas can only capture "this" inside methods, and calls to the lambda in that scope cannot substitute anything for "this". --- clang/lib/Analysis/ThreadSafetyCommon.cpp | 20 +++-- .../SemaCXX/warn-thread-safety-analysis.cpp | 29 +++ 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/clang/lib/Analysis/ThreadSafetyCommon.cpp b/clang/lib/Analysis/ThreadSafetyCommon.cpp index cbcfefdc525490..1df89802baa9ce 100644 --- a/clang/lib/Analysis/ThreadSafetyCommon.cpp +++ b/clang/lib/Analysis/ThreadSafetyCommon.cpp @@ -135,14 +135,30 @@ CapabilityExpr SExprBuilder::translateAttrExpr(const Expr *AttrExp, Ctx.NumArgs = CE->getNumArgs(); Ctx.FunArgs = CE->getArgs(); } else if (const auto *CE = dyn_cast(DeclExp)) { -Ctx.NumArgs = CE->getNumArgs(); -Ctx.FunArgs = CE->getArgs(); +// Calls to operators that are members need to be treated like member calls. +if (isa(CE) && isa(D)) { + Ctx.SelfArg = CE->getArg(0); + Ctx.SelfArrow = false; + Ctx.NumArgs = CE->getNumArgs() - 1; + Ctx.FunArgs = CE->getArgs() + 1; +} else { + Ctx.NumArgs = CE->getNumArgs(); + Ctx.FunArgs = CE->getArgs(); +} } else if (const auto *CE = dyn_cast(DeclExp)) { Ctx.SelfArg = nullptr; // Will be set below Ctx.NumArgs = CE->getNumArgs(); Ctx.FunArgs = CE->getArgs(); } + // Usually we want to substitute the self-argument for "this", but lambdas + // are an exception: "this" on or in a lambda call operator doesn't refer + // to the lambda, but to captured "this" in the context it was created in. + // This can happen for operator calls and member calls, so fix it up here. + if (const auto *CMD = dyn_cast(D)) +if (CMD->getParent()->isLambda()) + Ctx.SelfArg = nullptr; + if (Self) { assert(!Ctx.SelfArg && "Ambiguous self argument"); assert(isa(D) && "Self argument requires function"); diff --git a/clang/test/SemaCXX/warn-thread-safety-analysis.cpp b/clang/test/SemaCXX/warn-thread-safety-analysis.cpp index 8477200456d985..3c52c8165d8529 100644 --- a/clang/test/SemaCXX/warn-thread-safety-analysis.cpp +++ b/clang/test/SemaCXX/warn-thread-safety-analysis.cpp @@ -1593,8 +1593,12 @@ namespace substitution_test { void unlockData() UNLOCK_FUNCTION(mu); void doSomething() EXCLUSIVE_LOCKS_REQUIRED(mu) { } +void operator()() EXCLUSIVE_LOCKS_REQUIRED(mu) { } + +MyData operator+(const MyData& other) const SHARED_LOCKS_REQUIRED(mu, other.mu); }; + MyData operator-(const MyData& a, const MyData& b) SHARED_LOCKS_REQUIRED(a.mu, b.mu); class DataLocker { public: @@ -1607,6 +1611,27 @@ namespace substitution_test { public: void foo(MyData* d) EXCLUSIVE_LOCKS_REQUIRED(d->mu) { } +void subst(MyData& d) { + d.doSomething(); // expected-warning {{calling function 'doSomething' requires
[clang] 46d750b - [Sema] Remove unused includes (NFC) (#116461)
Author: Kazu Hirata Date: 2024-11-16T07:37:33-08:00 New Revision: 46d750be2e19220c318bc907dfaf6c61d3a0de92 URL: https://github.com/llvm/llvm-project/commit/46d750be2e19220c318bc907dfaf6c61d3a0de92 DIFF: https://github.com/llvm/llvm-project/commit/46d750be2e19220c318bc907dfaf6c61d3a0de92.diff LOG: [Sema] Remove unused includes (NFC) (#116461) Identified with misc-include-cleaner. Added: Modified: clang/lib/Sema/AnalysisBasedWarnings.cpp clang/lib/Sema/CodeCompleteConsumer.cpp clang/lib/Sema/DeclSpec.cpp clang/lib/Sema/ParsedAttr.cpp clang/lib/Sema/ScopeInfo.cpp clang/lib/Sema/Sema.cpp clang/lib/Sema/SemaAPINotes.cpp clang/lib/Sema/SemaAccess.cpp clang/lib/Sema/SemaAttr.cpp clang/lib/Sema/SemaCUDA.cpp clang/lib/Sema/SemaCXXScopeSpec.cpp clang/lib/Sema/SemaCast.cpp clang/lib/Sema/SemaChecking.cpp clang/lib/Sema/SemaCodeComplete.cpp clang/lib/Sema/SemaConcept.cpp clang/lib/Sema/SemaCoroutine.cpp clang/lib/Sema/SemaDecl.cpp clang/lib/Sema/SemaDeclAttr.cpp clang/lib/Sema/SemaDeclCXX.cpp clang/lib/Sema/SemaDeclObjC.cpp clang/lib/Sema/SemaExceptionSpec.cpp clang/lib/Sema/SemaExpr.cpp clang/lib/Sema/SemaExprMember.cpp clang/lib/Sema/SemaExprObjC.cpp clang/lib/Sema/SemaInit.cpp clang/lib/Sema/SemaLookup.cpp clang/lib/Sema/SemaModule.cpp clang/lib/Sema/SemaObjCProperty.cpp clang/lib/Sema/SemaOpenMP.cpp clang/lib/Sema/SemaOverload.cpp clang/lib/Sema/SemaPseudoObject.cpp clang/lib/Sema/SemaSYCL.cpp clang/lib/Sema/SemaStmt.cpp clang/lib/Sema/SemaStmtAsm.cpp clang/lib/Sema/SemaStmtAttr.cpp clang/lib/Sema/SemaTemplate.cpp clang/lib/Sema/SemaTemplateDeductionGuide.cpp clang/lib/Sema/SemaTemplateInstantiate.cpp clang/lib/Sema/SemaTemplateInstantiateDecl.cpp clang/lib/Sema/SemaType.cpp Removed: diff --git a/clang/lib/Sema/AnalysisBasedWarnings.cpp b/clang/lib/Sema/AnalysisBasedWarnings.cpp index 2ec98dc73f44cd..f11fd3a7e4038a 100644 --- a/clang/lib/Sema/AnalysisBasedWarnings.cpp +++ b/clang/lib/Sema/AnalysisBasedWarnings.cpp @@ -25,7 +25,6 @@ #include "clang/AST/ParentMap.h" #include "clang/AST/StmtCXX.h" #include "clang/AST/StmtObjC.h" -#include "clang/AST/StmtVisitor.h" #include "clang/AST/Type.h" #include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h" #include "clang/Analysis/Analyses/CalledOnceCheck.h" @@ -48,10 +47,8 @@ #include "llvm/ADT/BitVector.h" #include "llvm/ADT/MapVector.h" #include "llvm/ADT/STLFunctionalExtras.h" -#include "llvm/ADT/SmallString.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" -#include "llvm/Support/Casting.h" #include #include #include diff --git a/clang/lib/Sema/CodeCompleteConsumer.cpp b/clang/lib/Sema/CodeCompleteConsumer.cpp index 91713d71786ee5..c4e5ef0d75af75 100644 --- a/clang/lib/Sema/CodeCompleteConsumer.cpp +++ b/clang/lib/Sema/CodeCompleteConsumer.cpp @@ -21,15 +21,11 @@ #include "clang/Basic/IdentifierTable.h" #include "clang/Lex/Preprocessor.h" #include "clang/Sema/Sema.h" -#include "llvm/ADT/SmallString.h" -#include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Twine.h" -#include "llvm/Support/Casting.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/ErrorHandling.h" -#include "llvm/Support/FormatVariadic.h" #include "llvm/Support/raw_ostream.h" #include #include diff --git a/clang/lib/Sema/DeclSpec.cpp b/clang/lib/Sema/DeclSpec.cpp index 12d2d3f6060c63..ee237ffc4d2b99 100644 --- a/clang/lib/Sema/DeclSpec.cpp +++ b/clang/lib/Sema/DeclSpec.cpp @@ -22,9 +22,6 @@ #include "clang/Basic/TargetInfo.h" #include "clang/Sema/ParsedTemplate.h" #include "clang/Sema/Sema.h" -#include "clang/Sema/SemaDiagnostic.h" -#include "llvm/ADT/STLExtras.h" -#include "llvm/ADT/SmallString.h" #include using namespace clang; diff --git a/clang/lib/Sema/ParsedAttr.cpp b/clang/lib/Sema/ParsedAttr.cpp index 2109494aa5889d..eadc6ed6e6f581 100644 --- a/clang/lib/Sema/ParsedAttr.cpp +++ b/clang/lib/Sema/ParsedAttr.cpp @@ -16,9 +16,7 @@ #include "clang/Basic/IdentifierTable.h" #include "clang/Basic/TargetInfo.h" #include "clang/Sema/SemaInternal.h" -#include "llvm/ADT/SmallString.h" #include "llvm/ADT/SmallVector.h" -#include "llvm/ADT/StringRef.h" #include #include #include diff --git a/clang/lib/Sema/ScopeInfo.cpp b/clang/lib/Sema/ScopeInfo.cpp index 12fb7060727233..d089836fa36dd9 100644 --- a/clang/lib/Sema/ScopeInfo.cpp +++ b/clang/lib/Sema/ScopeInfo.cpp @@ -13,7 +13,6 @@ #include "clang/Sema/ScopeInfo.h" #include "clang/AST/Decl.h" -#include "clang/AST/DeclCXX.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprCXX.h" diff --git a/clang/lib/Sema/Sema.cpp b/clang/lib/Sema/Sema.cpp index 2b51765e80864a..942e7ece4283e3 100644 --- a/clang/lib/Sema/S
[clang] [Sema] Remove unused includes (NFC) (PR #116461)
https://github.com/kazutakahirata closed https://github.com/llvm/llvm-project/pull/116461 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] e8a6624 - [CodeGen] Remove unused includes (NFC) (#116459)
Author: Kazu Hirata Date: 2024-11-16T07:37:13-08:00 New Revision: e8a6624325e0c628ec23e5f124f1d2002f138dd5 URL: https://github.com/llvm/llvm-project/commit/e8a6624325e0c628ec23e5f124f1d2002f138dd5 DIFF: https://github.com/llvm/llvm-project/commit/e8a6624325e0c628ec23e5f124f1d2002f138dd5.diff LOG: [CodeGen] Remove unused includes (NFC) (#116459) Identified with misc-include-cleaner. Added: Modified: clang/lib/CodeGen/BackendUtil.cpp clang/lib/CodeGen/CGAtomic.cpp clang/lib/CodeGen/CGBlocks.cpp clang/lib/CodeGen/CGBuiltin.cpp clang/lib/CodeGen/CGCUDARuntime.cpp clang/lib/CodeGen/CGCXX.cpp clang/lib/CodeGen/CGCall.cpp clang/lib/CodeGen/CGClass.cpp clang/lib/CodeGen/CGDebugInfo.cpp clang/lib/CodeGen/CGDecl.cpp clang/lib/CodeGen/CGException.cpp clang/lib/CodeGen/CGExpr.cpp clang/lib/CodeGen/CGExprComplex.cpp clang/lib/CodeGen/CGGPUBuiltin.cpp clang/lib/CodeGen/CGObjC.cpp clang/lib/CodeGen/CGObjCGNU.cpp clang/lib/CodeGen/CGObjCMac.cpp clang/lib/CodeGen/CGOpenMPRuntime.cpp clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp clang/lib/CodeGen/CGVTables.cpp clang/lib/CodeGen/CodeGenABITypes.cpp clang/lib/CodeGen/CodeGenAction.cpp clang/lib/CodeGen/CodeGenFunction.cpp clang/lib/CodeGen/CodeGenModule.cpp clang/lib/CodeGen/CodeGenPGO.cpp clang/lib/CodeGen/CodeGenTBAA.cpp clang/lib/CodeGen/CoverageMappingGen.cpp clang/lib/CodeGen/ItaniumCXXABI.cpp clang/lib/CodeGen/LinkInModulesPass.cpp clang/lib/CodeGen/ObjectFilePCHContainerWriter.cpp clang/lib/CodeGen/SanitizerMetadata.cpp clang/lib/CodeGen/SwiftCallingConv.cpp Removed: diff --git a/clang/lib/CodeGen/BackendUtil.cpp b/clang/lib/CodeGen/BackendUtil.cpp index 70035a5e069a90..bf9b04f02e9f44 100644 --- a/clang/lib/CodeGen/BackendUtil.cpp +++ b/clang/lib/CodeGen/BackendUtil.cpp @@ -16,18 +16,14 @@ #include "clang/Frontend/FrontendDiagnostic.h" #include "clang/Frontend/Utils.h" #include "clang/Lex/HeaderSearchOptions.h" -#include "llvm/ADT/SmallSet.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringSwitch.h" -#include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/GlobalsModRef.h" #include "llvm/Analysis/TargetLibraryInfo.h" #include "llvm/Analysis/TargetTransformInfo.h" #include "llvm/Bitcode/BitcodeReader.h" #include "llvm/Bitcode/BitcodeWriter.h" #include "llvm/Bitcode/BitcodeWriterPass.h" -#include "llvm/CodeGen/RegAllocRegistry.h" -#include "llvm/CodeGen/SchedulerRegistry.h" #include "llvm/CodeGen/TargetSubtargetInfo.h" #include "llvm/Frontend/Driver/CodeGenOptions.h" #include "llvm/IR/DataLayout.h" @@ -39,7 +35,6 @@ #include "llvm/IR/Verifier.h" #include "llvm/IRPrinter/IRPrintingPasses.h" #include "llvm/LTO/LTOBackend.h" -#include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/TargetRegistry.h" #include "llvm/Object/OffloadBinary.h" #include "llvm/Passes/PassBuilder.h" diff --git a/clang/lib/CodeGen/CGAtomic.cpp b/clang/lib/CodeGen/CGAtomic.cpp index f8736695acf187..f6cb2ad421e906 100644 --- a/clang/lib/CodeGen/CGAtomic.cpp +++ b/clang/lib/CodeGen/CGAtomic.cpp @@ -21,7 +21,6 @@ #include "llvm/ADT/DenseMap.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/Intrinsics.h" -#include "llvm/IR/Operator.h" using namespace clang; using namespace CodeGen; diff --git a/clang/lib/CodeGen/CGBlocks.cpp b/clang/lib/CodeGen/CGBlocks.cpp index 1c46bac4bb232d..a7584a95c8ca7b 100644 --- a/clang/lib/CodeGen/CGBlocks.cpp +++ b/clang/lib/CodeGen/CGBlocks.cpp @@ -22,7 +22,6 @@ #include "clang/AST/Attr.h" #include "clang/AST/DeclObjC.h" #include "clang/CodeGen/ConstantInitBuilder.h" -#include "llvm/ADT/SmallSet.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/Module.h" #include "llvm/Support/ScopedPrinter.h" diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp index 0f29dbb9509296..df69d188306be0 100644 --- a/clang/lib/CodeGen/CGBuiltin.cpp +++ b/clang/lib/CodeGen/CGBuiltin.cpp @@ -55,7 +55,6 @@ #include "llvm/IR/IntrinsicsR600.h" #include "llvm/IR/IntrinsicsRISCV.h" #include "llvm/IR/IntrinsicsS390.h" -#include "llvm/IR/IntrinsicsVE.h" #include "llvm/IR/IntrinsicsWebAssembly.h" #include "llvm/IR/IntrinsicsX86.h" #include "llvm/IR/MDBuilder.h" @@ -69,7 +68,6 @@ #include "llvm/TargetParser/RISCVISAInfo.h" #include "llvm/TargetParser/X86TargetParser.h" #include -#include #include using namespace clang; diff --git a/clang/lib/CodeGen/CGCUDARuntime.cpp b/clang/lib/CodeGen/CGCUDARuntime.cpp index 1e1da1e2411a76..121a481213396a 100644 --- a/clang/lib/CodeGen/CGCUDARuntime.cpp +++ b/clang/lib/CodeGen/CGCUDARuntime.cpp @@ -15,7 +15,6 @@ #include "CGCUDARuntime.h" #include "CGCall.h" #include "CodeGenFunction.h" -#include "clang/AST/Decl.h" #include "clang/AST/ExprCXX.h" using namespace clang; diff --git a/clang/lib/CodeGen/CGCXX.cpp b/clang/lib/CodeGen/CGCXX.cpp in
[clang] [Lex] Remove unused includes (NFC) (PR #116460)
https://github.com/kazutakahirata updated https://github.com/llvm/llvm-project/pull/116460 >From ff95c21b5a5dbc4164c26d0d1760be2aa3d4 Mon Sep 17 00:00:00 2001 From: Kazu Hirata Date: Fri, 15 Nov 2024 17:34:23 -0800 Subject: [PATCH 1/2] [Lex] Remove unused includes (NFC) Identified with misc-include-cleaner. --- clang/lib/Lex/HeaderMap.cpp | 4 clang/lib/Lex/HeaderSearch.cpp| 1 - clang/lib/Lex/InitHeaderSearch.cpp| 3 --- clang/lib/Lex/Lexer.cpp | 1 - clang/lib/Lex/MacroArgs.cpp | 1 - clang/lib/Lex/MacroInfo.cpp | 2 -- clang/lib/Lex/ModuleMap.cpp | 2 -- clang/lib/Lex/PPCallbacks.cpp | 1 - clang/lib/Lex/PPDirectives.cpp| 4 clang/lib/Lex/PPExpressions.cpp | 1 - clang/lib/Lex/PPLexerChange.cpp | 1 - clang/lib/Lex/PPMacroExpansion.cpp| 4 clang/lib/Lex/Pragma.cpp | 4 clang/lib/Lex/PreprocessingRecord.cpp | 3 --- clang/lib/Lex/Preprocessor.cpp| 3 --- clang/lib/Lex/PreprocessorLexer.cpp | 1 - clang/lib/Lex/TokenLexer.cpp | 1 - 17 files changed, 37 deletions(-) diff --git a/clang/lib/Lex/HeaderMap.cpp b/clang/lib/Lex/HeaderMap.cpp index b04f67a4b2ed3c..f9e5b4ca0695e8 100644 --- a/clang/lib/Lex/HeaderMap.cpp +++ b/clang/lib/Lex/HeaderMap.cpp @@ -14,14 +14,10 @@ #include "clang/Basic/CharInfo.h" #include "clang/Basic/FileManager.h" #include "clang/Lex/HeaderMapTypes.h" -#include "llvm/ADT/SmallString.h" #include "llvm/Support/Compiler.h" -#include "llvm/Support/DataTypes.h" #include "llvm/Support/Debug.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/MemoryBuffer.h" -#include "llvm/Support/SwapByteOrder.h" -#include "llvm/Support/SystemZ/zOSSupport.h" #include #include #include diff --git a/clang/lib/Lex/HeaderSearch.cpp b/clang/lib/Lex/HeaderSearch.cpp index c5614a8e0ee526..bf8fe44e4ca9ca 100644 --- a/clang/lib/Lex/HeaderSearch.cpp +++ b/clang/lib/Lex/HeaderSearch.cpp @@ -24,7 +24,6 @@ #include "clang/Lex/ModuleMap.h" #include "clang/Lex/Preprocessor.h" #include "llvm/ADT/APInt.h" -#include "llvm/ADT/Hashing.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/SmallVector.h" diff --git a/clang/lib/Lex/InitHeaderSearch.cpp b/clang/lib/Lex/InitHeaderSearch.cpp index cb3941fa948211..ea02f5dfb62644 100644 --- a/clang/lib/Lex/InitHeaderSearch.cpp +++ b/clang/lib/Lex/InitHeaderSearch.cpp @@ -10,7 +10,6 @@ // //===--===// -#include "clang/Basic/DiagnosticFrontend.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/LangOptions.h" #include "clang/Config/config.h" // C_INCLUDE_DIRS @@ -18,8 +17,6 @@ #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/HeaderSearchOptions.h" #include "llvm/ADT/SmallPtrSet.h" -#include "llvm/ADT/SmallString.h" -#include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/ErrorHandling.h" diff --git a/clang/lib/Lex/Lexer.cpp b/clang/lib/Lex/Lexer.cpp index 12cb46042c946b..e58c8bc72ae5b3 100644 --- a/clang/lib/Lex/Lexer.cpp +++ b/clang/lib/Lex/Lexer.cpp @@ -32,7 +32,6 @@ #include "llvm/ADT/StringSwitch.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/ConvertUTF.h" -#include "llvm/Support/MathExtras.h" #include "llvm/Support/MemoryBufferRef.h" #include "llvm/Support/NativeFormatting.h" #include "llvm/Support/Unicode.h" diff --git a/clang/lib/Lex/MacroArgs.cpp b/clang/lib/Lex/MacroArgs.cpp index c54f69bb9ead39..2f97d9e02bc117 100644 --- a/clang/lib/Lex/MacroArgs.cpp +++ b/clang/lib/Lex/MacroArgs.cpp @@ -14,7 +14,6 @@ #include "clang/Lex/LexDiagnostic.h" #include "clang/Lex/MacroInfo.h" #include "clang/Lex/Preprocessor.h" -#include "llvm/ADT/SmallString.h" #include "llvm/Support/SaveAndRestore.h" #include diff --git a/clang/lib/Lex/MacroInfo.cpp b/clang/lib/Lex/MacroInfo.cpp index dfdf463665f3c1..c33276ea71cb7a 100644 --- a/clang/lib/Lex/MacroInfo.cpp +++ b/clang/lib/Lex/MacroInfo.cpp @@ -18,8 +18,6 @@ #include "clang/Basic/TokenKinds.h" #include "clang/Lex/Preprocessor.h" #include "clang/Lex/Token.h" -#include "llvm/ADT/StringRef.h" -#include "llvm/Support/Casting.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/raw_ostream.h" #include diff --git a/clang/lib/Lex/ModuleMap.cpp b/clang/lib/Lex/ModuleMap.cpp index dc9d2bfd5629c9..ccf94f6345ff28 100644 --- a/clang/lib/Lex/ModuleMap.cpp +++ b/clang/lib/Lex/ModuleMap.cpp @@ -30,7 +30,6 @@ #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallPtrSet.h" -#include "llvm/ADT/SmallString.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringRef.h" @@ -38,7 +37,6 @@ #include "llvm/Support/Allocator.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/ErrorHandling.h" -#include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h
[clang] [Lex] Remove unused includes (NFC) (PR #116460)
@@ -14,14 +14,10 @@ #include "clang/Basic/CharInfo.h" #include "clang/Basic/FileManager.h" #include "clang/Lex/HeaderMapTypes.h" -#include "llvm/ADT/SmallString.h" #include "llvm/Support/Compiler.h" -#include "llvm/Support/DataTypes.h" #include "llvm/Support/Debug.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/MemoryBuffer.h" -#include "llvm/Support/SwapByteOrder.h" -#include "llvm/Support/SystemZ/zOSSupport.h" kazutakahirata wrote: Thank you for catching this! Fixed in the latest revision. https://github.com/llvm/llvm-project/pull/116460 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Improved readability redundant casting with enums (PR #111424)
=?utf-8?q?Félix-Antoine?= Constantin, =?utf-8?q?Félix-Antoine?= Constantin, =?utf-8?q?Félix-Antoine?= Constantin Message-ID: In-Reply-To: 5chmidti wrote: > Is it really a false negative? In another word, does `enum E1 : char {};` > mean `E1` is the type alias of `char`? > IMO is not. for me a new option is more suitable for this case. I think it is a false negative in the sense that the cast is redundant, but it is a type conversion, so maybe the default should not warn on explicit casts from enums, and make the loss of explicit Information opt-in. https://github.com/llvm/llvm-project/pull/111424 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][Parser] Make 'T...[N]' within a function parameter a valid pack expansion prior to C++2c (PR #116332)
@@ -58,8 +58,9 @@ void b(T[] ...); template void c(T ... []); // expected-error {{expected expression}} \ efriedma-quic wrote: Consider: ``` templatevoid c(T ... []); ``` Earlier versions of clang consider this valid: it's a function that takes pointers to each type T as arguments (after decay). So the "expected expression" error is wrong. https://github.com/llvm/llvm-project/pull/116332 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [flang] [clang][driver] When -fveclib=ArmPL flag is in use, always link against libamath (PR #116432)
https://github.com/pawosm-arm updated https://github.com/llvm/llvm-project/pull/116432 >From dde726aa72cd23a5a824846e6b65583d1274d18c Mon Sep 17 00:00:00 2001 From: Pawel Osmialowski Date: Fri, 15 Nov 2024 15:22:21 + Subject: [PATCH] [clang][driver] When -fveclib=ArmPL flag is in use, always link against libamath Using `-fveclib=ArmPL` without `-lamath` likely effects in the link-time errors. --- clang/lib/Driver/ToolChains/CommonArgs.cpp | 10 ++ clang/test/Driver/fveclib.c| 11 +++ flang/test/Driver/fveclib.f90 | 11 +++ 3 files changed, 32 insertions(+) diff --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp b/clang/lib/Driver/ToolChains/CommonArgs.cpp index cbba4289eb9450..913797dec123fc 100644 --- a/clang/lib/Driver/ToolChains/CommonArgs.cpp +++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp @@ -490,6 +490,16 @@ void tools::AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs, else A.renderAsInput(Args, CmdArgs); } + if (const Arg *A = Args.getLastArg(options::OPT_fveclib)) { +if (A->getNumValues() == 1) { + StringRef V = A->getValue(); + if (V == "ArmPL") { +CmdArgs.push_back(Args.MakeArgString("-lamath")); +CmdArgs.push_back(Args.MakeArgString("-lm")); +addArchSpecificRPath(TC, Args, CmdArgs); + } +} + } } void tools::addLinkerCompressDebugSectionsOption( diff --git a/clang/test/Driver/fveclib.c b/clang/test/Driver/fveclib.c index 8b233b0023398f..f148e83e11d918 100644 --- a/clang/test/Driver/fveclib.c +++ b/clang/test/Driver/fveclib.c @@ -102,3 +102,14 @@ /* Verify no warning when math-errno is re-enabled for a different veclib (that does not imply -fno-math-errno). */ // RUN: %clang -### --target=aarch64-linux-gnu -fveclib=ArmPL -fmath-errno -fveclib=LIBMVEC %s 2>&1 | FileCheck --check-prefix=CHECK-REPEAT-VECLIB %s // CHECK-REPEAT-VECLIB-NOT: math errno enabled + +/* Verify that vectorized routines library is being linked in. */ +// RUN: %clang -### --target=aarch64-linux-gnu -fveclib=ArmPL %s 2>&1 | FileCheck --check-prefix=CHECK-LINKING-ARMPL %s +// CHECK-LINKING-ARMPL: "-lamath" +// CHECK-LINKING-ARMPL-SAME: "-lm" + +/* Verify that the RPATH is being set when needed. */ +// RUN: %clang -### --target=aarch64-linux-gnu -resource-dir=%S -frtlib-add-rpath -fveclib=ArmPL %s 2>&1 | FileCheck --check-prefix=CHECK-RPATH-ARMPL %s +// CHECK-RPATH-ARMPL: "-lamath" +// CHECK-RPATH-ARMPL-SAME: "-lm" +// CHECK-RPATH-ARMPL-SAME: "-rpath" diff --git a/flang/test/Driver/fveclib.f90 b/flang/test/Driver/fveclib.f90 index 14c59b0616f828..130fb266bf4ac9 100644 --- a/flang/test/Driver/fveclib.f90 +++ b/flang/test/Driver/fveclib.f90 @@ -30,3 +30,14 @@ ! TODO: if we add support for -nostdlib or -nodefaultlibs we need to test that ! these prevent "-framework Accelerate" being added on Darwin + +! RUN: %flang -### --target=aarch64-linux-gnu -fveclib=ArmPL %s 2>&1 | FileCheck --check-prefix=CHECK-LINKING-ARMPL %s +! CHECK-LINKING-ARMPL: "-lamath" +! CHECK-LINKING-ARMPL-SAME: "-lm" + +! RUN: %flang -### --target=aarch64-linux-gnu -resource-dir=%S -frtlib-add-rpath -fveclib=ArmPL %s 2>&1 | FileCheck --check-prefix=CHECK-RPATH-ARMPL %s +! CHECK-RPATH-ARMPL: "-lamath" +! CHECK-RPATH-ARMPL-SAME: "-lm" +! We need to see "-rpath" at least twice, one for veclib, one for the Fortran runtime +! CHECK-RPATH-ARMPL-SAME: "-rpath" +! CHECK-RPATH-ARMPL-SAME: "-rpath" ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Enhance modernize-use-starts-ends-with to handle substr patterns (PR #116033)
https://github.com/hjanuschka updated https://github.com/llvm/llvm-project/pull/116033 >From 7c446c6ce13e8c8c4fda22b70d5eef03852c5572 Mon Sep 17 00:00:00 2001 From: Helmut Januschka Date: Wed, 13 Nov 2024 12:52:36 +0100 Subject: [PATCH] [clang-tidy] Enhance modernize-use-starts-ends-with with substr detection Enhances the modernize-use-starts-ends-with check to detect substr-based patterns that can be replaced with starts_with() (C++20). This improves code readability and efficiency by avoiding temporary string creation. New patterns detected: str.substr(0, n) == "foo" -> str.starts_with("foo") "foo" == str.substr(0, n) -> str.starts_with("foo") str.substr(0, n) != "foo" -> !str.starts_with("foo") str.substr(0, strlen("foo")) == "foo" -> str.starts_with("foo") str.substr(0, prefix.size()) == "foo" -> str.starts_with("foo") The enhancement: - Integrates with existing starts_with patterns - Handles substr with zero first argument - Supports length via literals, strlen(), and size()/length() - Validates string literal length matches - Handles both == and != operators Part of modernize-use-starts-ends-with check. --- .../modernize/UseStartsEndsWithCheck.cpp | 114 +--- .../modernize/UseStartsEndsWithCheck.h| 1 + clang-tools-extra/docs/ReleaseNotes.rst | 5 +- .../checks/modernize/use-starts-ends-with.rst | 34 ++-- .../clang-tidy/checkers/Inputs/Headers/string | 2 + .../modernize/use-starts-ends-with.cpp| 167 -- 6 files changed, 224 insertions(+), 99 deletions(-) diff --git a/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp index 1231f954298adc..12ff31dfa03541 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp @@ -30,6 +30,17 @@ struct NotLengthExprForStringNode { IntegerLiteralSizeNode->getValue().getZExtValue(); } + if (const auto *DeclRefNode = Node.get()) { +if (const auto *VD = dyn_cast(DeclRefNode->getDecl())) { + if (VD->hasInit() && VD->getType().isConstQualified()) { +if (const auto *Init = dyn_cast(VD->getInit())) { + return StringLiteralNode->getLength() != + Init->getValue().getZExtValue(); +} + } +} + } + if (const auto *StrlenNode = Node.get()) { if (StrlenNode->getDirectCallee()->getName() != "strlen" || StrlenNode->getNumArgs() != 1) { @@ -171,10 +182,64 @@ void UseStartsEndsWithCheck::registerMatchers(MatchFinder *Finder) { hasRHS(lengthExprForStringNode("needle") .bind("expr"), this); + + Finder->addMatcher( + cxxOperatorCallExpr( + hasAnyOperatorName("==", "!="), + anyOf( + hasOperands( + cxxMemberCallExpr( + argumentCountIs(2), hasArgument(0, ZeroLiteral), + hasArgument(1, lengthExprForStringNode("needle")), + callee( + cxxMethodDecl(hasName("substr"), +ofClass(OnClassWithStartsWithFunction)) + .bind("find_fun"))) + .bind("find_expr"), + expr().bind("needle")), + hasOperands(expr().bind("needle"), + cxxMemberCallExpr( + argumentCountIs(2), hasArgument(0, ZeroLiteral), + hasArgument(1, lengthExprForStringNode("needle")), + callee(cxxMethodDecl( + hasName("substr"), + ofClass(OnClassWithStartsWithFunction)) + .bind("find_fun"))) + .bind("find_expr" + .bind("expr"), + this); +} + +bool UseStartsEndsWithCheck::isNegativeComparison(const Expr* ComparisonExpr) { + // Handle direct != operator + if (const auto *BO = llvm::dyn_cast(ComparisonExpr)) { +return BO->getOpcode() == BO_NE; + } + + // Handle operator!= call + if (const auto *Op = llvm::dyn_cast(ComparisonExpr)) { +return Op->getOperator() == OO_ExclaimEqual; + } + + // Handle rewritten !(expr == expr) + if (const auto *UO = llvm::dyn_cast(ComparisonExpr)) { +if (UO->getOpcode() == UO_LNot) { + if (const auto *InnerBO = + llvm::dyn_cast(UO->getSubExpr()->IgnoreParens())) { +return InnerBO->getOpcode() == BO_EQ; + } + if (const auto *InnerOp = + llvm::dyn_cast(UO->getSubExpr()->IgnoreParens())) { +return InnerOp->getOperator() == OO_EqualEqual; + } +} + } + + return false; } void UseStartsEndsWithCheck::check(const Match
[clang-tools-extra] [clang-tidy] Enhance modernize-use-starts-ends-with to handle substr patterns (PR #116033)
@@ -189,7 +203,54 @@ void UseStartsEndsWithCheck::check(const MatchFinder::MatchResult &Result) { if (ComparisonExpr->getBeginLoc().isMacroID()) return; - const bool Neg = ComparisonExpr->getOpcode() == BO_NE; + bool Neg; + if (const auto *BO = llvm::dyn_cast(ComparisonExpr)) { +Neg = BO->getOpcode() == BO_NE; + } else { +assert(llvm::isa(ComparisonExpr)); +Neg = llvm::cast(ComparisonExpr)->getOperator() == + OO_ExclaimEqual; + } hjanuschka wrote: added `isNegativeComparison` ```c++ bool UseStartsEndsWithCheck::isNegativeComparison(const Expr* ComparisonExpr) { // Handle direct != operator if (const auto *BO = llvm::dyn_cast(ComparisonExpr)) { return BO->getOpcode() == BO_NE; } // Handle operator!= call if (const auto *Op = llvm::dyn_cast(ComparisonExpr)) { return Op->getOperator() == OO_ExclaimEqual; } // Handle rewritten !(expr == expr) if (const auto *UO = llvm::dyn_cast(ComparisonExpr)) { if (UO->getOpcode() == UO_LNot) { if (const auto *InnerBO = llvm::dyn_cast(UO->getSubExpr()->IgnoreParens())) { return InnerBO->getOpcode() == BO_EQ; } if (const auto *InnerOp = llvm::dyn_cast(UO->getSubExpr()->IgnoreParens())) { return InnerOp->getOperator() == OO_EqualEqual; } } } return false; } ``` and some tests: ``` // Test != operator rewriting str.substr(0, 5) != "hello"; // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with instead of substr != [modernize-use-starts-ends-with] // CHECK-FIXES: !str.starts_with("hello"); // Test rewritten form !(str.substr(0, 5) == "hello"); // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: use starts_with instead of substr == [modernize-use-starts-ends-with] ``` https://github.com/llvm/llvm-project/pull/116033 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits